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