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