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