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