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