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