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