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