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