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