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