jbd2: simplify return path of journal_init_common
[linux-flexiantxendom0-3.2.10.git] / fs / jbd2 / journal.c
1 /*
2  * linux/fs/jbd2/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/jbd2.h>
29 #include <linux/errno.h>
30 #include <linux/slab.h>
31 #include <linux/init.h>
32 #include <linux/mm.h>
33 #include <linux/freezer.h>
34 #include <linux/pagemap.h>
35 #include <linux/kthread.h>
36 #include <linux/poison.h>
37 #include <linux/proc_fs.h>
38 #include <linux/debugfs.h>
39 #include <linux/seq_file.h>
40 #include <linux/math64.h>
41 #include <linux/hash.h>
42 #include <linux/log2.h>
43 #include <linux/vmalloc.h>
44 #include <linux/backing-dev.h>
45 #include <linux/bitops.h>
46 #include <linux/ratelimit.h>
47
48 #define CREATE_TRACE_POINTS
49 #include <trace/events/jbd2.h>
50
51 #include <asm/uaccess.h>
52 #include <asm/page.h>
53 #include <asm/system.h>
54
55 EXPORT_SYMBOL(jbd2_journal_extend);
56 EXPORT_SYMBOL(jbd2_journal_stop);
57 EXPORT_SYMBOL(jbd2_journal_lock_updates);
58 EXPORT_SYMBOL(jbd2_journal_unlock_updates);
59 EXPORT_SYMBOL(jbd2_journal_get_write_access);
60 EXPORT_SYMBOL(jbd2_journal_get_create_access);
61 EXPORT_SYMBOL(jbd2_journal_get_undo_access);
62 EXPORT_SYMBOL(jbd2_journal_set_triggers);
63 EXPORT_SYMBOL(jbd2_journal_dirty_metadata);
64 EXPORT_SYMBOL(jbd2_journal_release_buffer);
65 EXPORT_SYMBOL(jbd2_journal_forget);
66 #if 0
67 EXPORT_SYMBOL(journal_sync_buffer);
68 #endif
69 EXPORT_SYMBOL(jbd2_journal_flush);
70 EXPORT_SYMBOL(jbd2_journal_revoke);
71
72 EXPORT_SYMBOL(jbd2_journal_init_dev);
73 EXPORT_SYMBOL(jbd2_journal_init_inode);
74 EXPORT_SYMBOL(jbd2_journal_update_format);
75 EXPORT_SYMBOL(jbd2_journal_check_used_features);
76 EXPORT_SYMBOL(jbd2_journal_check_available_features);
77 EXPORT_SYMBOL(jbd2_journal_set_features);
78 EXPORT_SYMBOL(jbd2_journal_load);
79 EXPORT_SYMBOL(jbd2_journal_destroy);
80 EXPORT_SYMBOL(jbd2_journal_abort);
81 EXPORT_SYMBOL(jbd2_journal_errno);
82 EXPORT_SYMBOL(jbd2_journal_ack_err);
83 EXPORT_SYMBOL(jbd2_journal_clear_err);
84 EXPORT_SYMBOL(jbd2_log_wait_commit);
85 EXPORT_SYMBOL(jbd2_log_start_commit);
86 EXPORT_SYMBOL(jbd2_journal_start_commit);
87 EXPORT_SYMBOL(jbd2_journal_force_commit_nested);
88 EXPORT_SYMBOL(jbd2_journal_wipe);
89 EXPORT_SYMBOL(jbd2_journal_blocks_per_page);
90 EXPORT_SYMBOL(jbd2_journal_invalidatepage);
91 EXPORT_SYMBOL(jbd2_journal_try_to_free_buffers);
92 EXPORT_SYMBOL(jbd2_journal_force_commit);
93 EXPORT_SYMBOL(jbd2_journal_file_inode);
94 EXPORT_SYMBOL(jbd2_journal_init_jbd_inode);
95 EXPORT_SYMBOL(jbd2_journal_release_jbd_inode);
96 EXPORT_SYMBOL(jbd2_journal_begin_ordered_truncate);
97
98 static int journal_convert_superblock_v1(journal_t *, journal_superblock_t *);
99 static void __journal_abort_soft (journal_t *journal, int errno);
100 static int jbd2_journal_create_slab(size_t slab_size);
101
102 /*
103  * Helper function used to manage commit timeouts
104  */
105
106 static void commit_timeout(unsigned long __data)
107 {
108         struct task_struct * p = (struct task_struct *) __data;
109
110         wake_up_process(p);
111 }
112
113 /*
114  * kjournald2: The main thread function used to manage a logging device
115  * journal.
116  *
117  * This kernel thread is responsible for two things:
118  *
119  * 1) COMMIT:  Every so often we need to commit the current state of the
120  *    filesystem to disk.  The journal thread is responsible for writing
121  *    all of the metadata buffers to disk.
122  *
123  * 2) CHECKPOINT: We cannot reuse a used section of the log file until all
124  *    of the data in that part of the log has been rewritten elsewhere on
125  *    the disk.  Flushing these old buffers to reclaim space in the log is
126  *    known as checkpointing, and this thread is responsible for that job.
127  */
128
129 static int kjournald2(void *arg)
130 {
131         journal_t *journal = arg;
132         transaction_t *transaction;
133
134         /*
135          * Set up an interval timer which can be used to trigger a commit wakeup
136          * after the commit interval expires
137          */
138         setup_timer(&journal->j_commit_timer, commit_timeout,
139                         (unsigned long)current);
140
141         /* Record that the journal thread is running */
142         journal->j_task = current;
143         wake_up(&journal->j_wait_done_commit);
144
145         /*
146          * And now, wait forever for commit wakeup events.
147          */
148         write_lock(&journal->j_state_lock);
149
150 loop:
151         if (journal->j_flags & JBD2_UNMOUNT)
152                 goto end_loop;
153
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                 write_unlock(&journal->j_state_lock);
160                 del_timer_sync(&journal->j_commit_timer);
161                 jbd2_journal_commit_transaction(journal);
162                 write_lock(&journal->j_state_lock);
163                 goto loop;
164         }
165
166         wake_up(&journal->j_wait_done_commit);
167         if (freezing(current)) {
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 kjournald2\n");
174                 write_unlock(&journal->j_state_lock);
175                 refrigerator();
176                 write_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 (journal->j_flags & JBD2_UNMOUNT)
194                         should_sleep = 0;
195                 if (should_sleep) {
196                         write_unlock(&journal->j_state_lock);
197                         schedule();
198                         write_lock(&journal->j_state_lock);
199                 }
200                 finish_wait(&journal->j_wait_commit, &wait);
201         }
202
203         jbd_debug(1, "kjournald2 wakes\n");
204
205         /*
206          * Were we woken up by a commit wakeup event?
207          */
208         transaction = journal->j_running_transaction;
209         if (transaction && time_after_eq(jiffies, transaction->t_expires)) {
210                 journal->j_commit_request = transaction->t_tid;
211                 jbd_debug(1, "woke because of timeout\n");
212         }
213         goto loop;
214
215 end_loop:
216         write_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 int jbd2_journal_start_thread(journal_t *journal)
225 {
226         struct task_struct *t;
227
228         t = kthread_run(kjournald2, journal, "jbd2/%s",
229                         journal->j_devname);
230         if (IS_ERR(t))
231                 return PTR_ERR(t);
232
233         wait_event(journal->j_wait_done_commit, journal->j_task != NULL);
234         return 0;
235 }
236
237 static void journal_kill_thread(journal_t *journal)
238 {
239         write_lock(&journal->j_state_lock);
240         journal->j_flags |= JBD2_UNMOUNT;
241
242         while (journal->j_task) {
243                 wake_up(&journal->j_wait_commit);
244                 write_unlock(&journal->j_state_lock);
245                 wait_event(journal->j_wait_done_commit, journal->j_task == NULL);
246                 write_lock(&journal->j_state_lock);
247         }
248         write_unlock(&journal->j_state_lock);
249 }
250
251 /*
252  * jbd2_journal_write_metadata_buffer: write a metadata buffer to the journal.
253  *
254  * Writes a metadata buffer to a given disk block.  The actual IO is not
255  * performed but a new buffer_head is constructed which labels the data
256  * to be written with the correct destination disk block.
257  *
258  * Any magic-number escaping which needs to be done will cause a
259  * copy-out here.  If the buffer happens to start with the
260  * JBD2_MAGIC_NUMBER, then we can't write it to the log directly: the
261  * magic number is only written to the log for descripter blocks.  In
262  * this case, we copy the data and replace the first word with 0, and we
263  * return a result code which indicates that this buffer needs to be
264  * marked as an escaped buffer in the corresponding log descriptor
265  * block.  The missing word can then be restored when the block is read
266  * during recovery.
267  *
268  * If the source buffer has already been modified by a new transaction
269  * since we took the last commit snapshot, we use the frozen copy of
270  * that data for IO.  If we end up using the existing buffer_head's data
271  * for the write, then we *have* to lock the buffer to prevent anyone
272  * else from using and possibly modifying it while the IO is in
273  * progress.
274  *
275  * The function returns a pointer to the buffer_heads to be used for IO.
276  *
277  * We assume that the journal has already been locked in this function.
278  *
279  * Return value:
280  *  <0: Error
281  * >=0: Finished OK
282  *
283  * On success:
284  * Bit 0 set == escape performed on the data
285  * Bit 1 set == buffer copy-out performed (kfree the data after IO)
286  */
287
288 int jbd2_journal_write_metadata_buffer(transaction_t *transaction,
289                                   struct journal_head  *jh_in,
290                                   struct journal_head **jh_out,
291                                   unsigned long long blocknr)
292 {
293         int need_copy_out = 0;
294         int done_copy_out = 0;
295         int do_escape = 0;
296         char *mapped_data;
297         struct buffer_head *new_bh;
298         struct journal_head *new_jh;
299         struct page *new_page;
300         unsigned int new_offset;
301         struct buffer_head *bh_in = jh2bh(jh_in);
302         journal_t *journal = transaction->t_journal;
303
304         /*
305          * The buffer really shouldn't be locked: only the current committing
306          * transaction is allowed to write it, so nobody else is allowed
307          * to do any IO.
308          *
309          * akpm: except if we're journalling data, and write() output is
310          * also part of a shared mapping, and another thread has
311          * decided to launch a writepage() against this buffer.
312          */
313         J_ASSERT_BH(bh_in, buffer_jbddirty(bh_in));
314
315 retry_alloc:
316         new_bh = alloc_buffer_head(GFP_NOFS);
317         if (!new_bh) {
318                 /*
319                  * Failure is not an option, but __GFP_NOFAIL is going
320                  * away; so we retry ourselves here.
321                  */
322                 congestion_wait(BLK_RW_ASYNC, HZ/50);
323                 goto retry_alloc;
324         }
325
326         /* keep subsequent assertions sane */
327         new_bh->b_state = 0;
328         init_buffer(new_bh, NULL, NULL);
329         atomic_set(&new_bh->b_count, 1);
330         new_jh = jbd2_journal_add_journal_head(new_bh); /* This sleeps */
331
332         /*
333          * If a new transaction has already done a buffer copy-out, then
334          * we use that version of the data for the commit.
335          */
336         jbd_lock_bh_state(bh_in);
337 repeat:
338         if (jh_in->b_frozen_data) {
339                 done_copy_out = 1;
340                 new_page = virt_to_page(jh_in->b_frozen_data);
341                 new_offset = offset_in_page(jh_in->b_frozen_data);
342         } else {
343                 new_page = jh2bh(jh_in)->b_page;
344                 new_offset = offset_in_page(jh2bh(jh_in)->b_data);
345         }
346
347         mapped_data = kmap_atomic(new_page, KM_USER0);
348         /*
349          * Fire data frozen trigger if data already wasn't frozen.  Do this
350          * before checking for escaping, as the trigger may modify the magic
351          * offset.  If a copy-out happens afterwards, it will have the correct
352          * data in the buffer.
353          */
354         if (!done_copy_out)
355                 jbd2_buffer_frozen_trigger(jh_in, mapped_data + new_offset,
356                                            jh_in->b_triggers);
357
358         /*
359          * Check for escaping
360          */
361         if (*((__be32 *)(mapped_data + new_offset)) ==
362                                 cpu_to_be32(JBD2_MAGIC_NUMBER)) {
363                 need_copy_out = 1;
364                 do_escape = 1;
365         }
366         kunmap_atomic(mapped_data, KM_USER0);
367
368         /*
369          * Do we need to do a data copy?
370          */
371         if (need_copy_out && !done_copy_out) {
372                 char *tmp;
373
374                 jbd_unlock_bh_state(bh_in);
375                 tmp = jbd2_alloc(bh_in->b_size, GFP_NOFS);
376                 if (!tmp) {
377                         jbd2_journal_put_journal_head(new_jh);
378                         return -ENOMEM;
379                 }
380                 jbd_lock_bh_state(bh_in);
381                 if (jh_in->b_frozen_data) {
382                         jbd2_free(tmp, bh_in->b_size);
383                         goto repeat;
384                 }
385
386                 jh_in->b_frozen_data = tmp;
387                 mapped_data = kmap_atomic(new_page, KM_USER0);
388                 memcpy(tmp, mapped_data + new_offset, jh2bh(jh_in)->b_size);
389                 kunmap_atomic(mapped_data, KM_USER0);
390
391                 new_page = virt_to_page(tmp);
392                 new_offset = offset_in_page(tmp);
393                 done_copy_out = 1;
394
395                 /*
396                  * This isn't strictly necessary, as we're using frozen
397                  * data for the escaping, but it keeps consistency with
398                  * b_frozen_data usage.
399                  */
400                 jh_in->b_frozen_triggers = jh_in->b_triggers;
401         }
402
403         /*
404          * Did we need to do an escaping?  Now we've done all the
405          * copying, we can finally do so.
406          */
407         if (do_escape) {
408                 mapped_data = kmap_atomic(new_page, KM_USER0);
409                 *((unsigned int *)(mapped_data + new_offset)) = 0;
410                 kunmap_atomic(mapped_data, KM_USER0);
411         }
412
413         set_bh_page(new_bh, new_page, new_offset);
414         new_jh->b_transaction = NULL;
415         new_bh->b_size = jh2bh(jh_in)->b_size;
416         new_bh->b_bdev = transaction->t_journal->j_dev;
417         new_bh->b_blocknr = blocknr;
418         set_buffer_mapped(new_bh);
419         set_buffer_dirty(new_bh);
420
421         *jh_out = new_jh;
422
423         /*
424          * The to-be-written buffer needs to get moved to the io queue,
425          * and the original buffer whose contents we are shadowing or
426          * copying is moved to the transaction's shadow queue.
427          */
428         JBUFFER_TRACE(jh_in, "file as BJ_Shadow");
429         spin_lock(&journal->j_list_lock);
430         __jbd2_journal_file_buffer(jh_in, transaction, BJ_Shadow);
431         spin_unlock(&journal->j_list_lock);
432         jbd_unlock_bh_state(bh_in);
433
434         JBUFFER_TRACE(new_jh, "file as BJ_IO");
435         jbd2_journal_file_buffer(new_jh, transaction, BJ_IO);
436
437         return do_escape | (done_copy_out << 1);
438 }
439
440 /*
441  * Allocation code for the journal file.  Manage the space left in the
442  * journal, so that we can begin checkpointing when appropriate.
443  */
444
445 /*
446  * __jbd2_log_space_left: Return the number of free blocks left in the journal.
447  *
448  * Called with the journal already locked.
449  *
450  * Called under j_state_lock
451  */
452
453 int __jbd2_log_space_left(journal_t *journal)
454 {
455         int left = journal->j_free;
456
457         /* assert_spin_locked(&journal->j_state_lock); */
458
459         /*
460          * Be pessimistic here about the number of those free blocks which
461          * might be required for log descriptor control blocks.
462          */
463
464 #define MIN_LOG_RESERVED_BLOCKS 32 /* Allow for rounding errors */
465
466         left -= MIN_LOG_RESERVED_BLOCKS;
467
468         if (left <= 0)
469                 return 0;
470         left -= (left >> 3);
471         return left;
472 }
473
474 /*
475  * Called under j_state_lock.  Returns true if a transaction commit was started.
476  */
477 int __jbd2_log_start_commit(journal_t *journal, tid_t target)
478 {
479         /*
480          * Are we already doing a recent enough commit?
481          */
482         if (!tid_geq(journal->j_commit_request, target)) {
483                 /*
484                  * We want a new commit: OK, mark the request and wakeup the
485                  * commit thread.  We do _not_ do the commit ourselves.
486                  */
487
488                 journal->j_commit_request = target;
489                 jbd_debug(1, "JBD: requesting commit %d/%d\n",
490                           journal->j_commit_request,
491                           journal->j_commit_sequence);
492                 wake_up(&journal->j_wait_commit);
493                 return 1;
494         }
495         return 0;
496 }
497
498 int jbd2_log_start_commit(journal_t *journal, tid_t tid)
499 {
500         int ret;
501
502         write_lock(&journal->j_state_lock);
503         ret = __jbd2_log_start_commit(journal, tid);
504         write_unlock(&journal->j_state_lock);
505         return ret;
506 }
507
508 /*
509  * Force and wait upon a commit if the calling process is not within
510  * transaction.  This is used for forcing out undo-protected data which contains
511  * bitmaps, when the fs is running out of space.
512  *
513  * We can only force the running transaction if we don't have an active handle;
514  * otherwise, we will deadlock.
515  *
516  * Returns true if a transaction was started.
517  */
518 int jbd2_journal_force_commit_nested(journal_t *journal)
519 {
520         transaction_t *transaction = NULL;
521         tid_t tid;
522
523         read_lock(&journal->j_state_lock);
524         if (journal->j_running_transaction && !current->journal_info) {
525                 transaction = journal->j_running_transaction;
526                 __jbd2_log_start_commit(journal, transaction->t_tid);
527         } else if (journal->j_committing_transaction)
528                 transaction = journal->j_committing_transaction;
529
530         if (!transaction) {
531                 read_unlock(&journal->j_state_lock);
532                 return 0;       /* Nothing to retry */
533         }
534
535         tid = transaction->t_tid;
536         read_unlock(&journal->j_state_lock);
537         jbd2_log_wait_commit(journal, tid);
538         return 1;
539 }
540
541 /*
542  * Start a commit of the current running transaction (if any).  Returns true
543  * if a transaction is going to be committed (or is currently already
544  * committing), and fills its tid in at *ptid
545  */
546 int jbd2_journal_start_commit(journal_t *journal, tid_t *ptid)
547 {
548         int ret = 0;
549
550         write_lock(&journal->j_state_lock);
551         if (journal->j_running_transaction) {
552                 tid_t tid = journal->j_running_transaction->t_tid;
553
554                 __jbd2_log_start_commit(journal, tid);
555                 /* There's a running transaction and we've just made sure
556                  * it's commit has been scheduled. */
557                 if (ptid)
558                         *ptid = tid;
559                 ret = 1;
560         } else if (journal->j_committing_transaction) {
561                 /*
562                  * If ext3_write_super() recently started a commit, then we
563                  * have to wait for completion of that transaction
564                  */
565                 if (ptid)
566                         *ptid = journal->j_committing_transaction->t_tid;
567                 ret = 1;
568         }
569         write_unlock(&journal->j_state_lock);
570         return ret;
571 }
572
573 /*
574  * Wait for a specified commit to complete.
575  * The caller may not hold the journal lock.
576  */
577 int jbd2_log_wait_commit(journal_t *journal, tid_t tid)
578 {
579         int err = 0;
580
581         read_lock(&journal->j_state_lock);
582 #ifdef CONFIG_JBD2_DEBUG
583         if (!tid_geq(journal->j_commit_request, tid)) {
584                 printk(KERN_EMERG
585                        "%s: error: j_commit_request=%d, tid=%d\n",
586                        __func__, journal->j_commit_request, tid);
587         }
588 #endif
589         while (tid_gt(tid, journal->j_commit_sequence)) {
590                 jbd_debug(1, "JBD: want %d, j_commit_sequence=%d\n",
591                                   tid, journal->j_commit_sequence);
592                 wake_up(&journal->j_wait_commit);
593                 read_unlock(&journal->j_state_lock);
594                 wait_event(journal->j_wait_done_commit,
595                                 !tid_gt(tid, journal->j_commit_sequence));
596                 read_lock(&journal->j_state_lock);
597         }
598         read_unlock(&journal->j_state_lock);
599
600         if (unlikely(is_journal_aborted(journal))) {
601                 printk(KERN_EMERG "journal commit I/O error\n");
602                 err = -EIO;
603         }
604         return err;
605 }
606
607 /*
608  * Log buffer allocation routines:
609  */
610
611 int jbd2_journal_next_log_block(journal_t *journal, unsigned long long *retp)
612 {
613         unsigned long blocknr;
614
615         write_lock(&journal->j_state_lock);
616         J_ASSERT(journal->j_free > 1);
617
618         blocknr = journal->j_head;
619         journal->j_head++;
620         journal->j_free--;
621         if (journal->j_head == journal->j_last)
622                 journal->j_head = journal->j_first;
623         write_unlock(&journal->j_state_lock);
624         return jbd2_journal_bmap(journal, blocknr, retp);
625 }
626
627 /*
628  * Conversion of logical to physical block numbers for the journal
629  *
630  * On external journals the journal blocks are identity-mapped, so
631  * this is a no-op.  If needed, we can use j_blk_offset - everything is
632  * ready.
633  */
634 int jbd2_journal_bmap(journal_t *journal, unsigned long blocknr,
635                  unsigned long long *retp)
636 {
637         int err = 0;
638         unsigned long long ret;
639
640         if (journal->j_inode) {
641                 ret = bmap(journal->j_inode, blocknr);
642                 if (ret)
643                         *retp = ret;
644                 else {
645                         printk(KERN_ALERT "%s: journal block not found "
646                                         "at offset %lu on %s\n",
647                                __func__, blocknr, journal->j_devname);
648                         err = -EIO;
649                         __journal_abort_soft(journal, err);
650                 }
651         } else {
652                 *retp = blocknr; /* +journal->j_blk_offset */
653         }
654         return err;
655 }
656
657 /*
658  * We play buffer_head aliasing tricks to write data/metadata blocks to
659  * the journal without copying their contents, but for journal
660  * descriptor blocks we do need to generate bona fide buffers.
661  *
662  * After the caller of jbd2_journal_get_descriptor_buffer() has finished modifying
663  * the buffer's contents they really should run flush_dcache_page(bh->b_page).
664  * But we don't bother doing that, so there will be coherency problems with
665  * mmaps of blockdevs which hold live JBD-controlled filesystems.
666  */
667 struct journal_head *jbd2_journal_get_descriptor_buffer(journal_t *journal)
668 {
669         struct buffer_head *bh;
670         unsigned long long blocknr;
671         int err;
672
673         err = jbd2_journal_next_log_block(journal, &blocknr);
674
675         if (err)
676                 return NULL;
677
678         bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize);
679         if (!bh)
680                 return NULL;
681         lock_buffer(bh);
682         memset(bh->b_data, 0, journal->j_blocksize);
683         set_buffer_uptodate(bh);
684         unlock_buffer(bh);
685         BUFFER_TRACE(bh, "return this buffer");
686         return jbd2_journal_add_journal_head(bh);
687 }
688
689 struct jbd2_stats_proc_session {
690         journal_t *journal;
691         struct transaction_stats_s *stats;
692         int start;
693         int max;
694 };
695
696 static void *jbd2_seq_info_start(struct seq_file *seq, loff_t *pos)
697 {
698         return *pos ? NULL : SEQ_START_TOKEN;
699 }
700
701 static void *jbd2_seq_info_next(struct seq_file *seq, void *v, loff_t *pos)
702 {
703         return NULL;
704 }
705
706 static int jbd2_seq_info_show(struct seq_file *seq, void *v)
707 {
708         struct jbd2_stats_proc_session *s = seq->private;
709
710         if (v != SEQ_START_TOKEN)
711                 return 0;
712         seq_printf(seq, "%lu transaction, each up to %u blocks\n",
713                         s->stats->ts_tid,
714                         s->journal->j_max_transaction_buffers);
715         if (s->stats->ts_tid == 0)
716                 return 0;
717         seq_printf(seq, "average: \n  %ums waiting for transaction\n",
718             jiffies_to_msecs(s->stats->run.rs_wait / s->stats->ts_tid));
719         seq_printf(seq, "  %ums running transaction\n",
720             jiffies_to_msecs(s->stats->run.rs_running / s->stats->ts_tid));
721         seq_printf(seq, "  %ums transaction was being locked\n",
722             jiffies_to_msecs(s->stats->run.rs_locked / s->stats->ts_tid));
723         seq_printf(seq, "  %ums flushing data (in ordered mode)\n",
724             jiffies_to_msecs(s->stats->run.rs_flushing / s->stats->ts_tid));
725         seq_printf(seq, "  %ums logging transaction\n",
726             jiffies_to_msecs(s->stats->run.rs_logging / s->stats->ts_tid));
727         seq_printf(seq, "  %lluus average transaction commit time\n",
728                    div_u64(s->journal->j_average_commit_time, 1000));
729         seq_printf(seq, "  %lu handles per transaction\n",
730             s->stats->run.rs_handle_count / s->stats->ts_tid);
731         seq_printf(seq, "  %lu blocks per transaction\n",
732             s->stats->run.rs_blocks / s->stats->ts_tid);
733         seq_printf(seq, "  %lu logged blocks per transaction\n",
734             s->stats->run.rs_blocks_logged / s->stats->ts_tid);
735         return 0;
736 }
737
738 static void jbd2_seq_info_stop(struct seq_file *seq, void *v)
739 {
740 }
741
742 static const struct seq_operations jbd2_seq_info_ops = {
743         .start  = jbd2_seq_info_start,
744         .next   = jbd2_seq_info_next,
745         .stop   = jbd2_seq_info_stop,
746         .show   = jbd2_seq_info_show,
747 };
748
749 static int jbd2_seq_info_open(struct inode *inode, struct file *file)
750 {
751         journal_t *journal = PDE(inode)->data;
752         struct jbd2_stats_proc_session *s;
753         int rc, size;
754
755         s = kmalloc(sizeof(*s), GFP_KERNEL);
756         if (s == NULL)
757                 return -ENOMEM;
758         size = sizeof(struct transaction_stats_s);
759         s->stats = kmalloc(size, GFP_KERNEL);
760         if (s->stats == NULL) {
761                 kfree(s);
762                 return -ENOMEM;
763         }
764         spin_lock(&journal->j_history_lock);
765         memcpy(s->stats, &journal->j_stats, size);
766         s->journal = journal;
767         spin_unlock(&journal->j_history_lock);
768
769         rc = seq_open(file, &jbd2_seq_info_ops);
770         if (rc == 0) {
771                 struct seq_file *m = file->private_data;
772                 m->private = s;
773         } else {
774                 kfree(s->stats);
775                 kfree(s);
776         }
777         return rc;
778
779 }
780
781 static int jbd2_seq_info_release(struct inode *inode, struct file *file)
782 {
783         struct seq_file *seq = file->private_data;
784         struct jbd2_stats_proc_session *s = seq->private;
785         kfree(s->stats);
786         kfree(s);
787         return seq_release(inode, file);
788 }
789
790 static const struct file_operations jbd2_seq_info_fops = {
791         .owner          = THIS_MODULE,
792         .open           = jbd2_seq_info_open,
793         .read           = seq_read,
794         .llseek         = seq_lseek,
795         .release        = jbd2_seq_info_release,
796 };
797
798 static struct proc_dir_entry *proc_jbd2_stats;
799
800 static void jbd2_stats_proc_init(journal_t *journal)
801 {
802         journal->j_proc_entry = proc_mkdir(journal->j_devname, proc_jbd2_stats);
803         if (journal->j_proc_entry) {
804                 proc_create_data("info", S_IRUGO, journal->j_proc_entry,
805                                  &jbd2_seq_info_fops, journal);
806         }
807 }
808
809 static void jbd2_stats_proc_exit(journal_t *journal)
810 {
811         remove_proc_entry("info", journal->j_proc_entry);
812         remove_proc_entry(journal->j_devname, proc_jbd2_stats);
813 }
814
815 /*
816  * Management for journal control blocks: functions to create and
817  * destroy journal_t structures, and to initialise and read existing
818  * journal blocks from disk.  */
819
820 /* First: create and setup a journal_t object in memory.  We initialise
821  * very few fields yet: that has to wait until we have created the
822  * journal structures from from scratch, or loaded them from disk. */
823
824 static journal_t * journal_init_common (void)
825 {
826         journal_t *journal;
827         int err;
828
829         journal = kzalloc(sizeof(*journal), GFP_KERNEL);
830         if (!journal)
831                 return NULL;
832
833         init_waitqueue_head(&journal->j_wait_transaction_locked);
834         init_waitqueue_head(&journal->j_wait_logspace);
835         init_waitqueue_head(&journal->j_wait_done_commit);
836         init_waitqueue_head(&journal->j_wait_checkpoint);
837         init_waitqueue_head(&journal->j_wait_commit);
838         init_waitqueue_head(&journal->j_wait_updates);
839         mutex_init(&journal->j_barrier);
840         mutex_init(&journal->j_checkpoint_mutex);
841         spin_lock_init(&journal->j_revoke_lock);
842         spin_lock_init(&journal->j_list_lock);
843         rwlock_init(&journal->j_state_lock);
844
845         journal->j_commit_interval = (HZ * JBD2_DEFAULT_MAX_COMMIT_AGE);
846         journal->j_min_batch_time = 0;
847         journal->j_max_batch_time = 15000; /* 15ms */
848
849         /* The journal is marked for error until we succeed with recovery! */
850         journal->j_flags = JBD2_ABORT;
851
852         /* Set up a default-sized revoke table for the new mount. */
853         err = jbd2_journal_init_revoke(journal, JOURNAL_REVOKE_DEFAULT_HASH);
854         if (err) {
855                 kfree(journal);
856                 return NULL;
857         }
858
859         spin_lock_init(&journal->j_history_lock);
860
861         return journal;
862 }
863
864 /* jbd2_journal_init_dev and jbd2_journal_init_inode:
865  *
866  * Create a journal structure assigned some fixed set of disk blocks to
867  * the journal.  We don't actually touch those disk blocks yet, but we
868  * need to set up all of the mapping information to tell the journaling
869  * system where the journal blocks are.
870  *
871  */
872
873 /**
874  *  journal_t * jbd2_journal_init_dev() - creates and initialises a journal structure
875  *  @bdev: Block device on which to create the journal
876  *  @fs_dev: Device which hold journalled filesystem for this journal.
877  *  @start: Block nr Start of journal.
878  *  @len:  Length of the journal in blocks.
879  *  @blocksize: blocksize of journalling device
880  *
881  *  Returns: a newly created journal_t *
882  *
883  *  jbd2_journal_init_dev creates a journal which maps a fixed contiguous
884  *  range of blocks on an arbitrary block device.
885  *
886  */
887 journal_t * jbd2_journal_init_dev(struct block_device *bdev,
888                         struct block_device *fs_dev,
889                         unsigned long long start, int len, int blocksize)
890 {
891         journal_t *journal = journal_init_common();
892         struct buffer_head *bh;
893         char *p;
894         int n;
895
896         if (!journal)
897                 return NULL;
898
899         /* journal descriptor can store up to n blocks -bzzz */
900         journal->j_blocksize = blocksize;
901         journal->j_dev = bdev;
902         journal->j_fs_dev = fs_dev;
903         journal->j_blk_offset = start;
904         journal->j_maxlen = len;
905         bdevname(journal->j_dev, journal->j_devname);
906         p = journal->j_devname;
907         while ((p = strchr(p, '/')))
908                 *p = '!';
909         jbd2_stats_proc_init(journal);
910         n = journal->j_blocksize / sizeof(journal_block_tag_t);
911         journal->j_wbufsize = n;
912         journal->j_wbuf = kmalloc(n * sizeof(struct buffer_head*), GFP_KERNEL);
913         if (!journal->j_wbuf) {
914                 printk(KERN_ERR "%s: Cant allocate bhs for commit thread\n",
915                         __func__);
916                 goto out_err;
917         }
918
919         bh = __getblk(journal->j_dev, start, journal->j_blocksize);
920         if (!bh) {
921                 printk(KERN_ERR
922                        "%s: Cannot get buffer for journal superblock\n",
923                        __func__);
924                 goto out_err;
925         }
926         journal->j_sb_buffer = bh;
927         journal->j_superblock = (journal_superblock_t *)bh->b_data;
928
929         return journal;
930 out_err:
931         kfree(journal->j_wbuf);
932         jbd2_stats_proc_exit(journal);
933         kfree(journal);
934         return NULL;
935 }
936
937 /**
938  *  journal_t * jbd2_journal_init_inode () - creates a journal which maps to a inode.
939  *  @inode: An inode to create the journal in
940  *
941  * jbd2_journal_init_inode creates a journal which maps an on-disk inode as
942  * the journal.  The inode must exist already, must support bmap() and
943  * must have all data blocks preallocated.
944  */
945 journal_t * jbd2_journal_init_inode (struct inode *inode)
946 {
947         struct buffer_head *bh;
948         journal_t *journal = journal_init_common();
949         char *p;
950         int err;
951         int n;
952         unsigned long long blocknr;
953
954         if (!journal)
955                 return NULL;
956
957         journal->j_dev = journal->j_fs_dev = inode->i_sb->s_bdev;
958         journal->j_inode = inode;
959         bdevname(journal->j_dev, journal->j_devname);
960         p = journal->j_devname;
961         while ((p = strchr(p, '/')))
962                 *p = '!';
963         p = journal->j_devname + strlen(journal->j_devname);
964         sprintf(p, "-%lu", journal->j_inode->i_ino);
965         jbd_debug(1,
966                   "journal %p: inode %s/%ld, size %Ld, bits %d, blksize %ld\n",
967                   journal, inode->i_sb->s_id, inode->i_ino,
968                   (long long) inode->i_size,
969                   inode->i_sb->s_blocksize_bits, inode->i_sb->s_blocksize);
970
971         journal->j_maxlen = inode->i_size >> inode->i_sb->s_blocksize_bits;
972         journal->j_blocksize = inode->i_sb->s_blocksize;
973         jbd2_stats_proc_init(journal);
974
975         /* journal descriptor can store up to n blocks -bzzz */
976         n = journal->j_blocksize / sizeof(journal_block_tag_t);
977         journal->j_wbufsize = n;
978         journal->j_wbuf = kmalloc(n * sizeof(struct buffer_head*), GFP_KERNEL);
979         if (!journal->j_wbuf) {
980                 printk(KERN_ERR "%s: Cant allocate bhs for commit thread\n",
981                         __func__);
982                 goto out_err;
983         }
984
985         err = jbd2_journal_bmap(journal, 0, &blocknr);
986         /* If that failed, give up */
987         if (err) {
988                 printk(KERN_ERR "%s: Cannnot locate journal superblock\n",
989                        __func__);
990                 goto out_err;
991         }
992
993         bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize);
994         if (!bh) {
995                 printk(KERN_ERR
996                        "%s: Cannot get buffer for journal superblock\n",
997                        __func__);
998                 goto out_err;
999         }
1000         journal->j_sb_buffer = bh;
1001         journal->j_superblock = (journal_superblock_t *)bh->b_data;
1002
1003         return journal;
1004 out_err:
1005         kfree(journal->j_wbuf);
1006         jbd2_stats_proc_exit(journal);
1007         kfree(journal);
1008         return NULL;
1009 }
1010
1011 /*
1012  * If the journal init or create aborts, we need to mark the journal
1013  * superblock as being NULL to prevent the journal destroy from writing
1014  * back a bogus superblock.
1015  */
1016 static void journal_fail_superblock (journal_t *journal)
1017 {
1018         struct buffer_head *bh = journal->j_sb_buffer;
1019         brelse(bh);
1020         journal->j_sb_buffer = NULL;
1021 }
1022
1023 /*
1024  * Given a journal_t structure, initialise the various fields for
1025  * startup of a new journaling session.  We use this both when creating
1026  * a journal, and after recovering an old journal to reset it for
1027  * subsequent use.
1028  */
1029
1030 static int journal_reset(journal_t *journal)
1031 {
1032         journal_superblock_t *sb = journal->j_superblock;
1033         unsigned long long first, last;
1034
1035         first = be32_to_cpu(sb->s_first);
1036         last = be32_to_cpu(sb->s_maxlen);
1037         if (first + JBD2_MIN_JOURNAL_BLOCKS > last + 1) {
1038                 printk(KERN_ERR "JBD: Journal too short (blocks %llu-%llu).\n",
1039                        first, last);
1040                 journal_fail_superblock(journal);
1041                 return -EINVAL;
1042         }
1043
1044         journal->j_first = first;
1045         journal->j_last = last;
1046
1047         journal->j_head = first;
1048         journal->j_tail = first;
1049         journal->j_free = last - first;
1050
1051         journal->j_tail_sequence = journal->j_transaction_sequence;
1052         journal->j_commit_sequence = journal->j_transaction_sequence - 1;
1053         journal->j_commit_request = journal->j_commit_sequence;
1054
1055         journal->j_max_transaction_buffers = journal->j_maxlen / 4;
1056
1057         /* Add the dynamic fields and write it to disk. */
1058         jbd2_journal_update_superblock(journal, 1);
1059         return jbd2_journal_start_thread(journal);
1060 }
1061
1062 /**
1063  * void jbd2_journal_update_superblock() - Update journal sb on disk.
1064  * @journal: The journal to update.
1065  * @wait: Set to '0' if you don't want to wait for IO completion.
1066  *
1067  * Update a journal's dynamic superblock fields and write it to disk,
1068  * optionally waiting for the IO to complete.
1069  */
1070 void jbd2_journal_update_superblock(journal_t *journal, int wait)
1071 {
1072         journal_superblock_t *sb = journal->j_superblock;
1073         struct buffer_head *bh = journal->j_sb_buffer;
1074
1075         /*
1076          * As a special case, if the on-disk copy is already marked as needing
1077          * no recovery (s_start == 0) and there are no outstanding transactions
1078          * in the filesystem, then we can safely defer the superblock update
1079          * until the next commit by setting JBD2_FLUSHED.  This avoids
1080          * attempting a write to a potential-readonly device.
1081          */
1082         if (sb->s_start == 0 && journal->j_tail_sequence ==
1083                                 journal->j_transaction_sequence) {
1084                 jbd_debug(1,"JBD: Skipping superblock update on recovered sb "
1085                         "(start %ld, seq %d, errno %d)\n",
1086                         journal->j_tail, journal->j_tail_sequence,
1087                         journal->j_errno);
1088                 goto out;
1089         }
1090
1091         if (buffer_write_io_error(bh)) {
1092                 /*
1093                  * Oh, dear.  A previous attempt to write the journal
1094                  * superblock failed.  This could happen because the
1095                  * USB device was yanked out.  Or it could happen to
1096                  * be a transient write error and maybe the block will
1097                  * be remapped.  Nothing we can do but to retry the
1098                  * write and hope for the best.
1099                  */
1100                 printk(KERN_ERR "JBD2: previous I/O error detected "
1101                        "for journal superblock update for %s.\n",
1102                        journal->j_devname);
1103                 clear_buffer_write_io_error(bh);
1104                 set_buffer_uptodate(bh);
1105         }
1106
1107         read_lock(&journal->j_state_lock);
1108         jbd_debug(1,"JBD: updating superblock (start %ld, seq %d, errno %d)\n",
1109                   journal->j_tail, journal->j_tail_sequence, journal->j_errno);
1110
1111         sb->s_sequence = cpu_to_be32(journal->j_tail_sequence);
1112         sb->s_start    = cpu_to_be32(journal->j_tail);
1113         sb->s_errno    = cpu_to_be32(journal->j_errno);
1114         read_unlock(&journal->j_state_lock);
1115
1116         BUFFER_TRACE(bh, "marking dirty");
1117         mark_buffer_dirty(bh);
1118         if (wait) {
1119                 sync_dirty_buffer(bh);
1120                 if (buffer_write_io_error(bh)) {
1121                         printk(KERN_ERR "JBD2: I/O error detected "
1122                                "when updating journal superblock for %s.\n",
1123                                journal->j_devname);
1124                         clear_buffer_write_io_error(bh);
1125                         set_buffer_uptodate(bh);
1126                 }
1127         } else
1128                 write_dirty_buffer(bh, WRITE);
1129
1130 out:
1131         /* If we have just flushed the log (by marking s_start==0), then
1132          * any future commit will have to be careful to update the
1133          * superblock again to re-record the true start of the log. */
1134
1135         write_lock(&journal->j_state_lock);
1136         if (sb->s_start)
1137                 journal->j_flags &= ~JBD2_FLUSHED;
1138         else
1139                 journal->j_flags |= JBD2_FLUSHED;
1140         write_unlock(&journal->j_state_lock);
1141 }
1142
1143 /*
1144  * Read the superblock for a given journal, performing initial
1145  * validation of the format.
1146  */
1147
1148 static int journal_get_superblock(journal_t *journal)
1149 {
1150         struct buffer_head *bh;
1151         journal_superblock_t *sb;
1152         int err = -EIO;
1153
1154         bh = journal->j_sb_buffer;
1155
1156         J_ASSERT(bh != NULL);
1157         if (!buffer_uptodate(bh)) {
1158                 ll_rw_block(READ, 1, &bh);
1159                 wait_on_buffer(bh);
1160                 if (!buffer_uptodate(bh)) {
1161                         printk (KERN_ERR
1162                                 "JBD: IO error reading journal superblock\n");
1163                         goto out;
1164                 }
1165         }
1166
1167         sb = journal->j_superblock;
1168
1169         err = -EINVAL;
1170
1171         if (sb->s_header.h_magic != cpu_to_be32(JBD2_MAGIC_NUMBER) ||
1172             sb->s_blocksize != cpu_to_be32(journal->j_blocksize)) {
1173                 printk(KERN_WARNING "JBD: no valid journal superblock found\n");
1174                 goto out;
1175         }
1176
1177         switch(be32_to_cpu(sb->s_header.h_blocktype)) {
1178         case JBD2_SUPERBLOCK_V1:
1179                 journal->j_format_version = 1;
1180                 break;
1181         case JBD2_SUPERBLOCK_V2:
1182                 journal->j_format_version = 2;
1183                 break;
1184         default:
1185                 printk(KERN_WARNING "JBD: unrecognised superblock format ID\n");
1186                 goto out;
1187         }
1188
1189         if (be32_to_cpu(sb->s_maxlen) < journal->j_maxlen)
1190                 journal->j_maxlen = be32_to_cpu(sb->s_maxlen);
1191         else if (be32_to_cpu(sb->s_maxlen) > journal->j_maxlen) {
1192                 printk (KERN_WARNING "JBD: journal file too short\n");
1193                 goto out;
1194         }
1195
1196         return 0;
1197
1198 out:
1199         journal_fail_superblock(journal);
1200         return err;
1201 }
1202
1203 /*
1204  * Load the on-disk journal superblock and read the key fields into the
1205  * journal_t.
1206  */
1207
1208 static int load_superblock(journal_t *journal)
1209 {
1210         int err;
1211         journal_superblock_t *sb;
1212
1213         err = journal_get_superblock(journal);
1214         if (err)
1215                 return err;
1216
1217         sb = journal->j_superblock;
1218
1219         journal->j_tail_sequence = be32_to_cpu(sb->s_sequence);
1220         journal->j_tail = be32_to_cpu(sb->s_start);
1221         journal->j_first = be32_to_cpu(sb->s_first);
1222         journal->j_last = be32_to_cpu(sb->s_maxlen);
1223         journal->j_errno = be32_to_cpu(sb->s_errno);
1224
1225         return 0;
1226 }
1227
1228
1229 /**
1230  * int jbd2_journal_load() - Read journal from disk.
1231  * @journal: Journal to act on.
1232  *
1233  * Given a journal_t structure which tells us which disk blocks contain
1234  * a journal, read the journal from disk to initialise the in-memory
1235  * structures.
1236  */
1237 int jbd2_journal_load(journal_t *journal)
1238 {
1239         int err;
1240         journal_superblock_t *sb;
1241
1242         err = load_superblock(journal);
1243         if (err)
1244                 return err;
1245
1246         sb = journal->j_superblock;
1247         /* If this is a V2 superblock, then we have to check the
1248          * features flags on it. */
1249
1250         if (journal->j_format_version >= 2) {
1251                 if ((sb->s_feature_ro_compat &
1252                      ~cpu_to_be32(JBD2_KNOWN_ROCOMPAT_FEATURES)) ||
1253                     (sb->s_feature_incompat &
1254                      ~cpu_to_be32(JBD2_KNOWN_INCOMPAT_FEATURES))) {
1255                         printk (KERN_WARNING
1256                                 "JBD: Unrecognised features on journal\n");
1257                         return -EINVAL;
1258                 }
1259         }
1260
1261         /*
1262          * Create a slab for this blocksize
1263          */
1264         err = jbd2_journal_create_slab(be32_to_cpu(sb->s_blocksize));
1265         if (err)
1266                 return err;
1267
1268         /* Let the recovery code check whether it needs to recover any
1269          * data from the journal. */
1270         if (jbd2_journal_recover(journal))
1271                 goto recovery_error;
1272
1273         if (journal->j_failed_commit) {
1274                 printk(KERN_ERR "JBD2: journal transaction %u on %s "
1275                        "is corrupt.\n", journal->j_failed_commit,
1276                        journal->j_devname);
1277                 return -EIO;
1278         }
1279
1280         /* OK, we've finished with the dynamic journal bits:
1281          * reinitialise the dynamic contents of the superblock in memory
1282          * and reset them on disk. */
1283         if (journal_reset(journal))
1284                 goto recovery_error;
1285
1286         journal->j_flags &= ~JBD2_ABORT;
1287         journal->j_flags |= JBD2_LOADED;
1288         return 0;
1289
1290 recovery_error:
1291         printk (KERN_WARNING "JBD: recovery failed\n");
1292         return -EIO;
1293 }
1294
1295 /**
1296  * void jbd2_journal_destroy() - Release a journal_t structure.
1297  * @journal: Journal to act on.
1298  *
1299  * Release a journal_t structure once it is no longer in use by the
1300  * journaled object.
1301  * Return <0 if we couldn't clean up the journal.
1302  */
1303 int jbd2_journal_destroy(journal_t *journal)
1304 {
1305         int err = 0;
1306
1307         /* Wait for the commit thread to wake up and die. */
1308         journal_kill_thread(journal);
1309
1310         /* Force a final log commit */
1311         if (journal->j_running_transaction)
1312                 jbd2_journal_commit_transaction(journal);
1313
1314         /* Force any old transactions to disk */
1315
1316         /* Totally anal locking here... */
1317         spin_lock(&journal->j_list_lock);
1318         while (journal->j_checkpoint_transactions != NULL) {
1319                 spin_unlock(&journal->j_list_lock);
1320                 mutex_lock(&journal->j_checkpoint_mutex);
1321                 jbd2_log_do_checkpoint(journal);
1322                 mutex_unlock(&journal->j_checkpoint_mutex);
1323                 spin_lock(&journal->j_list_lock);
1324         }
1325
1326         J_ASSERT(journal->j_running_transaction == NULL);
1327         J_ASSERT(journal->j_committing_transaction == NULL);
1328         J_ASSERT(journal->j_checkpoint_transactions == NULL);
1329         spin_unlock(&journal->j_list_lock);
1330
1331         if (journal->j_sb_buffer) {
1332                 if (!is_journal_aborted(journal)) {
1333                         /* We can now mark the journal as empty. */
1334                         journal->j_tail = 0;
1335                         journal->j_tail_sequence =
1336                                 ++journal->j_transaction_sequence;
1337                         jbd2_journal_update_superblock(journal, 1);
1338                 } else {
1339                         err = -EIO;
1340                 }
1341                 brelse(journal->j_sb_buffer);
1342         }
1343
1344         if (journal->j_proc_entry)
1345                 jbd2_stats_proc_exit(journal);
1346         if (journal->j_inode)
1347                 iput(journal->j_inode);
1348         if (journal->j_revoke)
1349                 jbd2_journal_destroy_revoke(journal);
1350         kfree(journal->j_wbuf);
1351         kfree(journal);
1352
1353         return err;
1354 }
1355
1356
1357 /**
1358  *int jbd2_journal_check_used_features () - Check if features specified are used.
1359  * @journal: Journal to check.
1360  * @compat: bitmask of compatible features
1361  * @ro: bitmask of features that force read-only mount
1362  * @incompat: bitmask of incompatible features
1363  *
1364  * Check whether the journal uses all of a given set of
1365  * features.  Return true (non-zero) if it does.
1366  **/
1367
1368 int jbd2_journal_check_used_features (journal_t *journal, unsigned long compat,
1369                                  unsigned long ro, unsigned long incompat)
1370 {
1371         journal_superblock_t *sb;
1372
1373         if (!compat && !ro && !incompat)
1374                 return 1;
1375         /* Load journal superblock if it is not loaded yet. */
1376         if (journal->j_format_version == 0 &&
1377             journal_get_superblock(journal) != 0)
1378                 return 0;
1379         if (journal->j_format_version == 1)
1380                 return 0;
1381
1382         sb = journal->j_superblock;
1383
1384         if (((be32_to_cpu(sb->s_feature_compat) & compat) == compat) &&
1385             ((be32_to_cpu(sb->s_feature_ro_compat) & ro) == ro) &&
1386             ((be32_to_cpu(sb->s_feature_incompat) & incompat) == incompat))
1387                 return 1;
1388
1389         return 0;
1390 }
1391
1392 /**
1393  * int jbd2_journal_check_available_features() - Check feature set in journalling layer
1394  * @journal: Journal to check.
1395  * @compat: bitmask of compatible features
1396  * @ro: bitmask of features that force read-only mount
1397  * @incompat: bitmask of incompatible features
1398  *
1399  * Check whether the journaling code supports the use of
1400  * all of a given set of features on this journal.  Return true
1401  * (non-zero) if it can. */
1402
1403 int jbd2_journal_check_available_features (journal_t *journal, unsigned long compat,
1404                                       unsigned long ro, unsigned long incompat)
1405 {
1406         if (!compat && !ro && !incompat)
1407                 return 1;
1408
1409         /* We can support any known requested features iff the
1410          * superblock is in version 2.  Otherwise we fail to support any
1411          * extended sb features. */
1412
1413         if (journal->j_format_version != 2)
1414                 return 0;
1415
1416         if ((compat   & JBD2_KNOWN_COMPAT_FEATURES) == compat &&
1417             (ro       & JBD2_KNOWN_ROCOMPAT_FEATURES) == ro &&
1418             (incompat & JBD2_KNOWN_INCOMPAT_FEATURES) == incompat)
1419                 return 1;
1420
1421         return 0;
1422 }
1423
1424 /**
1425  * int jbd2_journal_set_features () - Mark a given journal feature in the superblock
1426  * @journal: Journal to act on.
1427  * @compat: bitmask of compatible features
1428  * @ro: bitmask of features that force read-only mount
1429  * @incompat: bitmask of incompatible features
1430  *
1431  * Mark a given journal feature as present on the
1432  * superblock.  Returns true if the requested features could be set.
1433  *
1434  */
1435
1436 int jbd2_journal_set_features (journal_t *journal, unsigned long compat,
1437                           unsigned long ro, unsigned long incompat)
1438 {
1439         journal_superblock_t *sb;
1440
1441         if (jbd2_journal_check_used_features(journal, compat, ro, incompat))
1442                 return 1;
1443
1444         if (!jbd2_journal_check_available_features(journal, compat, ro, incompat))
1445                 return 0;
1446
1447         jbd_debug(1, "Setting new features 0x%lx/0x%lx/0x%lx\n",
1448                   compat, ro, incompat);
1449
1450         sb = journal->j_superblock;
1451
1452         sb->s_feature_compat    |= cpu_to_be32(compat);
1453         sb->s_feature_ro_compat |= cpu_to_be32(ro);
1454         sb->s_feature_incompat  |= cpu_to_be32(incompat);
1455
1456         return 1;
1457 }
1458
1459 /*
1460  * jbd2_journal_clear_features () - Clear a given journal feature in the
1461  *                                  superblock
1462  * @journal: Journal to act on.
1463  * @compat: bitmask of compatible features
1464  * @ro: bitmask of features that force read-only mount
1465  * @incompat: bitmask of incompatible features
1466  *
1467  * Clear a given journal feature as present on the
1468  * superblock.
1469  */
1470 void jbd2_journal_clear_features(journal_t *journal, unsigned long compat,
1471                                 unsigned long ro, unsigned long incompat)
1472 {
1473         journal_superblock_t *sb;
1474
1475         jbd_debug(1, "Clear features 0x%lx/0x%lx/0x%lx\n",
1476                   compat, ro, incompat);
1477
1478         sb = journal->j_superblock;
1479
1480         sb->s_feature_compat    &= ~cpu_to_be32(compat);
1481         sb->s_feature_ro_compat &= ~cpu_to_be32(ro);
1482         sb->s_feature_incompat  &= ~cpu_to_be32(incompat);
1483 }
1484 EXPORT_SYMBOL(jbd2_journal_clear_features);
1485
1486 /**
1487  * int jbd2_journal_update_format () - Update on-disk journal structure.
1488  * @journal: Journal to act on.
1489  *
1490  * Given an initialised but unloaded journal struct, poke about in the
1491  * on-disk structure to update it to the most recent supported version.
1492  */
1493 int jbd2_journal_update_format (journal_t *journal)
1494 {
1495         journal_superblock_t *sb;
1496         int err;
1497
1498         err = journal_get_superblock(journal);
1499         if (err)
1500                 return err;
1501
1502         sb = journal->j_superblock;
1503
1504         switch (be32_to_cpu(sb->s_header.h_blocktype)) {
1505         case JBD2_SUPERBLOCK_V2:
1506                 return 0;
1507         case JBD2_SUPERBLOCK_V1:
1508                 return journal_convert_superblock_v1(journal, sb);
1509         default:
1510                 break;
1511         }
1512         return -EINVAL;
1513 }
1514
1515 static int journal_convert_superblock_v1(journal_t *journal,
1516                                          journal_superblock_t *sb)
1517 {
1518         int offset, blocksize;
1519         struct buffer_head *bh;
1520
1521         printk(KERN_WARNING
1522                 "JBD: Converting superblock from version 1 to 2.\n");
1523
1524         /* Pre-initialise new fields to zero */
1525         offset = ((char *) &(sb->s_feature_compat)) - ((char *) sb);
1526         blocksize = be32_to_cpu(sb->s_blocksize);
1527         memset(&sb->s_feature_compat, 0, blocksize-offset);
1528
1529         sb->s_nr_users = cpu_to_be32(1);
1530         sb->s_header.h_blocktype = cpu_to_be32(JBD2_SUPERBLOCK_V2);
1531         journal->j_format_version = 2;
1532
1533         bh = journal->j_sb_buffer;
1534         BUFFER_TRACE(bh, "marking dirty");
1535         mark_buffer_dirty(bh);
1536         sync_dirty_buffer(bh);
1537         return 0;
1538 }
1539
1540
1541 /**
1542  * int jbd2_journal_flush () - Flush journal
1543  * @journal: Journal to act on.
1544  *
1545  * Flush all data for a given journal to disk and empty the journal.
1546  * Filesystems can use this when remounting readonly to ensure that
1547  * recovery does not need to happen on remount.
1548  */
1549
1550 int jbd2_journal_flush(journal_t *journal)
1551 {
1552         int err = 0;
1553         transaction_t *transaction = NULL;
1554         unsigned long old_tail;
1555
1556         write_lock(&journal->j_state_lock);
1557
1558         /* Force everything buffered to the log... */
1559         if (journal->j_running_transaction) {
1560                 transaction = journal->j_running_transaction;
1561                 __jbd2_log_start_commit(journal, transaction->t_tid);
1562         } else if (journal->j_committing_transaction)
1563                 transaction = journal->j_committing_transaction;
1564
1565         /* Wait for the log commit to complete... */
1566         if (transaction) {
1567                 tid_t tid = transaction->t_tid;
1568
1569                 write_unlock(&journal->j_state_lock);
1570                 jbd2_log_wait_commit(journal, tid);
1571         } else {
1572                 write_unlock(&journal->j_state_lock);
1573         }
1574
1575         /* ...and flush everything in the log out to disk. */
1576         spin_lock(&journal->j_list_lock);
1577         while (!err && journal->j_checkpoint_transactions != NULL) {
1578                 spin_unlock(&journal->j_list_lock);
1579                 mutex_lock(&journal->j_checkpoint_mutex);
1580                 err = jbd2_log_do_checkpoint(journal);
1581                 mutex_unlock(&journal->j_checkpoint_mutex);
1582                 spin_lock(&journal->j_list_lock);
1583         }
1584         spin_unlock(&journal->j_list_lock);
1585
1586         if (is_journal_aborted(journal))
1587                 return -EIO;
1588
1589         jbd2_cleanup_journal_tail(journal);
1590
1591         /* Finally, mark the journal as really needing no recovery.
1592          * This sets s_start==0 in the underlying superblock, which is
1593          * the magic code for a fully-recovered superblock.  Any future
1594          * commits of data to the journal will restore the current
1595          * s_start value. */
1596         write_lock(&journal->j_state_lock);
1597         old_tail = journal->j_tail;
1598         journal->j_tail = 0;
1599         write_unlock(&journal->j_state_lock);
1600         jbd2_journal_update_superblock(journal, 1);
1601         write_lock(&journal->j_state_lock);
1602         journal->j_tail = old_tail;
1603
1604         J_ASSERT(!journal->j_running_transaction);
1605         J_ASSERT(!journal->j_committing_transaction);
1606         J_ASSERT(!journal->j_checkpoint_transactions);
1607         J_ASSERT(journal->j_head == journal->j_tail);
1608         J_ASSERT(journal->j_tail_sequence == journal->j_transaction_sequence);
1609         write_unlock(&journal->j_state_lock);
1610         return 0;
1611 }
1612
1613 /**
1614  * int jbd2_journal_wipe() - Wipe journal contents
1615  * @journal: Journal to act on.
1616  * @write: flag (see below)
1617  *
1618  * Wipe out all of the contents of a journal, safely.  This will produce
1619  * a warning if the journal contains any valid recovery information.
1620  * Must be called between journal_init_*() and jbd2_journal_load().
1621  *
1622  * If 'write' is non-zero, then we wipe out the journal on disk; otherwise
1623  * we merely suppress recovery.
1624  */
1625
1626 int jbd2_journal_wipe(journal_t *journal, int write)
1627 {
1628         int err = 0;
1629
1630         J_ASSERT (!(journal->j_flags & JBD2_LOADED));
1631
1632         err = load_superblock(journal);
1633         if (err)
1634                 return err;
1635
1636         if (!journal->j_tail)
1637                 goto no_recovery;
1638
1639         printk (KERN_WARNING "JBD: %s recovery information on journal\n",
1640                 write ? "Clearing" : "Ignoring");
1641
1642         err = jbd2_journal_skip_recovery(journal);
1643         if (write)
1644                 jbd2_journal_update_superblock(journal, 1);
1645
1646  no_recovery:
1647         return err;
1648 }
1649
1650 /*
1651  * Journal abort has very specific semantics, which we describe
1652  * for journal abort.
1653  *
1654  * Two internal functions, which provide abort to the jbd layer
1655  * itself are here.
1656  */
1657
1658 /*
1659  * Quick version for internal journal use (doesn't lock the journal).
1660  * Aborts hard --- we mark the abort as occurred, but do _nothing_ else,
1661  * and don't attempt to make any other journal updates.
1662  */
1663 void __jbd2_journal_abort_hard(journal_t *journal)
1664 {
1665         transaction_t *transaction;
1666
1667         if (journal->j_flags & JBD2_ABORT)
1668                 return;
1669
1670         printk(KERN_ERR "Aborting journal on device %s.\n",
1671                journal->j_devname);
1672
1673         write_lock(&journal->j_state_lock);
1674         journal->j_flags |= JBD2_ABORT;
1675         transaction = journal->j_running_transaction;
1676         if (transaction)
1677                 __jbd2_log_start_commit(journal, transaction->t_tid);
1678         write_unlock(&journal->j_state_lock);
1679 }
1680
1681 /* Soft abort: record the abort error status in the journal superblock,
1682  * but don't do any other IO. */
1683 static void __journal_abort_soft (journal_t *journal, int errno)
1684 {
1685         if (journal->j_flags & JBD2_ABORT)
1686                 return;
1687
1688         if (!journal->j_errno)
1689                 journal->j_errno = errno;
1690
1691         __jbd2_journal_abort_hard(journal);
1692
1693         if (errno)
1694                 jbd2_journal_update_superblock(journal, 1);
1695 }
1696
1697 /**
1698  * void jbd2_journal_abort () - Shutdown the journal immediately.
1699  * @journal: the journal to shutdown.
1700  * @errno:   an error number to record in the journal indicating
1701  *           the reason for the shutdown.
1702  *
1703  * Perform a complete, immediate shutdown of the ENTIRE
1704  * journal (not of a single transaction).  This operation cannot be
1705  * undone without closing and reopening the journal.
1706  *
1707  * The jbd2_journal_abort function is intended to support higher level error
1708  * recovery mechanisms such as the ext2/ext3 remount-readonly error
1709  * mode.
1710  *
1711  * Journal abort has very specific semantics.  Any existing dirty,
1712  * unjournaled buffers in the main filesystem will still be written to
1713  * disk by bdflush, but the journaling mechanism will be suspended
1714  * immediately and no further transaction commits will be honoured.
1715  *
1716  * Any dirty, journaled buffers will be written back to disk without
1717  * hitting the journal.  Atomicity cannot be guaranteed on an aborted
1718  * filesystem, but we _do_ attempt to leave as much data as possible
1719  * behind for fsck to use for cleanup.
1720  *
1721  * Any attempt to get a new transaction handle on a journal which is in
1722  * ABORT state will just result in an -EROFS error return.  A
1723  * jbd2_journal_stop on an existing handle will return -EIO if we have
1724  * entered abort state during the update.
1725  *
1726  * Recursive transactions are not disturbed by journal abort until the
1727  * final jbd2_journal_stop, which will receive the -EIO error.
1728  *
1729  * Finally, the jbd2_journal_abort call allows the caller to supply an errno
1730  * which will be recorded (if possible) in the journal superblock.  This
1731  * allows a client to record failure conditions in the middle of a
1732  * transaction without having to complete the transaction to record the
1733  * failure to disk.  ext3_error, for example, now uses this
1734  * functionality.
1735  *
1736  * Errors which originate from within the journaling layer will NOT
1737  * supply an errno; a null errno implies that absolutely no further
1738  * writes are done to the journal (unless there are any already in
1739  * progress).
1740  *
1741  */
1742
1743 void jbd2_journal_abort(journal_t *journal, int errno)
1744 {
1745         __journal_abort_soft(journal, errno);
1746 }
1747
1748 /**
1749  * int jbd2_journal_errno () - returns the journal's error state.
1750  * @journal: journal to examine.
1751  *
1752  * This is the errno number set with jbd2_journal_abort(), the last
1753  * time the journal was mounted - if the journal was stopped
1754  * without calling abort this will be 0.
1755  *
1756  * If the journal has been aborted on this mount time -EROFS will
1757  * be returned.
1758  */
1759 int jbd2_journal_errno(journal_t *journal)
1760 {
1761         int err;
1762
1763         read_lock(&journal->j_state_lock);
1764         if (journal->j_flags & JBD2_ABORT)
1765                 err = -EROFS;
1766         else
1767                 err = journal->j_errno;
1768         read_unlock(&journal->j_state_lock);
1769         return err;
1770 }
1771
1772 /**
1773  * int jbd2_journal_clear_err () - clears the journal's error state
1774  * @journal: journal to act on.
1775  *
1776  * An error must be cleared or acked to take a FS out of readonly
1777  * mode.
1778  */
1779 int jbd2_journal_clear_err(journal_t *journal)
1780 {
1781         int err = 0;
1782
1783         write_lock(&journal->j_state_lock);
1784         if (journal->j_flags & JBD2_ABORT)
1785                 err = -EROFS;
1786         else
1787                 journal->j_errno = 0;
1788         write_unlock(&journal->j_state_lock);
1789         return err;
1790 }
1791
1792 /**
1793  * void jbd2_journal_ack_err() - Ack journal err.
1794  * @journal: journal to act on.
1795  *
1796  * An error must be cleared or acked to take a FS out of readonly
1797  * mode.
1798  */
1799 void jbd2_journal_ack_err(journal_t *journal)
1800 {
1801         write_lock(&journal->j_state_lock);
1802         if (journal->j_errno)
1803                 journal->j_flags |= JBD2_ACK_ERR;
1804         write_unlock(&journal->j_state_lock);
1805 }
1806
1807 int jbd2_journal_blocks_per_page(struct inode *inode)
1808 {
1809         return 1 << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
1810 }
1811
1812 /*
1813  * helper functions to deal with 32 or 64bit block numbers.
1814  */
1815 size_t journal_tag_bytes(journal_t *journal)
1816 {
1817         if (JBD2_HAS_INCOMPAT_FEATURE(journal, JBD2_FEATURE_INCOMPAT_64BIT))
1818                 return JBD2_TAG_SIZE64;
1819         else
1820                 return JBD2_TAG_SIZE32;
1821 }
1822
1823 /*
1824  * JBD memory management
1825  *
1826  * These functions are used to allocate block-sized chunks of memory
1827  * used for making copies of buffer_head data.  Very often it will be
1828  * page-sized chunks of data, but sometimes it will be in
1829  * sub-page-size chunks.  (For example, 16k pages on Power systems
1830  * with a 4k block file system.)  For blocks smaller than a page, we
1831  * use a SLAB allocator.  There are slab caches for each block size,
1832  * which are allocated at mount time, if necessary, and we only free
1833  * (all of) the slab caches when/if the jbd2 module is unloaded.  For
1834  * this reason we don't need to a mutex to protect access to
1835  * jbd2_slab[] allocating or releasing memory; only in
1836  * jbd2_journal_create_slab().
1837  */
1838 #define JBD2_MAX_SLABS 8
1839 static struct kmem_cache *jbd2_slab[JBD2_MAX_SLABS];
1840
1841 static const char *jbd2_slab_names[JBD2_MAX_SLABS] = {
1842         "jbd2_1k", "jbd2_2k", "jbd2_4k", "jbd2_8k",
1843         "jbd2_16k", "jbd2_32k", "jbd2_64k", "jbd2_128k"
1844 };
1845
1846
1847 static void jbd2_journal_destroy_slabs(void)
1848 {
1849         int i;
1850
1851         for (i = 0; i < JBD2_MAX_SLABS; i++) {
1852                 if (jbd2_slab[i])
1853                         kmem_cache_destroy(jbd2_slab[i]);
1854                 jbd2_slab[i] = NULL;
1855         }
1856 }
1857
1858 static int jbd2_journal_create_slab(size_t size)
1859 {
1860         static DEFINE_MUTEX(jbd2_slab_create_mutex);
1861         int i = order_base_2(size) - 10;
1862         size_t slab_size;
1863
1864         if (size == PAGE_SIZE)
1865                 return 0;
1866
1867         if (i >= JBD2_MAX_SLABS)
1868                 return -EINVAL;
1869
1870         if (unlikely(i < 0))
1871                 i = 0;
1872         mutex_lock(&jbd2_slab_create_mutex);
1873         if (jbd2_slab[i]) {
1874                 mutex_unlock(&jbd2_slab_create_mutex);
1875                 return 0;       /* Already created */
1876         }
1877
1878         slab_size = 1 << (i+10);
1879         jbd2_slab[i] = kmem_cache_create(jbd2_slab_names[i], slab_size,
1880                                          slab_size, 0, NULL);
1881         mutex_unlock(&jbd2_slab_create_mutex);
1882         if (!jbd2_slab[i]) {
1883                 printk(KERN_EMERG "JBD2: no memory for jbd2_slab cache\n");
1884                 return -ENOMEM;
1885         }
1886         return 0;
1887 }
1888
1889 static struct kmem_cache *get_slab(size_t size)
1890 {
1891         int i = order_base_2(size) - 10;
1892
1893         BUG_ON(i >= JBD2_MAX_SLABS);
1894         if (unlikely(i < 0))
1895                 i = 0;
1896         BUG_ON(jbd2_slab[i] == NULL);
1897         return jbd2_slab[i];
1898 }
1899
1900 void *jbd2_alloc(size_t size, gfp_t flags)
1901 {
1902         void *ptr;
1903
1904         BUG_ON(size & (size-1)); /* Must be a power of 2 */
1905
1906         flags |= __GFP_REPEAT;
1907         if (size == PAGE_SIZE)
1908                 ptr = (void *)__get_free_pages(flags, 0);
1909         else if (size > PAGE_SIZE) {
1910                 int order = get_order(size);
1911
1912                 if (order < 3)
1913                         ptr = (void *)__get_free_pages(flags, order);
1914                 else
1915                         ptr = vmalloc(size);
1916         } else
1917                 ptr = kmem_cache_alloc(get_slab(size), flags);
1918
1919         /* Check alignment; SLUB has gotten this wrong in the past,
1920          * and this can lead to user data corruption! */
1921         BUG_ON(((unsigned long) ptr) & (size-1));
1922
1923         return ptr;
1924 }
1925
1926 void jbd2_free(void *ptr, size_t size)
1927 {
1928         if (size == PAGE_SIZE) {
1929                 free_pages((unsigned long)ptr, 0);
1930                 return;
1931         }
1932         if (size > PAGE_SIZE) {
1933                 int order = get_order(size);
1934
1935                 if (order < 3)
1936                         free_pages((unsigned long)ptr, order);
1937                 else
1938                         vfree(ptr);
1939                 return;
1940         }
1941         kmem_cache_free(get_slab(size), ptr);
1942 };
1943
1944 /*
1945  * Journal_head storage management
1946  */
1947 static struct kmem_cache *jbd2_journal_head_cache;
1948 #ifdef CONFIG_JBD2_DEBUG
1949 static atomic_t nr_journal_heads = ATOMIC_INIT(0);
1950 #endif
1951
1952 static int journal_init_jbd2_journal_head_cache(void)
1953 {
1954         int retval;
1955
1956         J_ASSERT(jbd2_journal_head_cache == NULL);
1957         jbd2_journal_head_cache = kmem_cache_create("jbd2_journal_head",
1958                                 sizeof(struct journal_head),
1959                                 0,              /* offset */
1960                                 SLAB_TEMPORARY, /* flags */
1961                                 NULL);          /* ctor */
1962         retval = 0;
1963         if (!jbd2_journal_head_cache) {
1964                 retval = -ENOMEM;
1965                 printk(KERN_EMERG "JBD: no memory for journal_head cache\n");
1966         }
1967         return retval;
1968 }
1969
1970 static void jbd2_journal_destroy_jbd2_journal_head_cache(void)
1971 {
1972         if (jbd2_journal_head_cache) {
1973                 kmem_cache_destroy(jbd2_journal_head_cache);
1974                 jbd2_journal_head_cache = NULL;
1975         }
1976 }
1977
1978 /*
1979  * journal_head splicing and dicing
1980  */
1981 static struct journal_head *journal_alloc_journal_head(void)
1982 {
1983         struct journal_head *ret;
1984
1985 #ifdef CONFIG_JBD2_DEBUG
1986         atomic_inc(&nr_journal_heads);
1987 #endif
1988         ret = kmem_cache_alloc(jbd2_journal_head_cache, GFP_NOFS);
1989         if (!ret) {
1990                 jbd_debug(1, "out of memory for journal_head\n");
1991                 pr_notice_ratelimited("ENOMEM in %s, retrying.\n", __func__);
1992                 while (!ret) {
1993                         yield();
1994                         ret = kmem_cache_alloc(jbd2_journal_head_cache, GFP_NOFS);
1995                 }
1996         }
1997         return ret;
1998 }
1999
2000 static void journal_free_journal_head(struct journal_head *jh)
2001 {
2002 #ifdef CONFIG_JBD2_DEBUG
2003         atomic_dec(&nr_journal_heads);
2004         memset(jh, JBD2_POISON_FREE, sizeof(*jh));
2005 #endif
2006         kmem_cache_free(jbd2_journal_head_cache, jh);
2007 }
2008
2009 /*
2010  * A journal_head is attached to a buffer_head whenever JBD has an
2011  * interest in the buffer.
2012  *
2013  * Whenever a buffer has an attached journal_head, its ->b_state:BH_JBD bit
2014  * is set.  This bit is tested in core kernel code where we need to take
2015  * JBD-specific actions.  Testing the zeroness of ->b_private is not reliable
2016  * there.
2017  *
2018  * When a buffer has its BH_JBD bit set, its ->b_count is elevated by one.
2019  *
2020  * When a buffer has its BH_JBD bit set it is immune from being released by
2021  * core kernel code, mainly via ->b_count.
2022  *
2023  * A journal_head may be detached from its buffer_head when the journal_head's
2024  * b_transaction, b_cp_transaction and b_next_transaction pointers are NULL.
2025  * Various places in JBD call jbd2_journal_remove_journal_head() to indicate that the
2026  * journal_head can be dropped if needed.
2027  *
2028  * Various places in the kernel want to attach a journal_head to a buffer_head
2029  * _before_ attaching the journal_head to a transaction.  To protect the
2030  * journal_head in this situation, jbd2_journal_add_journal_head elevates the
2031  * journal_head's b_jcount refcount by one.  The caller must call
2032  * jbd2_journal_put_journal_head() to undo this.
2033  *
2034  * So the typical usage would be:
2035  *
2036  *      (Attach a journal_head if needed.  Increments b_jcount)
2037  *      struct journal_head *jh = jbd2_journal_add_journal_head(bh);
2038  *      ...
2039  *      jh->b_transaction = xxx;
2040  *      jbd2_journal_put_journal_head(jh);
2041  *
2042  * Now, the journal_head's b_jcount is zero, but it is safe from being released
2043  * because it has a non-zero b_transaction.
2044  */
2045
2046 /*
2047  * Give a buffer_head a journal_head.
2048  *
2049  * Doesn't need the journal lock.
2050  * May sleep.
2051  */
2052 struct journal_head *jbd2_journal_add_journal_head(struct buffer_head *bh)
2053 {
2054         struct journal_head *jh;
2055         struct journal_head *new_jh = NULL;
2056
2057 repeat:
2058         if (!buffer_jbd(bh)) {
2059                 new_jh = journal_alloc_journal_head();
2060                 memset(new_jh, 0, sizeof(*new_jh));
2061         }
2062
2063         jbd_lock_bh_journal_head(bh);
2064         if (buffer_jbd(bh)) {
2065                 jh = bh2jh(bh);
2066         } else {
2067                 J_ASSERT_BH(bh,
2068                         (atomic_read(&bh->b_count) > 0) ||
2069                         (bh->b_page && bh->b_page->mapping));
2070
2071                 if (!new_jh) {
2072                         jbd_unlock_bh_journal_head(bh);
2073                         goto repeat;
2074                 }
2075
2076                 jh = new_jh;
2077                 new_jh = NULL;          /* We consumed it */
2078                 set_buffer_jbd(bh);
2079                 bh->b_private = jh;
2080                 jh->b_bh = bh;
2081                 get_bh(bh);
2082                 BUFFER_TRACE(bh, "added journal_head");
2083         }
2084         jh->b_jcount++;
2085         jbd_unlock_bh_journal_head(bh);
2086         if (new_jh)
2087                 journal_free_journal_head(new_jh);
2088         return bh->b_private;
2089 }
2090
2091 /*
2092  * Grab a ref against this buffer_head's journal_head.  If it ended up not
2093  * having a journal_head, return NULL
2094  */
2095 struct journal_head *jbd2_journal_grab_journal_head(struct buffer_head *bh)
2096 {
2097         struct journal_head *jh = NULL;
2098
2099         jbd_lock_bh_journal_head(bh);
2100         if (buffer_jbd(bh)) {
2101                 jh = bh2jh(bh);
2102                 jh->b_jcount++;
2103         }
2104         jbd_unlock_bh_journal_head(bh);
2105         return jh;
2106 }
2107
2108 static void __journal_remove_journal_head(struct buffer_head *bh)
2109 {
2110         struct journal_head *jh = bh2jh(bh);
2111
2112         J_ASSERT_JH(jh, jh->b_jcount >= 0);
2113
2114         get_bh(bh);
2115         if (jh->b_jcount == 0) {
2116                 if (jh->b_transaction == NULL &&
2117                                 jh->b_next_transaction == NULL &&
2118                                 jh->b_cp_transaction == NULL) {
2119                         J_ASSERT_JH(jh, jh->b_jlist == BJ_None);
2120                         J_ASSERT_BH(bh, buffer_jbd(bh));
2121                         J_ASSERT_BH(bh, jh2bh(jh) == bh);
2122                         BUFFER_TRACE(bh, "remove journal_head");
2123                         if (jh->b_frozen_data) {
2124                                 printk(KERN_WARNING "%s: freeing "
2125                                                 "b_frozen_data\n",
2126                                                 __func__);
2127                                 jbd2_free(jh->b_frozen_data, bh->b_size);
2128                         }
2129                         if (jh->b_committed_data) {
2130                                 printk(KERN_WARNING "%s: freeing "
2131                                                 "b_committed_data\n",
2132                                                 __func__);
2133                                 jbd2_free(jh->b_committed_data, bh->b_size);
2134                         }
2135                         bh->b_private = NULL;
2136                         jh->b_bh = NULL;        /* debug, really */
2137                         clear_buffer_jbd(bh);
2138                         __brelse(bh);
2139                         journal_free_journal_head(jh);
2140                 } else {
2141                         BUFFER_TRACE(bh, "journal_head was locked");
2142                 }
2143         }
2144 }
2145
2146 /*
2147  * jbd2_journal_remove_journal_head(): if the buffer isn't attached to a transaction
2148  * and has a zero b_jcount then remove and release its journal_head.   If we did
2149  * see that the buffer is not used by any transaction we also "logically"
2150  * decrement ->b_count.
2151  *
2152  * We in fact take an additional increment on ->b_count as a convenience,
2153  * because the caller usually wants to do additional things with the bh
2154  * after calling here.
2155  * The caller of jbd2_journal_remove_journal_head() *must* run __brelse(bh) at some
2156  * time.  Once the caller has run __brelse(), the buffer is eligible for
2157  * reaping by try_to_free_buffers().
2158  */
2159 void jbd2_journal_remove_journal_head(struct buffer_head *bh)
2160 {
2161         jbd_lock_bh_journal_head(bh);
2162         __journal_remove_journal_head(bh);
2163         jbd_unlock_bh_journal_head(bh);
2164 }
2165
2166 /*
2167  * Drop a reference on the passed journal_head.  If it fell to zero then try to
2168  * release the journal_head from the buffer_head.
2169  */
2170 void jbd2_journal_put_journal_head(struct journal_head *jh)
2171 {
2172         struct buffer_head *bh = jh2bh(jh);
2173
2174         jbd_lock_bh_journal_head(bh);
2175         J_ASSERT_JH(jh, jh->b_jcount > 0);
2176         --jh->b_jcount;
2177         if (!jh->b_jcount && !jh->b_transaction) {
2178                 __journal_remove_journal_head(bh);
2179                 __brelse(bh);
2180         }
2181         jbd_unlock_bh_journal_head(bh);
2182 }
2183
2184 /*
2185  * Initialize jbd inode head
2186  */
2187 void jbd2_journal_init_jbd_inode(struct jbd2_inode *jinode, struct inode *inode)
2188 {
2189         jinode->i_transaction = NULL;
2190         jinode->i_next_transaction = NULL;
2191         jinode->i_vfs_inode = inode;
2192         jinode->i_flags = 0;
2193         INIT_LIST_HEAD(&jinode->i_list);
2194 }
2195
2196 /*
2197  * Function to be called before we start removing inode from memory (i.e.,
2198  * clear_inode() is a fine place to be called from). It removes inode from
2199  * transaction's lists.
2200  */
2201 void jbd2_journal_release_jbd_inode(journal_t *journal,
2202                                     struct jbd2_inode *jinode)
2203 {
2204         if (!journal)
2205                 return;
2206 restart:
2207         spin_lock(&journal->j_list_lock);
2208         /* Is commit writing out inode - we have to wait */
2209         if (test_bit(__JI_COMMIT_RUNNING, &jinode->i_flags)) {
2210                 wait_queue_head_t *wq;
2211                 DEFINE_WAIT_BIT(wait, &jinode->i_flags, __JI_COMMIT_RUNNING);
2212                 wq = bit_waitqueue(&jinode->i_flags, __JI_COMMIT_RUNNING);
2213                 prepare_to_wait(wq, &wait.wait, TASK_UNINTERRUPTIBLE);
2214                 spin_unlock(&journal->j_list_lock);
2215                 schedule();
2216                 finish_wait(wq, &wait.wait);
2217                 goto restart;
2218         }
2219
2220         if (jinode->i_transaction) {
2221                 list_del(&jinode->i_list);
2222                 jinode->i_transaction = NULL;
2223         }
2224         spin_unlock(&journal->j_list_lock);
2225 }
2226
2227 /*
2228  * debugfs tunables
2229  */
2230 #ifdef CONFIG_JBD2_DEBUG
2231 u8 jbd2_journal_enable_debug __read_mostly;
2232 EXPORT_SYMBOL(jbd2_journal_enable_debug);
2233
2234 #define JBD2_DEBUG_NAME "jbd2-debug"
2235
2236 static struct dentry *jbd2_debugfs_dir;
2237 static struct dentry *jbd2_debug;
2238
2239 static void __init jbd2_create_debugfs_entry(void)
2240 {
2241         jbd2_debugfs_dir = debugfs_create_dir("jbd2", NULL);
2242         if (jbd2_debugfs_dir)
2243                 jbd2_debug = debugfs_create_u8(JBD2_DEBUG_NAME,
2244                                                S_IRUGO | S_IWUSR,
2245                                                jbd2_debugfs_dir,
2246                                                &jbd2_journal_enable_debug);
2247 }
2248
2249 static void __exit jbd2_remove_debugfs_entry(void)
2250 {
2251         debugfs_remove(jbd2_debug);
2252         debugfs_remove(jbd2_debugfs_dir);
2253 }
2254
2255 #else
2256
2257 static void __init jbd2_create_debugfs_entry(void)
2258 {
2259 }
2260
2261 static void __exit jbd2_remove_debugfs_entry(void)
2262 {
2263 }
2264
2265 #endif
2266
2267 #ifdef CONFIG_PROC_FS
2268
2269 #define JBD2_STATS_PROC_NAME "fs/jbd2"
2270
2271 static void __init jbd2_create_jbd_stats_proc_entry(void)
2272 {
2273         proc_jbd2_stats = proc_mkdir(JBD2_STATS_PROC_NAME, NULL);
2274 }
2275
2276 static void __exit jbd2_remove_jbd_stats_proc_entry(void)
2277 {
2278         if (proc_jbd2_stats)
2279                 remove_proc_entry(JBD2_STATS_PROC_NAME, NULL);
2280 }
2281
2282 #else
2283
2284 #define jbd2_create_jbd_stats_proc_entry() do {} while (0)
2285 #define jbd2_remove_jbd_stats_proc_entry() do {} while (0)
2286
2287 #endif
2288
2289 struct kmem_cache *jbd2_handle_cache;
2290
2291 static int __init journal_init_handle_cache(void)
2292 {
2293         jbd2_handle_cache = kmem_cache_create("jbd2_journal_handle",
2294                                 sizeof(handle_t),
2295                                 0,              /* offset */
2296                                 SLAB_TEMPORARY, /* flags */
2297                                 NULL);          /* ctor */
2298         if (jbd2_handle_cache == NULL) {
2299                 printk(KERN_EMERG "JBD: failed to create handle cache\n");
2300                 return -ENOMEM;
2301         }
2302         return 0;
2303 }
2304
2305 static void jbd2_journal_destroy_handle_cache(void)
2306 {
2307         if (jbd2_handle_cache)
2308                 kmem_cache_destroy(jbd2_handle_cache);
2309 }
2310
2311 /*
2312  * Module startup and shutdown
2313  */
2314
2315 static int __init journal_init_caches(void)
2316 {
2317         int ret;
2318
2319         ret = jbd2_journal_init_revoke_caches();
2320         if (ret == 0)
2321                 ret = journal_init_jbd2_journal_head_cache();
2322         if (ret == 0)
2323                 ret = journal_init_handle_cache();
2324         return ret;
2325 }
2326
2327 static void jbd2_journal_destroy_caches(void)
2328 {
2329         jbd2_journal_destroy_revoke_caches();
2330         jbd2_journal_destroy_jbd2_journal_head_cache();
2331         jbd2_journal_destroy_handle_cache();
2332         jbd2_journal_destroy_slabs();
2333 }
2334
2335 static int __init journal_init(void)
2336 {
2337         int ret;
2338
2339         BUILD_BUG_ON(sizeof(struct journal_superblock_s) != 1024);
2340
2341         ret = journal_init_caches();
2342         if (ret == 0) {
2343                 jbd2_create_debugfs_entry();
2344                 jbd2_create_jbd_stats_proc_entry();
2345         } else {
2346                 jbd2_journal_destroy_caches();
2347         }
2348         return ret;
2349 }
2350
2351 static void __exit journal_exit(void)
2352 {
2353 #ifdef CONFIG_JBD2_DEBUG
2354         int n = atomic_read(&nr_journal_heads);
2355         if (n)
2356                 printk(KERN_EMERG "JBD: leaked %d journal_heads!\n", n);
2357 #endif
2358         jbd2_remove_debugfs_entry();
2359         jbd2_remove_jbd_stats_proc_entry();
2360         jbd2_journal_destroy_caches();
2361 }
2362
2363 /* 
2364  * jbd2_dev_to_name is a utility function used by the jbd2 and ext4 
2365  * tracing infrastructure to map a dev_t to a device name.
2366  *
2367  * The caller should use rcu_read_lock() in order to make sure the
2368  * device name stays valid until its done with it.  We use
2369  * rcu_read_lock() as well to make sure we're safe in case the caller
2370  * gets sloppy, and because rcu_read_lock() is cheap and can be safely
2371  * nested.
2372  */
2373 struct devname_cache {
2374         struct rcu_head rcu;
2375         dev_t           device;
2376         char            devname[BDEVNAME_SIZE];
2377 };
2378 #define CACHE_SIZE_BITS 6
2379 static struct devname_cache *devcache[1 << CACHE_SIZE_BITS];
2380 static DEFINE_SPINLOCK(devname_cache_lock);
2381
2382 static void free_devcache(struct rcu_head *rcu)
2383 {
2384         kfree(rcu);
2385 }
2386
2387 const char *jbd2_dev_to_name(dev_t device)
2388 {
2389         int     i = hash_32(device, CACHE_SIZE_BITS);
2390         char    *ret;
2391         struct block_device *bd;
2392         static struct devname_cache *new_dev;
2393
2394         rcu_read_lock();
2395         if (devcache[i] && devcache[i]->device == device) {
2396                 ret = devcache[i]->devname;
2397                 rcu_read_unlock();
2398                 return ret;
2399         }
2400         rcu_read_unlock();
2401
2402         new_dev = kmalloc(sizeof(struct devname_cache), GFP_KERNEL);
2403         if (!new_dev)
2404                 return "NODEV-ALLOCFAILURE"; /* Something non-NULL */
2405         spin_lock(&devname_cache_lock);
2406         if (devcache[i]) {
2407                 if (devcache[i]->device == device) {
2408                         kfree(new_dev);
2409                         ret = devcache[i]->devname;
2410                         spin_unlock(&devname_cache_lock);
2411                         return ret;
2412                 }
2413                 call_rcu(&devcache[i]->rcu, free_devcache);
2414         }
2415         devcache[i] = new_dev;
2416         devcache[i]->device = device;
2417         bd = bdget(device);
2418         if (bd) {
2419                 bdevname(bd, devcache[i]->devname);
2420                 bdput(bd);
2421         } else
2422                 __bdevname(device, devcache[i]->devname);
2423         ret = devcache[i]->devname;
2424         spin_unlock(&devname_cache_lock);
2425         return ret;
2426 }
2427 EXPORT_SYMBOL(jbd2_dev_to_name);
2428
2429 MODULE_LICENSE("GPL");
2430 module_init(journal_init);
2431 module_exit(journal_exit);
2432