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