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