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