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