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