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