]> git.karo-electronics.de Git - mv-sheeva.git/blob - fs/jbd2/journal.c
Merge branch 'for-linus' of git://oss.sgi.com/xfs/xfs
[mv-sheeva.git] / fs / jbd2 / journal.c
1 /*
2  * linux/fs/jbd2/journal.c
3  *
4  * Written by Stephen C. Tweedie <sct@redhat.com>, 1998
5  *
6  * Copyright 1998 Red Hat corp --- All Rights Reserved
7  *
8  * This file is part of the Linux kernel and is made available under
9  * the terms of the GNU General Public License, version 2, or at your
10  * option, any later version, incorporated herein by reference.
11  *
12  * Generic filesystem journal-writing code; part of the ext2fs
13  * journaling system.
14  *
15  * This file manages journals: areas of disk reserved for logging
16  * transactional updates.  This includes the kernel journaling thread
17  * which is responsible for scheduling updates to the log.
18  *
19  * We do not actually manage the physical storage of the journal in this
20  * file: that is left to a per-journal policy function, which allows us
21  * to store the journal within a filesystem-specified area for ext2
22  * journaling (ext2 can use a reserved inode for storing the log).
23  */
24
25 #include <linux/module.h>
26 #include <linux/time.h>
27 #include <linux/fs.h>
28 #include <linux/jbd2.h>
29 #include <linux/errno.h>
30 #include <linux/slab.h>
31 #include <linux/init.h>
32 #include <linux/mm.h>
33 #include <linux/freezer.h>
34 #include <linux/pagemap.h>
35 #include <linux/kthread.h>
36 #include <linux/poison.h>
37 #include <linux/proc_fs.h>
38 #include <linux/debugfs.h>
39 #include <linux/seq_file.h>
40 #include <linux/math64.h>
41 #include <linux/hash.h>
42 #include <linux/log2.h>
43 #include <linux/vmalloc.h>
44 #include <linux/backing-dev.h>
45 #include <linux/bitops.h>
46 #include <linux/ratelimit.h>
47
48 #define CREATE_TRACE_POINTS
49 #include <trace/events/jbd2.h>
50
51 #include <asm/uaccess.h>
52 #include <asm/page.h>
53 #include <asm/system.h>
54
55 EXPORT_SYMBOL(jbd2_journal_extend);
56 EXPORT_SYMBOL(jbd2_journal_stop);
57 EXPORT_SYMBOL(jbd2_journal_lock_updates);
58 EXPORT_SYMBOL(jbd2_journal_unlock_updates);
59 EXPORT_SYMBOL(jbd2_journal_get_write_access);
60 EXPORT_SYMBOL(jbd2_journal_get_create_access);
61 EXPORT_SYMBOL(jbd2_journal_get_undo_access);
62 EXPORT_SYMBOL(jbd2_journal_set_triggers);
63 EXPORT_SYMBOL(jbd2_journal_dirty_metadata);
64 EXPORT_SYMBOL(jbd2_journal_release_buffer);
65 EXPORT_SYMBOL(jbd2_journal_forget);
66 #if 0
67 EXPORT_SYMBOL(journal_sync_buffer);
68 #endif
69 EXPORT_SYMBOL(jbd2_journal_flush);
70 EXPORT_SYMBOL(jbd2_journal_revoke);
71
72 EXPORT_SYMBOL(jbd2_journal_init_dev);
73 EXPORT_SYMBOL(jbd2_journal_init_inode);
74 EXPORT_SYMBOL(jbd2_journal_check_used_features);
75 EXPORT_SYMBOL(jbd2_journal_check_available_features);
76 EXPORT_SYMBOL(jbd2_journal_set_features);
77 EXPORT_SYMBOL(jbd2_journal_load);
78 EXPORT_SYMBOL(jbd2_journal_destroy);
79 EXPORT_SYMBOL(jbd2_journal_abort);
80 EXPORT_SYMBOL(jbd2_journal_errno);
81 EXPORT_SYMBOL(jbd2_journal_ack_err);
82 EXPORT_SYMBOL(jbd2_journal_clear_err);
83 EXPORT_SYMBOL(jbd2_log_wait_commit);
84 EXPORT_SYMBOL(jbd2_log_start_commit);
85 EXPORT_SYMBOL(jbd2_journal_start_commit);
86 EXPORT_SYMBOL(jbd2_journal_force_commit_nested);
87 EXPORT_SYMBOL(jbd2_journal_wipe);
88 EXPORT_SYMBOL(jbd2_journal_blocks_per_page);
89 EXPORT_SYMBOL(jbd2_journal_invalidatepage);
90 EXPORT_SYMBOL(jbd2_journal_try_to_free_buffers);
91 EXPORT_SYMBOL(jbd2_journal_force_commit);
92 EXPORT_SYMBOL(jbd2_journal_file_inode);
93 EXPORT_SYMBOL(jbd2_journal_init_jbd_inode);
94 EXPORT_SYMBOL(jbd2_journal_release_jbd_inode);
95 EXPORT_SYMBOL(jbd2_journal_begin_ordered_truncate);
96 EXPORT_SYMBOL(jbd2_inode_cache);
97
98 static void __journal_abort_soft (journal_t *journal, int errno);
99 static int jbd2_journal_create_slab(size_t slab_size);
100
101 /*
102  * Helper function used to manage commit timeouts
103  */
104
105 static void commit_timeout(unsigned long __data)
106 {
107         struct task_struct * p = (struct task_struct *) __data;
108
109         wake_up_process(p);
110 }
111
112 /*
113  * kjournald2: The main thread function used to manage a logging device
114  * journal.
115  *
116  * This kernel thread is responsible for two things:
117  *
118  * 1) COMMIT:  Every so often we need to commit the current state of the
119  *    filesystem to disk.  The journal thread is responsible for writing
120  *    all of the metadata buffers to disk.
121  *
122  * 2) CHECKPOINT: We cannot reuse a used section of the log file until all
123  *    of the data in that part of the log has been rewritten elsewhere on
124  *    the disk.  Flushing these old buffers to reclaim space in the log is
125  *    known as checkpointing, and this thread is responsible for that job.
126  */
127
128 static int kjournald2(void *arg)
129 {
130         journal_t *journal = arg;
131         transaction_t *transaction;
132
133         /*
134          * Set up an interval timer which can be used to trigger a commit wakeup
135          * after the commit interval expires
136          */
137         setup_timer(&journal->j_commit_timer, commit_timeout,
138                         (unsigned long)current);
139
140         set_freezable();
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                 try_to_freeze();
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);
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);
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);
389                 memcpy(tmp, mapped_data + new_offset, jh2bh(jh_in)->b_size);
390                 kunmap_atomic(mapped_data);
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);
410                 *((unsigned int *)(mapped_data + new_offset)) = 0;
411                 kunmap_atomic(mapped_data);
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  * Log buffer allocation routines:
667  */
668
669 int jbd2_journal_next_log_block(journal_t *journal, unsigned long long *retp)
670 {
671         unsigned long blocknr;
672
673         write_lock(&journal->j_state_lock);
674         J_ASSERT(journal->j_free > 1);
675
676         blocknr = journal->j_head;
677         journal->j_head++;
678         journal->j_free--;
679         if (journal->j_head == journal->j_last)
680                 journal->j_head = journal->j_first;
681         write_unlock(&journal->j_state_lock);
682         return jbd2_journal_bmap(journal, blocknr, retp);
683 }
684
685 /*
686  * Conversion of logical to physical block numbers for the journal
687  *
688  * On external journals the journal blocks are identity-mapped, so
689  * this is a no-op.  If needed, we can use j_blk_offset - everything is
690  * ready.
691  */
692 int jbd2_journal_bmap(journal_t *journal, unsigned long blocknr,
693                  unsigned long long *retp)
694 {
695         int err = 0;
696         unsigned long long ret;
697
698         if (journal->j_inode) {
699                 ret = bmap(journal->j_inode, blocknr);
700                 if (ret)
701                         *retp = ret;
702                 else {
703                         printk(KERN_ALERT "%s: journal block not found "
704                                         "at offset %lu on %s\n",
705                                __func__, blocknr, journal->j_devname);
706                         err = -EIO;
707                         __journal_abort_soft(journal, err);
708                 }
709         } else {
710                 *retp = blocknr; /* +journal->j_blk_offset */
711         }
712         return err;
713 }
714
715 /*
716  * We play buffer_head aliasing tricks to write data/metadata blocks to
717  * the journal without copying their contents, but for journal
718  * descriptor blocks we do need to generate bona fide buffers.
719  *
720  * After the caller of jbd2_journal_get_descriptor_buffer() has finished modifying
721  * the buffer's contents they really should run flush_dcache_page(bh->b_page).
722  * But we don't bother doing that, so there will be coherency problems with
723  * mmaps of blockdevs which hold live JBD-controlled filesystems.
724  */
725 struct journal_head *jbd2_journal_get_descriptor_buffer(journal_t *journal)
726 {
727         struct buffer_head *bh;
728         unsigned long long blocknr;
729         int err;
730
731         err = jbd2_journal_next_log_block(journal, &blocknr);
732
733         if (err)
734                 return NULL;
735
736         bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize);
737         if (!bh)
738                 return NULL;
739         lock_buffer(bh);
740         memset(bh->b_data, 0, journal->j_blocksize);
741         set_buffer_uptodate(bh);
742         unlock_buffer(bh);
743         BUFFER_TRACE(bh, "return this buffer");
744         return jbd2_journal_add_journal_head(bh);
745 }
746
747 /*
748  * Return tid of the oldest transaction in the journal and block in the journal
749  * where the transaction starts.
750  *
751  * If the journal is now empty, return which will be the next transaction ID
752  * we will write and where will that transaction start.
753  *
754  * The return value is 0 if journal tail cannot be pushed any further, 1 if
755  * it can.
756  */
757 int jbd2_journal_get_log_tail(journal_t *journal, tid_t *tid,
758                               unsigned long *block)
759 {
760         transaction_t *transaction;
761         int ret;
762
763         read_lock(&journal->j_state_lock);
764         spin_lock(&journal->j_list_lock);
765         transaction = journal->j_checkpoint_transactions;
766         if (transaction) {
767                 *tid = transaction->t_tid;
768                 *block = transaction->t_log_start;
769         } else if ((transaction = journal->j_committing_transaction) != NULL) {
770                 *tid = transaction->t_tid;
771                 *block = transaction->t_log_start;
772         } else if ((transaction = journal->j_running_transaction) != NULL) {
773                 *tid = transaction->t_tid;
774                 *block = journal->j_head;
775         } else {
776                 *tid = journal->j_transaction_sequence;
777                 *block = journal->j_head;
778         }
779         ret = tid_gt(*tid, journal->j_tail_sequence);
780         spin_unlock(&journal->j_list_lock);
781         read_unlock(&journal->j_state_lock);
782
783         return ret;
784 }
785
786 /*
787  * Update information in journal structure and in on disk journal superblock
788  * about log tail. This function does not check whether information passed in
789  * really pushes log tail further. It's responsibility of the caller to make
790  * sure provided log tail information is valid (e.g. by holding
791  * j_checkpoint_mutex all the time between computing log tail and calling this
792  * function as is the case with jbd2_cleanup_journal_tail()).
793  *
794  * Requires j_checkpoint_mutex
795  */
796 void __jbd2_update_log_tail(journal_t *journal, tid_t tid, unsigned long block)
797 {
798         unsigned long freed;
799
800         BUG_ON(!mutex_is_locked(&journal->j_checkpoint_mutex));
801
802         /*
803          * We cannot afford for write to remain in drive's caches since as
804          * soon as we update j_tail, next transaction can start reusing journal
805          * space and if we lose sb update during power failure we'd replay
806          * old transaction with possibly newly overwritten data.
807          */
808         jbd2_journal_update_sb_log_tail(journal, tid, block, WRITE_FUA);
809         write_lock(&journal->j_state_lock);
810         freed = block - journal->j_tail;
811         if (block < journal->j_tail)
812                 freed += journal->j_last - journal->j_first;
813
814         trace_jbd2_update_log_tail(journal, tid, block, freed);
815         jbd_debug(1,
816                   "Cleaning journal tail from %d to %d (offset %lu), "
817                   "freeing %lu\n",
818                   journal->j_tail_sequence, tid, block, freed);
819
820         journal->j_free += freed;
821         journal->j_tail_sequence = tid;
822         journal->j_tail = block;
823         write_unlock(&journal->j_state_lock);
824 }
825
826 /*
827  * This is a variaon of __jbd2_update_log_tail which checks for validity of
828  * provided log tail and locks j_checkpoint_mutex. So it is safe against races
829  * with other threads updating log tail.
830  */
831 void jbd2_update_log_tail(journal_t *journal, tid_t tid, unsigned long block)
832 {
833         mutex_lock(&journal->j_checkpoint_mutex);
834         if (tid_gt(tid, journal->j_tail_sequence))
835                 __jbd2_update_log_tail(journal, tid, block);
836         mutex_unlock(&journal->j_checkpoint_mutex);
837 }
838
839 struct jbd2_stats_proc_session {
840         journal_t *journal;
841         struct transaction_stats_s *stats;
842         int start;
843         int max;
844 };
845
846 static void *jbd2_seq_info_start(struct seq_file *seq, loff_t *pos)
847 {
848         return *pos ? NULL : SEQ_START_TOKEN;
849 }
850
851 static void *jbd2_seq_info_next(struct seq_file *seq, void *v, loff_t *pos)
852 {
853         return NULL;
854 }
855
856 static int jbd2_seq_info_show(struct seq_file *seq, void *v)
857 {
858         struct jbd2_stats_proc_session *s = seq->private;
859
860         if (v != SEQ_START_TOKEN)
861                 return 0;
862         seq_printf(seq, "%lu transaction, each up to %u blocks\n",
863                         s->stats->ts_tid,
864                         s->journal->j_max_transaction_buffers);
865         if (s->stats->ts_tid == 0)
866                 return 0;
867         seq_printf(seq, "average: \n  %ums waiting for transaction\n",
868             jiffies_to_msecs(s->stats->run.rs_wait / s->stats->ts_tid));
869         seq_printf(seq, "  %ums running transaction\n",
870             jiffies_to_msecs(s->stats->run.rs_running / s->stats->ts_tid));
871         seq_printf(seq, "  %ums transaction was being locked\n",
872             jiffies_to_msecs(s->stats->run.rs_locked / s->stats->ts_tid));
873         seq_printf(seq, "  %ums flushing data (in ordered mode)\n",
874             jiffies_to_msecs(s->stats->run.rs_flushing / s->stats->ts_tid));
875         seq_printf(seq, "  %ums logging transaction\n",
876             jiffies_to_msecs(s->stats->run.rs_logging / s->stats->ts_tid));
877         seq_printf(seq, "  %lluus average transaction commit time\n",
878                    div_u64(s->journal->j_average_commit_time, 1000));
879         seq_printf(seq, "  %lu handles per transaction\n",
880             s->stats->run.rs_handle_count / s->stats->ts_tid);
881         seq_printf(seq, "  %lu blocks per transaction\n",
882             s->stats->run.rs_blocks / s->stats->ts_tid);
883         seq_printf(seq, "  %lu logged blocks per transaction\n",
884             s->stats->run.rs_blocks_logged / s->stats->ts_tid);
885         return 0;
886 }
887
888 static void jbd2_seq_info_stop(struct seq_file *seq, void *v)
889 {
890 }
891
892 static const struct seq_operations jbd2_seq_info_ops = {
893         .start  = jbd2_seq_info_start,
894         .next   = jbd2_seq_info_next,
895         .stop   = jbd2_seq_info_stop,
896         .show   = jbd2_seq_info_show,
897 };
898
899 static int jbd2_seq_info_open(struct inode *inode, struct file *file)
900 {
901         journal_t *journal = PDE(inode)->data;
902         struct jbd2_stats_proc_session *s;
903         int rc, size;
904
905         s = kmalloc(sizeof(*s), GFP_KERNEL);
906         if (s == NULL)
907                 return -ENOMEM;
908         size = sizeof(struct transaction_stats_s);
909         s->stats = kmalloc(size, GFP_KERNEL);
910         if (s->stats == NULL) {
911                 kfree(s);
912                 return -ENOMEM;
913         }
914         spin_lock(&journal->j_history_lock);
915         memcpy(s->stats, &journal->j_stats, size);
916         s->journal = journal;
917         spin_unlock(&journal->j_history_lock);
918
919         rc = seq_open(file, &jbd2_seq_info_ops);
920         if (rc == 0) {
921                 struct seq_file *m = file->private_data;
922                 m->private = s;
923         } else {
924                 kfree(s->stats);
925                 kfree(s);
926         }
927         return rc;
928
929 }
930
931 static int jbd2_seq_info_release(struct inode *inode, struct file *file)
932 {
933         struct seq_file *seq = file->private_data;
934         struct jbd2_stats_proc_session *s = seq->private;
935         kfree(s->stats);
936         kfree(s);
937         return seq_release(inode, file);
938 }
939
940 static const struct file_operations jbd2_seq_info_fops = {
941         .owner          = THIS_MODULE,
942         .open           = jbd2_seq_info_open,
943         .read           = seq_read,
944         .llseek         = seq_lseek,
945         .release        = jbd2_seq_info_release,
946 };
947
948 static struct proc_dir_entry *proc_jbd2_stats;
949
950 static void jbd2_stats_proc_init(journal_t *journal)
951 {
952         journal->j_proc_entry = proc_mkdir(journal->j_devname, proc_jbd2_stats);
953         if (journal->j_proc_entry) {
954                 proc_create_data("info", S_IRUGO, journal->j_proc_entry,
955                                  &jbd2_seq_info_fops, journal);
956         }
957 }
958
959 static void jbd2_stats_proc_exit(journal_t *journal)
960 {
961         remove_proc_entry("info", journal->j_proc_entry);
962         remove_proc_entry(journal->j_devname, proc_jbd2_stats);
963 }
964
965 /*
966  * Management for journal control blocks: functions to create and
967  * destroy journal_t structures, and to initialise and read existing
968  * journal blocks from disk.  */
969
970 /* First: create and setup a journal_t object in memory.  We initialise
971  * very few fields yet: that has to wait until we have created the
972  * journal structures from from scratch, or loaded them from disk. */
973
974 static journal_t * journal_init_common (void)
975 {
976         journal_t *journal;
977         int err;
978
979         journal = kzalloc(sizeof(*journal), GFP_KERNEL);
980         if (!journal)
981                 return NULL;
982
983         init_waitqueue_head(&journal->j_wait_transaction_locked);
984         init_waitqueue_head(&journal->j_wait_logspace);
985         init_waitqueue_head(&journal->j_wait_done_commit);
986         init_waitqueue_head(&journal->j_wait_checkpoint);
987         init_waitqueue_head(&journal->j_wait_commit);
988         init_waitqueue_head(&journal->j_wait_updates);
989         mutex_init(&journal->j_barrier);
990         mutex_init(&journal->j_checkpoint_mutex);
991         spin_lock_init(&journal->j_revoke_lock);
992         spin_lock_init(&journal->j_list_lock);
993         rwlock_init(&journal->j_state_lock);
994
995         journal->j_commit_interval = (HZ * JBD2_DEFAULT_MAX_COMMIT_AGE);
996         journal->j_min_batch_time = 0;
997         journal->j_max_batch_time = 15000; /* 15ms */
998
999         /* The journal is marked for error until we succeed with recovery! */
1000         journal->j_flags = JBD2_ABORT;
1001
1002         /* Set up a default-sized revoke table for the new mount. */
1003         err = jbd2_journal_init_revoke(journal, JOURNAL_REVOKE_DEFAULT_HASH);
1004         if (err) {
1005                 kfree(journal);
1006                 return NULL;
1007         }
1008
1009         spin_lock_init(&journal->j_history_lock);
1010
1011         return journal;
1012 }
1013
1014 /* jbd2_journal_init_dev and jbd2_journal_init_inode:
1015  *
1016  * Create a journal structure assigned some fixed set of disk blocks to
1017  * the journal.  We don't actually touch those disk blocks yet, but we
1018  * need to set up all of the mapping information to tell the journaling
1019  * system where the journal blocks are.
1020  *
1021  */
1022
1023 /**
1024  *  journal_t * jbd2_journal_init_dev() - creates and initialises a journal structure
1025  *  @bdev: Block device on which to create the journal
1026  *  @fs_dev: Device which hold journalled filesystem for this journal.
1027  *  @start: Block nr Start of journal.
1028  *  @len:  Length of the journal in blocks.
1029  *  @blocksize: blocksize of journalling device
1030  *
1031  *  Returns: a newly created journal_t *
1032  *
1033  *  jbd2_journal_init_dev creates a journal which maps a fixed contiguous
1034  *  range of blocks on an arbitrary block device.
1035  *
1036  */
1037 journal_t * jbd2_journal_init_dev(struct block_device *bdev,
1038                         struct block_device *fs_dev,
1039                         unsigned long long start, int len, int blocksize)
1040 {
1041         journal_t *journal = journal_init_common();
1042         struct buffer_head *bh;
1043         char *p;
1044         int n;
1045
1046         if (!journal)
1047                 return NULL;
1048
1049         /* journal descriptor can store up to n blocks -bzzz */
1050         journal->j_blocksize = blocksize;
1051         journal->j_dev = bdev;
1052         journal->j_fs_dev = fs_dev;
1053         journal->j_blk_offset = start;
1054         journal->j_maxlen = len;
1055         bdevname(journal->j_dev, journal->j_devname);
1056         p = journal->j_devname;
1057         while ((p = strchr(p, '/')))
1058                 *p = '!';
1059         jbd2_stats_proc_init(journal);
1060         n = journal->j_blocksize / sizeof(journal_block_tag_t);
1061         journal->j_wbufsize = n;
1062         journal->j_wbuf = kmalloc(n * sizeof(struct buffer_head*), GFP_KERNEL);
1063         if (!journal->j_wbuf) {
1064                 printk(KERN_ERR "%s: Can't allocate bhs for commit thread\n",
1065                         __func__);
1066                 goto out_err;
1067         }
1068
1069         bh = __getblk(journal->j_dev, start, journal->j_blocksize);
1070         if (!bh) {
1071                 printk(KERN_ERR
1072                        "%s: Cannot get buffer for journal superblock\n",
1073                        __func__);
1074                 goto out_err;
1075         }
1076         journal->j_sb_buffer = bh;
1077         journal->j_superblock = (journal_superblock_t *)bh->b_data;
1078
1079         return journal;
1080 out_err:
1081         kfree(journal->j_wbuf);
1082         jbd2_stats_proc_exit(journal);
1083         kfree(journal);
1084         return NULL;
1085 }
1086
1087 /**
1088  *  journal_t * jbd2_journal_init_inode () - creates a journal which maps to a inode.
1089  *  @inode: An inode to create the journal in
1090  *
1091  * jbd2_journal_init_inode creates a journal which maps an on-disk inode as
1092  * the journal.  The inode must exist already, must support bmap() and
1093  * must have all data blocks preallocated.
1094  */
1095 journal_t * jbd2_journal_init_inode (struct inode *inode)
1096 {
1097         struct buffer_head *bh;
1098         journal_t *journal = journal_init_common();
1099         char *p;
1100         int err;
1101         int n;
1102         unsigned long long blocknr;
1103
1104         if (!journal)
1105                 return NULL;
1106
1107         journal->j_dev = journal->j_fs_dev = inode->i_sb->s_bdev;
1108         journal->j_inode = inode;
1109         bdevname(journal->j_dev, journal->j_devname);
1110         p = journal->j_devname;
1111         while ((p = strchr(p, '/')))
1112                 *p = '!';
1113         p = journal->j_devname + strlen(journal->j_devname);
1114         sprintf(p, "-%lu", journal->j_inode->i_ino);
1115         jbd_debug(1,
1116                   "journal %p: inode %s/%ld, size %Ld, bits %d, blksize %ld\n",
1117                   journal, inode->i_sb->s_id, inode->i_ino,
1118                   (long long) inode->i_size,
1119                   inode->i_sb->s_blocksize_bits, inode->i_sb->s_blocksize);
1120
1121         journal->j_maxlen = inode->i_size >> inode->i_sb->s_blocksize_bits;
1122         journal->j_blocksize = inode->i_sb->s_blocksize;
1123         jbd2_stats_proc_init(journal);
1124
1125         /* journal descriptor can store up to n blocks -bzzz */
1126         n = journal->j_blocksize / sizeof(journal_block_tag_t);
1127         journal->j_wbufsize = n;
1128         journal->j_wbuf = kmalloc(n * sizeof(struct buffer_head*), GFP_KERNEL);
1129         if (!journal->j_wbuf) {
1130                 printk(KERN_ERR "%s: Can't allocate bhs for commit thread\n",
1131                         __func__);
1132                 goto out_err;
1133         }
1134
1135         err = jbd2_journal_bmap(journal, 0, &blocknr);
1136         /* If that failed, give up */
1137         if (err) {
1138                 printk(KERN_ERR "%s: Cannot locate journal superblock\n",
1139                        __func__);
1140                 goto out_err;
1141         }
1142
1143         bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize);
1144         if (!bh) {
1145                 printk(KERN_ERR
1146                        "%s: Cannot get buffer for journal superblock\n",
1147                        __func__);
1148                 goto out_err;
1149         }
1150         journal->j_sb_buffer = bh;
1151         journal->j_superblock = (journal_superblock_t *)bh->b_data;
1152
1153         return journal;
1154 out_err:
1155         kfree(journal->j_wbuf);
1156         jbd2_stats_proc_exit(journal);
1157         kfree(journal);
1158         return NULL;
1159 }
1160
1161 /*
1162  * If the journal init or create aborts, we need to mark the journal
1163  * superblock as being NULL to prevent the journal destroy from writing
1164  * back a bogus superblock.
1165  */
1166 static void journal_fail_superblock (journal_t *journal)
1167 {
1168         struct buffer_head *bh = journal->j_sb_buffer;
1169         brelse(bh);
1170         journal->j_sb_buffer = NULL;
1171 }
1172
1173 /*
1174  * Given a journal_t structure, initialise the various fields for
1175  * startup of a new journaling session.  We use this both when creating
1176  * a journal, and after recovering an old journal to reset it for
1177  * subsequent use.
1178  */
1179
1180 static int journal_reset(journal_t *journal)
1181 {
1182         journal_superblock_t *sb = journal->j_superblock;
1183         unsigned long long first, last;
1184
1185         first = be32_to_cpu(sb->s_first);
1186         last = be32_to_cpu(sb->s_maxlen);
1187         if (first + JBD2_MIN_JOURNAL_BLOCKS > last + 1) {
1188                 printk(KERN_ERR "JBD2: Journal too short (blocks %llu-%llu).\n",
1189                        first, last);
1190                 journal_fail_superblock(journal);
1191                 return -EINVAL;
1192         }
1193
1194         journal->j_first = first;
1195         journal->j_last = last;
1196
1197         journal->j_head = first;
1198         journal->j_tail = first;
1199         journal->j_free = last - first;
1200
1201         journal->j_tail_sequence = journal->j_transaction_sequence;
1202         journal->j_commit_sequence = journal->j_transaction_sequence - 1;
1203         journal->j_commit_request = journal->j_commit_sequence;
1204
1205         journal->j_max_transaction_buffers = journal->j_maxlen / 4;
1206
1207         /*
1208          * As a special case, if the on-disk copy is already marked as needing
1209          * no recovery (s_start == 0), then we can safely defer the superblock
1210          * update until the next commit by setting JBD2_FLUSHED.  This avoids
1211          * attempting a write to a potential-readonly device.
1212          */
1213         if (sb->s_start == 0) {
1214                 jbd_debug(1, "JBD2: Skipping superblock update on recovered sb "
1215                         "(start %ld, seq %d, errno %d)\n",
1216                         journal->j_tail, journal->j_tail_sequence,
1217                         journal->j_errno);
1218                 journal->j_flags |= JBD2_FLUSHED;
1219         } else {
1220                 /* Lock here to make assertions happy... */
1221                 mutex_lock(&journal->j_checkpoint_mutex);
1222                 /*
1223                  * Update log tail information. We use WRITE_FUA since new
1224                  * transaction will start reusing journal space and so we
1225                  * must make sure information about current log tail is on
1226                  * disk before that.
1227                  */
1228                 jbd2_journal_update_sb_log_tail(journal,
1229                                                 journal->j_tail_sequence,
1230                                                 journal->j_tail,
1231                                                 WRITE_FUA);
1232                 mutex_unlock(&journal->j_checkpoint_mutex);
1233         }
1234         return jbd2_journal_start_thread(journal);
1235 }
1236
1237 static void jbd2_write_superblock(journal_t *journal, int write_op)
1238 {
1239         struct buffer_head *bh = journal->j_sb_buffer;
1240         int ret;
1241
1242         trace_jbd2_write_superblock(journal, write_op);
1243         if (!(journal->j_flags & JBD2_BARRIER))
1244                 write_op &= ~(REQ_FUA | REQ_FLUSH);
1245         lock_buffer(bh);
1246         if (buffer_write_io_error(bh)) {
1247                 /*
1248                  * Oh, dear.  A previous attempt to write the journal
1249                  * superblock failed.  This could happen because the
1250                  * USB device was yanked out.  Or it could happen to
1251                  * be a transient write error and maybe the block will
1252                  * be remapped.  Nothing we can do but to retry the
1253                  * write and hope for the best.
1254                  */
1255                 printk(KERN_ERR "JBD2: previous I/O error detected "
1256                        "for journal superblock update for %s.\n",
1257                        journal->j_devname);
1258                 clear_buffer_write_io_error(bh);
1259                 set_buffer_uptodate(bh);
1260         }
1261         get_bh(bh);
1262         bh->b_end_io = end_buffer_write_sync;
1263         ret = submit_bh(write_op, bh);
1264         wait_on_buffer(bh);
1265         if (buffer_write_io_error(bh)) {
1266                 clear_buffer_write_io_error(bh);
1267                 set_buffer_uptodate(bh);
1268                 ret = -EIO;
1269         }
1270         if (ret) {
1271                 printk(KERN_ERR "JBD2: Error %d detected when updating "
1272                        "journal superblock for %s.\n", ret,
1273                        journal->j_devname);
1274         }
1275 }
1276
1277 /**
1278  * jbd2_journal_update_sb_log_tail() - Update log tail in journal sb on disk.
1279  * @journal: The journal to update.
1280  * @tail_tid: TID of the new transaction at the tail of the log
1281  * @tail_block: The first block of the transaction at the tail of the log
1282  * @write_op: With which operation should we write the journal sb
1283  *
1284  * Update a journal's superblock information about log tail and write it to
1285  * disk, waiting for the IO to complete.
1286  */
1287 void jbd2_journal_update_sb_log_tail(journal_t *journal, tid_t tail_tid,
1288                                      unsigned long tail_block, int write_op)
1289 {
1290         journal_superblock_t *sb = journal->j_superblock;
1291
1292         BUG_ON(!mutex_is_locked(&journal->j_checkpoint_mutex));
1293         jbd_debug(1, "JBD2: updating superblock (start %lu, seq %u)\n",
1294                   tail_block, tail_tid);
1295
1296         sb->s_sequence = cpu_to_be32(tail_tid);
1297         sb->s_start    = cpu_to_be32(tail_block);
1298
1299         jbd2_write_superblock(journal, write_op);
1300
1301         /* Log is no longer empty */
1302         write_lock(&journal->j_state_lock);
1303         WARN_ON(!sb->s_sequence);
1304         journal->j_flags &= ~JBD2_FLUSHED;
1305         write_unlock(&journal->j_state_lock);
1306 }
1307
1308 /**
1309  * jbd2_mark_journal_empty() - Mark on disk journal as empty.
1310  * @journal: The journal to update.
1311  *
1312  * Update a journal's dynamic superblock fields to show that journal is empty.
1313  * Write updated superblock to disk waiting for IO to complete.
1314  */
1315 static void jbd2_mark_journal_empty(journal_t *journal)
1316 {
1317         journal_superblock_t *sb = journal->j_superblock;
1318
1319         BUG_ON(!mutex_is_locked(&journal->j_checkpoint_mutex));
1320         read_lock(&journal->j_state_lock);
1321         jbd_debug(1, "JBD2: Marking journal as empty (seq %d)\n",
1322                   journal->j_tail_sequence);
1323
1324         sb->s_sequence = cpu_to_be32(journal->j_tail_sequence);
1325         sb->s_start    = cpu_to_be32(0);
1326         read_unlock(&journal->j_state_lock);
1327
1328         jbd2_write_superblock(journal, WRITE_FUA);
1329
1330         /* Log is no longer empty */
1331         write_lock(&journal->j_state_lock);
1332         journal->j_flags |= JBD2_FLUSHED;
1333         write_unlock(&journal->j_state_lock);
1334 }
1335
1336
1337 /**
1338  * jbd2_journal_update_sb_errno() - Update error in the journal.
1339  * @journal: The journal to update.
1340  *
1341  * Update a journal's errno.  Write updated superblock to disk waiting for IO
1342  * to complete.
1343  */
1344 static void jbd2_journal_update_sb_errno(journal_t *journal)
1345 {
1346         journal_superblock_t *sb = journal->j_superblock;
1347
1348         read_lock(&journal->j_state_lock);
1349         jbd_debug(1, "JBD2: updating superblock error (errno %d)\n",
1350                   journal->j_errno);
1351         sb->s_errno    = cpu_to_be32(journal->j_errno);
1352         read_unlock(&journal->j_state_lock);
1353
1354         jbd2_write_superblock(journal, WRITE_SYNC);
1355 }
1356
1357 /*
1358  * Read the superblock for a given journal, performing initial
1359  * validation of the format.
1360  */
1361 static int journal_get_superblock(journal_t *journal)
1362 {
1363         struct buffer_head *bh;
1364         journal_superblock_t *sb;
1365         int err = -EIO;
1366
1367         bh = journal->j_sb_buffer;
1368
1369         J_ASSERT(bh != NULL);
1370         if (!buffer_uptodate(bh)) {
1371                 ll_rw_block(READ, 1, &bh);
1372                 wait_on_buffer(bh);
1373                 if (!buffer_uptodate(bh)) {
1374                         printk(KERN_ERR
1375                                 "JBD2: IO error reading journal superblock\n");
1376                         goto out;
1377                 }
1378         }
1379
1380         sb = journal->j_superblock;
1381
1382         err = -EINVAL;
1383
1384         if (sb->s_header.h_magic != cpu_to_be32(JBD2_MAGIC_NUMBER) ||
1385             sb->s_blocksize != cpu_to_be32(journal->j_blocksize)) {
1386                 printk(KERN_WARNING "JBD2: no valid journal superblock found\n");
1387                 goto out;
1388         }
1389
1390         switch(be32_to_cpu(sb->s_header.h_blocktype)) {
1391         case JBD2_SUPERBLOCK_V1:
1392                 journal->j_format_version = 1;
1393                 break;
1394         case JBD2_SUPERBLOCK_V2:
1395                 journal->j_format_version = 2;
1396                 break;
1397         default:
1398                 printk(KERN_WARNING "JBD2: unrecognised superblock format ID\n");
1399                 goto out;
1400         }
1401
1402         if (be32_to_cpu(sb->s_maxlen) < journal->j_maxlen)
1403                 journal->j_maxlen = be32_to_cpu(sb->s_maxlen);
1404         else if (be32_to_cpu(sb->s_maxlen) > journal->j_maxlen) {
1405                 printk(KERN_WARNING "JBD2: journal file too short\n");
1406                 goto out;
1407         }
1408
1409         if (be32_to_cpu(sb->s_first) == 0 ||
1410             be32_to_cpu(sb->s_first) >= journal->j_maxlen) {
1411                 printk(KERN_WARNING
1412                         "JBD2: Invalid start block of journal: %u\n",
1413                         be32_to_cpu(sb->s_first));
1414                 goto out;
1415         }
1416
1417         return 0;
1418
1419 out:
1420         journal_fail_superblock(journal);
1421         return err;
1422 }
1423
1424 /*
1425  * Load the on-disk journal superblock and read the key fields into the
1426  * journal_t.
1427  */
1428
1429 static int load_superblock(journal_t *journal)
1430 {
1431         int err;
1432         journal_superblock_t *sb;
1433
1434         err = journal_get_superblock(journal);
1435         if (err)
1436                 return err;
1437
1438         sb = journal->j_superblock;
1439
1440         journal->j_tail_sequence = be32_to_cpu(sb->s_sequence);
1441         journal->j_tail = be32_to_cpu(sb->s_start);
1442         journal->j_first = be32_to_cpu(sb->s_first);
1443         journal->j_last = be32_to_cpu(sb->s_maxlen);
1444         journal->j_errno = be32_to_cpu(sb->s_errno);
1445
1446         return 0;
1447 }
1448
1449
1450 /**
1451  * int jbd2_journal_load() - Read journal from disk.
1452  * @journal: Journal to act on.
1453  *
1454  * Given a journal_t structure which tells us which disk blocks contain
1455  * a journal, read the journal from disk to initialise the in-memory
1456  * structures.
1457  */
1458 int jbd2_journal_load(journal_t *journal)
1459 {
1460         int err;
1461         journal_superblock_t *sb;
1462
1463         err = load_superblock(journal);
1464         if (err)
1465                 return err;
1466
1467         sb = journal->j_superblock;
1468         /* If this is a V2 superblock, then we have to check the
1469          * features flags on it. */
1470
1471         if (journal->j_format_version >= 2) {
1472                 if ((sb->s_feature_ro_compat &
1473                      ~cpu_to_be32(JBD2_KNOWN_ROCOMPAT_FEATURES)) ||
1474                     (sb->s_feature_incompat &
1475                      ~cpu_to_be32(JBD2_KNOWN_INCOMPAT_FEATURES))) {
1476                         printk(KERN_WARNING
1477                                 "JBD2: Unrecognised features on journal\n");
1478                         return -EINVAL;
1479                 }
1480         }
1481
1482         /*
1483          * Create a slab for this blocksize
1484          */
1485         err = jbd2_journal_create_slab(be32_to_cpu(sb->s_blocksize));
1486         if (err)
1487                 return err;
1488
1489         /* Let the recovery code check whether it needs to recover any
1490          * data from the journal. */
1491         if (jbd2_journal_recover(journal))
1492                 goto recovery_error;
1493
1494         if (journal->j_failed_commit) {
1495                 printk(KERN_ERR "JBD2: journal transaction %u on %s "
1496                        "is corrupt.\n", journal->j_failed_commit,
1497                        journal->j_devname);
1498                 return -EIO;
1499         }
1500
1501         /* OK, we've finished with the dynamic journal bits:
1502          * reinitialise the dynamic contents of the superblock in memory
1503          * and reset them on disk. */
1504         if (journal_reset(journal))
1505                 goto recovery_error;
1506
1507         journal->j_flags &= ~JBD2_ABORT;
1508         journal->j_flags |= JBD2_LOADED;
1509         return 0;
1510
1511 recovery_error:
1512         printk(KERN_WARNING "JBD2: recovery failed\n");
1513         return -EIO;
1514 }
1515
1516 /**
1517  * void jbd2_journal_destroy() - Release a journal_t structure.
1518  * @journal: Journal to act on.
1519  *
1520  * Release a journal_t structure once it is no longer in use by the
1521  * journaled object.
1522  * Return <0 if we couldn't clean up the journal.
1523  */
1524 int jbd2_journal_destroy(journal_t *journal)
1525 {
1526         int err = 0;
1527
1528         /* Wait for the commit thread to wake up and die. */
1529         journal_kill_thread(journal);
1530
1531         /* Force a final log commit */
1532         if (journal->j_running_transaction)
1533                 jbd2_journal_commit_transaction(journal);
1534
1535         /* Force any old transactions to disk */
1536
1537         /* Totally anal locking here... */
1538         spin_lock(&journal->j_list_lock);
1539         while (journal->j_checkpoint_transactions != NULL) {
1540                 spin_unlock(&journal->j_list_lock);
1541                 mutex_lock(&journal->j_checkpoint_mutex);
1542                 jbd2_log_do_checkpoint(journal);
1543                 mutex_unlock(&journal->j_checkpoint_mutex);
1544                 spin_lock(&journal->j_list_lock);
1545         }
1546
1547         J_ASSERT(journal->j_running_transaction == NULL);
1548         J_ASSERT(journal->j_committing_transaction == NULL);
1549         J_ASSERT(journal->j_checkpoint_transactions == NULL);
1550         spin_unlock(&journal->j_list_lock);
1551
1552         if (journal->j_sb_buffer) {
1553                 if (!is_journal_aborted(journal)) {
1554                         mutex_lock(&journal->j_checkpoint_mutex);
1555                         jbd2_mark_journal_empty(journal);
1556                         mutex_unlock(&journal->j_checkpoint_mutex);
1557                 } else
1558                         err = -EIO;
1559                 brelse(journal->j_sb_buffer);
1560         }
1561
1562         if (journal->j_proc_entry)
1563                 jbd2_stats_proc_exit(journal);
1564         if (journal->j_inode)
1565                 iput(journal->j_inode);
1566         if (journal->j_revoke)
1567                 jbd2_journal_destroy_revoke(journal);
1568         kfree(journal->j_wbuf);
1569         kfree(journal);
1570
1571         return err;
1572 }
1573
1574
1575 /**
1576  *int jbd2_journal_check_used_features () - Check if features specified are used.
1577  * @journal: Journal to check.
1578  * @compat: bitmask of compatible features
1579  * @ro: bitmask of features that force read-only mount
1580  * @incompat: bitmask of incompatible features
1581  *
1582  * Check whether the journal uses all of a given set of
1583  * features.  Return true (non-zero) if it does.
1584  **/
1585
1586 int jbd2_journal_check_used_features (journal_t *journal, unsigned long compat,
1587                                  unsigned long ro, unsigned long incompat)
1588 {
1589         journal_superblock_t *sb;
1590
1591         if (!compat && !ro && !incompat)
1592                 return 1;
1593         /* Load journal superblock if it is not loaded yet. */
1594         if (journal->j_format_version == 0 &&
1595             journal_get_superblock(journal) != 0)
1596                 return 0;
1597         if (journal->j_format_version == 1)
1598                 return 0;
1599
1600         sb = journal->j_superblock;
1601
1602         if (((be32_to_cpu(sb->s_feature_compat) & compat) == compat) &&
1603             ((be32_to_cpu(sb->s_feature_ro_compat) & ro) == ro) &&
1604             ((be32_to_cpu(sb->s_feature_incompat) & incompat) == incompat))
1605                 return 1;
1606
1607         return 0;
1608 }
1609
1610 /**
1611  * int jbd2_journal_check_available_features() - Check feature set in journalling layer
1612  * @journal: Journal to check.
1613  * @compat: bitmask of compatible features
1614  * @ro: bitmask of features that force read-only mount
1615  * @incompat: bitmask of incompatible features
1616  *
1617  * Check whether the journaling code supports the use of
1618  * all of a given set of features on this journal.  Return true
1619  * (non-zero) if it can. */
1620
1621 int jbd2_journal_check_available_features (journal_t *journal, unsigned long compat,
1622                                       unsigned long ro, unsigned long incompat)
1623 {
1624         if (!compat && !ro && !incompat)
1625                 return 1;
1626
1627         /* We can support any known requested features iff the
1628          * superblock is in version 2.  Otherwise we fail to support any
1629          * extended sb features. */
1630
1631         if (journal->j_format_version != 2)
1632                 return 0;
1633
1634         if ((compat   & JBD2_KNOWN_COMPAT_FEATURES) == compat &&
1635             (ro       & JBD2_KNOWN_ROCOMPAT_FEATURES) == ro &&
1636             (incompat & JBD2_KNOWN_INCOMPAT_FEATURES) == incompat)
1637                 return 1;
1638
1639         return 0;
1640 }
1641
1642 /**
1643  * int jbd2_journal_set_features () - Mark a given journal feature in the superblock
1644  * @journal: Journal to act on.
1645  * @compat: bitmask of compatible features
1646  * @ro: bitmask of features that force read-only mount
1647  * @incompat: bitmask of incompatible features
1648  *
1649  * Mark a given journal feature as present on the
1650  * superblock.  Returns true if the requested features could be set.
1651  *
1652  */
1653
1654 int jbd2_journal_set_features (journal_t *journal, unsigned long compat,
1655                           unsigned long ro, unsigned long incompat)
1656 {
1657         journal_superblock_t *sb;
1658
1659         if (jbd2_journal_check_used_features(journal, compat, ro, incompat))
1660                 return 1;
1661
1662         if (!jbd2_journal_check_available_features(journal, compat, ro, incompat))
1663                 return 0;
1664
1665         jbd_debug(1, "Setting new features 0x%lx/0x%lx/0x%lx\n",
1666                   compat, ro, incompat);
1667
1668         sb = journal->j_superblock;
1669
1670         sb->s_feature_compat    |= cpu_to_be32(compat);
1671         sb->s_feature_ro_compat |= cpu_to_be32(ro);
1672         sb->s_feature_incompat  |= cpu_to_be32(incompat);
1673
1674         return 1;
1675 }
1676
1677 /*
1678  * jbd2_journal_clear_features () - Clear a given journal feature in the
1679  *                                  superblock
1680  * @journal: Journal to act on.
1681  * @compat: bitmask of compatible features
1682  * @ro: bitmask of features that force read-only mount
1683  * @incompat: bitmask of incompatible features
1684  *
1685  * Clear a given journal feature as present on the
1686  * superblock.
1687  */
1688 void jbd2_journal_clear_features(journal_t *journal, unsigned long compat,
1689                                 unsigned long ro, unsigned long incompat)
1690 {
1691         journal_superblock_t *sb;
1692
1693         jbd_debug(1, "Clear features 0x%lx/0x%lx/0x%lx\n",
1694                   compat, ro, incompat);
1695
1696         sb = journal->j_superblock;
1697
1698         sb->s_feature_compat    &= ~cpu_to_be32(compat);
1699         sb->s_feature_ro_compat &= ~cpu_to_be32(ro);
1700         sb->s_feature_incompat  &= ~cpu_to_be32(incompat);
1701 }
1702 EXPORT_SYMBOL(jbd2_journal_clear_features);
1703
1704 /**
1705  * int jbd2_journal_flush () - Flush journal
1706  * @journal: Journal to act on.
1707  *
1708  * Flush all data for a given journal to disk and empty the journal.
1709  * Filesystems can use this when remounting readonly to ensure that
1710  * recovery does not need to happen on remount.
1711  */
1712
1713 int jbd2_journal_flush(journal_t *journal)
1714 {
1715         int err = 0;
1716         transaction_t *transaction = NULL;
1717
1718         write_lock(&journal->j_state_lock);
1719
1720         /* Force everything buffered to the log... */
1721         if (journal->j_running_transaction) {
1722                 transaction = journal->j_running_transaction;
1723                 __jbd2_log_start_commit(journal, transaction->t_tid);
1724         } else if (journal->j_committing_transaction)
1725                 transaction = journal->j_committing_transaction;
1726
1727         /* Wait for the log commit to complete... */
1728         if (transaction) {
1729                 tid_t tid = transaction->t_tid;
1730
1731                 write_unlock(&journal->j_state_lock);
1732                 jbd2_log_wait_commit(journal, tid);
1733         } else {
1734                 write_unlock(&journal->j_state_lock);
1735         }
1736
1737         /* ...and flush everything in the log out to disk. */
1738         spin_lock(&journal->j_list_lock);
1739         while (!err && journal->j_checkpoint_transactions != NULL) {
1740                 spin_unlock(&journal->j_list_lock);
1741                 mutex_lock(&journal->j_checkpoint_mutex);
1742                 err = jbd2_log_do_checkpoint(journal);
1743                 mutex_unlock(&journal->j_checkpoint_mutex);
1744                 spin_lock(&journal->j_list_lock);
1745         }
1746         spin_unlock(&journal->j_list_lock);
1747
1748         if (is_journal_aborted(journal))
1749                 return -EIO;
1750
1751         mutex_lock(&journal->j_checkpoint_mutex);
1752         jbd2_cleanup_journal_tail(journal);
1753
1754         /* Finally, mark the journal as really needing no recovery.
1755          * This sets s_start==0 in the underlying superblock, which is
1756          * the magic code for a fully-recovered superblock.  Any future
1757          * commits of data to the journal will restore the current
1758          * s_start value. */
1759         jbd2_mark_journal_empty(journal);
1760         mutex_unlock(&journal->j_checkpoint_mutex);
1761         write_lock(&journal->j_state_lock);
1762         J_ASSERT(!journal->j_running_transaction);
1763         J_ASSERT(!journal->j_committing_transaction);
1764         J_ASSERT(!journal->j_checkpoint_transactions);
1765         J_ASSERT(journal->j_head == journal->j_tail);
1766         J_ASSERT(journal->j_tail_sequence == journal->j_transaction_sequence);
1767         write_unlock(&journal->j_state_lock);
1768         return 0;
1769 }
1770
1771 /**
1772  * int jbd2_journal_wipe() - Wipe journal contents
1773  * @journal: Journal to act on.
1774  * @write: flag (see below)
1775  *
1776  * Wipe out all of the contents of a journal, safely.  This will produce
1777  * a warning if the journal contains any valid recovery information.
1778  * Must be called between journal_init_*() and jbd2_journal_load().
1779  *
1780  * If 'write' is non-zero, then we wipe out the journal on disk; otherwise
1781  * we merely suppress recovery.
1782  */
1783
1784 int jbd2_journal_wipe(journal_t *journal, int write)
1785 {
1786         int err = 0;
1787
1788         J_ASSERT (!(journal->j_flags & JBD2_LOADED));
1789
1790         err = load_superblock(journal);
1791         if (err)
1792                 return err;
1793
1794         if (!journal->j_tail)
1795                 goto no_recovery;
1796
1797         printk(KERN_WARNING "JBD2: %s recovery information on journal\n",
1798                 write ? "Clearing" : "Ignoring");
1799
1800         err = jbd2_journal_skip_recovery(journal);
1801         if (write) {
1802                 /* Lock to make assertions happy... */
1803                 mutex_lock(&journal->j_checkpoint_mutex);
1804                 jbd2_mark_journal_empty(journal);
1805                 mutex_unlock(&journal->j_checkpoint_mutex);
1806         }
1807
1808  no_recovery:
1809         return err;
1810 }
1811
1812 /*
1813  * Journal abort has very specific semantics, which we describe
1814  * for journal abort.
1815  *
1816  * Two internal functions, which provide abort to the jbd layer
1817  * itself are here.
1818  */
1819
1820 /*
1821  * Quick version for internal journal use (doesn't lock the journal).
1822  * Aborts hard --- we mark the abort as occurred, but do _nothing_ else,
1823  * and don't attempt to make any other journal updates.
1824  */
1825 void __jbd2_journal_abort_hard(journal_t *journal)
1826 {
1827         transaction_t *transaction;
1828
1829         if (journal->j_flags & JBD2_ABORT)
1830                 return;
1831
1832         printk(KERN_ERR "Aborting journal on device %s.\n",
1833                journal->j_devname);
1834
1835         write_lock(&journal->j_state_lock);
1836         journal->j_flags |= JBD2_ABORT;
1837         transaction = journal->j_running_transaction;
1838         if (transaction)
1839                 __jbd2_log_start_commit(journal, transaction->t_tid);
1840         write_unlock(&journal->j_state_lock);
1841 }
1842
1843 /* Soft abort: record the abort error status in the journal superblock,
1844  * but don't do any other IO. */
1845 static void __journal_abort_soft (journal_t *journal, int errno)
1846 {
1847         if (journal->j_flags & JBD2_ABORT)
1848                 return;
1849
1850         if (!journal->j_errno)
1851                 journal->j_errno = errno;
1852
1853         __jbd2_journal_abort_hard(journal);
1854
1855         if (errno)
1856                 jbd2_journal_update_sb_errno(journal);
1857 }
1858
1859 /**
1860  * void jbd2_journal_abort () - Shutdown the journal immediately.
1861  * @journal: the journal to shutdown.
1862  * @errno:   an error number to record in the journal indicating
1863  *           the reason for the shutdown.
1864  *
1865  * Perform a complete, immediate shutdown of the ENTIRE
1866  * journal (not of a single transaction).  This operation cannot be
1867  * undone without closing and reopening the journal.
1868  *
1869  * The jbd2_journal_abort function is intended to support higher level error
1870  * recovery mechanisms such as the ext2/ext3 remount-readonly error
1871  * mode.
1872  *
1873  * Journal abort has very specific semantics.  Any existing dirty,
1874  * unjournaled buffers in the main filesystem will still be written to
1875  * disk by bdflush, but the journaling mechanism will be suspended
1876  * immediately and no further transaction commits will be honoured.
1877  *
1878  * Any dirty, journaled buffers will be written back to disk without
1879  * hitting the journal.  Atomicity cannot be guaranteed on an aborted
1880  * filesystem, but we _do_ attempt to leave as much data as possible
1881  * behind for fsck to use for cleanup.
1882  *
1883  * Any attempt to get a new transaction handle on a journal which is in
1884  * ABORT state will just result in an -EROFS error return.  A
1885  * jbd2_journal_stop on an existing handle will return -EIO if we have
1886  * entered abort state during the update.
1887  *
1888  * Recursive transactions are not disturbed by journal abort until the
1889  * final jbd2_journal_stop, which will receive the -EIO error.
1890  *
1891  * Finally, the jbd2_journal_abort call allows the caller to supply an errno
1892  * which will be recorded (if possible) in the journal superblock.  This
1893  * allows a client to record failure conditions in the middle of a
1894  * transaction without having to complete the transaction to record the
1895  * failure to disk.  ext3_error, for example, now uses this
1896  * functionality.
1897  *
1898  * Errors which originate from within the journaling layer will NOT
1899  * supply an errno; a null errno implies that absolutely no further
1900  * writes are done to the journal (unless there are any already in
1901  * progress).
1902  *
1903  */
1904
1905 void jbd2_journal_abort(journal_t *journal, int errno)
1906 {
1907         __journal_abort_soft(journal, errno);
1908 }
1909
1910 /**
1911  * int jbd2_journal_errno () - returns the journal's error state.
1912  * @journal: journal to examine.
1913  *
1914  * This is the errno number set with jbd2_journal_abort(), the last
1915  * time the journal was mounted - if the journal was stopped
1916  * without calling abort this will be 0.
1917  *
1918  * If the journal has been aborted on this mount time -EROFS will
1919  * be returned.
1920  */
1921 int jbd2_journal_errno(journal_t *journal)
1922 {
1923         int err;
1924
1925         read_lock(&journal->j_state_lock);
1926         if (journal->j_flags & JBD2_ABORT)
1927                 err = -EROFS;
1928         else
1929                 err = journal->j_errno;
1930         read_unlock(&journal->j_state_lock);
1931         return err;
1932 }
1933
1934 /**
1935  * int jbd2_journal_clear_err () - clears the journal's error state
1936  * @journal: journal to act on.
1937  *
1938  * An error must be cleared or acked to take a FS out of readonly
1939  * mode.
1940  */
1941 int jbd2_journal_clear_err(journal_t *journal)
1942 {
1943         int err = 0;
1944
1945         write_lock(&journal->j_state_lock);
1946         if (journal->j_flags & JBD2_ABORT)
1947                 err = -EROFS;
1948         else
1949                 journal->j_errno = 0;
1950         write_unlock(&journal->j_state_lock);
1951         return err;
1952 }
1953
1954 /**
1955  * void jbd2_journal_ack_err() - Ack journal err.
1956  * @journal: journal to act on.
1957  *
1958  * An error must be cleared or acked to take a FS out of readonly
1959  * mode.
1960  */
1961 void jbd2_journal_ack_err(journal_t *journal)
1962 {
1963         write_lock(&journal->j_state_lock);
1964         if (journal->j_errno)
1965                 journal->j_flags |= JBD2_ACK_ERR;
1966         write_unlock(&journal->j_state_lock);
1967 }
1968
1969 int jbd2_journal_blocks_per_page(struct inode *inode)
1970 {
1971         return 1 << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
1972 }
1973
1974 /*
1975  * helper functions to deal with 32 or 64bit block numbers.
1976  */
1977 size_t journal_tag_bytes(journal_t *journal)
1978 {
1979         if (JBD2_HAS_INCOMPAT_FEATURE(journal, JBD2_FEATURE_INCOMPAT_64BIT))
1980                 return JBD2_TAG_SIZE64;
1981         else
1982                 return JBD2_TAG_SIZE32;
1983 }
1984
1985 /*
1986  * JBD memory management
1987  *
1988  * These functions are used to allocate block-sized chunks of memory
1989  * used for making copies of buffer_head data.  Very often it will be
1990  * page-sized chunks of data, but sometimes it will be in
1991  * sub-page-size chunks.  (For example, 16k pages on Power systems
1992  * with a 4k block file system.)  For blocks smaller than a page, we
1993  * use a SLAB allocator.  There are slab caches for each block size,
1994  * which are allocated at mount time, if necessary, and we only free
1995  * (all of) the slab caches when/if the jbd2 module is unloaded.  For
1996  * this reason we don't need to a mutex to protect access to
1997  * jbd2_slab[] allocating or releasing memory; only in
1998  * jbd2_journal_create_slab().
1999  */
2000 #define JBD2_MAX_SLABS 8
2001 static struct kmem_cache *jbd2_slab[JBD2_MAX_SLABS];
2002
2003 static const char *jbd2_slab_names[JBD2_MAX_SLABS] = {
2004         "jbd2_1k", "jbd2_2k", "jbd2_4k", "jbd2_8k",
2005         "jbd2_16k", "jbd2_32k", "jbd2_64k", "jbd2_128k"
2006 };
2007
2008
2009 static void jbd2_journal_destroy_slabs(void)
2010 {
2011         int i;
2012
2013         for (i = 0; i < JBD2_MAX_SLABS; i++) {
2014                 if (jbd2_slab[i])
2015                         kmem_cache_destroy(jbd2_slab[i]);
2016                 jbd2_slab[i] = NULL;
2017         }
2018 }
2019
2020 static int jbd2_journal_create_slab(size_t size)
2021 {
2022         static DEFINE_MUTEX(jbd2_slab_create_mutex);
2023         int i = order_base_2(size) - 10;
2024         size_t slab_size;
2025
2026         if (size == PAGE_SIZE)
2027                 return 0;
2028
2029         if (i >= JBD2_MAX_SLABS)
2030                 return -EINVAL;
2031
2032         if (unlikely(i < 0))
2033                 i = 0;
2034         mutex_lock(&jbd2_slab_create_mutex);
2035         if (jbd2_slab[i]) {
2036                 mutex_unlock(&jbd2_slab_create_mutex);
2037                 return 0;       /* Already created */
2038         }
2039
2040         slab_size = 1 << (i+10);
2041         jbd2_slab[i] = kmem_cache_create(jbd2_slab_names[i], slab_size,
2042                                          slab_size, 0, NULL);
2043         mutex_unlock(&jbd2_slab_create_mutex);
2044         if (!jbd2_slab[i]) {
2045                 printk(KERN_EMERG "JBD2: no memory for jbd2_slab cache\n");
2046                 return -ENOMEM;
2047         }
2048         return 0;
2049 }
2050
2051 static struct kmem_cache *get_slab(size_t size)
2052 {
2053         int i = order_base_2(size) - 10;
2054
2055         BUG_ON(i >= JBD2_MAX_SLABS);
2056         if (unlikely(i < 0))
2057                 i = 0;
2058         BUG_ON(jbd2_slab[i] == NULL);
2059         return jbd2_slab[i];
2060 }
2061
2062 void *jbd2_alloc(size_t size, gfp_t flags)
2063 {
2064         void *ptr;
2065
2066         BUG_ON(size & (size-1)); /* Must be a power of 2 */
2067
2068         flags |= __GFP_REPEAT;
2069         if (size == PAGE_SIZE)
2070                 ptr = (void *)__get_free_pages(flags, 0);
2071         else if (size > PAGE_SIZE) {
2072                 int order = get_order(size);
2073
2074                 if (order < 3)
2075                         ptr = (void *)__get_free_pages(flags, order);
2076                 else
2077                         ptr = vmalloc(size);
2078         } else
2079                 ptr = kmem_cache_alloc(get_slab(size), flags);
2080
2081         /* Check alignment; SLUB has gotten this wrong in the past,
2082          * and this can lead to user data corruption! */
2083         BUG_ON(((unsigned long) ptr) & (size-1));
2084
2085         return ptr;
2086 }
2087
2088 void jbd2_free(void *ptr, size_t size)
2089 {
2090         if (size == PAGE_SIZE) {
2091                 free_pages((unsigned long)ptr, 0);
2092                 return;
2093         }
2094         if (size > PAGE_SIZE) {
2095                 int order = get_order(size);
2096
2097                 if (order < 3)
2098                         free_pages((unsigned long)ptr, order);
2099                 else
2100                         vfree(ptr);
2101                 return;
2102         }
2103         kmem_cache_free(get_slab(size), ptr);
2104 };
2105
2106 /*
2107  * Journal_head storage management
2108  */
2109 static struct kmem_cache *jbd2_journal_head_cache;
2110 #ifdef CONFIG_JBD2_DEBUG
2111 static atomic_t nr_journal_heads = ATOMIC_INIT(0);
2112 #endif
2113
2114 static int jbd2_journal_init_journal_head_cache(void)
2115 {
2116         int retval;
2117
2118         J_ASSERT(jbd2_journal_head_cache == NULL);
2119         jbd2_journal_head_cache = kmem_cache_create("jbd2_journal_head",
2120                                 sizeof(struct journal_head),
2121                                 0,              /* offset */
2122                                 SLAB_TEMPORARY, /* flags */
2123                                 NULL);          /* ctor */
2124         retval = 0;
2125         if (!jbd2_journal_head_cache) {
2126                 retval = -ENOMEM;
2127                 printk(KERN_EMERG "JBD2: no memory for journal_head cache\n");
2128         }
2129         return retval;
2130 }
2131
2132 static void jbd2_journal_destroy_journal_head_cache(void)
2133 {
2134         if (jbd2_journal_head_cache) {
2135                 kmem_cache_destroy(jbd2_journal_head_cache);
2136                 jbd2_journal_head_cache = NULL;
2137         }
2138 }
2139
2140 /*
2141  * journal_head splicing and dicing
2142  */
2143 static struct journal_head *journal_alloc_journal_head(void)
2144 {
2145         struct journal_head *ret;
2146
2147 #ifdef CONFIG_JBD2_DEBUG
2148         atomic_inc(&nr_journal_heads);
2149 #endif
2150         ret = kmem_cache_alloc(jbd2_journal_head_cache, GFP_NOFS);
2151         if (!ret) {
2152                 jbd_debug(1, "out of memory for journal_head\n");
2153                 pr_notice_ratelimited("ENOMEM in %s, retrying.\n", __func__);
2154                 while (!ret) {
2155                         yield();
2156                         ret = kmem_cache_alloc(jbd2_journal_head_cache, GFP_NOFS);
2157                 }
2158         }
2159         return ret;
2160 }
2161
2162 static void journal_free_journal_head(struct journal_head *jh)
2163 {
2164 #ifdef CONFIG_JBD2_DEBUG
2165         atomic_dec(&nr_journal_heads);
2166         memset(jh, JBD2_POISON_FREE, sizeof(*jh));
2167 #endif
2168         kmem_cache_free(jbd2_journal_head_cache, jh);
2169 }
2170
2171 /*
2172  * A journal_head is attached to a buffer_head whenever JBD has an
2173  * interest in the buffer.
2174  *
2175  * Whenever a buffer has an attached journal_head, its ->b_state:BH_JBD bit
2176  * is set.  This bit is tested in core kernel code where we need to take
2177  * JBD-specific actions.  Testing the zeroness of ->b_private is not reliable
2178  * there.
2179  *
2180  * When a buffer has its BH_JBD bit set, its ->b_count is elevated by one.
2181  *
2182  * When a buffer has its BH_JBD bit set it is immune from being released by
2183  * core kernel code, mainly via ->b_count.
2184  *
2185  * A journal_head is detached from its buffer_head when the journal_head's
2186  * b_jcount reaches zero. Running transaction (b_transaction) and checkpoint
2187  * transaction (b_cp_transaction) hold their references to b_jcount.
2188  *
2189  * Various places in the kernel want to attach a journal_head to a buffer_head
2190  * _before_ attaching the journal_head to a transaction.  To protect the
2191  * journal_head in this situation, jbd2_journal_add_journal_head elevates the
2192  * journal_head's b_jcount refcount by one.  The caller must call
2193  * jbd2_journal_put_journal_head() to undo this.
2194  *
2195  * So the typical usage would be:
2196  *
2197  *      (Attach a journal_head if needed.  Increments b_jcount)
2198  *      struct journal_head *jh = jbd2_journal_add_journal_head(bh);
2199  *      ...
2200  *      (Get another reference for transaction)
2201  *      jbd2_journal_grab_journal_head(bh);
2202  *      jh->b_transaction = xxx;
2203  *      (Put original reference)
2204  *      jbd2_journal_put_journal_head(jh);
2205  */
2206
2207 /*
2208  * Give a buffer_head a journal_head.
2209  *
2210  * May sleep.
2211  */
2212 struct journal_head *jbd2_journal_add_journal_head(struct buffer_head *bh)
2213 {
2214         struct journal_head *jh;
2215         struct journal_head *new_jh = NULL;
2216
2217 repeat:
2218         if (!buffer_jbd(bh)) {
2219                 new_jh = journal_alloc_journal_head();
2220                 memset(new_jh, 0, sizeof(*new_jh));
2221         }
2222
2223         jbd_lock_bh_journal_head(bh);
2224         if (buffer_jbd(bh)) {
2225                 jh = bh2jh(bh);
2226         } else {
2227                 J_ASSERT_BH(bh,
2228                         (atomic_read(&bh->b_count) > 0) ||
2229                         (bh->b_page && bh->b_page->mapping));
2230
2231                 if (!new_jh) {
2232                         jbd_unlock_bh_journal_head(bh);
2233                         goto repeat;
2234                 }
2235
2236                 jh = new_jh;
2237                 new_jh = NULL;          /* We consumed it */
2238                 set_buffer_jbd(bh);
2239                 bh->b_private = jh;
2240                 jh->b_bh = bh;
2241                 get_bh(bh);
2242                 BUFFER_TRACE(bh, "added journal_head");
2243         }
2244         jh->b_jcount++;
2245         jbd_unlock_bh_journal_head(bh);
2246         if (new_jh)
2247                 journal_free_journal_head(new_jh);
2248         return bh->b_private;
2249 }
2250
2251 /*
2252  * Grab a ref against this buffer_head's journal_head.  If it ended up not
2253  * having a journal_head, return NULL
2254  */
2255 struct journal_head *jbd2_journal_grab_journal_head(struct buffer_head *bh)
2256 {
2257         struct journal_head *jh = NULL;
2258
2259         jbd_lock_bh_journal_head(bh);
2260         if (buffer_jbd(bh)) {
2261                 jh = bh2jh(bh);
2262                 jh->b_jcount++;
2263         }
2264         jbd_unlock_bh_journal_head(bh);
2265         return jh;
2266 }
2267
2268 static void __journal_remove_journal_head(struct buffer_head *bh)
2269 {
2270         struct journal_head *jh = bh2jh(bh);
2271
2272         J_ASSERT_JH(jh, jh->b_jcount >= 0);
2273         J_ASSERT_JH(jh, jh->b_transaction == NULL);
2274         J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
2275         J_ASSERT_JH(jh, jh->b_cp_transaction == NULL);
2276         J_ASSERT_JH(jh, jh->b_jlist == BJ_None);
2277         J_ASSERT_BH(bh, buffer_jbd(bh));
2278         J_ASSERT_BH(bh, jh2bh(jh) == bh);
2279         BUFFER_TRACE(bh, "remove journal_head");
2280         if (jh->b_frozen_data) {
2281                 printk(KERN_WARNING "%s: freeing b_frozen_data\n", __func__);
2282                 jbd2_free(jh->b_frozen_data, bh->b_size);
2283         }
2284         if (jh->b_committed_data) {
2285                 printk(KERN_WARNING "%s: freeing b_committed_data\n", __func__);
2286                 jbd2_free(jh->b_committed_data, bh->b_size);
2287         }
2288         bh->b_private = NULL;
2289         jh->b_bh = NULL;        /* debug, really */
2290         clear_buffer_jbd(bh);
2291         journal_free_journal_head(jh);
2292 }
2293
2294 /*
2295  * Drop a reference on the passed journal_head.  If it fell to zero then
2296  * release the journal_head from the buffer_head.
2297  */
2298 void jbd2_journal_put_journal_head(struct journal_head *jh)
2299 {
2300         struct buffer_head *bh = jh2bh(jh);
2301
2302         jbd_lock_bh_journal_head(bh);
2303         J_ASSERT_JH(jh, jh->b_jcount > 0);
2304         --jh->b_jcount;
2305         if (!jh->b_jcount) {
2306                 __journal_remove_journal_head(bh);
2307                 jbd_unlock_bh_journal_head(bh);
2308                 __brelse(bh);
2309         } else
2310                 jbd_unlock_bh_journal_head(bh);
2311 }
2312
2313 /*
2314  * Initialize jbd inode head
2315  */
2316 void jbd2_journal_init_jbd_inode(struct jbd2_inode *jinode, struct inode *inode)
2317 {
2318         jinode->i_transaction = NULL;
2319         jinode->i_next_transaction = NULL;
2320         jinode->i_vfs_inode = inode;
2321         jinode->i_flags = 0;
2322         INIT_LIST_HEAD(&jinode->i_list);
2323 }
2324
2325 /*
2326  * Function to be called before we start removing inode from memory (i.e.,
2327  * clear_inode() is a fine place to be called from). It removes inode from
2328  * transaction's lists.
2329  */
2330 void jbd2_journal_release_jbd_inode(journal_t *journal,
2331                                     struct jbd2_inode *jinode)
2332 {
2333         if (!journal)
2334                 return;
2335 restart:
2336         spin_lock(&journal->j_list_lock);
2337         /* Is commit writing out inode - we have to wait */
2338         if (test_bit(__JI_COMMIT_RUNNING, &jinode->i_flags)) {
2339                 wait_queue_head_t *wq;
2340                 DEFINE_WAIT_BIT(wait, &jinode->i_flags, __JI_COMMIT_RUNNING);
2341                 wq = bit_waitqueue(&jinode->i_flags, __JI_COMMIT_RUNNING);
2342                 prepare_to_wait(wq, &wait.wait, TASK_UNINTERRUPTIBLE);
2343                 spin_unlock(&journal->j_list_lock);
2344                 schedule();
2345                 finish_wait(wq, &wait.wait);
2346                 goto restart;
2347         }
2348
2349         if (jinode->i_transaction) {
2350                 list_del(&jinode->i_list);
2351                 jinode->i_transaction = NULL;
2352         }
2353         spin_unlock(&journal->j_list_lock);
2354 }
2355
2356 /*
2357  * debugfs tunables
2358  */
2359 #ifdef CONFIG_JBD2_DEBUG
2360 u8 jbd2_journal_enable_debug __read_mostly;
2361 EXPORT_SYMBOL(jbd2_journal_enable_debug);
2362
2363 #define JBD2_DEBUG_NAME "jbd2-debug"
2364
2365 static struct dentry *jbd2_debugfs_dir;
2366 static struct dentry *jbd2_debug;
2367
2368 static void __init jbd2_create_debugfs_entry(void)
2369 {
2370         jbd2_debugfs_dir = debugfs_create_dir("jbd2", NULL);
2371         if (jbd2_debugfs_dir)
2372                 jbd2_debug = debugfs_create_u8(JBD2_DEBUG_NAME,
2373                                                S_IRUGO | S_IWUSR,
2374                                                jbd2_debugfs_dir,
2375                                                &jbd2_journal_enable_debug);
2376 }
2377
2378 static void __exit jbd2_remove_debugfs_entry(void)
2379 {
2380         debugfs_remove(jbd2_debug);
2381         debugfs_remove(jbd2_debugfs_dir);
2382 }
2383
2384 #else
2385
2386 static void __init jbd2_create_debugfs_entry(void)
2387 {
2388 }
2389
2390 static void __exit jbd2_remove_debugfs_entry(void)
2391 {
2392 }
2393
2394 #endif
2395
2396 #ifdef CONFIG_PROC_FS
2397
2398 #define JBD2_STATS_PROC_NAME "fs/jbd2"
2399
2400 static void __init jbd2_create_jbd_stats_proc_entry(void)
2401 {
2402         proc_jbd2_stats = proc_mkdir(JBD2_STATS_PROC_NAME, NULL);
2403 }
2404
2405 static void __exit jbd2_remove_jbd_stats_proc_entry(void)
2406 {
2407         if (proc_jbd2_stats)
2408                 remove_proc_entry(JBD2_STATS_PROC_NAME, NULL);
2409 }
2410
2411 #else
2412
2413 #define jbd2_create_jbd_stats_proc_entry() do {} while (0)
2414 #define jbd2_remove_jbd_stats_proc_entry() do {} while (0)
2415
2416 #endif
2417
2418 struct kmem_cache *jbd2_handle_cache, *jbd2_inode_cache;
2419
2420 static int __init jbd2_journal_init_handle_cache(void)
2421 {
2422         jbd2_handle_cache = KMEM_CACHE(jbd2_journal_handle, SLAB_TEMPORARY);
2423         if (jbd2_handle_cache == NULL) {
2424                 printk(KERN_EMERG "JBD2: failed to create handle cache\n");
2425                 return -ENOMEM;
2426         }
2427         jbd2_inode_cache = KMEM_CACHE(jbd2_inode, 0);
2428         if (jbd2_inode_cache == NULL) {
2429                 printk(KERN_EMERG "JBD2: failed to create inode cache\n");
2430                 kmem_cache_destroy(jbd2_handle_cache);
2431                 return -ENOMEM;
2432         }
2433         return 0;
2434 }
2435
2436 static void jbd2_journal_destroy_handle_cache(void)
2437 {
2438         if (jbd2_handle_cache)
2439                 kmem_cache_destroy(jbd2_handle_cache);
2440         if (jbd2_inode_cache)
2441                 kmem_cache_destroy(jbd2_inode_cache);
2442
2443 }
2444
2445 /*
2446  * Module startup and shutdown
2447  */
2448
2449 static int __init journal_init_caches(void)
2450 {
2451         int ret;
2452
2453         ret = jbd2_journal_init_revoke_caches();
2454         if (ret == 0)
2455                 ret = jbd2_journal_init_journal_head_cache();
2456         if (ret == 0)
2457                 ret = jbd2_journal_init_handle_cache();
2458         if (ret == 0)
2459                 ret = jbd2_journal_init_transaction_cache();
2460         return ret;
2461 }
2462
2463 static void jbd2_journal_destroy_caches(void)
2464 {
2465         jbd2_journal_destroy_revoke_caches();
2466         jbd2_journal_destroy_journal_head_cache();
2467         jbd2_journal_destroy_handle_cache();
2468         jbd2_journal_destroy_transaction_cache();
2469         jbd2_journal_destroy_slabs();
2470 }
2471
2472 static int __init journal_init(void)
2473 {
2474         int ret;
2475
2476         BUILD_BUG_ON(sizeof(struct journal_superblock_s) != 1024);
2477
2478         ret = journal_init_caches();
2479         if (ret == 0) {
2480                 jbd2_create_debugfs_entry();
2481                 jbd2_create_jbd_stats_proc_entry();
2482         } else {
2483                 jbd2_journal_destroy_caches();
2484         }
2485         return ret;
2486 }
2487
2488 static void __exit journal_exit(void)
2489 {
2490 #ifdef CONFIG_JBD2_DEBUG
2491         int n = atomic_read(&nr_journal_heads);
2492         if (n)
2493                 printk(KERN_EMERG "JBD2: leaked %d journal_heads!\n", n);
2494 #endif
2495         jbd2_remove_debugfs_entry();
2496         jbd2_remove_jbd_stats_proc_entry();
2497         jbd2_journal_destroy_caches();
2498 }
2499
2500 MODULE_LICENSE("GPL");
2501 module_init(journal_init);
2502 module_exit(journal_exit);
2503