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