Merge git://git.kernel.org/pub/scm/linux/kernel/git/jejb/scsi-rc-fixes-2.6
[linux-2.6] / fs / jbd / journal.c
1 /*
2  * linux/fs/jbd/journal.c
3  *
4  * Written by Stephen C. Tweedie <sct@redhat.com>, 1998
5  *
6  * Copyright 1998 Red Hat corp --- All Rights Reserved
7  *
8  * This file is part of the Linux kernel and is made available under
9  * the terms of the GNU General Public License, version 2, or at your
10  * option, any later version, incorporated herein by reference.
11  *
12  * Generic filesystem journal-writing code; part of the ext2fs
13  * journaling system.
14  *
15  * This file manages journals: areas of disk reserved for logging
16  * transactional updates.  This includes the kernel journaling thread
17  * which is responsible for scheduling updates to the log.
18  *
19  * We do not actually manage the physical storage of the journal in this
20  * file: that is left to a per-journal policy function, which allows us
21  * to store the journal within a filesystem-specified area for ext2
22  * journaling (ext2 can use a reserved inode for storing the log).
23  */
24
25 #include <linux/module.h>
26 #include <linux/time.h>
27 #include <linux/fs.h>
28 #include <linux/jbd.h>
29 #include <linux/errno.h>
30 #include <linux/slab.h>
31 #include <linux/init.h>
32 #include <linux/mm.h>
33 #include <linux/freezer.h>
34 #include <linux/pagemap.h>
35 #include <linux/kthread.h>
36 #include <linux/poison.h>
37 #include <linux/proc_fs.h>
38 #include <linux/debugfs.h>
39
40 #include <asm/uaccess.h>
41 #include <asm/page.h>
42
43 EXPORT_SYMBOL(journal_start);
44 EXPORT_SYMBOL(journal_restart);
45 EXPORT_SYMBOL(journal_extend);
46 EXPORT_SYMBOL(journal_stop);
47 EXPORT_SYMBOL(journal_lock_updates);
48 EXPORT_SYMBOL(journal_unlock_updates);
49 EXPORT_SYMBOL(journal_get_write_access);
50 EXPORT_SYMBOL(journal_get_create_access);
51 EXPORT_SYMBOL(journal_get_undo_access);
52 EXPORT_SYMBOL(journal_dirty_data);
53 EXPORT_SYMBOL(journal_dirty_metadata);
54 EXPORT_SYMBOL(journal_release_buffer);
55 EXPORT_SYMBOL(journal_forget);
56 #if 0
57 EXPORT_SYMBOL(journal_sync_buffer);
58 #endif
59 EXPORT_SYMBOL(journal_flush);
60 EXPORT_SYMBOL(journal_revoke);
61
62 EXPORT_SYMBOL(journal_init_dev);
63 EXPORT_SYMBOL(journal_init_inode);
64 EXPORT_SYMBOL(journal_update_format);
65 EXPORT_SYMBOL(journal_check_used_features);
66 EXPORT_SYMBOL(journal_check_available_features);
67 EXPORT_SYMBOL(journal_set_features);
68 EXPORT_SYMBOL(journal_create);
69 EXPORT_SYMBOL(journal_load);
70 EXPORT_SYMBOL(journal_destroy);
71 EXPORT_SYMBOL(journal_update_superblock);
72 EXPORT_SYMBOL(journal_abort);
73 EXPORT_SYMBOL(journal_errno);
74 EXPORT_SYMBOL(journal_ack_err);
75 EXPORT_SYMBOL(journal_clear_err);
76 EXPORT_SYMBOL(log_wait_commit);
77 EXPORT_SYMBOL(journal_start_commit);
78 EXPORT_SYMBOL(journal_force_commit_nested);
79 EXPORT_SYMBOL(journal_wipe);
80 EXPORT_SYMBOL(journal_blocks_per_page);
81 EXPORT_SYMBOL(journal_invalidatepage);
82 EXPORT_SYMBOL(journal_try_to_free_buffers);
83 EXPORT_SYMBOL(journal_force_commit);
84
85 static int journal_convert_superblock_v1(journal_t *, journal_superblock_t *);
86 static void __journal_abort_soft (journal_t *journal, int errno);
87
88 /*
89  * Helper function used to manage commit timeouts
90  */
91
92 static void commit_timeout(unsigned long __data)
93 {
94         struct task_struct * p = (struct task_struct *) __data;
95
96         wake_up_process(p);
97 }
98
99 /*
100  * kjournald: The main thread function used to manage a logging device
101  * journal.
102  *
103  * This kernel thread is responsible for two things:
104  *
105  * 1) COMMIT:  Every so often we need to commit the current state of the
106  *    filesystem to disk.  The journal thread is responsible for writing
107  *    all of the metadata buffers to disk.
108  *
109  * 2) CHECKPOINT: We cannot reuse a used section of the log file until all
110  *    of the data in that part of the log has been rewritten elsewhere on
111  *    the disk.  Flushing these old buffers to reclaim space in the log is
112  *    known as checkpointing, and this thread is responsible for that job.
113  */
114
115 static int kjournald(void *arg)
116 {
117         journal_t *journal = arg;
118         transaction_t *transaction;
119
120         /*
121          * Set up an interval timer which can be used to trigger a commit wakeup
122          * after the commit interval expires
123          */
124         setup_timer(&journal->j_commit_timer, commit_timeout,
125                         (unsigned long)current);
126
127         /* Record that the journal thread is running */
128         journal->j_task = current;
129         wake_up(&journal->j_wait_done_commit);
130
131         printk(KERN_INFO "kjournald starting.  Commit interval %ld seconds\n",
132                         journal->j_commit_interval / HZ);
133
134         /*
135          * And now, wait forever for commit wakeup events.
136          */
137         spin_lock(&journal->j_state_lock);
138
139 loop:
140         if (journal->j_flags & JFS_UNMOUNT)
141                 goto end_loop;
142
143         jbd_debug(1, "commit_sequence=%d, commit_request=%d\n",
144                 journal->j_commit_sequence, journal->j_commit_request);
145
146         if (journal->j_commit_sequence != journal->j_commit_request) {
147                 jbd_debug(1, "OK, requests differ\n");
148                 spin_unlock(&journal->j_state_lock);
149                 del_timer_sync(&journal->j_commit_timer);
150                 journal_commit_transaction(journal);
151                 spin_lock(&journal->j_state_lock);
152                 goto loop;
153         }
154
155         wake_up(&journal->j_wait_done_commit);
156         if (freezing(current)) {
157                 /*
158                  * The simpler the better. Flushing journal isn't a
159                  * good idea, because that depends on threads that may
160                  * be already stopped.
161                  */
162                 jbd_debug(1, "Now suspending kjournald\n");
163                 spin_unlock(&journal->j_state_lock);
164                 refrigerator();
165                 spin_lock(&journal->j_state_lock);
166         } else {
167                 /*
168                  * We assume on resume that commits are already there,
169                  * so we don't sleep
170                  */
171                 DEFINE_WAIT(wait);
172                 int should_sleep = 1;
173
174                 prepare_to_wait(&journal->j_wait_commit, &wait,
175                                 TASK_INTERRUPTIBLE);
176                 if (journal->j_commit_sequence != journal->j_commit_request)
177                         should_sleep = 0;
178                 transaction = journal->j_running_transaction;
179                 if (transaction && time_after_eq(jiffies,
180                                                 transaction->t_expires))
181                         should_sleep = 0;
182                 if (journal->j_flags & JFS_UNMOUNT)
183                         should_sleep = 0;
184                 if (should_sleep) {
185                         spin_unlock(&journal->j_state_lock);
186                         schedule();
187                         spin_lock(&journal->j_state_lock);
188                 }
189                 finish_wait(&journal->j_wait_commit, &wait);
190         }
191
192         jbd_debug(1, "kjournald wakes\n");
193
194         /*
195          * Were we woken up by a commit wakeup event?
196          */
197         transaction = journal->j_running_transaction;
198         if (transaction && time_after_eq(jiffies, transaction->t_expires)) {
199                 journal->j_commit_request = transaction->t_tid;
200                 jbd_debug(1, "woke because of timeout\n");
201         }
202         goto loop;
203
204 end_loop:
205         spin_unlock(&journal->j_state_lock);
206         del_timer_sync(&journal->j_commit_timer);
207         journal->j_task = NULL;
208         wake_up(&journal->j_wait_done_commit);
209         jbd_debug(1, "Journal thread exiting.\n");
210         return 0;
211 }
212
213 static int journal_start_thread(journal_t *journal)
214 {
215         struct task_struct *t;
216
217         t = kthread_run(kjournald, journal, "kjournald");
218         if (IS_ERR(t))
219                 return PTR_ERR(t);
220
221         wait_event(journal->j_wait_done_commit, journal->j_task != NULL);
222         return 0;
223 }
224
225 static void journal_kill_thread(journal_t *journal)
226 {
227         spin_lock(&journal->j_state_lock);
228         journal->j_flags |= JFS_UNMOUNT;
229
230         while (journal->j_task) {
231                 wake_up(&journal->j_wait_commit);
232                 spin_unlock(&journal->j_state_lock);
233                 wait_event(journal->j_wait_done_commit,
234                                 journal->j_task == NULL);
235                 spin_lock(&journal->j_state_lock);
236         }
237         spin_unlock(&journal->j_state_lock);
238 }
239
240 /*
241  * journal_write_metadata_buffer: write a metadata buffer to the journal.
242  *
243  * Writes a metadata buffer to a given disk block.  The actual IO is not
244  * performed but a new buffer_head is constructed which labels the data
245  * to be written with the correct destination disk block.
246  *
247  * Any magic-number escaping which needs to be done will cause a
248  * copy-out here.  If the buffer happens to start with the
249  * JFS_MAGIC_NUMBER, then we can't write it to the log directly: the
250  * magic number is only written to the log for descripter blocks.  In
251  * this case, we copy the data and replace the first word with 0, and we
252  * return a result code which indicates that this buffer needs to be
253  * marked as an escaped buffer in the corresponding log descriptor
254  * block.  The missing word can then be restored when the block is read
255  * during recovery.
256  *
257  * If the source buffer has already been modified by a new transaction
258  * since we took the last commit snapshot, we use the frozen copy of
259  * that data for IO.  If we end up using the existing buffer_head's data
260  * for the write, then we *have* to lock the buffer to prevent anyone
261  * else from using and possibly modifying it while the IO is in
262  * progress.
263  *
264  * The function returns a pointer to the buffer_heads to be used for IO.
265  *
266  * We assume that the journal has already been locked in this function.
267  *
268  * Return value:
269  *  <0: Error
270  * >=0: Finished OK
271  *
272  * On success:
273  * Bit 0 set == escape performed on the data
274  * Bit 1 set == buffer copy-out performed (kfree the data after IO)
275  */
276
277 int journal_write_metadata_buffer(transaction_t *transaction,
278                                   struct journal_head  *jh_in,
279                                   struct journal_head **jh_out,
280                                   unsigned long blocknr)
281 {
282         int need_copy_out = 0;
283         int done_copy_out = 0;
284         int do_escape = 0;
285         char *mapped_data;
286         struct buffer_head *new_bh;
287         struct journal_head *new_jh;
288         struct page *new_page;
289         unsigned int new_offset;
290         struct buffer_head *bh_in = jh2bh(jh_in);
291
292         /*
293          * The buffer really shouldn't be locked: only the current committing
294          * transaction is allowed to write it, so nobody else is allowed
295          * to do any IO.
296          *
297          * akpm: except if we're journalling data, and write() output is
298          * also part of a shared mapping, and another thread has
299          * decided to launch a writepage() against this buffer.
300          */
301         J_ASSERT_BH(bh_in, buffer_jbddirty(bh_in));
302
303         new_bh = alloc_buffer_head(GFP_NOFS|__GFP_NOFAIL);
304
305         /*
306          * If a new transaction has already done a buffer copy-out, then
307          * we use that version of the data for the commit.
308          */
309         jbd_lock_bh_state(bh_in);
310 repeat:
311         if (jh_in->b_frozen_data) {
312                 done_copy_out = 1;
313                 new_page = virt_to_page(jh_in->b_frozen_data);
314                 new_offset = offset_in_page(jh_in->b_frozen_data);
315         } else {
316                 new_page = jh2bh(jh_in)->b_page;
317                 new_offset = offset_in_page(jh2bh(jh_in)->b_data);
318         }
319
320         mapped_data = kmap_atomic(new_page, KM_USER0);
321         /*
322          * Check for escaping
323          */
324         if (*((__be32 *)(mapped_data + new_offset)) ==
325                                 cpu_to_be32(JFS_MAGIC_NUMBER)) {
326                 need_copy_out = 1;
327                 do_escape = 1;
328         }
329         kunmap_atomic(mapped_data, KM_USER0);
330
331         /*
332          * Do we need to do a data copy?
333          */
334         if (need_copy_out && !done_copy_out) {
335                 char *tmp;
336
337                 jbd_unlock_bh_state(bh_in);
338                 tmp = jbd_alloc(bh_in->b_size, GFP_NOFS);
339                 jbd_lock_bh_state(bh_in);
340                 if (jh_in->b_frozen_data) {
341                         jbd_free(tmp, bh_in->b_size);
342                         goto repeat;
343                 }
344
345                 jh_in->b_frozen_data = tmp;
346                 mapped_data = kmap_atomic(new_page, KM_USER0);
347                 memcpy(tmp, mapped_data + new_offset, jh2bh(jh_in)->b_size);
348                 kunmap_atomic(mapped_data, KM_USER0);
349
350                 new_page = virt_to_page(tmp);
351                 new_offset = offset_in_page(tmp);
352                 done_copy_out = 1;
353         }
354
355         /*
356          * Did we need to do an escaping?  Now we've done all the
357          * copying, we can finally do so.
358          */
359         if (do_escape) {
360                 mapped_data = kmap_atomic(new_page, KM_USER0);
361                 *((unsigned int *)(mapped_data + new_offset)) = 0;
362                 kunmap_atomic(mapped_data, KM_USER0);
363         }
364
365         /* keep subsequent assertions sane */
366         new_bh->b_state = 0;
367         init_buffer(new_bh, NULL, NULL);
368         atomic_set(&new_bh->b_count, 1);
369         jbd_unlock_bh_state(bh_in);
370
371         new_jh = journal_add_journal_head(new_bh);      /* This sleeps */
372
373         set_bh_page(new_bh, new_page, new_offset);
374         new_jh->b_transaction = NULL;
375         new_bh->b_size = jh2bh(jh_in)->b_size;
376         new_bh->b_bdev = transaction->t_journal->j_dev;
377         new_bh->b_blocknr = blocknr;
378         set_buffer_mapped(new_bh);
379         set_buffer_dirty(new_bh);
380
381         *jh_out = new_jh;
382
383         /*
384          * The to-be-written buffer needs to get moved to the io queue,
385          * and the original buffer whose contents we are shadowing or
386          * copying is moved to the transaction's shadow queue.
387          */
388         JBUFFER_TRACE(jh_in, "file as BJ_Shadow");
389         journal_file_buffer(jh_in, transaction, BJ_Shadow);
390         JBUFFER_TRACE(new_jh, "file as BJ_IO");
391         journal_file_buffer(new_jh, transaction, BJ_IO);
392
393         return do_escape | (done_copy_out << 1);
394 }
395
396 /*
397  * Allocation code for the journal file.  Manage the space left in the
398  * journal, so that we can begin checkpointing when appropriate.
399  */
400
401 /*
402  * __log_space_left: Return the number of free blocks left in the journal.
403  *
404  * Called with the journal already locked.
405  *
406  * Called under j_state_lock
407  */
408
409 int __log_space_left(journal_t *journal)
410 {
411         int left = journal->j_free;
412
413         assert_spin_locked(&journal->j_state_lock);
414
415         /*
416          * Be pessimistic here about the number of those free blocks which
417          * might be required for log descriptor control blocks.
418          */
419
420 #define MIN_LOG_RESERVED_BLOCKS 32 /* Allow for rounding errors */
421
422         left -= MIN_LOG_RESERVED_BLOCKS;
423
424         if (left <= 0)
425                 return 0;
426         left -= (left >> 3);
427         return left;
428 }
429
430 /*
431  * Called under j_state_lock.  Returns true if a transaction was started.
432  */
433 int __log_start_commit(journal_t *journal, tid_t target)
434 {
435         /*
436          * Are we already doing a recent enough commit?
437          */
438         if (!tid_geq(journal->j_commit_request, target)) {
439                 /*
440                  * We want a new commit: OK, mark the request and wakup the
441                  * commit thread.  We do _not_ do the commit ourselves.
442                  */
443
444                 journal->j_commit_request = target;
445                 jbd_debug(1, "JBD: requesting commit %d/%d\n",
446                           journal->j_commit_request,
447                           journal->j_commit_sequence);
448                 wake_up(&journal->j_wait_commit);
449                 return 1;
450         }
451         return 0;
452 }
453
454 int log_start_commit(journal_t *journal, tid_t tid)
455 {
456         int ret;
457
458         spin_lock(&journal->j_state_lock);
459         ret = __log_start_commit(journal, tid);
460         spin_unlock(&journal->j_state_lock);
461         return ret;
462 }
463
464 /*
465  * Force and wait upon a commit if the calling process is not within
466  * transaction.  This is used for forcing out undo-protected data which contains
467  * bitmaps, when the fs is running out of space.
468  *
469  * We can only force the running transaction if we don't have an active handle;
470  * otherwise, we will deadlock.
471  *
472  * Returns true if a transaction was started.
473  */
474 int journal_force_commit_nested(journal_t *journal)
475 {
476         transaction_t *transaction = NULL;
477         tid_t tid;
478
479         spin_lock(&journal->j_state_lock);
480         if (journal->j_running_transaction && !current->journal_info) {
481                 transaction = journal->j_running_transaction;
482                 __log_start_commit(journal, transaction->t_tid);
483         } else if (journal->j_committing_transaction)
484                 transaction = journal->j_committing_transaction;
485
486         if (!transaction) {
487                 spin_unlock(&journal->j_state_lock);
488                 return 0;       /* Nothing to retry */
489         }
490
491         tid = transaction->t_tid;
492         spin_unlock(&journal->j_state_lock);
493         log_wait_commit(journal, tid);
494         return 1;
495 }
496
497 /*
498  * Start a commit of the current running transaction (if any).  Returns true
499  * if a transaction was started, and fills its tid in at *ptid
500  */
501 int journal_start_commit(journal_t *journal, tid_t *ptid)
502 {
503         int ret = 0;
504
505         spin_lock(&journal->j_state_lock);
506         if (journal->j_running_transaction) {
507                 tid_t tid = journal->j_running_transaction->t_tid;
508
509                 ret = __log_start_commit(journal, tid);
510                 if (ret && ptid)
511                         *ptid = tid;
512         } else if (journal->j_committing_transaction && ptid) {
513                 /*
514                  * If ext3_write_super() recently started a commit, then we
515                  * have to wait for completion of that transaction
516                  */
517                 *ptid = journal->j_committing_transaction->t_tid;
518                 ret = 1;
519         }
520         spin_unlock(&journal->j_state_lock);
521         return ret;
522 }
523
524 /*
525  * Wait for a specified commit to complete.
526  * The caller may not hold the journal lock.
527  */
528 int log_wait_commit(journal_t *journal, tid_t tid)
529 {
530         int err = 0;
531
532 #ifdef CONFIG_JBD_DEBUG
533         spin_lock(&journal->j_state_lock);
534         if (!tid_geq(journal->j_commit_request, tid)) {
535                 printk(KERN_EMERG
536                        "%s: error: j_commit_request=%d, tid=%d\n",
537                        __FUNCTION__, journal->j_commit_request, tid);
538         }
539         spin_unlock(&journal->j_state_lock);
540 #endif
541         spin_lock(&journal->j_state_lock);
542         while (tid_gt(tid, journal->j_commit_sequence)) {
543                 jbd_debug(1, "JBD: want %d, j_commit_sequence=%d\n",
544                                   tid, journal->j_commit_sequence);
545                 wake_up(&journal->j_wait_commit);
546                 spin_unlock(&journal->j_state_lock);
547                 wait_event(journal->j_wait_done_commit,
548                                 !tid_gt(tid, journal->j_commit_sequence));
549                 spin_lock(&journal->j_state_lock);
550         }
551         spin_unlock(&journal->j_state_lock);
552
553         if (unlikely(is_journal_aborted(journal))) {
554                 printk(KERN_EMERG "journal commit I/O error\n");
555                 err = -EIO;
556         }
557         return err;
558 }
559
560 /*
561  * Log buffer allocation routines:
562  */
563
564 int journal_next_log_block(journal_t *journal, unsigned long *retp)
565 {
566         unsigned long blocknr;
567
568         spin_lock(&journal->j_state_lock);
569         J_ASSERT(journal->j_free > 1);
570
571         blocknr = journal->j_head;
572         journal->j_head++;
573         journal->j_free--;
574         if (journal->j_head == journal->j_last)
575                 journal->j_head = journal->j_first;
576         spin_unlock(&journal->j_state_lock);
577         return journal_bmap(journal, blocknr, retp);
578 }
579
580 /*
581  * Conversion of logical to physical block numbers for the journal
582  *
583  * On external journals the journal blocks are identity-mapped, so
584  * this is a no-op.  If needed, we can use j_blk_offset - everything is
585  * ready.
586  */
587 int journal_bmap(journal_t *journal, unsigned long blocknr,
588                  unsigned long *retp)
589 {
590         int err = 0;
591         unsigned long ret;
592
593         if (journal->j_inode) {
594                 ret = bmap(journal->j_inode, blocknr);
595                 if (ret)
596                         *retp = ret;
597                 else {
598                         char b[BDEVNAME_SIZE];
599
600                         printk(KERN_ALERT "%s: journal block not found "
601                                         "at offset %lu on %s\n",
602                                 __FUNCTION__,
603                                 blocknr,
604                                 bdevname(journal->j_dev, b));
605                         err = -EIO;
606                         __journal_abort_soft(journal, err);
607                 }
608         } else {
609                 *retp = blocknr; /* +journal->j_blk_offset */
610         }
611         return err;
612 }
613
614 /*
615  * We play buffer_head aliasing tricks to write data/metadata blocks to
616  * the journal without copying their contents, but for journal
617  * descriptor blocks we do need to generate bona fide buffers.
618  *
619  * After the caller of journal_get_descriptor_buffer() has finished modifying
620  * the buffer's contents they really should run flush_dcache_page(bh->b_page).
621  * But we don't bother doing that, so there will be coherency problems with
622  * mmaps of blockdevs which hold live JBD-controlled filesystems.
623  */
624 struct journal_head *journal_get_descriptor_buffer(journal_t *journal)
625 {
626         struct buffer_head *bh;
627         unsigned long blocknr;
628         int err;
629
630         err = journal_next_log_block(journal, &blocknr);
631
632         if (err)
633                 return NULL;
634
635         bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize);
636         lock_buffer(bh);
637         memset(bh->b_data, 0, journal->j_blocksize);
638         set_buffer_uptodate(bh);
639         unlock_buffer(bh);
640         BUFFER_TRACE(bh, "return this buffer");
641         return journal_add_journal_head(bh);
642 }
643
644 /*
645  * Management for journal control blocks: functions to create and
646  * destroy journal_t structures, and to initialise and read existing
647  * journal blocks from disk.  */
648
649 /* First: create and setup a journal_t object in memory.  We initialise
650  * very few fields yet: that has to wait until we have created the
651  * journal structures from from scratch, or loaded them from disk. */
652
653 static journal_t * journal_init_common (void)
654 {
655         journal_t *journal;
656         int err;
657
658         journal = kzalloc(sizeof(*journal), GFP_KERNEL);
659         if (!journal)
660                 goto fail;
661
662         init_waitqueue_head(&journal->j_wait_transaction_locked);
663         init_waitqueue_head(&journal->j_wait_logspace);
664         init_waitqueue_head(&journal->j_wait_done_commit);
665         init_waitqueue_head(&journal->j_wait_checkpoint);
666         init_waitqueue_head(&journal->j_wait_commit);
667         init_waitqueue_head(&journal->j_wait_updates);
668         mutex_init(&journal->j_barrier);
669         mutex_init(&journal->j_checkpoint_mutex);
670         spin_lock_init(&journal->j_revoke_lock);
671         spin_lock_init(&journal->j_list_lock);
672         spin_lock_init(&journal->j_state_lock);
673
674         journal->j_commit_interval = (HZ * JBD_DEFAULT_MAX_COMMIT_AGE);
675
676         /* The journal is marked for error until we succeed with recovery! */
677         journal->j_flags = JFS_ABORT;
678
679         /* Set up a default-sized revoke table for the new mount. */
680         err = journal_init_revoke(journal, JOURNAL_REVOKE_DEFAULT_HASH);
681         if (err) {
682                 kfree(journal);
683                 goto fail;
684         }
685         return journal;
686 fail:
687         return NULL;
688 }
689
690 /* journal_init_dev and journal_init_inode:
691  *
692  * Create a journal structure assigned some fixed set of disk blocks to
693  * the journal.  We don't actually touch those disk blocks yet, but we
694  * need to set up all of the mapping information to tell the journaling
695  * system where the journal blocks are.
696  *
697  */
698
699 /**
700  *  journal_t * journal_init_dev() - creates and initialises a journal structure
701  *  @bdev: Block device on which to create the journal
702  *  @fs_dev: Device which hold journalled filesystem for this journal.
703  *  @start: Block nr Start of journal.
704  *  @len:  Length of the journal in blocks.
705  *  @blocksize: blocksize of journalling device
706  *
707  *  Returns: a newly created journal_t *
708  *
709  *  journal_init_dev creates a journal which maps a fixed contiguous
710  *  range of blocks on an arbitrary block device.
711  *
712  */
713 journal_t * journal_init_dev(struct block_device *bdev,
714                         struct block_device *fs_dev,
715                         int start, int len, int blocksize)
716 {
717         journal_t *journal = journal_init_common();
718         struct buffer_head *bh;
719         int n;
720
721         if (!journal)
722                 return NULL;
723
724         /* journal descriptor can store up to n blocks -bzzz */
725         journal->j_blocksize = blocksize;
726         n = journal->j_blocksize / sizeof(journal_block_tag_t);
727         journal->j_wbufsize = n;
728         journal->j_wbuf = kmalloc(n * sizeof(struct buffer_head*), GFP_KERNEL);
729         if (!journal->j_wbuf) {
730                 printk(KERN_ERR "%s: Cant allocate bhs for commit thread\n",
731                         __FUNCTION__);
732                 kfree(journal);
733                 journal = NULL;
734                 goto out;
735         }
736         journal->j_dev = bdev;
737         journal->j_fs_dev = fs_dev;
738         journal->j_blk_offset = start;
739         journal->j_maxlen = len;
740
741         bh = __getblk(journal->j_dev, start, journal->j_blocksize);
742         J_ASSERT(bh != NULL);
743         journal->j_sb_buffer = bh;
744         journal->j_superblock = (journal_superblock_t *)bh->b_data;
745 out:
746         return journal;
747 }
748
749 /**
750  *  journal_t * journal_init_inode () - creates a journal which maps to a inode.
751  *  @inode: An inode to create the journal in
752  *
753  * journal_init_inode creates a journal which maps an on-disk inode as
754  * the journal.  The inode must exist already, must support bmap() and
755  * must have all data blocks preallocated.
756  */
757 journal_t * journal_init_inode (struct inode *inode)
758 {
759         struct buffer_head *bh;
760         journal_t *journal = journal_init_common();
761         int err;
762         int n;
763         unsigned long blocknr;
764
765         if (!journal)
766                 return NULL;
767
768         journal->j_dev = journal->j_fs_dev = inode->i_sb->s_bdev;
769         journal->j_inode = inode;
770         jbd_debug(1,
771                   "journal %p: inode %s/%ld, size %Ld, bits %d, blksize %ld\n",
772                   journal, inode->i_sb->s_id, inode->i_ino,
773                   (long long) inode->i_size,
774                   inode->i_sb->s_blocksize_bits, inode->i_sb->s_blocksize);
775
776         journal->j_maxlen = inode->i_size >> inode->i_sb->s_blocksize_bits;
777         journal->j_blocksize = inode->i_sb->s_blocksize;
778
779         /* journal descriptor can store up to n blocks -bzzz */
780         n = journal->j_blocksize / sizeof(journal_block_tag_t);
781         journal->j_wbufsize = n;
782         journal->j_wbuf = kmalloc(n * sizeof(struct buffer_head*), GFP_KERNEL);
783         if (!journal->j_wbuf) {
784                 printk(KERN_ERR "%s: Cant allocate bhs for commit thread\n",
785                         __FUNCTION__);
786                 kfree(journal);
787                 return NULL;
788         }
789
790         err = journal_bmap(journal, 0, &blocknr);
791         /* If that failed, give up */
792         if (err) {
793                 printk(KERN_ERR "%s: Cannnot locate journal superblock\n",
794                        __FUNCTION__);
795                 kfree(journal);
796                 return NULL;
797         }
798
799         bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize);
800         J_ASSERT(bh != NULL);
801         journal->j_sb_buffer = bh;
802         journal->j_superblock = (journal_superblock_t *)bh->b_data;
803
804         return journal;
805 }
806
807 /*
808  * If the journal init or create aborts, we need to mark the journal
809  * superblock as being NULL to prevent the journal destroy from writing
810  * back a bogus superblock.
811  */
812 static void journal_fail_superblock (journal_t *journal)
813 {
814         struct buffer_head *bh = journal->j_sb_buffer;
815         brelse(bh);
816         journal->j_sb_buffer = NULL;
817 }
818
819 /*
820  * Given a journal_t structure, initialise the various fields for
821  * startup of a new journaling session.  We use this both when creating
822  * a journal, and after recovering an old journal to reset it for
823  * subsequent use.
824  */
825
826 static int journal_reset(journal_t *journal)
827 {
828         journal_superblock_t *sb = journal->j_superblock;
829         unsigned long first, last;
830
831         first = be32_to_cpu(sb->s_first);
832         last = be32_to_cpu(sb->s_maxlen);
833
834         journal->j_first = first;
835         journal->j_last = last;
836
837         journal->j_head = first;
838         journal->j_tail = first;
839         journal->j_free = last - first;
840
841         journal->j_tail_sequence = journal->j_transaction_sequence;
842         journal->j_commit_sequence = journal->j_transaction_sequence - 1;
843         journal->j_commit_request = journal->j_commit_sequence;
844
845         journal->j_max_transaction_buffers = journal->j_maxlen / 4;
846
847         /* Add the dynamic fields and write it to disk. */
848         journal_update_superblock(journal, 1);
849         return journal_start_thread(journal);
850 }
851
852 /**
853  * int journal_create() - Initialise the new journal file
854  * @journal: Journal to create. This structure must have been initialised
855  *
856  * Given a journal_t structure which tells us which disk blocks we can
857  * use, create a new journal superblock and initialise all of the
858  * journal fields from scratch.
859  **/
860 int journal_create(journal_t *journal)
861 {
862         unsigned long blocknr;
863         struct buffer_head *bh;
864         journal_superblock_t *sb;
865         int i, err;
866
867         if (journal->j_maxlen < JFS_MIN_JOURNAL_BLOCKS) {
868                 printk (KERN_ERR "Journal length (%d blocks) too short.\n",
869                         journal->j_maxlen);
870                 journal_fail_superblock(journal);
871                 return -EINVAL;
872         }
873
874         if (journal->j_inode == NULL) {
875                 /*
876                  * We don't know what block to start at!
877                  */
878                 printk(KERN_EMERG
879                        "%s: creation of journal on external device!\n",
880                        __FUNCTION__);
881                 BUG();
882         }
883
884         /* Zero out the entire journal on disk.  We cannot afford to
885            have any blocks on disk beginning with JFS_MAGIC_NUMBER. */
886         jbd_debug(1, "JBD: Zeroing out journal blocks...\n");
887         for (i = 0; i < journal->j_maxlen; i++) {
888                 err = journal_bmap(journal, i, &blocknr);
889                 if (err)
890                         return err;
891                 bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize);
892                 lock_buffer(bh);
893                 memset (bh->b_data, 0, journal->j_blocksize);
894                 BUFFER_TRACE(bh, "marking dirty");
895                 mark_buffer_dirty(bh);
896                 BUFFER_TRACE(bh, "marking uptodate");
897                 set_buffer_uptodate(bh);
898                 unlock_buffer(bh);
899                 __brelse(bh);
900         }
901
902         sync_blockdev(journal->j_dev);
903         jbd_debug(1, "JBD: journal cleared.\n");
904
905         /* OK, fill in the initial static fields in the new superblock */
906         sb = journal->j_superblock;
907
908         sb->s_header.h_magic     = cpu_to_be32(JFS_MAGIC_NUMBER);
909         sb->s_header.h_blocktype = cpu_to_be32(JFS_SUPERBLOCK_V2);
910
911         sb->s_blocksize = cpu_to_be32(journal->j_blocksize);
912         sb->s_maxlen    = cpu_to_be32(journal->j_maxlen);
913         sb->s_first     = cpu_to_be32(1);
914
915         journal->j_transaction_sequence = 1;
916
917         journal->j_flags &= ~JFS_ABORT;
918         journal->j_format_version = 2;
919
920         return journal_reset(journal);
921 }
922
923 /**
924  * void journal_update_superblock() - Update journal sb on disk.
925  * @journal: The journal to update.
926  * @wait: Set to '0' if you don't want to wait for IO completion.
927  *
928  * Update a journal's dynamic superblock fields and write it to disk,
929  * optionally waiting for the IO to complete.
930  */
931 void journal_update_superblock(journal_t *journal, int wait)
932 {
933         journal_superblock_t *sb = journal->j_superblock;
934         struct buffer_head *bh = journal->j_sb_buffer;
935
936         /*
937          * As a special case, if the on-disk copy is already marked as needing
938          * no recovery (s_start == 0) and there are no outstanding transactions
939          * in the filesystem, then we can safely defer the superblock update
940          * until the next commit by setting JFS_FLUSHED.  This avoids
941          * attempting a write to a potential-readonly device.
942          */
943         if (sb->s_start == 0 && journal->j_tail_sequence ==
944                                 journal->j_transaction_sequence) {
945                 jbd_debug(1,"JBD: Skipping superblock update on recovered sb "
946                         "(start %ld, seq %d, errno %d)\n",
947                         journal->j_tail, journal->j_tail_sequence,
948                         journal->j_errno);
949                 goto out;
950         }
951
952         spin_lock(&journal->j_state_lock);
953         jbd_debug(1,"JBD: updating superblock (start %ld, seq %d, errno %d)\n",
954                   journal->j_tail, journal->j_tail_sequence, journal->j_errno);
955
956         sb->s_sequence = cpu_to_be32(journal->j_tail_sequence);
957         sb->s_start    = cpu_to_be32(journal->j_tail);
958         sb->s_errno    = cpu_to_be32(journal->j_errno);
959         spin_unlock(&journal->j_state_lock);
960
961         BUFFER_TRACE(bh, "marking dirty");
962         mark_buffer_dirty(bh);
963         if (wait)
964                 sync_dirty_buffer(bh);
965         else
966                 ll_rw_block(SWRITE, 1, &bh);
967
968 out:
969         /* If we have just flushed the log (by marking s_start==0), then
970          * any future commit will have to be careful to update the
971          * superblock again to re-record the true start of the log. */
972
973         spin_lock(&journal->j_state_lock);
974         if (sb->s_start)
975                 journal->j_flags &= ~JFS_FLUSHED;
976         else
977                 journal->j_flags |= JFS_FLUSHED;
978         spin_unlock(&journal->j_state_lock);
979 }
980
981 /*
982  * Read the superblock for a given journal, performing initial
983  * validation of the format.
984  */
985
986 static int journal_get_superblock(journal_t *journal)
987 {
988         struct buffer_head *bh;
989         journal_superblock_t *sb;
990         int err = -EIO;
991
992         bh = journal->j_sb_buffer;
993
994         J_ASSERT(bh != NULL);
995         if (!buffer_uptodate(bh)) {
996                 ll_rw_block(READ, 1, &bh);
997                 wait_on_buffer(bh);
998                 if (!buffer_uptodate(bh)) {
999                         printk (KERN_ERR
1000                                 "JBD: IO error reading journal superblock\n");
1001                         goto out;
1002                 }
1003         }
1004
1005         sb = journal->j_superblock;
1006
1007         err = -EINVAL;
1008
1009         if (sb->s_header.h_magic != cpu_to_be32(JFS_MAGIC_NUMBER) ||
1010             sb->s_blocksize != cpu_to_be32(journal->j_blocksize)) {
1011                 printk(KERN_WARNING "JBD: no valid journal superblock found\n");
1012                 goto out;
1013         }
1014
1015         switch(be32_to_cpu(sb->s_header.h_blocktype)) {
1016         case JFS_SUPERBLOCK_V1:
1017                 journal->j_format_version = 1;
1018                 break;
1019         case JFS_SUPERBLOCK_V2:
1020                 journal->j_format_version = 2;
1021                 break;
1022         default:
1023                 printk(KERN_WARNING "JBD: unrecognised superblock format ID\n");
1024                 goto out;
1025         }
1026
1027         if (be32_to_cpu(sb->s_maxlen) < journal->j_maxlen)
1028                 journal->j_maxlen = be32_to_cpu(sb->s_maxlen);
1029         else if (be32_to_cpu(sb->s_maxlen) > journal->j_maxlen) {
1030                 printk (KERN_WARNING "JBD: journal file too short\n");
1031                 goto out;
1032         }
1033
1034         return 0;
1035
1036 out:
1037         journal_fail_superblock(journal);
1038         return err;
1039 }
1040
1041 /*
1042  * Load the on-disk journal superblock and read the key fields into the
1043  * journal_t.
1044  */
1045
1046 static int load_superblock(journal_t *journal)
1047 {
1048         int err;
1049         journal_superblock_t *sb;
1050
1051         err = journal_get_superblock(journal);
1052         if (err)
1053                 return err;
1054
1055         sb = journal->j_superblock;
1056
1057         journal->j_tail_sequence = be32_to_cpu(sb->s_sequence);
1058         journal->j_tail = be32_to_cpu(sb->s_start);
1059         journal->j_first = be32_to_cpu(sb->s_first);
1060         journal->j_last = be32_to_cpu(sb->s_maxlen);
1061         journal->j_errno = be32_to_cpu(sb->s_errno);
1062
1063         return 0;
1064 }
1065
1066
1067 /**
1068  * int journal_load() - Read journal from disk.
1069  * @journal: Journal to act on.
1070  *
1071  * Given a journal_t structure which tells us which disk blocks contain
1072  * a journal, read the journal from disk to initialise the in-memory
1073  * structures.
1074  */
1075 int journal_load(journal_t *journal)
1076 {
1077         int err;
1078         journal_superblock_t *sb;
1079
1080         err = load_superblock(journal);
1081         if (err)
1082                 return err;
1083
1084         sb = journal->j_superblock;
1085         /* If this is a V2 superblock, then we have to check the
1086          * features flags on it. */
1087
1088         if (journal->j_format_version >= 2) {
1089                 if ((sb->s_feature_ro_compat &
1090                      ~cpu_to_be32(JFS_KNOWN_ROCOMPAT_FEATURES)) ||
1091                     (sb->s_feature_incompat &
1092                      ~cpu_to_be32(JFS_KNOWN_INCOMPAT_FEATURES))) {
1093                         printk (KERN_WARNING
1094                                 "JBD: Unrecognised features on journal\n");
1095                         return -EINVAL;
1096                 }
1097         }
1098
1099         /* Let the recovery code check whether it needs to recover any
1100          * data from the journal. */
1101         if (journal_recover(journal))
1102                 goto recovery_error;
1103
1104         /* OK, we've finished with the dynamic journal bits:
1105          * reinitialise the dynamic contents of the superblock in memory
1106          * and reset them on disk. */
1107         if (journal_reset(journal))
1108                 goto recovery_error;
1109
1110         journal->j_flags &= ~JFS_ABORT;
1111         journal->j_flags |= JFS_LOADED;
1112         return 0;
1113
1114 recovery_error:
1115         printk (KERN_WARNING "JBD: recovery failed\n");
1116         return -EIO;
1117 }
1118
1119 /**
1120  * void journal_destroy() - Release a journal_t structure.
1121  * @journal: Journal to act on.
1122  *
1123  * Release a journal_t structure once it is no longer in use by the
1124  * journaled object.
1125  */
1126 void journal_destroy(journal_t *journal)
1127 {
1128         /* Wait for the commit thread to wake up and die. */
1129         journal_kill_thread(journal);
1130
1131         /* Force a final log commit */
1132         if (journal->j_running_transaction)
1133                 journal_commit_transaction(journal);
1134
1135         /* Force any old transactions to disk */
1136
1137         /* Totally anal locking here... */
1138         spin_lock(&journal->j_list_lock);
1139         while (journal->j_checkpoint_transactions != NULL) {
1140                 spin_unlock(&journal->j_list_lock);
1141                 log_do_checkpoint(journal);
1142                 spin_lock(&journal->j_list_lock);
1143         }
1144
1145         J_ASSERT(journal->j_running_transaction == NULL);
1146         J_ASSERT(journal->j_committing_transaction == NULL);
1147         J_ASSERT(journal->j_checkpoint_transactions == NULL);
1148         spin_unlock(&journal->j_list_lock);
1149
1150         /* We can now mark the journal as empty. */
1151         journal->j_tail = 0;
1152         journal->j_tail_sequence = ++journal->j_transaction_sequence;
1153         if (journal->j_sb_buffer) {
1154                 journal_update_superblock(journal, 1);
1155                 brelse(journal->j_sb_buffer);
1156         }
1157
1158         if (journal->j_inode)
1159                 iput(journal->j_inode);
1160         if (journal->j_revoke)
1161                 journal_destroy_revoke(journal);
1162         kfree(journal->j_wbuf);
1163         kfree(journal);
1164 }
1165
1166
1167 /**
1168  *int journal_check_used_features () - Check if features specified are used.
1169  * @journal: Journal to check.
1170  * @compat: bitmask of compatible features
1171  * @ro: bitmask of features that force read-only mount
1172  * @incompat: bitmask of incompatible features
1173  *
1174  * Check whether the journal uses all of a given set of
1175  * features.  Return true (non-zero) if it does.
1176  **/
1177
1178 int journal_check_used_features (journal_t *journal, unsigned long compat,
1179                                  unsigned long ro, unsigned long incompat)
1180 {
1181         journal_superblock_t *sb;
1182
1183         if (!compat && !ro && !incompat)
1184                 return 1;
1185         if (journal->j_format_version == 1)
1186                 return 0;
1187
1188         sb = journal->j_superblock;
1189
1190         if (((be32_to_cpu(sb->s_feature_compat) & compat) == compat) &&
1191             ((be32_to_cpu(sb->s_feature_ro_compat) & ro) == ro) &&
1192             ((be32_to_cpu(sb->s_feature_incompat) & incompat) == incompat))
1193                 return 1;
1194
1195         return 0;
1196 }
1197
1198 /**
1199  * int journal_check_available_features() - Check feature set in journalling layer
1200  * @journal: Journal to check.
1201  * @compat: bitmask of compatible features
1202  * @ro: bitmask of features that force read-only mount
1203  * @incompat: bitmask of incompatible features
1204  *
1205  * Check whether the journaling code supports the use of
1206  * all of a given set of features on this journal.  Return true
1207  * (non-zero) if it can. */
1208
1209 int journal_check_available_features (journal_t *journal, unsigned long compat,
1210                                       unsigned long ro, unsigned long incompat)
1211 {
1212         journal_superblock_t *sb;
1213
1214         if (!compat && !ro && !incompat)
1215                 return 1;
1216
1217         sb = journal->j_superblock;
1218
1219         /* We can support any known requested features iff the
1220          * superblock is in version 2.  Otherwise we fail to support any
1221          * extended sb features. */
1222
1223         if (journal->j_format_version != 2)
1224                 return 0;
1225
1226         if ((compat   & JFS_KNOWN_COMPAT_FEATURES) == compat &&
1227             (ro       & JFS_KNOWN_ROCOMPAT_FEATURES) == ro &&
1228             (incompat & JFS_KNOWN_INCOMPAT_FEATURES) == incompat)
1229                 return 1;
1230
1231         return 0;
1232 }
1233
1234 /**
1235  * int journal_set_features () - Mark a given journal feature in the superblock
1236  * @journal: Journal to act on.
1237  * @compat: bitmask of compatible features
1238  * @ro: bitmask of features that force read-only mount
1239  * @incompat: bitmask of incompatible features
1240  *
1241  * Mark a given journal feature as present on the
1242  * superblock.  Returns true if the requested features could be set.
1243  *
1244  */
1245
1246 int journal_set_features (journal_t *journal, unsigned long compat,
1247                           unsigned long ro, unsigned long incompat)
1248 {
1249         journal_superblock_t *sb;
1250
1251         if (journal_check_used_features(journal, compat, ro, incompat))
1252                 return 1;
1253
1254         if (!journal_check_available_features(journal, compat, ro, incompat))
1255                 return 0;
1256
1257         jbd_debug(1, "Setting new features 0x%lx/0x%lx/0x%lx\n",
1258                   compat, ro, incompat);
1259
1260         sb = journal->j_superblock;
1261
1262         sb->s_feature_compat    |= cpu_to_be32(compat);
1263         sb->s_feature_ro_compat |= cpu_to_be32(ro);
1264         sb->s_feature_incompat  |= cpu_to_be32(incompat);
1265
1266         return 1;
1267 }
1268
1269
1270 /**
1271  * int journal_update_format () - Update on-disk journal structure.
1272  * @journal: Journal to act on.
1273  *
1274  * Given an initialised but unloaded journal struct, poke about in the
1275  * on-disk structure to update it to the most recent supported version.
1276  */
1277 int journal_update_format (journal_t *journal)
1278 {
1279         journal_superblock_t *sb;
1280         int err;
1281
1282         err = journal_get_superblock(journal);
1283         if (err)
1284                 return err;
1285
1286         sb = journal->j_superblock;
1287
1288         switch (be32_to_cpu(sb->s_header.h_blocktype)) {
1289         case JFS_SUPERBLOCK_V2:
1290                 return 0;
1291         case JFS_SUPERBLOCK_V1:
1292                 return journal_convert_superblock_v1(journal, sb);
1293         default:
1294                 break;
1295         }
1296         return -EINVAL;
1297 }
1298
1299 static int journal_convert_superblock_v1(journal_t *journal,
1300                                          journal_superblock_t *sb)
1301 {
1302         int offset, blocksize;
1303         struct buffer_head *bh;
1304
1305         printk(KERN_WARNING
1306                 "JBD: Converting superblock from version 1 to 2.\n");
1307
1308         /* Pre-initialise new fields to zero */
1309         offset = ((char *) &(sb->s_feature_compat)) - ((char *) sb);
1310         blocksize = be32_to_cpu(sb->s_blocksize);
1311         memset(&sb->s_feature_compat, 0, blocksize-offset);
1312
1313         sb->s_nr_users = cpu_to_be32(1);
1314         sb->s_header.h_blocktype = cpu_to_be32(JFS_SUPERBLOCK_V2);
1315         journal->j_format_version = 2;
1316
1317         bh = journal->j_sb_buffer;
1318         BUFFER_TRACE(bh, "marking dirty");
1319         mark_buffer_dirty(bh);
1320         sync_dirty_buffer(bh);
1321         return 0;
1322 }
1323
1324
1325 /**
1326  * int journal_flush () - Flush journal
1327  * @journal: Journal to act on.
1328  *
1329  * Flush all data for a given journal to disk and empty the journal.
1330  * Filesystems can use this when remounting readonly to ensure that
1331  * recovery does not need to happen on remount.
1332  */
1333
1334 int journal_flush(journal_t *journal)
1335 {
1336         int err = 0;
1337         transaction_t *transaction = NULL;
1338         unsigned long old_tail;
1339
1340         spin_lock(&journal->j_state_lock);
1341
1342         /* Force everything buffered to the log... */
1343         if (journal->j_running_transaction) {
1344                 transaction = journal->j_running_transaction;
1345                 __log_start_commit(journal, transaction->t_tid);
1346         } else if (journal->j_committing_transaction)
1347                 transaction = journal->j_committing_transaction;
1348
1349         /* Wait for the log commit to complete... */
1350         if (transaction) {
1351                 tid_t tid = transaction->t_tid;
1352
1353                 spin_unlock(&journal->j_state_lock);
1354                 log_wait_commit(journal, tid);
1355         } else {
1356                 spin_unlock(&journal->j_state_lock);
1357         }
1358
1359         /* ...and flush everything in the log out to disk. */
1360         spin_lock(&journal->j_list_lock);
1361         while (!err && journal->j_checkpoint_transactions != NULL) {
1362                 spin_unlock(&journal->j_list_lock);
1363                 err = log_do_checkpoint(journal);
1364                 spin_lock(&journal->j_list_lock);
1365         }
1366         spin_unlock(&journal->j_list_lock);
1367         cleanup_journal_tail(journal);
1368
1369         /* Finally, mark the journal as really needing no recovery.
1370          * This sets s_start==0 in the underlying superblock, which is
1371          * the magic code for a fully-recovered superblock.  Any future
1372          * commits of data to the journal will restore the current
1373          * s_start value. */
1374         spin_lock(&journal->j_state_lock);
1375         old_tail = journal->j_tail;
1376         journal->j_tail = 0;
1377         spin_unlock(&journal->j_state_lock);
1378         journal_update_superblock(journal, 1);
1379         spin_lock(&journal->j_state_lock);
1380         journal->j_tail = old_tail;
1381
1382         J_ASSERT(!journal->j_running_transaction);
1383         J_ASSERT(!journal->j_committing_transaction);
1384         J_ASSERT(!journal->j_checkpoint_transactions);
1385         J_ASSERT(journal->j_head == journal->j_tail);
1386         J_ASSERT(journal->j_tail_sequence == journal->j_transaction_sequence);
1387         spin_unlock(&journal->j_state_lock);
1388         return err;
1389 }
1390
1391 /**
1392  * int journal_wipe() - Wipe journal contents
1393  * @journal: Journal to act on.
1394  * @write: flag (see below)
1395  *
1396  * Wipe out all of the contents of a journal, safely.  This will produce
1397  * a warning if the journal contains any valid recovery information.
1398  * Must be called between journal_init_*() and journal_load().
1399  *
1400  * If 'write' is non-zero, then we wipe out the journal on disk; otherwise
1401  * we merely suppress recovery.
1402  */
1403
1404 int journal_wipe(journal_t *journal, int write)
1405 {
1406         journal_superblock_t *sb;
1407         int err = 0;
1408
1409         J_ASSERT (!(journal->j_flags & JFS_LOADED));
1410
1411         err = load_superblock(journal);
1412         if (err)
1413                 return err;
1414
1415         sb = journal->j_superblock;
1416
1417         if (!journal->j_tail)
1418                 goto no_recovery;
1419
1420         printk (KERN_WARNING "JBD: %s recovery information on journal\n",
1421                 write ? "Clearing" : "Ignoring");
1422
1423         err = journal_skip_recovery(journal);
1424         if (write)
1425                 journal_update_superblock(journal, 1);
1426
1427  no_recovery:
1428         return err;
1429 }
1430
1431 /*
1432  * journal_dev_name: format a character string to describe on what
1433  * device this journal is present.
1434  */
1435
1436 static const char *journal_dev_name(journal_t *journal, char *buffer)
1437 {
1438         struct block_device *bdev;
1439
1440         if (journal->j_inode)
1441                 bdev = journal->j_inode->i_sb->s_bdev;
1442         else
1443                 bdev = journal->j_dev;
1444
1445         return bdevname(bdev, buffer);
1446 }
1447
1448 /*
1449  * Journal abort has very specific semantics, which we describe
1450  * for journal abort.
1451  *
1452  * Two internal function, which provide abort to te jbd layer
1453  * itself are here.
1454  */
1455
1456 /*
1457  * Quick version for internal journal use (doesn't lock the journal).
1458  * Aborts hard --- we mark the abort as occurred, but do _nothing_ else,
1459  * and don't attempt to make any other journal updates.
1460  */
1461 static void __journal_abort_hard(journal_t *journal)
1462 {
1463         transaction_t *transaction;
1464         char b[BDEVNAME_SIZE];
1465
1466         if (journal->j_flags & JFS_ABORT)
1467                 return;
1468
1469         printk(KERN_ERR "Aborting journal on device %s.\n",
1470                 journal_dev_name(journal, b));
1471
1472         spin_lock(&journal->j_state_lock);
1473         journal->j_flags |= JFS_ABORT;
1474         transaction = journal->j_running_transaction;
1475         if (transaction)
1476                 __log_start_commit(journal, transaction->t_tid);
1477         spin_unlock(&journal->j_state_lock);
1478 }
1479
1480 /* Soft abort: record the abort error status in the journal superblock,
1481  * but don't do any other IO. */
1482 static void __journal_abort_soft (journal_t *journal, int errno)
1483 {
1484         if (journal->j_flags & JFS_ABORT)
1485                 return;
1486
1487         if (!journal->j_errno)
1488                 journal->j_errno = errno;
1489
1490         __journal_abort_hard(journal);
1491
1492         if (errno)
1493                 journal_update_superblock(journal, 1);
1494 }
1495
1496 /**
1497  * void journal_abort () - Shutdown the journal immediately.
1498  * @journal: the journal to shutdown.
1499  * @errno:   an error number to record in the journal indicating
1500  *           the reason for the shutdown.
1501  *
1502  * Perform a complete, immediate shutdown of the ENTIRE
1503  * journal (not of a single transaction).  This operation cannot be
1504  * undone without closing and reopening the journal.
1505  *
1506  * The journal_abort function is intended to support higher level error
1507  * recovery mechanisms such as the ext2/ext3 remount-readonly error
1508  * mode.
1509  *
1510  * Journal abort has very specific semantics.  Any existing dirty,
1511  * unjournaled buffers in the main filesystem will still be written to
1512  * disk by bdflush, but the journaling mechanism will be suspended
1513  * immediately and no further transaction commits will be honoured.
1514  *
1515  * Any dirty, journaled buffers will be written back to disk without
1516  * hitting the journal.  Atomicity cannot be guaranteed on an aborted
1517  * filesystem, but we _do_ attempt to leave as much data as possible
1518  * behind for fsck to use for cleanup.
1519  *
1520  * Any attempt to get a new transaction handle on a journal which is in
1521  * ABORT state will just result in an -EROFS error return.  A
1522  * journal_stop on an existing handle will return -EIO if we have
1523  * entered abort state during the update.
1524  *
1525  * Recursive transactions are not disturbed by journal abort until the
1526  * final journal_stop, which will receive the -EIO error.
1527  *
1528  * Finally, the journal_abort call allows the caller to supply an errno
1529  * which will be recorded (if possible) in the journal superblock.  This
1530  * allows a client to record failure conditions in the middle of a
1531  * transaction without having to complete the transaction to record the
1532  * failure to disk.  ext3_error, for example, now uses this
1533  * functionality.
1534  *
1535  * Errors which originate from within the journaling layer will NOT
1536  * supply an errno; a null errno implies that absolutely no further
1537  * writes are done to the journal (unless there are any already in
1538  * progress).
1539  *
1540  */
1541
1542 void journal_abort(journal_t *journal, int errno)
1543 {
1544         __journal_abort_soft(journal, errno);
1545 }
1546
1547 /**
1548  * int journal_errno () - returns the journal's error state.
1549  * @journal: journal to examine.
1550  *
1551  * This is the errno numbet set with journal_abort(), the last
1552  * time the journal was mounted - if the journal was stopped
1553  * without calling abort this will be 0.
1554  *
1555  * If the journal has been aborted on this mount time -EROFS will
1556  * be returned.
1557  */
1558 int journal_errno(journal_t *journal)
1559 {
1560         int err;
1561
1562         spin_lock(&journal->j_state_lock);
1563         if (journal->j_flags & JFS_ABORT)
1564                 err = -EROFS;
1565         else
1566                 err = journal->j_errno;
1567         spin_unlock(&journal->j_state_lock);
1568         return err;
1569 }
1570
1571 /**
1572  * int journal_clear_err () - clears the journal's error state
1573  * @journal: journal to act on.
1574  *
1575  * An error must be cleared or Acked to take a FS out of readonly
1576  * mode.
1577  */
1578 int journal_clear_err(journal_t *journal)
1579 {
1580         int err = 0;
1581
1582         spin_lock(&journal->j_state_lock);
1583         if (journal->j_flags & JFS_ABORT)
1584                 err = -EROFS;
1585         else
1586                 journal->j_errno = 0;
1587         spin_unlock(&journal->j_state_lock);
1588         return err;
1589 }
1590
1591 /**
1592  * void journal_ack_err() - Ack journal err.
1593  * @journal: journal to act on.
1594  *
1595  * An error must be cleared or Acked to take a FS out of readonly
1596  * mode.
1597  */
1598 void journal_ack_err(journal_t *journal)
1599 {
1600         spin_lock(&journal->j_state_lock);
1601         if (journal->j_errno)
1602                 journal->j_flags |= JFS_ACK_ERR;
1603         spin_unlock(&journal->j_state_lock);
1604 }
1605
1606 int journal_blocks_per_page(struct inode *inode)
1607 {
1608         return 1 << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
1609 }
1610
1611 /*
1612  * Journal_head storage management
1613  */
1614 static struct kmem_cache *journal_head_cache;
1615 #ifdef CONFIG_JBD_DEBUG
1616 static atomic_t nr_journal_heads = ATOMIC_INIT(0);
1617 #endif
1618
1619 static int journal_init_journal_head_cache(void)
1620 {
1621         int retval;
1622
1623         J_ASSERT(journal_head_cache == 0);
1624         journal_head_cache = kmem_cache_create("journal_head",
1625                                 sizeof(struct journal_head),
1626                                 0,              /* offset */
1627                                 SLAB_TEMPORARY, /* flags */
1628                                 NULL);          /* ctor */
1629         retval = 0;
1630         if (journal_head_cache == 0) {
1631                 retval = -ENOMEM;
1632                 printk(KERN_EMERG "JBD: no memory for journal_head cache\n");
1633         }
1634         return retval;
1635 }
1636
1637 static void journal_destroy_journal_head_cache(void)
1638 {
1639         J_ASSERT(journal_head_cache != NULL);
1640         kmem_cache_destroy(journal_head_cache);
1641         journal_head_cache = NULL;
1642 }
1643
1644 /*
1645  * journal_head splicing and dicing
1646  */
1647 static struct journal_head *journal_alloc_journal_head(void)
1648 {
1649         struct journal_head *ret;
1650         static unsigned long last_warning;
1651
1652 #ifdef CONFIG_JBD_DEBUG
1653         atomic_inc(&nr_journal_heads);
1654 #endif
1655         ret = kmem_cache_alloc(journal_head_cache, GFP_NOFS);
1656         if (ret == NULL) {
1657                 jbd_debug(1, "out of memory for journal_head\n");
1658                 if (time_after(jiffies, last_warning + 5*HZ)) {
1659                         printk(KERN_NOTICE "ENOMEM in %s, retrying.\n",
1660                                __FUNCTION__);
1661                         last_warning = jiffies;
1662                 }
1663                 while (ret == NULL) {
1664                         yield();
1665                         ret = kmem_cache_alloc(journal_head_cache, GFP_NOFS);
1666                 }
1667         }
1668         return ret;
1669 }
1670
1671 static void journal_free_journal_head(struct journal_head *jh)
1672 {
1673 #ifdef CONFIG_JBD_DEBUG
1674         atomic_dec(&nr_journal_heads);
1675         memset(jh, JBD_POISON_FREE, sizeof(*jh));
1676 #endif
1677         kmem_cache_free(journal_head_cache, jh);
1678 }
1679
1680 /*
1681  * A journal_head is attached to a buffer_head whenever JBD has an
1682  * interest in the buffer.
1683  *
1684  * Whenever a buffer has an attached journal_head, its ->b_state:BH_JBD bit
1685  * is set.  This bit is tested in core kernel code where we need to take
1686  * JBD-specific actions.  Testing the zeroness of ->b_private is not reliable
1687  * there.
1688  *
1689  * When a buffer has its BH_JBD bit set, its ->b_count is elevated by one.
1690  *
1691  * When a buffer has its BH_JBD bit set it is immune from being released by
1692  * core kernel code, mainly via ->b_count.
1693  *
1694  * A journal_head may be detached from its buffer_head when the journal_head's
1695  * b_transaction, b_cp_transaction and b_next_transaction pointers are NULL.
1696  * Various places in JBD call journal_remove_journal_head() to indicate that the
1697  * journal_head can be dropped if needed.
1698  *
1699  * Various places in the kernel want to attach a journal_head to a buffer_head
1700  * _before_ attaching the journal_head to a transaction.  To protect the
1701  * journal_head in this situation, journal_add_journal_head elevates the
1702  * journal_head's b_jcount refcount by one.  The caller must call
1703  * journal_put_journal_head() to undo this.
1704  *
1705  * So the typical usage would be:
1706  *
1707  *      (Attach a journal_head if needed.  Increments b_jcount)
1708  *      struct journal_head *jh = journal_add_journal_head(bh);
1709  *      ...
1710  *      jh->b_transaction = xxx;
1711  *      journal_put_journal_head(jh);
1712  *
1713  * Now, the journal_head's b_jcount is zero, but it is safe from being released
1714  * because it has a non-zero b_transaction.
1715  */
1716
1717 /*
1718  * Give a buffer_head a journal_head.
1719  *
1720  * Doesn't need the journal lock.
1721  * May sleep.
1722  */
1723 struct journal_head *journal_add_journal_head(struct buffer_head *bh)
1724 {
1725         struct journal_head *jh;
1726         struct journal_head *new_jh = NULL;
1727
1728 repeat:
1729         if (!buffer_jbd(bh)) {
1730                 new_jh = journal_alloc_journal_head();
1731                 memset(new_jh, 0, sizeof(*new_jh));
1732         }
1733
1734         jbd_lock_bh_journal_head(bh);
1735         if (buffer_jbd(bh)) {
1736                 jh = bh2jh(bh);
1737         } else {
1738                 J_ASSERT_BH(bh,
1739                         (atomic_read(&bh->b_count) > 0) ||
1740                         (bh->b_page && bh->b_page->mapping));
1741
1742                 if (!new_jh) {
1743                         jbd_unlock_bh_journal_head(bh);
1744                         goto repeat;
1745                 }
1746
1747                 jh = new_jh;
1748                 new_jh = NULL;          /* We consumed it */
1749                 set_buffer_jbd(bh);
1750                 bh->b_private = jh;
1751                 jh->b_bh = bh;
1752                 get_bh(bh);
1753                 BUFFER_TRACE(bh, "added journal_head");
1754         }
1755         jh->b_jcount++;
1756         jbd_unlock_bh_journal_head(bh);
1757         if (new_jh)
1758                 journal_free_journal_head(new_jh);
1759         return bh->b_private;
1760 }
1761
1762 /*
1763  * Grab a ref against this buffer_head's journal_head.  If it ended up not
1764  * having a journal_head, return NULL
1765  */
1766 struct journal_head *journal_grab_journal_head(struct buffer_head *bh)
1767 {
1768         struct journal_head *jh = NULL;
1769
1770         jbd_lock_bh_journal_head(bh);
1771         if (buffer_jbd(bh)) {
1772                 jh = bh2jh(bh);
1773                 jh->b_jcount++;
1774         }
1775         jbd_unlock_bh_journal_head(bh);
1776         return jh;
1777 }
1778
1779 static void __journal_remove_journal_head(struct buffer_head *bh)
1780 {
1781         struct journal_head *jh = bh2jh(bh);
1782
1783         J_ASSERT_JH(jh, jh->b_jcount >= 0);
1784
1785         get_bh(bh);
1786         if (jh->b_jcount == 0) {
1787                 if (jh->b_transaction == NULL &&
1788                                 jh->b_next_transaction == NULL &&
1789                                 jh->b_cp_transaction == NULL) {
1790                         J_ASSERT_JH(jh, jh->b_jlist == BJ_None);
1791                         J_ASSERT_BH(bh, buffer_jbd(bh));
1792                         J_ASSERT_BH(bh, jh2bh(jh) == bh);
1793                         BUFFER_TRACE(bh, "remove journal_head");
1794                         if (jh->b_frozen_data) {
1795                                 printk(KERN_WARNING "%s: freeing "
1796                                                 "b_frozen_data\n",
1797                                                 __FUNCTION__);
1798                                 jbd_free(jh->b_frozen_data, bh->b_size);
1799                         }
1800                         if (jh->b_committed_data) {
1801                                 printk(KERN_WARNING "%s: freeing "
1802                                                 "b_committed_data\n",
1803                                                 __FUNCTION__);
1804                                 jbd_free(jh->b_committed_data, bh->b_size);
1805                         }
1806                         bh->b_private = NULL;
1807                         jh->b_bh = NULL;        /* debug, really */
1808                         clear_buffer_jbd(bh);
1809                         __brelse(bh);
1810                         journal_free_journal_head(jh);
1811                 } else {
1812                         BUFFER_TRACE(bh, "journal_head was locked");
1813                 }
1814         }
1815 }
1816
1817 /*
1818  * journal_remove_journal_head(): if the buffer isn't attached to a transaction
1819  * and has a zero b_jcount then remove and release its journal_head.   If we did
1820  * see that the buffer is not used by any transaction we also "logically"
1821  * decrement ->b_count.
1822  *
1823  * We in fact take an additional increment on ->b_count as a convenience,
1824  * because the caller usually wants to do additional things with the bh
1825  * after calling here.
1826  * The caller of journal_remove_journal_head() *must* run __brelse(bh) at some
1827  * time.  Once the caller has run __brelse(), the buffer is eligible for
1828  * reaping by try_to_free_buffers().
1829  */
1830 void journal_remove_journal_head(struct buffer_head *bh)
1831 {
1832         jbd_lock_bh_journal_head(bh);
1833         __journal_remove_journal_head(bh);
1834         jbd_unlock_bh_journal_head(bh);
1835 }
1836
1837 /*
1838  * Drop a reference on the passed journal_head.  If it fell to zero then try to
1839  * release the journal_head from the buffer_head.
1840  */
1841 void journal_put_journal_head(struct journal_head *jh)
1842 {
1843         struct buffer_head *bh = jh2bh(jh);
1844
1845         jbd_lock_bh_journal_head(bh);
1846         J_ASSERT_JH(jh, jh->b_jcount > 0);
1847         --jh->b_jcount;
1848         if (!jh->b_jcount && !jh->b_transaction) {
1849                 __journal_remove_journal_head(bh);
1850                 __brelse(bh);
1851         }
1852         jbd_unlock_bh_journal_head(bh);
1853 }
1854
1855 /*
1856  * debugfs tunables
1857  */
1858 #ifdef CONFIG_JBD_DEBUG
1859
1860 u8 journal_enable_debug __read_mostly;
1861 EXPORT_SYMBOL(journal_enable_debug);
1862
1863 static struct dentry *jbd_debugfs_dir;
1864 static struct dentry *jbd_debug;
1865
1866 static void __init jbd_create_debugfs_entry(void)
1867 {
1868         jbd_debugfs_dir = debugfs_create_dir("jbd", NULL);
1869         if (jbd_debugfs_dir)
1870                 jbd_debug = debugfs_create_u8("jbd-debug", S_IRUGO,
1871                                                jbd_debugfs_dir,
1872                                                &journal_enable_debug);
1873 }
1874
1875 static void __exit jbd_remove_debugfs_entry(void)
1876 {
1877         debugfs_remove(jbd_debug);
1878         debugfs_remove(jbd_debugfs_dir);
1879 }
1880
1881 #else
1882
1883 static inline void jbd_create_debugfs_entry(void)
1884 {
1885 }
1886
1887 static inline void jbd_remove_debugfs_entry(void)
1888 {
1889 }
1890
1891 #endif
1892
1893 struct kmem_cache *jbd_handle_cache;
1894
1895 static int __init journal_init_handle_cache(void)
1896 {
1897         jbd_handle_cache = kmem_cache_create("journal_handle",
1898                                 sizeof(handle_t),
1899                                 0,              /* offset */
1900                                 SLAB_TEMPORARY, /* flags */
1901                                 NULL);          /* ctor */
1902         if (jbd_handle_cache == NULL) {
1903                 printk(KERN_EMERG "JBD: failed to create handle cache\n");
1904                 return -ENOMEM;
1905         }
1906         return 0;
1907 }
1908
1909 static void journal_destroy_handle_cache(void)
1910 {
1911         if (jbd_handle_cache)
1912                 kmem_cache_destroy(jbd_handle_cache);
1913 }
1914
1915 /*
1916  * Module startup and shutdown
1917  */
1918
1919 static int __init journal_init_caches(void)
1920 {
1921         int ret;
1922
1923         ret = journal_init_revoke_caches();
1924         if (ret == 0)
1925                 ret = journal_init_journal_head_cache();
1926         if (ret == 0)
1927                 ret = journal_init_handle_cache();
1928         return ret;
1929 }
1930
1931 static void journal_destroy_caches(void)
1932 {
1933         journal_destroy_revoke_caches();
1934         journal_destroy_journal_head_cache();
1935         journal_destroy_handle_cache();
1936 }
1937
1938 static int __init journal_init(void)
1939 {
1940         int ret;
1941
1942         BUILD_BUG_ON(sizeof(struct journal_superblock_s) != 1024);
1943
1944         ret = journal_init_caches();
1945         if (ret != 0)
1946                 journal_destroy_caches();
1947         jbd_create_debugfs_entry();
1948         return ret;
1949 }
1950
1951 static void __exit journal_exit(void)
1952 {
1953 #ifdef CONFIG_JBD_DEBUG
1954         int n = atomic_read(&nr_journal_heads);
1955         if (n)
1956                 printk(KERN_EMERG "JBD: leaked %d journal_heads!\n", n);
1957 #endif
1958         jbd_remove_debugfs_entry();
1959         journal_destroy_caches();
1960 }
1961
1962 MODULE_LICENSE("GPL");
1963 module_init(journal_init);
1964 module_exit(journal_exit);
1965