xref: /linux/fs/jbd2/transaction.c (revision 66f8e4df003e61b72fdc794ed0ec8378d74a9a4a)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * linux/fs/jbd2/transaction.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 transaction handling code; part of the ext2fs
10  * journaling system.
11  *
12  * This file manages transactions (compound commits managed by the
13  * journaling code) and handles (individual atomic operations by the
14  * filesystem).
15  */
16 
17 #include <linux/time.h>
18 #include <linux/fs.h>
19 #include <linux/jbd2.h>
20 #include <linux/errno.h>
21 #include <linux/slab.h>
22 #include <linux/timer.h>
23 #include <linux/mm.h>
24 #include <linux/highmem.h>
25 #include <linux/hrtimer.h>
26 #include <linux/backing-dev.h>
27 #include <linux/bug.h>
28 #include <linux/module.h>
29 #include <linux/sched/mm.h>
30 
31 #include <trace/events/jbd2.h>
32 
33 static void __jbd2_journal_temp_unlink_buffer(struct journal_head *jh);
34 static void __jbd2_journal_unfile_buffer(struct journal_head *jh);
35 
36 static struct kmem_cache *transaction_cache;
jbd2_journal_init_transaction_cache(void)37 int __init jbd2_journal_init_transaction_cache(void)
38 {
39 	J_ASSERT(!transaction_cache);
40 	transaction_cache = kmem_cache_create("jbd2_transaction_s",
41 					sizeof(transaction_t),
42 					0,
43 					SLAB_HWCACHE_ALIGN|SLAB_TEMPORARY,
44 					NULL);
45 	if (!transaction_cache) {
46 		pr_emerg("JBD2: failed to create transaction cache\n");
47 		return -ENOMEM;
48 	}
49 	return 0;
50 }
51 
jbd2_journal_destroy_transaction_cache(void)52 void jbd2_journal_destroy_transaction_cache(void)
53 {
54 	kmem_cache_destroy(transaction_cache);
55 	transaction_cache = NULL;
56 }
57 
jbd2_journal_free_transaction(transaction_t * transaction)58 void jbd2_journal_free_transaction(transaction_t *transaction)
59 {
60 	if (unlikely(ZERO_OR_NULL_PTR(transaction)))
61 		return;
62 	kmem_cache_free(transaction_cache, transaction);
63 }
64 
65 /*
66  * jbd2_get_transaction: obtain a new transaction_t object.
67  *
68  * Simply initialise a new transaction. Initialize it in
69  * RUNNING state and add it to the current journal (which should not
70  * have an existing running transaction: we only make a new transaction
71  * once we have started to commit the old one).
72  *
73  * Preconditions:
74  *	The journal MUST be locked.  We don't perform atomic mallocs on the
75  *	new transaction	and we can't block without protecting against other
76  *	processes trying to touch the journal while it is in transition.
77  *
78  */
79 
jbd2_get_transaction(journal_t * journal,transaction_t * transaction)80 static void jbd2_get_transaction(journal_t *journal,
81 				transaction_t *transaction)
82 {
83 	transaction->t_journal = journal;
84 	transaction->t_state = T_RUNNING;
85 	transaction->t_start_time = ktime_get();
86 	transaction->t_tid = journal->j_transaction_sequence++;
87 	transaction->t_expires = jiffies + journal->j_commit_interval;
88 	atomic_set(&transaction->t_updates, 0);
89 	atomic_set(&transaction->t_outstanding_credits,
90 		   journal->j_transaction_overhead_buffers +
91 		   atomic_read(&journal->j_reserved_credits));
92 	atomic_set(&transaction->t_outstanding_revokes, 0);
93 	atomic_set(&transaction->t_handle_count, 0);
94 	INIT_LIST_HEAD(&transaction->t_inode_list);
95 
96 	/* Set up the commit timer for the new transaction. */
97 	journal->j_commit_timer.expires = round_jiffies_up(transaction->t_expires);
98 	add_timer(&journal->j_commit_timer);
99 
100 	J_ASSERT(journal->j_running_transaction == NULL);
101 	journal->j_running_transaction = transaction;
102 	transaction->t_max_wait = 0;
103 	transaction->t_start = jiffies;
104 	transaction->t_requested = 0;
105 }
106 
107 /*
108  * Handle management.
109  *
110  * A handle_t is an object which represents a single atomic update to a
111  * filesystem, and which tracks all of the modifications which form part
112  * of that one update.
113  */
114 
115 /*
116  * t_max_wait is carefully updated here with use of atomic compare exchange.
117  * Note that there could be multiplre threads trying to do this simultaneously
118  * hence using cmpxchg to avoid any use of locks in this case.
119  */
update_t_max_wait(transaction_t * transaction,unsigned long ts)120 static inline void update_t_max_wait(transaction_t *transaction,
121 				     unsigned long ts)
122 {
123 	unsigned long oldts, newts;
124 
125 	if (time_after(transaction->t_start, ts)) {
126 		newts = jbd2_time_diff(ts, transaction->t_start);
127 		oldts = READ_ONCE(transaction->t_max_wait);
128 		while (oldts < newts)
129 			oldts = cmpxchg(&transaction->t_max_wait, oldts, newts);
130 	}
131 }
132 
133 /*
134  * Wait until running transaction passes to T_FLUSH state and new transaction
135  * can thus be started. Also starts the commit if needed. The function expects
136  * running transaction to exist and releases j_state_lock.
137  */
wait_transaction_locked(journal_t * journal)138 static void wait_transaction_locked(journal_t *journal)
139 	__releases(journal->j_state_lock)
140 {
141 	DEFINE_WAIT(wait);
142 	int need_to_start;
143 	tid_t tid = journal->j_running_transaction->t_tid;
144 
145 	prepare_to_wait_exclusive(&journal->j_wait_transaction_locked, &wait,
146 			TASK_UNINTERRUPTIBLE);
147 	need_to_start = !tid_geq(journal->j_commit_request, tid);
148 	read_unlock(&journal->j_state_lock);
149 	if (need_to_start)
150 		jbd2_log_start_commit(journal, tid);
151 	jbd2_might_wait_for_commit(journal);
152 	schedule();
153 	finish_wait(&journal->j_wait_transaction_locked, &wait);
154 }
155 
156 /*
157  * Wait until running transaction transitions from T_SWITCH to T_FLUSH
158  * state and new transaction can thus be started. The function releases
159  * j_state_lock.
160  */
wait_transaction_switching(journal_t * journal)161 static void wait_transaction_switching(journal_t *journal)
162 	__releases(journal->j_state_lock)
163 {
164 	DEFINE_WAIT(wait);
165 
166 	if (WARN_ON(!journal->j_running_transaction ||
167 		    journal->j_running_transaction->t_state != T_SWITCH)) {
168 		read_unlock(&journal->j_state_lock);
169 		return;
170 	}
171 	prepare_to_wait_exclusive(&journal->j_wait_transaction_locked, &wait,
172 			TASK_UNINTERRUPTIBLE);
173 	read_unlock(&journal->j_state_lock);
174 	/*
175 	 * We don't call jbd2_might_wait_for_commit() here as there's no
176 	 * waiting for outstanding handles happening anymore in T_SWITCH state
177 	 * and handling of reserved handles actually relies on that for
178 	 * correctness.
179 	 */
180 	schedule();
181 	finish_wait(&journal->j_wait_transaction_locked, &wait);
182 }
183 
sub_reserved_credits(journal_t * journal,int blocks)184 static void sub_reserved_credits(journal_t *journal, int blocks)
185 {
186 	atomic_sub(blocks, &journal->j_reserved_credits);
187 	wake_up(&journal->j_wait_reserved);
188 }
189 
190 /* Maximum number of blocks for user transaction payload */
jbd2_max_user_trans_buffers(journal_t * journal)191 static int jbd2_max_user_trans_buffers(journal_t *journal)
192 {
193 	return journal->j_max_transaction_buffers -
194 				journal->j_transaction_overhead_buffers;
195 }
196 
197 /*
198  * Wait until we can add credits for handle to the running transaction.  Called
199  * with j_state_lock held for reading. Returns 0 if handle joined the running
200  * transaction. Returns 1 if we had to wait, j_state_lock is dropped, and
201  * caller must retry.
202  *
203  * Note: because j_state_lock may be dropped depending on the return
204  * value, we need to fake out sparse so ti doesn't complain about a
205  * locking imbalance.  Callers of add_transaction_credits will need to
206  * make a similar accomodation.
207  */
add_transaction_credits(journal_t * journal,int blocks,int rsv_blocks)208 static int add_transaction_credits(journal_t *journal, int blocks,
209 				   int rsv_blocks)
210 __must_hold(&journal->j_state_lock)
211 {
212 	transaction_t *t = journal->j_running_transaction;
213 	int needed;
214 	int total = blocks + rsv_blocks;
215 
216 	/*
217 	 * If the current transaction is locked down for commit, wait
218 	 * for the lock to be released.
219 	 */
220 	if (t->t_state != T_RUNNING) {
221 		WARN_ON_ONCE(t->t_state >= T_FLUSH);
222 		wait_transaction_locked(journal);
223 		__acquire(&journal->j_state_lock); /* fake out sparse */
224 		return 1;
225 	}
226 
227 	/*
228 	 * If there is not enough space left in the log to write all
229 	 * potential buffers requested by this operation, we need to
230 	 * stall pending a log checkpoint to free some more log space.
231 	 */
232 	needed = atomic_add_return(total, &t->t_outstanding_credits);
233 	if (needed > journal->j_max_transaction_buffers) {
234 		/*
235 		 * If the current transaction is already too large,
236 		 * then start to commit it: we can then go back and
237 		 * attach this handle to a new transaction.
238 		 */
239 		atomic_sub(total, &t->t_outstanding_credits);
240 
241 		/*
242 		 * Is the number of reserved credits in the current transaction too
243 		 * big to fit this handle? Wait until reserved credits are freed.
244 		 */
245 		if (atomic_read(&journal->j_reserved_credits) + total >
246 		    jbd2_max_user_trans_buffers(journal)) {
247 			read_unlock(&journal->j_state_lock);
248 			jbd2_might_wait_for_commit(journal);
249 			wait_event(journal->j_wait_reserved,
250 				   atomic_read(&journal->j_reserved_credits) + total <=
251 				   jbd2_max_user_trans_buffers(journal));
252 			__acquire(&journal->j_state_lock); /* fake out sparse */
253 			return 1;
254 		}
255 
256 		wait_transaction_locked(journal);
257 		__acquire(&journal->j_state_lock); /* fake out sparse */
258 		return 1;
259 	}
260 
261 	/*
262 	 * The commit code assumes that it can get enough log space
263 	 * without forcing a checkpoint.  This is *critical* for
264 	 * correctness: a checkpoint of a buffer which is also
265 	 * associated with a committing transaction creates a deadlock,
266 	 * so commit simply cannot force through checkpoints.
267 	 *
268 	 * We must therefore ensure the necessary space in the journal
269 	 * *before* starting to dirty potentially checkpointed buffers
270 	 * in the new transaction.
271 	 */
272 	if (jbd2_log_space_left(journal) < journal->j_max_transaction_buffers) {
273 		atomic_sub(total, &t->t_outstanding_credits);
274 		read_unlock(&journal->j_state_lock);
275 		jbd2_might_wait_for_commit(journal);
276 		write_lock(&journal->j_state_lock);
277 		if (jbd2_log_space_left(journal) <
278 					journal->j_max_transaction_buffers)
279 			__jbd2_log_wait_for_space(journal);
280 		write_unlock(&journal->j_state_lock);
281 		__acquire(&journal->j_state_lock); /* fake out sparse */
282 		return 1;
283 	}
284 
285 	/* No reservation? We are done... */
286 	if (!rsv_blocks)
287 		return 0;
288 
289 	needed = atomic_add_return(rsv_blocks, &journal->j_reserved_credits);
290 	/* We allow at most half of a transaction to be reserved */
291 	if (needed > jbd2_max_user_trans_buffers(journal) / 2) {
292 		sub_reserved_credits(journal, rsv_blocks);
293 		atomic_sub(total, &t->t_outstanding_credits);
294 		read_unlock(&journal->j_state_lock);
295 		jbd2_might_wait_for_commit(journal);
296 		wait_event(journal->j_wait_reserved,
297 			 atomic_read(&journal->j_reserved_credits) + rsv_blocks
298 			 <= jbd2_max_user_trans_buffers(journal) / 2);
299 		__acquire(&journal->j_state_lock); /* fake out sparse */
300 		return 1;
301 	}
302 	return 0;
303 }
304 
305 /*
306  * start_this_handle: Given a handle, deal with any locking or stalling
307  * needed to make sure that there is enough journal space for the handle
308  * to begin.  Attach the handle to a transaction and set up the
309  * transaction's buffer credits.
310  */
311 
start_this_handle(journal_t * journal,handle_t * handle,gfp_t gfp_mask)312 static int start_this_handle(journal_t *journal, handle_t *handle,
313 			     gfp_t gfp_mask)
314 {
315 	transaction_t	*transaction, *new_transaction = NULL;
316 	int		blocks = handle->h_total_credits;
317 	int		rsv_blocks = 0;
318 	unsigned long ts = jiffies;
319 
320 	if (handle->h_rsv_handle)
321 		rsv_blocks = handle->h_rsv_handle->h_total_credits;
322 
323 	/*
324 	 * Limit the number of reserved credits to 1/2 of maximum transaction
325 	 * size and limit the number of total credits to not exceed maximum
326 	 * transaction size per operation.
327 	 */
328 	if (rsv_blocks > jbd2_max_user_trans_buffers(journal) / 2 ||
329 	    rsv_blocks + blocks > jbd2_max_user_trans_buffers(journal)) {
330 		printk(KERN_ERR "JBD2: %s wants too many credits "
331 		       "credits:%d rsv_credits:%d max:%d\n",
332 		       current->comm, blocks, rsv_blocks,
333 		       jbd2_max_user_trans_buffers(journal));
334 		WARN_ON(1);
335 		return -ENOSPC;
336 	}
337 
338 alloc_transaction:
339 	/*
340 	 * This check is racy but it is just an optimization of allocating new
341 	 * transaction early if there are high chances we'll need it. If we
342 	 * guess wrong, we'll retry or free unused transaction.
343 	 */
344 	if (!data_race(journal->j_running_transaction)) {
345 		/*
346 		 * If __GFP_FS is not present, then we may be being called from
347 		 * inside the fs writeback layer, so we MUST NOT fail.
348 		 */
349 		if ((gfp_mask & __GFP_FS) == 0)
350 			gfp_mask |= __GFP_NOFAIL;
351 		new_transaction = kmem_cache_zalloc(transaction_cache,
352 						    gfp_mask);
353 		if (!new_transaction)
354 			return -ENOMEM;
355 	}
356 
357 	jbd2_debug(3, "New handle %p going live.\n", handle);
358 
359 	/*
360 	 * We need to hold j_state_lock until t_updates has been incremented,
361 	 * for proper journal barrier handling
362 	 */
363 repeat:
364 	read_lock(&journal->j_state_lock);
365 	BUG_ON(journal->j_flags & JBD2_UNMOUNT);
366 	if (is_journal_aborted(journal) ||
367 	    (journal->j_errno != 0 && !(journal->j_flags & JBD2_ACK_ERR))) {
368 		read_unlock(&journal->j_state_lock);
369 		jbd2_journal_free_transaction(new_transaction);
370 		return -EROFS;
371 	}
372 
373 	/*
374 	 * Wait on the journal's transaction barrier if necessary. Specifically
375 	 * we allow reserved handles to proceed because otherwise commit could
376 	 * deadlock on page writeback not being able to complete.
377 	 */
378 	if (!handle->h_reserved && journal->j_barrier_count) {
379 		read_unlock(&journal->j_state_lock);
380 		wait_event(journal->j_wait_transaction_locked,
381 				journal->j_barrier_count == 0);
382 		goto repeat;
383 	}
384 
385 	if (!journal->j_running_transaction) {
386 		read_unlock(&journal->j_state_lock);
387 		if (!new_transaction)
388 			goto alloc_transaction;
389 		write_lock(&journal->j_state_lock);
390 		if (!journal->j_running_transaction &&
391 		    (handle->h_reserved || !journal->j_barrier_count)) {
392 			jbd2_get_transaction(journal, new_transaction);
393 			new_transaction = NULL;
394 		}
395 		write_unlock(&journal->j_state_lock);
396 		goto repeat;
397 	}
398 
399 	transaction = journal->j_running_transaction;
400 
401 	if (!handle->h_reserved) {
402 		/* We may have dropped j_state_lock - restart in that case */
403 		if (add_transaction_credits(journal, blocks, rsv_blocks)) {
404 			/*
405 			 * add_transaction_credits releases
406 			 * j_state_lock on a non-zero return
407 			 */
408 			__release(&journal->j_state_lock);
409 			goto repeat;
410 		}
411 	} else {
412 		/*
413 		 * We have handle reserved so we are allowed to join T_LOCKED
414 		 * transaction and we don't have to check for transaction size
415 		 * and journal space. But we still have to wait while running
416 		 * transaction is being switched to a committing one as it
417 		 * won't wait for any handles anymore.
418 		 */
419 		if (transaction->t_state == T_SWITCH) {
420 			wait_transaction_switching(journal);
421 			goto repeat;
422 		}
423 		sub_reserved_credits(journal, blocks);
424 		handle->h_reserved = 0;
425 	}
426 
427 	/* OK, account for the buffers that this operation expects to
428 	 * use and add the handle to the running transaction.
429 	 */
430 	update_t_max_wait(transaction, ts);
431 	handle->h_transaction = transaction;
432 	handle->h_requested_credits = blocks;
433 	handle->h_revoke_credits_requested = handle->h_revoke_credits;
434 	handle->h_start_jiffies = jiffies;
435 	atomic_inc(&transaction->t_updates);
436 	atomic_inc(&transaction->t_handle_count);
437 	jbd2_debug(4, "Handle %p given %d credits (total %d, free %lu)\n",
438 		  handle, blocks,
439 		  atomic_read(&transaction->t_outstanding_credits),
440 		  jbd2_log_space_left(journal));
441 	read_unlock(&journal->j_state_lock);
442 	current->journal_info = handle;
443 
444 	rwsem_acquire_read(&journal->j_trans_commit_map, 0, 0, _THIS_IP_);
445 	jbd2_journal_free_transaction(new_transaction);
446 	/*
447 	 * Ensure that no allocations done while the transaction is open are
448 	 * going to recurse back to the fs layer.
449 	 */
450 	handle->saved_alloc_context = memalloc_nofs_save();
451 	return 0;
452 }
453 
454 /* Allocate a new handle.  This should probably be in a slab... */
new_handle(int nblocks)455 static handle_t *new_handle(int nblocks)
456 {
457 	handle_t *handle = jbd2_alloc_handle(GFP_NOFS);
458 	if (!handle)
459 		return NULL;
460 	handle->h_total_credits = nblocks;
461 	handle->h_ref = 1;
462 
463 	return handle;
464 }
465 
jbd2__journal_start(journal_t * journal,int nblocks,int rsv_blocks,int revoke_records,gfp_t gfp_mask,unsigned int type,unsigned int line_no)466 handle_t *jbd2__journal_start(journal_t *journal, int nblocks, int rsv_blocks,
467 			      int revoke_records, gfp_t gfp_mask,
468 			      unsigned int type, unsigned int line_no)
469 {
470 	handle_t *handle = journal_current_handle();
471 	int err;
472 
473 	if (!journal)
474 		return ERR_PTR(-EROFS);
475 
476 	if (handle) {
477 		J_ASSERT(handle->h_transaction->t_journal == journal);
478 		handle->h_ref++;
479 		return handle;
480 	}
481 
482 	nblocks += DIV_ROUND_UP(revoke_records,
483 				journal->j_revoke_records_per_block);
484 	handle = new_handle(nblocks);
485 	if (!handle)
486 		return ERR_PTR(-ENOMEM);
487 	if (rsv_blocks) {
488 		handle_t *rsv_handle;
489 
490 		rsv_handle = new_handle(rsv_blocks);
491 		if (!rsv_handle) {
492 			jbd2_free_handle(handle);
493 			return ERR_PTR(-ENOMEM);
494 		}
495 		rsv_handle->h_reserved = 1;
496 		rsv_handle->h_journal = journal;
497 		handle->h_rsv_handle = rsv_handle;
498 	}
499 	handle->h_revoke_credits = revoke_records;
500 
501 	err = start_this_handle(journal, handle, gfp_mask);
502 	if (err < 0) {
503 		if (handle->h_rsv_handle)
504 			jbd2_free_handle(handle->h_rsv_handle);
505 		jbd2_free_handle(handle);
506 		return ERR_PTR(err);
507 	}
508 	handle->h_type = type;
509 	handle->h_line_no = line_no;
510 	trace_jbd2_handle_start(journal->j_fs_dev->bd_dev,
511 				handle->h_transaction->t_tid, type,
512 				line_no, nblocks);
513 
514 	return handle;
515 }
516 EXPORT_SYMBOL(jbd2__journal_start);
517 
518 
519 /**
520  * jbd2_journal_start() - Obtain a new handle.
521  * @journal: Journal to start transaction on.
522  * @nblocks: number of block buffer we might modify
523  *
524  * We make sure that the transaction can guarantee at least nblocks of
525  * modified buffers in the log.  We block until the log can guarantee
526  * that much space. Additionally, if rsv_blocks > 0, we also create another
527  * handle with rsv_blocks reserved blocks in the journal. This handle is
528  * stored in h_rsv_handle. It is not attached to any particular transaction
529  * and thus doesn't block transaction commit. If the caller uses this reserved
530  * handle, it has to set h_rsv_handle to NULL as otherwise jbd2_journal_stop()
531  * on the parent handle will dispose the reserved one. Reserved handle has to
532  * be converted to a normal handle using jbd2_journal_start_reserved() before
533  * it can be used.
534  *
535  * Return a pointer to a newly allocated handle, or an ERR_PTR() value
536  * on failure.
537  */
jbd2_journal_start(journal_t * journal,int nblocks)538 handle_t *jbd2_journal_start(journal_t *journal, int nblocks)
539 {
540 	return jbd2__journal_start(journal, nblocks, 0, 0, GFP_NOFS, 0, 0);
541 }
542 EXPORT_SYMBOL(jbd2_journal_start);
543 
__jbd2_journal_unreserve_handle(handle_t * handle,transaction_t * t)544 static void __jbd2_journal_unreserve_handle(handle_t *handle, transaction_t *t)
545 {
546 	journal_t *journal = handle->h_journal;
547 
548 	WARN_ON(!handle->h_reserved);
549 	sub_reserved_credits(journal, handle->h_total_credits);
550 	if (t)
551 		atomic_sub(handle->h_total_credits, &t->t_outstanding_credits);
552 }
553 
jbd2_journal_free_reserved(handle_t * handle)554 void jbd2_journal_free_reserved(handle_t *handle)
555 {
556 	journal_t *journal = handle->h_journal;
557 
558 	/* Get j_state_lock to pin running transaction if it exists */
559 	read_lock(&journal->j_state_lock);
560 	__jbd2_journal_unreserve_handle(handle, journal->j_running_transaction);
561 	read_unlock(&journal->j_state_lock);
562 	jbd2_free_handle(handle);
563 }
564 EXPORT_SYMBOL(jbd2_journal_free_reserved);
565 
566 /**
567  * jbd2_journal_start_reserved() - start reserved handle
568  * @handle: handle to start
569  * @type: for handle statistics
570  * @line_no: for handle statistics
571  *
572  * Start handle that has been previously reserved with jbd2_journal_reserve().
573  * This attaches @handle to the running transaction (or creates one if there's
574  * not transaction running). Unlike jbd2_journal_start() this function cannot
575  * block on journal commit, checkpointing, or similar stuff. It can block on
576  * memory allocation or frozen journal though.
577  *
578  * Return 0 on success, non-zero on error - handle is freed in that case.
579  */
jbd2_journal_start_reserved(handle_t * handle,unsigned int type,unsigned int line_no)580 int jbd2_journal_start_reserved(handle_t *handle, unsigned int type,
581 				unsigned int line_no)
582 {
583 	journal_t *journal = handle->h_journal;
584 	int ret = -EIO;
585 
586 	if (WARN_ON(!handle->h_reserved)) {
587 		/* Someone passed in normal handle? Just stop it. */
588 		jbd2_journal_stop(handle);
589 		return ret;
590 	}
591 	/*
592 	 * Usefulness of mixing of reserved and unreserved handles is
593 	 * questionable. So far nobody seems to need it so just error out.
594 	 */
595 	if (WARN_ON(current->journal_info)) {
596 		jbd2_journal_free_reserved(handle);
597 		return ret;
598 	}
599 
600 	handle->h_journal = NULL;
601 	/*
602 	 * GFP_NOFS is here because callers are likely from writeback or
603 	 * similarly constrained call sites
604 	 */
605 	ret = start_this_handle(journal, handle, GFP_NOFS);
606 	if (ret < 0) {
607 		handle->h_journal = journal;
608 		jbd2_journal_free_reserved(handle);
609 		return ret;
610 	}
611 	handle->h_type = type;
612 	handle->h_line_no = line_no;
613 	trace_jbd2_handle_start(journal->j_fs_dev->bd_dev,
614 				handle->h_transaction->t_tid, type,
615 				line_no, handle->h_total_credits);
616 	return 0;
617 }
618 EXPORT_SYMBOL(jbd2_journal_start_reserved);
619 
620 /**
621  * jbd2_journal_extend() - extend buffer credits.
622  * @handle:  handle to 'extend'
623  * @nblocks: nr blocks to try to extend by.
624  * @revoke_records: number of revoke records to try to extend by.
625  *
626  * Some transactions, such as large extends and truncates, can be done
627  * atomically all at once or in several stages.  The operation requests
628  * a credit for a number of buffer modifications in advance, but can
629  * extend its credit if it needs more.
630  *
631  * jbd2_journal_extend tries to give the running handle more buffer credits.
632  * It does not guarantee that allocation - this is a best-effort only.
633  * The calling process MUST be able to deal cleanly with a failure to
634  * extend here.
635  *
636  * Return 0 on success, non-zero on failure.
637  *
638  * return code < 0 implies an error
639  * return code > 0 implies normal transaction-full status.
640  */
jbd2_journal_extend(handle_t * handle,int nblocks,int revoke_records)641 int jbd2_journal_extend(handle_t *handle, int nblocks, int revoke_records)
642 {
643 	transaction_t *transaction = handle->h_transaction;
644 	journal_t *journal;
645 	int result;
646 	int wanted;
647 
648 	if (is_handle_aborted(handle))
649 		return -EROFS;
650 	journal = transaction->t_journal;
651 
652 	result = 1;
653 
654 	read_lock(&journal->j_state_lock);
655 
656 	/* Don't extend a locked-down transaction! */
657 	if (transaction->t_state != T_RUNNING) {
658 		jbd2_debug(3, "denied handle %p %d blocks: "
659 			  "transaction not running\n", handle, nblocks);
660 		goto error_out;
661 	}
662 
663 	nblocks += DIV_ROUND_UP(
664 			handle->h_revoke_credits_requested + revoke_records,
665 			journal->j_revoke_records_per_block) -
666 		DIV_ROUND_UP(
667 			handle->h_revoke_credits_requested,
668 			journal->j_revoke_records_per_block);
669 	wanted = atomic_add_return(nblocks,
670 				   &transaction->t_outstanding_credits);
671 
672 	if (wanted > journal->j_max_transaction_buffers) {
673 		jbd2_debug(3, "denied handle %p %d blocks: "
674 			  "transaction too large\n", handle, nblocks);
675 		atomic_sub(nblocks, &transaction->t_outstanding_credits);
676 		goto error_out;
677 	}
678 
679 	trace_jbd2_handle_extend(journal->j_fs_dev->bd_dev,
680 				 transaction->t_tid,
681 				 handle->h_type, handle->h_line_no,
682 				 handle->h_total_credits,
683 				 nblocks);
684 
685 	handle->h_total_credits += nblocks;
686 	handle->h_requested_credits += nblocks;
687 	handle->h_revoke_credits += revoke_records;
688 	handle->h_revoke_credits_requested += revoke_records;
689 	result = 0;
690 
691 	jbd2_debug(3, "extended handle %p by %d\n", handle, nblocks);
692 error_out:
693 	read_unlock(&journal->j_state_lock);
694 	return result;
695 }
696 
stop_this_handle(handle_t * handle)697 static void stop_this_handle(handle_t *handle)
698 {
699 	transaction_t *transaction = handle->h_transaction;
700 	journal_t *journal = transaction->t_journal;
701 	int revokes;
702 
703 	J_ASSERT(journal_current_handle() == handle);
704 	J_ASSERT(atomic_read(&transaction->t_updates) > 0);
705 	current->journal_info = NULL;
706 	/*
707 	 * Subtract necessary revoke descriptor blocks from handle credits. We
708 	 * take care to account only for revoke descriptor blocks the
709 	 * transaction will really need as large sequences of transactions with
710 	 * small numbers of revokes are relatively common.
711 	 */
712 	revokes = handle->h_revoke_credits_requested - handle->h_revoke_credits;
713 	if (revokes) {
714 		int t_revokes, revoke_descriptors;
715 		int rr_per_blk = journal->j_revoke_records_per_block;
716 
717 		WARN_ON_ONCE(DIV_ROUND_UP(revokes, rr_per_blk)
718 				> handle->h_total_credits);
719 		t_revokes = atomic_add_return(revokes,
720 				&transaction->t_outstanding_revokes);
721 		revoke_descriptors =
722 			DIV_ROUND_UP(t_revokes, rr_per_blk) -
723 			DIV_ROUND_UP(t_revokes - revokes, rr_per_blk);
724 		handle->h_total_credits -= revoke_descriptors;
725 	}
726 	atomic_sub(handle->h_total_credits,
727 		   &transaction->t_outstanding_credits);
728 	if (handle->h_rsv_handle)
729 		__jbd2_journal_unreserve_handle(handle->h_rsv_handle,
730 						transaction);
731 	if (atomic_dec_and_test(&transaction->t_updates))
732 		wake_up(&journal->j_wait_updates);
733 
734 	rwsem_release(&journal->j_trans_commit_map, _THIS_IP_);
735 	/*
736 	 * Scope of the GFP_NOFS context is over here and so we can restore the
737 	 * original alloc context.
738 	 */
739 	memalloc_nofs_restore(handle->saved_alloc_context);
740 }
741 
742 /**
743  * jbd2__journal_restart() - restart a handle .
744  * @handle:  handle to restart
745  * @nblocks: nr credits requested
746  * @revoke_records: number of revoke record credits requested
747  * @gfp_mask: memory allocation flags (for start_this_handle)
748  *
749  * Restart a handle for a multi-transaction filesystem
750  * operation.
751  *
752  * If the jbd2_journal_extend() call above fails to grant new buffer credits
753  * to a running handle, a call to jbd2_journal_restart will commit the
754  * handle's transaction so far and reattach the handle to a new
755  * transaction capable of guaranteeing the requested number of
756  * credits. We preserve reserved handle if there's any attached to the
757  * passed in handle.
758  */
jbd2__journal_restart(handle_t * handle,int nblocks,int revoke_records,gfp_t gfp_mask)759 int jbd2__journal_restart(handle_t *handle, int nblocks, int revoke_records,
760 			  gfp_t gfp_mask)
761 {
762 	transaction_t *transaction = handle->h_transaction;
763 	journal_t *journal;
764 	tid_t		tid;
765 	int		need_to_start;
766 	int		ret;
767 
768 	/* If we've had an abort of any type, don't even think about
769 	 * actually doing the restart! */
770 	if (is_handle_aborted(handle))
771 		return 0;
772 	journal = transaction->t_journal;
773 	tid = transaction->t_tid;
774 
775 	/*
776 	 * First unlink the handle from its current transaction, and start the
777 	 * commit on that.
778 	 */
779 	jbd2_debug(2, "restarting handle %p\n", handle);
780 	stop_this_handle(handle);
781 	handle->h_transaction = NULL;
782 
783 	/*
784 	 * TODO: If we use READ_ONCE / WRITE_ONCE for j_commit_request we can
785  	 * get rid of pointless j_state_lock traffic like this.
786 	 */
787 	read_lock(&journal->j_state_lock);
788 	need_to_start = !tid_geq(journal->j_commit_request, tid);
789 	read_unlock(&journal->j_state_lock);
790 	if (need_to_start)
791 		jbd2_log_start_commit(journal, tid);
792 	handle->h_total_credits = nblocks +
793 		DIV_ROUND_UP(revoke_records,
794 			     journal->j_revoke_records_per_block);
795 	handle->h_revoke_credits = revoke_records;
796 	ret = start_this_handle(journal, handle, gfp_mask);
797 	trace_jbd2_handle_restart(journal->j_fs_dev->bd_dev,
798 				 ret ? 0 : handle->h_transaction->t_tid,
799 				 handle->h_type, handle->h_line_no,
800 				 handle->h_total_credits);
801 	return ret;
802 }
803 EXPORT_SYMBOL(jbd2__journal_restart);
804 
805 
jbd2_journal_restart(handle_t * handle,int nblocks)806 int jbd2_journal_restart(handle_t *handle, int nblocks)
807 {
808 	return jbd2__journal_restart(handle, nblocks, 0, GFP_NOFS);
809 }
810 EXPORT_SYMBOL(jbd2_journal_restart);
811 
812 /*
813  * Waits for any outstanding t_updates to finish.
814  * This is called with write j_state_lock held.
815  */
jbd2_journal_wait_updates(journal_t * journal)816 void jbd2_journal_wait_updates(journal_t *journal)
817 {
818 	DEFINE_WAIT(wait);
819 
820 	while (1) {
821 		/*
822 		 * Note that the running transaction can get freed under us if
823 		 * this transaction is getting committed in
824 		 * jbd2_journal_commit_transaction() ->
825 		 * jbd2_journal_free_transaction(). This can only happen when we
826 		 * release j_state_lock -> schedule() -> acquire j_state_lock.
827 		 * Hence we should everytime retrieve new j_running_transaction
828 		 * value (after j_state_lock release acquire cycle), else it may
829 		 * lead to use-after-free of old freed transaction.
830 		 */
831 		transaction_t *transaction = journal->j_running_transaction;
832 
833 		if (!transaction)
834 			break;
835 
836 		prepare_to_wait(&journal->j_wait_updates, &wait,
837 				TASK_UNINTERRUPTIBLE);
838 		if (!atomic_read(&transaction->t_updates)) {
839 			finish_wait(&journal->j_wait_updates, &wait);
840 			break;
841 		}
842 		write_unlock(&journal->j_state_lock);
843 		schedule();
844 		finish_wait(&journal->j_wait_updates, &wait);
845 		write_lock(&journal->j_state_lock);
846 	}
847 }
848 
849 /**
850  * jbd2_journal_lock_updates () - establish a transaction barrier.
851  * @journal:  Journal to establish a barrier on.
852  *
853  * This locks out any further updates from being started, and blocks
854  * until all existing updates have completed, returning only once the
855  * journal is in a quiescent state with no updates running.
856  *
857  * The journal lock should not be held on entry.
858  */
jbd2_journal_lock_updates(journal_t * journal)859 void jbd2_journal_lock_updates(journal_t *journal)
860 {
861 	jbd2_might_wait_for_commit(journal);
862 
863 	write_lock(&journal->j_state_lock);
864 	++journal->j_barrier_count;
865 
866 	/* Wait until there are no reserved handles */
867 	if (atomic_read(&journal->j_reserved_credits)) {
868 		write_unlock(&journal->j_state_lock);
869 		wait_event(journal->j_wait_reserved,
870 			   atomic_read(&journal->j_reserved_credits) == 0);
871 		write_lock(&journal->j_state_lock);
872 	}
873 
874 	/* Wait until there are no running t_updates */
875 	jbd2_journal_wait_updates(journal);
876 
877 	write_unlock(&journal->j_state_lock);
878 
879 	/*
880 	 * We have now established a barrier against other normal updates, but
881 	 * we also need to barrier against other jbd2_journal_lock_updates() calls
882 	 * to make sure that we serialise special journal-locked operations
883 	 * too.
884 	 */
885 	mutex_lock(&journal->j_barrier);
886 }
887 
888 /**
889  * jbd2_journal_unlock_updates () - release barrier
890  * @journal:  Journal to release the barrier on.
891  *
892  * Release a transaction barrier obtained with jbd2_journal_lock_updates().
893  *
894  * Should be called without the journal lock held.
895  */
jbd2_journal_unlock_updates(journal_t * journal)896 void jbd2_journal_unlock_updates (journal_t *journal)
897 {
898 	J_ASSERT(journal->j_barrier_count != 0);
899 
900 	mutex_unlock(&journal->j_barrier);
901 	write_lock(&journal->j_state_lock);
902 	--journal->j_barrier_count;
903 	write_unlock(&journal->j_state_lock);
904 	wake_up_all(&journal->j_wait_transaction_locked);
905 }
906 
warn_dirty_buffer(struct buffer_head * bh)907 static void warn_dirty_buffer(struct buffer_head *bh)
908 {
909 	printk(KERN_WARNING
910 	       "JBD2: Spotted dirty metadata buffer (dev = %pg, blocknr = %llu). "
911 	       "There's a risk of filesystem corruption in case of system "
912 	       "crash.\n",
913 	       bh->b_bdev, (unsigned long long)bh->b_blocknr);
914 }
915 
916 /* Call t_frozen trigger and copy buffer data into jh->b_frozen_data. */
jbd2_freeze_jh_data(struct journal_head * jh)917 static void jbd2_freeze_jh_data(struct journal_head *jh)
918 {
919 	char *source;
920 	struct buffer_head *bh = jh2bh(jh);
921 
922 	J_EXPECT_JH(jh, buffer_uptodate(bh), "Possible IO failure.\n");
923 	source = kmap_local_folio(bh->b_folio, bh_offset(bh));
924 	/* Fire data frozen trigger just before we copy the data */
925 	jbd2_buffer_frozen_trigger(jh, source, jh->b_triggers);
926 	memcpy(jh->b_frozen_data, source, bh->b_size);
927 	kunmap_local(source);
928 
929 	/*
930 	 * Now that the frozen data is saved off, we need to store any matching
931 	 * triggers.
932 	 */
933 	jh->b_frozen_triggers = jh->b_triggers;
934 }
935 
936 /*
937  * If the buffer is already part of the current transaction, then there
938  * is nothing we need to do.  If it is already part of a prior
939  * transaction which we are still committing to disk, then we need to
940  * make sure that we do not overwrite the old copy: we do copy-out to
941  * preserve the copy going to disk.  We also account the buffer against
942  * the handle's metadata buffer credits (unless the buffer is already
943  * part of the transaction, that is).
944  *
945  */
946 static int
do_get_write_access(handle_t * handle,struct journal_head * jh,int force_copy)947 do_get_write_access(handle_t *handle, struct journal_head *jh,
948 			int force_copy)
949 {
950 	struct buffer_head *bh;
951 	transaction_t *transaction = handle->h_transaction;
952 	journal_t *journal;
953 	int error;
954 	char *frozen_buffer = NULL;
955 	unsigned long start_lock, time_lock;
956 
957 	journal = transaction->t_journal;
958 
959 	jbd2_debug(5, "journal_head %p, force_copy %d\n", jh, force_copy);
960 
961 	JBUFFER_TRACE(jh, "entry");
962 repeat:
963 	bh = jh2bh(jh);
964 
965 	/* @@@ Need to check for errors here at some point. */
966 
967  	start_lock = jiffies;
968 	lock_buffer(bh);
969 	spin_lock(&jh->b_state_lock);
970 
971 	/* If it takes too long to lock the buffer, trace it */
972 	time_lock = jbd2_time_diff(start_lock, jiffies);
973 	if (time_lock > HZ/10)
974 		trace_jbd2_lock_buffer_stall(bh->b_bdev->bd_dev,
975 			jiffies_to_msecs(time_lock));
976 
977 	/* We now hold the buffer lock so it is safe to query the buffer
978 	 * state.  Is the buffer dirty?
979 	 *
980 	 * If so, there are two possibilities.  The buffer may be
981 	 * non-journaled, and undergoing a quite legitimate writeback.
982 	 * Otherwise, it is journaled, and we don't expect dirty buffers
983 	 * in that state (the buffers should be marked JBD_Dirty
984 	 * instead.)  So either the IO is being done under our own
985 	 * control and this is a bug, or it's a third party IO such as
986 	 * dump(8) (which may leave the buffer scheduled for read ---
987 	 * ie. locked but not dirty) or tune2fs (which may actually have
988 	 * the buffer dirtied, ugh.)  */
989 
990 	if (buffer_dirty(bh) && jh->b_transaction) {
991 		warn_dirty_buffer(bh);
992 		/*
993 		 * We need to clean the dirty flag and we must do it under the
994 		 * buffer lock to be sure we don't race with running write-out.
995 		 */
996 		JBUFFER_TRACE(jh, "Journalling dirty buffer");
997 		clear_buffer_dirty(bh);
998 		/*
999 		 * The buffer is going to be added to BJ_Reserved list now and
1000 		 * nothing guarantees jbd2_journal_dirty_metadata() will be
1001 		 * ever called for it. So we need to set jbddirty bit here to
1002 		 * make sure the buffer is dirtied and written out when the
1003 		 * journaling machinery is done with it.
1004 		 */
1005 		set_buffer_jbddirty(bh);
1006 	}
1007 
1008 	error = -EROFS;
1009 	if (is_handle_aborted(handle)) {
1010 		spin_unlock(&jh->b_state_lock);
1011 		unlock_buffer(bh);
1012 		goto out;
1013 	}
1014 	error = 0;
1015 
1016 	/*
1017 	 * The buffer is already part of this transaction if b_transaction or
1018 	 * b_next_transaction points to it
1019 	 */
1020 	if (jh->b_transaction == transaction ||
1021 	    jh->b_next_transaction == transaction) {
1022 		unlock_buffer(bh);
1023 		goto done;
1024 	}
1025 
1026 	/*
1027 	 * this is the first time this transaction is touching this buffer,
1028 	 * reset the modified flag
1029 	 */
1030 	jh->b_modified = 0;
1031 
1032 	/*
1033 	 * If the buffer is not journaled right now, we need to make sure it
1034 	 * doesn't get written to disk before the caller actually commits the
1035 	 * new data
1036 	 */
1037 	if (!jh->b_transaction) {
1038 		JBUFFER_TRACE(jh, "no transaction");
1039 		J_ASSERT_JH(jh, !jh->b_next_transaction);
1040 		JBUFFER_TRACE(jh, "file as BJ_Reserved");
1041 		/*
1042 		 * Make sure all stores to jh (b_modified, b_frozen_data) are
1043 		 * visible before attaching it to the running transaction.
1044 		 * Paired with barrier in jbd2_write_access_granted()
1045 		 */
1046 		smp_wmb();
1047 		spin_lock(&journal->j_list_lock);
1048 		if (test_clear_buffer_dirty(bh)) {
1049 			/*
1050 			 * Execute buffer dirty clearing and jh->b_transaction
1051 			 * assignment under journal->j_list_lock locked to
1052 			 * prevent bh being removed from checkpoint list if
1053 			 * the buffer is in an intermediate state (not dirty
1054 			 * and jh->b_transaction is NULL).
1055 			 */
1056 			JBUFFER_TRACE(jh, "Journalling dirty buffer");
1057 			set_buffer_jbddirty(bh);
1058 		}
1059 		__jbd2_journal_file_buffer(jh, transaction, BJ_Reserved);
1060 		spin_unlock(&journal->j_list_lock);
1061 		unlock_buffer(bh);
1062 		goto done;
1063 	}
1064 	unlock_buffer(bh);
1065 
1066 	/*
1067 	 * If there is already a copy-out version of this buffer, then we don't
1068 	 * need to make another one
1069 	 */
1070 	if (jh->b_frozen_data) {
1071 		JBUFFER_TRACE(jh, "has frozen data");
1072 		J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
1073 		goto attach_next;
1074 	}
1075 
1076 	JBUFFER_TRACE(jh, "owned by older transaction");
1077 	J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
1078 	J_ASSERT_JH(jh, jh->b_transaction == journal->j_committing_transaction);
1079 
1080 	/*
1081 	 * There is one case we have to be very careful about.  If the
1082 	 * committing transaction is currently writing this buffer out to disk
1083 	 * and has NOT made a copy-out, then we cannot modify the buffer
1084 	 * contents at all right now.  The essence of copy-out is that it is
1085 	 * the extra copy, not the primary copy, which gets journaled.  If the
1086 	 * primary copy is already going to disk then we cannot do copy-out
1087 	 * here.
1088 	 */
1089 	if (buffer_shadow(bh)) {
1090 		JBUFFER_TRACE(jh, "on shadow: sleep");
1091 		spin_unlock(&jh->b_state_lock);
1092 		wait_on_bit_io(&bh->b_state, BH_Shadow, TASK_UNINTERRUPTIBLE);
1093 		goto repeat;
1094 	}
1095 
1096 	/*
1097 	 * Only do the copy if the currently-owning transaction still needs it.
1098 	 * If buffer isn't on BJ_Metadata list, the committing transaction is
1099 	 * past that stage (here we use the fact that BH_Shadow is set under
1100 	 * bh_state lock together with refiling to BJ_Shadow list and at this
1101 	 * point we know the buffer doesn't have BH_Shadow set).
1102 	 *
1103 	 * Subtle point, though: if this is a get_undo_access, then we will be
1104 	 * relying on the frozen_data to contain the new value of the
1105 	 * committed_data record after the transaction, so we HAVE to force the
1106 	 * frozen_data copy in that case.
1107 	 */
1108 	if (jh->b_jlist == BJ_Metadata || force_copy) {
1109 		JBUFFER_TRACE(jh, "generate frozen data");
1110 		if (!frozen_buffer) {
1111 			JBUFFER_TRACE(jh, "allocate memory for buffer");
1112 			spin_unlock(&jh->b_state_lock);
1113 			frozen_buffer = jbd2_alloc(jh2bh(jh)->b_size,
1114 						   GFP_NOFS | __GFP_NOFAIL);
1115 			goto repeat;
1116 		}
1117 		jh->b_frozen_data = frozen_buffer;
1118 		frozen_buffer = NULL;
1119 		jbd2_freeze_jh_data(jh);
1120 	}
1121 attach_next:
1122 	/*
1123 	 * Make sure all stores to jh (b_modified, b_frozen_data) are visible
1124 	 * before attaching it to the running transaction. Paired with barrier
1125 	 * in jbd2_write_access_granted()
1126 	 */
1127 	smp_wmb();
1128 	jh->b_next_transaction = transaction;
1129 
1130 done:
1131 	spin_unlock(&jh->b_state_lock);
1132 
1133 	/*
1134 	 * If we are about to journal a buffer, then any revoke pending on it is
1135 	 * no longer valid
1136 	 */
1137 	jbd2_journal_cancel_revoke(handle, jh);
1138 
1139 out:
1140 	if (unlikely(frozen_buffer))	/* It's usually NULL */
1141 		jbd2_free(frozen_buffer, bh->b_size);
1142 
1143 	JBUFFER_TRACE(jh, "exit");
1144 	return error;
1145 }
1146 
1147 /* Fast check whether buffer is already attached to the required transaction */
jbd2_write_access_granted(handle_t * handle,struct buffer_head * bh,bool undo)1148 static bool jbd2_write_access_granted(handle_t *handle, struct buffer_head *bh,
1149 							bool undo)
1150 {
1151 	struct journal_head *jh;
1152 	bool ret = false;
1153 
1154 	/* Dirty buffers require special handling... */
1155 	if (buffer_dirty(bh))
1156 		return false;
1157 
1158 	/*
1159 	 * RCU protects us from dereferencing freed pages. So the checks we do
1160 	 * are guaranteed not to oops. However the jh slab object can get freed
1161 	 * & reallocated while we work with it. So we have to be careful. When
1162 	 * we see jh attached to the running transaction, we know it must stay
1163 	 * so until the transaction is committed. Thus jh won't be freed and
1164 	 * will be attached to the same bh while we run.  However it can
1165 	 * happen jh gets freed, reallocated, and attached to the transaction
1166 	 * just after we get pointer to it from bh. So we have to be careful
1167 	 * and recheck jh still belongs to our bh before we return success.
1168 	 */
1169 	rcu_read_lock();
1170 	if (!buffer_jbd(bh))
1171 		goto out;
1172 	/* This should be bh2jh() but that doesn't work with inline functions */
1173 	jh = READ_ONCE(bh->b_private);
1174 	if (!jh)
1175 		goto out;
1176 	/* For undo access buffer must have data copied */
1177 	if (undo && !jh->b_committed_data)
1178 		goto out;
1179 	if (READ_ONCE(jh->b_transaction) != handle->h_transaction &&
1180 	    READ_ONCE(jh->b_next_transaction) != handle->h_transaction)
1181 		goto out;
1182 	/*
1183 	 * There are two reasons for the barrier here:
1184 	 * 1) Make sure to fetch b_bh after we did previous checks so that we
1185 	 * detect when jh went through free, realloc, attach to transaction
1186 	 * while we were checking. Paired with implicit barrier in that path.
1187 	 * 2) So that access to bh done after jbd2_write_access_granted()
1188 	 * doesn't get reordered and see inconsistent state of concurrent
1189 	 * do_get_write_access().
1190 	 */
1191 	smp_mb();
1192 	if (unlikely(jh->b_bh != bh))
1193 		goto out;
1194 	ret = true;
1195 out:
1196 	rcu_read_unlock();
1197 	return ret;
1198 }
1199 
1200 /**
1201  * jbd2_journal_get_write_access() - notify intent to modify a buffer
1202  *				     for metadata (not data) update.
1203  * @handle: transaction to add buffer modifications to
1204  * @bh:     bh to be used for metadata writes
1205  *
1206  * Returns: error code or 0 on success.
1207  *
1208  * In full data journalling mode the buffer may be of type BJ_AsyncData,
1209  * because we're ``write()ing`` a buffer which is also part of a shared mapping.
1210  */
1211 
jbd2_journal_get_write_access(handle_t * handle,struct buffer_head * bh)1212 int jbd2_journal_get_write_access(handle_t *handle, struct buffer_head *bh)
1213 {
1214 	struct journal_head *jh;
1215 	journal_t *journal;
1216 	int rc;
1217 
1218 	if (is_handle_aborted(handle))
1219 		return -EROFS;
1220 
1221 	journal = handle->h_transaction->t_journal;
1222 	if (jbd2_check_fs_dev_write_error(journal)) {
1223 		/*
1224 		 * If the fs dev has writeback errors, it may have failed
1225 		 * to async write out metadata buffers in the background.
1226 		 * In this case, we could read old data from disk and write
1227 		 * it out again, which may lead to on-disk filesystem
1228 		 * inconsistency. Aborting journal can avoid it happen.
1229 		 */
1230 		jbd2_journal_abort(journal, -EIO);
1231 		return -EIO;
1232 	}
1233 
1234 	if (jbd2_write_access_granted(handle, bh, false))
1235 		return 0;
1236 
1237 	jh = jbd2_journal_add_journal_head(bh);
1238 	/* We do not want to get caught playing with fields which the
1239 	 * log thread also manipulates.  Make sure that the buffer
1240 	 * completes any outstanding IO before proceeding. */
1241 	rc = do_get_write_access(handle, jh, 0);
1242 	jbd2_journal_put_journal_head(jh);
1243 	return rc;
1244 }
1245 
1246 
1247 /*
1248  * When the user wants to journal a newly created buffer_head
1249  * (ie. getblk() returned a new buffer and we are going to populate it
1250  * manually rather than reading off disk), then we need to keep the
1251  * buffer_head locked until it has been completely filled with new
1252  * data.  In this case, we should be able to make the assertion that
1253  * the bh is not already part of an existing transaction.
1254  *
1255  * The buffer should already be locked by the caller by this point.
1256  * There is no lock ranking violation: it was a newly created,
1257  * unlocked buffer beforehand. */
1258 
1259 /**
1260  * jbd2_journal_get_create_access () - notify intent to use newly created bh
1261  * @handle: transaction to new buffer to
1262  * @bh: new buffer.
1263  *
1264  * Call this if you create a new bh.
1265  */
jbd2_journal_get_create_access(handle_t * handle,struct buffer_head * bh)1266 int jbd2_journal_get_create_access(handle_t *handle, struct buffer_head *bh)
1267 {
1268 	transaction_t *transaction = handle->h_transaction;
1269 	journal_t *journal;
1270 	struct journal_head *jh = jbd2_journal_add_journal_head(bh);
1271 	int err;
1272 
1273 	jbd2_debug(5, "journal_head %p\n", jh);
1274 	err = -EROFS;
1275 	if (is_handle_aborted(handle))
1276 		goto out;
1277 	journal = transaction->t_journal;
1278 	err = 0;
1279 
1280 	JBUFFER_TRACE(jh, "entry");
1281 	/*
1282 	 * The buffer may already belong to this transaction due to pre-zeroing
1283 	 * in the filesystem's new_block code.  It may also be on the previous,
1284 	 * committing transaction's lists, but it HAS to be in Forget state in
1285 	 * that case: the transaction must have deleted the buffer for it to be
1286 	 * reused here.
1287 	 */
1288 	spin_lock(&jh->b_state_lock);
1289 	J_ASSERT_JH(jh, (jh->b_transaction == transaction ||
1290 		jh->b_transaction == NULL ||
1291 		(jh->b_transaction == journal->j_committing_transaction &&
1292 			  jh->b_jlist == BJ_Forget)));
1293 
1294 	J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
1295 	J_ASSERT_JH(jh, buffer_locked(jh2bh(jh)));
1296 
1297 	if (jh->b_transaction == NULL) {
1298 		/*
1299 		 * Previous jbd2_journal_forget() could have left the buffer
1300 		 * with jbddirty bit set because it was being committed. When
1301 		 * the commit finished, we've filed the buffer for
1302 		 * checkpointing and marked it dirty. Now we are reallocating
1303 		 * the buffer so the transaction freeing it must have
1304 		 * committed and so it's safe to clear the dirty bit.
1305 		 */
1306 		clear_buffer_dirty(jh2bh(jh));
1307 		/* first access by this transaction */
1308 		jh->b_modified = 0;
1309 
1310 		JBUFFER_TRACE(jh, "file as BJ_Reserved");
1311 		spin_lock(&journal->j_list_lock);
1312 		__jbd2_journal_file_buffer(jh, transaction, BJ_Reserved);
1313 		spin_unlock(&journal->j_list_lock);
1314 	} else if (jh->b_transaction == journal->j_committing_transaction) {
1315 		/* first access by this transaction */
1316 		jh->b_modified = 0;
1317 
1318 		JBUFFER_TRACE(jh, "set next transaction");
1319 		spin_lock(&journal->j_list_lock);
1320 		jh->b_next_transaction = transaction;
1321 		spin_unlock(&journal->j_list_lock);
1322 	}
1323 	spin_unlock(&jh->b_state_lock);
1324 
1325 	/*
1326 	 * akpm: I added this.  ext3_alloc_branch can pick up new indirect
1327 	 * blocks which contain freed but then revoked metadata.  We need
1328 	 * to cancel the revoke in case we end up freeing it yet again
1329 	 * and the reallocating as data - this would cause a second revoke,
1330 	 * which hits an assertion error.
1331 	 */
1332 	JBUFFER_TRACE(jh, "cancelling revoke");
1333 	jbd2_journal_cancel_revoke(handle, jh);
1334 out:
1335 	jbd2_journal_put_journal_head(jh);
1336 	return err;
1337 }
1338 
1339 /**
1340  * jbd2_journal_get_undo_access() -  Notify intent to modify metadata with
1341  *     non-rewindable consequences
1342  * @handle: transaction
1343  * @bh: buffer to undo
1344  *
1345  * Sometimes there is a need to distinguish between metadata which has
1346  * been committed to disk and that which has not.  The ext3fs code uses
1347  * this for freeing and allocating space, we have to make sure that we
1348  * do not reuse freed space until the deallocation has been committed,
1349  * since if we overwrote that space we would make the delete
1350  * un-rewindable in case of a crash.
1351  *
1352  * To deal with that, jbd2_journal_get_undo_access requests write access to a
1353  * buffer for parts of non-rewindable operations such as delete
1354  * operations on the bitmaps.  The journaling code must keep a copy of
1355  * the buffer's contents prior to the undo_access call until such time
1356  * as we know that the buffer has definitely been committed to disk.
1357  *
1358  * We never need to know which transaction the committed data is part
1359  * of, buffers touched here are guaranteed to be dirtied later and so
1360  * will be committed to a new transaction in due course, at which point
1361  * we can discard the old committed data pointer.
1362  *
1363  * Returns error number or 0 on success.
1364  */
jbd2_journal_get_undo_access(handle_t * handle,struct buffer_head * bh)1365 int jbd2_journal_get_undo_access(handle_t *handle, struct buffer_head *bh)
1366 {
1367 	int err;
1368 	struct journal_head *jh;
1369 	char *committed_data = NULL;
1370 
1371 	if (is_handle_aborted(handle))
1372 		return -EROFS;
1373 
1374 	if (jbd2_write_access_granted(handle, bh, true))
1375 		return 0;
1376 
1377 	jh = jbd2_journal_add_journal_head(bh);
1378 	JBUFFER_TRACE(jh, "entry");
1379 
1380 	/*
1381 	 * Do this first --- it can drop the journal lock, so we want to
1382 	 * make sure that obtaining the committed_data is done
1383 	 * atomically wrt. completion of any outstanding commits.
1384 	 */
1385 	err = do_get_write_access(handle, jh, 1);
1386 	if (err)
1387 		goto out;
1388 
1389 repeat:
1390 	if (!jh->b_committed_data)
1391 		committed_data = jbd2_alloc(jh2bh(jh)->b_size,
1392 					    GFP_NOFS|__GFP_NOFAIL);
1393 
1394 	spin_lock(&jh->b_state_lock);
1395 	if (!jh->b_committed_data) {
1396 		/* Copy out the current buffer contents into the
1397 		 * preserved, committed copy. */
1398 		JBUFFER_TRACE(jh, "generate b_committed data");
1399 		if (!committed_data) {
1400 			spin_unlock(&jh->b_state_lock);
1401 			goto repeat;
1402 		}
1403 
1404 		jh->b_committed_data = committed_data;
1405 		committed_data = NULL;
1406 		memcpy(jh->b_committed_data, bh->b_data, bh->b_size);
1407 	}
1408 	spin_unlock(&jh->b_state_lock);
1409 out:
1410 	jbd2_journal_put_journal_head(jh);
1411 	if (unlikely(committed_data))
1412 		jbd2_free(committed_data, bh->b_size);
1413 	return err;
1414 }
1415 
1416 /**
1417  * jbd2_journal_set_triggers() - Add triggers for commit writeout
1418  * @bh: buffer to trigger on
1419  * @type: struct jbd2_buffer_trigger_type containing the trigger(s).
1420  *
1421  * Set any triggers on this journal_head.  This is always safe, because
1422  * triggers for a committing buffer will be saved off, and triggers for
1423  * a running transaction will match the buffer in that transaction.
1424  *
1425  * Call with NULL to clear the triggers.
1426  */
jbd2_journal_set_triggers(struct buffer_head * bh,struct jbd2_buffer_trigger_type * type)1427 void jbd2_journal_set_triggers(struct buffer_head *bh,
1428 			       struct jbd2_buffer_trigger_type *type)
1429 {
1430 	struct journal_head *jh = jbd2_journal_grab_journal_head(bh);
1431 
1432 	if (WARN_ON_ONCE(!jh))
1433 		return;
1434 	jh->b_triggers = type;
1435 	jbd2_journal_put_journal_head(jh);
1436 }
1437 
jbd2_buffer_frozen_trigger(struct journal_head * jh,void * mapped_data,struct jbd2_buffer_trigger_type * triggers)1438 void jbd2_buffer_frozen_trigger(struct journal_head *jh, void *mapped_data,
1439 				struct jbd2_buffer_trigger_type *triggers)
1440 {
1441 	struct buffer_head *bh = jh2bh(jh);
1442 
1443 	if (!triggers || !triggers->t_frozen)
1444 		return;
1445 
1446 	triggers->t_frozen(triggers, bh, mapped_data, bh->b_size);
1447 }
1448 
jbd2_buffer_abort_trigger(struct journal_head * jh,struct jbd2_buffer_trigger_type * triggers)1449 void jbd2_buffer_abort_trigger(struct journal_head *jh,
1450 			       struct jbd2_buffer_trigger_type *triggers)
1451 {
1452 	if (!triggers || !triggers->t_abort)
1453 		return;
1454 
1455 	triggers->t_abort(triggers, jh2bh(jh));
1456 }
1457 
1458 /**
1459  * jbd2_journal_dirty_metadata() -  mark a buffer as containing dirty metadata
1460  * @handle: transaction to add buffer to.
1461  * @bh: buffer to mark
1462  *
1463  * mark dirty metadata which needs to be journaled as part of the current
1464  * transaction.
1465  *
1466  * The buffer must have previously had jbd2_journal_get_write_access()
1467  * called so that it has a valid journal_head attached to the buffer
1468  * head.
1469  *
1470  * The buffer is placed on the transaction's metadata list and is marked
1471  * as belonging to the transaction.
1472  *
1473  * Returns error number or 0 on success.
1474  *
1475  * Special care needs to be taken if the buffer already belongs to the
1476  * current committing transaction (in which case we should have frozen
1477  * data present for that commit).  In that case, we don't relink the
1478  * buffer: that only gets done when the old transaction finally
1479  * completes its commit.
1480  */
jbd2_journal_dirty_metadata(handle_t * handle,struct buffer_head * bh)1481 int jbd2_journal_dirty_metadata(handle_t *handle, struct buffer_head *bh)
1482 {
1483 	transaction_t *transaction = handle->h_transaction;
1484 	journal_t *journal;
1485 	struct journal_head *jh;
1486 	int ret = 0;
1487 
1488 	if (!buffer_jbd(bh))
1489 		return -EUCLEAN;
1490 
1491 	/*
1492 	 * We don't grab jh reference here since the buffer must be part
1493 	 * of the running transaction.
1494 	 */
1495 	jh = bh2jh(bh);
1496 	jbd2_debug(5, "journal_head %p\n", jh);
1497 	JBUFFER_TRACE(jh, "entry");
1498 
1499 	/*
1500 	 * This and the following assertions are unreliable since we may see jh
1501 	 * in inconsistent state unless we grab bh_state lock. But this is
1502 	 * crucial to catch bugs so let's do a reliable check until the
1503 	 * lockless handling is fully proven.
1504 	 */
1505 	if (data_race(jh->b_transaction != transaction &&
1506 	    jh->b_next_transaction != transaction)) {
1507 		spin_lock(&jh->b_state_lock);
1508 		J_ASSERT_JH(jh, jh->b_transaction == transaction ||
1509 				jh->b_next_transaction == transaction);
1510 		spin_unlock(&jh->b_state_lock);
1511 	}
1512 	if (data_race(jh->b_modified == 1)) {
1513 		/* If it's in our transaction it must be in BJ_Metadata list. */
1514 		if (data_race(jh->b_transaction == transaction &&
1515 		    jh->b_jlist != BJ_Metadata)) {
1516 			spin_lock(&jh->b_state_lock);
1517 			if (jh->b_transaction == transaction &&
1518 			    jh->b_jlist != BJ_Metadata)
1519 				pr_err("JBD2: assertion failure: h_type=%u "
1520 				       "h_line_no=%u block_no=%llu jlist=%u\n",
1521 				       handle->h_type, handle->h_line_no,
1522 				       (unsigned long long) bh->b_blocknr,
1523 				       jh->b_jlist);
1524 			J_ASSERT_JH(jh, jh->b_transaction != transaction ||
1525 					jh->b_jlist == BJ_Metadata);
1526 			spin_unlock(&jh->b_state_lock);
1527 		}
1528 		goto out;
1529 	}
1530 
1531 	spin_lock(&jh->b_state_lock);
1532 
1533 	if (is_handle_aborted(handle)) {
1534 		/*
1535 		 * Check journal aborting with @jh->b_state_lock locked,
1536 		 * since 'jh->b_transaction' could be replaced with
1537 		 * 'jh->b_next_transaction' during old transaction
1538 		 * committing if journal aborted, which may fail
1539 		 * assertion on 'jh->b_frozen_data == NULL'.
1540 		 */
1541 		ret = -EROFS;
1542 		goto out_unlock_bh;
1543 	}
1544 
1545 	journal = transaction->t_journal;
1546 
1547 	if (jh->b_modified == 0) {
1548 		/*
1549 		 * This buffer's got modified and becoming part
1550 		 * of the transaction. This needs to be done
1551 		 * once a transaction -bzzz
1552 		 */
1553 		if (WARN_ON_ONCE(jbd2_handle_buffer_credits(handle) <= 0)) {
1554 			ret = -ENOSPC;
1555 			goto out_unlock_bh;
1556 		}
1557 		jh->b_modified = 1;
1558 		handle->h_total_credits--;
1559 	}
1560 
1561 	/*
1562 	 * fastpath, to avoid expensive locking.  If this buffer is already
1563 	 * on the running transaction's metadata list there is nothing to do.
1564 	 * Nobody can take it off again because there is a handle open.
1565 	 * I _think_ we're OK here with SMP barriers - a mistaken decision will
1566 	 * result in this test being false, so we go in and take the locks.
1567 	 */
1568 	if (jh->b_transaction == transaction && jh->b_jlist == BJ_Metadata) {
1569 		JBUFFER_TRACE(jh, "fastpath");
1570 		if (unlikely(jh->b_transaction !=
1571 			     journal->j_running_transaction)) {
1572 			printk(KERN_ERR "JBD2: %s: "
1573 			       "jh->b_transaction (%llu, %p, %u) != "
1574 			       "journal->j_running_transaction (%p, %u)\n",
1575 			       journal->j_devname,
1576 			       (unsigned long long) bh->b_blocknr,
1577 			       jh->b_transaction,
1578 			       jh->b_transaction ? jh->b_transaction->t_tid : 0,
1579 			       journal->j_running_transaction,
1580 			       journal->j_running_transaction ?
1581 			       journal->j_running_transaction->t_tid : 0);
1582 			ret = -EINVAL;
1583 		}
1584 		goto out_unlock_bh;
1585 	}
1586 
1587 	set_buffer_jbddirty(bh);
1588 
1589 	/*
1590 	 * Metadata already on the current transaction list doesn't
1591 	 * need to be filed.  Metadata on another transaction's list must
1592 	 * be committing, and will be refiled once the commit completes:
1593 	 * leave it alone for now.
1594 	 */
1595 	if (jh->b_transaction != transaction) {
1596 		JBUFFER_TRACE(jh, "already on other transaction");
1597 		if (unlikely(((jh->b_transaction !=
1598 			       journal->j_committing_transaction)) ||
1599 			     (jh->b_next_transaction != transaction))) {
1600 			printk(KERN_ERR "jbd2_journal_dirty_metadata: %s: "
1601 			       "bad jh for block %llu: "
1602 			       "transaction (%p, %u), "
1603 			       "jh->b_transaction (%p, %u), "
1604 			       "jh->b_next_transaction (%p, %u), jlist %u\n",
1605 			       journal->j_devname,
1606 			       (unsigned long long) bh->b_blocknr,
1607 			       transaction, transaction->t_tid,
1608 			       jh->b_transaction,
1609 			       jh->b_transaction ?
1610 			       jh->b_transaction->t_tid : 0,
1611 			       jh->b_next_transaction,
1612 			       jh->b_next_transaction ?
1613 			       jh->b_next_transaction->t_tid : 0,
1614 			       jh->b_jlist);
1615 			WARN_ON(1);
1616 			ret = -EINVAL;
1617 		}
1618 		/* And this case is illegal: we can't reuse another
1619 		 * transaction's data buffer, ever. */
1620 		goto out_unlock_bh;
1621 	}
1622 
1623 	/* That test should have eliminated the following case: */
1624 	J_ASSERT_JH(jh, jh->b_frozen_data == NULL);
1625 
1626 	JBUFFER_TRACE(jh, "file as BJ_Metadata");
1627 	spin_lock(&journal->j_list_lock);
1628 	__jbd2_journal_file_buffer(jh, transaction, BJ_Metadata);
1629 	spin_unlock(&journal->j_list_lock);
1630 out_unlock_bh:
1631 	spin_unlock(&jh->b_state_lock);
1632 out:
1633 	JBUFFER_TRACE(jh, "exit");
1634 	return ret;
1635 }
1636 
1637 /**
1638  * jbd2_journal_forget() - bforget() for potentially-journaled buffers.
1639  * @handle: transaction handle
1640  * @bh:     bh to 'forget'
1641  *
1642  * We can only do the bforget if there are no commits pending against the
1643  * buffer.  If the buffer is dirty in the current running transaction we
1644  * can safely unlink it.
1645  *
1646  * bh may not be a journalled buffer at all - it may be a non-JBD
1647  * buffer which came off the hashtable.  Check for this.
1648  *
1649  * Decrements bh->b_count by one.
1650  *
1651  * Allow this call even if the handle has aborted --- it may be part of
1652  * the caller's cleanup after an abort.
1653  */
jbd2_journal_forget(handle_t * handle,struct buffer_head * bh)1654 int jbd2_journal_forget(handle_t *handle, struct buffer_head *bh)
1655 {
1656 	transaction_t *transaction = handle->h_transaction;
1657 	journal_t *journal;
1658 	struct journal_head *jh;
1659 	int drop_reserve = 0;
1660 	int err = 0;
1661 	int was_modified = 0;
1662 	int wait_for_writeback = 0;
1663 
1664 	if (is_handle_aborted(handle))
1665 		return -EROFS;
1666 	journal = transaction->t_journal;
1667 
1668 	BUFFER_TRACE(bh, "entry");
1669 
1670 	jh = jbd2_journal_grab_journal_head(bh);
1671 	if (!jh) {
1672 		__bforget(bh);
1673 		return 0;
1674 	}
1675 
1676 	spin_lock(&jh->b_state_lock);
1677 
1678 	/* Critical error: attempting to delete a bitmap buffer, maybe?
1679 	 * Don't do any jbd operations, and return an error. */
1680 	if (!J_EXPECT_JH(jh, !jh->b_committed_data,
1681 			 "inconsistent data on disk")) {
1682 		err = -EIO;
1683 		goto drop;
1684 	}
1685 
1686 	/* keep track of whether or not this transaction modified us */
1687 	was_modified = jh->b_modified;
1688 
1689 	/*
1690 	 * The buffer's going from the transaction, we must drop
1691 	 * all references -bzzz
1692 	 */
1693 	jh->b_modified = 0;
1694 
1695 	if (jh->b_transaction == transaction) {
1696 		J_ASSERT_JH(jh, !jh->b_frozen_data);
1697 
1698 		/* If we are forgetting a buffer which is already part
1699 		 * of this transaction, then we can just drop it from
1700 		 * the transaction immediately. */
1701 		clear_buffer_dirty(bh);
1702 		clear_buffer_jbddirty(bh);
1703 
1704 		JBUFFER_TRACE(jh, "belongs to current transaction: unfile");
1705 
1706 		/*
1707 		 * we only want to drop a reference if this transaction
1708 		 * modified the buffer
1709 		 */
1710 		if (was_modified)
1711 			drop_reserve = 1;
1712 
1713 		/*
1714 		 * We are no longer going to journal this buffer.
1715 		 * However, the commit of this transaction is still
1716 		 * important to the buffer: the delete that we are now
1717 		 * processing might obsolete an old log entry, so by
1718 		 * committing, we can satisfy the buffer's checkpoint.
1719 		 *
1720 		 * So, if we have a checkpoint on the buffer, we should
1721 		 * now refile the buffer on our BJ_Forget list so that
1722 		 * we know to remove the checkpoint after we commit.
1723 		 */
1724 
1725 		spin_lock(&journal->j_list_lock);
1726 		if (jh->b_cp_transaction) {
1727 			__jbd2_journal_temp_unlink_buffer(jh);
1728 			__jbd2_journal_file_buffer(jh, transaction, BJ_Forget);
1729 		} else {
1730 			__jbd2_journal_unfile_buffer(jh);
1731 			jbd2_journal_put_journal_head(jh);
1732 		}
1733 		spin_unlock(&journal->j_list_lock);
1734 	} else if (jh->b_transaction) {
1735 		J_ASSERT_JH(jh, (jh->b_transaction ==
1736 				 journal->j_committing_transaction));
1737 		/* However, if the buffer is still owned by a prior
1738 		 * (committing) transaction, we can't drop it yet... */
1739 		JBUFFER_TRACE(jh, "belongs to older transaction");
1740 		/* ... but we CAN drop it from the new transaction through
1741 		 * marking the buffer as freed and set j_next_transaction to
1742 		 * the new transaction, so that not only the commit code
1743 		 * knows it should clear dirty bits when it is done with the
1744 		 * buffer, but also the buffer can be checkpointed only
1745 		 * after the new transaction commits. */
1746 
1747 		set_buffer_freed(bh);
1748 
1749 		if (!jh->b_next_transaction) {
1750 			spin_lock(&journal->j_list_lock);
1751 			jh->b_next_transaction = transaction;
1752 			spin_unlock(&journal->j_list_lock);
1753 		} else {
1754 			J_ASSERT(jh->b_next_transaction == transaction);
1755 
1756 			/*
1757 			 * only drop a reference if this transaction modified
1758 			 * the buffer
1759 			 */
1760 			if (was_modified)
1761 				drop_reserve = 1;
1762 		}
1763 	} else {
1764 		/*
1765 		 * Finally, if the buffer is not belongs to any
1766 		 * transaction, we can just drop it now if it has no
1767 		 * checkpoint.
1768 		 */
1769 		spin_lock(&journal->j_list_lock);
1770 		if (!jh->b_cp_transaction) {
1771 			JBUFFER_TRACE(jh, "belongs to none transaction");
1772 			spin_unlock(&journal->j_list_lock);
1773 			goto drop;
1774 		}
1775 
1776 		/*
1777 		 * Otherwise, if the buffer has been written to disk,
1778 		 * it is safe to remove the checkpoint and drop it.
1779 		 */
1780 		if (jbd2_journal_try_remove_checkpoint(jh) >= 0) {
1781 			spin_unlock(&journal->j_list_lock);
1782 			goto drop;
1783 		}
1784 
1785 		/*
1786 		 * The buffer has not yet been written to disk. We should
1787 		 * either clear the buffer or ensure that the ongoing I/O
1788 		 * is completed, and attach this buffer to current
1789 		 * transaction so that the buffer can be checkpointed only
1790 		 * after the current transaction commits.
1791 		 */
1792 		clear_buffer_dirty(bh);
1793 		wait_for_writeback = 1;
1794 		__jbd2_journal_file_buffer(jh, transaction, BJ_Forget);
1795 		spin_unlock(&journal->j_list_lock);
1796 	}
1797 drop:
1798 	__brelse(bh);
1799 	spin_unlock(&jh->b_state_lock);
1800 	if (wait_for_writeback)
1801 		wait_on_buffer(bh);
1802 	jbd2_journal_put_journal_head(jh);
1803 	if (drop_reserve) {
1804 		/* no need to reserve log space for this block -bzzz */
1805 		handle->h_total_credits++;
1806 	}
1807 	return err;
1808 }
1809 
1810 /**
1811  * jbd2_journal_stop() - complete a transaction
1812  * @handle: transaction to complete.
1813  *
1814  * All done for a particular handle.
1815  *
1816  * There is not much action needed here.  We just return any remaining
1817  * buffer credits to the transaction and remove the handle.  The only
1818  * complication is that we need to start a commit operation if the
1819  * filesystem is marked for synchronous update.
1820  *
1821  * jbd2_journal_stop itself will not usually return an error, but it may
1822  * do so in unusual circumstances.  In particular, expect it to
1823  * return -EIO if a jbd2_journal_abort has been executed since the
1824  * transaction began.
1825  */
jbd2_journal_stop(handle_t * handle)1826 int jbd2_journal_stop(handle_t *handle)
1827 {
1828 	transaction_t *transaction = handle->h_transaction;
1829 	journal_t *journal;
1830 	int err = 0, wait_for_commit = 0;
1831 	tid_t tid;
1832 	pid_t pid;
1833 
1834 	if (--handle->h_ref > 0) {
1835 		jbd2_debug(4, "h_ref %d -> %d\n", handle->h_ref + 1,
1836 						 handle->h_ref);
1837 		if (is_handle_aborted(handle))
1838 			return -EIO;
1839 		return 0;
1840 	}
1841 	if (!transaction) {
1842 		/*
1843 		 * Handle is already detached from the transaction so there is
1844 		 * nothing to do other than free the handle.
1845 		 */
1846 		memalloc_nofs_restore(handle->saved_alloc_context);
1847 		goto free_and_exit;
1848 	}
1849 	journal = transaction->t_journal;
1850 	tid = transaction->t_tid;
1851 
1852 	if (is_handle_aborted(handle))
1853 		err = -EIO;
1854 
1855 	jbd2_debug(4, "Handle %p going down\n", handle);
1856 	trace_jbd2_handle_stats(journal->j_fs_dev->bd_dev,
1857 				tid, handle->h_type, handle->h_line_no,
1858 				jiffies - handle->h_start_jiffies,
1859 				handle->h_sync, handle->h_requested_credits,
1860 				(handle->h_requested_credits -
1861 				 handle->h_total_credits));
1862 
1863 	/*
1864 	 * Implement synchronous transaction batching.  If the handle
1865 	 * was synchronous, don't force a commit immediately.  Let's
1866 	 * yield and let another thread piggyback onto this
1867 	 * transaction.  Keep doing that while new threads continue to
1868 	 * arrive.  It doesn't cost much - we're about to run a commit
1869 	 * and sleep on IO anyway.  Speeds up many-threaded, many-dir
1870 	 * operations by 30x or more...
1871 	 *
1872 	 * We try and optimize the sleep time against what the
1873 	 * underlying disk can do, instead of having a static sleep
1874 	 * time.  This is useful for the case where our storage is so
1875 	 * fast that it is more optimal to go ahead and force a flush
1876 	 * and wait for the transaction to be committed than it is to
1877 	 * wait for an arbitrary amount of time for new writers to
1878 	 * join the transaction.  We achieve this by measuring how
1879 	 * long it takes to commit a transaction, and compare it with
1880 	 * how long this transaction has been running, and if run time
1881 	 * < commit time then we sleep for the delta and commit.  This
1882 	 * greatly helps super fast disks that would see slowdowns as
1883 	 * more threads started doing fsyncs.
1884 	 *
1885 	 * But don't do this if this process was the most recent one
1886 	 * to perform a synchronous write.  We do this to detect the
1887 	 * case where a single process is doing a stream of sync
1888 	 * writes.  No point in waiting for joiners in that case.
1889 	 *
1890 	 * Setting max_batch_time to 0 disables this completely.
1891 	 */
1892 	pid = current->pid;
1893 	if (handle->h_sync && journal->j_last_sync_writer != pid &&
1894 	    journal->j_max_batch_time) {
1895 		u64 commit_time, trans_time;
1896 
1897 		journal->j_last_sync_writer = pid;
1898 
1899 		read_lock(&journal->j_state_lock);
1900 		commit_time = journal->j_average_commit_time;
1901 		read_unlock(&journal->j_state_lock);
1902 
1903 		trans_time = ktime_to_ns(ktime_sub(ktime_get(),
1904 						   transaction->t_start_time));
1905 
1906 		commit_time = max_t(u64, commit_time,
1907 				    1000*journal->j_min_batch_time);
1908 		commit_time = min_t(u64, commit_time,
1909 				    1000*journal->j_max_batch_time);
1910 
1911 		if (trans_time < commit_time) {
1912 			ktime_t expires = ktime_add_ns(ktime_get(),
1913 						       commit_time);
1914 			set_current_state(TASK_UNINTERRUPTIBLE);
1915 			schedule_hrtimeout(&expires, HRTIMER_MODE_ABS);
1916 		}
1917 	}
1918 
1919 	if (handle->h_sync)
1920 		transaction->t_synchronous_commit = 1;
1921 
1922 	/*
1923 	 * If the handle is marked SYNC, we need to set another commit
1924 	 * going!  We also want to force a commit if the transaction is too
1925 	 * old now.
1926 	 */
1927 	if (handle->h_sync ||
1928 	    time_after_eq(jiffies, transaction->t_expires)) {
1929 		/* Do this even for aborted journals: an abort still
1930 		 * completes the commit thread, it just doesn't write
1931 		 * anything to disk. */
1932 
1933 		jbd2_debug(2, "transaction too old, requesting commit for "
1934 					"handle %p\n", handle);
1935 		/* This is non-blocking */
1936 		jbd2_log_start_commit(journal, tid);
1937 
1938 		/*
1939 		 * Special case: JBD2_SYNC synchronous updates require us
1940 		 * to wait for the commit to complete.
1941 		 */
1942 		if (handle->h_sync && !(current->flags & PF_MEMALLOC))
1943 			wait_for_commit = 1;
1944 	}
1945 
1946 	/*
1947 	 * Once stop_this_handle() drops t_updates, the transaction could start
1948 	 * committing on us and eventually disappear.  So we must not
1949 	 * dereference transaction pointer again after calling
1950 	 * stop_this_handle().
1951 	 */
1952 	stop_this_handle(handle);
1953 
1954 	if (wait_for_commit)
1955 		err = jbd2_log_wait_commit(journal, tid);
1956 
1957 free_and_exit:
1958 	if (handle->h_rsv_handle)
1959 		jbd2_free_handle(handle->h_rsv_handle);
1960 	jbd2_free_handle(handle);
1961 	return err;
1962 }
1963 
1964 /*
1965  *
1966  * List management code snippets: various functions for manipulating the
1967  * transaction buffer lists.
1968  *
1969  */
1970 
1971 /*
1972  * Append a buffer to a transaction list, given the transaction's list head
1973  * pointer.
1974  *
1975  * j_list_lock is held.
1976  *
1977  * jh->b_state_lock is held.
1978  */
1979 
1980 static inline void
__blist_add_buffer(struct journal_head ** list,struct journal_head * jh)1981 __blist_add_buffer(struct journal_head **list, struct journal_head *jh)
1982 {
1983 	if (!*list) {
1984 		jh->b_tnext = jh->b_tprev = jh;
1985 		*list = jh;
1986 	} else {
1987 		/* Insert at the tail of the list to preserve order */
1988 		struct journal_head *first = *list, *last = first->b_tprev;
1989 		jh->b_tprev = last;
1990 		jh->b_tnext = first;
1991 		last->b_tnext = first->b_tprev = jh;
1992 	}
1993 }
1994 
1995 /*
1996  * Remove a buffer from a transaction list, given the transaction's list
1997  * head pointer.
1998  *
1999  * Called with j_list_lock held, and the journal may not be locked.
2000  *
2001  * jh->b_state_lock is held.
2002  */
2003 
2004 static inline void
__blist_del_buffer(struct journal_head ** list,struct journal_head * jh)2005 __blist_del_buffer(struct journal_head **list, struct journal_head *jh)
2006 {
2007 	if (*list == jh) {
2008 		*list = jh->b_tnext;
2009 		if (*list == jh)
2010 			*list = NULL;
2011 	}
2012 	jh->b_tprev->b_tnext = jh->b_tnext;
2013 	jh->b_tnext->b_tprev = jh->b_tprev;
2014 }
2015 
2016 /*
2017  * Remove a buffer from the appropriate transaction list.
2018  *
2019  * Note that this function can *change* the value of
2020  * bh->b_transaction->t_buffers, t_forget, t_shadow_list, t_log_list or
2021  * t_reserved_list.  If the caller is holding onto a copy of one of these
2022  * pointers, it could go bad.  Generally the caller needs to re-read the
2023  * pointer from the transaction_t.
2024  *
2025  * Called under j_list_lock.
2026  */
__jbd2_journal_temp_unlink_buffer(struct journal_head * jh)2027 static void __jbd2_journal_temp_unlink_buffer(struct journal_head *jh)
2028 {
2029 	struct journal_head **list = NULL;
2030 	transaction_t *transaction;
2031 	struct buffer_head *bh = jh2bh(jh);
2032 
2033 	lockdep_assert_held(&jh->b_state_lock);
2034 	transaction = jh->b_transaction;
2035 	if (transaction)
2036 		assert_spin_locked(&transaction->t_journal->j_list_lock);
2037 
2038 	J_ASSERT_JH(jh, jh->b_jlist < BJ_Types);
2039 	if (jh->b_jlist != BJ_None)
2040 		J_ASSERT_JH(jh, transaction != NULL);
2041 
2042 	switch (jh->b_jlist) {
2043 	case BJ_None:
2044 		return;
2045 	case BJ_Metadata:
2046 		transaction->t_nr_buffers--;
2047 		J_ASSERT_JH(jh, transaction->t_nr_buffers >= 0);
2048 		list = &transaction->t_buffers;
2049 		break;
2050 	case BJ_Forget:
2051 		list = &transaction->t_forget;
2052 		break;
2053 	case BJ_Shadow:
2054 		list = &transaction->t_shadow_list;
2055 		break;
2056 	case BJ_Reserved:
2057 		list = &transaction->t_reserved_list;
2058 		break;
2059 	}
2060 
2061 	__blist_del_buffer(list, jh);
2062 	jh->b_jlist = BJ_None;
2063 	if (transaction && is_journal_aborted(transaction->t_journal))
2064 		clear_buffer_jbddirty(bh);
2065 	else if (test_clear_buffer_jbddirty(bh))
2066 		mark_buffer_dirty(bh);	/* Expose it to the VM */
2067 }
2068 
2069 /*
2070  * Remove buffer from all transactions. The caller is responsible for dropping
2071  * the jh reference that belonged to the transaction.
2072  *
2073  * Called with bh_state lock and j_list_lock
2074  */
__jbd2_journal_unfile_buffer(struct journal_head * jh)2075 static void __jbd2_journal_unfile_buffer(struct journal_head *jh)
2076 {
2077 	J_ASSERT_JH(jh, jh->b_transaction != NULL);
2078 	J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
2079 
2080 	__jbd2_journal_temp_unlink_buffer(jh);
2081 	jh->b_transaction = NULL;
2082 }
2083 
2084 /**
2085  * jbd2_journal_try_to_free_buffers() - try to free page buffers.
2086  * @journal: journal for operation
2087  * @folio: Folio to detach data from.
2088  *
2089  * For all the buffers on this page,
2090  * if they are fully written out ordered data, move them onto BUF_CLEAN
2091  * so try_to_free_buffers() can reap them.
2092  *
2093  * This function returns non-zero if we wish try_to_free_buffers()
2094  * to be called. We do this if the page is releasable by try_to_free_buffers().
2095  * We also do it if the page has locked or dirty buffers and the caller wants
2096  * us to perform sync or async writeout.
2097  *
2098  * This complicates JBD locking somewhat.  We aren't protected by the
2099  * BKL here.  We wish to remove the buffer from its committing or
2100  * running transaction's ->t_datalist via __jbd2_journal_unfile_buffer.
2101  *
2102  * This may *change* the value of transaction_t->t_datalist, so anyone
2103  * who looks at t_datalist needs to lock against this function.
2104  *
2105  * Even worse, someone may be doing a jbd2_journal_dirty_data on this
2106  * buffer.  So we need to lock against that.  jbd2_journal_dirty_data()
2107  * will come out of the lock with the buffer dirty, which makes it
2108  * ineligible for release here.
2109  *
2110  * Who else is affected by this?  hmm...  Really the only contender
2111  * is do_get_write_access() - it could be looking at the buffer while
2112  * journal_try_to_free_buffer() is changing its state.  But that
2113  * cannot happen because we never reallocate freed data as metadata
2114  * while the data is part of a transaction.  Yes?
2115  *
2116  * Return false on failure, true on success
2117  */
jbd2_journal_try_to_free_buffers(journal_t * journal,struct folio * folio)2118 bool jbd2_journal_try_to_free_buffers(journal_t *journal, struct folio *folio)
2119 {
2120 	struct buffer_head *head;
2121 	struct buffer_head *bh;
2122 	bool ret = false;
2123 
2124 	J_ASSERT(folio_test_locked(folio));
2125 
2126 	head = folio_buffers(folio);
2127 	bh = head;
2128 	do {
2129 		struct journal_head *jh;
2130 
2131 		/*
2132 		 * We take our own ref against the journal_head here to avoid
2133 		 * having to add tons of locking around each instance of
2134 		 * jbd2_journal_put_journal_head().
2135 		 */
2136 		jh = jbd2_journal_grab_journal_head(bh);
2137 		if (!jh)
2138 			continue;
2139 
2140 		spin_lock(&jh->b_state_lock);
2141 		if (!jh->b_transaction && !jh->b_next_transaction) {
2142 			spin_lock(&journal->j_list_lock);
2143 			/* Remove written-back checkpointed metadata buffer */
2144 			if (jh->b_cp_transaction != NULL)
2145 				jbd2_journal_try_remove_checkpoint(jh);
2146 			spin_unlock(&journal->j_list_lock);
2147 		}
2148 		spin_unlock(&jh->b_state_lock);
2149 		jbd2_journal_put_journal_head(jh);
2150 		if (buffer_jbd(bh))
2151 			goto busy;
2152 	} while ((bh = bh->b_this_page) != head);
2153 
2154 	ret = try_to_free_buffers(folio);
2155 busy:
2156 	return ret;
2157 }
2158 
2159 /*
2160  * This buffer is no longer needed.  If it is on an older transaction's
2161  * checkpoint list we need to record it on this transaction's forget list
2162  * to pin this buffer (and hence its checkpointing transaction) down until
2163  * this transaction commits.  If the buffer isn't on a checkpoint list, we
2164  * release it.
2165  * Returns non-zero if JBD no longer has an interest in the buffer.
2166  *
2167  * Called under j_list_lock.
2168  *
2169  * Called under jh->b_state_lock.
2170  */
__dispose_buffer(struct journal_head * jh,transaction_t * transaction)2171 static int __dispose_buffer(struct journal_head *jh, transaction_t *transaction)
2172 {
2173 	int may_free = 1;
2174 	struct buffer_head *bh = jh2bh(jh);
2175 
2176 	if (jh->b_cp_transaction) {
2177 		JBUFFER_TRACE(jh, "on running+cp transaction");
2178 		__jbd2_journal_temp_unlink_buffer(jh);
2179 		/*
2180 		 * We don't want to write the buffer anymore, clear the
2181 		 * bit so that we don't confuse checks in
2182 		 * __jbd2_journal_file_buffer
2183 		 */
2184 		clear_buffer_dirty(bh);
2185 		__jbd2_journal_file_buffer(jh, transaction, BJ_Forget);
2186 		may_free = 0;
2187 	} else {
2188 		JBUFFER_TRACE(jh, "on running transaction");
2189 		__jbd2_journal_unfile_buffer(jh);
2190 		jbd2_journal_put_journal_head(jh);
2191 	}
2192 	return may_free;
2193 }
2194 
2195 /*
2196  * jbd2_journal_invalidate_folio
2197  *
2198  * This code is tricky.  It has a number of cases to deal with.
2199  *
2200  * There are two invariants which this code relies on:
2201  *
2202  * i_size must be updated on disk before we start calling invalidate_folio
2203  * on the data.
2204  *
2205  *  This is done in ext3 by defining an ext3_setattr method which
2206  *  updates i_size before truncate gets going.  By maintaining this
2207  *  invariant, we can be sure that it is safe to throw away any buffers
2208  *  attached to the current transaction: once the transaction commits,
2209  *  we know that the data will not be needed.
2210  *
2211  *  Note however that we can *not* throw away data belonging to the
2212  *  previous, committing transaction!
2213  *
2214  * Any disk blocks which *are* part of the previous, committing
2215  * transaction (and which therefore cannot be discarded immediately) are
2216  * not going to be reused in the new running transaction
2217  *
2218  *  The bitmap committed_data images guarantee this: any block which is
2219  *  allocated in one transaction and removed in the next will be marked
2220  *  as in-use in the committed_data bitmap, so cannot be reused until
2221  *  the next transaction to delete the block commits.  This means that
2222  *  leaving committing buffers dirty is quite safe: the disk blocks
2223  *  cannot be reallocated to a different file and so buffer aliasing is
2224  *  not possible.
2225  *
2226  *
2227  * The above applies mainly to ordered data mode.  In writeback mode we
2228  * don't make guarantees about the order in which data hits disk --- in
2229  * particular we don't guarantee that new dirty data is flushed before
2230  * transaction commit --- so it is always safe just to discard data
2231  * immediately in that mode.  --sct
2232  */
2233 
2234 /*
2235  * The journal_unmap_buffer helper function returns zero if the buffer
2236  * concerned remains pinned as an anonymous buffer belonging to an older
2237  * transaction.
2238  *
2239  * We're outside-transaction here.  Either or both of j_running_transaction
2240  * and j_committing_transaction may be NULL.
2241  */
journal_unmap_buffer(journal_t * journal,struct buffer_head * bh,int partial_page)2242 static int journal_unmap_buffer(journal_t *journal, struct buffer_head *bh,
2243 				int partial_page)
2244 {
2245 	transaction_t *transaction;
2246 	struct journal_head *jh;
2247 	int may_free = 1;
2248 
2249 	BUFFER_TRACE(bh, "entry");
2250 
2251 	/*
2252 	 * It is safe to proceed here without the j_list_lock because the
2253 	 * buffers cannot be stolen by try_to_free_buffers as long as we are
2254 	 * holding the page lock. --sct
2255 	 */
2256 
2257 	jh = jbd2_journal_grab_journal_head(bh);
2258 	if (!jh)
2259 		goto zap_buffer_unlocked;
2260 
2261 	/* OK, we have data buffer in journaled mode */
2262 	write_lock(&journal->j_state_lock);
2263 	spin_lock(&jh->b_state_lock);
2264 	spin_lock(&journal->j_list_lock);
2265 
2266 	/*
2267 	 * We cannot remove the buffer from checkpoint lists until the
2268 	 * transaction adding inode to orphan list (let's call it T)
2269 	 * is committed.  Otherwise if the transaction changing the
2270 	 * buffer would be cleaned from the journal before T is
2271 	 * committed, a crash will cause that the correct contents of
2272 	 * the buffer will be lost.  On the other hand we have to
2273 	 * clear the buffer dirty bit at latest at the moment when the
2274 	 * transaction marking the buffer as freed in the filesystem
2275 	 * structures is committed because from that moment on the
2276 	 * block can be reallocated and used by a different page.
2277 	 * Since the block hasn't been freed yet but the inode has
2278 	 * already been added to orphan list, it is safe for us to add
2279 	 * the buffer to BJ_Forget list of the newest transaction.
2280 	 *
2281 	 * Also we have to clear buffer_mapped flag of a truncated buffer
2282 	 * because the buffer_head may be attached to the page straddling
2283 	 * i_size (can happen only when blocksize < pagesize) and thus the
2284 	 * buffer_head can be reused when the file is extended again. So we end
2285 	 * up keeping around invalidated buffers attached to transactions'
2286 	 * BJ_Forget list just to stop checkpointing code from cleaning up
2287 	 * the transaction this buffer was modified in.
2288 	 */
2289 	transaction = jh->b_transaction;
2290 	if (transaction == NULL) {
2291 		/* First case: not on any transaction.  If it
2292 		 * has no checkpoint link, then we can zap it:
2293 		 * it's a writeback-mode buffer so we don't care
2294 		 * if it hits disk safely. */
2295 		if (!jh->b_cp_transaction) {
2296 			JBUFFER_TRACE(jh, "not on any transaction: zap");
2297 			goto zap_buffer;
2298 		}
2299 
2300 		if (!buffer_dirty(bh)) {
2301 			/* bdflush has written it.  We can drop it now */
2302 			__jbd2_journal_remove_checkpoint(jh);
2303 			goto zap_buffer;
2304 		}
2305 
2306 		/* OK, it must be in the journal but still not
2307 		 * written fully to disk: it's metadata or
2308 		 * journaled data... */
2309 
2310 		if (journal->j_running_transaction) {
2311 			/* ... and once the current transaction has
2312 			 * committed, the buffer won't be needed any
2313 			 * longer. */
2314 			JBUFFER_TRACE(jh, "checkpointed: add to BJ_Forget");
2315 			may_free = __dispose_buffer(jh,
2316 					journal->j_running_transaction);
2317 			goto zap_buffer;
2318 		} else {
2319 			/* There is no currently-running transaction. So the
2320 			 * orphan record which we wrote for this file must have
2321 			 * passed into commit.  We must attach this buffer to
2322 			 * the committing transaction, if it exists. */
2323 			if (journal->j_committing_transaction) {
2324 				JBUFFER_TRACE(jh, "give to committing trans");
2325 				may_free = __dispose_buffer(jh,
2326 					journal->j_committing_transaction);
2327 				goto zap_buffer;
2328 			} else {
2329 				/* The orphan record's transaction has
2330 				 * committed.  We can cleanse this buffer */
2331 				clear_buffer_jbddirty(bh);
2332 				__jbd2_journal_remove_checkpoint(jh);
2333 				goto zap_buffer;
2334 			}
2335 		}
2336 	} else if (transaction == journal->j_committing_transaction) {
2337 		JBUFFER_TRACE(jh, "on committing transaction");
2338 		/*
2339 		 * The buffer is committing, we simply cannot touch
2340 		 * it. If the page is straddling i_size we have to wait
2341 		 * for commit and try again.
2342 		 */
2343 		if (partial_page) {
2344 			spin_unlock(&journal->j_list_lock);
2345 			spin_unlock(&jh->b_state_lock);
2346 			write_unlock(&journal->j_state_lock);
2347 			jbd2_journal_put_journal_head(jh);
2348 			/* Already zapped buffer? Nothing to do... */
2349 			if (!bh->b_bdev)
2350 				return 0;
2351 			return -EBUSY;
2352 		}
2353 		/*
2354 		 * OK, buffer won't be reachable after truncate. We just clear
2355 		 * b_modified to not confuse transaction credit accounting, and
2356 		 * set j_next_transaction to the running transaction (if there
2357 		 * is one) and mark buffer as freed so that commit code knows
2358 		 * it should clear dirty bits when it is done with the buffer.
2359 		 */
2360 		set_buffer_freed(bh);
2361 		if (journal->j_running_transaction && buffer_jbddirty(bh))
2362 			jh->b_next_transaction = journal->j_running_transaction;
2363 		jh->b_modified = 0;
2364 		spin_unlock(&journal->j_list_lock);
2365 		spin_unlock(&jh->b_state_lock);
2366 		write_unlock(&journal->j_state_lock);
2367 		jbd2_journal_put_journal_head(jh);
2368 		return 0;
2369 	} else {
2370 		/* Good, the buffer belongs to the running transaction.
2371 		 * We are writing our own transaction's data, not any
2372 		 * previous one's, so it is safe to throw it away
2373 		 * (remember that we expect the filesystem to have set
2374 		 * i_size already for this truncate so recovery will not
2375 		 * expose the disk blocks we are discarding here.) */
2376 		J_ASSERT_JH(jh, transaction == journal->j_running_transaction);
2377 		JBUFFER_TRACE(jh, "on running transaction");
2378 		may_free = __dispose_buffer(jh, transaction);
2379 	}
2380 
2381 zap_buffer:
2382 	/*
2383 	 * This is tricky. Although the buffer is truncated, it may be reused
2384 	 * if blocksize < pagesize and it is attached to the page straddling
2385 	 * EOF. Since the buffer might have been added to BJ_Forget list of the
2386 	 * running transaction, journal_get_write_access() won't clear
2387 	 * b_modified and credit accounting gets confused. So clear b_modified
2388 	 * here.
2389 	 */
2390 	jh->b_modified = 0;
2391 	spin_unlock(&journal->j_list_lock);
2392 	spin_unlock(&jh->b_state_lock);
2393 	write_unlock(&journal->j_state_lock);
2394 	jbd2_journal_put_journal_head(jh);
2395 zap_buffer_unlocked:
2396 	clear_buffer_dirty(bh);
2397 	J_ASSERT_BH(bh, !buffer_jbddirty(bh));
2398 	clear_buffer_mapped(bh);
2399 	clear_buffer_req(bh);
2400 	clear_buffer_new(bh);
2401 	clear_buffer_delay(bh);
2402 	clear_buffer_unwritten(bh);
2403 	bh->b_bdev = NULL;
2404 	return may_free;
2405 }
2406 
2407 /**
2408  * jbd2_journal_invalidate_folio()
2409  * @journal: journal to use for flush...
2410  * @folio:    folio to flush
2411  * @offset:  start of the range to invalidate
2412  * @length:  length of the range to invalidate
2413  *
2414  * Reap page buffers containing data after in the specified range in page.
2415  * Can return -EBUSY if buffers are part of the committing transaction and
2416  * the page is straddling i_size. Caller then has to wait for current commit
2417  * and try again.
2418  */
jbd2_journal_invalidate_folio(journal_t * journal,struct folio * folio,size_t offset,size_t length)2419 int jbd2_journal_invalidate_folio(journal_t *journal, struct folio *folio,
2420 				size_t offset, size_t length)
2421 {
2422 	struct buffer_head *head, *bh, *next;
2423 	unsigned int stop = offset + length;
2424 	unsigned int curr_off = 0;
2425 	int partial_page = (offset || length < folio_size(folio));
2426 	int may_free = 1;
2427 	int ret = 0;
2428 
2429 	if (!folio_test_locked(folio))
2430 		BUG();
2431 	head = folio_buffers(folio);
2432 	if (!head)
2433 		return 0;
2434 
2435 	BUG_ON(stop > folio_size(folio) || stop < length);
2436 
2437 	/* We will potentially be playing with lists other than just the
2438 	 * data lists (especially for journaled data mode), so be
2439 	 * cautious in our locking. */
2440 
2441 	bh = head;
2442 	do {
2443 		unsigned int next_off = curr_off + bh->b_size;
2444 		next = bh->b_this_page;
2445 
2446 		if (next_off > stop)
2447 			return 0;
2448 
2449 		if (offset <= curr_off) {
2450 			/* This block is wholly outside the truncation point */
2451 			lock_buffer(bh);
2452 			ret = journal_unmap_buffer(journal, bh, partial_page);
2453 			unlock_buffer(bh);
2454 			if (ret < 0)
2455 				return ret;
2456 			may_free &= ret;
2457 		}
2458 		curr_off = next_off;
2459 		bh = next;
2460 
2461 	} while (bh != head);
2462 
2463 	if (!partial_page) {
2464 		if (may_free && try_to_free_buffers(folio))
2465 			J_ASSERT(!folio_buffers(folio));
2466 	}
2467 	return 0;
2468 }
2469 
2470 /*
2471  * File a buffer on the given transaction list.
2472  */
__jbd2_journal_file_buffer(struct journal_head * jh,transaction_t * transaction,int jlist)2473 void __jbd2_journal_file_buffer(struct journal_head *jh,
2474 			transaction_t *transaction, int jlist)
2475 {
2476 	struct journal_head **list = NULL;
2477 	int was_dirty = 0;
2478 	struct buffer_head *bh = jh2bh(jh);
2479 
2480 	lockdep_assert_held(&jh->b_state_lock);
2481 	assert_spin_locked(&transaction->t_journal->j_list_lock);
2482 
2483 	J_ASSERT_JH(jh, jh->b_jlist < BJ_Types);
2484 	J_ASSERT_JH(jh, jh->b_transaction == transaction ||
2485 				jh->b_transaction == NULL);
2486 
2487 	if (jh->b_transaction && jh->b_jlist == jlist)
2488 		return;
2489 
2490 	if (jlist == BJ_Metadata || jlist == BJ_Reserved ||
2491 	    jlist == BJ_Shadow || jlist == BJ_Forget) {
2492 		/*
2493 		 * For metadata buffers, we track dirty bit in buffer_jbddirty
2494 		 * instead of buffer_dirty. We should not see a dirty bit set
2495 		 * here because we clear it in do_get_write_access but e.g.
2496 		 * tune2fs can modify the sb and set the dirty bit at any time
2497 		 * so we try to gracefully handle that.
2498 		 */
2499 		if (buffer_dirty(bh))
2500 			warn_dirty_buffer(bh);
2501 		if (test_clear_buffer_dirty(bh) ||
2502 		    test_clear_buffer_jbddirty(bh))
2503 			was_dirty = 1;
2504 	}
2505 
2506 	if (jh->b_transaction)
2507 		__jbd2_journal_temp_unlink_buffer(jh);
2508 	else
2509 		jbd2_journal_grab_journal_head(bh);
2510 	jh->b_transaction = transaction;
2511 
2512 	switch (jlist) {
2513 	case BJ_None:
2514 		J_ASSERT_JH(jh, !jh->b_committed_data);
2515 		J_ASSERT_JH(jh, !jh->b_frozen_data);
2516 		return;
2517 	case BJ_Metadata:
2518 		transaction->t_nr_buffers++;
2519 		list = &transaction->t_buffers;
2520 		break;
2521 	case BJ_Forget:
2522 		list = &transaction->t_forget;
2523 		break;
2524 	case BJ_Shadow:
2525 		list = &transaction->t_shadow_list;
2526 		break;
2527 	case BJ_Reserved:
2528 		list = &transaction->t_reserved_list;
2529 		break;
2530 	}
2531 
2532 	__blist_add_buffer(list, jh);
2533 	jh->b_jlist = jlist;
2534 
2535 	if (was_dirty)
2536 		set_buffer_jbddirty(bh);
2537 }
2538 
jbd2_journal_file_buffer(struct journal_head * jh,transaction_t * transaction,int jlist)2539 void jbd2_journal_file_buffer(struct journal_head *jh,
2540 				transaction_t *transaction, int jlist)
2541 {
2542 	spin_lock(&jh->b_state_lock);
2543 	spin_lock(&transaction->t_journal->j_list_lock);
2544 	__jbd2_journal_file_buffer(jh, transaction, jlist);
2545 	spin_unlock(&transaction->t_journal->j_list_lock);
2546 	spin_unlock(&jh->b_state_lock);
2547 }
2548 
2549 /*
2550  * Remove a buffer from its current buffer list in preparation for
2551  * dropping it from its current transaction entirely.  If the buffer has
2552  * already started to be used by a subsequent transaction, refile the
2553  * buffer on that transaction's metadata list.
2554  *
2555  * Called under j_list_lock
2556  * Called under jh->b_state_lock
2557  *
2558  * When this function returns true, there's no next transaction to refile to
2559  * and the caller has to drop jh reference through
2560  * jbd2_journal_put_journal_head().
2561  */
__jbd2_journal_refile_buffer(struct journal_head * jh)2562 bool __jbd2_journal_refile_buffer(struct journal_head *jh)
2563 {
2564 	int was_dirty, jlist;
2565 	struct buffer_head *bh = jh2bh(jh);
2566 
2567 	lockdep_assert_held(&jh->b_state_lock);
2568 	if (jh->b_transaction)
2569 		assert_spin_locked(&jh->b_transaction->t_journal->j_list_lock);
2570 
2571 	/* If the buffer is now unused, just drop it. */
2572 	if (jh->b_next_transaction == NULL) {
2573 		__jbd2_journal_unfile_buffer(jh);
2574 		return true;
2575 	}
2576 
2577 	/*
2578 	 * It has been modified by a later transaction: add it to the new
2579 	 * transaction's metadata list.
2580 	 */
2581 
2582 	was_dirty = test_clear_buffer_jbddirty(bh);
2583 	__jbd2_journal_temp_unlink_buffer(jh);
2584 
2585 	/*
2586 	 * b_transaction must be set, otherwise the new b_transaction won't
2587 	 * be holding jh reference
2588 	 */
2589 	J_ASSERT_JH(jh, jh->b_transaction != NULL);
2590 
2591 	/*
2592 	 * We set b_transaction here because b_next_transaction will inherit
2593 	 * our jh reference and thus __jbd2_journal_file_buffer() must not
2594 	 * take a new one.
2595 	 */
2596 	WRITE_ONCE(jh->b_transaction, jh->b_next_transaction);
2597 	WRITE_ONCE(jh->b_next_transaction, NULL);
2598 	if (buffer_freed(bh))
2599 		jlist = BJ_Forget;
2600 	else if (jh->b_modified)
2601 		jlist = BJ_Metadata;
2602 	else
2603 		jlist = BJ_Reserved;
2604 	__jbd2_journal_file_buffer(jh, jh->b_transaction, jlist);
2605 	J_ASSERT_JH(jh, jh->b_transaction->t_state == T_RUNNING);
2606 
2607 	if (was_dirty)
2608 		set_buffer_jbddirty(bh);
2609 	return false;
2610 }
2611 
2612 /*
2613  * __jbd2_journal_refile_buffer() with necessary locking added. We take our
2614  * bh reference so that we can safely unlock bh.
2615  *
2616  * The jh and bh may be freed by this call.
2617  */
jbd2_journal_refile_buffer(journal_t * journal,struct journal_head * jh)2618 void jbd2_journal_refile_buffer(journal_t *journal, struct journal_head *jh)
2619 {
2620 	bool drop;
2621 
2622 	spin_lock(&jh->b_state_lock);
2623 	spin_lock(&journal->j_list_lock);
2624 	drop = __jbd2_journal_refile_buffer(jh);
2625 	spin_unlock(&jh->b_state_lock);
2626 	spin_unlock(&journal->j_list_lock);
2627 	if (drop)
2628 		jbd2_journal_put_journal_head(jh);
2629 }
2630 
2631 /*
2632  * File inode in the inode list of the handle's transaction
2633  */
jbd2_journal_file_inode(handle_t * handle,struct jbd2_inode * jinode,unsigned long flags,loff_t start_byte,loff_t end_byte)2634 static int jbd2_journal_file_inode(handle_t *handle, struct jbd2_inode *jinode,
2635 		unsigned long flags, loff_t start_byte, loff_t end_byte)
2636 {
2637 	transaction_t *transaction = handle->h_transaction;
2638 	journal_t *journal;
2639 
2640 	if (is_handle_aborted(handle))
2641 		return -EROFS;
2642 	journal = transaction->t_journal;
2643 
2644 	jbd2_debug(4, "Adding inode %lu, tid:%d\n", jinode->i_vfs_inode->i_ino,
2645 			transaction->t_tid);
2646 
2647 	spin_lock(&journal->j_list_lock);
2648 	jinode->i_flags |= flags;
2649 
2650 	if (jinode->i_dirty_end) {
2651 		jinode->i_dirty_start = min(jinode->i_dirty_start, start_byte);
2652 		jinode->i_dirty_end = max(jinode->i_dirty_end, end_byte);
2653 	} else {
2654 		jinode->i_dirty_start = start_byte;
2655 		jinode->i_dirty_end = end_byte;
2656 	}
2657 
2658 	/* Is inode already attached where we need it? */
2659 	if (jinode->i_transaction == transaction ||
2660 	    jinode->i_next_transaction == transaction)
2661 		goto done;
2662 
2663 	/*
2664 	 * We only ever set this variable to 1 so the test is safe. Since
2665 	 * t_need_data_flush is likely to be set, we do the test to save some
2666 	 * cacheline bouncing
2667 	 */
2668 	if (!transaction->t_need_data_flush)
2669 		transaction->t_need_data_flush = 1;
2670 	/* On some different transaction's list - should be
2671 	 * the committing one */
2672 	if (jinode->i_transaction) {
2673 		J_ASSERT(jinode->i_next_transaction == NULL);
2674 		J_ASSERT(jinode->i_transaction ==
2675 					journal->j_committing_transaction);
2676 		jinode->i_next_transaction = transaction;
2677 		goto done;
2678 	}
2679 	/* Not on any transaction list... */
2680 	J_ASSERT(!jinode->i_next_transaction);
2681 	jinode->i_transaction = transaction;
2682 	list_add(&jinode->i_list, &transaction->t_inode_list);
2683 done:
2684 	spin_unlock(&journal->j_list_lock);
2685 
2686 	return 0;
2687 }
2688 
jbd2_journal_inode_ranged_write(handle_t * handle,struct jbd2_inode * jinode,loff_t start_byte,loff_t length)2689 int jbd2_journal_inode_ranged_write(handle_t *handle,
2690 		struct jbd2_inode *jinode, loff_t start_byte, loff_t length)
2691 {
2692 	return jbd2_journal_file_inode(handle, jinode,
2693 			JI_WRITE_DATA | JI_WAIT_DATA, start_byte,
2694 			start_byte + length - 1);
2695 }
2696 
jbd2_journal_inode_ranged_wait(handle_t * handle,struct jbd2_inode * jinode,loff_t start_byte,loff_t length)2697 int jbd2_journal_inode_ranged_wait(handle_t *handle, struct jbd2_inode *jinode,
2698 		loff_t start_byte, loff_t length)
2699 {
2700 	return jbd2_journal_file_inode(handle, jinode, JI_WAIT_DATA,
2701 			start_byte, start_byte + length - 1);
2702 }
2703 
2704 /*
2705  * File truncate and transaction commit interact with each other in a
2706  * non-trivial way.  If a transaction writing data block A is
2707  * committing, we cannot discard the data by truncate until we have
2708  * written them.  Otherwise if we crashed after the transaction with
2709  * write has committed but before the transaction with truncate has
2710  * committed, we could see stale data in block A.  This function is a
2711  * helper to solve this problem.  It starts writeout of the truncated
2712  * part in case it is in the committing transaction.
2713  *
2714  * Filesystem code must call this function when inode is journaled in
2715  * ordered mode before truncation happens and after the inode has been
2716  * placed on orphan list with the new inode size. The second condition
2717  * avoids the race that someone writes new data and we start
2718  * committing the transaction after this function has been called but
2719  * before a transaction for truncate is started (and furthermore it
2720  * allows us to optimize the case where the addition to orphan list
2721  * happens in the same transaction as write --- we don't have to write
2722  * any data in such case).
2723  */
jbd2_journal_begin_ordered_truncate(journal_t * journal,struct jbd2_inode * jinode,loff_t new_size)2724 int jbd2_journal_begin_ordered_truncate(journal_t *journal,
2725 					struct jbd2_inode *jinode,
2726 					loff_t new_size)
2727 {
2728 	transaction_t *inode_trans, *commit_trans;
2729 	int ret = 0;
2730 
2731 	/* This is a quick check to avoid locking if not necessary */
2732 	if (!jinode->i_transaction)
2733 		goto out;
2734 	/* Locks are here just to force reading of recent values, it is
2735 	 * enough that the transaction was not committing before we started
2736 	 * a transaction adding the inode to orphan list */
2737 	read_lock(&journal->j_state_lock);
2738 	commit_trans = journal->j_committing_transaction;
2739 	read_unlock(&journal->j_state_lock);
2740 	spin_lock(&journal->j_list_lock);
2741 	inode_trans = jinode->i_transaction;
2742 	spin_unlock(&journal->j_list_lock);
2743 	if (inode_trans == commit_trans) {
2744 		ret = filemap_fdatawrite_range(jinode->i_vfs_inode->i_mapping,
2745 			new_size, LLONG_MAX);
2746 		if (ret)
2747 			jbd2_journal_abort(journal, ret);
2748 	}
2749 out:
2750 	return ret;
2751 }
2752