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