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