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