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