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