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