xref: /linux/fs/btrfs/transaction.c (revision 50c44fea13ec339d0d457079b254e8c8420d6511)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/fs.h>
7 #include <linux/slab.h>
8 #include <linux/sched.h>
9 #include <linux/sched/mm.h>
10 #include <linux/writeback.h>
11 #include <linux/pagemap.h>
12 #include <linux/blkdev.h>
13 #include <linux/uuid.h>
14 #include <linux/timekeeping.h>
15 #include "misc.h"
16 #include "ctree.h"
17 #include "disk-io.h"
18 #include "extent_io.h"
19 #include "transaction.h"
20 #include "locking.h"
21 #include "tree-log.h"
22 #include "volumes.h"
23 #include "dev-replace.h"
24 #include "qgroup.h"
25 #include "block-group.h"
26 #include "space-info.h"
27 #include "fs.h"
28 #include "accessors.h"
29 #include "extent-tree.h"
30 #include "root-tree.h"
31 #include "dir-item.h"
32 #include "uuid-tree.h"
33 #include "ioctl.h"
34 #include "relocation.h"
35 #include "scrub.h"
36 #include "ordered-data.h"
37 #include "delayed-inode.h"
38 
39 static struct kmem_cache *btrfs_trans_handle_cachep;
40 
41 /*
42  * Transaction states and transitions
43  *
44  * No running transaction (fs tree blocks are not modified)
45  * |
46  * | To next stage:
47  * |  Call start_transaction() variants. Except btrfs_join_transaction_nostart().
48  * V
49  * Transaction N [[TRANS_STATE_RUNNING]]
50  * |
51  * | New trans handles can be attached to transaction N by calling all
52  * | start_transaction() variants.
53  * |
54  * | To next stage:
55  * |  Call btrfs_commit_transaction() on any trans handle attached to
56  * |  transaction N
57  * V
58  * Transaction N [[TRANS_STATE_COMMIT_PREP]]
59  * |
60  * | If there are simultaneous calls to btrfs_commit_transaction() one will win
61  * | the race and the rest will wait for the winner to commit the transaction.
62  * |
63  * | The winner will wait for previous running transaction to completely finish
64  * | if there is one.
65  * |
66  * Transaction N [[TRANS_STATE_COMMIT_START]]
67  * |
68  * | Then one of the following happens:
69  * | - Wait for all other trans handle holders to release.
70  * |   The btrfs_commit_transaction() caller will do the commit work.
71  * | - Wait for current transaction to be committed by others.
72  * |   Other btrfs_commit_transaction() caller will do the commit work.
73  * |
74  * | At this stage, only btrfs_join_transaction*() variants can attach
75  * | to this running transaction.
76  * | All other variants will wait for current one to finish and attach to
77  * | transaction N+1.
78  * |
79  * | To next stage:
80  * |  Caller is chosen to commit transaction N, and all other trans handle
81  * |  haven been released.
82  * V
83  * Transaction N [[TRANS_STATE_COMMIT_DOING]]
84  * |
85  * | The heavy lifting transaction work is started.
86  * | From running delayed refs (modifying extent tree) to creating pending
87  * | snapshots, running qgroups.
88  * | In short, modify supporting trees to reflect modifications of subvolume
89  * | trees.
90  * |
91  * | At this stage, all start_transaction() calls will wait for this
92  * | transaction to finish and attach to transaction N+1.
93  * |
94  * | To next stage:
95  * |  Until all supporting trees are updated.
96  * V
97  * Transaction N [[TRANS_STATE_UNBLOCKED]]
98  * |						    Transaction N+1
99  * | All needed trees are modified, thus we only    [[TRANS_STATE_RUNNING]]
100  * | need to write them back to disk and update	    |
101  * | super blocks.				    |
102  * |						    |
103  * | At this stage, new transaction is allowed to   |
104  * | start.					    |
105  * | All new start_transaction() calls will be	    |
106  * | attached to transid N+1.			    |
107  * |						    |
108  * | To next stage:				    |
109  * |  Until all tree blocks and super blocks are    |
110  * |  written to block devices			    |
111  * V						    |
112  * Transaction N [[TRANS_STATE_COMPLETED]]	    V
113  *   All tree blocks and super blocks are written.  Transaction N+1
114  *   This transaction is finished and all its	    [[TRANS_STATE_COMMIT_START]]
115  *   data structures will be cleaned up.	    | Life goes on
116  */
117 static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
118 	[TRANS_STATE_RUNNING]		= 0U,
119 	[TRANS_STATE_COMMIT_PREP]	= 0U,
120 	[TRANS_STATE_COMMIT_START]	= (__TRANS_START | __TRANS_ATTACH),
121 	[TRANS_STATE_COMMIT_DOING]	= (__TRANS_START |
122 					   __TRANS_ATTACH |
123 					   __TRANS_JOIN |
124 					   __TRANS_JOIN_NOSTART),
125 	[TRANS_STATE_UNBLOCKED]		= (__TRANS_START |
126 					   __TRANS_ATTACH |
127 					   __TRANS_JOIN |
128 					   __TRANS_JOIN_NOLOCK |
129 					   __TRANS_JOIN_NOSTART),
130 	[TRANS_STATE_SUPER_COMMITTED]	= (__TRANS_START |
131 					   __TRANS_ATTACH |
132 					   __TRANS_JOIN |
133 					   __TRANS_JOIN_NOLOCK |
134 					   __TRANS_JOIN_NOSTART),
135 	[TRANS_STATE_COMPLETED]		= (__TRANS_START |
136 					   __TRANS_ATTACH |
137 					   __TRANS_JOIN |
138 					   __TRANS_JOIN_NOLOCK |
139 					   __TRANS_JOIN_NOSTART),
140 };
141 
btrfs_put_transaction(struct btrfs_transaction * transaction)142 void btrfs_put_transaction(struct btrfs_transaction *transaction)
143 {
144 	if (refcount_dec_and_test(&transaction->use_count)) {
145 		BUG_ON(!list_empty(&transaction->list));
146 		WARN_ON(!xa_empty(&transaction->delayed_refs.head_refs));
147 		WARN_ON(!xa_empty(&transaction->delayed_refs.dirty_extents));
148 		if (transaction->delayed_refs.pending_csums)
149 			btrfs_err(transaction->fs_info,
150 				  "pending csums is %llu",
151 				  transaction->delayed_refs.pending_csums);
152 		/*
153 		 * If any block groups are found in ->deleted_bgs then it's
154 		 * because the transaction was aborted and a commit did not
155 		 * happen (things failed before writing the new superblock
156 		 * and calling btrfs_finish_extent_commit()), so we can not
157 		 * discard the physical locations of the block groups.
158 		 */
159 		while (!list_empty(&transaction->deleted_bgs)) {
160 			struct btrfs_block_group *cache;
161 
162 			cache = list_first_entry(&transaction->deleted_bgs,
163 						 struct btrfs_block_group,
164 						 bg_list);
165 			/*
166 			 * Not strictly necessary to lock, as no other task will be using a
167 			 * block_group on the deleted_bgs list during a transaction abort.
168 			 */
169 			spin_lock(&transaction->fs_info->unused_bgs_lock);
170 			list_del_init(&cache->bg_list);
171 			spin_unlock(&transaction->fs_info->unused_bgs_lock);
172 			btrfs_unfreeze_block_group(cache);
173 			btrfs_put_block_group(cache);
174 		}
175 		WARN_ON(!list_empty(&transaction->dev_update_list));
176 		kfree(transaction);
177 	}
178 }
179 
switch_commit_roots(struct btrfs_trans_handle * trans)180 static noinline void switch_commit_roots(struct btrfs_trans_handle *trans)
181 {
182 	struct btrfs_transaction *cur_trans = trans->transaction;
183 	struct btrfs_fs_info *fs_info = trans->fs_info;
184 	struct btrfs_root *root, *tmp;
185 
186 	/*
187 	 * At this point no one can be using this transaction to modify any tree
188 	 * and no one can start another transaction to modify any tree either.
189 	 */
190 	ASSERT(cur_trans->state == TRANS_STATE_COMMIT_DOING,
191 	       "cur_trans->state=%d", cur_trans->state);
192 
193 	down_write(&fs_info->commit_root_sem);
194 
195 	if (test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
196 		fs_info->last_reloc_trans = trans->transid;
197 
198 	list_for_each_entry_safe(root, tmp, &cur_trans->switch_commits,
199 				 dirty_list) {
200 		list_del_init(&root->dirty_list);
201 		free_extent_buffer(root->commit_root);
202 		root->commit_root = btrfs_root_node(root);
203 		btrfs_extent_io_tree_release(&root->dirty_log_pages);
204 		btrfs_qgroup_clean_swapped_blocks(root);
205 	}
206 
207 	/* We can free old roots now. */
208 	spin_lock(&cur_trans->dropped_roots_lock);
209 	while (!list_empty(&cur_trans->dropped_roots)) {
210 		root = list_first_entry(&cur_trans->dropped_roots,
211 					struct btrfs_root, root_list);
212 		list_del_init(&root->root_list);
213 		spin_unlock(&cur_trans->dropped_roots_lock);
214 		btrfs_free_log(trans, root);
215 		btrfs_drop_and_free_fs_root(fs_info, root);
216 		spin_lock(&cur_trans->dropped_roots_lock);
217 	}
218 	spin_unlock(&cur_trans->dropped_roots_lock);
219 
220 	up_write(&fs_info->commit_root_sem);
221 }
222 
extwriter_counter_inc(struct btrfs_transaction * trans,unsigned int type)223 static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
224 					 unsigned int type)
225 {
226 	if (type & TRANS_EXTWRITERS)
227 		atomic_inc(&trans->num_extwriters);
228 }
229 
extwriter_counter_dec(struct btrfs_transaction * trans,unsigned int type)230 static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
231 					 unsigned int type)
232 {
233 	if (type & TRANS_EXTWRITERS)
234 		atomic_dec(&trans->num_extwriters);
235 }
236 
extwriter_counter_init(struct btrfs_transaction * trans,unsigned int type)237 static inline void extwriter_counter_init(struct btrfs_transaction *trans,
238 					  unsigned int type)
239 {
240 	atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
241 }
242 
extwriter_counter_read(struct btrfs_transaction * trans)243 static inline int extwriter_counter_read(struct btrfs_transaction *trans)
244 {
245 	return atomic_read(&trans->num_extwriters);
246 }
247 
248 /*
249  * To be called after doing the chunk btree updates right after allocating a new
250  * chunk (after btrfs_chunk_alloc_add_chunk_item() is called), when removing a
251  * chunk after all chunk btree updates and after finishing the second phase of
252  * chunk allocation (btrfs_create_pending_block_groups()) in case some block
253  * group had its chunk item insertion delayed to the second phase.
254  */
btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle * trans)255 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
256 {
257 	struct btrfs_fs_info *fs_info = trans->fs_info;
258 
259 	if (!trans->chunk_bytes_reserved)
260 		return;
261 
262 	btrfs_block_rsv_release(fs_info, &fs_info->chunk_block_rsv,
263 				trans->chunk_bytes_reserved, NULL);
264 	trans->chunk_bytes_reserved = 0;
265 }
266 
267 /*
268  * either allocate a new transaction or hop into the existing one
269  */
join_transaction(struct btrfs_fs_info * fs_info,unsigned int type)270 static noinline int join_transaction(struct btrfs_fs_info *fs_info,
271 				     unsigned int type)
272 {
273 	struct btrfs_transaction *cur_trans;
274 
275 	spin_lock(&fs_info->trans_lock);
276 loop:
277 	/* The file system has been taken offline. No new transactions. */
278 	if (unlikely(BTRFS_FS_ERROR(fs_info))) {
279 		spin_unlock(&fs_info->trans_lock);
280 		return -EROFS;
281 	}
282 
283 	cur_trans = fs_info->running_transaction;
284 	if (cur_trans) {
285 		if (TRANS_ABORTED(cur_trans)) {
286 			const int abort_error = cur_trans->aborted;
287 
288 			spin_unlock(&fs_info->trans_lock);
289 			return abort_error;
290 		}
291 		if (btrfs_blocked_trans_types[cur_trans->state] & type) {
292 			spin_unlock(&fs_info->trans_lock);
293 			return -EBUSY;
294 		}
295 		refcount_inc(&cur_trans->use_count);
296 		atomic_inc(&cur_trans->num_writers);
297 		extwriter_counter_inc(cur_trans, type);
298 		spin_unlock(&fs_info->trans_lock);
299 		btrfs_lockdep_acquire(fs_info, btrfs_trans_num_writers);
300 		btrfs_lockdep_acquire(fs_info, btrfs_trans_num_extwriters);
301 		return 0;
302 	}
303 	spin_unlock(&fs_info->trans_lock);
304 
305 	/*
306 	 * If we are ATTACH or TRANS_JOIN_NOSTART, we just want to catch the
307 	 * current transaction, and commit it. If there is no transaction, just
308 	 * return ENOENT.
309 	 */
310 	if (type == TRANS_ATTACH || type == TRANS_JOIN_NOSTART)
311 		return -ENOENT;
312 
313 	/*
314 	 * JOIN_NOLOCK only happens during the transaction commit, so
315 	 * it is impossible that ->running_transaction is NULL
316 	 */
317 	BUG_ON(type == TRANS_JOIN_NOLOCK);
318 
319 	cur_trans = kmalloc_obj(*cur_trans, GFP_NOFS);
320 	if (!cur_trans)
321 		return -ENOMEM;
322 
323 	btrfs_lockdep_acquire(fs_info, btrfs_trans_num_writers);
324 	btrfs_lockdep_acquire(fs_info, btrfs_trans_num_extwriters);
325 
326 	spin_lock(&fs_info->trans_lock);
327 	if (fs_info->running_transaction) {
328 		/*
329 		 * someone started a transaction after we unlocked.  Make sure
330 		 * to redo the checks above
331 		 */
332 		btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
333 		btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
334 		kfree(cur_trans);
335 		goto loop;
336 	} else if (unlikely(BTRFS_FS_ERROR(fs_info))) {
337 		spin_unlock(&fs_info->trans_lock);
338 		btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
339 		btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
340 		kfree(cur_trans);
341 		return -EROFS;
342 	}
343 
344 	cur_trans->fs_info = fs_info;
345 	atomic_set(&cur_trans->pending_ordered, 0);
346 	init_waitqueue_head(&cur_trans->pending_wait);
347 	atomic_set(&cur_trans->num_writers, 1);
348 	extwriter_counter_init(cur_trans, type);
349 	init_waitqueue_head(&cur_trans->writer_wait);
350 	init_waitqueue_head(&cur_trans->commit_wait);
351 	cur_trans->state = TRANS_STATE_RUNNING;
352 	/*
353 	 * One for this trans handle, one so it will live on until we
354 	 * commit the transaction.
355 	 */
356 	refcount_set(&cur_trans->use_count, 2);
357 	cur_trans->flags = 0;
358 	cur_trans->start_time = ktime_get_seconds();
359 
360 	memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
361 
362 	xa_init(&cur_trans->delayed_refs.head_refs);
363 	xa_init(&cur_trans->delayed_refs.dirty_extents);
364 
365 	/*
366 	 * although the tree mod log is per file system and not per transaction,
367 	 * the log must never go across transaction boundaries.
368 	 */
369 	smp_mb();
370 	if (!list_empty(&fs_info->tree_mod_seq_list))
371 		WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
372 	if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
373 		WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
374 	atomic64_set(&fs_info->tree_mod_seq, 0);
375 
376 	spin_lock_init(&cur_trans->delayed_refs.lock);
377 
378 	INIT_LIST_HEAD(&cur_trans->pending_snapshots);
379 	INIT_LIST_HEAD(&cur_trans->dev_update_list);
380 	INIT_LIST_HEAD(&cur_trans->switch_commits);
381 	INIT_LIST_HEAD(&cur_trans->dirty_bgs);
382 	INIT_LIST_HEAD(&cur_trans->io_bgs);
383 	INIT_LIST_HEAD(&cur_trans->dropped_roots);
384 	mutex_init(&cur_trans->cache_write_mutex);
385 	spin_lock_init(&cur_trans->dirty_bgs_lock);
386 	INIT_LIST_HEAD(&cur_trans->deleted_bgs);
387 	spin_lock_init(&cur_trans->dropped_roots_lock);
388 	list_add_tail(&cur_trans->list, &fs_info->trans_list);
389 	btrfs_extent_io_tree_init(fs_info, &cur_trans->dirty_pages,
390 				  IO_TREE_TRANS_DIRTY_PAGES);
391 	btrfs_extent_io_tree_init(fs_info, &cur_trans->pinned_extents,
392 				  IO_TREE_FS_PINNED_EXTENTS);
393 	btrfs_set_fs_generation(fs_info, fs_info->generation + 1);
394 	cur_trans->transid = fs_info->generation;
395 	fs_info->running_transaction = cur_trans;
396 	cur_trans->aborted = 0;
397 	trace_btrfs_transaction_start(cur_trans);
398 	spin_unlock(&fs_info->trans_lock);
399 
400 	return 0;
401 }
402 
403 /*
404  * This does all the record keeping required to make sure that a shareable root
405  * is properly recorded in a given transaction.  This is required to make sure
406  * the old root from before we joined the transaction is deleted when the
407  * transaction commits.
408  */
record_root_in_trans(struct btrfs_trans_handle * trans,struct btrfs_root * root,bool force)409 static int record_root_in_trans(struct btrfs_trans_handle *trans,
410 			       struct btrfs_root *root,
411 			       bool force)
412 {
413 	struct btrfs_fs_info *fs_info = root->fs_info;
414 	int ret = 0;
415 
416 	if ((test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
417 	    btrfs_get_root_last_trans(root) < trans->transid) || force) {
418 		WARN_ON(!force && root->commit_root != root->node);
419 
420 		/*
421 		 * see below for IN_TRANS_SETUP usage rules
422 		 * we have the reloc mutex held now, so there
423 		 * is only one writer in this function
424 		 */
425 		set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
426 
427 		/* make sure readers find IN_TRANS_SETUP before
428 		 * they find our root->last_trans update
429 		 */
430 		smp_wmb();
431 
432 		spin_lock(&fs_info->fs_roots_radix_lock);
433 		if (btrfs_get_root_last_trans(root) == trans->transid && !force) {
434 			spin_unlock(&fs_info->fs_roots_radix_lock);
435 			return 0;
436 		}
437 		radix_tree_tag_set(&fs_info->fs_roots_radix,
438 				   (unsigned long)btrfs_root_id(root),
439 				   BTRFS_ROOT_TRANS_TAG);
440 		spin_unlock(&fs_info->fs_roots_radix_lock);
441 		btrfs_set_root_last_trans(root, trans->transid);
442 
443 		/* this is pretty tricky.  We don't want to
444 		 * take the relocation lock in btrfs_record_root_in_trans
445 		 * unless we're really doing the first setup for this root in
446 		 * this transaction.
447 		 *
448 		 * Normally we'd use root->last_trans as a flag to decide
449 		 * if we want to take the expensive mutex.
450 		 *
451 		 * But, we have to set root->last_trans before we
452 		 * init the relocation root, otherwise, we trip over warnings
453 		 * in ctree.c.  The solution used here is to flag ourselves
454 		 * with root IN_TRANS_SETUP.  When this is 1, we're still
455 		 * fixing up the reloc trees and everyone must wait.
456 		 *
457 		 * When this is zero, they can trust root->last_trans and fly
458 		 * through btrfs_record_root_in_trans without having to take the
459 		 * lock.  smp_wmb() makes sure that all the writes above are
460 		 * done before we pop in the zero below
461 		 */
462 		ret = btrfs_init_reloc_root(trans, root);
463 		smp_mb__before_atomic();
464 		clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
465 	}
466 	return ret;
467 }
468 
469 
btrfs_add_dropped_root(struct btrfs_trans_handle * trans,struct btrfs_root * root)470 void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
471 			    struct btrfs_root *root)
472 {
473 	struct btrfs_fs_info *fs_info = root->fs_info;
474 	struct btrfs_transaction *cur_trans = trans->transaction;
475 
476 	/* Add ourselves to the transaction dropped list */
477 	spin_lock(&cur_trans->dropped_roots_lock);
478 	list_add_tail(&root->root_list, &cur_trans->dropped_roots);
479 	spin_unlock(&cur_trans->dropped_roots_lock);
480 
481 	/* Make sure we don't try to update the root at commit time */
482 	spin_lock(&fs_info->fs_roots_radix_lock);
483 	radix_tree_tag_clear(&fs_info->fs_roots_radix,
484 			     (unsigned long)btrfs_root_id(root),
485 			     BTRFS_ROOT_TRANS_TAG);
486 	spin_unlock(&fs_info->fs_roots_radix_lock);
487 }
488 
btrfs_record_root_in_trans(struct btrfs_trans_handle * trans,struct btrfs_root * root)489 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
490 			       struct btrfs_root *root)
491 {
492 	struct btrfs_fs_info *fs_info = root->fs_info;
493 	int ret;
494 
495 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
496 		return 0;
497 
498 	/*
499 	 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
500 	 * and barriers
501 	 */
502 	smp_rmb();
503 	if (btrfs_get_root_last_trans(root) == trans->transid &&
504 	    !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
505 		return 0;
506 
507 	mutex_lock(&fs_info->reloc_mutex);
508 	ret = record_root_in_trans(trans, root, false);
509 	mutex_unlock(&fs_info->reloc_mutex);
510 
511 	return ret;
512 }
513 
is_transaction_blocked(struct btrfs_transaction * trans)514 static inline int is_transaction_blocked(struct btrfs_transaction *trans)
515 {
516 	return (trans->state >= TRANS_STATE_COMMIT_START &&
517 		trans->state < TRANS_STATE_UNBLOCKED &&
518 		!TRANS_ABORTED(trans));
519 }
520 
521 /* wait for commit against the current transaction to become unblocked
522  * when this is done, it is safe to start a new transaction, but the current
523  * transaction might not be fully on disk.
524  */
wait_current_trans(struct btrfs_fs_info * fs_info,unsigned int type)525 static void wait_current_trans(struct btrfs_fs_info *fs_info, unsigned int type)
526 {
527 	struct btrfs_transaction *cur_trans;
528 
529 	spin_lock(&fs_info->trans_lock);
530 	cur_trans = fs_info->running_transaction;
531 	if (cur_trans && is_transaction_blocked(cur_trans) &&
532 	    (btrfs_blocked_trans_types[cur_trans->state] & type)) {
533 		refcount_inc(&cur_trans->use_count);
534 		spin_unlock(&fs_info->trans_lock);
535 
536 		btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
537 		wait_event(fs_info->transaction_wait,
538 			   cur_trans->state >= TRANS_STATE_UNBLOCKED ||
539 			   TRANS_ABORTED(cur_trans));
540 		btrfs_put_transaction(cur_trans);
541 	} else {
542 		spin_unlock(&fs_info->trans_lock);
543 	}
544 }
545 
may_wait_transaction(struct btrfs_fs_info * fs_info,int type)546 static bool may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
547 {
548 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
549 		return false;
550 
551 	if (type == TRANS_START)
552 		return true;
553 
554 	return false;
555 }
556 
need_reserve_reloc_root(struct btrfs_root * root)557 static inline bool need_reserve_reloc_root(struct btrfs_root *root)
558 {
559 	struct btrfs_fs_info *fs_info = root->fs_info;
560 
561 	if (!fs_info->reloc_ctl ||
562 	    !test_bit(BTRFS_ROOT_SHAREABLE, &root->state) ||
563 	    btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID ||
564 	    root->reloc_root)
565 		return false;
566 
567 	return true;
568 }
569 
btrfs_reserve_trans_metadata(struct btrfs_fs_info * fs_info,enum btrfs_reserve_flush_enum flush,u64 num_bytes,u64 * delayed_refs_bytes)570 static int btrfs_reserve_trans_metadata(struct btrfs_fs_info *fs_info,
571 					enum btrfs_reserve_flush_enum flush,
572 					u64 num_bytes,
573 					u64 *delayed_refs_bytes)
574 {
575 	struct btrfs_space_info *si = fs_info->trans_block_rsv.space_info;
576 	u64 bytes = num_bytes + *delayed_refs_bytes;
577 	int ret;
578 
579 	/*
580 	 * We want to reserve all the bytes we may need all at once, so we only
581 	 * do 1 enospc flushing cycle per transaction start.
582 	 */
583 	ret = btrfs_reserve_metadata_bytes(si, bytes, flush);
584 
585 	/*
586 	 * If we are an emergency flush, which can steal from the global block
587 	 * reserve, then attempt to not reserve space for the delayed refs, as
588 	 * we will consume space for them from the global block reserve.
589 	 */
590 	if (ret && flush == BTRFS_RESERVE_FLUSH_ALL_STEAL) {
591 		bytes -= *delayed_refs_bytes;
592 		*delayed_refs_bytes = 0;
593 		ret = btrfs_reserve_metadata_bytes(si, bytes, flush);
594 	}
595 
596 	return ret;
597 }
598 
599 static struct btrfs_trans_handle *
start_transaction(struct btrfs_root * root,unsigned int num_items,unsigned int type,enum btrfs_reserve_flush_enum flush,bool enforce_qgroups)600 start_transaction(struct btrfs_root *root, unsigned int num_items,
601 		  unsigned int type, enum btrfs_reserve_flush_enum flush,
602 		  bool enforce_qgroups)
603 {
604 	struct btrfs_fs_info *fs_info = root->fs_info;
605 	struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
606 	struct btrfs_block_rsv *trans_rsv = &fs_info->trans_block_rsv;
607 	struct btrfs_trans_handle *h;
608 	struct btrfs_transaction *cur_trans;
609 	u64 num_bytes = 0;
610 	u64 qgroup_reserved = 0;
611 	u64 delayed_refs_bytes = 0;
612 	bool reloc_reserved = false;
613 	bool do_chunk_alloc = false;
614 	int ret;
615 
616 	if (unlikely(BTRFS_FS_ERROR(fs_info)))
617 		return ERR_PTR(-EROFS);
618 
619 	if (current->journal_info) {
620 		WARN_ON(type & TRANS_EXTWRITERS);
621 		h = current->journal_info;
622 		refcount_inc(&h->use_count);
623 		WARN_ON(refcount_read(&h->use_count) > 2);
624 		h->orig_rsv = h->block_rsv;
625 		h->block_rsv = NULL;
626 		goto got_it;
627 	}
628 
629 	/*
630 	 * Do the reservation before we join the transaction so we can do all
631 	 * the appropriate flushing if need be.
632 	 */
633 	if (num_items && root != fs_info->chunk_root) {
634 		qgroup_reserved = (num_items << fs_info->nodesize_bits);
635 		/*
636 		 * Use prealloc for now, as there might be a currently running
637 		 * transaction that could free this reserved space prematurely
638 		 * by committing.
639 		 */
640 		ret = btrfs_qgroup_reserve_meta_prealloc(root, qgroup_reserved,
641 							 enforce_qgroups, false);
642 		if (ret)
643 			return ERR_PTR(ret);
644 
645 		num_bytes = btrfs_calc_insert_metadata_size(fs_info, num_items);
646 		/*
647 		 * If we plan to insert/update/delete "num_items" from a btree,
648 		 * we will also generate delayed refs for extent buffers in the
649 		 * respective btree paths, so reserve space for the delayed refs
650 		 * that will be generated by the caller as it modifies btrees.
651 		 * Try to reserve them to avoid excessive use of the global
652 		 * block reserve.
653 		 */
654 		delayed_refs_bytes = btrfs_calc_delayed_ref_bytes(fs_info, num_items);
655 
656 		/*
657 		 * Do the reservation for the relocation root creation
658 		 */
659 		if (need_reserve_reloc_root(root)) {
660 			num_bytes += fs_info->nodesize;
661 			reloc_reserved = true;
662 		}
663 
664 		ret = btrfs_reserve_trans_metadata(fs_info, flush, num_bytes,
665 						   &delayed_refs_bytes);
666 		if (ret)
667 			goto reserve_fail;
668 
669 		btrfs_block_rsv_add_bytes(trans_rsv, num_bytes, true);
670 
671 		if (trans_rsv->space_info->force_alloc)
672 			do_chunk_alloc = true;
673 	} else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
674 		   !btrfs_block_rsv_full(delayed_refs_rsv)) {
675 		/*
676 		 * Some people call with btrfs_start_transaction(root, 0)
677 		 * because they can be throttled, but have some other mechanism
678 		 * for reserving space.  We still want these guys to refill the
679 		 * delayed block_rsv so just add 1 items worth of reservation
680 		 * here.
681 		 */
682 		ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
683 		if (ret == -EAGAIN) {
684 			ASSERT(btrfs_is_zoned(fs_info));
685 			ret = btrfs_commit_current_transaction(root);
686 			if (ret)
687 				goto reserve_fail;
688 			ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
689 		}
690 
691 		if (ret)
692 			goto reserve_fail;
693 	}
694 again:
695 	h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
696 	if (!h) {
697 		ret = -ENOMEM;
698 		goto alloc_fail;
699 	}
700 
701 	/*
702 	 * If we are JOIN_NOLOCK we're already committing a transaction and
703 	 * waiting on this guy, so we don't need to do the sb_start_intwrite
704 	 * because we're already holding a ref.  We need this because we could
705 	 * have raced in and did an fsync() on a file which can kick a commit
706 	 * and then we deadlock with somebody doing a freeze.
707 	 *
708 	 * If we are ATTACH, it means we just want to catch the current
709 	 * transaction and commit it, so we needn't do sb_start_intwrite().
710 	 */
711 	if (type & __TRANS_FREEZABLE)
712 		sb_start_intwrite(fs_info->sb);
713 
714 	if (may_wait_transaction(fs_info, type))
715 		wait_current_trans(fs_info, type);
716 
717 	do {
718 		ret = join_transaction(fs_info, type);
719 		if (ret == -EBUSY) {
720 			wait_current_trans(fs_info, type);
721 			if (unlikely(type == TRANS_ATTACH ||
722 				     type == TRANS_JOIN_NOSTART))
723 				ret = -ENOENT;
724 		}
725 	} while (ret == -EBUSY);
726 
727 	if (ret < 0)
728 		goto join_fail;
729 
730 	cur_trans = fs_info->running_transaction;
731 
732 	h->transid = cur_trans->transid;
733 	h->transaction = cur_trans;
734 	refcount_set(&h->use_count, 1);
735 	h->fs_info = root->fs_info;
736 
737 	h->type = type;
738 	INIT_LIST_HEAD(&h->new_bgs);
739 	btrfs_init_metadata_block_rsv(fs_info, &h->delayed_rsv, BTRFS_BLOCK_RSV_DELREFS);
740 
741 	smp_mb();
742 	if (cur_trans->state >= TRANS_STATE_COMMIT_START &&
743 	    may_wait_transaction(fs_info, type)) {
744 		current->journal_info = h;
745 		btrfs_commit_transaction(h);
746 		goto again;
747 	}
748 
749 	if (num_bytes) {
750 		trace_btrfs_space_reservation(fs_info, "transaction",
751 					      h->transid, num_bytes, 1);
752 		h->block_rsv = trans_rsv;
753 		h->bytes_reserved = num_bytes;
754 		if (delayed_refs_bytes > 0) {
755 			trace_btrfs_space_reservation(fs_info,
756 						      "local_delayed_refs_rsv",
757 						      h->transid,
758 						      delayed_refs_bytes, 1);
759 			h->delayed_refs_bytes_reserved = delayed_refs_bytes;
760 			btrfs_block_rsv_add_bytes(&h->delayed_rsv, delayed_refs_bytes, true);
761 			delayed_refs_bytes = 0;
762 		}
763 		h->reloc_reserved = reloc_reserved;
764 	}
765 
766 got_it:
767 	if (!current->journal_info)
768 		current->journal_info = h;
769 
770 	/*
771 	 * If the space_info is marked ALLOC_FORCE then we'll get upgraded to
772 	 * ALLOC_FORCE the first run through, and then we won't allocate for
773 	 * anybody else who races in later.  We don't care about the return
774 	 * value here.
775 	 */
776 	if (do_chunk_alloc && num_bytes) {
777 		struct btrfs_space_info *space_info = h->block_rsv->space_info;
778 		u64 flags = space_info->flags;
779 
780 		btrfs_chunk_alloc(h, space_info, btrfs_get_alloc_profile(fs_info, flags),
781 				  CHUNK_ALLOC_NO_FORCE);
782 	}
783 
784 	/*
785 	 * btrfs_record_root_in_trans() needs to alloc new extents, and may
786 	 * call btrfs_join_transaction() while we're also starting a
787 	 * transaction.
788 	 *
789 	 * Thus it need to be called after current->journal_info initialized,
790 	 * or we can deadlock.
791 	 */
792 	ret = btrfs_record_root_in_trans(h, root);
793 	if (ret) {
794 		/*
795 		 * The transaction handle is fully initialized and linked with
796 		 * other structures so it needs to be ended in case of errors,
797 		 * not just freed.
798 		 */
799 		btrfs_end_transaction(h);
800 		goto reserve_fail;
801 	}
802 	/*
803 	 * Now that we have found a transaction to be a part of, convert the
804 	 * qgroup reservation from prealloc to pertrans. A different transaction
805 	 * can't race in and free our pertrans out from under us.
806 	 */
807 	if (qgroup_reserved)
808 		btrfs_qgroup_convert_reserved_meta(root, qgroup_reserved);
809 
810 	return h;
811 
812 join_fail:
813 	if (type & __TRANS_FREEZABLE)
814 		sb_end_intwrite(fs_info->sb);
815 	kmem_cache_free(btrfs_trans_handle_cachep, h);
816 alloc_fail:
817 	if (num_bytes)
818 		btrfs_block_rsv_release(fs_info, trans_rsv, num_bytes, NULL);
819 	if (delayed_refs_bytes)
820 		btrfs_space_info_free_bytes_may_use(trans_rsv->space_info, delayed_refs_bytes);
821 reserve_fail:
822 	btrfs_qgroup_free_meta_prealloc(root, qgroup_reserved);
823 	return ERR_PTR(ret);
824 }
825 
btrfs_start_transaction(struct btrfs_root * root,unsigned int num_items)826 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
827 						   unsigned int num_items)
828 {
829 	return start_transaction(root, num_items, TRANS_START,
830 				 BTRFS_RESERVE_FLUSH_ALL, true);
831 }
832 
btrfs_start_transaction_fallback_global_rsv(struct btrfs_root * root,unsigned int num_items)833 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
834 					struct btrfs_root *root,
835 					unsigned int num_items)
836 {
837 	return start_transaction(root, num_items, TRANS_START,
838 				 BTRFS_RESERVE_FLUSH_ALL_STEAL, false);
839 }
840 
btrfs_join_transaction(struct btrfs_root * root)841 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
842 {
843 	return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
844 				 true);
845 }
846 
btrfs_join_transaction_spacecache(struct btrfs_root * root)847 struct btrfs_trans_handle *btrfs_join_transaction_spacecache(struct btrfs_root *root)
848 {
849 	return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
850 				 BTRFS_RESERVE_NO_FLUSH, true);
851 }
852 
853 /*
854  * Similar to regular join but it never starts a transaction when none is
855  * running or when there's a running one at a state >= TRANS_STATE_UNBLOCKED.
856  * This is similar to btrfs_attach_transaction() but it allows the join to
857  * happen if the transaction commit already started but it's not yet in the
858  * "doing" phase (the state is < TRANS_STATE_COMMIT_DOING).
859  */
btrfs_join_transaction_nostart(struct btrfs_root * root)860 struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
861 {
862 	return start_transaction(root, 0, TRANS_JOIN_NOSTART,
863 				 BTRFS_RESERVE_NO_FLUSH, true);
864 }
865 
866 /*
867  * Catch the running transaction.
868  *
869  * It is used when we want to commit the current the transaction, but
870  * don't want to start a new one.
871  *
872  * Note: If this function return -ENOENT, it just means there is no
873  * running transaction. But it is possible that the inactive transaction
874  * is still in the memory, not fully on disk. If you hope there is no
875  * inactive transaction in the fs when -ENOENT is returned, you should
876  * invoke
877  *     btrfs_attach_transaction_barrier()
878  */
btrfs_attach_transaction(struct btrfs_root * root)879 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
880 {
881 	return start_transaction(root, 0, TRANS_ATTACH,
882 				 BTRFS_RESERVE_NO_FLUSH, true);
883 }
884 
885 /*
886  * Catch the running transaction.
887  *
888  * It is similar to the above function, the difference is this one
889  * will wait for all the inactive transactions until they fully
890  * complete.
891  */
892 struct btrfs_trans_handle *
btrfs_attach_transaction_barrier(struct btrfs_root * root)893 btrfs_attach_transaction_barrier(struct btrfs_root *root)
894 {
895 	struct btrfs_trans_handle *trans;
896 
897 	trans = start_transaction(root, 0, TRANS_ATTACH,
898 				  BTRFS_RESERVE_NO_FLUSH, true);
899 	if (trans == ERR_PTR(-ENOENT)) {
900 		int ret;
901 
902 		ret = btrfs_wait_for_commit(root->fs_info, 0);
903 		if (ret)
904 			return ERR_PTR(ret);
905 	}
906 
907 	return trans;
908 }
909 
910 /* Wait for a transaction commit to reach at least the given state. */
wait_for_commit(struct btrfs_transaction * commit,const enum btrfs_trans_state min_state)911 static noinline void wait_for_commit(struct btrfs_transaction *commit,
912 				     const enum btrfs_trans_state min_state)
913 {
914 	struct btrfs_fs_info *fs_info = commit->fs_info;
915 	u64 transid = commit->transid;
916 	bool put = false;
917 
918 	/*
919 	 * At the moment this function is called with min_state either being
920 	 * TRANS_STATE_COMPLETED or TRANS_STATE_SUPER_COMMITTED.
921 	 */
922 	if (min_state == TRANS_STATE_COMPLETED)
923 		btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
924 	else
925 		btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
926 
927 	while (1) {
928 		wait_event(commit->commit_wait, commit->state >= min_state);
929 		if (put)
930 			btrfs_put_transaction(commit);
931 
932 		if (min_state < TRANS_STATE_COMPLETED)
933 			break;
934 
935 		/*
936 		 * A transaction isn't really completed until all of the
937 		 * previous transactions are completed, but with fsync we can
938 		 * end up with SUPER_COMMITTED transactions before a COMPLETED
939 		 * transaction. Wait for those.
940 		 */
941 
942 		spin_lock(&fs_info->trans_lock);
943 		commit = list_first_entry_or_null(&fs_info->trans_list,
944 						  struct btrfs_transaction,
945 						  list);
946 		if (!commit || commit->transid > transid) {
947 			spin_unlock(&fs_info->trans_lock);
948 			break;
949 		}
950 		refcount_inc(&commit->use_count);
951 		put = true;
952 		spin_unlock(&fs_info->trans_lock);
953 	}
954 }
955 
btrfs_wait_for_commit(struct btrfs_fs_info * fs_info,u64 transid)956 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
957 {
958 	struct btrfs_transaction *cur_trans = NULL, *t;
959 	int ret = 0;
960 
961 	if (transid) {
962 		if (transid <= btrfs_get_last_trans_committed(fs_info))
963 			return 0;
964 
965 		/* find specified transaction */
966 		spin_lock(&fs_info->trans_lock);
967 		list_for_each_entry(t, &fs_info->trans_list, list) {
968 			if (t->transid == transid) {
969 				cur_trans = t;
970 				refcount_inc(&cur_trans->use_count);
971 				ret = 0;
972 				break;
973 			}
974 			if (t->transid > transid) {
975 				ret = 0;
976 				break;
977 			}
978 		}
979 		spin_unlock(&fs_info->trans_lock);
980 
981 		/*
982 		 * The specified transaction doesn't exist, or we
983 		 * raced with btrfs_commit_transaction
984 		 */
985 		if (!cur_trans) {
986 			if (transid > btrfs_get_last_trans_committed(fs_info))
987 				ret = -EINVAL;
988 			return ret;
989 		}
990 	} else {
991 		/* find newest transaction that is committing | committed */
992 		spin_lock(&fs_info->trans_lock);
993 		list_for_each_entry_reverse(t, &fs_info->trans_list,
994 					    list) {
995 			if (t->state >= TRANS_STATE_COMMIT_START) {
996 				if (t->state == TRANS_STATE_COMPLETED)
997 					break;
998 				cur_trans = t;
999 				refcount_inc(&cur_trans->use_count);
1000 				break;
1001 			}
1002 		}
1003 		spin_unlock(&fs_info->trans_lock);
1004 		/* Nothing committing or committed. */
1005 		if (!cur_trans)
1006 			return ret;
1007 	}
1008 
1009 	wait_for_commit(cur_trans, TRANS_STATE_COMPLETED);
1010 	ret = cur_trans->aborted;
1011 	btrfs_put_transaction(cur_trans);
1012 
1013 	return ret;
1014 }
1015 
btrfs_throttle(struct btrfs_fs_info * fs_info)1016 void btrfs_throttle(struct btrfs_fs_info *fs_info)
1017 {
1018 	wait_current_trans(fs_info, TRANS_START);
1019 }
1020 
btrfs_should_end_transaction(struct btrfs_trans_handle * trans)1021 bool btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
1022 {
1023 	struct btrfs_transaction *cur_trans = trans->transaction;
1024 
1025 	if (cur_trans->state >= TRANS_STATE_COMMIT_START ||
1026 	    test_bit(BTRFS_DELAYED_REFS_FLUSHING, &cur_trans->delayed_refs.flags))
1027 		return true;
1028 
1029 	if (btrfs_check_space_for_delayed_refs(trans->fs_info))
1030 		return true;
1031 
1032 	return !!btrfs_block_rsv_check(&trans->fs_info->global_block_rsv, 50);
1033 }
1034 
btrfs_trans_release_metadata(struct btrfs_trans_handle * trans)1035 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
1036 
1037 {
1038 	struct btrfs_fs_info *fs_info = trans->fs_info;
1039 
1040 	if (!trans->block_rsv) {
1041 		ASSERT(trans->bytes_reserved == 0,
1042 		       "trans->bytes_reserved=%llu", trans->bytes_reserved);
1043 		ASSERT(trans->delayed_refs_bytes_reserved == 0,
1044 		       "trans->delayed_refs_bytes_reserved=%llu",
1045 		       trans->delayed_refs_bytes_reserved);
1046 		return;
1047 	}
1048 
1049 	if (!trans->bytes_reserved) {
1050 		ASSERT(trans->delayed_refs_bytes_reserved == 0,
1051 		       "trans->delayed_refs_bytes_reserved=%llu",
1052 		       trans->delayed_refs_bytes_reserved);
1053 		return;
1054 	}
1055 
1056 	ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
1057 	trace_btrfs_space_reservation(fs_info, "transaction",
1058 				      trans->transid, trans->bytes_reserved, 0);
1059 	btrfs_block_rsv_release(fs_info, trans->block_rsv,
1060 				trans->bytes_reserved, NULL);
1061 	trans->bytes_reserved = 0;
1062 
1063 	if (!trans->delayed_refs_bytes_reserved)
1064 		return;
1065 
1066 	trace_btrfs_space_reservation(fs_info, "local_delayed_refs_rsv",
1067 				      trans->transid,
1068 				      trans->delayed_refs_bytes_reserved, 0);
1069 	btrfs_block_rsv_release(fs_info, &trans->delayed_rsv,
1070 				trans->delayed_refs_bytes_reserved, NULL);
1071 	trans->delayed_refs_bytes_reserved = 0;
1072 }
1073 
__btrfs_end_transaction(struct btrfs_trans_handle * trans,int throttle)1074 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
1075 				   int throttle)
1076 {
1077 	struct btrfs_fs_info *info = trans->fs_info;
1078 	struct btrfs_transaction *cur_trans = trans->transaction;
1079 	int ret = 0;
1080 
1081 	if (refcount_read(&trans->use_count) > 1) {
1082 		refcount_dec(&trans->use_count);
1083 		trans->block_rsv = trans->orig_rsv;
1084 		return 0;
1085 	}
1086 
1087 	btrfs_trans_release_metadata(trans);
1088 	trans->block_rsv = NULL;
1089 
1090 	btrfs_create_pending_block_groups(trans);
1091 
1092 	btrfs_trans_release_chunk_metadata(trans);
1093 
1094 	if (trans->type & __TRANS_FREEZABLE)
1095 		sb_end_intwrite(info->sb);
1096 
1097 	/*
1098 	 * Uninhibit extent buffer writeback before decrementing num_writers,
1099 	 * since the decrement wakes the committing thread which needs all
1100 	 * buffers uninhibited to write them to disk.
1101 	 */
1102 	btrfs_uninhibit_all_eb_writeback(trans);
1103 
1104 	WARN_ON(cur_trans != info->running_transaction);
1105 	WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
1106 	atomic_dec(&cur_trans->num_writers);
1107 	extwriter_counter_dec(cur_trans, trans->type);
1108 
1109 	cond_wake_up(&cur_trans->writer_wait);
1110 
1111 	btrfs_lockdep_release(info, btrfs_trans_num_extwriters);
1112 	btrfs_lockdep_release(info, btrfs_trans_num_writers);
1113 
1114 	btrfs_put_transaction(cur_trans);
1115 
1116 	if (current->journal_info == trans)
1117 		current->journal_info = NULL;
1118 
1119 	if (throttle)
1120 		btrfs_run_delayed_iputs(info);
1121 
1122 	if (unlikely(TRANS_ABORTED(trans) || BTRFS_FS_ERROR(info))) {
1123 		wake_up_process(info->transaction_kthread);
1124 		if (TRANS_ABORTED(trans))
1125 			ret = trans->aborted;
1126 		else
1127 			ret = -EROFS;
1128 	}
1129 
1130 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
1131 	return ret;
1132 }
1133 
btrfs_end_transaction(struct btrfs_trans_handle * trans)1134 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
1135 {
1136 	return __btrfs_end_transaction(trans, 0);
1137 }
1138 
btrfs_end_transaction_throttle(struct btrfs_trans_handle * trans)1139 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
1140 {
1141 	return __btrfs_end_transaction(trans, 1);
1142 }
1143 
1144 /*
1145  * when btree blocks are allocated, they have some corresponding bits set for
1146  * them in one of two extent_io trees.  This is used to make sure all of
1147  * those extents are sent to disk but does not wait on them
1148  */
btrfs_write_marked_extents(struct btrfs_fs_info * fs_info,struct extent_io_tree * dirty_pages,int mark)1149 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
1150 			       struct extent_io_tree *dirty_pages, int mark)
1151 {
1152 	int ret = 0;
1153 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
1154 	struct extent_state *cached_state = NULL;
1155 	u64 start = 0;
1156 	u64 end;
1157 
1158 	while (btrfs_find_first_extent_bit(dirty_pages, start, &start, &end,
1159 					   mark, &cached_state)) {
1160 		bool wait_writeback = false;
1161 
1162 		ret = btrfs_convert_extent_bit(dirty_pages, start, end,
1163 					       EXTENT_NEED_WAIT,
1164 					       mark, &cached_state);
1165 		/*
1166 		 * convert_extent_bit can return -ENOMEM, which is most of the
1167 		 * time a temporary error. So when it happens, ignore the error
1168 		 * and wait for writeback of this range to finish - because we
1169 		 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
1170 		 * to __btrfs_wait_marked_extents() would not know that
1171 		 * writeback for this range started and therefore wouldn't
1172 		 * wait for it to finish - we don't want to commit a
1173 		 * superblock that points to btree nodes/leafs for which
1174 		 * writeback hasn't finished yet (and without errors).
1175 		 * We cleanup any entries left in the io tree when committing
1176 		 * the transaction (through extent_io_tree_release()).
1177 		 */
1178 		if (ret == -ENOMEM) {
1179 			ret = 0;
1180 			wait_writeback = true;
1181 		}
1182 		if (!ret)
1183 			ret = filemap_fdatawrite_range(mapping, start, end);
1184 		if (!ret && wait_writeback)
1185 			btrfs_btree_wait_writeback_range(fs_info, start, end);
1186 		btrfs_free_extent_state(cached_state);
1187 		if (ret)
1188 			break;
1189 		cached_state = NULL;
1190 		cond_resched();
1191 		start = end + 1;
1192 	}
1193 	return ret;
1194 }
1195 
1196 /*
1197  * when btree blocks are allocated, they have some corresponding bits set for
1198  * them in one of two extent_io trees.  This is used to make sure all of
1199  * those extents are on disk for transaction or log commit.  We wait
1200  * on all the pages and clear them from the dirty pages state tree
1201  */
__btrfs_wait_marked_extents(struct btrfs_fs_info * fs_info,struct extent_io_tree * dirty_pages)1202 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
1203 				       struct extent_io_tree *dirty_pages)
1204 {
1205 	struct extent_state *cached_state = NULL;
1206 	u64 start = 0;
1207 	u64 end;
1208 	int ret = 0;
1209 
1210 	while (btrfs_find_first_extent_bit(dirty_pages, start, &start, &end,
1211 					   EXTENT_NEED_WAIT, &cached_state)) {
1212 		/*
1213 		 * Ignore -ENOMEM errors returned by clear_extent_bit().
1214 		 * When committing the transaction, we'll remove any entries
1215 		 * left in the io tree. For a log commit, we don't remove them
1216 		 * after committing the log because the tree can be accessed
1217 		 * concurrently - we do it only at transaction commit time when
1218 		 * it's safe to do it (through extent_io_tree_release()).
1219 		 */
1220 		ret = btrfs_clear_extent_bit(dirty_pages, start, end,
1221 					     EXTENT_NEED_WAIT, &cached_state);
1222 		if (ret == -ENOMEM)
1223 			ret = 0;
1224 		if (!ret)
1225 			btrfs_btree_wait_writeback_range(fs_info, start, end);
1226 		btrfs_free_extent_state(cached_state);
1227 		if (ret)
1228 			break;
1229 		cached_state = NULL;
1230 		cond_resched();
1231 		start = end + 1;
1232 	}
1233 	return ret;
1234 }
1235 
btrfs_wait_extents(struct btrfs_fs_info * fs_info,struct extent_io_tree * dirty_pages)1236 static int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1237 		       struct extent_io_tree *dirty_pages)
1238 {
1239 	bool errors = false;
1240 	int ret;
1241 
1242 	ret = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1243 	if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1244 		errors = true;
1245 
1246 	if (errors && !ret)
1247 		ret = -EIO;
1248 	return ret;
1249 }
1250 
btrfs_wait_tree_log_extents(struct btrfs_root * log_root,int mark)1251 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1252 {
1253 	struct btrfs_fs_info *fs_info = log_root->fs_info;
1254 	struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1255 	bool errors = false;
1256 	int ret;
1257 
1258 	ASSERT(btrfs_root_id(log_root) == BTRFS_TREE_LOG_OBJECTID,
1259 	       "root_id(log_root)=%llu", btrfs_root_id(log_root));
1260 
1261 	ret = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1262 	if ((mark & EXTENT_DIRTY_LOG1) &&
1263 	    test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1264 		errors = true;
1265 
1266 	if ((mark & EXTENT_DIRTY_LOG2) &&
1267 	    test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1268 		errors = true;
1269 
1270 	if (errors && !ret)
1271 		ret = -EIO;
1272 	return ret;
1273 }
1274 
1275 /*
1276  * When btree blocks are allocated the corresponding extents are marked dirty.
1277  * This function ensures such extents are persisted on disk for transaction or
1278  * log commit.
1279  *
1280  * @trans: transaction whose dirty pages we'd like to write
1281  */
btrfs_write_and_wait_transaction(struct btrfs_trans_handle * trans)1282 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1283 {
1284 	int ret;
1285 	int ret2;
1286 	struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
1287 	struct btrfs_fs_info *fs_info = trans->fs_info;
1288 	struct blk_plug plug;
1289 
1290 	blk_start_plug(&plug);
1291 	ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1292 	blk_finish_plug(&plug);
1293 	ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1294 
1295 	if (ret)
1296 		return ret;
1297 	if (ret2)
1298 		return ret2;
1299 
1300 	btrfs_extent_io_tree_release(&trans->transaction->dirty_pages);
1301 	return 0;
1302 }
1303 
1304 /*
1305  * this is used to update the root pointer in the tree of tree roots.
1306  *
1307  * But, in the case of the extent allocation tree, updating the root
1308  * pointer may allocate blocks which may change the root of the extent
1309  * allocation tree.
1310  *
1311  * So, this loops and repeats and makes sure the cowonly root didn't
1312  * change while the root pointer was being updated in the metadata.
1313  */
update_cowonly_root(struct btrfs_trans_handle * trans,struct btrfs_root * root)1314 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1315 			       struct btrfs_root *root)
1316 {
1317 	int ret;
1318 	u64 old_root_bytenr;
1319 	u64 old_root_used;
1320 	struct btrfs_fs_info *fs_info = root->fs_info;
1321 	struct btrfs_root *tree_root = fs_info->tree_root;
1322 
1323 	old_root_used = btrfs_root_used(&root->root_item);
1324 
1325 	while (1) {
1326 		old_root_bytenr = btrfs_root_bytenr(&root->root_item);
1327 		if (old_root_bytenr == root->node->start &&
1328 		    old_root_used == btrfs_root_used(&root->root_item))
1329 			break;
1330 
1331 		btrfs_set_root_node(&root->root_item, root->node);
1332 		ret = btrfs_update_root(trans, tree_root,
1333 					&root->root_key,
1334 					&root->root_item);
1335 		if (ret)
1336 			return ret;
1337 
1338 		old_root_used = btrfs_root_used(&root->root_item);
1339 	}
1340 
1341 	return 0;
1342 }
1343 
1344 /*
1345  * update all the cowonly tree roots on disk
1346  *
1347  * The error handling in this function may not be obvious. Any of the
1348  * failures will cause the file system to go offline. We still need
1349  * to clean up the delayed refs.
1350  */
commit_cowonly_roots(struct btrfs_trans_handle * trans)1351 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
1352 {
1353 	struct btrfs_fs_info *fs_info = trans->fs_info;
1354 	struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1355 	struct list_head *io_bgs = &trans->transaction->io_bgs;
1356 	struct extent_buffer *eb;
1357 	int ret;
1358 
1359 	/*
1360 	 * At this point no one can be using this transaction to modify any tree
1361 	 * and no one can start another transaction to modify any tree either.
1362 	 */
1363 	ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING,
1364 	       "trans->transaction->state=%d", trans->transaction->state);
1365 
1366 	eb = btrfs_lock_root_node(fs_info->tree_root);
1367 	ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
1368 			      0, &eb, BTRFS_NESTING_COW);
1369 	btrfs_tree_unlock(eb);
1370 	free_extent_buffer(eb);
1371 
1372 	if (ret)
1373 		return ret;
1374 
1375 	ret = btrfs_run_dev_stats(trans);
1376 	if (ret)
1377 		return ret;
1378 	ret = btrfs_run_dev_replace(trans);
1379 	if (ret)
1380 		return ret;
1381 	ret = btrfs_run_qgroups(trans);
1382 	if (ret)
1383 		return ret;
1384 
1385 	ret = btrfs_setup_space_cache(trans);
1386 	if (ret)
1387 		return ret;
1388 
1389 again:
1390 	while (!list_empty(&fs_info->dirty_cowonly_roots)) {
1391 		struct btrfs_root *root;
1392 
1393 		root = list_first_entry(&fs_info->dirty_cowonly_roots,
1394 					struct btrfs_root, dirty_list);
1395 		clear_bit(BTRFS_ROOT_DIRTY, &root->state);
1396 		list_move_tail(&root->dirty_list,
1397 			       &trans->transaction->switch_commits);
1398 
1399 		ret = update_cowonly_root(trans, root);
1400 		if (ret)
1401 			return ret;
1402 	}
1403 
1404 	/* Now flush any delayed refs generated by updating all of the roots */
1405 	ret = btrfs_run_delayed_refs(trans, U64_MAX);
1406 	if (ret)
1407 		return ret;
1408 
1409 	while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1410 		ret = btrfs_write_dirty_block_groups(trans);
1411 		if (ret)
1412 			return ret;
1413 
1414 		/*
1415 		 * We're writing the dirty block groups, which could generate
1416 		 * delayed refs, which could generate more dirty block groups,
1417 		 * so we want to keep this flushing in this loop to make sure
1418 		 * everything gets run.
1419 		 */
1420 		ret = btrfs_run_delayed_refs(trans, U64_MAX);
1421 		if (ret)
1422 			return ret;
1423 	}
1424 
1425 	if (!list_empty(&fs_info->dirty_cowonly_roots))
1426 		goto again;
1427 
1428 	/* Update dev-replace pointer once everything is committed */
1429 	fs_info->dev_replace.committed_cursor_left =
1430 		fs_info->dev_replace.cursor_left_last_write_of_item;
1431 
1432 	return 0;
1433 }
1434 
1435 /*
1436  * If we had a pending drop we need to see if there are any others left in our
1437  * dead roots list, and if not clear our bit and wake any waiters.
1438  */
btrfs_maybe_wake_unfinished_drop(struct btrfs_fs_info * fs_info)1439 void btrfs_maybe_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
1440 {
1441 	/*
1442 	 * We put the drop in progress roots at the front of the list, so if the
1443 	 * first entry doesn't have UNFINISHED_DROP set we can wake everybody
1444 	 * up.
1445 	 */
1446 	spin_lock(&fs_info->trans_lock);
1447 	if (!list_empty(&fs_info->dead_roots)) {
1448 		struct btrfs_root *root = list_first_entry(&fs_info->dead_roots,
1449 							   struct btrfs_root,
1450 							   root_list);
1451 		if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state)) {
1452 			spin_unlock(&fs_info->trans_lock);
1453 			return;
1454 		}
1455 	}
1456 	spin_unlock(&fs_info->trans_lock);
1457 
1458 	btrfs_wake_unfinished_drop(fs_info);
1459 }
1460 
1461 /*
1462  * dead roots are old snapshots that need to be deleted.  This allocates
1463  * a dirty root struct and adds it into the list of dead roots that need to
1464  * be deleted
1465  */
btrfs_add_dead_root(struct btrfs_root * root)1466 void btrfs_add_dead_root(struct btrfs_root *root)
1467 {
1468 	struct btrfs_fs_info *fs_info = root->fs_info;
1469 
1470 	spin_lock(&fs_info->trans_lock);
1471 	if (list_empty(&root->root_list)) {
1472 		btrfs_grab_root(root);
1473 
1474 		/* We want to process the partially complete drops first. */
1475 		if (test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state))
1476 			list_add(&root->root_list, &fs_info->dead_roots);
1477 		else
1478 			list_add_tail(&root->root_list, &fs_info->dead_roots);
1479 	}
1480 	spin_unlock(&fs_info->trans_lock);
1481 }
1482 
1483 /*
1484  * Update each subvolume root and its relocation root, if it exists, in the tree
1485  * of tree roots. Also free log roots if they exist.
1486  */
commit_fs_roots(struct btrfs_trans_handle * trans)1487 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1488 {
1489 	struct btrfs_fs_info *fs_info = trans->fs_info;
1490 	struct btrfs_root *gang[8];
1491 	int i;
1492 	int ret;
1493 
1494 	/*
1495 	 * At this point no one can be using this transaction to modify any tree
1496 	 * and no one can start another transaction to modify any tree either.
1497 	 */
1498 	ASSERT(trans->transaction->state == TRANS_STATE_COMMIT_DOING,
1499 	       "trans->transaction->state=%d", trans->transaction->state);
1500 
1501 	spin_lock(&fs_info->fs_roots_radix_lock);
1502 	while (1) {
1503 		ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1504 						 (void **)gang, 0,
1505 						 ARRAY_SIZE(gang),
1506 						 BTRFS_ROOT_TRANS_TAG);
1507 		if (ret == 0)
1508 			break;
1509 		for (i = 0; i < ret; i++) {
1510 			struct btrfs_root *root = gang[i];
1511 			int ret2;
1512 
1513 			/*
1514 			 * At this point we can neither have tasks logging inodes
1515 			 * from a root nor trying to commit a log tree.
1516 			 */
1517 			ASSERT(atomic_read(&root->log_writers) == 0,
1518 			       "atomic_read(&root->log_writers)=%d",
1519 			       atomic_read(&root->log_writers));
1520 			ASSERT(!root->log_commit[0]);
1521 			ASSERT(!root->log_commit[1]);
1522 
1523 			radix_tree_tag_clear(&fs_info->fs_roots_radix,
1524 					(unsigned long)btrfs_root_id(root),
1525 					BTRFS_ROOT_TRANS_TAG);
1526 			btrfs_qgroup_free_meta_all_pertrans(root);
1527 			spin_unlock(&fs_info->fs_roots_radix_lock);
1528 
1529 			btrfs_free_log(trans, root);
1530 			ret2 = btrfs_update_reloc_root(trans, root);
1531 			if (unlikely(ret2))
1532 				return ret2;
1533 
1534 			/* see comments in should_cow_block() */
1535 			clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1536 			smp_mb__after_atomic();
1537 
1538 			if (root->commit_root != root->node) {
1539 				list_add_tail(&root->dirty_list,
1540 					&trans->transaction->switch_commits);
1541 				btrfs_set_root_node(&root->root_item,
1542 						    root->node);
1543 			}
1544 
1545 			ret2 = btrfs_update_root(trans, fs_info->tree_root,
1546 						&root->root_key,
1547 						&root->root_item);
1548 			if (unlikely(ret2))
1549 				return ret2;
1550 			spin_lock(&fs_info->fs_roots_radix_lock);
1551 		}
1552 	}
1553 	spin_unlock(&fs_info->fs_roots_radix_lock);
1554 	return 0;
1555 }
1556 
1557 /*
1558  * Do all special snapshot related qgroup dirty hack.
1559  *
1560  * Will do all needed qgroup inherit and dirty hack like switch commit
1561  * roots inside one transaction and write all btree into disk, to make
1562  * qgroup works.
1563  */
qgroup_account_snapshot(struct btrfs_trans_handle * trans,struct btrfs_root * src,struct btrfs_root * parent,struct btrfs_qgroup_inherit * inherit,u64 dst_objectid)1564 static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1565 				   struct btrfs_root *src,
1566 				   struct btrfs_root *parent,
1567 				   struct btrfs_qgroup_inherit *inherit,
1568 				   u64 dst_objectid)
1569 {
1570 	struct btrfs_fs_info *fs_info = src->fs_info;
1571 	int ret;
1572 
1573 	/*
1574 	 * Save some performance in the case that qgroups are not enabled. If
1575 	 * this check races with the ioctl, rescan will kick in anyway.
1576 	 */
1577 	if (!btrfs_qgroup_full_accounting(fs_info))
1578 		return 0;
1579 
1580 	/*
1581 	 * Ensure dirty @src will be committed.  Or, after coming
1582 	 * commit_fs_roots() and switch_commit_roots(), any dirty but not
1583 	 * recorded root will never be updated again, causing an outdated root
1584 	 * item.
1585 	 */
1586 	ret = record_root_in_trans(trans, src, true);
1587 	if (ret)
1588 		return ret;
1589 
1590 	/*
1591 	 * btrfs_qgroup_inherit relies on a consistent view of the usage for the
1592 	 * src root, so we must run the delayed refs here.
1593 	 *
1594 	 * However this isn't particularly fool proof, because there's no
1595 	 * synchronization keeping us from changing the tree after this point
1596 	 * before we do the qgroup_inherit, or even from making changes while
1597 	 * we're doing the qgroup_inherit.  But that's a problem for the future,
1598 	 * for now flush the delayed refs to narrow the race window where the
1599 	 * qgroup counters could end up wrong.
1600 	 */
1601 	ret = btrfs_run_delayed_refs(trans, U64_MAX);
1602 	if (unlikely(ret)) {
1603 		btrfs_abort_transaction(trans, ret);
1604 		return ret;
1605 	}
1606 
1607 	ret = commit_fs_roots(trans);
1608 	if (ret)
1609 		return ret;
1610 	ret = btrfs_qgroup_account_extents(trans);
1611 	if (ret < 0)
1612 		return ret;
1613 
1614 	/* Now qgroup are all updated, we can inherit it to new qgroups */
1615 	ret = btrfs_qgroup_inherit(trans, btrfs_root_id(src), dst_objectid,
1616 				   btrfs_root_id(parent), inherit);
1617 	if (ret < 0)
1618 		return ret;
1619 
1620 	/*
1621 	 * Now we do a simplified commit transaction, which will:
1622 	 * 1) commit all subvolume and extent tree
1623 	 *    To ensure all subvolume and extent tree have a valid
1624 	 *    commit_root to accounting later insert_dir_item()
1625 	 * 2) write all btree blocks onto disk
1626 	 *    This is to make sure later btree modification will be cowed
1627 	 *    Or commit_root can be populated and cause wrong qgroup numbers
1628 	 * In this simplified commit, we don't really care about other trees
1629 	 * like chunk and root tree, as they won't affect qgroup.
1630 	 * And we don't write super to avoid half committed status.
1631 	 */
1632 	ret = commit_cowonly_roots(trans);
1633 	if (ret)
1634 		return ret;
1635 	switch_commit_roots(trans);
1636 	ret = btrfs_write_and_wait_transaction(trans);
1637 	if (unlikely(ret)) {
1638 		btrfs_err(fs_info,
1639 "error while writing out transaction during qgroup snapshot accounting: %pe", ERR_PTR(ret));
1640 		return ret;
1641 	}
1642 
1643 	/*
1644 	 * Force parent root to be updated, as we recorded it before so its
1645 	 * last_trans == cur_transid.
1646 	 * Or it won't be committed again onto disk after later
1647 	 * insert_dir_item()
1648 	 */
1649 	return record_root_in_trans(trans, parent, true);
1650 }
1651 
1652 /*
1653  * new snapshots need to be created at a very specific time in the
1654  * transaction commit.  This does the actual creation.
1655  *
1656  * Note:
1657  * If the error which may affect the commitment of the current transaction
1658  * happens, we should return the error number. If the error which just affect
1659  * the creation of the pending snapshots, just return 0.
1660  */
create_pending_snapshot(struct btrfs_trans_handle * trans,struct btrfs_pending_snapshot * pending)1661 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1662 				   struct btrfs_pending_snapshot *pending)
1663 {
1664 
1665 	struct btrfs_fs_info *fs_info = trans->fs_info;
1666 	struct btrfs_key key;
1667 	struct btrfs_root_item *new_root_item;
1668 	struct btrfs_root *tree_root = fs_info->tree_root;
1669 	struct btrfs_root *root = pending->root;
1670 	struct btrfs_root *parent_root;
1671 	struct btrfs_block_rsv *rsv;
1672 	struct btrfs_inode *parent_inode = pending->dir;
1673 	BTRFS_PATH_AUTO_FREE(path);
1674 	struct btrfs_dir_item *dir_item;
1675 	struct extent_buffer *tmp;
1676 	struct extent_buffer *root_eb;
1677 	struct timespec64 cur_time;
1678 	int ret = 0;
1679 	u64 to_reserve = 0;
1680 	u64 index = 0;
1681 	u64 objectid;
1682 	u64 root_flags;
1683 	unsigned int nofs_flags;
1684 	struct fscrypt_name fname;
1685 
1686 	ASSERT(pending->path);
1687 	path = pending->path;
1688 
1689 	ASSERT(pending->root_item);
1690 	new_root_item = pending->root_item;
1691 
1692 	/*
1693 	 * We're inside a transaction and must make sure that any potential
1694 	 * allocations with GFP_KERNEL in fscrypt won't recurse back to
1695 	 * filesystem.
1696 	 */
1697 	nofs_flags = memalloc_nofs_save();
1698 	pending->error = fscrypt_setup_filename(&parent_inode->vfs_inode,
1699 						&pending->dentry->d_name, 0,
1700 						&fname);
1701 	memalloc_nofs_restore(nofs_flags);
1702 	if (unlikely(pending->error))
1703 		goto free_pending;
1704 
1705 	pending->error = btrfs_get_free_objectid(tree_root, &objectid);
1706 	if (unlikely(pending->error))
1707 		goto free_fname;
1708 
1709 	/*
1710 	 * Make qgroup to skip current new snapshot's qgroupid, as it is
1711 	 * accounted by later btrfs_qgroup_inherit().
1712 	 */
1713 	btrfs_set_skip_qgroup(trans, objectid);
1714 
1715 	btrfs_reloc_pre_snapshot(pending, &to_reserve);
1716 
1717 	if (to_reserve > 0) {
1718 		pending->error = btrfs_block_rsv_add(fs_info,
1719 						     &pending->block_rsv,
1720 						     to_reserve,
1721 						     BTRFS_RESERVE_NO_FLUSH);
1722 		if (unlikely(pending->error))
1723 			goto clear_skip_qgroup;
1724 	}
1725 
1726 	rsv = trans->block_rsv;
1727 	trans->block_rsv = &pending->block_rsv;
1728 	trans->bytes_reserved = trans->block_rsv->reserved;
1729 	trace_btrfs_space_reservation(fs_info, "transaction",
1730 				      trans->transid,
1731 				      trans->bytes_reserved, 1);
1732 	parent_root = parent_inode->root;
1733 	ret = record_root_in_trans(trans, parent_root, false);
1734 	if (unlikely(ret))
1735 		goto fail;
1736 	cur_time = current_time(&parent_inode->vfs_inode);
1737 
1738 	/*
1739 	 * insert the directory item
1740 	 */
1741 	ret = btrfs_set_inode_index(parent_inode, &index);
1742 	if (unlikely(ret)) {
1743 		btrfs_abort_transaction(trans, ret);
1744 		goto fail;
1745 	}
1746 
1747 	/* check if there is a file/dir which has the same name. */
1748 	dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1749 					 btrfs_ino(parent_inode),
1750 					 &fname.disk_name, 0);
1751 	if (!IS_ERR_OR_NULL(dir_item)) {
1752 		pending->error = -EEXIST;
1753 		goto dir_item_existed;
1754 	} else if (IS_ERR(dir_item)) {
1755 		ret = PTR_ERR(dir_item);
1756 		btrfs_abort_transaction(trans, ret);
1757 		goto fail;
1758 	}
1759 	btrfs_release_path(path);
1760 
1761 	ret = btrfs_create_qgroup(trans, objectid);
1762 	if (ret && ret != -EEXIST) {
1763 		if (unlikely(ret != -ENOTCONN || btrfs_qgroup_enabled(fs_info))) {
1764 			btrfs_abort_transaction(trans, ret);
1765 			goto fail;
1766 		}
1767 	}
1768 
1769 	/*
1770 	 * pull in the delayed directory update
1771 	 * and the delayed inode item
1772 	 * otherwise we corrupt the FS during
1773 	 * snapshot
1774 	 */
1775 	ret = btrfs_run_delayed_items(trans);
1776 	if (unlikely(ret)) {
1777 		btrfs_abort_transaction(trans, ret);
1778 		goto fail;
1779 	}
1780 
1781 	ret = record_root_in_trans(trans, root, false);
1782 	if (unlikely(ret)) {
1783 		btrfs_abort_transaction(trans, ret);
1784 		goto fail;
1785 	}
1786 	btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1787 	memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1788 	btrfs_check_and_init_root_item(new_root_item);
1789 
1790 	root_flags = btrfs_root_flags(new_root_item);
1791 	if (pending->readonly)
1792 		root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1793 	else
1794 		root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1795 	btrfs_set_root_flags(new_root_item, root_flags);
1796 
1797 	btrfs_set_root_generation_v2(new_root_item,
1798 			trans->transid);
1799 	generate_random_guid(new_root_item->uuid);
1800 	memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1801 			BTRFS_UUID_SIZE);
1802 	if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1803 		memset(new_root_item->received_uuid, 0,
1804 		       sizeof(new_root_item->received_uuid));
1805 		memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1806 		memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1807 		btrfs_set_root_stransid(new_root_item, 0);
1808 		btrfs_set_root_rtransid(new_root_item, 0);
1809 	}
1810 	btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1811 	btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
1812 	btrfs_set_root_otransid(new_root_item, trans->transid);
1813 
1814 	root_eb = btrfs_lock_root_node(root);
1815 	ret = btrfs_copy_root(trans, root, root_eb, &tmp, objectid);
1816 	btrfs_tree_unlock(root_eb);
1817 	free_extent_buffer(root_eb);
1818 	if (unlikely(ret)) {
1819 		btrfs_abort_transaction(trans, ret);
1820 		goto fail;
1821 	}
1822 	/* see comments in should_cow_block() */
1823 	set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1824 	smp_mb__after_atomic();
1825 
1826 	btrfs_set_root_node(new_root_item, tmp);
1827 	/* record when the snapshot was created in key.offset */
1828 	key.objectid = objectid;
1829 	key.type = BTRFS_ROOT_ITEM_KEY;
1830 	key.offset = trans->transid;
1831 	ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1832 	btrfs_tree_unlock(tmp);
1833 	free_extent_buffer(tmp);
1834 	if (unlikely(ret)) {
1835 		btrfs_abort_transaction(trans, ret);
1836 		goto fail;
1837 	}
1838 
1839 	/*
1840 	 * insert root back/forward references
1841 	 */
1842 	ret = btrfs_add_root_ref(trans, objectid,
1843 				 btrfs_root_id(parent_root),
1844 				 btrfs_ino(parent_inode), index,
1845 				 &fname.disk_name);
1846 	if (unlikely(ret)) {
1847 		btrfs_abort_transaction(trans, ret);
1848 		goto fail;
1849 	}
1850 
1851 	key.offset = (u64)-1;
1852 	pending->snap = btrfs_get_new_fs_root(fs_info, objectid, &pending->anon_dev);
1853 	if (IS_ERR(pending->snap)) {
1854 		ret = PTR_ERR(pending->snap);
1855 		pending->snap = NULL;
1856 		btrfs_abort_transaction(trans, ret);
1857 		goto fail;
1858 	}
1859 
1860 	ret = btrfs_reloc_post_snapshot(trans, pending);
1861 	if (unlikely(ret)) {
1862 		btrfs_abort_transaction(trans, ret);
1863 		goto fail;
1864 	}
1865 
1866 	/*
1867 	 * Do special qgroup accounting for snapshot, as we do some qgroup
1868 	 * snapshot hack to do fast snapshot.
1869 	 * To co-operate with that hack, we do hack again.
1870 	 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1871 	 */
1872 	if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_FULL)
1873 		ret = qgroup_account_snapshot(trans, root, parent_root,
1874 					      pending->inherit, objectid);
1875 	else if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE)
1876 		ret = btrfs_qgroup_inherit(trans, btrfs_root_id(root), objectid,
1877 					   btrfs_root_id(parent_root), pending->inherit);
1878 	if (unlikely(ret < 0))
1879 		goto fail;
1880 
1881 	ret = btrfs_insert_dir_item(trans, &fname.disk_name,
1882 				    parent_inode, &key, BTRFS_FT_DIR,
1883 				    index);
1884 	if (unlikely(ret)) {
1885 		btrfs_abort_transaction(trans, ret);
1886 		goto fail;
1887 	}
1888 
1889 	btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
1890 						  fname.disk_name.len * 2);
1891 	inode_set_mtime_to_ts(&parent_inode->vfs_inode,
1892 			      inode_set_ctime_current(&parent_inode->vfs_inode));
1893 	ret = btrfs_update_inode_fallback(trans, parent_inode);
1894 	if (unlikely(ret)) {
1895 		btrfs_abort_transaction(trans, ret);
1896 		goto fail;
1897 	}
1898 	ret = btrfs_uuid_tree_add(trans, new_root_item->uuid,
1899 				  BTRFS_UUID_KEY_SUBVOL,
1900 				  objectid);
1901 	if (unlikely(ret)) {
1902 		btrfs_abort_transaction(trans, ret);
1903 		goto fail;
1904 	}
1905 	if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1906 		ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1907 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1908 					  objectid);
1909 		/*
1910 		 * We are creating of lot of snapshots of the same root that was
1911 		 * received (has a received UUID) and reached a leaf's limit for
1912 		 * an item. We can safely ignore this and avoid a transaction
1913 		 * abort. A deletion of this snapshot will still work since we
1914 		 * ignore if an item with a BTRFS_UUID_KEY_RECEIVED_SUBVOL key
1915 		 * is missing (see btrfs_delete_subvolume()). Send/receive will
1916 		 * work too since it peeks the first root id from the existing
1917 		 * item (it could peek any), and in case it's missing it
1918 		 * falls back to search by BTRFS_UUID_KEY_SUBVOL keys.
1919 		 * Creation of a snapshot does not require CAP_SYS_ADMIN, so
1920 		 * we don't want users triggering transaction aborts, either
1921 		 * intentionally or not.
1922 		 */
1923 		if (ret == -EOVERFLOW)
1924 			ret = 0;
1925 		if (unlikely(ret)) {
1926 			btrfs_abort_transaction(trans, ret);
1927 			goto fail;
1928 		}
1929 	}
1930 
1931 fail:
1932 	pending->error = ret;
1933 dir_item_existed:
1934 	trans->block_rsv = rsv;
1935 	trans->bytes_reserved = 0;
1936 clear_skip_qgroup:
1937 	btrfs_clear_skip_qgroup(trans);
1938 free_fname:
1939 	fscrypt_free_filename(&fname);
1940 free_pending:
1941 	kfree(new_root_item);
1942 	pending->root_item = NULL;
1943 	pending->path = NULL;
1944 
1945 	return ret;
1946 }
1947 
1948 /*
1949  * create all the snapshots we've scheduled for creation
1950  */
create_pending_snapshots(struct btrfs_trans_handle * trans)1951 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1952 {
1953 	struct btrfs_pending_snapshot *pending, *next;
1954 	struct list_head *head = &trans->transaction->pending_snapshots;
1955 	int ret = 0;
1956 
1957 	list_for_each_entry_safe(pending, next, head, list) {
1958 		list_del(&pending->list);
1959 		ret = create_pending_snapshot(trans, pending);
1960 		if (unlikely(ret))
1961 			break;
1962 	}
1963 	return ret;
1964 }
1965 
update_super_roots(struct btrfs_fs_info * fs_info)1966 static void update_super_roots(struct btrfs_fs_info *fs_info)
1967 {
1968 	struct btrfs_root_item *root_item;
1969 	struct btrfs_super_block *super;
1970 
1971 	super = fs_info->super_copy;
1972 
1973 	root_item = &fs_info->chunk_root->root_item;
1974 	super->chunk_root = root_item->bytenr;
1975 	super->chunk_root_generation = root_item->generation;
1976 	super->chunk_root_level = root_item->level;
1977 
1978 	root_item = &fs_info->tree_root->root_item;
1979 	super->root = root_item->bytenr;
1980 	super->generation = root_item->generation;
1981 	super->root_level = root_item->level;
1982 	if (btrfs_test_opt(fs_info, SPACE_CACHE))
1983 		super->cache_generation = root_item->generation;
1984 	else if (test_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags))
1985 		super->cache_generation = 0;
1986 	if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1987 		super->uuid_tree_generation = root_item->generation;
1988 
1989 	if (btrfs_fs_incompat(fs_info, REMAP_TREE)) {
1990 		root_item = &fs_info->remap_root->root_item;
1991 		super->remap_root = root_item->bytenr;
1992 		super->remap_root_generation = root_item->generation;
1993 		super->remap_root_level = root_item->level;
1994 	}
1995 }
1996 
btrfs_transaction_blocked(struct btrfs_fs_info * info)1997 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1998 {
1999 	struct btrfs_transaction *trans;
2000 	int ret = 0;
2001 
2002 	spin_lock(&info->trans_lock);
2003 	trans = info->running_transaction;
2004 	if (trans)
2005 		ret = is_transaction_blocked(trans);
2006 	spin_unlock(&info->trans_lock);
2007 	return ret;
2008 }
2009 
btrfs_commit_transaction_async(struct btrfs_trans_handle * trans)2010 void btrfs_commit_transaction_async(struct btrfs_trans_handle *trans)
2011 {
2012 	struct btrfs_fs_info *fs_info = trans->fs_info;
2013 	struct btrfs_transaction *cur_trans;
2014 
2015 	/* Kick the transaction kthread. */
2016 	set_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
2017 	wake_up_process(fs_info->transaction_kthread);
2018 
2019 	/* take transaction reference */
2020 	cur_trans = trans->transaction;
2021 	refcount_inc(&cur_trans->use_count);
2022 
2023 	btrfs_end_transaction(trans);
2024 
2025 	/*
2026 	 * Wait for the current transaction commit to start and block
2027 	 * subsequent transaction joins
2028 	 */
2029 	btrfs_might_wait_for_state(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2030 	wait_event(fs_info->transaction_blocked_wait,
2031 		   cur_trans->state >= TRANS_STATE_COMMIT_START ||
2032 		   TRANS_ABORTED(cur_trans));
2033 	btrfs_put_transaction(cur_trans);
2034 }
2035 
2036 /*
2037  * If there is a running transaction commit it or if it's already committing,
2038  * wait for its commit to complete. Does not start and commit a new transaction
2039  * if there isn't any running.
2040  */
btrfs_commit_current_transaction(struct btrfs_root * root)2041 int btrfs_commit_current_transaction(struct btrfs_root *root)
2042 {
2043 	struct btrfs_trans_handle *trans;
2044 
2045 	trans = btrfs_attach_transaction_barrier(root);
2046 	if (IS_ERR(trans)) {
2047 		int ret = PTR_ERR(trans);
2048 
2049 		return (ret == -ENOENT) ? 0 : ret;
2050 	}
2051 
2052 	return btrfs_commit_transaction(trans);
2053 }
2054 
cleanup_transaction(struct btrfs_trans_handle * trans,int err)2055 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
2056 {
2057 	struct btrfs_fs_info *fs_info = trans->fs_info;
2058 	struct btrfs_transaction *cur_trans = trans->transaction;
2059 
2060 	WARN_ON(refcount_read(&trans->use_count) > 1);
2061 
2062 	btrfs_abort_transaction(trans, err);
2063 
2064 	spin_lock(&fs_info->trans_lock);
2065 
2066 	/*
2067 	 * If the transaction is removed from the list, it means this
2068 	 * transaction has been committed successfully, so it is impossible
2069 	 * to call the cleanup function.
2070 	 */
2071 	BUG_ON(list_empty(&cur_trans->list));
2072 
2073 	if (cur_trans == fs_info->running_transaction) {
2074 		cur_trans->state = TRANS_STATE_COMMIT_DOING;
2075 		spin_unlock(&fs_info->trans_lock);
2076 
2077 		/*
2078 		 * The thread has already released the lockdep map as reader
2079 		 * already in btrfs_commit_transaction().
2080 		 */
2081 		btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2082 		wait_event(cur_trans->writer_wait,
2083 			   atomic_read(&cur_trans->num_writers) == 1);
2084 
2085 		spin_lock(&fs_info->trans_lock);
2086 	}
2087 
2088 	/*
2089 	 * Now that we know no one else is still using the transaction we can
2090 	 * remove the transaction from the list of transactions. This avoids
2091 	 * the transaction kthread from cleaning up the transaction while some
2092 	 * other task is still using it, which could result in a use-after-free
2093 	 * on things like log trees, as it forces the transaction kthread to
2094 	 * wait for this transaction to be cleaned up by us.
2095 	 */
2096 	list_del_init(&cur_trans->list);
2097 
2098 	spin_unlock(&fs_info->trans_lock);
2099 
2100 	btrfs_cleanup_one_transaction(trans->transaction);
2101 
2102 	spin_lock(&fs_info->trans_lock);
2103 	if (cur_trans == fs_info->running_transaction)
2104 		fs_info->running_transaction = NULL;
2105 	spin_unlock(&fs_info->trans_lock);
2106 
2107 	if (trans->type & __TRANS_FREEZABLE)
2108 		sb_end_intwrite(fs_info->sb);
2109 	btrfs_put_transaction(cur_trans);
2110 	btrfs_put_transaction(cur_trans);
2111 
2112 	trace_btrfs_transaction_commit(trans);
2113 
2114 	if (current->journal_info == trans)
2115 		current->journal_info = NULL;
2116 
2117 	/*
2118 	 * If relocation is running, we can't cancel scrub because that will
2119 	 * result in a deadlock. Before relocating a block group, relocation
2120 	 * pauses scrub, then starts and commits a transaction before unpausing
2121 	 * scrub. If the transaction commit is being done by the relocation
2122 	 * task or triggered by another task and the relocation task is waiting
2123 	 * for the commit, and we end up here due to an error in the commit
2124 	 * path, then calling btrfs_scrub_cancel() will deadlock, as we are
2125 	 * asking for scrub to stop while having it asked to be paused higher
2126 	 * above in relocation code.
2127 	 */
2128 	if (!test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags))
2129 		btrfs_scrub_cancel(fs_info);
2130 
2131 	btrfs_uninhibit_all_eb_writeback(trans);
2132 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
2133 }
2134 
2135 /*
2136  * Release reserved delayed ref space of all pending block groups of the
2137  * transaction and remove them from the list
2138  */
btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle * trans)2139 static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
2140 {
2141        struct btrfs_fs_info *fs_info = trans->fs_info;
2142        struct btrfs_block_group *block_group, *tmp;
2143 
2144        list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
2145                btrfs_dec_delayed_refs_rsv_bg_inserts(fs_info);
2146 		/*
2147 		* Not strictly necessary to lock, as no other task will be using a
2148 		* block_group on the new_bgs list during a transaction abort.
2149 		*/
2150 	       spin_lock(&fs_info->unused_bgs_lock);
2151                list_del_init(&block_group->bg_list);
2152 	       btrfs_put_block_group(block_group);
2153 	       spin_unlock(&fs_info->unused_bgs_lock);
2154        }
2155 }
2156 
btrfs_start_delalloc_flush(struct btrfs_fs_info * fs_info)2157 static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
2158 {
2159 	/*
2160 	 * We use try_to_writeback_inodes_sb() here because if we used
2161 	 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
2162 	 * Currently are holding the fs freeze lock, if we do an async flush
2163 	 * we'll do btrfs_join_transaction() and deadlock because we need to
2164 	 * wait for the fs freeze lock.  Using the direct flushing we benefit
2165 	 * from already being in a transaction and our join_transaction doesn't
2166 	 * have to re-take the fs freeze lock.
2167 	 *
2168 	 * Note that try_to_writeback_inodes_sb() will only trigger writeback
2169 	 * if it can read lock sb->s_umount. It will always be able to lock it,
2170 	 * except when the filesystem is being unmounted or being frozen, but in
2171 	 * those cases sync_filesystem() is called, which results in calling
2172 	 * writeback_inodes_sb() while holding a write lock on sb->s_umount.
2173 	 * Note that we don't call writeback_inodes_sb() directly, because it
2174 	 * will emit a warning if sb->s_umount is not locked.
2175 	 */
2176 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2177 		try_to_writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
2178 	return 0;
2179 }
2180 
btrfs_wait_delalloc_flush(struct btrfs_fs_info * fs_info)2181 static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
2182 {
2183 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
2184 		btrfs_wait_ordered_roots(fs_info, U64_MAX, NULL);
2185 }
2186 
2187 /*
2188  * Add a pending snapshot associated with the given transaction handle to the
2189  * respective handle. This must be called after the transaction commit started
2190  * and while holding fs_info->trans_lock.
2191  * This serves to guarantee a caller of btrfs_commit_transaction() that it can
2192  * safely free the pending snapshot pointer in case btrfs_commit_transaction()
2193  * returns an error.
2194  */
add_pending_snapshot(struct btrfs_trans_handle * trans)2195 static void add_pending_snapshot(struct btrfs_trans_handle *trans)
2196 {
2197 	struct btrfs_transaction *cur_trans = trans->transaction;
2198 
2199 	if (!trans->pending_snapshot)
2200 		return;
2201 
2202 	lockdep_assert_held(&trans->fs_info->trans_lock);
2203 	ASSERT(cur_trans->state >= TRANS_STATE_COMMIT_PREP,
2204 	       "cur_trans->state=%d", cur_trans->state);
2205 
2206 	list_add(&trans->pending_snapshot->list, &cur_trans->pending_snapshots);
2207 }
2208 
update_commit_stats(struct btrfs_fs_info * fs_info)2209 static void update_commit_stats(struct btrfs_fs_info *fs_info)
2210 {
2211 	ktime_t now = ktime_get_ns();
2212 	ktime_t interval = now - fs_info->commit_stats.critical_section_start_time;
2213 
2214 	ASSERT(fs_info->commit_stats.critical_section_start_time);
2215 
2216 	fs_info->commit_stats.commit_count++;
2217 	fs_info->commit_stats.last_commit_dur = interval;
2218 	fs_info->commit_stats.max_commit_dur =
2219 			max_t(u64, fs_info->commit_stats.max_commit_dur, interval);
2220 	fs_info->commit_stats.total_commit_dur += interval;
2221 	fs_info->commit_stats.critical_section_start_time = 0;
2222 }
2223 
btrfs_commit_transaction(struct btrfs_trans_handle * trans)2224 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
2225 {
2226 	struct btrfs_fs_info *fs_info = trans->fs_info;
2227 	struct btrfs_transaction *cur_trans = trans->transaction;
2228 	struct btrfs_transaction *prev_trans = NULL;
2229 	int ret;
2230 
2231 	ASSERT(refcount_read(&trans->use_count) == 1,
2232 	       "refcount_read(&trans->use_count)=%d", refcount_read(&trans->use_count));
2233 	btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2234 
2235 	clear_bit(BTRFS_FS_NEED_TRANS_COMMIT, &fs_info->flags);
2236 
2237 	/* Stop the commit early if ->aborted is set */
2238 	if (TRANS_ABORTED(cur_trans)) {
2239 		ret = cur_trans->aborted;
2240 		goto lockdep_trans_commit_start_release;
2241 	}
2242 
2243 	btrfs_trans_release_metadata(trans);
2244 	trans->block_rsv = NULL;
2245 
2246 	/*
2247 	 * We only want one transaction commit doing the flushing so we do not
2248 	 * waste a bunch of time on lock contention on the extent root node.
2249 	 */
2250 	if (!test_and_set_bit(BTRFS_DELAYED_REFS_FLUSHING,
2251 			      &cur_trans->delayed_refs.flags)) {
2252 		/*
2253 		 * Make a pass through all the delayed refs we have so far.
2254 		 * Any running threads may add more while we are here.
2255 		 */
2256 		ret = btrfs_run_delayed_refs(trans, 0);
2257 		if (ret)
2258 			goto lockdep_trans_commit_start_release;
2259 	}
2260 
2261 	btrfs_create_pending_block_groups(trans);
2262 
2263 	if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
2264 		bool run_it = false;
2265 
2266 		/* this mutex is also taken before trying to set
2267 		 * block groups readonly.  We need to make sure
2268 		 * that nobody has set a block group readonly
2269 		 * after a extents from that block group have been
2270 		 * allocated for cache files.  btrfs_set_block_group_ro
2271 		 * will wait for the transaction to commit if it
2272 		 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
2273 		 *
2274 		 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
2275 		 * only one process starts all the block group IO.  It wouldn't
2276 		 * hurt to have more than one go through, but there's no
2277 		 * real advantage to it either.
2278 		 */
2279 		mutex_lock(&fs_info->ro_block_group_mutex);
2280 		if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
2281 				      &cur_trans->flags))
2282 			run_it = true;
2283 		mutex_unlock(&fs_info->ro_block_group_mutex);
2284 
2285 		if (run_it) {
2286 			ret = btrfs_start_dirty_block_groups(trans);
2287 			if (unlikely(ret))
2288 				goto lockdep_trans_commit_start_release;
2289 		}
2290 	}
2291 
2292 	spin_lock(&fs_info->trans_lock);
2293 	if (cur_trans->state >= TRANS_STATE_COMMIT_PREP) {
2294 		enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2295 
2296 		add_pending_snapshot(trans);
2297 
2298 		spin_unlock(&fs_info->trans_lock);
2299 		refcount_inc(&cur_trans->use_count);
2300 
2301 		if (trans->in_fsync)
2302 			want_state = TRANS_STATE_SUPER_COMMITTED;
2303 
2304 		btrfs_trans_state_lockdep_release(fs_info,
2305 						  BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2306 		ret = btrfs_end_transaction(trans);
2307 		wait_for_commit(cur_trans, want_state);
2308 
2309 		if (TRANS_ABORTED(cur_trans))
2310 			ret = cur_trans->aborted;
2311 
2312 		btrfs_put_transaction(cur_trans);
2313 
2314 		return ret;
2315 	}
2316 
2317 	cur_trans->state = TRANS_STATE_COMMIT_PREP;
2318 	trace_btrfs_transaction_commit(trans);
2319 	wake_up(&fs_info->transaction_blocked_wait);
2320 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2321 
2322 	if (!list_is_first(&cur_trans->list, &fs_info->trans_list)) {
2323 		enum btrfs_trans_state want_state = TRANS_STATE_COMPLETED;
2324 
2325 		if (trans->in_fsync)
2326 			want_state = TRANS_STATE_SUPER_COMMITTED;
2327 
2328 		prev_trans = list_prev_entry(cur_trans, list);
2329 		if (prev_trans->state < want_state) {
2330 			refcount_inc(&prev_trans->use_count);
2331 			spin_unlock(&fs_info->trans_lock);
2332 
2333 			wait_for_commit(prev_trans, want_state);
2334 
2335 			ret = READ_ONCE(prev_trans->aborted);
2336 
2337 			btrfs_put_transaction(prev_trans);
2338 			if (unlikely(ret))
2339 				goto lockdep_release;
2340 			spin_lock(&fs_info->trans_lock);
2341 		}
2342 	} else {
2343 		/*
2344 		 * The previous transaction was aborted and was already removed
2345 		 * from the list of transactions at fs_info->trans_list. So we
2346 		 * abort to prevent writing a new superblock that reflects a
2347 		 * corrupt state (pointing to trees with unwritten nodes/leafs).
2348 		 */
2349 		if (unlikely(BTRFS_FS_ERROR(fs_info))) {
2350 			spin_unlock(&fs_info->trans_lock);
2351 			ret = -EROFS;
2352 			goto lockdep_release;
2353 		}
2354 	}
2355 
2356 	cur_trans->state = TRANS_STATE_COMMIT_START;
2357 	trace_btrfs_transaction_commit(trans);
2358 	wake_up(&fs_info->transaction_blocked_wait);
2359 	spin_unlock(&fs_info->trans_lock);
2360 
2361 	/*
2362 	 * Get the time spent on the work done by the commit thread and not
2363 	 * the time spent waiting on a previous commit
2364 	 */
2365 	fs_info->commit_stats.critical_section_start_time = ktime_get_ns();
2366 	extwriter_counter_dec(cur_trans, trans->type);
2367 
2368 	ret = btrfs_start_delalloc_flush(fs_info);
2369 	if (unlikely(ret))
2370 		goto lockdep_release;
2371 
2372 	ret = btrfs_run_delayed_items(trans);
2373 	if (unlikely(ret))
2374 		goto lockdep_release;
2375 
2376 	/*
2377 	 * The thread has started/joined the transaction thus it holds the
2378 	 * lockdep map as a reader. It has to release it before acquiring the
2379 	 * lockdep map as a writer.
2380 	 */
2381 	btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2382 	btrfs_might_wait_for_event(fs_info, btrfs_trans_num_extwriters);
2383 	wait_event(cur_trans->writer_wait,
2384 		   extwriter_counter_read(cur_trans) == 0);
2385 
2386 	/* some pending stuffs might be added after the previous flush. */
2387 	ret = btrfs_run_delayed_items(trans);
2388 	if (unlikely(ret)) {
2389 		btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2390 		goto cleanup_transaction;
2391 	}
2392 
2393 	btrfs_wait_delalloc_flush(fs_info);
2394 
2395 	/*
2396 	 * Wait for all ordered extents started by a fast fsync that joined this
2397 	 * transaction. Otherwise if this transaction commits before the ordered
2398 	 * extents complete we lose logged data after a power failure.
2399 	 */
2400 	btrfs_might_wait_for_event(fs_info, btrfs_trans_pending_ordered);
2401 	wait_event(cur_trans->pending_wait,
2402 		   atomic_read(&cur_trans->pending_ordered) == 0);
2403 
2404 	btrfs_scrub_pause(fs_info);
2405 	/*
2406 	 * Ok now we need to make sure to block out any other joins while we
2407 	 * commit the transaction.  We could have started a join before setting
2408 	 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2409 	 */
2410 	spin_lock(&fs_info->trans_lock);
2411 	add_pending_snapshot(trans);
2412 	cur_trans->state = TRANS_STATE_COMMIT_DOING;
2413 	trace_btrfs_transaction_commit(trans);
2414 	spin_unlock(&fs_info->trans_lock);
2415 
2416 	/*
2417 	 * The thread has started/joined the transaction thus it holds the
2418 	 * lockdep map as a reader. It has to release it before acquiring the
2419 	 * lockdep map as a writer.
2420 	 */
2421 	btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2422 	btrfs_might_wait_for_event(fs_info, btrfs_trans_num_writers);
2423 	wait_event(cur_trans->writer_wait,
2424 		   atomic_read(&cur_trans->num_writers) == 1);
2425 
2426 	/*
2427 	 * Make lockdep happy by acquiring the state locks after
2428 	 * btrfs_trans_num_writers is released. If we acquired the state locks
2429 	 * before releasing the btrfs_trans_num_writers lock then lockdep would
2430 	 * complain because we did not follow the reverse order unlocking rule.
2431 	 */
2432 	btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2433 	btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2434 	btrfs_trans_state_lockdep_acquire(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2435 
2436 	/*
2437 	 * We've started the commit, clear the flag in case we were triggered to
2438 	 * do an async commit but somebody else started before the transaction
2439 	 * kthread could do the work.
2440 	 */
2441 	clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
2442 
2443 	if (TRANS_ABORTED(cur_trans)) {
2444 		ret = cur_trans->aborted;
2445 		btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2446 		goto scrub_continue;
2447 	}
2448 	/*
2449 	 * the reloc mutex makes sure that we stop
2450 	 * the balancing code from coming in and moving
2451 	 * extents around in the middle of the commit
2452 	 */
2453 	mutex_lock(&fs_info->reloc_mutex);
2454 
2455 	/*
2456 	 * We needn't worry about the delayed items because we will
2457 	 * deal with them in create_pending_snapshot(), which is the
2458 	 * core function of the snapshot creation.
2459 	 */
2460 	ret = create_pending_snapshots(trans);
2461 	if (unlikely(ret))
2462 		goto unlock_reloc;
2463 
2464 	/*
2465 	 * We insert the dir indexes of the snapshots and update the inode
2466 	 * of the snapshots' parents after the snapshot creation, so there
2467 	 * are some delayed items which are not dealt with. Now deal with
2468 	 * them.
2469 	 *
2470 	 * We needn't worry that this operation will corrupt the snapshots,
2471 	 * because all the tree which are snapshotted will be forced to COW
2472 	 * the nodes and leaves.
2473 	 */
2474 	ret = btrfs_run_delayed_items(trans);
2475 	if (unlikely(ret))
2476 		goto unlock_reloc;
2477 
2478 	ret = btrfs_run_delayed_refs(trans, U64_MAX);
2479 	if (unlikely(ret))
2480 		goto unlock_reloc;
2481 
2482 	/*
2483 	 * make sure none of the code above managed to slip in a
2484 	 * delayed item
2485 	 */
2486 	btrfs_assert_delayed_root_empty(fs_info);
2487 
2488 	WARN_ON(cur_trans != trans->transaction);
2489 
2490 	ret = commit_fs_roots(trans);
2491 	if (unlikely(ret))
2492 		goto unlock_reloc;
2493 
2494 	/* commit_fs_roots gets rid of all the tree log roots, it is now
2495 	 * safe to free the root of tree log roots
2496 	 */
2497 	btrfs_free_log_root_tree(trans, fs_info);
2498 
2499 	/*
2500 	 * Since fs roots are all committed, we can get a quite accurate
2501 	 * new_roots. So let's do quota accounting.
2502 	 */
2503 	ret = btrfs_qgroup_account_extents(trans);
2504 	if (unlikely(ret < 0))
2505 		goto unlock_reloc;
2506 
2507 	ret = commit_cowonly_roots(trans);
2508 	if (unlikely(ret))
2509 		goto unlock_reloc;
2510 
2511 	/*
2512 	 * The tasks which save the space cache and inode cache may also
2513 	 * update ->aborted, check it.
2514 	 */
2515 	if (TRANS_ABORTED(cur_trans)) {
2516 		ret = cur_trans->aborted;
2517 		goto unlock_reloc;
2518 	}
2519 
2520 	cur_trans = fs_info->running_transaction;
2521 
2522 	btrfs_set_root_node(&fs_info->tree_root->root_item,
2523 			    fs_info->tree_root->node);
2524 	list_add_tail(&fs_info->tree_root->dirty_list,
2525 		      &cur_trans->switch_commits);
2526 
2527 	btrfs_set_root_node(&fs_info->chunk_root->root_item,
2528 			    fs_info->chunk_root->node);
2529 	list_add_tail(&fs_info->chunk_root->dirty_list,
2530 		      &cur_trans->switch_commits);
2531 
2532 	switch_commit_roots(trans);
2533 
2534 	ASSERT(list_empty(&cur_trans->dirty_bgs));
2535 	ASSERT(list_empty(&cur_trans->io_bgs));
2536 	update_super_roots(fs_info);
2537 
2538 	btrfs_set_super_log_root(fs_info->super_copy, 0);
2539 	btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2540 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
2541 	       sizeof(*fs_info->super_copy));
2542 
2543 	btrfs_commit_device_sizes(cur_trans);
2544 
2545 	clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2546 	clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2547 
2548 	btrfs_trans_release_chunk_metadata(trans);
2549 
2550 	/*
2551 	 * Before changing the transaction state to TRANS_STATE_UNBLOCKED and
2552 	 * setting fs_info->running_transaction to NULL, lock tree_log_mutex to
2553 	 * make sure that before we commit our superblock, no other task can
2554 	 * start a new transaction and commit a log tree before we commit our
2555 	 * superblock. Anyone trying to commit a log tree locks this mutex before
2556 	 * writing its superblock.
2557 	 */
2558 	mutex_lock(&fs_info->tree_log_mutex);
2559 
2560 	spin_lock(&fs_info->trans_lock);
2561 	cur_trans->state = TRANS_STATE_UNBLOCKED;
2562 	trace_btrfs_transaction_commit(trans);
2563 	fs_info->running_transaction = NULL;
2564 	spin_unlock(&fs_info->trans_lock);
2565 	mutex_unlock(&fs_info->reloc_mutex);
2566 
2567 	wake_up(&fs_info->transaction_wait);
2568 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2569 
2570 	/* If we have features changed, wake up the cleaner to update sysfs. */
2571 	if (test_bit(BTRFS_FS_FEATURE_CHANGED, &fs_info->flags) &&
2572 	    fs_info->cleaner_kthread)
2573 		wake_up_process(fs_info->cleaner_kthread);
2574 
2575 	/*
2576 	 * Uninhibit writeback on all extent buffers inhibited during this
2577 	 * transaction before writing them to disk. Inhibiting prevented
2578 	 * writeback while the transaction was building, but now we need
2579 	 * them written.
2580 	 */
2581 	btrfs_uninhibit_all_eb_writeback(trans);
2582 
2583 	ret = btrfs_write_and_wait_transaction(trans);
2584 	if (unlikely(ret)) {
2585 		btrfs_err(fs_info, "error while writing out transaction: %pe", ERR_PTR(ret));
2586 		mutex_unlock(&fs_info->tree_log_mutex);
2587 		goto scrub_continue;
2588 	}
2589 
2590 	ret = write_all_supers(trans);
2591 	/*
2592 	 * the super is written, we can safely allow the tree-loggers
2593 	 * to go about their business
2594 	 */
2595 	mutex_unlock(&fs_info->tree_log_mutex);
2596 	if (unlikely(ret))
2597 		goto scrub_continue;
2598 
2599 	update_commit_stats(fs_info);
2600 	/*
2601 	 * We needn't acquire the lock here because there is no other task
2602 	 * which can change it.
2603 	 */
2604 	cur_trans->state = TRANS_STATE_SUPER_COMMITTED;
2605 	trace_btrfs_transaction_commit(trans);
2606 	wake_up(&cur_trans->commit_wait);
2607 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2608 
2609 	ret = btrfs_finish_extent_commit(trans);
2610 	if (unlikely(ret))
2611 		goto scrub_continue;
2612 
2613 	if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2614 		btrfs_clear_space_info_full(fs_info);
2615 
2616 	btrfs_set_last_trans_committed(fs_info, cur_trans->transid);
2617 	/*
2618 	 * We needn't acquire the lock here because there is no other task
2619 	 * which can change it.
2620 	 */
2621 	cur_trans->state = TRANS_STATE_COMPLETED;
2622 	trace_btrfs_transaction_commit(trans);
2623 	wake_up(&cur_trans->commit_wait);
2624 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2625 
2626 	spin_lock(&fs_info->trans_lock);
2627 	list_del_init(&cur_trans->list);
2628 	spin_unlock(&fs_info->trans_lock);
2629 
2630 	btrfs_put_transaction(cur_trans);
2631 	btrfs_put_transaction(cur_trans);
2632 
2633 	if (trans->type & __TRANS_FREEZABLE)
2634 		sb_end_intwrite(fs_info->sb);
2635 
2636 	btrfs_scrub_continue(fs_info);
2637 
2638 	if (current->journal_info == trans)
2639 		current->journal_info = NULL;
2640 
2641 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
2642 
2643 	return ret;
2644 
2645 unlock_reloc:
2646 	mutex_unlock(&fs_info->reloc_mutex);
2647 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2648 scrub_continue:
2649 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2650 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMPLETED);
2651 	btrfs_scrub_continue(fs_info);
2652 cleanup_transaction:
2653 	btrfs_trans_release_metadata(trans);
2654 	btrfs_cleanup_pending_block_groups(trans);
2655 	btrfs_trans_release_chunk_metadata(trans);
2656 	trans->block_rsv = NULL;
2657 	btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2658 	cleanup_transaction(trans, ret);
2659 
2660 	return ret;
2661 
2662 lockdep_release:
2663 	btrfs_lockdep_release(fs_info, btrfs_trans_num_extwriters);
2664 	btrfs_lockdep_release(fs_info, btrfs_trans_num_writers);
2665 	goto cleanup_transaction;
2666 
2667 lockdep_trans_commit_start_release:
2668 	btrfs_trans_state_lockdep_release(fs_info, BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2669 	btrfs_end_transaction(trans);
2670 	return ret;
2671 }
2672 
2673 /*
2674  * return < 0 if error
2675  * 0 if there are no more dead_roots at the time of call
2676  * 1 there are more to be processed, call me again
2677  *
2678  * The return value indicates there are certainly more snapshots to delete, but
2679  * if there comes a new one during processing, it may return 0. We don't mind,
2680  * because btrfs_commit_super will poke cleaner thread and it will process it a
2681  * few seconds later.
2682  */
btrfs_clean_one_deleted_snapshot(struct btrfs_fs_info * fs_info)2683 int btrfs_clean_one_deleted_snapshot(struct btrfs_fs_info *fs_info)
2684 {
2685 	struct btrfs_root *root;
2686 	int ret;
2687 
2688 	spin_lock(&fs_info->trans_lock);
2689 	if (list_empty(&fs_info->dead_roots)) {
2690 		spin_unlock(&fs_info->trans_lock);
2691 		return 0;
2692 	}
2693 	root = list_first_entry(&fs_info->dead_roots,
2694 			struct btrfs_root, root_list);
2695 	list_del_init(&root->root_list);
2696 	spin_unlock(&fs_info->trans_lock);
2697 
2698 	btrfs_debug(fs_info, "cleaner removing %llu", btrfs_root_id(root));
2699 
2700 	btrfs_kill_all_delayed_nodes(root);
2701 
2702 	if (btrfs_header_backref_rev(root->node) <
2703 			BTRFS_MIXED_BACKREF_REV)
2704 		ret = btrfs_drop_snapshot(root, false, false);
2705 	else
2706 		ret = btrfs_drop_snapshot(root, true, false);
2707 
2708 	btrfs_put_root(root);
2709 	return (ret < 0) ? 0 : 1;
2710 }
2711 
2712 /*
2713  * We only mark the transaction aborted and then set the file system read-only.
2714  * This will prevent new transactions from starting or trying to join this
2715  * one.
2716  *
2717  * This means that error recovery at the call site is limited to freeing
2718  * any local memory allocations and passing the error code up without
2719  * further cleanup. The transaction should complete as it normally would
2720  * in the call path but will return -EIO.
2721  *
2722  * We'll complete the cleanup in btrfs_end_transaction and
2723  * btrfs_commit_transaction.
2724  *
2725  * Note: the parameter @error encodes whether the transactin abort was first hit
2726  *       (setting the FS_ERROR state bit in btrfs_abort_transaction())
2727  *       - positive number - first hit
2728  *       - negative number - abort after it was already done
2729  */
__btrfs_abort_transaction(struct btrfs_trans_handle * trans,const char * function,unsigned int line,int error)2730 void __cold __btrfs_abort_transaction(struct btrfs_trans_handle *trans,
2731 				      const char *function,
2732 				      unsigned int line, int error)
2733 {
2734 	struct btrfs_fs_info *fs_info = trans->fs_info;
2735 	bool first_hit = false;
2736 
2737 	if (error > 0) {
2738 		error = -error;
2739 		first_hit = true;
2740 	}
2741 
2742 	WRITE_ONCE(trans->aborted, error);
2743 	WRITE_ONCE(trans->transaction->aborted, error);
2744 	trace_btrfs_transaction_abort(trans);
2745 	if (first_hit) {
2746 		btrfs_err(fs_info, "Transaction %llu aborted (%pe)",
2747 			  trans->transid, ERR_PTR(error));
2748 		if (error == -ENOSPC)
2749 			btrfs_dump_space_info_for_trans_abort(fs_info);
2750 	}
2751 	/* Wake up anybody who may be waiting on this transaction */
2752 	wake_up(&fs_info->transaction_wait);
2753 	wake_up(&fs_info->transaction_blocked_wait);
2754 	__btrfs_handle_fs_error(fs_info, function, line, error, NULL);
2755 }
2756 
btrfs_transaction_init(void)2757 int __init btrfs_transaction_init(void)
2758 {
2759 	btrfs_trans_handle_cachep = KMEM_CACHE(btrfs_trans_handle, SLAB_TEMPORARY);
2760 	if (!btrfs_trans_handle_cachep)
2761 		return -ENOMEM;
2762 	return 0;
2763 }
2764 
btrfs_transaction_exit(void)2765 void __cold btrfs_transaction_exit(void)
2766 {
2767 	kmem_cache_destroy(btrfs_trans_handle_cachep);
2768 }
2769