xref: /openbmc/linux/fs/btrfs/transaction.c (revision 41e7acd3)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
36cbd5570SChris Mason  * Copyright (C) 2007 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
679154b1bSChris Mason #include <linux/fs.h>
75a0e3ad6STejun Heo #include <linux/slab.h>
834088780SChris Mason #include <linux/sched.h>
9d3c2fdcfSChris Mason #include <linux/writeback.h>
105f39d397SChris Mason #include <linux/pagemap.h>
115f2cc086SChris Mason #include <linux/blkdev.h>
128ea05e3aSAlexander Block #include <linux/uuid.h>
1379154b1bSChris Mason #include "ctree.h"
1479154b1bSChris Mason #include "disk-io.h"
1579154b1bSChris Mason #include "transaction.h"
16925baeddSChris Mason #include "locking.h"
17e02119d5SChris Mason #include "tree-log.h"
18581bb050SLi Zefan #include "inode-map.h"
19733f4fbbSStefan Behrens #include "volumes.h"
208dabb742SStefan Behrens #include "dev-replace.h"
21fcebe456SJosef Bacik #include "qgroup.h"
2279154b1bSChris Mason 
230f7d52f4SChris Mason #define BTRFS_ROOT_TRANS_TAG 0
240f7d52f4SChris Mason 
25e8c9f186SDavid Sterba static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
264a9d8bdeSMiao Xie 	[TRANS_STATE_RUNNING]		= 0U,
27bcf3a3e7SNikolay Borisov 	[TRANS_STATE_BLOCKED]		=  __TRANS_START,
28bcf3a3e7SNikolay Borisov 	[TRANS_STATE_COMMIT_START]	= (__TRANS_START | __TRANS_ATTACH),
29bcf3a3e7SNikolay Borisov 	[TRANS_STATE_COMMIT_DOING]	= (__TRANS_START |
304a9d8bdeSMiao Xie 					   __TRANS_ATTACH |
314a9d8bdeSMiao Xie 					   __TRANS_JOIN),
32bcf3a3e7SNikolay Borisov 	[TRANS_STATE_UNBLOCKED]		= (__TRANS_START |
334a9d8bdeSMiao Xie 					   __TRANS_ATTACH |
344a9d8bdeSMiao Xie 					   __TRANS_JOIN |
354a9d8bdeSMiao Xie 					   __TRANS_JOIN_NOLOCK),
36bcf3a3e7SNikolay Borisov 	[TRANS_STATE_COMPLETED]		= (__TRANS_START |
374a9d8bdeSMiao Xie 					   __TRANS_ATTACH |
384a9d8bdeSMiao Xie 					   __TRANS_JOIN |
394a9d8bdeSMiao Xie 					   __TRANS_JOIN_NOLOCK),
404a9d8bdeSMiao Xie };
414a9d8bdeSMiao Xie 
42724e2315SJosef Bacik void btrfs_put_transaction(struct btrfs_transaction *transaction)
4379154b1bSChris Mason {
449b64f57dSElena Reshetova 	WARN_ON(refcount_read(&transaction->use_count) == 0);
459b64f57dSElena Reshetova 	if (refcount_dec_and_test(&transaction->use_count)) {
46a4abeea4SJosef Bacik 		BUG_ON(!list_empty(&transaction->list));
475c9d028bSLiu Bo 		WARN_ON(!RB_EMPTY_ROOT(
485c9d028bSLiu Bo 				&transaction->delayed_refs.href_root.rb_root));
491262133bSJosef Bacik 		if (transaction->delayed_refs.pending_csums)
50ab8d0fc4SJeff Mahoney 			btrfs_err(transaction->fs_info,
51ab8d0fc4SJeff Mahoney 				  "pending csums is %llu",
521262133bSJosef Bacik 				  transaction->delayed_refs.pending_csums);
536df9a95eSJosef Bacik 		while (!list_empty(&transaction->pending_chunks)) {
546df9a95eSJosef Bacik 			struct extent_map *em;
556df9a95eSJosef Bacik 
566df9a95eSJosef Bacik 			em = list_first_entry(&transaction->pending_chunks,
576df9a95eSJosef Bacik 					      struct extent_map, list);
586df9a95eSJosef Bacik 			list_del_init(&em->list);
596df9a95eSJosef Bacik 			free_extent_map(em);
606df9a95eSJosef Bacik 		}
617785a663SFilipe Manana 		/*
627785a663SFilipe Manana 		 * If any block groups are found in ->deleted_bgs then it's
637785a663SFilipe Manana 		 * because the transaction was aborted and a commit did not
647785a663SFilipe Manana 		 * happen (things failed before writing the new superblock
657785a663SFilipe Manana 		 * and calling btrfs_finish_extent_commit()), so we can not
667785a663SFilipe Manana 		 * discard the physical locations of the block groups.
677785a663SFilipe Manana 		 */
687785a663SFilipe Manana 		while (!list_empty(&transaction->deleted_bgs)) {
697785a663SFilipe Manana 			struct btrfs_block_group_cache *cache;
707785a663SFilipe Manana 
717785a663SFilipe Manana 			cache = list_first_entry(&transaction->deleted_bgs,
727785a663SFilipe Manana 						 struct btrfs_block_group_cache,
737785a663SFilipe Manana 						 bg_list);
747785a663SFilipe Manana 			list_del_init(&cache->bg_list);
757785a663SFilipe Manana 			btrfs_put_block_group_trimming(cache);
767785a663SFilipe Manana 			btrfs_put_block_group(cache);
777785a663SFilipe Manana 		}
78bbbf7243SNikolay Borisov 		WARN_ON(!list_empty(&transaction->dev_update_list));
794b5faeacSDavid Sterba 		kfree(transaction);
8079154b1bSChris Mason 	}
8178fae27eSChris Mason }
8279154b1bSChris Mason 
8316916a88SNikolay Borisov static noinline void switch_commit_roots(struct btrfs_transaction *trans)
84817d52f8SJosef Bacik {
8516916a88SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
869e351cc8SJosef Bacik 	struct btrfs_root *root, *tmp;
879e351cc8SJosef Bacik 
889e351cc8SJosef Bacik 	down_write(&fs_info->commit_root_sem);
899e351cc8SJosef Bacik 	list_for_each_entry_safe(root, tmp, &trans->switch_commits,
909e351cc8SJosef Bacik 				 dirty_list) {
919e351cc8SJosef Bacik 		list_del_init(&root->dirty_list);
92817d52f8SJosef Bacik 		free_extent_buffer(root->commit_root);
93817d52f8SJosef Bacik 		root->commit_root = btrfs_root_node(root);
944fd786e6SMisono Tomohiro 		if (is_fstree(root->root_key.objectid))
959e351cc8SJosef Bacik 			btrfs_unpin_free_ino(root);
9641e7acd3SNikolay Borisov 		extent_io_tree_release(&root->dirty_log_pages);
97370a11b8SQu Wenruo 		btrfs_qgroup_clean_swapped_blocks(root);
989e351cc8SJosef Bacik 	}
992b9dbef2SJosef Bacik 
1002b9dbef2SJosef Bacik 	/* We can free old roots now. */
1012b9dbef2SJosef Bacik 	spin_lock(&trans->dropped_roots_lock);
1022b9dbef2SJosef Bacik 	while (!list_empty(&trans->dropped_roots)) {
1032b9dbef2SJosef Bacik 		root = list_first_entry(&trans->dropped_roots,
1042b9dbef2SJosef Bacik 					struct btrfs_root, root_list);
1052b9dbef2SJosef Bacik 		list_del_init(&root->root_list);
1062b9dbef2SJosef Bacik 		spin_unlock(&trans->dropped_roots_lock);
1072b9dbef2SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, root);
1082b9dbef2SJosef Bacik 		spin_lock(&trans->dropped_roots_lock);
1092b9dbef2SJosef Bacik 	}
1102b9dbef2SJosef Bacik 	spin_unlock(&trans->dropped_roots_lock);
1119e351cc8SJosef Bacik 	up_write(&fs_info->commit_root_sem);
112817d52f8SJosef Bacik }
113817d52f8SJosef Bacik 
1140860adfdSMiao Xie static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
1150860adfdSMiao Xie 					 unsigned int type)
1160860adfdSMiao Xie {
1170860adfdSMiao Xie 	if (type & TRANS_EXTWRITERS)
1180860adfdSMiao Xie 		atomic_inc(&trans->num_extwriters);
1190860adfdSMiao Xie }
1200860adfdSMiao Xie 
1210860adfdSMiao Xie static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
1220860adfdSMiao Xie 					 unsigned int type)
1230860adfdSMiao Xie {
1240860adfdSMiao Xie 	if (type & TRANS_EXTWRITERS)
1250860adfdSMiao Xie 		atomic_dec(&trans->num_extwriters);
1260860adfdSMiao Xie }
1270860adfdSMiao Xie 
1280860adfdSMiao Xie static inline void extwriter_counter_init(struct btrfs_transaction *trans,
1290860adfdSMiao Xie 					  unsigned int type)
1300860adfdSMiao Xie {
1310860adfdSMiao Xie 	atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
1320860adfdSMiao Xie }
1330860adfdSMiao Xie 
1340860adfdSMiao Xie static inline int extwriter_counter_read(struct btrfs_transaction *trans)
1350860adfdSMiao Xie {
1360860adfdSMiao Xie 	return atomic_read(&trans->num_extwriters);
137178260b2SMiao Xie }
138178260b2SMiao Xie 
139d352ac68SChris Mason /*
140d352ac68SChris Mason  * either allocate a new transaction or hop into the existing one
141d352ac68SChris Mason  */
1422ff7e61eSJeff Mahoney static noinline int join_transaction(struct btrfs_fs_info *fs_info,
1432ff7e61eSJeff Mahoney 				     unsigned int type)
14479154b1bSChris Mason {
14579154b1bSChris Mason 	struct btrfs_transaction *cur_trans;
146a4abeea4SJosef Bacik 
14719ae4e81SJan Schmidt 	spin_lock(&fs_info->trans_lock);
148d43317dcSChris Mason loop:
14949b25e05SJeff Mahoney 	/* The file system has been taken offline. No new transactions. */
15087533c47SMiao Xie 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
15119ae4e81SJan Schmidt 		spin_unlock(&fs_info->trans_lock);
15249b25e05SJeff Mahoney 		return -EROFS;
15349b25e05SJeff Mahoney 	}
15449b25e05SJeff Mahoney 
15519ae4e81SJan Schmidt 	cur_trans = fs_info->running_transaction;
156a4abeea4SJosef Bacik 	if (cur_trans) {
157871383beSDavid Sterba 		if (cur_trans->aborted) {
15819ae4e81SJan Schmidt 			spin_unlock(&fs_info->trans_lock);
15949b25e05SJeff Mahoney 			return cur_trans->aborted;
160871383beSDavid Sterba 		}
1614a9d8bdeSMiao Xie 		if (btrfs_blocked_trans_types[cur_trans->state] & type) {
162178260b2SMiao Xie 			spin_unlock(&fs_info->trans_lock);
163178260b2SMiao Xie 			return -EBUSY;
164178260b2SMiao Xie 		}
1659b64f57dSElena Reshetova 		refcount_inc(&cur_trans->use_count);
166a4abeea4SJosef Bacik 		atomic_inc(&cur_trans->num_writers);
1670860adfdSMiao Xie 		extwriter_counter_inc(cur_trans, type);
16819ae4e81SJan Schmidt 		spin_unlock(&fs_info->trans_lock);
169a4abeea4SJosef Bacik 		return 0;
170a4abeea4SJosef Bacik 	}
17119ae4e81SJan Schmidt 	spin_unlock(&fs_info->trans_lock);
172a4abeea4SJosef Bacik 
173354aa0fbSMiao Xie 	/*
174354aa0fbSMiao Xie 	 * If we are ATTACH, we just want to catch the current transaction,
175354aa0fbSMiao Xie 	 * and commit it. If there is no transaction, just return ENOENT.
176354aa0fbSMiao Xie 	 */
177354aa0fbSMiao Xie 	if (type == TRANS_ATTACH)
178354aa0fbSMiao Xie 		return -ENOENT;
179354aa0fbSMiao Xie 
1804a9d8bdeSMiao Xie 	/*
1814a9d8bdeSMiao Xie 	 * JOIN_NOLOCK only happens during the transaction commit, so
1824a9d8bdeSMiao Xie 	 * it is impossible that ->running_transaction is NULL
1834a9d8bdeSMiao Xie 	 */
1844a9d8bdeSMiao Xie 	BUG_ON(type == TRANS_JOIN_NOLOCK);
1854a9d8bdeSMiao Xie 
1864b5faeacSDavid Sterba 	cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
187db5b493aSTsutomu Itoh 	if (!cur_trans)
188db5b493aSTsutomu Itoh 		return -ENOMEM;
189d43317dcSChris Mason 
19019ae4e81SJan Schmidt 	spin_lock(&fs_info->trans_lock);
19119ae4e81SJan Schmidt 	if (fs_info->running_transaction) {
192d43317dcSChris Mason 		/*
193d43317dcSChris Mason 		 * someone started a transaction after we unlocked.  Make sure
1944a9d8bdeSMiao Xie 		 * to redo the checks above
195d43317dcSChris Mason 		 */
1964b5faeacSDavid Sterba 		kfree(cur_trans);
197d43317dcSChris Mason 		goto loop;
19887533c47SMiao Xie 	} else if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
199e4b50e14SDan Carpenter 		spin_unlock(&fs_info->trans_lock);
2004b5faeacSDavid Sterba 		kfree(cur_trans);
2017b8b92afSJosef Bacik 		return -EROFS;
202a4abeea4SJosef Bacik 	}
203d43317dcSChris Mason 
204ab8d0fc4SJeff Mahoney 	cur_trans->fs_info = fs_info;
20513c5a93eSJosef Bacik 	atomic_set(&cur_trans->num_writers, 1);
2060860adfdSMiao Xie 	extwriter_counter_init(cur_trans, type);
20779154b1bSChris Mason 	init_waitqueue_head(&cur_trans->writer_wait);
20879154b1bSChris Mason 	init_waitqueue_head(&cur_trans->commit_wait);
2094a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_RUNNING;
210a4abeea4SJosef Bacik 	/*
211a4abeea4SJosef Bacik 	 * One for this trans handle, one so it will live on until we
212a4abeea4SJosef Bacik 	 * commit the transaction.
213a4abeea4SJosef Bacik 	 */
2149b64f57dSElena Reshetova 	refcount_set(&cur_trans->use_count, 2);
2153204d33cSJosef Bacik 	cur_trans->flags = 0;
216afd48513SArnd Bergmann 	cur_trans->start_time = ktime_get_seconds();
21756bec294SChris Mason 
218a099d0fdSAlexandru Moise 	memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
219a099d0fdSAlexandru Moise 
2205c9d028bSLiu Bo 	cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
2213368d001SQu Wenruo 	cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
222d7df2c79SJosef Bacik 	atomic_set(&cur_trans->delayed_refs.num_entries, 0);
22320b297d6SJan Schmidt 
22420b297d6SJan Schmidt 	/*
22520b297d6SJan Schmidt 	 * although the tree mod log is per file system and not per transaction,
22620b297d6SJan Schmidt 	 * the log must never go across transaction boundaries.
22720b297d6SJan Schmidt 	 */
22820b297d6SJan Schmidt 	smp_mb();
22931b1a2bdSJulia Lawall 	if (!list_empty(&fs_info->tree_mod_seq_list))
2305d163e0eSJeff Mahoney 		WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
23131b1a2bdSJulia Lawall 	if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
2325d163e0eSJeff Mahoney 		WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
233fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
23420b297d6SJan Schmidt 
23556bec294SChris Mason 	spin_lock_init(&cur_trans->delayed_refs.lock);
23656bec294SChris Mason 
2373063d29fSChris Mason 	INIT_LIST_HEAD(&cur_trans->pending_snapshots);
2386df9a95eSJosef Bacik 	INIT_LIST_HEAD(&cur_trans->pending_chunks);
239bbbf7243SNikolay Borisov 	INIT_LIST_HEAD(&cur_trans->dev_update_list);
2409e351cc8SJosef Bacik 	INIT_LIST_HEAD(&cur_trans->switch_commits);
241ce93ec54SJosef Bacik 	INIT_LIST_HEAD(&cur_trans->dirty_bgs);
2421bbc621eSChris Mason 	INIT_LIST_HEAD(&cur_trans->io_bgs);
2432b9dbef2SJosef Bacik 	INIT_LIST_HEAD(&cur_trans->dropped_roots);
2441bbc621eSChris Mason 	mutex_init(&cur_trans->cache_write_mutex);
245cb723e49SJosef Bacik 	cur_trans->num_dirty_bgs = 0;
246ce93ec54SJosef Bacik 	spin_lock_init(&cur_trans->dirty_bgs_lock);
247e33e17eeSJeff Mahoney 	INIT_LIST_HEAD(&cur_trans->deleted_bgs);
2482b9dbef2SJosef Bacik 	spin_lock_init(&cur_trans->dropped_roots_lock);
24919ae4e81SJan Schmidt 	list_add_tail(&cur_trans->list, &fs_info->trans_list);
250c258d6e3SQu Wenruo 	extent_io_tree_init(fs_info, &cur_trans->dirty_pages,
25143eb5f29SQu Wenruo 			IO_TREE_TRANS_DIRTY_PAGES, fs_info->btree_inode);
25219ae4e81SJan Schmidt 	fs_info->generation++;
25319ae4e81SJan Schmidt 	cur_trans->transid = fs_info->generation;
25419ae4e81SJan Schmidt 	fs_info->running_transaction = cur_trans;
25549b25e05SJeff Mahoney 	cur_trans->aborted = 0;
25619ae4e81SJan Schmidt 	spin_unlock(&fs_info->trans_lock);
25715ee9bc7SJosef Bacik 
25879154b1bSChris Mason 	return 0;
25979154b1bSChris Mason }
26079154b1bSChris Mason 
261d352ac68SChris Mason /*
262d397712bSChris Mason  * this does all the record keeping required to make sure that a reference
263d397712bSChris Mason  * counted root is properly recorded in a given transaction.  This is required
264d397712bSChris Mason  * to make sure the old root from before we joined the transaction is deleted
265d397712bSChris Mason  * when the transaction commits
266d352ac68SChris Mason  */
2677585717fSChris Mason static int record_root_in_trans(struct btrfs_trans_handle *trans,
2686426c7adSQu Wenruo 			       struct btrfs_root *root,
2696426c7adSQu Wenruo 			       int force)
2706702ed49SChris Mason {
2710b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2720b246afaSJeff Mahoney 
2736426c7adSQu Wenruo 	if ((test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
2746426c7adSQu Wenruo 	    root->last_trans < trans->transid) || force) {
2750b246afaSJeff Mahoney 		WARN_ON(root == fs_info->extent_root);
2764d31778aSQu Wenruo 		WARN_ON(!force && root->commit_root != root->node);
2775d4f98a2SYan Zheng 
2787585717fSChris Mason 		/*
27927cdeb70SMiao Xie 		 * see below for IN_TRANS_SETUP usage rules
2807585717fSChris Mason 		 * we have the reloc mutex held now, so there
2817585717fSChris Mason 		 * is only one writer in this function
2827585717fSChris Mason 		 */
28327cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
2847585717fSChris Mason 
28527cdeb70SMiao Xie 		/* make sure readers find IN_TRANS_SETUP before
2867585717fSChris Mason 		 * they find our root->last_trans update
2877585717fSChris Mason 		 */
2887585717fSChris Mason 		smp_wmb();
2897585717fSChris Mason 
2900b246afaSJeff Mahoney 		spin_lock(&fs_info->fs_roots_radix_lock);
2916426c7adSQu Wenruo 		if (root->last_trans == trans->transid && !force) {
2920b246afaSJeff Mahoney 			spin_unlock(&fs_info->fs_roots_radix_lock);
293a4abeea4SJosef Bacik 			return 0;
294a4abeea4SJosef Bacik 		}
2950b246afaSJeff Mahoney 		radix_tree_tag_set(&fs_info->fs_roots_radix,
2966702ed49SChris Mason 				   (unsigned long)root->root_key.objectid,
2976702ed49SChris Mason 				   BTRFS_ROOT_TRANS_TAG);
2980b246afaSJeff Mahoney 		spin_unlock(&fs_info->fs_roots_radix_lock);
2997585717fSChris Mason 		root->last_trans = trans->transid;
3007585717fSChris Mason 
3017585717fSChris Mason 		/* this is pretty tricky.  We don't want to
3027585717fSChris Mason 		 * take the relocation lock in btrfs_record_root_in_trans
3037585717fSChris Mason 		 * unless we're really doing the first setup for this root in
3047585717fSChris Mason 		 * this transaction.
3057585717fSChris Mason 		 *
3067585717fSChris Mason 		 * Normally we'd use root->last_trans as a flag to decide
3077585717fSChris Mason 		 * if we want to take the expensive mutex.
3087585717fSChris Mason 		 *
3097585717fSChris Mason 		 * But, we have to set root->last_trans before we
3107585717fSChris Mason 		 * init the relocation root, otherwise, we trip over warnings
3117585717fSChris Mason 		 * in ctree.c.  The solution used here is to flag ourselves
31227cdeb70SMiao Xie 		 * with root IN_TRANS_SETUP.  When this is 1, we're still
3137585717fSChris Mason 		 * fixing up the reloc trees and everyone must wait.
3147585717fSChris Mason 		 *
3157585717fSChris Mason 		 * When this is zero, they can trust root->last_trans and fly
3167585717fSChris Mason 		 * through btrfs_record_root_in_trans without having to take the
3177585717fSChris Mason 		 * lock.  smp_wmb() makes sure that all the writes above are
3187585717fSChris Mason 		 * done before we pop in the zero below
3197585717fSChris Mason 		 */
3205d4f98a2SYan Zheng 		btrfs_init_reloc_root(trans, root);
321c7548af6SChris Mason 		smp_mb__before_atomic();
32227cdeb70SMiao Xie 		clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
3236702ed49SChris Mason 	}
3245d4f98a2SYan Zheng 	return 0;
3256702ed49SChris Mason }
3265d4f98a2SYan Zheng 
3277585717fSChris Mason 
3282b9dbef2SJosef Bacik void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
3292b9dbef2SJosef Bacik 			    struct btrfs_root *root)
3302b9dbef2SJosef Bacik {
3310b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3322b9dbef2SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
3332b9dbef2SJosef Bacik 
3342b9dbef2SJosef Bacik 	/* Add ourselves to the transaction dropped list */
3352b9dbef2SJosef Bacik 	spin_lock(&cur_trans->dropped_roots_lock);
3362b9dbef2SJosef Bacik 	list_add_tail(&root->root_list, &cur_trans->dropped_roots);
3372b9dbef2SJosef Bacik 	spin_unlock(&cur_trans->dropped_roots_lock);
3382b9dbef2SJosef Bacik 
3392b9dbef2SJosef Bacik 	/* Make sure we don't try to update the root at commit time */
3400b246afaSJeff Mahoney 	spin_lock(&fs_info->fs_roots_radix_lock);
3410b246afaSJeff Mahoney 	radix_tree_tag_clear(&fs_info->fs_roots_radix,
3422b9dbef2SJosef Bacik 			     (unsigned long)root->root_key.objectid,
3432b9dbef2SJosef Bacik 			     BTRFS_ROOT_TRANS_TAG);
3440b246afaSJeff Mahoney 	spin_unlock(&fs_info->fs_roots_radix_lock);
3452b9dbef2SJosef Bacik }
3462b9dbef2SJosef Bacik 
3477585717fSChris Mason int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
3487585717fSChris Mason 			       struct btrfs_root *root)
3497585717fSChris Mason {
3500b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3510b246afaSJeff Mahoney 
35227cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
3537585717fSChris Mason 		return 0;
3547585717fSChris Mason 
3557585717fSChris Mason 	/*
35627cdeb70SMiao Xie 	 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
3577585717fSChris Mason 	 * and barriers
3587585717fSChris Mason 	 */
3597585717fSChris Mason 	smp_rmb();
3607585717fSChris Mason 	if (root->last_trans == trans->transid &&
36127cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
3627585717fSChris Mason 		return 0;
3637585717fSChris Mason 
3640b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
3656426c7adSQu Wenruo 	record_root_in_trans(trans, root, 0);
3660b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
3677585717fSChris Mason 
3687585717fSChris Mason 	return 0;
3697585717fSChris Mason }
3707585717fSChris Mason 
3714a9d8bdeSMiao Xie static inline int is_transaction_blocked(struct btrfs_transaction *trans)
3724a9d8bdeSMiao Xie {
3734a9d8bdeSMiao Xie 	return (trans->state >= TRANS_STATE_BLOCKED &&
374501407aaSJosef Bacik 		trans->state < TRANS_STATE_UNBLOCKED &&
375501407aaSJosef Bacik 		!trans->aborted);
3764a9d8bdeSMiao Xie }
3774a9d8bdeSMiao Xie 
378d352ac68SChris Mason /* wait for commit against the current transaction to become unblocked
379d352ac68SChris Mason  * when this is done, it is safe to start a new transaction, but the current
380d352ac68SChris Mason  * transaction might not be fully on disk.
381d352ac68SChris Mason  */
3822ff7e61eSJeff Mahoney static void wait_current_trans(struct btrfs_fs_info *fs_info)
38379154b1bSChris Mason {
384f9295749SChris Mason 	struct btrfs_transaction *cur_trans;
38579154b1bSChris Mason 
3860b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
3870b246afaSJeff Mahoney 	cur_trans = fs_info->running_transaction;
3884a9d8bdeSMiao Xie 	if (cur_trans && is_transaction_blocked(cur_trans)) {
3899b64f57dSElena Reshetova 		refcount_inc(&cur_trans->use_count);
3900b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
39172d63ed6SLi Zefan 
3920b246afaSJeff Mahoney 		wait_event(fs_info->transaction_wait,
393501407aaSJosef Bacik 			   cur_trans->state >= TRANS_STATE_UNBLOCKED ||
394501407aaSJosef Bacik 			   cur_trans->aborted);
395724e2315SJosef Bacik 		btrfs_put_transaction(cur_trans);
396a4abeea4SJosef Bacik 	} else {
3970b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
398f9295749SChris Mason 	}
39937d1aeeeSChris Mason }
40037d1aeeeSChris Mason 
4012ff7e61eSJeff Mahoney static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
40237d1aeeeSChris Mason {
4030b246afaSJeff Mahoney 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
404a4abeea4SJosef Bacik 		return 0;
405a4abeea4SJosef Bacik 
40692e2f7e3SNikolay Borisov 	if (type == TRANS_START)
407a4abeea4SJosef Bacik 		return 1;
408a4abeea4SJosef Bacik 
409a22285a6SYan, Zheng 	return 0;
410a22285a6SYan, Zheng }
411a22285a6SYan, Zheng 
41220dd2cbfSMiao Xie static inline bool need_reserve_reloc_root(struct btrfs_root *root)
41320dd2cbfSMiao Xie {
4140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4150b246afaSJeff Mahoney 
4160b246afaSJeff Mahoney 	if (!fs_info->reloc_ctl ||
41727cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
41820dd2cbfSMiao Xie 	    root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
41920dd2cbfSMiao Xie 	    root->reloc_root)
42020dd2cbfSMiao Xie 		return false;
42120dd2cbfSMiao Xie 
42220dd2cbfSMiao Xie 	return true;
42320dd2cbfSMiao Xie }
42420dd2cbfSMiao Xie 
42508e007d2SMiao Xie static struct btrfs_trans_handle *
4265aed1dd8SAlexandru Moise start_transaction(struct btrfs_root *root, unsigned int num_items,
427003d7c59SJeff Mahoney 		  unsigned int type, enum btrfs_reserve_flush_enum flush,
428003d7c59SJeff Mahoney 		  bool enforce_qgroups)
429a22285a6SYan, Zheng {
4300b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
431ba2c4d4eSJosef Bacik 	struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
432a22285a6SYan, Zheng 	struct btrfs_trans_handle *h;
433a22285a6SYan, Zheng 	struct btrfs_transaction *cur_trans;
434b5009945SJosef Bacik 	u64 num_bytes = 0;
435c5567237SArne Jansen 	u64 qgroup_reserved = 0;
43620dd2cbfSMiao Xie 	bool reloc_reserved = false;
43720dd2cbfSMiao Xie 	int ret;
438acce952bSliubo 
43946c4e71eSFilipe Manana 	/* Send isn't supposed to start transactions. */
4402755a0deSDavid Sterba 	ASSERT(current->journal_info != BTRFS_SEND_TRANS_STUB);
44146c4e71eSFilipe Manana 
4420b246afaSJeff Mahoney 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
443acce952bSliubo 		return ERR_PTR(-EROFS);
4442a1eb461SJosef Bacik 
44546c4e71eSFilipe Manana 	if (current->journal_info) {
4460860adfdSMiao Xie 		WARN_ON(type & TRANS_EXTWRITERS);
4472a1eb461SJosef Bacik 		h = current->journal_info;
448b50fff81SDavid Sterba 		refcount_inc(&h->use_count);
449b50fff81SDavid Sterba 		WARN_ON(refcount_read(&h->use_count) > 2);
4502a1eb461SJosef Bacik 		h->orig_rsv = h->block_rsv;
4512a1eb461SJosef Bacik 		h->block_rsv = NULL;
4522a1eb461SJosef Bacik 		goto got_it;
4532a1eb461SJosef Bacik 	}
454b5009945SJosef Bacik 
455b5009945SJosef Bacik 	/*
456b5009945SJosef Bacik 	 * Do the reservation before we join the transaction so we can do all
457b5009945SJosef Bacik 	 * the appropriate flushing if need be.
458b5009945SJosef Bacik 	 */
459003d7c59SJeff Mahoney 	if (num_items && root != fs_info->chunk_root) {
460ba2c4d4eSJosef Bacik 		struct btrfs_block_rsv *rsv = &fs_info->trans_block_rsv;
461ba2c4d4eSJosef Bacik 		u64 delayed_refs_bytes = 0;
462ba2c4d4eSJosef Bacik 
4630b246afaSJeff Mahoney 		qgroup_reserved = num_items * fs_info->nodesize;
464733e03a0SQu Wenruo 		ret = btrfs_qgroup_reserve_meta_pertrans(root, qgroup_reserved,
465003d7c59SJeff Mahoney 				enforce_qgroups);
466c5567237SArne Jansen 		if (ret)
467c5567237SArne Jansen 			return ERR_PTR(ret);
468c5567237SArne Jansen 
469ba2c4d4eSJosef Bacik 		/*
470ba2c4d4eSJosef Bacik 		 * We want to reserve all the bytes we may need all at once, so
471ba2c4d4eSJosef Bacik 		 * we only do 1 enospc flushing cycle per transaction start.  We
472ba2c4d4eSJosef Bacik 		 * accomplish this by simply assuming we'll do 2 x num_items
473ba2c4d4eSJosef Bacik 		 * worth of delayed refs updates in this trans handle, and
474ba2c4d4eSJosef Bacik 		 * refill that amount for whatever is missing in the reserve.
475ba2c4d4eSJosef Bacik 		 */
4760b246afaSJeff Mahoney 		num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
477ba2c4d4eSJosef Bacik 		if (delayed_refs_rsv->full == 0) {
478ba2c4d4eSJosef Bacik 			delayed_refs_bytes = num_bytes;
479ba2c4d4eSJosef Bacik 			num_bytes <<= 1;
480ba2c4d4eSJosef Bacik 		}
481ba2c4d4eSJosef Bacik 
48220dd2cbfSMiao Xie 		/*
48320dd2cbfSMiao Xie 		 * Do the reservation for the relocation root creation
48420dd2cbfSMiao Xie 		 */
485ee39b432SDavid Sterba 		if (need_reserve_reloc_root(root)) {
4860b246afaSJeff Mahoney 			num_bytes += fs_info->nodesize;
48720dd2cbfSMiao Xie 			reloc_reserved = true;
48820dd2cbfSMiao Xie 		}
48920dd2cbfSMiao Xie 
490ba2c4d4eSJosef Bacik 		ret = btrfs_block_rsv_add(root, rsv, num_bytes, flush);
491ba2c4d4eSJosef Bacik 		if (ret)
492ba2c4d4eSJosef Bacik 			goto reserve_fail;
493ba2c4d4eSJosef Bacik 		if (delayed_refs_bytes) {
494ba2c4d4eSJosef Bacik 			btrfs_migrate_to_delayed_refs_rsv(fs_info, rsv,
495ba2c4d4eSJosef Bacik 							  delayed_refs_bytes);
496ba2c4d4eSJosef Bacik 			num_bytes -= delayed_refs_bytes;
497ba2c4d4eSJosef Bacik 		}
498ba2c4d4eSJosef Bacik 	} else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
499ba2c4d4eSJosef Bacik 		   !delayed_refs_rsv->full) {
500ba2c4d4eSJosef Bacik 		/*
501ba2c4d4eSJosef Bacik 		 * Some people call with btrfs_start_transaction(root, 0)
502ba2c4d4eSJosef Bacik 		 * because they can be throttled, but have some other mechanism
503ba2c4d4eSJosef Bacik 		 * for reserving space.  We still want these guys to refill the
504ba2c4d4eSJosef Bacik 		 * delayed block_rsv so just add 1 items worth of reservation
505ba2c4d4eSJosef Bacik 		 * here.
506ba2c4d4eSJosef Bacik 		 */
507ba2c4d4eSJosef Bacik 		ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
508b5009945SJosef Bacik 		if (ret)
509843fcf35SMiao Xie 			goto reserve_fail;
510b5009945SJosef Bacik 	}
511a22285a6SYan, Zheng again:
512f2f767e7SAlexandru Moise 	h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
513843fcf35SMiao Xie 	if (!h) {
514843fcf35SMiao Xie 		ret = -ENOMEM;
515843fcf35SMiao Xie 		goto alloc_fail;
516843fcf35SMiao Xie 	}
517a22285a6SYan, Zheng 
51898114659SJosef Bacik 	/*
51998114659SJosef Bacik 	 * If we are JOIN_NOLOCK we're already committing a transaction and
52098114659SJosef Bacik 	 * waiting on this guy, so we don't need to do the sb_start_intwrite
52198114659SJosef Bacik 	 * because we're already holding a ref.  We need this because we could
52298114659SJosef Bacik 	 * have raced in and did an fsync() on a file which can kick a commit
52398114659SJosef Bacik 	 * and then we deadlock with somebody doing a freeze.
524354aa0fbSMiao Xie 	 *
525354aa0fbSMiao Xie 	 * If we are ATTACH, it means we just want to catch the current
526354aa0fbSMiao Xie 	 * transaction and commit it, so we needn't do sb_start_intwrite().
52798114659SJosef Bacik 	 */
5280860adfdSMiao Xie 	if (type & __TRANS_FREEZABLE)
5290b246afaSJeff Mahoney 		sb_start_intwrite(fs_info->sb);
530b2b5ef5cSJan Kara 
5312ff7e61eSJeff Mahoney 	if (may_wait_transaction(fs_info, type))
5322ff7e61eSJeff Mahoney 		wait_current_trans(fs_info);
533a22285a6SYan, Zheng 
534a4abeea4SJosef Bacik 	do {
5352ff7e61eSJeff Mahoney 		ret = join_transaction(fs_info, type);
536178260b2SMiao Xie 		if (ret == -EBUSY) {
5372ff7e61eSJeff Mahoney 			wait_current_trans(fs_info);
538178260b2SMiao Xie 			if (unlikely(type == TRANS_ATTACH))
539178260b2SMiao Xie 				ret = -ENOENT;
540178260b2SMiao Xie 		}
541a4abeea4SJosef Bacik 	} while (ret == -EBUSY);
542a4abeea4SJosef Bacik 
543a43f7f82SLiu Bo 	if (ret < 0)
544843fcf35SMiao Xie 		goto join_fail;
5450f7d52f4SChris Mason 
5460b246afaSJeff Mahoney 	cur_trans = fs_info->running_transaction;
547a22285a6SYan, Zheng 
548a22285a6SYan, Zheng 	h->transid = cur_trans->transid;
549a22285a6SYan, Zheng 	h->transaction = cur_trans;
550d13603efSArne Jansen 	h->root = root;
551b50fff81SDavid Sterba 	refcount_set(&h->use_count, 1);
55264b63580SJeff Mahoney 	h->fs_info = root->fs_info;
5537174109cSQu Wenruo 
554a698d075SMiao Xie 	h->type = type;
555d9a0540aSFilipe Manana 	h->can_flush_pending_bgs = true;
556ea658badSJosef Bacik 	INIT_LIST_HEAD(&h->new_bgs);
557b7ec40d7SChris Mason 
558a22285a6SYan, Zheng 	smp_mb();
5594a9d8bdeSMiao Xie 	if (cur_trans->state >= TRANS_STATE_BLOCKED &&
5602ff7e61eSJeff Mahoney 	    may_wait_transaction(fs_info, type)) {
561abdd2e80SFilipe Manana 		current->journal_info = h;
5623a45bb20SJeff Mahoney 		btrfs_commit_transaction(h);
563a22285a6SYan, Zheng 		goto again;
564a22285a6SYan, Zheng 	}
5659ed74f2dSJosef Bacik 
566b5009945SJosef Bacik 	if (num_bytes) {
5670b246afaSJeff Mahoney 		trace_btrfs_space_reservation(fs_info, "transaction",
5682bcc0328SLiu Bo 					      h->transid, num_bytes, 1);
5690b246afaSJeff Mahoney 		h->block_rsv = &fs_info->trans_block_rsv;
570b5009945SJosef Bacik 		h->bytes_reserved = num_bytes;
57120dd2cbfSMiao Xie 		h->reloc_reserved = reloc_reserved;
572a22285a6SYan, Zheng 	}
573a22285a6SYan, Zheng 
5742a1eb461SJosef Bacik got_it:
575a4abeea4SJosef Bacik 	btrfs_record_root_in_trans(h, root);
576a22285a6SYan, Zheng 
577bcf3a3e7SNikolay Borisov 	if (!current->journal_info)
578a22285a6SYan, Zheng 		current->journal_info = h;
57979154b1bSChris Mason 	return h;
580843fcf35SMiao Xie 
581843fcf35SMiao Xie join_fail:
5820860adfdSMiao Xie 	if (type & __TRANS_FREEZABLE)
5830b246afaSJeff Mahoney 		sb_end_intwrite(fs_info->sb);
584843fcf35SMiao Xie 	kmem_cache_free(btrfs_trans_handle_cachep, h);
585843fcf35SMiao Xie alloc_fail:
586843fcf35SMiao Xie 	if (num_bytes)
5872ff7e61eSJeff Mahoney 		btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
588843fcf35SMiao Xie 					num_bytes);
589843fcf35SMiao Xie reserve_fail:
590733e03a0SQu Wenruo 	btrfs_qgroup_free_meta_pertrans(root, qgroup_reserved);
591843fcf35SMiao Xie 	return ERR_PTR(ret);
59279154b1bSChris Mason }
59379154b1bSChris Mason 
594f9295749SChris Mason struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
5955aed1dd8SAlexandru Moise 						   unsigned int num_items)
596f9295749SChris Mason {
59708e007d2SMiao Xie 	return start_transaction(root, num_items, TRANS_START,
598003d7c59SJeff Mahoney 				 BTRFS_RESERVE_FLUSH_ALL, true);
599f9295749SChris Mason }
600003d7c59SJeff Mahoney 
6018eab77ffSFilipe Manana struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
6028eab77ffSFilipe Manana 					struct btrfs_root *root,
6038eab77ffSFilipe Manana 					unsigned int num_items,
6048eab77ffSFilipe Manana 					int min_factor)
6058eab77ffSFilipe Manana {
6060b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6078eab77ffSFilipe Manana 	struct btrfs_trans_handle *trans;
6088eab77ffSFilipe Manana 	u64 num_bytes;
6098eab77ffSFilipe Manana 	int ret;
6108eab77ffSFilipe Manana 
611003d7c59SJeff Mahoney 	/*
612003d7c59SJeff Mahoney 	 * We have two callers: unlink and block group removal.  The
613003d7c59SJeff Mahoney 	 * former should succeed even if we will temporarily exceed
614003d7c59SJeff Mahoney 	 * quota and the latter operates on the extent root so
615003d7c59SJeff Mahoney 	 * qgroup enforcement is ignored anyway.
616003d7c59SJeff Mahoney 	 */
617003d7c59SJeff Mahoney 	trans = start_transaction(root, num_items, TRANS_START,
618003d7c59SJeff Mahoney 				  BTRFS_RESERVE_FLUSH_ALL, false);
6198eab77ffSFilipe Manana 	if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
6208eab77ffSFilipe Manana 		return trans;
6218eab77ffSFilipe Manana 
6228eab77ffSFilipe Manana 	trans = btrfs_start_transaction(root, 0);
6238eab77ffSFilipe Manana 	if (IS_ERR(trans))
6248eab77ffSFilipe Manana 		return trans;
6258eab77ffSFilipe Manana 
6260b246afaSJeff Mahoney 	num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
6270b246afaSJeff Mahoney 	ret = btrfs_cond_migrate_bytes(fs_info, &fs_info->trans_block_rsv,
6280b246afaSJeff Mahoney 				       num_bytes, min_factor);
6298eab77ffSFilipe Manana 	if (ret) {
6303a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
6318eab77ffSFilipe Manana 		return ERR_PTR(ret);
6328eab77ffSFilipe Manana 	}
6338eab77ffSFilipe Manana 
6340b246afaSJeff Mahoney 	trans->block_rsv = &fs_info->trans_block_rsv;
6358eab77ffSFilipe Manana 	trans->bytes_reserved = num_bytes;
6360b246afaSJeff Mahoney 	trace_btrfs_space_reservation(fs_info, "transaction",
63788d3a5aaSJosef Bacik 				      trans->transid, num_bytes, 1);
6388eab77ffSFilipe Manana 
6398eab77ffSFilipe Manana 	return trans;
6408eab77ffSFilipe Manana }
6418407aa46SMiao Xie 
6427a7eaa40SJosef Bacik struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
643f9295749SChris Mason {
644003d7c59SJeff Mahoney 	return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
645003d7c59SJeff Mahoney 				 true);
646f9295749SChris Mason }
647f9295749SChris Mason 
6487a7eaa40SJosef Bacik struct btrfs_trans_handle *btrfs_join_transaction_nolock(struct btrfs_root *root)
6490af3d00bSJosef Bacik {
650575a75d6SAlexandru Moise 	return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
651003d7c59SJeff Mahoney 				 BTRFS_RESERVE_NO_FLUSH, true);
6520af3d00bSJosef Bacik }
6530af3d00bSJosef Bacik 
654d4edf39bSMiao Xie /*
655d4edf39bSMiao Xie  * btrfs_attach_transaction() - catch the running transaction
656d4edf39bSMiao Xie  *
657d4edf39bSMiao Xie  * It is used when we want to commit the current the transaction, but
658d4edf39bSMiao Xie  * don't want to start a new one.
659d4edf39bSMiao Xie  *
660d4edf39bSMiao Xie  * Note: If this function return -ENOENT, it just means there is no
661d4edf39bSMiao Xie  * running transaction. But it is possible that the inactive transaction
662d4edf39bSMiao Xie  * is still in the memory, not fully on disk. If you hope there is no
663d4edf39bSMiao Xie  * inactive transaction in the fs when -ENOENT is returned, you should
664d4edf39bSMiao Xie  * invoke
665d4edf39bSMiao Xie  *     btrfs_attach_transaction_barrier()
666d4edf39bSMiao Xie  */
667354aa0fbSMiao Xie struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
66860376ce4SJosef Bacik {
669575a75d6SAlexandru Moise 	return start_transaction(root, 0, TRANS_ATTACH,
670003d7c59SJeff Mahoney 				 BTRFS_RESERVE_NO_FLUSH, true);
67160376ce4SJosef Bacik }
67260376ce4SJosef Bacik 
673d4edf39bSMiao Xie /*
67490b6d283SWang Sheng-Hui  * btrfs_attach_transaction_barrier() - catch the running transaction
675d4edf39bSMiao Xie  *
67652042d8eSAndrea Gelmini  * It is similar to the above function, the difference is this one
677d4edf39bSMiao Xie  * will wait for all the inactive transactions until they fully
678d4edf39bSMiao Xie  * complete.
679d4edf39bSMiao Xie  */
680d4edf39bSMiao Xie struct btrfs_trans_handle *
681d4edf39bSMiao Xie btrfs_attach_transaction_barrier(struct btrfs_root *root)
682d4edf39bSMiao Xie {
683d4edf39bSMiao Xie 	struct btrfs_trans_handle *trans;
684d4edf39bSMiao Xie 
685575a75d6SAlexandru Moise 	trans = start_transaction(root, 0, TRANS_ATTACH,
686003d7c59SJeff Mahoney 				  BTRFS_RESERVE_NO_FLUSH, true);
6878d9e220cSAl Viro 	if (trans == ERR_PTR(-ENOENT))
6882ff7e61eSJeff Mahoney 		btrfs_wait_for_commit(root->fs_info, 0);
689d4edf39bSMiao Xie 
690d4edf39bSMiao Xie 	return trans;
691d4edf39bSMiao Xie }
692d4edf39bSMiao Xie 
693d352ac68SChris Mason /* wait for a transaction commit to be fully complete */
6942ff7e61eSJeff Mahoney static noinline void wait_for_commit(struct btrfs_transaction *commit)
69589ce8a63SChris Mason {
6964a9d8bdeSMiao Xie 	wait_event(commit->commit_wait, commit->state == TRANS_STATE_COMPLETED);
69789ce8a63SChris Mason }
69889ce8a63SChris Mason 
6992ff7e61eSJeff Mahoney int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
70046204592SSage Weil {
70146204592SSage Weil 	struct btrfs_transaction *cur_trans = NULL, *t;
7028cd2807fSMiao Xie 	int ret = 0;
70346204592SSage Weil 
70446204592SSage Weil 	if (transid) {
7050b246afaSJeff Mahoney 		if (transid <= fs_info->last_trans_committed)
706a4abeea4SJosef Bacik 			goto out;
70746204592SSage Weil 
70846204592SSage Weil 		/* find specified transaction */
7090b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
7100b246afaSJeff Mahoney 		list_for_each_entry(t, &fs_info->trans_list, list) {
71146204592SSage Weil 			if (t->transid == transid) {
71246204592SSage Weil 				cur_trans = t;
7139b64f57dSElena Reshetova 				refcount_inc(&cur_trans->use_count);
7148cd2807fSMiao Xie 				ret = 0;
71546204592SSage Weil 				break;
71646204592SSage Weil 			}
7178cd2807fSMiao Xie 			if (t->transid > transid) {
7188cd2807fSMiao Xie 				ret = 0;
71946204592SSage Weil 				break;
72046204592SSage Weil 			}
7218cd2807fSMiao Xie 		}
7220b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
72342383020SSage Weil 
72442383020SSage Weil 		/*
72542383020SSage Weil 		 * The specified transaction doesn't exist, or we
72642383020SSage Weil 		 * raced with btrfs_commit_transaction
72742383020SSage Weil 		 */
72842383020SSage Weil 		if (!cur_trans) {
7290b246afaSJeff Mahoney 			if (transid > fs_info->last_trans_committed)
73042383020SSage Weil 				ret = -EINVAL;
7318cd2807fSMiao Xie 			goto out;
73242383020SSage Weil 		}
73346204592SSage Weil 	} else {
73446204592SSage Weil 		/* find newest transaction that is committing | committed */
7350b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
7360b246afaSJeff Mahoney 		list_for_each_entry_reverse(t, &fs_info->trans_list,
73746204592SSage Weil 					    list) {
7384a9d8bdeSMiao Xie 			if (t->state >= TRANS_STATE_COMMIT_START) {
7394a9d8bdeSMiao Xie 				if (t->state == TRANS_STATE_COMPLETED)
7403473f3c0SJosef Bacik 					break;
74146204592SSage Weil 				cur_trans = t;
7429b64f57dSElena Reshetova 				refcount_inc(&cur_trans->use_count);
74346204592SSage Weil 				break;
74446204592SSage Weil 			}
74546204592SSage Weil 		}
7460b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
74746204592SSage Weil 		if (!cur_trans)
748a4abeea4SJosef Bacik 			goto out;  /* nothing committing|committed */
74946204592SSage Weil 	}
75046204592SSage Weil 
7512ff7e61eSJeff Mahoney 	wait_for_commit(cur_trans);
752724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
753a4abeea4SJosef Bacik out:
75446204592SSage Weil 	return ret;
75546204592SSage Weil }
75646204592SSage Weil 
7572ff7e61eSJeff Mahoney void btrfs_throttle(struct btrfs_fs_info *fs_info)
75837d1aeeeSChris Mason {
7592ff7e61eSJeff Mahoney 	wait_current_trans(fs_info);
76037d1aeeeSChris Mason }
76137d1aeeeSChris Mason 
7622ff7e61eSJeff Mahoney static int should_end_transaction(struct btrfs_trans_handle *trans)
7638929ecfaSYan, Zheng {
7642ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = trans->fs_info;
7650b246afaSJeff Mahoney 
76664403612SJosef Bacik 	if (btrfs_check_space_for_delayed_refs(fs_info))
7671be41b78SJosef Bacik 		return 1;
76836ba022aSJosef Bacik 
7692ff7e61eSJeff Mahoney 	return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
7708929ecfaSYan, Zheng }
7718929ecfaSYan, Zheng 
7723a45bb20SJeff Mahoney int btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
7738929ecfaSYan, Zheng {
7748929ecfaSYan, Zheng 	struct btrfs_transaction *cur_trans = trans->transaction;
7758929ecfaSYan, Zheng 
776a4abeea4SJosef Bacik 	smp_mb();
7774a9d8bdeSMiao Xie 	if (cur_trans->state >= TRANS_STATE_BLOCKED ||
7784a9d8bdeSMiao Xie 	    cur_trans->delayed_refs.flushing)
7798929ecfaSYan, Zheng 		return 1;
7808929ecfaSYan, Zheng 
7812ff7e61eSJeff Mahoney 	return should_end_transaction(trans);
7828929ecfaSYan, Zheng }
7838929ecfaSYan, Zheng 
784dc60c525SNikolay Borisov static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
785dc60c525SNikolay Borisov 
7860e34693fSNikolay Borisov {
787dc60c525SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
788dc60c525SNikolay Borisov 
7890e34693fSNikolay Borisov 	if (!trans->block_rsv) {
7900e34693fSNikolay Borisov 		ASSERT(!trans->bytes_reserved);
7910e34693fSNikolay Borisov 		return;
7920e34693fSNikolay Borisov 	}
7930e34693fSNikolay Borisov 
7940e34693fSNikolay Borisov 	if (!trans->bytes_reserved)
7950e34693fSNikolay Borisov 		return;
7960e34693fSNikolay Borisov 
7970e34693fSNikolay Borisov 	ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
7980e34693fSNikolay Borisov 	trace_btrfs_space_reservation(fs_info, "transaction",
7990e34693fSNikolay Borisov 				      trans->transid, trans->bytes_reserved, 0);
8000e34693fSNikolay Borisov 	btrfs_block_rsv_release(fs_info, trans->block_rsv,
8010e34693fSNikolay Borisov 				trans->bytes_reserved);
8020e34693fSNikolay Borisov 	trans->bytes_reserved = 0;
8030e34693fSNikolay Borisov }
8040e34693fSNikolay Borisov 
80589ce8a63SChris Mason static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
8063a45bb20SJeff Mahoney 				   int throttle)
80779154b1bSChris Mason {
8083a45bb20SJeff Mahoney 	struct btrfs_fs_info *info = trans->fs_info;
8098929ecfaSYan, Zheng 	struct btrfs_transaction *cur_trans = trans->transaction;
810a698d075SMiao Xie 	int lock = (trans->type != TRANS_JOIN_NOLOCK);
8114edc2ca3SDave Jones 	int err = 0;
812d6e4a428SChris Mason 
813b50fff81SDavid Sterba 	if (refcount_read(&trans->use_count) > 1) {
814b50fff81SDavid Sterba 		refcount_dec(&trans->use_count);
8152a1eb461SJosef Bacik 		trans->block_rsv = trans->orig_rsv;
8162a1eb461SJosef Bacik 		return 0;
8172a1eb461SJosef Bacik 	}
8182a1eb461SJosef Bacik 
819dc60c525SNikolay Borisov 	btrfs_trans_release_metadata(trans);
8204c13d758SJosef Bacik 	trans->block_rsv = NULL;
821c5567237SArne Jansen 
8226c686b35SNikolay Borisov 	btrfs_create_pending_block_groups(trans);
823ea658badSJosef Bacik 
8244fbcdf66SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
8254fbcdf66SFilipe Manana 
82620c7bcecSSeraphime Kirkovski 	if (lock && READ_ONCE(cur_trans->state) == TRANS_STATE_BLOCKED) {
8273bbb24b2SJosef Bacik 		if (throttle)
8283a45bb20SJeff Mahoney 			return btrfs_commit_transaction(trans);
8293bbb24b2SJosef Bacik 		else
8308929ecfaSYan, Zheng 			wake_up_process(info->transaction_kthread);
8318929ecfaSYan, Zheng 	}
8328929ecfaSYan, Zheng 
8330860adfdSMiao Xie 	if (trans->type & __TRANS_FREEZABLE)
8340b246afaSJeff Mahoney 		sb_end_intwrite(info->sb);
8356df7881aSJosef Bacik 
8368929ecfaSYan, Zheng 	WARN_ON(cur_trans != info->running_transaction);
83713c5a93eSJosef Bacik 	WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
83813c5a93eSJosef Bacik 	atomic_dec(&cur_trans->num_writers);
8390860adfdSMiao Xie 	extwriter_counter_dec(cur_trans, trans->type);
84089ce8a63SChris Mason 
841093258e6SDavid Sterba 	cond_wake_up(&cur_trans->writer_wait);
842724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
8439ed74f2dSJosef Bacik 
8449ed74f2dSJosef Bacik 	if (current->journal_info == trans)
8459ed74f2dSJosef Bacik 		current->journal_info = NULL;
846ab78c84dSChris Mason 
84724bbcf04SYan, Zheng 	if (throttle)
8482ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(info);
84924bbcf04SYan, Zheng 
85049b25e05SJeff Mahoney 	if (trans->aborted ||
8510b246afaSJeff Mahoney 	    test_bit(BTRFS_FS_STATE_ERROR, &info->fs_state)) {
8524e121c06SJosef Bacik 		wake_up_process(info->transaction_kthread);
8534edc2ca3SDave Jones 		err = -EIO;
8544e121c06SJosef Bacik 	}
85549b25e05SJeff Mahoney 
8564edc2ca3SDave Jones 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
8574edc2ca3SDave Jones 	return err;
85879154b1bSChris Mason }
85979154b1bSChris Mason 
8603a45bb20SJeff Mahoney int btrfs_end_transaction(struct btrfs_trans_handle *trans)
86189ce8a63SChris Mason {
8623a45bb20SJeff Mahoney 	return __btrfs_end_transaction(trans, 0);
86389ce8a63SChris Mason }
86489ce8a63SChris Mason 
8653a45bb20SJeff Mahoney int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
86689ce8a63SChris Mason {
8673a45bb20SJeff Mahoney 	return __btrfs_end_transaction(trans, 1);
86816cdcec7SMiao Xie }
86916cdcec7SMiao Xie 
870d352ac68SChris Mason /*
871d352ac68SChris Mason  * when btree blocks are allocated, they have some corresponding bits set for
872d352ac68SChris Mason  * them in one of two extent_io trees.  This is used to make sure all of
873690587d1SChris Mason  * those extents are sent to disk but does not wait on them
874d352ac68SChris Mason  */
8752ff7e61eSJeff Mahoney int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
8768cef4e16SYan, Zheng 			       struct extent_io_tree *dirty_pages, int mark)
87779154b1bSChris Mason {
878777e6bd7SChris Mason 	int err = 0;
8797c4452b9SChris Mason 	int werr = 0;
8800b246afaSJeff Mahoney 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
881e6138876SJosef Bacik 	struct extent_state *cached_state = NULL;
882777e6bd7SChris Mason 	u64 start = 0;
8835f39d397SChris Mason 	u64 end;
8847c4452b9SChris Mason 
8856300463bSLiu Bo 	atomic_inc(&BTRFS_I(fs_info->btree_inode)->sync_writers);
8861728366eSJosef Bacik 	while (!find_first_extent_bit(dirty_pages, start, &start, &end,
887e6138876SJosef Bacik 				      mark, &cached_state)) {
888663dfbb0SFilipe Manana 		bool wait_writeback = false;
889663dfbb0SFilipe Manana 
890663dfbb0SFilipe Manana 		err = convert_extent_bit(dirty_pages, start, end,
891663dfbb0SFilipe Manana 					 EXTENT_NEED_WAIT,
892210aa277SDavid Sterba 					 mark, &cached_state);
893663dfbb0SFilipe Manana 		/*
894663dfbb0SFilipe Manana 		 * convert_extent_bit can return -ENOMEM, which is most of the
895663dfbb0SFilipe Manana 		 * time a temporary error. So when it happens, ignore the error
896663dfbb0SFilipe Manana 		 * and wait for writeback of this range to finish - because we
897663dfbb0SFilipe Manana 		 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
898bf89d38fSJeff Mahoney 		 * to __btrfs_wait_marked_extents() would not know that
899bf89d38fSJeff Mahoney 		 * writeback for this range started and therefore wouldn't
900bf89d38fSJeff Mahoney 		 * wait for it to finish - we don't want to commit a
901bf89d38fSJeff Mahoney 		 * superblock that points to btree nodes/leafs for which
902bf89d38fSJeff Mahoney 		 * writeback hasn't finished yet (and without errors).
903663dfbb0SFilipe Manana 		 * We cleanup any entries left in the io tree when committing
90441e7acd3SNikolay Borisov 		 * the transaction (through extent_io_tree_release()).
905663dfbb0SFilipe Manana 		 */
906663dfbb0SFilipe Manana 		if (err == -ENOMEM) {
907663dfbb0SFilipe Manana 			err = 0;
908663dfbb0SFilipe Manana 			wait_writeback = true;
909663dfbb0SFilipe Manana 		}
910663dfbb0SFilipe Manana 		if (!err)
9111728366eSJosef Bacik 			err = filemap_fdatawrite_range(mapping, start, end);
9127c4452b9SChris Mason 		if (err)
9137c4452b9SChris Mason 			werr = err;
914663dfbb0SFilipe Manana 		else if (wait_writeback)
915663dfbb0SFilipe Manana 			werr = filemap_fdatawait_range(mapping, start, end);
916e38e2ed7SFilipe Manana 		free_extent_state(cached_state);
917663dfbb0SFilipe Manana 		cached_state = NULL;
9181728366eSJosef Bacik 		cond_resched();
9191728366eSJosef Bacik 		start = end + 1;
9207c4452b9SChris Mason 	}
9216300463bSLiu Bo 	atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
922690587d1SChris Mason 	return werr;
923690587d1SChris Mason }
924690587d1SChris Mason 
925690587d1SChris Mason /*
926690587d1SChris Mason  * when btree blocks are allocated, they have some corresponding bits set for
927690587d1SChris Mason  * them in one of two extent_io trees.  This is used to make sure all of
928690587d1SChris Mason  * those extents are on disk for transaction or log commit.  We wait
929690587d1SChris Mason  * on all the pages and clear them from the dirty pages state tree
930690587d1SChris Mason  */
931bf89d38fSJeff Mahoney static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
932bf89d38fSJeff Mahoney 				       struct extent_io_tree *dirty_pages)
933690587d1SChris Mason {
934690587d1SChris Mason 	int err = 0;
935690587d1SChris Mason 	int werr = 0;
9360b246afaSJeff Mahoney 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
937e6138876SJosef Bacik 	struct extent_state *cached_state = NULL;
938690587d1SChris Mason 	u64 start = 0;
939690587d1SChris Mason 	u64 end;
940690587d1SChris Mason 
9411728366eSJosef Bacik 	while (!find_first_extent_bit(dirty_pages, start, &start, &end,
942e6138876SJosef Bacik 				      EXTENT_NEED_WAIT, &cached_state)) {
943663dfbb0SFilipe Manana 		/*
944663dfbb0SFilipe Manana 		 * Ignore -ENOMEM errors returned by clear_extent_bit().
945663dfbb0SFilipe Manana 		 * When committing the transaction, we'll remove any entries
946663dfbb0SFilipe Manana 		 * left in the io tree. For a log commit, we don't remove them
947663dfbb0SFilipe Manana 		 * after committing the log because the tree can be accessed
948663dfbb0SFilipe Manana 		 * concurrently - we do it only at transaction commit time when
94941e7acd3SNikolay Borisov 		 * it's safe to do it (through extent_io_tree_release()).
950663dfbb0SFilipe Manana 		 */
951663dfbb0SFilipe Manana 		err = clear_extent_bit(dirty_pages, start, end,
952ae0f1625SDavid Sterba 				       EXTENT_NEED_WAIT, 0, 0, &cached_state);
953663dfbb0SFilipe Manana 		if (err == -ENOMEM)
954663dfbb0SFilipe Manana 			err = 0;
955663dfbb0SFilipe Manana 		if (!err)
9561728366eSJosef Bacik 			err = filemap_fdatawait_range(mapping, start, end);
957777e6bd7SChris Mason 		if (err)
958777e6bd7SChris Mason 			werr = err;
959e38e2ed7SFilipe Manana 		free_extent_state(cached_state);
960e38e2ed7SFilipe Manana 		cached_state = NULL;
961777e6bd7SChris Mason 		cond_resched();
9621728366eSJosef Bacik 		start = end + 1;
963777e6bd7SChris Mason 	}
9647c4452b9SChris Mason 	if (err)
9657c4452b9SChris Mason 		werr = err;
966bf89d38fSJeff Mahoney 	return werr;
967bf89d38fSJeff Mahoney }
968656f30dbSFilipe Manana 
969bf89d38fSJeff Mahoney int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
970bf89d38fSJeff Mahoney 		       struct extent_io_tree *dirty_pages)
971bf89d38fSJeff Mahoney {
972bf89d38fSJeff Mahoney 	bool errors = false;
973bf89d38fSJeff Mahoney 	int err;
974bf89d38fSJeff Mahoney 
975bf89d38fSJeff Mahoney 	err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
976bf89d38fSJeff Mahoney 	if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
977bf89d38fSJeff Mahoney 		errors = true;
978bf89d38fSJeff Mahoney 
979bf89d38fSJeff Mahoney 	if (errors && !err)
980bf89d38fSJeff Mahoney 		err = -EIO;
981bf89d38fSJeff Mahoney 	return err;
982bf89d38fSJeff Mahoney }
983bf89d38fSJeff Mahoney 
984bf89d38fSJeff Mahoney int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
985bf89d38fSJeff Mahoney {
986bf89d38fSJeff Mahoney 	struct btrfs_fs_info *fs_info = log_root->fs_info;
987bf89d38fSJeff Mahoney 	struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
988bf89d38fSJeff Mahoney 	bool errors = false;
989bf89d38fSJeff Mahoney 	int err;
990bf89d38fSJeff Mahoney 
991bf89d38fSJeff Mahoney 	ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
992bf89d38fSJeff Mahoney 
993bf89d38fSJeff Mahoney 	err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
994656f30dbSFilipe Manana 	if ((mark & EXTENT_DIRTY) &&
9950b246afaSJeff Mahoney 	    test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
996656f30dbSFilipe Manana 		errors = true;
997656f30dbSFilipe Manana 
998656f30dbSFilipe Manana 	if ((mark & EXTENT_NEW) &&
9990b246afaSJeff Mahoney 	    test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1000656f30dbSFilipe Manana 		errors = true;
1001656f30dbSFilipe Manana 
1002bf89d38fSJeff Mahoney 	if (errors && !err)
1003bf89d38fSJeff Mahoney 		err = -EIO;
1004bf89d38fSJeff Mahoney 	return err;
100579154b1bSChris Mason }
100679154b1bSChris Mason 
1007690587d1SChris Mason /*
1008c9b577c0SNikolay Borisov  * When btree blocks are allocated the corresponding extents are marked dirty.
1009c9b577c0SNikolay Borisov  * This function ensures such extents are persisted on disk for transaction or
1010c9b577c0SNikolay Borisov  * log commit.
1011c9b577c0SNikolay Borisov  *
1012c9b577c0SNikolay Borisov  * @trans: transaction whose dirty pages we'd like to write
1013690587d1SChris Mason  */
101470458a58SNikolay Borisov static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1015d0c803c4SChris Mason {
1016663dfbb0SFilipe Manana 	int ret;
1017c9b577c0SNikolay Borisov 	int ret2;
1018c9b577c0SNikolay Borisov 	struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
101970458a58SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
1020c9b577c0SNikolay Borisov 	struct blk_plug plug;
1021663dfbb0SFilipe Manana 
1022c9b577c0SNikolay Borisov 	blk_start_plug(&plug);
1023c9b577c0SNikolay Borisov 	ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1024c9b577c0SNikolay Borisov 	blk_finish_plug(&plug);
1025c9b577c0SNikolay Borisov 	ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1026c9b577c0SNikolay Borisov 
102741e7acd3SNikolay Borisov 	extent_io_tree_release(&trans->transaction->dirty_pages);
1028663dfbb0SFilipe Manana 
1029c9b577c0SNikolay Borisov 	if (ret)
1030663dfbb0SFilipe Manana 		return ret;
1031c9b577c0SNikolay Borisov 	else if (ret2)
1032c9b577c0SNikolay Borisov 		return ret2;
1033c9b577c0SNikolay Borisov 	else
1034c9b577c0SNikolay Borisov 		return 0;
1035d0c803c4SChris Mason }
1036d0c803c4SChris Mason 
1037d352ac68SChris Mason /*
1038d352ac68SChris Mason  * this is used to update the root pointer in the tree of tree roots.
1039d352ac68SChris Mason  *
1040d352ac68SChris Mason  * But, in the case of the extent allocation tree, updating the root
1041d352ac68SChris Mason  * pointer may allocate blocks which may change the root of the extent
1042d352ac68SChris Mason  * allocation tree.
1043d352ac68SChris Mason  *
1044d352ac68SChris Mason  * So, this loops and repeats and makes sure the cowonly root didn't
1045d352ac68SChris Mason  * change while the root pointer was being updated in the metadata.
1046d352ac68SChris Mason  */
10470b86a832SChris Mason static int update_cowonly_root(struct btrfs_trans_handle *trans,
104879154b1bSChris Mason 			       struct btrfs_root *root)
104979154b1bSChris Mason {
105079154b1bSChris Mason 	int ret;
10510b86a832SChris Mason 	u64 old_root_bytenr;
105286b9f2ecSYan, Zheng 	u64 old_root_used;
10530b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10540b246afaSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
105579154b1bSChris Mason 
105686b9f2ecSYan, Zheng 	old_root_used = btrfs_root_used(&root->root_item);
105756bec294SChris Mason 
105879154b1bSChris Mason 	while (1) {
10590b86a832SChris Mason 		old_root_bytenr = btrfs_root_bytenr(&root->root_item);
106086b9f2ecSYan, Zheng 		if (old_root_bytenr == root->node->start &&
1061ea526d18SJosef Bacik 		    old_root_used == btrfs_root_used(&root->root_item))
106279154b1bSChris Mason 			break;
106387ef2bb4SChris Mason 
10645d4f98a2SYan Zheng 		btrfs_set_root_node(&root->root_item, root->node);
106579154b1bSChris Mason 		ret = btrfs_update_root(trans, tree_root,
10660b86a832SChris Mason 					&root->root_key,
10670b86a832SChris Mason 					&root->root_item);
106849b25e05SJeff Mahoney 		if (ret)
106949b25e05SJeff Mahoney 			return ret;
107056bec294SChris Mason 
107186b9f2ecSYan, Zheng 		old_root_used = btrfs_root_used(&root->root_item);
1072e7070be1SJosef Bacik 	}
1073276e680dSYan Zheng 
10740b86a832SChris Mason 	return 0;
10750b86a832SChris Mason }
10760b86a832SChris Mason 
1077d352ac68SChris Mason /*
1078d352ac68SChris Mason  * update all the cowonly tree roots on disk
107949b25e05SJeff Mahoney  *
108049b25e05SJeff Mahoney  * The error handling in this function may not be obvious. Any of the
108149b25e05SJeff Mahoney  * failures will cause the file system to go offline. We still need
108249b25e05SJeff Mahoney  * to clean up the delayed refs.
1083d352ac68SChris Mason  */
10849386d8bcSNikolay Borisov static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
10850b86a832SChris Mason {
10869386d8bcSNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
1087ea526d18SJosef Bacik 	struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
10881bbc621eSChris Mason 	struct list_head *io_bgs = &trans->transaction->io_bgs;
10890b86a832SChris Mason 	struct list_head *next;
109084234f3aSYan Zheng 	struct extent_buffer *eb;
109156bec294SChris Mason 	int ret;
109284234f3aSYan Zheng 
109384234f3aSYan Zheng 	eb = btrfs_lock_root_node(fs_info->tree_root);
109449b25e05SJeff Mahoney 	ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
109549b25e05SJeff Mahoney 			      0, &eb);
109684234f3aSYan Zheng 	btrfs_tree_unlock(eb);
109784234f3aSYan Zheng 	free_extent_buffer(eb);
10980b86a832SChris Mason 
109949b25e05SJeff Mahoney 	if (ret)
110049b25e05SJeff Mahoney 		return ret;
110149b25e05SJeff Mahoney 
1102c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
110349b25e05SJeff Mahoney 	if (ret)
110449b25e05SJeff Mahoney 		return ret;
110587ef2bb4SChris Mason 
11060b246afaSJeff Mahoney 	ret = btrfs_run_dev_stats(trans, fs_info);
1107c16ce190SJosef Bacik 	if (ret)
1108c16ce190SJosef Bacik 		return ret;
11090b246afaSJeff Mahoney 	ret = btrfs_run_dev_replace(trans, fs_info);
1110c16ce190SJosef Bacik 	if (ret)
1111c16ce190SJosef Bacik 		return ret;
1112280f8bd2SLu Fengqi 	ret = btrfs_run_qgroups(trans);
1113c16ce190SJosef Bacik 	if (ret)
1114c16ce190SJosef Bacik 		return ret;
1115546adb0dSJan Schmidt 
11162ff7e61eSJeff Mahoney 	ret = btrfs_setup_space_cache(trans, fs_info);
1117dcdf7f6dSJosef Bacik 	if (ret)
1118dcdf7f6dSJosef Bacik 		return ret;
1119dcdf7f6dSJosef Bacik 
1120546adb0dSJan Schmidt 	/* run_qgroups might have added some more refs */
1121c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1122c16ce190SJosef Bacik 	if (ret)
1123c16ce190SJosef Bacik 		return ret;
1124ea526d18SJosef Bacik again:
11250b86a832SChris Mason 	while (!list_empty(&fs_info->dirty_cowonly_roots)) {
11262ff7e61eSJeff Mahoney 		struct btrfs_root *root;
11270b86a832SChris Mason 		next = fs_info->dirty_cowonly_roots.next;
11280b86a832SChris Mason 		list_del_init(next);
11290b86a832SChris Mason 		root = list_entry(next, struct btrfs_root, dirty_list);
1130e7070be1SJosef Bacik 		clear_bit(BTRFS_ROOT_DIRTY, &root->state);
113187ef2bb4SChris Mason 
11329e351cc8SJosef Bacik 		if (root != fs_info->extent_root)
11339e351cc8SJosef Bacik 			list_add_tail(&root->dirty_list,
11349e351cc8SJosef Bacik 				      &trans->transaction->switch_commits);
113549b25e05SJeff Mahoney 		ret = update_cowonly_root(trans, root);
113649b25e05SJeff Mahoney 		if (ret)
113749b25e05SJeff Mahoney 			return ret;
1138c79a70b1SNikolay Borisov 		ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1139ea526d18SJosef Bacik 		if (ret)
1140ea526d18SJosef Bacik 			return ret;
114179154b1bSChris Mason 	}
1142276e680dSYan Zheng 
11431bbc621eSChris Mason 	while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
11442ff7e61eSJeff Mahoney 		ret = btrfs_write_dirty_block_groups(trans, fs_info);
1145ea526d18SJosef Bacik 		if (ret)
1146ea526d18SJosef Bacik 			return ret;
1147c79a70b1SNikolay Borisov 		ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1148ea526d18SJosef Bacik 		if (ret)
1149ea526d18SJosef Bacik 			return ret;
1150ea526d18SJosef Bacik 	}
1151ea526d18SJosef Bacik 
1152ea526d18SJosef Bacik 	if (!list_empty(&fs_info->dirty_cowonly_roots))
1153ea526d18SJosef Bacik 		goto again;
1154ea526d18SJosef Bacik 
11559e351cc8SJosef Bacik 	list_add_tail(&fs_info->extent_root->dirty_list,
11569e351cc8SJosef Bacik 		      &trans->transaction->switch_commits);
11579f6cbcbbSDavid Sterba 
11589f6cbcbbSDavid Sterba 	/* Update dev-replace pointer once everything is committed */
11599f6cbcbbSDavid Sterba 	fs_info->dev_replace.committed_cursor_left =
11609f6cbcbbSDavid Sterba 		fs_info->dev_replace.cursor_left_last_write_of_item;
11618dabb742SStefan Behrens 
116279154b1bSChris Mason 	return 0;
116379154b1bSChris Mason }
116479154b1bSChris Mason 
1165d352ac68SChris Mason /*
1166d352ac68SChris Mason  * dead roots are old snapshots that need to be deleted.  This allocates
1167d352ac68SChris Mason  * a dirty root struct and adds it into the list of dead roots that need to
1168d352ac68SChris Mason  * be deleted
1169d352ac68SChris Mason  */
1170cfad392bSJosef Bacik void btrfs_add_dead_root(struct btrfs_root *root)
11715eda7b5eSChris Mason {
11720b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11730b246afaSJeff Mahoney 
11740b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
1175cfad392bSJosef Bacik 	if (list_empty(&root->root_list))
11760b246afaSJeff Mahoney 		list_add_tail(&root->root_list, &fs_info->dead_roots);
11770b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
11785eda7b5eSChris Mason }
11795eda7b5eSChris Mason 
1180d352ac68SChris Mason /*
11815d4f98a2SYan Zheng  * update all the cowonly tree roots on disk
1182d352ac68SChris Mason  */
11837e4443d9SNikolay Borisov static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
11840f7d52f4SChris Mason {
11857e4443d9SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
11860f7d52f4SChris Mason 	struct btrfs_root *gang[8];
11870f7d52f4SChris Mason 	int i;
11880f7d52f4SChris Mason 	int ret;
118954aa1f4dSChris Mason 	int err = 0;
119054aa1f4dSChris Mason 
1191a4abeea4SJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
11920f7d52f4SChris Mason 	while (1) {
11935d4f98a2SYan Zheng 		ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
11945d4f98a2SYan Zheng 						 (void **)gang, 0,
11950f7d52f4SChris Mason 						 ARRAY_SIZE(gang),
11960f7d52f4SChris Mason 						 BTRFS_ROOT_TRANS_TAG);
11970f7d52f4SChris Mason 		if (ret == 0)
11980f7d52f4SChris Mason 			break;
11990f7d52f4SChris Mason 		for (i = 0; i < ret; i++) {
12005b4aacefSJeff Mahoney 			struct btrfs_root *root = gang[i];
12015d4f98a2SYan Zheng 			radix_tree_tag_clear(&fs_info->fs_roots_radix,
12022619ba1fSChris Mason 					(unsigned long)root->root_key.objectid,
12030f7d52f4SChris Mason 					BTRFS_ROOT_TRANS_TAG);
1204a4abeea4SJosef Bacik 			spin_unlock(&fs_info->fs_roots_radix_lock);
120531153d81SYan Zheng 
1206e02119d5SChris Mason 			btrfs_free_log(trans, root);
12075d4f98a2SYan Zheng 			btrfs_update_reloc_root(trans, root);
1208e02119d5SChris Mason 
120982d5902dSLi Zefan 			btrfs_save_ino_cache(root, trans);
121082d5902dSLi Zefan 
1211f1ebcc74SLiu Bo 			/* see comments in should_cow_block() */
121227cdeb70SMiao Xie 			clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1213c7548af6SChris Mason 			smp_mb__after_atomic();
1214f1ebcc74SLiu Bo 
1215978d910dSYan Zheng 			if (root->commit_root != root->node) {
12169e351cc8SJosef Bacik 				list_add_tail(&root->dirty_list,
12179e351cc8SJosef Bacik 					&trans->transaction->switch_commits);
1218978d910dSYan Zheng 				btrfs_set_root_node(&root->root_item,
1219978d910dSYan Zheng 						    root->node);
1220978d910dSYan Zheng 			}
122131153d81SYan Zheng 
12225d4f98a2SYan Zheng 			err = btrfs_update_root(trans, fs_info->tree_root,
12230f7d52f4SChris Mason 						&root->root_key,
12240f7d52f4SChris Mason 						&root->root_item);
1225a4abeea4SJosef Bacik 			spin_lock(&fs_info->fs_roots_radix_lock);
122654aa1f4dSChris Mason 			if (err)
122754aa1f4dSChris Mason 				break;
1228733e03a0SQu Wenruo 			btrfs_qgroup_free_meta_all_pertrans(root);
12290f7d52f4SChris Mason 		}
12309f3a7427SChris Mason 	}
1231a4abeea4SJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
123254aa1f4dSChris Mason 	return err;
12330f7d52f4SChris Mason }
12340f7d52f4SChris Mason 
1235d352ac68SChris Mason /*
1236de78b51aSEric Sandeen  * defrag a given btree.
1237de78b51aSEric Sandeen  * Every leaf in the btree is read and defragged.
1238d352ac68SChris Mason  */
1239de78b51aSEric Sandeen int btrfs_defrag_root(struct btrfs_root *root)
1240e9d0b13bSChris Mason {
1241e9d0b13bSChris Mason 	struct btrfs_fs_info *info = root->fs_info;
1242e9d0b13bSChris Mason 	struct btrfs_trans_handle *trans;
12438929ecfaSYan, Zheng 	int ret;
1244e9d0b13bSChris Mason 
124527cdeb70SMiao Xie 	if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1246e9d0b13bSChris Mason 		return 0;
12478929ecfaSYan, Zheng 
12486b80053dSChris Mason 	while (1) {
12498929ecfaSYan, Zheng 		trans = btrfs_start_transaction(root, 0);
12508929ecfaSYan, Zheng 		if (IS_ERR(trans))
12518929ecfaSYan, Zheng 			return PTR_ERR(trans);
12528929ecfaSYan, Zheng 
1253de78b51aSEric Sandeen 		ret = btrfs_defrag_leaves(trans, root);
12548929ecfaSYan, Zheng 
12553a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
12562ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(info);
1257e9d0b13bSChris Mason 		cond_resched();
1258e9d0b13bSChris Mason 
1259ab8d0fc4SJeff Mahoney 		if (btrfs_fs_closing(info) || ret != -EAGAIN)
1260e9d0b13bSChris Mason 			break;
1261210549ebSDavid Sterba 
1262ab8d0fc4SJeff Mahoney 		if (btrfs_defrag_cancelled(info)) {
1263ab8d0fc4SJeff Mahoney 			btrfs_debug(info, "defrag_root cancelled");
1264210549ebSDavid Sterba 			ret = -EAGAIN;
1265210549ebSDavid Sterba 			break;
1266210549ebSDavid Sterba 		}
1267e9d0b13bSChris Mason 	}
126827cdeb70SMiao Xie 	clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
12698929ecfaSYan, Zheng 	return ret;
1270e9d0b13bSChris Mason }
1271e9d0b13bSChris Mason 
1272d352ac68SChris Mason /*
12736426c7adSQu Wenruo  * Do all special snapshot related qgroup dirty hack.
12746426c7adSQu Wenruo  *
12756426c7adSQu Wenruo  * Will do all needed qgroup inherit and dirty hack like switch commit
12766426c7adSQu Wenruo  * roots inside one transaction and write all btree into disk, to make
12776426c7adSQu Wenruo  * qgroup works.
12786426c7adSQu Wenruo  */
12796426c7adSQu Wenruo static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
12806426c7adSQu Wenruo 				   struct btrfs_root *src,
12816426c7adSQu Wenruo 				   struct btrfs_root *parent,
12826426c7adSQu Wenruo 				   struct btrfs_qgroup_inherit *inherit,
12836426c7adSQu Wenruo 				   u64 dst_objectid)
12846426c7adSQu Wenruo {
12856426c7adSQu Wenruo 	struct btrfs_fs_info *fs_info = src->fs_info;
12866426c7adSQu Wenruo 	int ret;
12876426c7adSQu Wenruo 
12886426c7adSQu Wenruo 	/*
12896426c7adSQu Wenruo 	 * Save some performance in the case that qgroups are not
12906426c7adSQu Wenruo 	 * enabled. If this check races with the ioctl, rescan will
12916426c7adSQu Wenruo 	 * kick in anyway.
12926426c7adSQu Wenruo 	 */
12939ea6e2b5SDavid Sterba 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
12946426c7adSQu Wenruo 		return 0;
12956426c7adSQu Wenruo 
12966426c7adSQu Wenruo 	/*
129752042d8eSAndrea Gelmini 	 * Ensure dirty @src will be committed.  Or, after coming
12984d31778aSQu Wenruo 	 * commit_fs_roots() and switch_commit_roots(), any dirty but not
12994d31778aSQu Wenruo 	 * recorded root will never be updated again, causing an outdated root
13004d31778aSQu Wenruo 	 * item.
13014d31778aSQu Wenruo 	 */
13024d31778aSQu Wenruo 	record_root_in_trans(trans, src, 1);
13034d31778aSQu Wenruo 
13044d31778aSQu Wenruo 	/*
13056426c7adSQu Wenruo 	 * We are going to commit transaction, see btrfs_commit_transaction()
13066426c7adSQu Wenruo 	 * comment for reason locking tree_log_mutex
13076426c7adSQu Wenruo 	 */
13086426c7adSQu Wenruo 	mutex_lock(&fs_info->tree_log_mutex);
13096426c7adSQu Wenruo 
13107e4443d9SNikolay Borisov 	ret = commit_fs_roots(trans);
13116426c7adSQu Wenruo 	if (ret)
13126426c7adSQu Wenruo 		goto out;
1313460fb20aSNikolay Borisov 	ret = btrfs_qgroup_account_extents(trans);
13146426c7adSQu Wenruo 	if (ret < 0)
13156426c7adSQu Wenruo 		goto out;
13166426c7adSQu Wenruo 
13176426c7adSQu Wenruo 	/* Now qgroup are all updated, we can inherit it to new qgroups */
1318a9377422SLu Fengqi 	ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
13196426c7adSQu Wenruo 				   inherit);
13206426c7adSQu Wenruo 	if (ret < 0)
13216426c7adSQu Wenruo 		goto out;
13226426c7adSQu Wenruo 
13236426c7adSQu Wenruo 	/*
13246426c7adSQu Wenruo 	 * Now we do a simplified commit transaction, which will:
13256426c7adSQu Wenruo 	 * 1) commit all subvolume and extent tree
13266426c7adSQu Wenruo 	 *    To ensure all subvolume and extent tree have a valid
13276426c7adSQu Wenruo 	 *    commit_root to accounting later insert_dir_item()
13286426c7adSQu Wenruo 	 * 2) write all btree blocks onto disk
13296426c7adSQu Wenruo 	 *    This is to make sure later btree modification will be cowed
13306426c7adSQu Wenruo 	 *    Or commit_root can be populated and cause wrong qgroup numbers
13316426c7adSQu Wenruo 	 * In this simplified commit, we don't really care about other trees
13326426c7adSQu Wenruo 	 * like chunk and root tree, as they won't affect qgroup.
13336426c7adSQu Wenruo 	 * And we don't write super to avoid half committed status.
13346426c7adSQu Wenruo 	 */
13359386d8bcSNikolay Borisov 	ret = commit_cowonly_roots(trans);
13366426c7adSQu Wenruo 	if (ret)
13376426c7adSQu Wenruo 		goto out;
133816916a88SNikolay Borisov 	switch_commit_roots(trans->transaction);
133970458a58SNikolay Borisov 	ret = btrfs_write_and_wait_transaction(trans);
13406426c7adSQu Wenruo 	if (ret)
1341f7af3934SDavid Sterba 		btrfs_handle_fs_error(fs_info, ret,
13426426c7adSQu Wenruo 			"Error while writing out transaction for qgroup");
13436426c7adSQu Wenruo 
13446426c7adSQu Wenruo out:
13456426c7adSQu Wenruo 	mutex_unlock(&fs_info->tree_log_mutex);
13466426c7adSQu Wenruo 
13476426c7adSQu Wenruo 	/*
13486426c7adSQu Wenruo 	 * Force parent root to be updated, as we recorded it before so its
13496426c7adSQu Wenruo 	 * last_trans == cur_transid.
13506426c7adSQu Wenruo 	 * Or it won't be committed again onto disk after later
13516426c7adSQu Wenruo 	 * insert_dir_item()
13526426c7adSQu Wenruo 	 */
13536426c7adSQu Wenruo 	if (!ret)
13546426c7adSQu Wenruo 		record_root_in_trans(trans, parent, 1);
13556426c7adSQu Wenruo 	return ret;
13566426c7adSQu Wenruo }
13576426c7adSQu Wenruo 
13586426c7adSQu Wenruo /*
1359d352ac68SChris Mason  * new snapshots need to be created at a very specific time in the
1360aec8030aSMiao Xie  * transaction commit.  This does the actual creation.
1361aec8030aSMiao Xie  *
1362aec8030aSMiao Xie  * Note:
1363aec8030aSMiao Xie  * If the error which may affect the commitment of the current transaction
1364aec8030aSMiao Xie  * happens, we should return the error number. If the error which just affect
1365aec8030aSMiao Xie  * the creation of the pending snapshots, just return 0.
1366d352ac68SChris Mason  */
136780b6794dSChris Mason static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
13683063d29fSChris Mason 				   struct btrfs_pending_snapshot *pending)
13693063d29fSChris Mason {
137008d50ca3SNikolay Borisov 
137108d50ca3SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
13723063d29fSChris Mason 	struct btrfs_key key;
137380b6794dSChris Mason 	struct btrfs_root_item *new_root_item;
13743063d29fSChris Mason 	struct btrfs_root *tree_root = fs_info->tree_root;
13753063d29fSChris Mason 	struct btrfs_root *root = pending->root;
13766bdb72deSSage Weil 	struct btrfs_root *parent_root;
137798c9942aSLiu Bo 	struct btrfs_block_rsv *rsv;
13786bdb72deSSage Weil 	struct inode *parent_inode;
137942874b3dSMiao Xie 	struct btrfs_path *path;
138042874b3dSMiao Xie 	struct btrfs_dir_item *dir_item;
1381a22285a6SYan, Zheng 	struct dentry *dentry;
13823063d29fSChris Mason 	struct extent_buffer *tmp;
1383925baeddSChris Mason 	struct extent_buffer *old;
138495582b00SDeepa Dinamani 	struct timespec64 cur_time;
1385aec8030aSMiao Xie 	int ret = 0;
1386d68fc57bSYan, Zheng 	u64 to_reserve = 0;
13876bdb72deSSage Weil 	u64 index = 0;
1388a22285a6SYan, Zheng 	u64 objectid;
1389b83cc969SLi Zefan 	u64 root_flags;
13908ea05e3aSAlexander Block 	uuid_le new_uuid;
13913063d29fSChris Mason 
13928546b570SDavid Sterba 	ASSERT(pending->path);
13938546b570SDavid Sterba 	path = pending->path;
139442874b3dSMiao Xie 
1395b0c0ea63SDavid Sterba 	ASSERT(pending->root_item);
1396b0c0ea63SDavid Sterba 	new_root_item = pending->root_item;
1397a22285a6SYan, Zheng 
1398aec8030aSMiao Xie 	pending->error = btrfs_find_free_objectid(tree_root, &objectid);
1399aec8030aSMiao Xie 	if (pending->error)
14006fa9700eSMiao Xie 		goto no_free_objectid;
14013063d29fSChris Mason 
1402d6726335SQu Wenruo 	/*
1403d6726335SQu Wenruo 	 * Make qgroup to skip current new snapshot's qgroupid, as it is
1404d6726335SQu Wenruo 	 * accounted by later btrfs_qgroup_inherit().
1405d6726335SQu Wenruo 	 */
1406d6726335SQu Wenruo 	btrfs_set_skip_qgroup(trans, objectid);
1407d6726335SQu Wenruo 
1408147d256eSZhaolei 	btrfs_reloc_pre_snapshot(pending, &to_reserve);
1409d68fc57bSYan, Zheng 
1410d68fc57bSYan, Zheng 	if (to_reserve > 0) {
1411aec8030aSMiao Xie 		pending->error = btrfs_block_rsv_add(root,
1412aec8030aSMiao Xie 						     &pending->block_rsv,
141308e007d2SMiao Xie 						     to_reserve,
141408e007d2SMiao Xie 						     BTRFS_RESERVE_NO_FLUSH);
1415aec8030aSMiao Xie 		if (pending->error)
1416d6726335SQu Wenruo 			goto clear_skip_qgroup;
1417d68fc57bSYan, Zheng 	}
1418d68fc57bSYan, Zheng 
14193063d29fSChris Mason 	key.objectid = objectid;
1420a22285a6SYan, Zheng 	key.offset = (u64)-1;
1421a22285a6SYan, Zheng 	key.type = BTRFS_ROOT_ITEM_KEY;
14223063d29fSChris Mason 
14236fa9700eSMiao Xie 	rsv = trans->block_rsv;
1424a22285a6SYan, Zheng 	trans->block_rsv = &pending->block_rsv;
14252382c5ccSLiu Bo 	trans->bytes_reserved = trans->block_rsv->reserved;
14260b246afaSJeff Mahoney 	trace_btrfs_space_reservation(fs_info, "transaction",
142788d3a5aaSJosef Bacik 				      trans->transid,
142888d3a5aaSJosef Bacik 				      trans->bytes_reserved, 1);
1429a22285a6SYan, Zheng 	dentry = pending->dentry;
1430e9662f70SMiao Xie 	parent_inode = pending->dir;
1431a22285a6SYan, Zheng 	parent_root = BTRFS_I(parent_inode)->root;
14326426c7adSQu Wenruo 	record_root_in_trans(trans, parent_root, 0);
1433a22285a6SYan, Zheng 
1434c2050a45SDeepa Dinamani 	cur_time = current_time(parent_inode);
143504b285f3SDeepa Dinamani 
14366bdb72deSSage Weil 	/*
14376bdb72deSSage Weil 	 * insert the directory item
14386bdb72deSSage Weil 	 */
1439877574e2SNikolay Borisov 	ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
144049b25e05SJeff Mahoney 	BUG_ON(ret); /* -ENOMEM */
144142874b3dSMiao Xie 
144242874b3dSMiao Xie 	/* check if there is a file/dir which has the same name. */
144342874b3dSMiao Xie 	dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
14444a0cc7caSNikolay Borisov 					 btrfs_ino(BTRFS_I(parent_inode)),
144542874b3dSMiao Xie 					 dentry->d_name.name,
144642874b3dSMiao Xie 					 dentry->d_name.len, 0);
144742874b3dSMiao Xie 	if (dir_item != NULL && !IS_ERR(dir_item)) {
1448fe66a05aSChris Mason 		pending->error = -EEXIST;
1449aec8030aSMiao Xie 		goto dir_item_existed;
145042874b3dSMiao Xie 	} else if (IS_ERR(dir_item)) {
145142874b3dSMiao Xie 		ret = PTR_ERR(dir_item);
145266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
14538732d44fSMiao Xie 		goto fail;
145479787eaaSJeff Mahoney 	}
145542874b3dSMiao Xie 	btrfs_release_path(path);
14566bdb72deSSage Weil 
1457e999376fSChris Mason 	/*
1458e999376fSChris Mason 	 * pull in the delayed directory update
1459e999376fSChris Mason 	 * and the delayed inode item
1460e999376fSChris Mason 	 * otherwise we corrupt the FS during
1461e999376fSChris Mason 	 * snapshot
1462e999376fSChris Mason 	 */
1463e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
14648732d44fSMiao Xie 	if (ret) {	/* Transaction aborted */
146566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
14668732d44fSMiao Xie 		goto fail;
14678732d44fSMiao Xie 	}
1468e999376fSChris Mason 
14696426c7adSQu Wenruo 	record_root_in_trans(trans, root, 0);
14706bdb72deSSage Weil 	btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
14716bdb72deSSage Weil 	memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
147208fe4db1SLi Zefan 	btrfs_check_and_init_root_item(new_root_item);
14736bdb72deSSage Weil 
1474b83cc969SLi Zefan 	root_flags = btrfs_root_flags(new_root_item);
1475b83cc969SLi Zefan 	if (pending->readonly)
1476b83cc969SLi Zefan 		root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1477b83cc969SLi Zefan 	else
1478b83cc969SLi Zefan 		root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1479b83cc969SLi Zefan 	btrfs_set_root_flags(new_root_item, root_flags);
1480b83cc969SLi Zefan 
14818ea05e3aSAlexander Block 	btrfs_set_root_generation_v2(new_root_item,
14828ea05e3aSAlexander Block 			trans->transid);
14838ea05e3aSAlexander Block 	uuid_le_gen(&new_uuid);
14848ea05e3aSAlexander Block 	memcpy(new_root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
14858ea05e3aSAlexander Block 	memcpy(new_root_item->parent_uuid, root->root_item.uuid,
14868ea05e3aSAlexander Block 			BTRFS_UUID_SIZE);
148770023da2SStefan Behrens 	if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
148870023da2SStefan Behrens 		memset(new_root_item->received_uuid, 0,
148970023da2SStefan Behrens 		       sizeof(new_root_item->received_uuid));
14908ea05e3aSAlexander Block 		memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
14918ea05e3aSAlexander Block 		memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
14928ea05e3aSAlexander Block 		btrfs_set_root_stransid(new_root_item, 0);
14938ea05e3aSAlexander Block 		btrfs_set_root_rtransid(new_root_item, 0);
149470023da2SStefan Behrens 	}
14953cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
14963cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
149770023da2SStefan Behrens 	btrfs_set_root_otransid(new_root_item, trans->transid);
14988ea05e3aSAlexander Block 
1499925baeddSChris Mason 	old = btrfs_lock_root_node(root);
150049b25e05SJeff Mahoney 	ret = btrfs_cow_block(trans, root, old, NULL, 0, &old);
150179787eaaSJeff Mahoney 	if (ret) {
150279787eaaSJeff Mahoney 		btrfs_tree_unlock(old);
150379787eaaSJeff Mahoney 		free_extent_buffer(old);
150466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15058732d44fSMiao Xie 		goto fail;
150679787eaaSJeff Mahoney 	}
150749b25e05SJeff Mahoney 
15088bead258SDavid Sterba 	btrfs_set_lock_blocking_write(old);
15093063d29fSChris Mason 
151049b25e05SJeff Mahoney 	ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
151179787eaaSJeff Mahoney 	/* clean up in any case */
1512925baeddSChris Mason 	btrfs_tree_unlock(old);
1513925baeddSChris Mason 	free_extent_buffer(old);
15148732d44fSMiao Xie 	if (ret) {
151566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15168732d44fSMiao Xie 		goto fail;
15178732d44fSMiao Xie 	}
1518f1ebcc74SLiu Bo 	/* see comments in should_cow_block() */
151927cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1520f1ebcc74SLiu Bo 	smp_wmb();
1521f1ebcc74SLiu Bo 
15225d4f98a2SYan Zheng 	btrfs_set_root_node(new_root_item, tmp);
1523a22285a6SYan, Zheng 	/* record when the snapshot was created in key.offset */
1524a22285a6SYan, Zheng 	key.offset = trans->transid;
1525a22285a6SYan, Zheng 	ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1526925baeddSChris Mason 	btrfs_tree_unlock(tmp);
15273063d29fSChris Mason 	free_extent_buffer(tmp);
15288732d44fSMiao Xie 	if (ret) {
152966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15308732d44fSMiao Xie 		goto fail;
15318732d44fSMiao Xie 	}
15320660b5afSChris Mason 
1533a22285a6SYan, Zheng 	/*
1534a22285a6SYan, Zheng 	 * insert root back/forward references
1535a22285a6SYan, Zheng 	 */
15366025c19fSLu Fengqi 	ret = btrfs_add_root_ref(trans, objectid,
1537a22285a6SYan, Zheng 				 parent_root->root_key.objectid,
15384a0cc7caSNikolay Borisov 				 btrfs_ino(BTRFS_I(parent_inode)), index,
1539a22285a6SYan, Zheng 				 dentry->d_name.name, dentry->d_name.len);
15408732d44fSMiao Xie 	if (ret) {
154166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15428732d44fSMiao Xie 		goto fail;
15438732d44fSMiao Xie 	}
1544a22285a6SYan, Zheng 
1545a22285a6SYan, Zheng 	key.offset = (u64)-1;
15460b246afaSJeff Mahoney 	pending->snap = btrfs_read_fs_root_no_name(fs_info, &key);
154779787eaaSJeff Mahoney 	if (IS_ERR(pending->snap)) {
154879787eaaSJeff Mahoney 		ret = PTR_ERR(pending->snap);
154966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15508732d44fSMiao Xie 		goto fail;
155179787eaaSJeff Mahoney 	}
1552d68fc57bSYan, Zheng 
155349b25e05SJeff Mahoney 	ret = btrfs_reloc_post_snapshot(trans, pending);
15548732d44fSMiao Xie 	if (ret) {
155566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15568732d44fSMiao Xie 		goto fail;
15578732d44fSMiao Xie 	}
1558361048f5SMiao Xie 
1559c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
15608732d44fSMiao Xie 	if (ret) {
156166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15628732d44fSMiao Xie 		goto fail;
15638732d44fSMiao Xie 	}
156442874b3dSMiao Xie 
15656426c7adSQu Wenruo 	/*
15666426c7adSQu Wenruo 	 * Do special qgroup accounting for snapshot, as we do some qgroup
15676426c7adSQu Wenruo 	 * snapshot hack to do fast snapshot.
15686426c7adSQu Wenruo 	 * To co-operate with that hack, we do hack again.
15696426c7adSQu Wenruo 	 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
15706426c7adSQu Wenruo 	 */
15716426c7adSQu Wenruo 	ret = qgroup_account_snapshot(trans, root, parent_root,
15726426c7adSQu Wenruo 				      pending->inherit, objectid);
15736426c7adSQu Wenruo 	if (ret < 0)
15746426c7adSQu Wenruo 		goto fail;
15756426c7adSQu Wenruo 
1576684572dfSLu Fengqi 	ret = btrfs_insert_dir_item(trans, dentry->d_name.name,
1577684572dfSLu Fengqi 				    dentry->d_name.len, BTRFS_I(parent_inode),
1578684572dfSLu Fengqi 				    &key, BTRFS_FT_DIR, index);
157942874b3dSMiao Xie 	/* We have check then name at the beginning, so it is impossible. */
15809c52057cSChris Mason 	BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
15818732d44fSMiao Xie 	if (ret) {
158266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15838732d44fSMiao Xie 		goto fail;
15848732d44fSMiao Xie 	}
158542874b3dSMiao Xie 
15866ef06d27SNikolay Borisov 	btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
158742874b3dSMiao Xie 					 dentry->d_name.len * 2);
158804b285f3SDeepa Dinamani 	parent_inode->i_mtime = parent_inode->i_ctime =
1589c2050a45SDeepa Dinamani 		current_time(parent_inode);
1590be6aef60SJosef Bacik 	ret = btrfs_update_inode_fallback(trans, parent_root, parent_inode);
1591dd5f9615SStefan Behrens 	if (ret) {
159266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1593dd5f9615SStefan Behrens 		goto fail;
1594dd5f9615SStefan Behrens 	}
1595cdb345a8SLu Fengqi 	ret = btrfs_uuid_tree_add(trans, new_uuid.b, BTRFS_UUID_KEY_SUBVOL,
1596cdb345a8SLu Fengqi 				  objectid);
1597dd5f9615SStefan Behrens 	if (ret) {
159866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1599dd5f9615SStefan Behrens 		goto fail;
1600dd5f9615SStefan Behrens 	}
1601dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1602cdb345a8SLu Fengqi 		ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1603dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1604dd5f9615SStefan Behrens 					  objectid);
1605dd5f9615SStefan Behrens 		if (ret && ret != -EEXIST) {
160666642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
1607dd5f9615SStefan Behrens 			goto fail;
1608dd5f9615SStefan Behrens 		}
1609dd5f9615SStefan Behrens 	}
1610d6726335SQu Wenruo 
1611c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1612d6726335SQu Wenruo 	if (ret) {
161366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1614d6726335SQu Wenruo 		goto fail;
1615d6726335SQu Wenruo 	}
1616d6726335SQu Wenruo 
16173063d29fSChris Mason fail:
1618aec8030aSMiao Xie 	pending->error = ret;
1619aec8030aSMiao Xie dir_item_existed:
162098c9942aSLiu Bo 	trans->block_rsv = rsv;
16212382c5ccSLiu Bo 	trans->bytes_reserved = 0;
1622d6726335SQu Wenruo clear_skip_qgroup:
1623d6726335SQu Wenruo 	btrfs_clear_skip_qgroup(trans);
16246fa9700eSMiao Xie no_free_objectid:
16256fa9700eSMiao Xie 	kfree(new_root_item);
1626b0c0ea63SDavid Sterba 	pending->root_item = NULL;
162742874b3dSMiao Xie 	btrfs_free_path(path);
16288546b570SDavid Sterba 	pending->path = NULL;
16298546b570SDavid Sterba 
163049b25e05SJeff Mahoney 	return ret;
16313063d29fSChris Mason }
16323063d29fSChris Mason 
1633d352ac68SChris Mason /*
1634d352ac68SChris Mason  * create all the snapshots we've scheduled for creation
1635d352ac68SChris Mason  */
163608d50ca3SNikolay Borisov static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
16373063d29fSChris Mason {
1638aec8030aSMiao Xie 	struct btrfs_pending_snapshot *pending, *next;
16393063d29fSChris Mason 	struct list_head *head = &trans->transaction->pending_snapshots;
1640aec8030aSMiao Xie 	int ret = 0;
16413de4586cSChris Mason 
1642aec8030aSMiao Xie 	list_for_each_entry_safe(pending, next, head, list) {
1643aec8030aSMiao Xie 		list_del(&pending->list);
164408d50ca3SNikolay Borisov 		ret = create_pending_snapshot(trans, pending);
1645aec8030aSMiao Xie 		if (ret)
1646aec8030aSMiao Xie 			break;
1647aec8030aSMiao Xie 	}
1648aec8030aSMiao Xie 	return ret;
16493de4586cSChris Mason }
16503de4586cSChris Mason 
16512ff7e61eSJeff Mahoney static void update_super_roots(struct btrfs_fs_info *fs_info)
16525d4f98a2SYan Zheng {
16535d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
16545d4f98a2SYan Zheng 	struct btrfs_super_block *super;
16555d4f98a2SYan Zheng 
16560b246afaSJeff Mahoney 	super = fs_info->super_copy;
16575d4f98a2SYan Zheng 
16580b246afaSJeff Mahoney 	root_item = &fs_info->chunk_root->root_item;
1659093e037cSDavid Sterba 	super->chunk_root = root_item->bytenr;
1660093e037cSDavid Sterba 	super->chunk_root_generation = root_item->generation;
1661093e037cSDavid Sterba 	super->chunk_root_level = root_item->level;
16625d4f98a2SYan Zheng 
16630b246afaSJeff Mahoney 	root_item = &fs_info->tree_root->root_item;
1664093e037cSDavid Sterba 	super->root = root_item->bytenr;
1665093e037cSDavid Sterba 	super->generation = root_item->generation;
1666093e037cSDavid Sterba 	super->root_level = root_item->level;
16670b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, SPACE_CACHE))
1668093e037cSDavid Sterba 		super->cache_generation = root_item->generation;
16690b246afaSJeff Mahoney 	if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1670093e037cSDavid Sterba 		super->uuid_tree_generation = root_item->generation;
16715d4f98a2SYan Zheng }
16725d4f98a2SYan Zheng 
1673f36f3042SChris Mason int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1674f36f3042SChris Mason {
16754a9d8bdeSMiao Xie 	struct btrfs_transaction *trans;
1676f36f3042SChris Mason 	int ret = 0;
16774a9d8bdeSMiao Xie 
1678a4abeea4SJosef Bacik 	spin_lock(&info->trans_lock);
16794a9d8bdeSMiao Xie 	trans = info->running_transaction;
16804a9d8bdeSMiao Xie 	if (trans)
16814a9d8bdeSMiao Xie 		ret = (trans->state >= TRANS_STATE_COMMIT_START);
1682a4abeea4SJosef Bacik 	spin_unlock(&info->trans_lock);
1683f36f3042SChris Mason 	return ret;
1684f36f3042SChris Mason }
1685f36f3042SChris Mason 
16868929ecfaSYan, Zheng int btrfs_transaction_blocked(struct btrfs_fs_info *info)
16878929ecfaSYan, Zheng {
16884a9d8bdeSMiao Xie 	struct btrfs_transaction *trans;
16898929ecfaSYan, Zheng 	int ret = 0;
16904a9d8bdeSMiao Xie 
1691a4abeea4SJosef Bacik 	spin_lock(&info->trans_lock);
16924a9d8bdeSMiao Xie 	trans = info->running_transaction;
16934a9d8bdeSMiao Xie 	if (trans)
16944a9d8bdeSMiao Xie 		ret = is_transaction_blocked(trans);
1695a4abeea4SJosef Bacik 	spin_unlock(&info->trans_lock);
16968929ecfaSYan, Zheng 	return ret;
16978929ecfaSYan, Zheng }
16988929ecfaSYan, Zheng 
1699bb9c12c9SSage Weil /*
1700bb9c12c9SSage Weil  * wait for the current transaction commit to start and block subsequent
1701bb9c12c9SSage Weil  * transaction joins
1702bb9c12c9SSage Weil  */
17032ff7e61eSJeff Mahoney static void wait_current_trans_commit_start(struct btrfs_fs_info *fs_info,
1704bb9c12c9SSage Weil 					    struct btrfs_transaction *trans)
1705bb9c12c9SSage Weil {
17062ff7e61eSJeff Mahoney 	wait_event(fs_info->transaction_blocked_wait,
17072ff7e61eSJeff Mahoney 		   trans->state >= TRANS_STATE_COMMIT_START || trans->aborted);
1708bb9c12c9SSage Weil }
1709bb9c12c9SSage Weil 
1710bb9c12c9SSage Weil /*
1711bb9c12c9SSage Weil  * wait for the current transaction to start and then become unblocked.
1712bb9c12c9SSage Weil  * caller holds ref.
1713bb9c12c9SSage Weil  */
17142ff7e61eSJeff Mahoney static void wait_current_trans_commit_start_and_unblock(
17152ff7e61eSJeff Mahoney 					struct btrfs_fs_info *fs_info,
1716bb9c12c9SSage Weil 					struct btrfs_transaction *trans)
1717bb9c12c9SSage Weil {
17182ff7e61eSJeff Mahoney 	wait_event(fs_info->transaction_wait,
17192ff7e61eSJeff Mahoney 		   trans->state >= TRANS_STATE_UNBLOCKED || trans->aborted);
1720bb9c12c9SSage Weil }
1721bb9c12c9SSage Weil 
1722bb9c12c9SSage Weil /*
1723bb9c12c9SSage Weil  * commit transactions asynchronously. once btrfs_commit_transaction_async
1724bb9c12c9SSage Weil  * returns, any subsequent transaction will not be allowed to join.
1725bb9c12c9SSage Weil  */
1726bb9c12c9SSage Weil struct btrfs_async_commit {
1727bb9c12c9SSage Weil 	struct btrfs_trans_handle *newtrans;
17287892b5afSMiao Xie 	struct work_struct work;
1729bb9c12c9SSage Weil };
1730bb9c12c9SSage Weil 
1731bb9c12c9SSage Weil static void do_async_commit(struct work_struct *work)
1732bb9c12c9SSage Weil {
1733bb9c12c9SSage Weil 	struct btrfs_async_commit *ac =
17347892b5afSMiao Xie 		container_of(work, struct btrfs_async_commit, work);
1735bb9c12c9SSage Weil 
17366fc4e354SSage Weil 	/*
17376fc4e354SSage Weil 	 * We've got freeze protection passed with the transaction.
17386fc4e354SSage Weil 	 * Tell lockdep about it.
17396fc4e354SSage Weil 	 */
1740b1a06a4bSLiu Bo 	if (ac->newtrans->type & __TRANS_FREEZABLE)
17413a45bb20SJeff Mahoney 		__sb_writers_acquired(ac->newtrans->fs_info->sb, SB_FREEZE_FS);
17426fc4e354SSage Weil 
1743e209db7aSSage Weil 	current->journal_info = ac->newtrans;
1744e209db7aSSage Weil 
17453a45bb20SJeff Mahoney 	btrfs_commit_transaction(ac->newtrans);
1746bb9c12c9SSage Weil 	kfree(ac);
1747bb9c12c9SSage Weil }
1748bb9c12c9SSage Weil 
1749bb9c12c9SSage Weil int btrfs_commit_transaction_async(struct btrfs_trans_handle *trans,
1750bb9c12c9SSage Weil 				   int wait_for_unblock)
1751bb9c12c9SSage Weil {
17523a45bb20SJeff Mahoney 	struct btrfs_fs_info *fs_info = trans->fs_info;
1753bb9c12c9SSage Weil 	struct btrfs_async_commit *ac;
1754bb9c12c9SSage Weil 	struct btrfs_transaction *cur_trans;
1755bb9c12c9SSage Weil 
1756bb9c12c9SSage Weil 	ac = kmalloc(sizeof(*ac), GFP_NOFS);
1757db5b493aSTsutomu Itoh 	if (!ac)
1758db5b493aSTsutomu Itoh 		return -ENOMEM;
1759bb9c12c9SSage Weil 
17607892b5afSMiao Xie 	INIT_WORK(&ac->work, do_async_commit);
17613a45bb20SJeff Mahoney 	ac->newtrans = btrfs_join_transaction(trans->root);
17623612b495STsutomu Itoh 	if (IS_ERR(ac->newtrans)) {
17633612b495STsutomu Itoh 		int err = PTR_ERR(ac->newtrans);
17643612b495STsutomu Itoh 		kfree(ac);
17653612b495STsutomu Itoh 		return err;
17663612b495STsutomu Itoh 	}
1767bb9c12c9SSage Weil 
1768bb9c12c9SSage Weil 	/* take transaction reference */
1769bb9c12c9SSage Weil 	cur_trans = trans->transaction;
17709b64f57dSElena Reshetova 	refcount_inc(&cur_trans->use_count);
1771bb9c12c9SSage Weil 
17723a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
17736fc4e354SSage Weil 
17746fc4e354SSage Weil 	/*
17756fc4e354SSage Weil 	 * Tell lockdep we've released the freeze rwsem, since the
17766fc4e354SSage Weil 	 * async commit thread will be the one to unlock it.
17776fc4e354SSage Weil 	 */
1778b1a06a4bSLiu Bo 	if (ac->newtrans->type & __TRANS_FREEZABLE)
17790b246afaSJeff Mahoney 		__sb_writers_release(fs_info->sb, SB_FREEZE_FS);
17806fc4e354SSage Weil 
17817892b5afSMiao Xie 	schedule_work(&ac->work);
1782bb9c12c9SSage Weil 
1783bb9c12c9SSage Weil 	/* wait for transaction to start and unblock */
1784bb9c12c9SSage Weil 	if (wait_for_unblock)
17852ff7e61eSJeff Mahoney 		wait_current_trans_commit_start_and_unblock(fs_info, cur_trans);
1786bb9c12c9SSage Weil 	else
17872ff7e61eSJeff Mahoney 		wait_current_trans_commit_start(fs_info, cur_trans);
1788bb9c12c9SSage Weil 
178938e88054SSage Weil 	if (current->journal_info == trans)
179038e88054SSage Weil 		current->journal_info = NULL;
179138e88054SSage Weil 
1792724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
1793bb9c12c9SSage Weil 	return 0;
1794bb9c12c9SSage Weil }
1795bb9c12c9SSage Weil 
179649b25e05SJeff Mahoney 
179797cb39bbSNikolay Borisov static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
179849b25e05SJeff Mahoney {
179997cb39bbSNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
180049b25e05SJeff Mahoney 	struct btrfs_transaction *cur_trans = trans->transaction;
180149b25e05SJeff Mahoney 
1802b50fff81SDavid Sterba 	WARN_ON(refcount_read(&trans->use_count) > 1);
180349b25e05SJeff Mahoney 
180466642832SJeff Mahoney 	btrfs_abort_transaction(trans, err);
18057b8b92afSJosef Bacik 
18060b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
180766b6135bSLiu Bo 
180825d8c284SMiao Xie 	/*
180925d8c284SMiao Xie 	 * If the transaction is removed from the list, it means this
181025d8c284SMiao Xie 	 * transaction has been committed successfully, so it is impossible
181125d8c284SMiao Xie 	 * to call the cleanup function.
181225d8c284SMiao Xie 	 */
181325d8c284SMiao Xie 	BUG_ON(list_empty(&cur_trans->list));
181466b6135bSLiu Bo 
181549b25e05SJeff Mahoney 	list_del_init(&cur_trans->list);
18160b246afaSJeff Mahoney 	if (cur_trans == fs_info->running_transaction) {
18174a9d8bdeSMiao Xie 		cur_trans->state = TRANS_STATE_COMMIT_DOING;
18180b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
1819f094ac32SLiu Bo 		wait_event(cur_trans->writer_wait,
1820f094ac32SLiu Bo 			   atomic_read(&cur_trans->num_writers) == 1);
1821f094ac32SLiu Bo 
18220b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
1823d7096fc3SJosef Bacik 	}
18240b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
182549b25e05SJeff Mahoney 
18262ff7e61eSJeff Mahoney 	btrfs_cleanup_one_transaction(trans->transaction, fs_info);
182749b25e05SJeff Mahoney 
18280b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
18290b246afaSJeff Mahoney 	if (cur_trans == fs_info->running_transaction)
18300b246afaSJeff Mahoney 		fs_info->running_transaction = NULL;
18310b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
18324a9d8bdeSMiao Xie 
1833e0228285SJosef Bacik 	if (trans->type & __TRANS_FREEZABLE)
18340b246afaSJeff Mahoney 		sb_end_intwrite(fs_info->sb);
1835724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
1836724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
183749b25e05SJeff Mahoney 
183897cb39bbSNikolay Borisov 	trace_btrfs_transaction_commit(trans->root);
183949b25e05SJeff Mahoney 
184049b25e05SJeff Mahoney 	if (current->journal_info == trans)
184149b25e05SJeff Mahoney 		current->journal_info = NULL;
18420b246afaSJeff Mahoney 	btrfs_scrub_cancel(fs_info);
184349b25e05SJeff Mahoney 
184449b25e05SJeff Mahoney 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
184549b25e05SJeff Mahoney }
184649b25e05SJeff Mahoney 
1847c7cc64a9SDavid Sterba /*
1848c7cc64a9SDavid Sterba  * Release reserved delayed ref space of all pending block groups of the
1849c7cc64a9SDavid Sterba  * transaction and remove them from the list
1850c7cc64a9SDavid Sterba  */
1851c7cc64a9SDavid Sterba static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
1852c7cc64a9SDavid Sterba {
1853c7cc64a9SDavid Sterba        struct btrfs_fs_info *fs_info = trans->fs_info;
1854c7cc64a9SDavid Sterba        struct btrfs_block_group_cache *block_group, *tmp;
1855c7cc64a9SDavid Sterba 
1856c7cc64a9SDavid Sterba        list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
1857c7cc64a9SDavid Sterba                btrfs_delayed_refs_rsv_release(fs_info, 1);
1858c7cc64a9SDavid Sterba                list_del_init(&block_group->bg_list);
1859c7cc64a9SDavid Sterba        }
1860c7cc64a9SDavid Sterba }
1861c7cc64a9SDavid Sterba 
1862609e804dSFilipe Manana static inline int btrfs_start_delalloc_flush(struct btrfs_trans_handle *trans)
186382436617SMiao Xie {
1864609e804dSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
1865609e804dSFilipe Manana 
1866ce8ea7ccSJosef Bacik 	/*
1867ce8ea7ccSJosef Bacik 	 * We use writeback_inodes_sb here because if we used
1868ce8ea7ccSJosef Bacik 	 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
1869ce8ea7ccSJosef Bacik 	 * Currently are holding the fs freeze lock, if we do an async flush
1870ce8ea7ccSJosef Bacik 	 * we'll do btrfs_join_transaction() and deadlock because we need to
1871ce8ea7ccSJosef Bacik 	 * wait for the fs freeze lock.  Using the direct flushing we benefit
1872ce8ea7ccSJosef Bacik 	 * from already being in a transaction and our join_transaction doesn't
1873ce8ea7ccSJosef Bacik 	 * have to re-take the fs freeze lock.
1874ce8ea7ccSJosef Bacik 	 */
1875609e804dSFilipe Manana 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT)) {
1876ce8ea7ccSJosef Bacik 		writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
1877609e804dSFilipe Manana 	} else {
1878609e804dSFilipe Manana 		struct btrfs_pending_snapshot *pending;
1879609e804dSFilipe Manana 		struct list_head *head = &trans->transaction->pending_snapshots;
1880609e804dSFilipe Manana 
1881609e804dSFilipe Manana 		/*
1882609e804dSFilipe Manana 		 * Flush dellaloc for any root that is going to be snapshotted.
1883609e804dSFilipe Manana 		 * This is done to avoid a corrupted version of files, in the
1884609e804dSFilipe Manana 		 * snapshots, that had both buffered and direct IO writes (even
1885609e804dSFilipe Manana 		 * if they were done sequentially) due to an unordered update of
1886609e804dSFilipe Manana 		 * the inode's size on disk.
1887609e804dSFilipe Manana 		 */
1888609e804dSFilipe Manana 		list_for_each_entry(pending, head, list) {
1889609e804dSFilipe Manana 			int ret;
1890609e804dSFilipe Manana 
1891609e804dSFilipe Manana 			ret = btrfs_start_delalloc_snapshot(pending->root);
1892609e804dSFilipe Manana 			if (ret)
1893609e804dSFilipe Manana 				return ret;
1894609e804dSFilipe Manana 		}
1895609e804dSFilipe Manana 	}
189682436617SMiao Xie 	return 0;
189782436617SMiao Xie }
189882436617SMiao Xie 
1899609e804dSFilipe Manana static inline void btrfs_wait_delalloc_flush(struct btrfs_trans_handle *trans)
190082436617SMiao Xie {
1901609e804dSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
1902609e804dSFilipe Manana 
1903609e804dSFilipe Manana 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT)) {
19046374e57aSChris Mason 		btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
1905609e804dSFilipe Manana 	} else {
1906609e804dSFilipe Manana 		struct btrfs_pending_snapshot *pending;
1907609e804dSFilipe Manana 		struct list_head *head = &trans->transaction->pending_snapshots;
1908609e804dSFilipe Manana 
1909609e804dSFilipe Manana 		/*
1910609e804dSFilipe Manana 		 * Wait for any dellaloc that we started previously for the roots
1911609e804dSFilipe Manana 		 * that are going to be snapshotted. This is to avoid a corrupted
1912609e804dSFilipe Manana 		 * version of files in the snapshots that had both buffered and
1913609e804dSFilipe Manana 		 * direct IO writes (even if they were done sequentially).
1914609e804dSFilipe Manana 		 */
1915609e804dSFilipe Manana 		list_for_each_entry(pending, head, list)
1916609e804dSFilipe Manana 			btrfs_wait_ordered_extents(pending->root,
1917609e804dSFilipe Manana 						   U64_MAX, 0, U64_MAX);
1918609e804dSFilipe Manana 	}
191982436617SMiao Xie }
192082436617SMiao Xie 
19213a45bb20SJeff Mahoney int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
192279154b1bSChris Mason {
19233a45bb20SJeff Mahoney 	struct btrfs_fs_info *fs_info = trans->fs_info;
192449b25e05SJeff Mahoney 	struct btrfs_transaction *cur_trans = trans->transaction;
19258fd17795SChris Mason 	struct btrfs_transaction *prev_trans = NULL;
192625287e0aSMiao Xie 	int ret;
192779154b1bSChris Mason 
19288d25a086SMiao Xie 	/* Stop the commit early if ->aborted is set */
192920c7bcecSSeraphime Kirkovski 	if (unlikely(READ_ONCE(cur_trans->aborted))) {
193025287e0aSMiao Xie 		ret = cur_trans->aborted;
19313a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
1932e4a2bcacSJosef Bacik 		return ret;
193325287e0aSMiao Xie 	}
193449b25e05SJeff Mahoney 
1935f45c752bSJosef Bacik 	btrfs_trans_release_metadata(trans);
1936f45c752bSJosef Bacik 	trans->block_rsv = NULL;
1937f45c752bSJosef Bacik 
193856bec294SChris Mason 	/* make a pass through all the delayed refs we have so far
193956bec294SChris Mason 	 * any runnings procs may add more while we are here
194056bec294SChris Mason 	 */
1941c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, 0);
1942e4a2bcacSJosef Bacik 	if (ret) {
19433a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
1944e4a2bcacSJosef Bacik 		return ret;
1945e4a2bcacSJosef Bacik 	}
194656bec294SChris Mason 
1947b7ec40d7SChris Mason 	cur_trans = trans->transaction;
194849b25e05SJeff Mahoney 
194956bec294SChris Mason 	/*
195056bec294SChris Mason 	 * set the flushing flag so procs in this transaction have to
195156bec294SChris Mason 	 * start sending their work down.
195256bec294SChris Mason 	 */
1953b7ec40d7SChris Mason 	cur_trans->delayed_refs.flushing = 1;
19541be41b78SJosef Bacik 	smp_wmb();
195556bec294SChris Mason 
19566c686b35SNikolay Borisov 	btrfs_create_pending_block_groups(trans);
1957ea658badSJosef Bacik 
1958c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, 0);
1959e4a2bcacSJosef Bacik 	if (ret) {
19603a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
1961e4a2bcacSJosef Bacik 		return ret;
1962e4a2bcacSJosef Bacik 	}
196356bec294SChris Mason 
19643204d33cSJosef Bacik 	if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
19651bbc621eSChris Mason 		int run_it = 0;
19661bbc621eSChris Mason 
19671bbc621eSChris Mason 		/* this mutex is also taken before trying to set
19681bbc621eSChris Mason 		 * block groups readonly.  We need to make sure
19691bbc621eSChris Mason 		 * that nobody has set a block group readonly
19701bbc621eSChris Mason 		 * after a extents from that block group have been
19711bbc621eSChris Mason 		 * allocated for cache files.  btrfs_set_block_group_ro
19721bbc621eSChris Mason 		 * will wait for the transaction to commit if it
19733204d33cSJosef Bacik 		 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
19741bbc621eSChris Mason 		 *
19753204d33cSJosef Bacik 		 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
19763204d33cSJosef Bacik 		 * only one process starts all the block group IO.  It wouldn't
19771bbc621eSChris Mason 		 * hurt to have more than one go through, but there's no
19781bbc621eSChris Mason 		 * real advantage to it either.
19791bbc621eSChris Mason 		 */
19800b246afaSJeff Mahoney 		mutex_lock(&fs_info->ro_block_group_mutex);
19813204d33cSJosef Bacik 		if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
19823204d33cSJosef Bacik 				      &cur_trans->flags))
19831bbc621eSChris Mason 			run_it = 1;
19840b246afaSJeff Mahoney 		mutex_unlock(&fs_info->ro_block_group_mutex);
19851bbc621eSChris Mason 
1986f9cacae3SNikolay Borisov 		if (run_it) {
198721217054SNikolay Borisov 			ret = btrfs_start_dirty_block_groups(trans);
19881bbc621eSChris Mason 			if (ret) {
19893a45bb20SJeff Mahoney 				btrfs_end_transaction(trans);
19901bbc621eSChris Mason 				return ret;
19911bbc621eSChris Mason 			}
1992f9cacae3SNikolay Borisov 		}
1993f9cacae3SNikolay Borisov 	}
19941bbc621eSChris Mason 
19950b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
19964a9d8bdeSMiao Xie 	if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
19970b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
19989b64f57dSElena Reshetova 		refcount_inc(&cur_trans->use_count);
19993a45bb20SJeff Mahoney 		ret = btrfs_end_transaction(trans);
2000ccd467d6SChris Mason 
20012ff7e61eSJeff Mahoney 		wait_for_commit(cur_trans);
200215ee9bc7SJosef Bacik 
2003b4924a0fSLiu Bo 		if (unlikely(cur_trans->aborted))
2004b4924a0fSLiu Bo 			ret = cur_trans->aborted;
2005b4924a0fSLiu Bo 
2006724e2315SJosef Bacik 		btrfs_put_transaction(cur_trans);
200715ee9bc7SJosef Bacik 
200849b25e05SJeff Mahoney 		return ret;
200979154b1bSChris Mason 	}
20104313b399SChris Mason 
20114a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
20120b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
2013bb9c12c9SSage Weil 
20140b246afaSJeff Mahoney 	if (cur_trans->list.prev != &fs_info->trans_list) {
2015ccd467d6SChris Mason 		prev_trans = list_entry(cur_trans->list.prev,
2016ccd467d6SChris Mason 					struct btrfs_transaction, list);
20174a9d8bdeSMiao Xie 		if (prev_trans->state != TRANS_STATE_COMPLETED) {
20189b64f57dSElena Reshetova 			refcount_inc(&prev_trans->use_count);
20190b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
2020ccd467d6SChris Mason 
20212ff7e61eSJeff Mahoney 			wait_for_commit(prev_trans);
20221f9b8c8fSFilipe Manana 			ret = prev_trans->aborted;
2023ccd467d6SChris Mason 
2024724e2315SJosef Bacik 			btrfs_put_transaction(prev_trans);
20251f9b8c8fSFilipe Manana 			if (ret)
20261f9b8c8fSFilipe Manana 				goto cleanup_transaction;
2027a4abeea4SJosef Bacik 		} else {
20280b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
2029ccd467d6SChris Mason 		}
2030a4abeea4SJosef Bacik 	} else {
20310b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
2032ccd467d6SChris Mason 	}
203315ee9bc7SJosef Bacik 
20340860adfdSMiao Xie 	extwriter_counter_dec(cur_trans, trans->type);
20350860adfdSMiao Xie 
2036609e804dSFilipe Manana 	ret = btrfs_start_delalloc_flush(trans);
203782436617SMiao Xie 	if (ret)
203882436617SMiao Xie 		goto cleanup_transaction;
203982436617SMiao Xie 
2040e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
204149b25e05SJeff Mahoney 	if (ret)
204249b25e05SJeff Mahoney 		goto cleanup_transaction;
204316cdcec7SMiao Xie 
2044581227d0SMiao Xie 	wait_event(cur_trans->writer_wait,
2045581227d0SMiao Xie 		   extwriter_counter_read(cur_trans) == 0);
2046ed3b3d31SChris Mason 
2047581227d0SMiao Xie 	/* some pending stuffs might be added after the previous flush. */
2048e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
2049ca469637SMiao Xie 	if (ret)
2050ca469637SMiao Xie 		goto cleanup_transaction;
2051ca469637SMiao Xie 
2052609e804dSFilipe Manana 	btrfs_wait_delalloc_flush(trans);
2053cb7ab021SWang Shilong 
20542ff7e61eSJeff Mahoney 	btrfs_scrub_pause(fs_info);
2055ed0ca140SJosef Bacik 	/*
2056ed0ca140SJosef Bacik 	 * Ok now we need to make sure to block out any other joins while we
2057ed0ca140SJosef Bacik 	 * commit the transaction.  We could have started a join before setting
20584a9d8bdeSMiao Xie 	 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2059ed0ca140SJosef Bacik 	 */
20600b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
20614a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_DOING;
20620b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2063ed0ca140SJosef Bacik 	wait_event(cur_trans->writer_wait,
2064ed0ca140SJosef Bacik 		   atomic_read(&cur_trans->num_writers) == 1);
206515ee9bc7SJosef Bacik 
20662cba30f1SMiao Xie 	/* ->aborted might be set after the previous check, so check it */
206720c7bcecSSeraphime Kirkovski 	if (unlikely(READ_ONCE(cur_trans->aborted))) {
20682cba30f1SMiao Xie 		ret = cur_trans->aborted;
20696cf7f77eSWang Shilong 		goto scrub_continue;
20702cba30f1SMiao Xie 	}
20717585717fSChris Mason 	/*
20727585717fSChris Mason 	 * the reloc mutex makes sure that we stop
20737585717fSChris Mason 	 * the balancing code from coming in and moving
20747585717fSChris Mason 	 * extents around in the middle of the commit
20757585717fSChris Mason 	 */
20760b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
20777585717fSChris Mason 
207842874b3dSMiao Xie 	/*
207942874b3dSMiao Xie 	 * We needn't worry about the delayed items because we will
208042874b3dSMiao Xie 	 * deal with them in create_pending_snapshot(), which is the
208142874b3dSMiao Xie 	 * core function of the snapshot creation.
208242874b3dSMiao Xie 	 */
208308d50ca3SNikolay Borisov 	ret = create_pending_snapshots(trans);
208449b25e05SJeff Mahoney 	if (ret) {
20850b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
20866cf7f77eSWang Shilong 		goto scrub_continue;
208749b25e05SJeff Mahoney 	}
20883063d29fSChris Mason 
208942874b3dSMiao Xie 	/*
209042874b3dSMiao Xie 	 * We insert the dir indexes of the snapshots and update the inode
209142874b3dSMiao Xie 	 * of the snapshots' parents after the snapshot creation, so there
209242874b3dSMiao Xie 	 * are some delayed items which are not dealt with. Now deal with
209342874b3dSMiao Xie 	 * them.
209442874b3dSMiao Xie 	 *
209542874b3dSMiao Xie 	 * We needn't worry that this operation will corrupt the snapshots,
209642874b3dSMiao Xie 	 * because all the tree which are snapshoted will be forced to COW
209742874b3dSMiao Xie 	 * the nodes and leaves.
209842874b3dSMiao Xie 	 */
2099e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
210049b25e05SJeff Mahoney 	if (ret) {
21010b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21026cf7f77eSWang Shilong 		goto scrub_continue;
210349b25e05SJeff Mahoney 	}
210416cdcec7SMiao Xie 
2105c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
210649b25e05SJeff Mahoney 	if (ret) {
21070b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21086cf7f77eSWang Shilong 		goto scrub_continue;
210949b25e05SJeff Mahoney 	}
211056bec294SChris Mason 
2111e999376fSChris Mason 	/*
2112e999376fSChris Mason 	 * make sure none of the code above managed to slip in a
2113e999376fSChris Mason 	 * delayed item
2114e999376fSChris Mason 	 */
2115ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
2116e999376fSChris Mason 
21172c90e5d6SChris Mason 	WARN_ON(cur_trans != trans->transaction);
2118dc17ff8fSChris Mason 
2119e02119d5SChris Mason 	/* btrfs_commit_tree_roots is responsible for getting the
2120e02119d5SChris Mason 	 * various roots consistent with each other.  Every pointer
2121e02119d5SChris Mason 	 * in the tree of tree roots has to point to the most up to date
2122e02119d5SChris Mason 	 * root for every subvolume and other tree.  So, we have to keep
2123e02119d5SChris Mason 	 * the tree logging code from jumping in and changing any
2124e02119d5SChris Mason 	 * of the trees.
2125e02119d5SChris Mason 	 *
2126e02119d5SChris Mason 	 * At this point in the commit, there can't be any tree-log
2127e02119d5SChris Mason 	 * writers, but a little lower down we drop the trans mutex
2128e02119d5SChris Mason 	 * and let new people in.  By holding the tree_log_mutex
2129e02119d5SChris Mason 	 * from now until after the super is written, we avoid races
2130e02119d5SChris Mason 	 * with the tree-log code.
2131e02119d5SChris Mason 	 */
21320b246afaSJeff Mahoney 	mutex_lock(&fs_info->tree_log_mutex);
21331a40e23bSZheng Yan 
21347e4443d9SNikolay Borisov 	ret = commit_fs_roots(trans);
213549b25e05SJeff Mahoney 	if (ret) {
21360b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
21370b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21386cf7f77eSWang Shilong 		goto scrub_continue;
213949b25e05SJeff Mahoney 	}
214054aa1f4dSChris Mason 
21413818aea2SQu Wenruo 	/*
21427e1876acSDavid Sterba 	 * Since the transaction is done, we can apply the pending changes
21437e1876acSDavid Sterba 	 * before the next transaction.
21443818aea2SQu Wenruo 	 */
21450b246afaSJeff Mahoney 	btrfs_apply_pending_changes(fs_info);
21463818aea2SQu Wenruo 
21475d4f98a2SYan Zheng 	/* commit_fs_roots gets rid of all the tree log roots, it is now
2148e02119d5SChris Mason 	 * safe to free the root of tree log roots
2149e02119d5SChris Mason 	 */
21500b246afaSJeff Mahoney 	btrfs_free_log_root_tree(trans, fs_info);
2151e02119d5SChris Mason 
21520ed4792aSQu Wenruo 	/*
215382bafb38SQu Wenruo 	 * commit_fs_roots() can call btrfs_save_ino_cache(), which generates
215482bafb38SQu Wenruo 	 * new delayed refs. Must handle them or qgroup can be wrong.
215582bafb38SQu Wenruo 	 */
2156c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
215782bafb38SQu Wenruo 	if (ret) {
215882bafb38SQu Wenruo 		mutex_unlock(&fs_info->tree_log_mutex);
215982bafb38SQu Wenruo 		mutex_unlock(&fs_info->reloc_mutex);
216082bafb38SQu Wenruo 		goto scrub_continue;
216182bafb38SQu Wenruo 	}
216282bafb38SQu Wenruo 
216382bafb38SQu Wenruo 	/*
21640ed4792aSQu Wenruo 	 * Since fs roots are all committed, we can get a quite accurate
21650ed4792aSQu Wenruo 	 * new_roots. So let's do quota accounting.
21660ed4792aSQu Wenruo 	 */
2167460fb20aSNikolay Borisov 	ret = btrfs_qgroup_account_extents(trans);
21680ed4792aSQu Wenruo 	if (ret < 0) {
21690b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
21700b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21710ed4792aSQu Wenruo 		goto scrub_continue;
21720ed4792aSQu Wenruo 	}
21730ed4792aSQu Wenruo 
21749386d8bcSNikolay Borisov 	ret = commit_cowonly_roots(trans);
217549b25e05SJeff Mahoney 	if (ret) {
21760b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
21770b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21786cf7f77eSWang Shilong 		goto scrub_continue;
217949b25e05SJeff Mahoney 	}
218054aa1f4dSChris Mason 
21812cba30f1SMiao Xie 	/*
21822cba30f1SMiao Xie 	 * The tasks which save the space cache and inode cache may also
21832cba30f1SMiao Xie 	 * update ->aborted, check it.
21842cba30f1SMiao Xie 	 */
218520c7bcecSSeraphime Kirkovski 	if (unlikely(READ_ONCE(cur_trans->aborted))) {
21862cba30f1SMiao Xie 		ret = cur_trans->aborted;
21870b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
21880b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21896cf7f77eSWang Shilong 		goto scrub_continue;
21902cba30f1SMiao Xie 	}
21912cba30f1SMiao Xie 
21928b74c03eSDavid Sterba 	btrfs_prepare_extent_commit(fs_info);
219311833d66SYan Zheng 
21940b246afaSJeff Mahoney 	cur_trans = fs_info->running_transaction;
21955f39d397SChris Mason 
21960b246afaSJeff Mahoney 	btrfs_set_root_node(&fs_info->tree_root->root_item,
21970b246afaSJeff Mahoney 			    fs_info->tree_root->node);
21980b246afaSJeff Mahoney 	list_add_tail(&fs_info->tree_root->dirty_list,
21999e351cc8SJosef Bacik 		      &cur_trans->switch_commits);
22005d4f98a2SYan Zheng 
22010b246afaSJeff Mahoney 	btrfs_set_root_node(&fs_info->chunk_root->root_item,
22020b246afaSJeff Mahoney 			    fs_info->chunk_root->node);
22030b246afaSJeff Mahoney 	list_add_tail(&fs_info->chunk_root->dirty_list,
22049e351cc8SJosef Bacik 		      &cur_trans->switch_commits);
22059e351cc8SJosef Bacik 
220616916a88SNikolay Borisov 	switch_commit_roots(cur_trans);
22075d4f98a2SYan Zheng 
2208ce93ec54SJosef Bacik 	ASSERT(list_empty(&cur_trans->dirty_bgs));
22091bbc621eSChris Mason 	ASSERT(list_empty(&cur_trans->io_bgs));
22102ff7e61eSJeff Mahoney 	update_super_roots(fs_info);
2211e02119d5SChris Mason 
22120b246afaSJeff Mahoney 	btrfs_set_super_log_root(fs_info->super_copy, 0);
22130b246afaSJeff Mahoney 	btrfs_set_super_log_root_level(fs_info->super_copy, 0);
22140b246afaSJeff Mahoney 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
22150b246afaSJeff Mahoney 	       sizeof(*fs_info->super_copy));
2216ccd467d6SChris Mason 
2217bbbf7243SNikolay Borisov 	btrfs_commit_device_sizes(cur_trans);
2218935e5cc9SMiao Xie 
22190b246afaSJeff Mahoney 	clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
22200b246afaSJeff Mahoney 	clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2221656f30dbSFilipe Manana 
22224fbcdf66SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
22234fbcdf66SFilipe Manana 
22240b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
22254a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
22260b246afaSJeff Mahoney 	fs_info->running_transaction = NULL;
22270b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
22280b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
2229b7ec40d7SChris Mason 
22300b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
2231e6dcd2dcSChris Mason 
223270458a58SNikolay Borisov 	ret = btrfs_write_and_wait_transaction(trans);
223349b25e05SJeff Mahoney 	if (ret) {
22340b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
223508748810SDavid Sterba 				      "Error while writing out transaction");
22360b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
22376cf7f77eSWang Shilong 		goto scrub_continue;
223849b25e05SJeff Mahoney 	}
223949b25e05SJeff Mahoney 
2240eece6a9cSDavid Sterba 	ret = write_all_supers(fs_info, 0);
2241e02119d5SChris Mason 	/*
2242e02119d5SChris Mason 	 * the super is written, we can safely allow the tree-loggers
2243e02119d5SChris Mason 	 * to go about their business
2244e02119d5SChris Mason 	 */
22450b246afaSJeff Mahoney 	mutex_unlock(&fs_info->tree_log_mutex);
2246c1f32b7cSAnand Jain 	if (ret)
2247c1f32b7cSAnand Jain 		goto scrub_continue;
2248e02119d5SChris Mason 
22495ead2dd0SNikolay Borisov 	btrfs_finish_extent_commit(trans);
22504313b399SChris Mason 
22513204d33cSJosef Bacik 	if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
22520b246afaSJeff Mahoney 		btrfs_clear_space_info_full(fs_info);
225313212b54SZhao Lei 
22540b246afaSJeff Mahoney 	fs_info->last_trans_committed = cur_trans->transid;
22554a9d8bdeSMiao Xie 	/*
22564a9d8bdeSMiao Xie 	 * We needn't acquire the lock here because there is no other task
22574a9d8bdeSMiao Xie 	 * which can change it.
22584a9d8bdeSMiao Xie 	 */
22594a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMPLETED;
22602c90e5d6SChris Mason 	wake_up(&cur_trans->commit_wait);
2261a514d638SQu Wenruo 	clear_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags);
22623de4586cSChris Mason 
22630b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
226413c5a93eSJosef Bacik 	list_del_init(&cur_trans->list);
22650b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2266a4abeea4SJosef Bacik 
2267724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
2268724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
226958176a96SJosef Bacik 
22700860adfdSMiao Xie 	if (trans->type & __TRANS_FREEZABLE)
22710b246afaSJeff Mahoney 		sb_end_intwrite(fs_info->sb);
2272b2b5ef5cSJan Kara 
22733a45bb20SJeff Mahoney 	trace_btrfs_transaction_commit(trans->root);
22741abe9b8aSliubo 
22752ff7e61eSJeff Mahoney 	btrfs_scrub_continue(fs_info);
2276a2de733cSArne Jansen 
22779ed74f2dSJosef Bacik 	if (current->journal_info == trans)
22789ed74f2dSJosef Bacik 		current->journal_info = NULL;
22799ed74f2dSJosef Bacik 
22802c90e5d6SChris Mason 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
228124bbcf04SYan, Zheng 
228279154b1bSChris Mason 	return ret;
228349b25e05SJeff Mahoney 
22846cf7f77eSWang Shilong scrub_continue:
22852ff7e61eSJeff Mahoney 	btrfs_scrub_continue(fs_info);
228649b25e05SJeff Mahoney cleanup_transaction:
2287dc60c525SNikolay Borisov 	btrfs_trans_release_metadata(trans);
2288c7cc64a9SDavid Sterba 	btrfs_cleanup_pending_block_groups(trans);
22894fbcdf66SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
22900e721106SJosef Bacik 	trans->block_rsv = NULL;
22910b246afaSJeff Mahoney 	btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
229249b25e05SJeff Mahoney 	if (current->journal_info == trans)
229349b25e05SJeff Mahoney 		current->journal_info = NULL;
229497cb39bbSNikolay Borisov 	cleanup_transaction(trans, ret);
229549b25e05SJeff Mahoney 
229649b25e05SJeff Mahoney 	return ret;
229779154b1bSChris Mason }
229879154b1bSChris Mason 
2299d352ac68SChris Mason /*
23009d1a2a3aSDavid Sterba  * return < 0 if error
23019d1a2a3aSDavid Sterba  * 0 if there are no more dead_roots at the time of call
23029d1a2a3aSDavid Sterba  * 1 there are more to be processed, call me again
23039d1a2a3aSDavid Sterba  *
23049d1a2a3aSDavid Sterba  * The return value indicates there are certainly more snapshots to delete, but
23059d1a2a3aSDavid Sterba  * if there comes a new one during processing, it may return 0. We don't mind,
23069d1a2a3aSDavid Sterba  * because btrfs_commit_super will poke cleaner thread and it will process it a
23079d1a2a3aSDavid Sterba  * few seconds later.
2308d352ac68SChris Mason  */
23099d1a2a3aSDavid Sterba int btrfs_clean_one_deleted_snapshot(struct btrfs_root *root)
2310e9d0b13bSChris Mason {
23119d1a2a3aSDavid Sterba 	int ret;
23125d4f98a2SYan Zheng 	struct btrfs_fs_info *fs_info = root->fs_info;
2313e9d0b13bSChris Mason 
2314a4abeea4SJosef Bacik 	spin_lock(&fs_info->trans_lock);
23159d1a2a3aSDavid Sterba 	if (list_empty(&fs_info->dead_roots)) {
23169d1a2a3aSDavid Sterba 		spin_unlock(&fs_info->trans_lock);
23179d1a2a3aSDavid Sterba 		return 0;
23189d1a2a3aSDavid Sterba 	}
23199d1a2a3aSDavid Sterba 	root = list_first_entry(&fs_info->dead_roots,
23209d1a2a3aSDavid Sterba 			struct btrfs_root, root_list);
2321cfad392bSJosef Bacik 	list_del_init(&root->root_list);
2322a4abeea4SJosef Bacik 	spin_unlock(&fs_info->trans_lock);
23235d4f98a2SYan Zheng 
23244fd786e6SMisono Tomohiro 	btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
232576dda93cSYan, Zheng 
232616cdcec7SMiao Xie 	btrfs_kill_all_delayed_nodes(root);
232716cdcec7SMiao Xie 
232876dda93cSYan, Zheng 	if (btrfs_header_backref_rev(root->node) <
232976dda93cSYan, Zheng 			BTRFS_MIXED_BACKREF_REV)
23302c536799SJeff Mahoney 		ret = btrfs_drop_snapshot(root, NULL, 0, 0);
233176dda93cSYan, Zheng 	else
23322c536799SJeff Mahoney 		ret = btrfs_drop_snapshot(root, NULL, 1, 0);
233332471dc2SDavid Sterba 
23346596a928SJosef Bacik 	return (ret < 0) ? 0 : 1;
2335e9d0b13bSChris Mason }
2336572d9ab7SDavid Sterba 
2337572d9ab7SDavid Sterba void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2338572d9ab7SDavid Sterba {
2339572d9ab7SDavid Sterba 	unsigned long prev;
2340572d9ab7SDavid Sterba 	unsigned long bit;
2341572d9ab7SDavid Sterba 
23426c9fe14fSQu Wenruo 	prev = xchg(&fs_info->pending_changes, 0);
2343572d9ab7SDavid Sterba 	if (!prev)
2344572d9ab7SDavid Sterba 		return;
2345572d9ab7SDavid Sterba 
23467e1876acSDavid Sterba 	bit = 1 << BTRFS_PENDING_SET_INODE_MAP_CACHE;
23477e1876acSDavid Sterba 	if (prev & bit)
23487e1876acSDavid Sterba 		btrfs_set_opt(fs_info->mount_opt, INODE_MAP_CACHE);
23497e1876acSDavid Sterba 	prev &= ~bit;
23507e1876acSDavid Sterba 
23517e1876acSDavid Sterba 	bit = 1 << BTRFS_PENDING_CLEAR_INODE_MAP_CACHE;
23527e1876acSDavid Sterba 	if (prev & bit)
23537e1876acSDavid Sterba 		btrfs_clear_opt(fs_info->mount_opt, INODE_MAP_CACHE);
23547e1876acSDavid Sterba 	prev &= ~bit;
23557e1876acSDavid Sterba 
2356d51033d0SDavid Sterba 	bit = 1 << BTRFS_PENDING_COMMIT;
2357d51033d0SDavid Sterba 	if (prev & bit)
2358d51033d0SDavid Sterba 		btrfs_debug(fs_info, "pending commit done");
2359d51033d0SDavid Sterba 	prev &= ~bit;
2360d51033d0SDavid Sterba 
2361572d9ab7SDavid Sterba 	if (prev)
2362572d9ab7SDavid Sterba 		btrfs_warn(fs_info,
2363572d9ab7SDavid Sterba 			"unknown pending changes left 0x%lx, ignoring", prev);
2364572d9ab7SDavid Sterba }
2365