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