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