xref: /openbmc/linux/fs/btrfs/transaction.c (revision 64403612)
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 		}
784b5faeacSDavid Sterba 		kfree(transaction);
7979154b1bSChris Mason 	}
8078fae27eSChris Mason }
8179154b1bSChris Mason 
82663dfbb0SFilipe Manana static void clear_btree_io_tree(struct extent_io_tree *tree)
83663dfbb0SFilipe Manana {
84663dfbb0SFilipe Manana 	spin_lock(&tree->lock);
85b666a9cdSDavid Sterba 	/*
86b666a9cdSDavid Sterba 	 * Do a single barrier for the waitqueue_active check here, the state
87b666a9cdSDavid Sterba 	 * of the waitqueue should not change once clear_btree_io_tree is
88b666a9cdSDavid Sterba 	 * called.
89b666a9cdSDavid Sterba 	 */
90b666a9cdSDavid Sterba 	smp_mb();
91663dfbb0SFilipe Manana 	while (!RB_EMPTY_ROOT(&tree->state)) {
92663dfbb0SFilipe Manana 		struct rb_node *node;
93663dfbb0SFilipe Manana 		struct extent_state *state;
94663dfbb0SFilipe Manana 
95663dfbb0SFilipe Manana 		node = rb_first(&tree->state);
96663dfbb0SFilipe Manana 		state = rb_entry(node, struct extent_state, rb_node);
97663dfbb0SFilipe Manana 		rb_erase(&state->rb_node, &tree->state);
98663dfbb0SFilipe Manana 		RB_CLEAR_NODE(&state->rb_node);
99663dfbb0SFilipe Manana 		/*
100663dfbb0SFilipe Manana 		 * btree io trees aren't supposed to have tasks waiting for
101663dfbb0SFilipe Manana 		 * changes in the flags of extent states ever.
102663dfbb0SFilipe Manana 		 */
103663dfbb0SFilipe Manana 		ASSERT(!waitqueue_active(&state->wq));
104663dfbb0SFilipe Manana 		free_extent_state(state);
105351810c1SDavid Sterba 
106351810c1SDavid Sterba 		cond_resched_lock(&tree->lock);
107663dfbb0SFilipe Manana 	}
108663dfbb0SFilipe Manana 	spin_unlock(&tree->lock);
109663dfbb0SFilipe Manana }
110663dfbb0SFilipe Manana 
11116916a88SNikolay Borisov static noinline void switch_commit_roots(struct btrfs_transaction *trans)
112817d52f8SJosef Bacik {
11316916a88SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
1149e351cc8SJosef Bacik 	struct btrfs_root *root, *tmp;
1159e351cc8SJosef Bacik 
1169e351cc8SJosef Bacik 	down_write(&fs_info->commit_root_sem);
1179e351cc8SJosef Bacik 	list_for_each_entry_safe(root, tmp, &trans->switch_commits,
1189e351cc8SJosef Bacik 				 dirty_list) {
1199e351cc8SJosef Bacik 		list_del_init(&root->dirty_list);
120817d52f8SJosef Bacik 		free_extent_buffer(root->commit_root);
121817d52f8SJosef Bacik 		root->commit_root = btrfs_root_node(root);
1224fd786e6SMisono Tomohiro 		if (is_fstree(root->root_key.objectid))
1239e351cc8SJosef Bacik 			btrfs_unpin_free_ino(root);
124663dfbb0SFilipe Manana 		clear_btree_io_tree(&root->dirty_log_pages);
1259e351cc8SJosef Bacik 	}
1262b9dbef2SJosef Bacik 
1272b9dbef2SJosef Bacik 	/* We can free old roots now. */
1282b9dbef2SJosef Bacik 	spin_lock(&trans->dropped_roots_lock);
1292b9dbef2SJosef Bacik 	while (!list_empty(&trans->dropped_roots)) {
1302b9dbef2SJosef Bacik 		root = list_first_entry(&trans->dropped_roots,
1312b9dbef2SJosef Bacik 					struct btrfs_root, root_list);
1322b9dbef2SJosef Bacik 		list_del_init(&root->root_list);
1332b9dbef2SJosef Bacik 		spin_unlock(&trans->dropped_roots_lock);
1342b9dbef2SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, root);
1352b9dbef2SJosef Bacik 		spin_lock(&trans->dropped_roots_lock);
1362b9dbef2SJosef Bacik 	}
1372b9dbef2SJosef Bacik 	spin_unlock(&trans->dropped_roots_lock);
1389e351cc8SJosef Bacik 	up_write(&fs_info->commit_root_sem);
139817d52f8SJosef Bacik }
140817d52f8SJosef Bacik 
1410860adfdSMiao Xie static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
1420860adfdSMiao Xie 					 unsigned int type)
1430860adfdSMiao Xie {
1440860adfdSMiao Xie 	if (type & TRANS_EXTWRITERS)
1450860adfdSMiao Xie 		atomic_inc(&trans->num_extwriters);
1460860adfdSMiao Xie }
1470860adfdSMiao Xie 
1480860adfdSMiao Xie static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
1490860adfdSMiao Xie 					 unsigned int type)
1500860adfdSMiao Xie {
1510860adfdSMiao Xie 	if (type & TRANS_EXTWRITERS)
1520860adfdSMiao Xie 		atomic_dec(&trans->num_extwriters);
1530860adfdSMiao Xie }
1540860adfdSMiao Xie 
1550860adfdSMiao Xie static inline void extwriter_counter_init(struct btrfs_transaction *trans,
1560860adfdSMiao Xie 					  unsigned int type)
1570860adfdSMiao Xie {
1580860adfdSMiao Xie 	atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
1590860adfdSMiao Xie }
1600860adfdSMiao Xie 
1610860adfdSMiao Xie static inline int extwriter_counter_read(struct btrfs_transaction *trans)
1620860adfdSMiao Xie {
1630860adfdSMiao Xie 	return atomic_read(&trans->num_extwriters);
164178260b2SMiao Xie }
165178260b2SMiao Xie 
166d352ac68SChris Mason /*
167d352ac68SChris Mason  * either allocate a new transaction or hop into the existing one
168d352ac68SChris Mason  */
1692ff7e61eSJeff Mahoney static noinline int join_transaction(struct btrfs_fs_info *fs_info,
1702ff7e61eSJeff Mahoney 				     unsigned int type)
17179154b1bSChris Mason {
17279154b1bSChris Mason 	struct btrfs_transaction *cur_trans;
173a4abeea4SJosef Bacik 
17419ae4e81SJan Schmidt 	spin_lock(&fs_info->trans_lock);
175d43317dcSChris Mason loop:
17649b25e05SJeff Mahoney 	/* The file system has been taken offline. No new transactions. */
17787533c47SMiao Xie 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
17819ae4e81SJan Schmidt 		spin_unlock(&fs_info->trans_lock);
17949b25e05SJeff Mahoney 		return -EROFS;
18049b25e05SJeff Mahoney 	}
18149b25e05SJeff Mahoney 
18219ae4e81SJan Schmidt 	cur_trans = fs_info->running_transaction;
183a4abeea4SJosef Bacik 	if (cur_trans) {
184871383beSDavid Sterba 		if (cur_trans->aborted) {
18519ae4e81SJan Schmidt 			spin_unlock(&fs_info->trans_lock);
18649b25e05SJeff Mahoney 			return cur_trans->aborted;
187871383beSDavid Sterba 		}
1884a9d8bdeSMiao Xie 		if (btrfs_blocked_trans_types[cur_trans->state] & type) {
189178260b2SMiao Xie 			spin_unlock(&fs_info->trans_lock);
190178260b2SMiao Xie 			return -EBUSY;
191178260b2SMiao Xie 		}
1929b64f57dSElena Reshetova 		refcount_inc(&cur_trans->use_count);
193a4abeea4SJosef Bacik 		atomic_inc(&cur_trans->num_writers);
1940860adfdSMiao Xie 		extwriter_counter_inc(cur_trans, type);
19519ae4e81SJan Schmidt 		spin_unlock(&fs_info->trans_lock);
196a4abeea4SJosef Bacik 		return 0;
197a4abeea4SJosef Bacik 	}
19819ae4e81SJan Schmidt 	spin_unlock(&fs_info->trans_lock);
199a4abeea4SJosef Bacik 
200354aa0fbSMiao Xie 	/*
201354aa0fbSMiao Xie 	 * If we are ATTACH, we just want to catch the current transaction,
202354aa0fbSMiao Xie 	 * and commit it. If there is no transaction, just return ENOENT.
203354aa0fbSMiao Xie 	 */
204354aa0fbSMiao Xie 	if (type == TRANS_ATTACH)
205354aa0fbSMiao Xie 		return -ENOENT;
206354aa0fbSMiao Xie 
2074a9d8bdeSMiao Xie 	/*
2084a9d8bdeSMiao Xie 	 * JOIN_NOLOCK only happens during the transaction commit, so
2094a9d8bdeSMiao Xie 	 * it is impossible that ->running_transaction is NULL
2104a9d8bdeSMiao Xie 	 */
2114a9d8bdeSMiao Xie 	BUG_ON(type == TRANS_JOIN_NOLOCK);
2124a9d8bdeSMiao Xie 
2134b5faeacSDavid Sterba 	cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
214db5b493aSTsutomu Itoh 	if (!cur_trans)
215db5b493aSTsutomu Itoh 		return -ENOMEM;
216d43317dcSChris Mason 
21719ae4e81SJan Schmidt 	spin_lock(&fs_info->trans_lock);
21819ae4e81SJan Schmidt 	if (fs_info->running_transaction) {
219d43317dcSChris Mason 		/*
220d43317dcSChris Mason 		 * someone started a transaction after we unlocked.  Make sure
2214a9d8bdeSMiao Xie 		 * to redo the checks above
222d43317dcSChris Mason 		 */
2234b5faeacSDavid Sterba 		kfree(cur_trans);
224d43317dcSChris Mason 		goto loop;
22587533c47SMiao Xie 	} else if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
226e4b50e14SDan Carpenter 		spin_unlock(&fs_info->trans_lock);
2274b5faeacSDavid Sterba 		kfree(cur_trans);
2287b8b92afSJosef Bacik 		return -EROFS;
229a4abeea4SJosef Bacik 	}
230d43317dcSChris Mason 
231ab8d0fc4SJeff Mahoney 	cur_trans->fs_info = fs_info;
23213c5a93eSJosef Bacik 	atomic_set(&cur_trans->num_writers, 1);
2330860adfdSMiao Xie 	extwriter_counter_init(cur_trans, type);
23479154b1bSChris Mason 	init_waitqueue_head(&cur_trans->writer_wait);
23579154b1bSChris Mason 	init_waitqueue_head(&cur_trans->commit_wait);
2364a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_RUNNING;
237a4abeea4SJosef Bacik 	/*
238a4abeea4SJosef Bacik 	 * One for this trans handle, one so it will live on until we
239a4abeea4SJosef Bacik 	 * commit the transaction.
240a4abeea4SJosef Bacik 	 */
2419b64f57dSElena Reshetova 	refcount_set(&cur_trans->use_count, 2);
2423204d33cSJosef Bacik 	cur_trans->flags = 0;
243afd48513SArnd Bergmann 	cur_trans->start_time = ktime_get_seconds();
24456bec294SChris Mason 
245a099d0fdSAlexandru Moise 	memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
246a099d0fdSAlexandru Moise 
2475c9d028bSLiu Bo 	cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
2483368d001SQu Wenruo 	cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
249d7df2c79SJosef Bacik 	atomic_set(&cur_trans->delayed_refs.num_entries, 0);
25020b297d6SJan Schmidt 
25120b297d6SJan Schmidt 	/*
25220b297d6SJan Schmidt 	 * although the tree mod log is per file system and not per transaction,
25320b297d6SJan Schmidt 	 * the log must never go across transaction boundaries.
25420b297d6SJan Schmidt 	 */
25520b297d6SJan Schmidt 	smp_mb();
25631b1a2bdSJulia Lawall 	if (!list_empty(&fs_info->tree_mod_seq_list))
2575d163e0eSJeff Mahoney 		WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
25831b1a2bdSJulia Lawall 	if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
2595d163e0eSJeff Mahoney 		WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
260fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
26120b297d6SJan Schmidt 
26256bec294SChris Mason 	spin_lock_init(&cur_trans->delayed_refs.lock);
26356bec294SChris Mason 
2643063d29fSChris Mason 	INIT_LIST_HEAD(&cur_trans->pending_snapshots);
2656df9a95eSJosef Bacik 	INIT_LIST_HEAD(&cur_trans->pending_chunks);
2669e351cc8SJosef Bacik 	INIT_LIST_HEAD(&cur_trans->switch_commits);
267ce93ec54SJosef Bacik 	INIT_LIST_HEAD(&cur_trans->dirty_bgs);
2681bbc621eSChris Mason 	INIT_LIST_HEAD(&cur_trans->io_bgs);
2692b9dbef2SJosef Bacik 	INIT_LIST_HEAD(&cur_trans->dropped_roots);
2701bbc621eSChris Mason 	mutex_init(&cur_trans->cache_write_mutex);
271cb723e49SJosef Bacik 	cur_trans->num_dirty_bgs = 0;
272ce93ec54SJosef Bacik 	spin_lock_init(&cur_trans->dirty_bgs_lock);
273e33e17eeSJeff Mahoney 	INIT_LIST_HEAD(&cur_trans->deleted_bgs);
2742b9dbef2SJosef Bacik 	spin_lock_init(&cur_trans->dropped_roots_lock);
27519ae4e81SJan Schmidt 	list_add_tail(&cur_trans->list, &fs_info->trans_list);
276d1310b2eSChris Mason 	extent_io_tree_init(&cur_trans->dirty_pages,
277c6100a4bSJosef Bacik 			     fs_info->btree_inode);
27819ae4e81SJan Schmidt 	fs_info->generation++;
27919ae4e81SJan Schmidt 	cur_trans->transid = fs_info->generation;
28019ae4e81SJan Schmidt 	fs_info->running_transaction = cur_trans;
28149b25e05SJeff Mahoney 	cur_trans->aborted = 0;
28219ae4e81SJan Schmidt 	spin_unlock(&fs_info->trans_lock);
28315ee9bc7SJosef Bacik 
28479154b1bSChris Mason 	return 0;
28579154b1bSChris Mason }
28679154b1bSChris Mason 
287d352ac68SChris Mason /*
288d397712bSChris Mason  * this does all the record keeping required to make sure that a reference
289d397712bSChris Mason  * counted root is properly recorded in a given transaction.  This is required
290d397712bSChris Mason  * to make sure the old root from before we joined the transaction is deleted
291d397712bSChris Mason  * when the transaction commits
292d352ac68SChris Mason  */
2937585717fSChris Mason static int record_root_in_trans(struct btrfs_trans_handle *trans,
2946426c7adSQu Wenruo 			       struct btrfs_root *root,
2956426c7adSQu Wenruo 			       int force)
2966702ed49SChris Mason {
2970b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2980b246afaSJeff Mahoney 
2996426c7adSQu Wenruo 	if ((test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
3006426c7adSQu Wenruo 	    root->last_trans < trans->transid) || force) {
3010b246afaSJeff Mahoney 		WARN_ON(root == fs_info->extent_root);
3024d31778aSQu Wenruo 		WARN_ON(!force && root->commit_root != root->node);
3035d4f98a2SYan Zheng 
3047585717fSChris Mason 		/*
30527cdeb70SMiao Xie 		 * see below for IN_TRANS_SETUP usage rules
3067585717fSChris Mason 		 * we have the reloc mutex held now, so there
3077585717fSChris Mason 		 * is only one writer in this function
3087585717fSChris Mason 		 */
30927cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
3107585717fSChris Mason 
31127cdeb70SMiao Xie 		/* make sure readers find IN_TRANS_SETUP before
3127585717fSChris Mason 		 * they find our root->last_trans update
3137585717fSChris Mason 		 */
3147585717fSChris Mason 		smp_wmb();
3157585717fSChris Mason 
3160b246afaSJeff Mahoney 		spin_lock(&fs_info->fs_roots_radix_lock);
3176426c7adSQu Wenruo 		if (root->last_trans == trans->transid && !force) {
3180b246afaSJeff Mahoney 			spin_unlock(&fs_info->fs_roots_radix_lock);
319a4abeea4SJosef Bacik 			return 0;
320a4abeea4SJosef Bacik 		}
3210b246afaSJeff Mahoney 		radix_tree_tag_set(&fs_info->fs_roots_radix,
3226702ed49SChris Mason 				   (unsigned long)root->root_key.objectid,
3236702ed49SChris Mason 				   BTRFS_ROOT_TRANS_TAG);
3240b246afaSJeff Mahoney 		spin_unlock(&fs_info->fs_roots_radix_lock);
3257585717fSChris Mason 		root->last_trans = trans->transid;
3267585717fSChris Mason 
3277585717fSChris Mason 		/* this is pretty tricky.  We don't want to
3287585717fSChris Mason 		 * take the relocation lock in btrfs_record_root_in_trans
3297585717fSChris Mason 		 * unless we're really doing the first setup for this root in
3307585717fSChris Mason 		 * this transaction.
3317585717fSChris Mason 		 *
3327585717fSChris Mason 		 * Normally we'd use root->last_trans as a flag to decide
3337585717fSChris Mason 		 * if we want to take the expensive mutex.
3347585717fSChris Mason 		 *
3357585717fSChris Mason 		 * But, we have to set root->last_trans before we
3367585717fSChris Mason 		 * init the relocation root, otherwise, we trip over warnings
3377585717fSChris Mason 		 * in ctree.c.  The solution used here is to flag ourselves
33827cdeb70SMiao Xie 		 * with root IN_TRANS_SETUP.  When this is 1, we're still
3397585717fSChris Mason 		 * fixing up the reloc trees and everyone must wait.
3407585717fSChris Mason 		 *
3417585717fSChris Mason 		 * When this is zero, they can trust root->last_trans and fly
3427585717fSChris Mason 		 * through btrfs_record_root_in_trans without having to take the
3437585717fSChris Mason 		 * lock.  smp_wmb() makes sure that all the writes above are
3447585717fSChris Mason 		 * done before we pop in the zero below
3457585717fSChris Mason 		 */
3465d4f98a2SYan Zheng 		btrfs_init_reloc_root(trans, root);
347c7548af6SChris Mason 		smp_mb__before_atomic();
34827cdeb70SMiao Xie 		clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
3496702ed49SChris Mason 	}
3505d4f98a2SYan Zheng 	return 0;
3516702ed49SChris Mason }
3525d4f98a2SYan Zheng 
3537585717fSChris Mason 
3542b9dbef2SJosef Bacik void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
3552b9dbef2SJosef Bacik 			    struct btrfs_root *root)
3562b9dbef2SJosef Bacik {
3570b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3582b9dbef2SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
3592b9dbef2SJosef Bacik 
3602b9dbef2SJosef Bacik 	/* Add ourselves to the transaction dropped list */
3612b9dbef2SJosef Bacik 	spin_lock(&cur_trans->dropped_roots_lock);
3622b9dbef2SJosef Bacik 	list_add_tail(&root->root_list, &cur_trans->dropped_roots);
3632b9dbef2SJosef Bacik 	spin_unlock(&cur_trans->dropped_roots_lock);
3642b9dbef2SJosef Bacik 
3652b9dbef2SJosef Bacik 	/* Make sure we don't try to update the root at commit time */
3660b246afaSJeff Mahoney 	spin_lock(&fs_info->fs_roots_radix_lock);
3670b246afaSJeff Mahoney 	radix_tree_tag_clear(&fs_info->fs_roots_radix,
3682b9dbef2SJosef Bacik 			     (unsigned long)root->root_key.objectid,
3692b9dbef2SJosef Bacik 			     BTRFS_ROOT_TRANS_TAG);
3700b246afaSJeff Mahoney 	spin_unlock(&fs_info->fs_roots_radix_lock);
3712b9dbef2SJosef Bacik }
3722b9dbef2SJosef Bacik 
3737585717fSChris Mason int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
3747585717fSChris Mason 			       struct btrfs_root *root)
3757585717fSChris Mason {
3760b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3770b246afaSJeff Mahoney 
37827cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
3797585717fSChris Mason 		return 0;
3807585717fSChris Mason 
3817585717fSChris Mason 	/*
38227cdeb70SMiao Xie 	 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
3837585717fSChris Mason 	 * and barriers
3847585717fSChris Mason 	 */
3857585717fSChris Mason 	smp_rmb();
3867585717fSChris Mason 	if (root->last_trans == trans->transid &&
38727cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
3887585717fSChris Mason 		return 0;
3897585717fSChris Mason 
3900b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
3916426c7adSQu Wenruo 	record_root_in_trans(trans, root, 0);
3920b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
3937585717fSChris Mason 
3947585717fSChris Mason 	return 0;
3957585717fSChris Mason }
3967585717fSChris Mason 
3974a9d8bdeSMiao Xie static inline int is_transaction_blocked(struct btrfs_transaction *trans)
3984a9d8bdeSMiao Xie {
3994a9d8bdeSMiao Xie 	return (trans->state >= TRANS_STATE_BLOCKED &&
400501407aaSJosef Bacik 		trans->state < TRANS_STATE_UNBLOCKED &&
401501407aaSJosef Bacik 		!trans->aborted);
4024a9d8bdeSMiao Xie }
4034a9d8bdeSMiao Xie 
404d352ac68SChris Mason /* wait for commit against the current transaction to become unblocked
405d352ac68SChris Mason  * when this is done, it is safe to start a new transaction, but the current
406d352ac68SChris Mason  * transaction might not be fully on disk.
407d352ac68SChris Mason  */
4082ff7e61eSJeff Mahoney static void wait_current_trans(struct btrfs_fs_info *fs_info)
40979154b1bSChris Mason {
410f9295749SChris Mason 	struct btrfs_transaction *cur_trans;
41179154b1bSChris Mason 
4120b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
4130b246afaSJeff Mahoney 	cur_trans = fs_info->running_transaction;
4144a9d8bdeSMiao Xie 	if (cur_trans && is_transaction_blocked(cur_trans)) {
4159b64f57dSElena Reshetova 		refcount_inc(&cur_trans->use_count);
4160b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
41772d63ed6SLi Zefan 
4180b246afaSJeff Mahoney 		wait_event(fs_info->transaction_wait,
419501407aaSJosef Bacik 			   cur_trans->state >= TRANS_STATE_UNBLOCKED ||
420501407aaSJosef Bacik 			   cur_trans->aborted);
421724e2315SJosef Bacik 		btrfs_put_transaction(cur_trans);
422a4abeea4SJosef Bacik 	} else {
4230b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
424f9295749SChris Mason 	}
42537d1aeeeSChris Mason }
42637d1aeeeSChris Mason 
4272ff7e61eSJeff Mahoney static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
42837d1aeeeSChris Mason {
4290b246afaSJeff Mahoney 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
430a4abeea4SJosef Bacik 		return 0;
431a4abeea4SJosef Bacik 
43292e2f7e3SNikolay Borisov 	if (type == TRANS_START)
433a4abeea4SJosef Bacik 		return 1;
434a4abeea4SJosef Bacik 
435a22285a6SYan, Zheng 	return 0;
436a22285a6SYan, Zheng }
437a22285a6SYan, Zheng 
43820dd2cbfSMiao Xie static inline bool need_reserve_reloc_root(struct btrfs_root *root)
43920dd2cbfSMiao Xie {
4400b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4410b246afaSJeff Mahoney 
4420b246afaSJeff Mahoney 	if (!fs_info->reloc_ctl ||
44327cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
44420dd2cbfSMiao Xie 	    root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
44520dd2cbfSMiao Xie 	    root->reloc_root)
44620dd2cbfSMiao Xie 		return false;
44720dd2cbfSMiao Xie 
44820dd2cbfSMiao Xie 	return true;
44920dd2cbfSMiao Xie }
45020dd2cbfSMiao Xie 
45108e007d2SMiao Xie static struct btrfs_trans_handle *
4525aed1dd8SAlexandru Moise start_transaction(struct btrfs_root *root, unsigned int num_items,
453003d7c59SJeff Mahoney 		  unsigned int type, enum btrfs_reserve_flush_enum flush,
454003d7c59SJeff Mahoney 		  bool enforce_qgroups)
455a22285a6SYan, Zheng {
4560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
457ba2c4d4eSJosef Bacik 	struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
458a22285a6SYan, Zheng 	struct btrfs_trans_handle *h;
459a22285a6SYan, Zheng 	struct btrfs_transaction *cur_trans;
460b5009945SJosef Bacik 	u64 num_bytes = 0;
461c5567237SArne Jansen 	u64 qgroup_reserved = 0;
46220dd2cbfSMiao Xie 	bool reloc_reserved = false;
46320dd2cbfSMiao Xie 	int ret;
464acce952bSliubo 
46546c4e71eSFilipe Manana 	/* Send isn't supposed to start transactions. */
4662755a0deSDavid Sterba 	ASSERT(current->journal_info != BTRFS_SEND_TRANS_STUB);
46746c4e71eSFilipe Manana 
4680b246afaSJeff Mahoney 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
469acce952bSliubo 		return ERR_PTR(-EROFS);
4702a1eb461SJosef Bacik 
47146c4e71eSFilipe Manana 	if (current->journal_info) {
4720860adfdSMiao Xie 		WARN_ON(type & TRANS_EXTWRITERS);
4732a1eb461SJosef Bacik 		h = current->journal_info;
474b50fff81SDavid Sterba 		refcount_inc(&h->use_count);
475b50fff81SDavid Sterba 		WARN_ON(refcount_read(&h->use_count) > 2);
4762a1eb461SJosef Bacik 		h->orig_rsv = h->block_rsv;
4772a1eb461SJosef Bacik 		h->block_rsv = NULL;
4782a1eb461SJosef Bacik 		goto got_it;
4792a1eb461SJosef Bacik 	}
480b5009945SJosef Bacik 
481b5009945SJosef Bacik 	/*
482b5009945SJosef Bacik 	 * Do the reservation before we join the transaction so we can do all
483b5009945SJosef Bacik 	 * the appropriate flushing if need be.
484b5009945SJosef Bacik 	 */
485003d7c59SJeff Mahoney 	if (num_items && root != fs_info->chunk_root) {
486ba2c4d4eSJosef Bacik 		struct btrfs_block_rsv *rsv = &fs_info->trans_block_rsv;
487ba2c4d4eSJosef Bacik 		u64 delayed_refs_bytes = 0;
488ba2c4d4eSJosef Bacik 
4890b246afaSJeff Mahoney 		qgroup_reserved = num_items * fs_info->nodesize;
490733e03a0SQu Wenruo 		ret = btrfs_qgroup_reserve_meta_pertrans(root, qgroup_reserved,
491003d7c59SJeff Mahoney 				enforce_qgroups);
492c5567237SArne Jansen 		if (ret)
493c5567237SArne Jansen 			return ERR_PTR(ret);
494c5567237SArne Jansen 
495ba2c4d4eSJosef Bacik 		/*
496ba2c4d4eSJosef Bacik 		 * We want to reserve all the bytes we may need all at once, so
497ba2c4d4eSJosef Bacik 		 * we only do 1 enospc flushing cycle per transaction start.  We
498ba2c4d4eSJosef Bacik 		 * accomplish this by simply assuming we'll do 2 x num_items
499ba2c4d4eSJosef Bacik 		 * worth of delayed refs updates in this trans handle, and
500ba2c4d4eSJosef Bacik 		 * refill that amount for whatever is missing in the reserve.
501ba2c4d4eSJosef Bacik 		 */
5020b246afaSJeff Mahoney 		num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
503ba2c4d4eSJosef Bacik 		if (delayed_refs_rsv->full == 0) {
504ba2c4d4eSJosef Bacik 			delayed_refs_bytes = num_bytes;
505ba2c4d4eSJosef Bacik 			num_bytes <<= 1;
506ba2c4d4eSJosef Bacik 		}
507ba2c4d4eSJosef Bacik 
50820dd2cbfSMiao Xie 		/*
50920dd2cbfSMiao Xie 		 * Do the reservation for the relocation root creation
51020dd2cbfSMiao Xie 		 */
511ee39b432SDavid Sterba 		if (need_reserve_reloc_root(root)) {
5120b246afaSJeff Mahoney 			num_bytes += fs_info->nodesize;
51320dd2cbfSMiao Xie 			reloc_reserved = true;
51420dd2cbfSMiao Xie 		}
51520dd2cbfSMiao Xie 
516ba2c4d4eSJosef Bacik 		ret = btrfs_block_rsv_add(root, rsv, num_bytes, flush);
517ba2c4d4eSJosef Bacik 		if (ret)
518ba2c4d4eSJosef Bacik 			goto reserve_fail;
519ba2c4d4eSJosef Bacik 		if (delayed_refs_bytes) {
520ba2c4d4eSJosef Bacik 			btrfs_migrate_to_delayed_refs_rsv(fs_info, rsv,
521ba2c4d4eSJosef Bacik 							  delayed_refs_bytes);
522ba2c4d4eSJosef Bacik 			num_bytes -= delayed_refs_bytes;
523ba2c4d4eSJosef Bacik 		}
524ba2c4d4eSJosef Bacik 	} else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
525ba2c4d4eSJosef Bacik 		   !delayed_refs_rsv->full) {
526ba2c4d4eSJosef Bacik 		/*
527ba2c4d4eSJosef Bacik 		 * Some people call with btrfs_start_transaction(root, 0)
528ba2c4d4eSJosef Bacik 		 * because they can be throttled, but have some other mechanism
529ba2c4d4eSJosef Bacik 		 * for reserving space.  We still want these guys to refill the
530ba2c4d4eSJosef Bacik 		 * delayed block_rsv so just add 1 items worth of reservation
531ba2c4d4eSJosef Bacik 		 * here.
532ba2c4d4eSJosef Bacik 		 */
533ba2c4d4eSJosef Bacik 		ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
534b5009945SJosef Bacik 		if (ret)
535843fcf35SMiao Xie 			goto reserve_fail;
536b5009945SJosef Bacik 	}
537a22285a6SYan, Zheng again:
538f2f767e7SAlexandru Moise 	h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
539843fcf35SMiao Xie 	if (!h) {
540843fcf35SMiao Xie 		ret = -ENOMEM;
541843fcf35SMiao Xie 		goto alloc_fail;
542843fcf35SMiao Xie 	}
543a22285a6SYan, Zheng 
54498114659SJosef Bacik 	/*
54598114659SJosef Bacik 	 * If we are JOIN_NOLOCK we're already committing a transaction and
54698114659SJosef Bacik 	 * waiting on this guy, so we don't need to do the sb_start_intwrite
54798114659SJosef Bacik 	 * because we're already holding a ref.  We need this because we could
54898114659SJosef Bacik 	 * have raced in and did an fsync() on a file which can kick a commit
54998114659SJosef Bacik 	 * and then we deadlock with somebody doing a freeze.
550354aa0fbSMiao Xie 	 *
551354aa0fbSMiao Xie 	 * If we are ATTACH, it means we just want to catch the current
552354aa0fbSMiao Xie 	 * transaction and commit it, so we needn't do sb_start_intwrite().
55398114659SJosef Bacik 	 */
5540860adfdSMiao Xie 	if (type & __TRANS_FREEZABLE)
5550b246afaSJeff Mahoney 		sb_start_intwrite(fs_info->sb);
556b2b5ef5cSJan Kara 
5572ff7e61eSJeff Mahoney 	if (may_wait_transaction(fs_info, type))
5582ff7e61eSJeff Mahoney 		wait_current_trans(fs_info);
559a22285a6SYan, Zheng 
560a4abeea4SJosef Bacik 	do {
5612ff7e61eSJeff Mahoney 		ret = join_transaction(fs_info, type);
562178260b2SMiao Xie 		if (ret == -EBUSY) {
5632ff7e61eSJeff Mahoney 			wait_current_trans(fs_info);
564178260b2SMiao Xie 			if (unlikely(type == TRANS_ATTACH))
565178260b2SMiao Xie 				ret = -ENOENT;
566178260b2SMiao Xie 		}
567a4abeea4SJosef Bacik 	} while (ret == -EBUSY);
568a4abeea4SJosef Bacik 
569a43f7f82SLiu Bo 	if (ret < 0)
570843fcf35SMiao Xie 		goto join_fail;
5710f7d52f4SChris Mason 
5720b246afaSJeff Mahoney 	cur_trans = fs_info->running_transaction;
573a22285a6SYan, Zheng 
574a22285a6SYan, Zheng 	h->transid = cur_trans->transid;
575a22285a6SYan, Zheng 	h->transaction = cur_trans;
576d13603efSArne Jansen 	h->root = root;
577b50fff81SDavid Sterba 	refcount_set(&h->use_count, 1);
57864b63580SJeff Mahoney 	h->fs_info = root->fs_info;
5797174109cSQu Wenruo 
580a698d075SMiao Xie 	h->type = type;
581d9a0540aSFilipe Manana 	h->can_flush_pending_bgs = true;
582ea658badSJosef Bacik 	INIT_LIST_HEAD(&h->new_bgs);
583b7ec40d7SChris Mason 
584a22285a6SYan, Zheng 	smp_mb();
5854a9d8bdeSMiao Xie 	if (cur_trans->state >= TRANS_STATE_BLOCKED &&
5862ff7e61eSJeff Mahoney 	    may_wait_transaction(fs_info, type)) {
587abdd2e80SFilipe Manana 		current->journal_info = h;
5883a45bb20SJeff Mahoney 		btrfs_commit_transaction(h);
589a22285a6SYan, Zheng 		goto again;
590a22285a6SYan, Zheng 	}
5919ed74f2dSJosef Bacik 
592b5009945SJosef Bacik 	if (num_bytes) {
5930b246afaSJeff Mahoney 		trace_btrfs_space_reservation(fs_info, "transaction",
5942bcc0328SLiu Bo 					      h->transid, num_bytes, 1);
5950b246afaSJeff Mahoney 		h->block_rsv = &fs_info->trans_block_rsv;
596b5009945SJosef Bacik 		h->bytes_reserved = num_bytes;
59720dd2cbfSMiao Xie 		h->reloc_reserved = reloc_reserved;
598a22285a6SYan, Zheng 	}
599a22285a6SYan, Zheng 
6002a1eb461SJosef Bacik got_it:
601a4abeea4SJosef Bacik 	btrfs_record_root_in_trans(h, root);
602a22285a6SYan, Zheng 
603bcf3a3e7SNikolay Borisov 	if (!current->journal_info)
604a22285a6SYan, Zheng 		current->journal_info = h;
60579154b1bSChris Mason 	return h;
606843fcf35SMiao Xie 
607843fcf35SMiao Xie join_fail:
6080860adfdSMiao Xie 	if (type & __TRANS_FREEZABLE)
6090b246afaSJeff Mahoney 		sb_end_intwrite(fs_info->sb);
610843fcf35SMiao Xie 	kmem_cache_free(btrfs_trans_handle_cachep, h);
611843fcf35SMiao Xie alloc_fail:
612843fcf35SMiao Xie 	if (num_bytes)
6132ff7e61eSJeff Mahoney 		btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
614843fcf35SMiao Xie 					num_bytes);
615843fcf35SMiao Xie reserve_fail:
616733e03a0SQu Wenruo 	btrfs_qgroup_free_meta_pertrans(root, qgroup_reserved);
617843fcf35SMiao Xie 	return ERR_PTR(ret);
61879154b1bSChris Mason }
61979154b1bSChris Mason 
620f9295749SChris Mason struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
6215aed1dd8SAlexandru Moise 						   unsigned int num_items)
622f9295749SChris Mason {
62308e007d2SMiao Xie 	return start_transaction(root, num_items, TRANS_START,
624003d7c59SJeff Mahoney 				 BTRFS_RESERVE_FLUSH_ALL, true);
625f9295749SChris Mason }
626003d7c59SJeff Mahoney 
6278eab77ffSFilipe Manana struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
6288eab77ffSFilipe Manana 					struct btrfs_root *root,
6298eab77ffSFilipe Manana 					unsigned int num_items,
6308eab77ffSFilipe Manana 					int min_factor)
6318eab77ffSFilipe Manana {
6320b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6338eab77ffSFilipe Manana 	struct btrfs_trans_handle *trans;
6348eab77ffSFilipe Manana 	u64 num_bytes;
6358eab77ffSFilipe Manana 	int ret;
6368eab77ffSFilipe Manana 
637003d7c59SJeff Mahoney 	/*
638003d7c59SJeff Mahoney 	 * We have two callers: unlink and block group removal.  The
639003d7c59SJeff Mahoney 	 * former should succeed even if we will temporarily exceed
640003d7c59SJeff Mahoney 	 * quota and the latter operates on the extent root so
641003d7c59SJeff Mahoney 	 * qgroup enforcement is ignored anyway.
642003d7c59SJeff Mahoney 	 */
643003d7c59SJeff Mahoney 	trans = start_transaction(root, num_items, TRANS_START,
644003d7c59SJeff Mahoney 				  BTRFS_RESERVE_FLUSH_ALL, false);
6458eab77ffSFilipe Manana 	if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
6468eab77ffSFilipe Manana 		return trans;
6478eab77ffSFilipe Manana 
6488eab77ffSFilipe Manana 	trans = btrfs_start_transaction(root, 0);
6498eab77ffSFilipe Manana 	if (IS_ERR(trans))
6508eab77ffSFilipe Manana 		return trans;
6518eab77ffSFilipe Manana 
6520b246afaSJeff Mahoney 	num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
6530b246afaSJeff Mahoney 	ret = btrfs_cond_migrate_bytes(fs_info, &fs_info->trans_block_rsv,
6540b246afaSJeff Mahoney 				       num_bytes, min_factor);
6558eab77ffSFilipe Manana 	if (ret) {
6563a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
6578eab77ffSFilipe Manana 		return ERR_PTR(ret);
6588eab77ffSFilipe Manana 	}
6598eab77ffSFilipe Manana 
6600b246afaSJeff Mahoney 	trans->block_rsv = &fs_info->trans_block_rsv;
6618eab77ffSFilipe Manana 	trans->bytes_reserved = num_bytes;
6620b246afaSJeff Mahoney 	trace_btrfs_space_reservation(fs_info, "transaction",
66388d3a5aaSJosef Bacik 				      trans->transid, num_bytes, 1);
6648eab77ffSFilipe Manana 
6658eab77ffSFilipe Manana 	return trans;
6668eab77ffSFilipe Manana }
6678407aa46SMiao Xie 
6687a7eaa40SJosef Bacik struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
669f9295749SChris Mason {
670003d7c59SJeff Mahoney 	return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
671003d7c59SJeff Mahoney 				 true);
672f9295749SChris Mason }
673f9295749SChris Mason 
6747a7eaa40SJosef Bacik struct btrfs_trans_handle *btrfs_join_transaction_nolock(struct btrfs_root *root)
6750af3d00bSJosef Bacik {
676575a75d6SAlexandru Moise 	return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
677003d7c59SJeff Mahoney 				 BTRFS_RESERVE_NO_FLUSH, true);
6780af3d00bSJosef Bacik }
6790af3d00bSJosef Bacik 
680d4edf39bSMiao Xie /*
681d4edf39bSMiao Xie  * btrfs_attach_transaction() - catch the running transaction
682d4edf39bSMiao Xie  *
683d4edf39bSMiao Xie  * It is used when we want to commit the current the transaction, but
684d4edf39bSMiao Xie  * don't want to start a new one.
685d4edf39bSMiao Xie  *
686d4edf39bSMiao Xie  * Note: If this function return -ENOENT, it just means there is no
687d4edf39bSMiao Xie  * running transaction. But it is possible that the inactive transaction
688d4edf39bSMiao Xie  * is still in the memory, not fully on disk. If you hope there is no
689d4edf39bSMiao Xie  * inactive transaction in the fs when -ENOENT is returned, you should
690d4edf39bSMiao Xie  * invoke
691d4edf39bSMiao Xie  *     btrfs_attach_transaction_barrier()
692d4edf39bSMiao Xie  */
693354aa0fbSMiao Xie struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
69460376ce4SJosef Bacik {
695575a75d6SAlexandru Moise 	return start_transaction(root, 0, TRANS_ATTACH,
696003d7c59SJeff Mahoney 				 BTRFS_RESERVE_NO_FLUSH, true);
69760376ce4SJosef Bacik }
69860376ce4SJosef Bacik 
699d4edf39bSMiao Xie /*
70090b6d283SWang Sheng-Hui  * btrfs_attach_transaction_barrier() - catch the running transaction
701d4edf39bSMiao Xie  *
702d4edf39bSMiao Xie  * It is similar to the above function, the differentia is this one
703d4edf39bSMiao Xie  * will wait for all the inactive transactions until they fully
704d4edf39bSMiao Xie  * complete.
705d4edf39bSMiao Xie  */
706d4edf39bSMiao Xie struct btrfs_trans_handle *
707d4edf39bSMiao Xie btrfs_attach_transaction_barrier(struct btrfs_root *root)
708d4edf39bSMiao Xie {
709d4edf39bSMiao Xie 	struct btrfs_trans_handle *trans;
710d4edf39bSMiao Xie 
711575a75d6SAlexandru Moise 	trans = start_transaction(root, 0, TRANS_ATTACH,
712003d7c59SJeff Mahoney 				  BTRFS_RESERVE_NO_FLUSH, true);
7138d9e220cSAl Viro 	if (trans == ERR_PTR(-ENOENT))
7142ff7e61eSJeff Mahoney 		btrfs_wait_for_commit(root->fs_info, 0);
715d4edf39bSMiao Xie 
716d4edf39bSMiao Xie 	return trans;
717d4edf39bSMiao Xie }
718d4edf39bSMiao Xie 
719d352ac68SChris Mason /* wait for a transaction commit to be fully complete */
7202ff7e61eSJeff Mahoney static noinline void wait_for_commit(struct btrfs_transaction *commit)
72189ce8a63SChris Mason {
7224a9d8bdeSMiao Xie 	wait_event(commit->commit_wait, commit->state == TRANS_STATE_COMPLETED);
72389ce8a63SChris Mason }
72489ce8a63SChris Mason 
7252ff7e61eSJeff Mahoney int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
72646204592SSage Weil {
72746204592SSage Weil 	struct btrfs_transaction *cur_trans = NULL, *t;
7288cd2807fSMiao Xie 	int ret = 0;
72946204592SSage Weil 
73046204592SSage Weil 	if (transid) {
7310b246afaSJeff Mahoney 		if (transid <= fs_info->last_trans_committed)
732a4abeea4SJosef Bacik 			goto out;
73346204592SSage Weil 
73446204592SSage Weil 		/* find specified transaction */
7350b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
7360b246afaSJeff Mahoney 		list_for_each_entry(t, &fs_info->trans_list, list) {
73746204592SSage Weil 			if (t->transid == transid) {
73846204592SSage Weil 				cur_trans = t;
7399b64f57dSElena Reshetova 				refcount_inc(&cur_trans->use_count);
7408cd2807fSMiao Xie 				ret = 0;
74146204592SSage Weil 				break;
74246204592SSage Weil 			}
7438cd2807fSMiao Xie 			if (t->transid > transid) {
7448cd2807fSMiao Xie 				ret = 0;
74546204592SSage Weil 				break;
74646204592SSage Weil 			}
7478cd2807fSMiao Xie 		}
7480b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
74942383020SSage Weil 
75042383020SSage Weil 		/*
75142383020SSage Weil 		 * The specified transaction doesn't exist, or we
75242383020SSage Weil 		 * raced with btrfs_commit_transaction
75342383020SSage Weil 		 */
75442383020SSage Weil 		if (!cur_trans) {
7550b246afaSJeff Mahoney 			if (transid > fs_info->last_trans_committed)
75642383020SSage Weil 				ret = -EINVAL;
7578cd2807fSMiao Xie 			goto out;
75842383020SSage Weil 		}
75946204592SSage Weil 	} else {
76046204592SSage Weil 		/* find newest transaction that is committing | committed */
7610b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
7620b246afaSJeff Mahoney 		list_for_each_entry_reverse(t, &fs_info->trans_list,
76346204592SSage Weil 					    list) {
7644a9d8bdeSMiao Xie 			if (t->state >= TRANS_STATE_COMMIT_START) {
7654a9d8bdeSMiao Xie 				if (t->state == TRANS_STATE_COMPLETED)
7663473f3c0SJosef Bacik 					break;
76746204592SSage Weil 				cur_trans = t;
7689b64f57dSElena Reshetova 				refcount_inc(&cur_trans->use_count);
76946204592SSage Weil 				break;
77046204592SSage Weil 			}
77146204592SSage Weil 		}
7720b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
77346204592SSage Weil 		if (!cur_trans)
774a4abeea4SJosef Bacik 			goto out;  /* nothing committing|committed */
77546204592SSage Weil 	}
77646204592SSage Weil 
7772ff7e61eSJeff Mahoney 	wait_for_commit(cur_trans);
778724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
779a4abeea4SJosef Bacik out:
78046204592SSage Weil 	return ret;
78146204592SSage Weil }
78246204592SSage Weil 
7832ff7e61eSJeff Mahoney void btrfs_throttle(struct btrfs_fs_info *fs_info)
78437d1aeeeSChris Mason {
7852ff7e61eSJeff Mahoney 	wait_current_trans(fs_info);
78637d1aeeeSChris Mason }
78737d1aeeeSChris Mason 
7882ff7e61eSJeff Mahoney static int should_end_transaction(struct btrfs_trans_handle *trans)
7898929ecfaSYan, Zheng {
7902ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = trans->fs_info;
7910b246afaSJeff Mahoney 
79264403612SJosef Bacik 	if (btrfs_check_space_for_delayed_refs(fs_info))
7931be41b78SJosef Bacik 		return 1;
79436ba022aSJosef Bacik 
7952ff7e61eSJeff Mahoney 	return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
7968929ecfaSYan, Zheng }
7978929ecfaSYan, Zheng 
7983a45bb20SJeff Mahoney int btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
7998929ecfaSYan, Zheng {
8008929ecfaSYan, Zheng 	struct btrfs_transaction *cur_trans = trans->transaction;
8018929ecfaSYan, Zheng 	int updates;
80249b25e05SJeff Mahoney 	int err;
8038929ecfaSYan, Zheng 
804a4abeea4SJosef Bacik 	smp_mb();
8054a9d8bdeSMiao Xie 	if (cur_trans->state >= TRANS_STATE_BLOCKED ||
8064a9d8bdeSMiao Xie 	    cur_trans->delayed_refs.flushing)
8078929ecfaSYan, Zheng 		return 1;
8088929ecfaSYan, Zheng 
8098929ecfaSYan, Zheng 	updates = trans->delayed_ref_updates;
8108929ecfaSYan, Zheng 	trans->delayed_ref_updates = 0;
81149b25e05SJeff Mahoney 	if (updates) {
812c79a70b1SNikolay Borisov 		err = btrfs_run_delayed_refs(trans, updates * 2);
81349b25e05SJeff Mahoney 		if (err) /* Error code will also eval true */
81449b25e05SJeff Mahoney 			return err;
81549b25e05SJeff Mahoney 	}
8168929ecfaSYan, Zheng 
8172ff7e61eSJeff Mahoney 	return should_end_transaction(trans);
8188929ecfaSYan, Zheng }
8198929ecfaSYan, Zheng 
820dc60c525SNikolay Borisov static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
821dc60c525SNikolay Borisov 
8220e34693fSNikolay Borisov {
823dc60c525SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
824dc60c525SNikolay Borisov 
8250e34693fSNikolay Borisov 	if (!trans->block_rsv) {
8260e34693fSNikolay Borisov 		ASSERT(!trans->bytes_reserved);
8270e34693fSNikolay Borisov 		return;
8280e34693fSNikolay Borisov 	}
8290e34693fSNikolay Borisov 
8300e34693fSNikolay Borisov 	if (!trans->bytes_reserved)
8310e34693fSNikolay Borisov 		return;
8320e34693fSNikolay Borisov 
8330e34693fSNikolay Borisov 	ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
8340e34693fSNikolay Borisov 	trace_btrfs_space_reservation(fs_info, "transaction",
8350e34693fSNikolay Borisov 				      trans->transid, trans->bytes_reserved, 0);
8360e34693fSNikolay Borisov 	btrfs_block_rsv_release(fs_info, trans->block_rsv,
8370e34693fSNikolay Borisov 				trans->bytes_reserved);
8380e34693fSNikolay Borisov 	trans->bytes_reserved = 0;
8390e34693fSNikolay Borisov }
8400e34693fSNikolay Borisov 
84189ce8a63SChris Mason static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
8423a45bb20SJeff Mahoney 				   int throttle)
84379154b1bSChris Mason {
8443a45bb20SJeff Mahoney 	struct btrfs_fs_info *info = trans->fs_info;
8458929ecfaSYan, Zheng 	struct btrfs_transaction *cur_trans = trans->transaction;
84631b9655fSJosef Bacik 	u64 transid = trans->transid;
8471be41b78SJosef Bacik 	unsigned long cur = trans->delayed_ref_updates;
848a698d075SMiao Xie 	int lock = (trans->type != TRANS_JOIN_NOLOCK);
8494edc2ca3SDave Jones 	int err = 0;
850a79b7d4bSChris Mason 	int must_run_delayed_refs = 0;
851d6e4a428SChris Mason 
852b50fff81SDavid Sterba 	if (refcount_read(&trans->use_count) > 1) {
853b50fff81SDavid Sterba 		refcount_dec(&trans->use_count);
8542a1eb461SJosef Bacik 		trans->block_rsv = trans->orig_rsv;
8552a1eb461SJosef Bacik 		return 0;
8562a1eb461SJosef Bacik 	}
8572a1eb461SJosef Bacik 
858dc60c525SNikolay Borisov 	btrfs_trans_release_metadata(trans);
8594c13d758SJosef Bacik 	trans->block_rsv = NULL;
860c5567237SArne Jansen 
861ea658badSJosef Bacik 	if (!list_empty(&trans->new_bgs))
8626c686b35SNikolay Borisov 		btrfs_create_pending_block_groups(trans);
863ea658badSJosef Bacik 
864c3e69d58SChris Mason 	trans->delayed_ref_updates = 0;
865a79b7d4bSChris Mason 	if (!trans->sync) {
866a79b7d4bSChris Mason 		must_run_delayed_refs =
8677c861627SLu Fengqi 			btrfs_should_throttle_delayed_refs(trans);
8680a2b2a84SJosef Bacik 		cur = max_t(unsigned long, cur, 32);
869a79b7d4bSChris Mason 
870a79b7d4bSChris Mason 		/*
871a79b7d4bSChris Mason 		 * don't make the caller wait if they are from a NOLOCK
872a79b7d4bSChris Mason 		 * or ATTACH transaction, it will deadlock with commit
873a79b7d4bSChris Mason 		 */
874a79b7d4bSChris Mason 		if (must_run_delayed_refs == 1 &&
875a79b7d4bSChris Mason 		    (trans->type & (__TRANS_JOIN_NOLOCK | __TRANS_ATTACH)))
876a79b7d4bSChris Mason 			must_run_delayed_refs = 2;
87756bec294SChris Mason 	}
878bb721703SChris Mason 
879dc60c525SNikolay Borisov 	btrfs_trans_release_metadata(trans);
8800e721106SJosef Bacik 	trans->block_rsv = NULL;
88156bec294SChris Mason 
882ea658badSJosef Bacik 	if (!list_empty(&trans->new_bgs))
8836c686b35SNikolay Borisov 		btrfs_create_pending_block_groups(trans);
884ea658badSJosef Bacik 
8854fbcdf66SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
8864fbcdf66SFilipe Manana 
88792e2f7e3SNikolay Borisov 	if (lock && should_end_transaction(trans) &&
88820c7bcecSSeraphime Kirkovski 	    READ_ONCE(cur_trans->state) == TRANS_STATE_RUNNING) {
8894a9d8bdeSMiao Xie 		spin_lock(&info->trans_lock);
8904a9d8bdeSMiao Xie 		if (cur_trans->state == TRANS_STATE_RUNNING)
8914a9d8bdeSMiao Xie 			cur_trans->state = TRANS_STATE_BLOCKED;
8924a9d8bdeSMiao Xie 		spin_unlock(&info->trans_lock);
893a4abeea4SJosef Bacik 	}
8948929ecfaSYan, Zheng 
89520c7bcecSSeraphime Kirkovski 	if (lock && READ_ONCE(cur_trans->state) == TRANS_STATE_BLOCKED) {
8963bbb24b2SJosef Bacik 		if (throttle)
8973a45bb20SJeff Mahoney 			return btrfs_commit_transaction(trans);
8983bbb24b2SJosef Bacik 		else
8998929ecfaSYan, Zheng 			wake_up_process(info->transaction_kthread);
9008929ecfaSYan, Zheng 	}
9018929ecfaSYan, Zheng 
9020860adfdSMiao Xie 	if (trans->type & __TRANS_FREEZABLE)
9030b246afaSJeff Mahoney 		sb_end_intwrite(info->sb);
9046df7881aSJosef Bacik 
9058929ecfaSYan, Zheng 	WARN_ON(cur_trans != info->running_transaction);
90613c5a93eSJosef Bacik 	WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
90713c5a93eSJosef Bacik 	atomic_dec(&cur_trans->num_writers);
9080860adfdSMiao Xie 	extwriter_counter_dec(cur_trans, trans->type);
90989ce8a63SChris Mason 
910093258e6SDavid Sterba 	cond_wake_up(&cur_trans->writer_wait);
911724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
9129ed74f2dSJosef Bacik 
9139ed74f2dSJosef Bacik 	if (current->journal_info == trans)
9149ed74f2dSJosef Bacik 		current->journal_info = NULL;
915ab78c84dSChris Mason 
91624bbcf04SYan, Zheng 	if (throttle)
9172ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(info);
91824bbcf04SYan, Zheng 
91949b25e05SJeff Mahoney 	if (trans->aborted ||
9200b246afaSJeff Mahoney 	    test_bit(BTRFS_FS_STATE_ERROR, &info->fs_state)) {
9214e121c06SJosef Bacik 		wake_up_process(info->transaction_kthread);
9224edc2ca3SDave Jones 		err = -EIO;
9234e121c06SJosef Bacik 	}
92449b25e05SJeff Mahoney 
9254edc2ca3SDave Jones 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
926a79b7d4bSChris Mason 	if (must_run_delayed_refs) {
9272ff7e61eSJeff Mahoney 		btrfs_async_run_delayed_refs(info, cur, transid,
928a79b7d4bSChris Mason 					     must_run_delayed_refs == 1);
929a79b7d4bSChris Mason 	}
9304edc2ca3SDave Jones 	return err;
93179154b1bSChris Mason }
93279154b1bSChris Mason 
9333a45bb20SJeff Mahoney int btrfs_end_transaction(struct btrfs_trans_handle *trans)
93489ce8a63SChris Mason {
9353a45bb20SJeff Mahoney 	return __btrfs_end_transaction(trans, 0);
93689ce8a63SChris Mason }
93789ce8a63SChris Mason 
9383a45bb20SJeff Mahoney int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
93989ce8a63SChris Mason {
9403a45bb20SJeff Mahoney 	return __btrfs_end_transaction(trans, 1);
94116cdcec7SMiao Xie }
94216cdcec7SMiao Xie 
943d352ac68SChris Mason /*
944d352ac68SChris Mason  * when btree blocks are allocated, they have some corresponding bits set for
945d352ac68SChris Mason  * them in one of two extent_io trees.  This is used to make sure all of
946690587d1SChris Mason  * those extents are sent to disk but does not wait on them
947d352ac68SChris Mason  */
9482ff7e61eSJeff Mahoney int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
9498cef4e16SYan, Zheng 			       struct extent_io_tree *dirty_pages, int mark)
95079154b1bSChris Mason {
951777e6bd7SChris Mason 	int err = 0;
9527c4452b9SChris Mason 	int werr = 0;
9530b246afaSJeff Mahoney 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
954e6138876SJosef Bacik 	struct extent_state *cached_state = NULL;
955777e6bd7SChris Mason 	u64 start = 0;
9565f39d397SChris Mason 	u64 end;
9577c4452b9SChris Mason 
9586300463bSLiu Bo 	atomic_inc(&BTRFS_I(fs_info->btree_inode)->sync_writers);
9591728366eSJosef Bacik 	while (!find_first_extent_bit(dirty_pages, start, &start, &end,
960e6138876SJosef Bacik 				      mark, &cached_state)) {
961663dfbb0SFilipe Manana 		bool wait_writeback = false;
962663dfbb0SFilipe Manana 
963663dfbb0SFilipe Manana 		err = convert_extent_bit(dirty_pages, start, end,
964663dfbb0SFilipe Manana 					 EXTENT_NEED_WAIT,
965210aa277SDavid Sterba 					 mark, &cached_state);
966663dfbb0SFilipe Manana 		/*
967663dfbb0SFilipe Manana 		 * convert_extent_bit can return -ENOMEM, which is most of the
968663dfbb0SFilipe Manana 		 * time a temporary error. So when it happens, ignore the error
969663dfbb0SFilipe Manana 		 * and wait for writeback of this range to finish - because we
970663dfbb0SFilipe Manana 		 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
971bf89d38fSJeff Mahoney 		 * to __btrfs_wait_marked_extents() would not know that
972bf89d38fSJeff Mahoney 		 * writeback for this range started and therefore wouldn't
973bf89d38fSJeff Mahoney 		 * wait for it to finish - we don't want to commit a
974bf89d38fSJeff Mahoney 		 * superblock that points to btree nodes/leafs for which
975bf89d38fSJeff Mahoney 		 * writeback hasn't finished yet (and without errors).
976663dfbb0SFilipe Manana 		 * We cleanup any entries left in the io tree when committing
977663dfbb0SFilipe Manana 		 * the transaction (through clear_btree_io_tree()).
978663dfbb0SFilipe Manana 		 */
979663dfbb0SFilipe Manana 		if (err == -ENOMEM) {
980663dfbb0SFilipe Manana 			err = 0;
981663dfbb0SFilipe Manana 			wait_writeback = true;
982663dfbb0SFilipe Manana 		}
983663dfbb0SFilipe Manana 		if (!err)
9841728366eSJosef Bacik 			err = filemap_fdatawrite_range(mapping, start, end);
9857c4452b9SChris Mason 		if (err)
9867c4452b9SChris Mason 			werr = err;
987663dfbb0SFilipe Manana 		else if (wait_writeback)
988663dfbb0SFilipe Manana 			werr = filemap_fdatawait_range(mapping, start, end);
989e38e2ed7SFilipe Manana 		free_extent_state(cached_state);
990663dfbb0SFilipe Manana 		cached_state = NULL;
9911728366eSJosef Bacik 		cond_resched();
9921728366eSJosef Bacik 		start = end + 1;
9937c4452b9SChris Mason 	}
9946300463bSLiu Bo 	atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
995690587d1SChris Mason 	return werr;
996690587d1SChris Mason }
997690587d1SChris Mason 
998690587d1SChris Mason /*
999690587d1SChris Mason  * when btree blocks are allocated, they have some corresponding bits set for
1000690587d1SChris Mason  * them in one of two extent_io trees.  This is used to make sure all of
1001690587d1SChris Mason  * those extents are on disk for transaction or log commit.  We wait
1002690587d1SChris Mason  * on all the pages and clear them from the dirty pages state tree
1003690587d1SChris Mason  */
1004bf89d38fSJeff Mahoney static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
1005bf89d38fSJeff Mahoney 				       struct extent_io_tree *dirty_pages)
1006690587d1SChris Mason {
1007690587d1SChris Mason 	int err = 0;
1008690587d1SChris Mason 	int werr = 0;
10090b246afaSJeff Mahoney 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
1010e6138876SJosef Bacik 	struct extent_state *cached_state = NULL;
1011690587d1SChris Mason 	u64 start = 0;
1012690587d1SChris Mason 	u64 end;
1013690587d1SChris Mason 
10141728366eSJosef Bacik 	while (!find_first_extent_bit(dirty_pages, start, &start, &end,
1015e6138876SJosef Bacik 				      EXTENT_NEED_WAIT, &cached_state)) {
1016663dfbb0SFilipe Manana 		/*
1017663dfbb0SFilipe Manana 		 * Ignore -ENOMEM errors returned by clear_extent_bit().
1018663dfbb0SFilipe Manana 		 * When committing the transaction, we'll remove any entries
1019663dfbb0SFilipe Manana 		 * left in the io tree. For a log commit, we don't remove them
1020663dfbb0SFilipe Manana 		 * after committing the log because the tree can be accessed
1021663dfbb0SFilipe Manana 		 * concurrently - we do it only at transaction commit time when
1022663dfbb0SFilipe Manana 		 * it's safe to do it (through clear_btree_io_tree()).
1023663dfbb0SFilipe Manana 		 */
1024663dfbb0SFilipe Manana 		err = clear_extent_bit(dirty_pages, start, end,
1025ae0f1625SDavid Sterba 				       EXTENT_NEED_WAIT, 0, 0, &cached_state);
1026663dfbb0SFilipe Manana 		if (err == -ENOMEM)
1027663dfbb0SFilipe Manana 			err = 0;
1028663dfbb0SFilipe Manana 		if (!err)
10291728366eSJosef Bacik 			err = filemap_fdatawait_range(mapping, start, end);
1030777e6bd7SChris Mason 		if (err)
1031777e6bd7SChris Mason 			werr = err;
1032e38e2ed7SFilipe Manana 		free_extent_state(cached_state);
1033e38e2ed7SFilipe Manana 		cached_state = NULL;
1034777e6bd7SChris Mason 		cond_resched();
10351728366eSJosef Bacik 		start = end + 1;
1036777e6bd7SChris Mason 	}
10377c4452b9SChris Mason 	if (err)
10387c4452b9SChris Mason 		werr = err;
1039bf89d38fSJeff Mahoney 	return werr;
1040bf89d38fSJeff Mahoney }
1041656f30dbSFilipe Manana 
1042bf89d38fSJeff Mahoney int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1043bf89d38fSJeff Mahoney 		       struct extent_io_tree *dirty_pages)
1044bf89d38fSJeff Mahoney {
1045bf89d38fSJeff Mahoney 	bool errors = false;
1046bf89d38fSJeff Mahoney 	int err;
1047bf89d38fSJeff Mahoney 
1048bf89d38fSJeff Mahoney 	err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1049bf89d38fSJeff Mahoney 	if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1050bf89d38fSJeff Mahoney 		errors = true;
1051bf89d38fSJeff Mahoney 
1052bf89d38fSJeff Mahoney 	if (errors && !err)
1053bf89d38fSJeff Mahoney 		err = -EIO;
1054bf89d38fSJeff Mahoney 	return err;
1055bf89d38fSJeff Mahoney }
1056bf89d38fSJeff Mahoney 
1057bf89d38fSJeff Mahoney int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1058bf89d38fSJeff Mahoney {
1059bf89d38fSJeff Mahoney 	struct btrfs_fs_info *fs_info = log_root->fs_info;
1060bf89d38fSJeff Mahoney 	struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1061bf89d38fSJeff Mahoney 	bool errors = false;
1062bf89d38fSJeff Mahoney 	int err;
1063bf89d38fSJeff Mahoney 
1064bf89d38fSJeff Mahoney 	ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1065bf89d38fSJeff Mahoney 
1066bf89d38fSJeff Mahoney 	err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1067656f30dbSFilipe Manana 	if ((mark & EXTENT_DIRTY) &&
10680b246afaSJeff Mahoney 	    test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1069656f30dbSFilipe Manana 		errors = true;
1070656f30dbSFilipe Manana 
1071656f30dbSFilipe Manana 	if ((mark & EXTENT_NEW) &&
10720b246afaSJeff Mahoney 	    test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1073656f30dbSFilipe Manana 		errors = true;
1074656f30dbSFilipe Manana 
1075bf89d38fSJeff Mahoney 	if (errors && !err)
1076bf89d38fSJeff Mahoney 		err = -EIO;
1077bf89d38fSJeff Mahoney 	return err;
107879154b1bSChris Mason }
107979154b1bSChris Mason 
1080690587d1SChris Mason /*
1081c9b577c0SNikolay Borisov  * When btree blocks are allocated the corresponding extents are marked dirty.
1082c9b577c0SNikolay Borisov  * This function ensures such extents are persisted on disk for transaction or
1083c9b577c0SNikolay Borisov  * log commit.
1084c9b577c0SNikolay Borisov  *
1085c9b577c0SNikolay Borisov  * @trans: transaction whose dirty pages we'd like to write
1086690587d1SChris Mason  */
108770458a58SNikolay Borisov static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1088d0c803c4SChris Mason {
1089663dfbb0SFilipe Manana 	int ret;
1090c9b577c0SNikolay Borisov 	int ret2;
1091c9b577c0SNikolay Borisov 	struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
109270458a58SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
1093c9b577c0SNikolay Borisov 	struct blk_plug plug;
1094663dfbb0SFilipe Manana 
1095c9b577c0SNikolay Borisov 	blk_start_plug(&plug);
1096c9b577c0SNikolay Borisov 	ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1097c9b577c0SNikolay Borisov 	blk_finish_plug(&plug);
1098c9b577c0SNikolay Borisov 	ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1099c9b577c0SNikolay Borisov 
1100663dfbb0SFilipe Manana 	clear_btree_io_tree(&trans->transaction->dirty_pages);
1101663dfbb0SFilipe Manana 
1102c9b577c0SNikolay Borisov 	if (ret)
1103663dfbb0SFilipe Manana 		return ret;
1104c9b577c0SNikolay Borisov 	else if (ret2)
1105c9b577c0SNikolay Borisov 		return ret2;
1106c9b577c0SNikolay Borisov 	else
1107c9b577c0SNikolay Borisov 		return 0;
1108d0c803c4SChris Mason }
1109d0c803c4SChris Mason 
1110d352ac68SChris Mason /*
1111d352ac68SChris Mason  * this is used to update the root pointer in the tree of tree roots.
1112d352ac68SChris Mason  *
1113d352ac68SChris Mason  * But, in the case of the extent allocation tree, updating the root
1114d352ac68SChris Mason  * pointer may allocate blocks which may change the root of the extent
1115d352ac68SChris Mason  * allocation tree.
1116d352ac68SChris Mason  *
1117d352ac68SChris Mason  * So, this loops and repeats and makes sure the cowonly root didn't
1118d352ac68SChris Mason  * change while the root pointer was being updated in the metadata.
1119d352ac68SChris Mason  */
11200b86a832SChris Mason static int update_cowonly_root(struct btrfs_trans_handle *trans,
112179154b1bSChris Mason 			       struct btrfs_root *root)
112279154b1bSChris Mason {
112379154b1bSChris Mason 	int ret;
11240b86a832SChris Mason 	u64 old_root_bytenr;
112586b9f2ecSYan, Zheng 	u64 old_root_used;
11260b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11270b246afaSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
112879154b1bSChris Mason 
112986b9f2ecSYan, Zheng 	old_root_used = btrfs_root_used(&root->root_item);
113056bec294SChris Mason 
113179154b1bSChris Mason 	while (1) {
11320b86a832SChris Mason 		old_root_bytenr = btrfs_root_bytenr(&root->root_item);
113386b9f2ecSYan, Zheng 		if (old_root_bytenr == root->node->start &&
1134ea526d18SJosef Bacik 		    old_root_used == btrfs_root_used(&root->root_item))
113579154b1bSChris Mason 			break;
113687ef2bb4SChris Mason 
11375d4f98a2SYan Zheng 		btrfs_set_root_node(&root->root_item, root->node);
113879154b1bSChris Mason 		ret = btrfs_update_root(trans, tree_root,
11390b86a832SChris Mason 					&root->root_key,
11400b86a832SChris Mason 					&root->root_item);
114149b25e05SJeff Mahoney 		if (ret)
114249b25e05SJeff Mahoney 			return ret;
114356bec294SChris Mason 
114486b9f2ecSYan, Zheng 		old_root_used = btrfs_root_used(&root->root_item);
1145e7070be1SJosef Bacik 	}
1146276e680dSYan Zheng 
11470b86a832SChris Mason 	return 0;
11480b86a832SChris Mason }
11490b86a832SChris Mason 
1150d352ac68SChris Mason /*
1151d352ac68SChris Mason  * update all the cowonly tree roots on disk
115249b25e05SJeff Mahoney  *
115349b25e05SJeff Mahoney  * The error handling in this function may not be obvious. Any of the
115449b25e05SJeff Mahoney  * failures will cause the file system to go offline. We still need
115549b25e05SJeff Mahoney  * to clean up the delayed refs.
1156d352ac68SChris Mason  */
11579386d8bcSNikolay Borisov static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
11580b86a832SChris Mason {
11599386d8bcSNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
1160ea526d18SJosef Bacik 	struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
11611bbc621eSChris Mason 	struct list_head *io_bgs = &trans->transaction->io_bgs;
11620b86a832SChris Mason 	struct list_head *next;
116384234f3aSYan Zheng 	struct extent_buffer *eb;
116456bec294SChris Mason 	int ret;
116584234f3aSYan Zheng 
116684234f3aSYan Zheng 	eb = btrfs_lock_root_node(fs_info->tree_root);
116749b25e05SJeff Mahoney 	ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
116849b25e05SJeff Mahoney 			      0, &eb);
116984234f3aSYan Zheng 	btrfs_tree_unlock(eb);
117084234f3aSYan Zheng 	free_extent_buffer(eb);
11710b86a832SChris Mason 
117249b25e05SJeff Mahoney 	if (ret)
117349b25e05SJeff Mahoney 		return ret;
117449b25e05SJeff Mahoney 
1175c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
117649b25e05SJeff Mahoney 	if (ret)
117749b25e05SJeff Mahoney 		return ret;
117887ef2bb4SChris Mason 
11790b246afaSJeff Mahoney 	ret = btrfs_run_dev_stats(trans, fs_info);
1180c16ce190SJosef Bacik 	if (ret)
1181c16ce190SJosef Bacik 		return ret;
11820b246afaSJeff Mahoney 	ret = btrfs_run_dev_replace(trans, fs_info);
1183c16ce190SJosef Bacik 	if (ret)
1184c16ce190SJosef Bacik 		return ret;
1185280f8bd2SLu Fengqi 	ret = btrfs_run_qgroups(trans);
1186c16ce190SJosef Bacik 	if (ret)
1187c16ce190SJosef Bacik 		return ret;
1188546adb0dSJan Schmidt 
11892ff7e61eSJeff Mahoney 	ret = btrfs_setup_space_cache(trans, fs_info);
1190dcdf7f6dSJosef Bacik 	if (ret)
1191dcdf7f6dSJosef Bacik 		return ret;
1192dcdf7f6dSJosef Bacik 
1193546adb0dSJan Schmidt 	/* run_qgroups might have added some more refs */
1194c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1195c16ce190SJosef Bacik 	if (ret)
1196c16ce190SJosef Bacik 		return ret;
1197ea526d18SJosef Bacik again:
11980b86a832SChris Mason 	while (!list_empty(&fs_info->dirty_cowonly_roots)) {
11992ff7e61eSJeff Mahoney 		struct btrfs_root *root;
12000b86a832SChris Mason 		next = fs_info->dirty_cowonly_roots.next;
12010b86a832SChris Mason 		list_del_init(next);
12020b86a832SChris Mason 		root = list_entry(next, struct btrfs_root, dirty_list);
1203e7070be1SJosef Bacik 		clear_bit(BTRFS_ROOT_DIRTY, &root->state);
120487ef2bb4SChris Mason 
12059e351cc8SJosef Bacik 		if (root != fs_info->extent_root)
12069e351cc8SJosef Bacik 			list_add_tail(&root->dirty_list,
12079e351cc8SJosef Bacik 				      &trans->transaction->switch_commits);
120849b25e05SJeff Mahoney 		ret = update_cowonly_root(trans, root);
120949b25e05SJeff Mahoney 		if (ret)
121049b25e05SJeff Mahoney 			return ret;
1211c79a70b1SNikolay Borisov 		ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1212ea526d18SJosef Bacik 		if (ret)
1213ea526d18SJosef Bacik 			return ret;
121479154b1bSChris Mason 	}
1215276e680dSYan Zheng 
12161bbc621eSChris Mason 	while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
12172ff7e61eSJeff Mahoney 		ret = btrfs_write_dirty_block_groups(trans, fs_info);
1218ea526d18SJosef Bacik 		if (ret)
1219ea526d18SJosef Bacik 			return ret;
1220c79a70b1SNikolay Borisov 		ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1221ea526d18SJosef Bacik 		if (ret)
1222ea526d18SJosef Bacik 			return ret;
1223ea526d18SJosef Bacik 	}
1224ea526d18SJosef Bacik 
1225ea526d18SJosef Bacik 	if (!list_empty(&fs_info->dirty_cowonly_roots))
1226ea526d18SJosef Bacik 		goto again;
1227ea526d18SJosef Bacik 
12289e351cc8SJosef Bacik 	list_add_tail(&fs_info->extent_root->dirty_list,
12299e351cc8SJosef Bacik 		      &trans->transaction->switch_commits);
12309f6cbcbbSDavid Sterba 
12319f6cbcbbSDavid Sterba 	/* Update dev-replace pointer once everything is committed */
12329f6cbcbbSDavid Sterba 	fs_info->dev_replace.committed_cursor_left =
12339f6cbcbbSDavid Sterba 		fs_info->dev_replace.cursor_left_last_write_of_item;
12348dabb742SStefan Behrens 
123579154b1bSChris Mason 	return 0;
123679154b1bSChris Mason }
123779154b1bSChris Mason 
1238d352ac68SChris Mason /*
1239d352ac68SChris Mason  * dead roots are old snapshots that need to be deleted.  This allocates
1240d352ac68SChris Mason  * a dirty root struct and adds it into the list of dead roots that need to
1241d352ac68SChris Mason  * be deleted
1242d352ac68SChris Mason  */
1243cfad392bSJosef Bacik void btrfs_add_dead_root(struct btrfs_root *root)
12445eda7b5eSChris Mason {
12450b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12460b246afaSJeff Mahoney 
12470b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
1248cfad392bSJosef Bacik 	if (list_empty(&root->root_list))
12490b246afaSJeff Mahoney 		list_add_tail(&root->root_list, &fs_info->dead_roots);
12500b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
12515eda7b5eSChris Mason }
12525eda7b5eSChris Mason 
1253d352ac68SChris Mason /*
12545d4f98a2SYan Zheng  * update all the cowonly tree roots on disk
1255d352ac68SChris Mason  */
12567e4443d9SNikolay Borisov static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
12570f7d52f4SChris Mason {
12587e4443d9SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
12590f7d52f4SChris Mason 	struct btrfs_root *gang[8];
12600f7d52f4SChris Mason 	int i;
12610f7d52f4SChris Mason 	int ret;
126254aa1f4dSChris Mason 	int err = 0;
126354aa1f4dSChris Mason 
1264a4abeea4SJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
12650f7d52f4SChris Mason 	while (1) {
12665d4f98a2SYan Zheng 		ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
12675d4f98a2SYan Zheng 						 (void **)gang, 0,
12680f7d52f4SChris Mason 						 ARRAY_SIZE(gang),
12690f7d52f4SChris Mason 						 BTRFS_ROOT_TRANS_TAG);
12700f7d52f4SChris Mason 		if (ret == 0)
12710f7d52f4SChris Mason 			break;
12720f7d52f4SChris Mason 		for (i = 0; i < ret; i++) {
12735b4aacefSJeff Mahoney 			struct btrfs_root *root = gang[i];
12745d4f98a2SYan Zheng 			radix_tree_tag_clear(&fs_info->fs_roots_radix,
12752619ba1fSChris Mason 					(unsigned long)root->root_key.objectid,
12760f7d52f4SChris Mason 					BTRFS_ROOT_TRANS_TAG);
1277a4abeea4SJosef Bacik 			spin_unlock(&fs_info->fs_roots_radix_lock);
127831153d81SYan Zheng 
1279e02119d5SChris Mason 			btrfs_free_log(trans, root);
12805d4f98a2SYan Zheng 			btrfs_update_reloc_root(trans, root);
1281e02119d5SChris Mason 
128282d5902dSLi Zefan 			btrfs_save_ino_cache(root, trans);
128382d5902dSLi Zefan 
1284f1ebcc74SLiu Bo 			/* see comments in should_cow_block() */
128527cdeb70SMiao Xie 			clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1286c7548af6SChris Mason 			smp_mb__after_atomic();
1287f1ebcc74SLiu Bo 
1288978d910dSYan Zheng 			if (root->commit_root != root->node) {
12899e351cc8SJosef Bacik 				list_add_tail(&root->dirty_list,
12909e351cc8SJosef Bacik 					&trans->transaction->switch_commits);
1291978d910dSYan Zheng 				btrfs_set_root_node(&root->root_item,
1292978d910dSYan Zheng 						    root->node);
1293978d910dSYan Zheng 			}
129431153d81SYan Zheng 
12955d4f98a2SYan Zheng 			err = btrfs_update_root(trans, fs_info->tree_root,
12960f7d52f4SChris Mason 						&root->root_key,
12970f7d52f4SChris Mason 						&root->root_item);
1298a4abeea4SJosef Bacik 			spin_lock(&fs_info->fs_roots_radix_lock);
129954aa1f4dSChris Mason 			if (err)
130054aa1f4dSChris Mason 				break;
1301733e03a0SQu Wenruo 			btrfs_qgroup_free_meta_all_pertrans(root);
13020f7d52f4SChris Mason 		}
13039f3a7427SChris Mason 	}
1304a4abeea4SJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
130554aa1f4dSChris Mason 	return err;
13060f7d52f4SChris Mason }
13070f7d52f4SChris Mason 
1308d352ac68SChris Mason /*
1309de78b51aSEric Sandeen  * defrag a given btree.
1310de78b51aSEric Sandeen  * Every leaf in the btree is read and defragged.
1311d352ac68SChris Mason  */
1312de78b51aSEric Sandeen int btrfs_defrag_root(struct btrfs_root *root)
1313e9d0b13bSChris Mason {
1314e9d0b13bSChris Mason 	struct btrfs_fs_info *info = root->fs_info;
1315e9d0b13bSChris Mason 	struct btrfs_trans_handle *trans;
13168929ecfaSYan, Zheng 	int ret;
1317e9d0b13bSChris Mason 
131827cdeb70SMiao Xie 	if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1319e9d0b13bSChris Mason 		return 0;
13208929ecfaSYan, Zheng 
13216b80053dSChris Mason 	while (1) {
13228929ecfaSYan, Zheng 		trans = btrfs_start_transaction(root, 0);
13238929ecfaSYan, Zheng 		if (IS_ERR(trans))
13248929ecfaSYan, Zheng 			return PTR_ERR(trans);
13258929ecfaSYan, Zheng 
1326de78b51aSEric Sandeen 		ret = btrfs_defrag_leaves(trans, root);
13278929ecfaSYan, Zheng 
13283a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
13292ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(info);
1330e9d0b13bSChris Mason 		cond_resched();
1331e9d0b13bSChris Mason 
1332ab8d0fc4SJeff Mahoney 		if (btrfs_fs_closing(info) || ret != -EAGAIN)
1333e9d0b13bSChris Mason 			break;
1334210549ebSDavid Sterba 
1335ab8d0fc4SJeff Mahoney 		if (btrfs_defrag_cancelled(info)) {
1336ab8d0fc4SJeff Mahoney 			btrfs_debug(info, "defrag_root cancelled");
1337210549ebSDavid Sterba 			ret = -EAGAIN;
1338210549ebSDavid Sterba 			break;
1339210549ebSDavid Sterba 		}
1340e9d0b13bSChris Mason 	}
134127cdeb70SMiao Xie 	clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
13428929ecfaSYan, Zheng 	return ret;
1343e9d0b13bSChris Mason }
1344e9d0b13bSChris Mason 
1345d352ac68SChris Mason /*
13466426c7adSQu Wenruo  * Do all special snapshot related qgroup dirty hack.
13476426c7adSQu Wenruo  *
13486426c7adSQu Wenruo  * Will do all needed qgroup inherit and dirty hack like switch commit
13496426c7adSQu Wenruo  * roots inside one transaction and write all btree into disk, to make
13506426c7adSQu Wenruo  * qgroup works.
13516426c7adSQu Wenruo  */
13526426c7adSQu Wenruo static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
13536426c7adSQu Wenruo 				   struct btrfs_root *src,
13546426c7adSQu Wenruo 				   struct btrfs_root *parent,
13556426c7adSQu Wenruo 				   struct btrfs_qgroup_inherit *inherit,
13566426c7adSQu Wenruo 				   u64 dst_objectid)
13576426c7adSQu Wenruo {
13586426c7adSQu Wenruo 	struct btrfs_fs_info *fs_info = src->fs_info;
13596426c7adSQu Wenruo 	int ret;
13606426c7adSQu Wenruo 
13616426c7adSQu Wenruo 	/*
13626426c7adSQu Wenruo 	 * Save some performance in the case that qgroups are not
13636426c7adSQu Wenruo 	 * enabled. If this check races with the ioctl, rescan will
13646426c7adSQu Wenruo 	 * kick in anyway.
13656426c7adSQu Wenruo 	 */
13669ea6e2b5SDavid Sterba 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
13676426c7adSQu Wenruo 		return 0;
13686426c7adSQu Wenruo 
13696426c7adSQu Wenruo 	/*
13704d31778aSQu Wenruo 	 * Ensure dirty @src will be commited.  Or, after comming
13714d31778aSQu Wenruo 	 * commit_fs_roots() and switch_commit_roots(), any dirty but not
13724d31778aSQu Wenruo 	 * recorded root will never be updated again, causing an outdated root
13734d31778aSQu Wenruo 	 * item.
13744d31778aSQu Wenruo 	 */
13754d31778aSQu Wenruo 	record_root_in_trans(trans, src, 1);
13764d31778aSQu Wenruo 
13774d31778aSQu Wenruo 	/*
13786426c7adSQu Wenruo 	 * We are going to commit transaction, see btrfs_commit_transaction()
13796426c7adSQu Wenruo 	 * comment for reason locking tree_log_mutex
13806426c7adSQu Wenruo 	 */
13816426c7adSQu Wenruo 	mutex_lock(&fs_info->tree_log_mutex);
13826426c7adSQu Wenruo 
13837e4443d9SNikolay Borisov 	ret = commit_fs_roots(trans);
13846426c7adSQu Wenruo 	if (ret)
13856426c7adSQu Wenruo 		goto out;
1386460fb20aSNikolay Borisov 	ret = btrfs_qgroup_account_extents(trans);
13876426c7adSQu Wenruo 	if (ret < 0)
13886426c7adSQu Wenruo 		goto out;
13896426c7adSQu Wenruo 
13906426c7adSQu Wenruo 	/* Now qgroup are all updated, we can inherit it to new qgroups */
1391a9377422SLu Fengqi 	ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
13926426c7adSQu Wenruo 				   inherit);
13936426c7adSQu Wenruo 	if (ret < 0)
13946426c7adSQu Wenruo 		goto out;
13956426c7adSQu Wenruo 
13966426c7adSQu Wenruo 	/*
13976426c7adSQu Wenruo 	 * Now we do a simplified commit transaction, which will:
13986426c7adSQu Wenruo 	 * 1) commit all subvolume and extent tree
13996426c7adSQu Wenruo 	 *    To ensure all subvolume and extent tree have a valid
14006426c7adSQu Wenruo 	 *    commit_root to accounting later insert_dir_item()
14016426c7adSQu Wenruo 	 * 2) write all btree blocks onto disk
14026426c7adSQu Wenruo 	 *    This is to make sure later btree modification will be cowed
14036426c7adSQu Wenruo 	 *    Or commit_root can be populated and cause wrong qgroup numbers
14046426c7adSQu Wenruo 	 * In this simplified commit, we don't really care about other trees
14056426c7adSQu Wenruo 	 * like chunk and root tree, as they won't affect qgroup.
14066426c7adSQu Wenruo 	 * And we don't write super to avoid half committed status.
14076426c7adSQu Wenruo 	 */
14089386d8bcSNikolay Borisov 	ret = commit_cowonly_roots(trans);
14096426c7adSQu Wenruo 	if (ret)
14106426c7adSQu Wenruo 		goto out;
141116916a88SNikolay Borisov 	switch_commit_roots(trans->transaction);
141270458a58SNikolay Borisov 	ret = btrfs_write_and_wait_transaction(trans);
14136426c7adSQu Wenruo 	if (ret)
1414f7af3934SDavid Sterba 		btrfs_handle_fs_error(fs_info, ret,
14156426c7adSQu Wenruo 			"Error while writing out transaction for qgroup");
14166426c7adSQu Wenruo 
14176426c7adSQu Wenruo out:
14186426c7adSQu Wenruo 	mutex_unlock(&fs_info->tree_log_mutex);
14196426c7adSQu Wenruo 
14206426c7adSQu Wenruo 	/*
14216426c7adSQu Wenruo 	 * Force parent root to be updated, as we recorded it before so its
14226426c7adSQu Wenruo 	 * last_trans == cur_transid.
14236426c7adSQu Wenruo 	 * Or it won't be committed again onto disk after later
14246426c7adSQu Wenruo 	 * insert_dir_item()
14256426c7adSQu Wenruo 	 */
14266426c7adSQu Wenruo 	if (!ret)
14276426c7adSQu Wenruo 		record_root_in_trans(trans, parent, 1);
14286426c7adSQu Wenruo 	return ret;
14296426c7adSQu Wenruo }
14306426c7adSQu Wenruo 
14316426c7adSQu Wenruo /*
1432d352ac68SChris Mason  * new snapshots need to be created at a very specific time in the
1433aec8030aSMiao Xie  * transaction commit.  This does the actual creation.
1434aec8030aSMiao Xie  *
1435aec8030aSMiao Xie  * Note:
1436aec8030aSMiao Xie  * If the error which may affect the commitment of the current transaction
1437aec8030aSMiao Xie  * happens, we should return the error number. If the error which just affect
1438aec8030aSMiao Xie  * the creation of the pending snapshots, just return 0.
1439d352ac68SChris Mason  */
144080b6794dSChris Mason static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
14413063d29fSChris Mason 				   struct btrfs_pending_snapshot *pending)
14423063d29fSChris Mason {
144308d50ca3SNikolay Borisov 
144408d50ca3SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
14453063d29fSChris Mason 	struct btrfs_key key;
144680b6794dSChris Mason 	struct btrfs_root_item *new_root_item;
14473063d29fSChris Mason 	struct btrfs_root *tree_root = fs_info->tree_root;
14483063d29fSChris Mason 	struct btrfs_root *root = pending->root;
14496bdb72deSSage Weil 	struct btrfs_root *parent_root;
145098c9942aSLiu Bo 	struct btrfs_block_rsv *rsv;
14516bdb72deSSage Weil 	struct inode *parent_inode;
145242874b3dSMiao Xie 	struct btrfs_path *path;
145342874b3dSMiao Xie 	struct btrfs_dir_item *dir_item;
1454a22285a6SYan, Zheng 	struct dentry *dentry;
14553063d29fSChris Mason 	struct extent_buffer *tmp;
1456925baeddSChris Mason 	struct extent_buffer *old;
145795582b00SDeepa Dinamani 	struct timespec64 cur_time;
1458aec8030aSMiao Xie 	int ret = 0;
1459d68fc57bSYan, Zheng 	u64 to_reserve = 0;
14606bdb72deSSage Weil 	u64 index = 0;
1461a22285a6SYan, Zheng 	u64 objectid;
1462b83cc969SLi Zefan 	u64 root_flags;
14638ea05e3aSAlexander Block 	uuid_le new_uuid;
14643063d29fSChris Mason 
14658546b570SDavid Sterba 	ASSERT(pending->path);
14668546b570SDavid Sterba 	path = pending->path;
146742874b3dSMiao Xie 
1468b0c0ea63SDavid Sterba 	ASSERT(pending->root_item);
1469b0c0ea63SDavid Sterba 	new_root_item = pending->root_item;
1470a22285a6SYan, Zheng 
1471aec8030aSMiao Xie 	pending->error = btrfs_find_free_objectid(tree_root, &objectid);
1472aec8030aSMiao Xie 	if (pending->error)
14736fa9700eSMiao Xie 		goto no_free_objectid;
14743063d29fSChris Mason 
1475d6726335SQu Wenruo 	/*
1476d6726335SQu Wenruo 	 * Make qgroup to skip current new snapshot's qgroupid, as it is
1477d6726335SQu Wenruo 	 * accounted by later btrfs_qgroup_inherit().
1478d6726335SQu Wenruo 	 */
1479d6726335SQu Wenruo 	btrfs_set_skip_qgroup(trans, objectid);
1480d6726335SQu Wenruo 
1481147d256eSZhaolei 	btrfs_reloc_pre_snapshot(pending, &to_reserve);
1482d68fc57bSYan, Zheng 
1483d68fc57bSYan, Zheng 	if (to_reserve > 0) {
1484aec8030aSMiao Xie 		pending->error = btrfs_block_rsv_add(root,
1485aec8030aSMiao Xie 						     &pending->block_rsv,
148608e007d2SMiao Xie 						     to_reserve,
148708e007d2SMiao Xie 						     BTRFS_RESERVE_NO_FLUSH);
1488aec8030aSMiao Xie 		if (pending->error)
1489d6726335SQu Wenruo 			goto clear_skip_qgroup;
1490d68fc57bSYan, Zheng 	}
1491d68fc57bSYan, Zheng 
14923063d29fSChris Mason 	key.objectid = objectid;
1493a22285a6SYan, Zheng 	key.offset = (u64)-1;
1494a22285a6SYan, Zheng 	key.type = BTRFS_ROOT_ITEM_KEY;
14953063d29fSChris Mason 
14966fa9700eSMiao Xie 	rsv = trans->block_rsv;
1497a22285a6SYan, Zheng 	trans->block_rsv = &pending->block_rsv;
14982382c5ccSLiu Bo 	trans->bytes_reserved = trans->block_rsv->reserved;
14990b246afaSJeff Mahoney 	trace_btrfs_space_reservation(fs_info, "transaction",
150088d3a5aaSJosef Bacik 				      trans->transid,
150188d3a5aaSJosef Bacik 				      trans->bytes_reserved, 1);
1502a22285a6SYan, Zheng 	dentry = pending->dentry;
1503e9662f70SMiao Xie 	parent_inode = pending->dir;
1504a22285a6SYan, Zheng 	parent_root = BTRFS_I(parent_inode)->root;
15056426c7adSQu Wenruo 	record_root_in_trans(trans, parent_root, 0);
1506a22285a6SYan, Zheng 
1507c2050a45SDeepa Dinamani 	cur_time = current_time(parent_inode);
150804b285f3SDeepa Dinamani 
15096bdb72deSSage Weil 	/*
15106bdb72deSSage Weil 	 * insert the directory item
15116bdb72deSSage Weil 	 */
1512877574e2SNikolay Borisov 	ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
151349b25e05SJeff Mahoney 	BUG_ON(ret); /* -ENOMEM */
151442874b3dSMiao Xie 
151542874b3dSMiao Xie 	/* check if there is a file/dir which has the same name. */
151642874b3dSMiao Xie 	dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
15174a0cc7caSNikolay Borisov 					 btrfs_ino(BTRFS_I(parent_inode)),
151842874b3dSMiao Xie 					 dentry->d_name.name,
151942874b3dSMiao Xie 					 dentry->d_name.len, 0);
152042874b3dSMiao Xie 	if (dir_item != NULL && !IS_ERR(dir_item)) {
1521fe66a05aSChris Mason 		pending->error = -EEXIST;
1522aec8030aSMiao Xie 		goto dir_item_existed;
152342874b3dSMiao Xie 	} else if (IS_ERR(dir_item)) {
152442874b3dSMiao Xie 		ret = PTR_ERR(dir_item);
152566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15268732d44fSMiao Xie 		goto fail;
152779787eaaSJeff Mahoney 	}
152842874b3dSMiao Xie 	btrfs_release_path(path);
15296bdb72deSSage Weil 
1530e999376fSChris Mason 	/*
1531e999376fSChris Mason 	 * pull in the delayed directory update
1532e999376fSChris Mason 	 * and the delayed inode item
1533e999376fSChris Mason 	 * otherwise we corrupt the FS during
1534e999376fSChris Mason 	 * snapshot
1535e999376fSChris Mason 	 */
1536e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
15378732d44fSMiao Xie 	if (ret) {	/* Transaction aborted */
153866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15398732d44fSMiao Xie 		goto fail;
15408732d44fSMiao Xie 	}
1541e999376fSChris Mason 
15426426c7adSQu Wenruo 	record_root_in_trans(trans, root, 0);
15436bdb72deSSage Weil 	btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
15446bdb72deSSage Weil 	memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
154508fe4db1SLi Zefan 	btrfs_check_and_init_root_item(new_root_item);
15466bdb72deSSage Weil 
1547b83cc969SLi Zefan 	root_flags = btrfs_root_flags(new_root_item);
1548b83cc969SLi Zefan 	if (pending->readonly)
1549b83cc969SLi Zefan 		root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1550b83cc969SLi Zefan 	else
1551b83cc969SLi Zefan 		root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1552b83cc969SLi Zefan 	btrfs_set_root_flags(new_root_item, root_flags);
1553b83cc969SLi Zefan 
15548ea05e3aSAlexander Block 	btrfs_set_root_generation_v2(new_root_item,
15558ea05e3aSAlexander Block 			trans->transid);
15568ea05e3aSAlexander Block 	uuid_le_gen(&new_uuid);
15578ea05e3aSAlexander Block 	memcpy(new_root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
15588ea05e3aSAlexander Block 	memcpy(new_root_item->parent_uuid, root->root_item.uuid,
15598ea05e3aSAlexander Block 			BTRFS_UUID_SIZE);
156070023da2SStefan Behrens 	if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
156170023da2SStefan Behrens 		memset(new_root_item->received_uuid, 0,
156270023da2SStefan Behrens 		       sizeof(new_root_item->received_uuid));
15638ea05e3aSAlexander Block 		memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
15648ea05e3aSAlexander Block 		memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
15658ea05e3aSAlexander Block 		btrfs_set_root_stransid(new_root_item, 0);
15668ea05e3aSAlexander Block 		btrfs_set_root_rtransid(new_root_item, 0);
156770023da2SStefan Behrens 	}
15683cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
15693cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
157070023da2SStefan Behrens 	btrfs_set_root_otransid(new_root_item, trans->transid);
15718ea05e3aSAlexander Block 
1572925baeddSChris Mason 	old = btrfs_lock_root_node(root);
157349b25e05SJeff Mahoney 	ret = btrfs_cow_block(trans, root, old, NULL, 0, &old);
157479787eaaSJeff Mahoney 	if (ret) {
157579787eaaSJeff Mahoney 		btrfs_tree_unlock(old);
157679787eaaSJeff Mahoney 		free_extent_buffer(old);
157766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15788732d44fSMiao Xie 		goto fail;
157979787eaaSJeff Mahoney 	}
158049b25e05SJeff Mahoney 
15815d4f98a2SYan Zheng 	btrfs_set_lock_blocking(old);
15823063d29fSChris Mason 
158349b25e05SJeff Mahoney 	ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
158479787eaaSJeff Mahoney 	/* clean up in any case */
1585925baeddSChris Mason 	btrfs_tree_unlock(old);
1586925baeddSChris Mason 	free_extent_buffer(old);
15878732d44fSMiao Xie 	if (ret) {
158866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15898732d44fSMiao Xie 		goto fail;
15908732d44fSMiao Xie 	}
1591f1ebcc74SLiu Bo 	/* see comments in should_cow_block() */
159227cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1593f1ebcc74SLiu Bo 	smp_wmb();
1594f1ebcc74SLiu Bo 
15955d4f98a2SYan Zheng 	btrfs_set_root_node(new_root_item, tmp);
1596a22285a6SYan, Zheng 	/* record when the snapshot was created in key.offset */
1597a22285a6SYan, Zheng 	key.offset = trans->transid;
1598a22285a6SYan, Zheng 	ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1599925baeddSChris Mason 	btrfs_tree_unlock(tmp);
16003063d29fSChris Mason 	free_extent_buffer(tmp);
16018732d44fSMiao Xie 	if (ret) {
160266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16038732d44fSMiao Xie 		goto fail;
16048732d44fSMiao Xie 	}
16050660b5afSChris Mason 
1606a22285a6SYan, Zheng 	/*
1607a22285a6SYan, Zheng 	 * insert root back/forward references
1608a22285a6SYan, Zheng 	 */
16096025c19fSLu Fengqi 	ret = btrfs_add_root_ref(trans, objectid,
1610a22285a6SYan, Zheng 				 parent_root->root_key.objectid,
16114a0cc7caSNikolay Borisov 				 btrfs_ino(BTRFS_I(parent_inode)), index,
1612a22285a6SYan, Zheng 				 dentry->d_name.name, dentry->d_name.len);
16138732d44fSMiao Xie 	if (ret) {
161466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16158732d44fSMiao Xie 		goto fail;
16168732d44fSMiao Xie 	}
1617a22285a6SYan, Zheng 
1618a22285a6SYan, Zheng 	key.offset = (u64)-1;
16190b246afaSJeff Mahoney 	pending->snap = btrfs_read_fs_root_no_name(fs_info, &key);
162079787eaaSJeff Mahoney 	if (IS_ERR(pending->snap)) {
162179787eaaSJeff Mahoney 		ret = PTR_ERR(pending->snap);
162266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16238732d44fSMiao Xie 		goto fail;
162479787eaaSJeff Mahoney 	}
1625d68fc57bSYan, Zheng 
162649b25e05SJeff Mahoney 	ret = btrfs_reloc_post_snapshot(trans, pending);
16278732d44fSMiao Xie 	if (ret) {
162866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16298732d44fSMiao Xie 		goto fail;
16308732d44fSMiao Xie 	}
1631361048f5SMiao Xie 
1632c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
16338732d44fSMiao Xie 	if (ret) {
163466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16358732d44fSMiao Xie 		goto fail;
16368732d44fSMiao Xie 	}
163742874b3dSMiao Xie 
16386426c7adSQu Wenruo 	/*
16396426c7adSQu Wenruo 	 * Do special qgroup accounting for snapshot, as we do some qgroup
16406426c7adSQu Wenruo 	 * snapshot hack to do fast snapshot.
16416426c7adSQu Wenruo 	 * To co-operate with that hack, we do hack again.
16426426c7adSQu Wenruo 	 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
16436426c7adSQu Wenruo 	 */
16446426c7adSQu Wenruo 	ret = qgroup_account_snapshot(trans, root, parent_root,
16456426c7adSQu Wenruo 				      pending->inherit, objectid);
16466426c7adSQu Wenruo 	if (ret < 0)
16476426c7adSQu Wenruo 		goto fail;
16486426c7adSQu Wenruo 
1649684572dfSLu Fengqi 	ret = btrfs_insert_dir_item(trans, dentry->d_name.name,
1650684572dfSLu Fengqi 				    dentry->d_name.len, BTRFS_I(parent_inode),
1651684572dfSLu Fengqi 				    &key, BTRFS_FT_DIR, index);
165242874b3dSMiao Xie 	/* We have check then name at the beginning, so it is impossible. */
16539c52057cSChris Mason 	BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
16548732d44fSMiao Xie 	if (ret) {
165566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16568732d44fSMiao Xie 		goto fail;
16578732d44fSMiao Xie 	}
165842874b3dSMiao Xie 
16596ef06d27SNikolay Borisov 	btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
166042874b3dSMiao Xie 					 dentry->d_name.len * 2);
166104b285f3SDeepa Dinamani 	parent_inode->i_mtime = parent_inode->i_ctime =
1662c2050a45SDeepa Dinamani 		current_time(parent_inode);
1663be6aef60SJosef Bacik 	ret = btrfs_update_inode_fallback(trans, parent_root, parent_inode);
1664dd5f9615SStefan Behrens 	if (ret) {
166566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1666dd5f9615SStefan Behrens 		goto fail;
1667dd5f9615SStefan Behrens 	}
1668cdb345a8SLu Fengqi 	ret = btrfs_uuid_tree_add(trans, new_uuid.b, BTRFS_UUID_KEY_SUBVOL,
1669cdb345a8SLu Fengqi 				  objectid);
1670dd5f9615SStefan Behrens 	if (ret) {
167166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1672dd5f9615SStefan Behrens 		goto fail;
1673dd5f9615SStefan Behrens 	}
1674dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1675cdb345a8SLu Fengqi 		ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1676dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1677dd5f9615SStefan Behrens 					  objectid);
1678dd5f9615SStefan Behrens 		if (ret && ret != -EEXIST) {
167966642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
1680dd5f9615SStefan Behrens 			goto fail;
1681dd5f9615SStefan Behrens 		}
1682dd5f9615SStefan Behrens 	}
1683d6726335SQu Wenruo 
1684c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1685d6726335SQu Wenruo 	if (ret) {
168666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1687d6726335SQu Wenruo 		goto fail;
1688d6726335SQu Wenruo 	}
1689d6726335SQu Wenruo 
16903063d29fSChris Mason fail:
1691aec8030aSMiao Xie 	pending->error = ret;
1692aec8030aSMiao Xie dir_item_existed:
169398c9942aSLiu Bo 	trans->block_rsv = rsv;
16942382c5ccSLiu Bo 	trans->bytes_reserved = 0;
1695d6726335SQu Wenruo clear_skip_qgroup:
1696d6726335SQu Wenruo 	btrfs_clear_skip_qgroup(trans);
16976fa9700eSMiao Xie no_free_objectid:
16986fa9700eSMiao Xie 	kfree(new_root_item);
1699b0c0ea63SDavid Sterba 	pending->root_item = NULL;
170042874b3dSMiao Xie 	btrfs_free_path(path);
17018546b570SDavid Sterba 	pending->path = NULL;
17028546b570SDavid Sterba 
170349b25e05SJeff Mahoney 	return ret;
17043063d29fSChris Mason }
17053063d29fSChris Mason 
1706d352ac68SChris Mason /*
1707d352ac68SChris Mason  * create all the snapshots we've scheduled for creation
1708d352ac68SChris Mason  */
170908d50ca3SNikolay Borisov static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
17103063d29fSChris Mason {
1711aec8030aSMiao Xie 	struct btrfs_pending_snapshot *pending, *next;
17123063d29fSChris Mason 	struct list_head *head = &trans->transaction->pending_snapshots;
1713aec8030aSMiao Xie 	int ret = 0;
17143de4586cSChris Mason 
1715aec8030aSMiao Xie 	list_for_each_entry_safe(pending, next, head, list) {
1716aec8030aSMiao Xie 		list_del(&pending->list);
171708d50ca3SNikolay Borisov 		ret = create_pending_snapshot(trans, pending);
1718aec8030aSMiao Xie 		if (ret)
1719aec8030aSMiao Xie 			break;
1720aec8030aSMiao Xie 	}
1721aec8030aSMiao Xie 	return ret;
17223de4586cSChris Mason }
17233de4586cSChris Mason 
17242ff7e61eSJeff Mahoney static void update_super_roots(struct btrfs_fs_info *fs_info)
17255d4f98a2SYan Zheng {
17265d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
17275d4f98a2SYan Zheng 	struct btrfs_super_block *super;
17285d4f98a2SYan Zheng 
17290b246afaSJeff Mahoney 	super = fs_info->super_copy;
17305d4f98a2SYan Zheng 
17310b246afaSJeff Mahoney 	root_item = &fs_info->chunk_root->root_item;
1732093e037cSDavid Sterba 	super->chunk_root = root_item->bytenr;
1733093e037cSDavid Sterba 	super->chunk_root_generation = root_item->generation;
1734093e037cSDavid Sterba 	super->chunk_root_level = root_item->level;
17355d4f98a2SYan Zheng 
17360b246afaSJeff Mahoney 	root_item = &fs_info->tree_root->root_item;
1737093e037cSDavid Sterba 	super->root = root_item->bytenr;
1738093e037cSDavid Sterba 	super->generation = root_item->generation;
1739093e037cSDavid Sterba 	super->root_level = root_item->level;
17400b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, SPACE_CACHE))
1741093e037cSDavid Sterba 		super->cache_generation = root_item->generation;
17420b246afaSJeff Mahoney 	if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1743093e037cSDavid Sterba 		super->uuid_tree_generation = root_item->generation;
17445d4f98a2SYan Zheng }
17455d4f98a2SYan Zheng 
1746f36f3042SChris Mason int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1747f36f3042SChris Mason {
17484a9d8bdeSMiao Xie 	struct btrfs_transaction *trans;
1749f36f3042SChris Mason 	int ret = 0;
17504a9d8bdeSMiao Xie 
1751a4abeea4SJosef Bacik 	spin_lock(&info->trans_lock);
17524a9d8bdeSMiao Xie 	trans = info->running_transaction;
17534a9d8bdeSMiao Xie 	if (trans)
17544a9d8bdeSMiao Xie 		ret = (trans->state >= TRANS_STATE_COMMIT_START);
1755a4abeea4SJosef Bacik 	spin_unlock(&info->trans_lock);
1756f36f3042SChris Mason 	return ret;
1757f36f3042SChris Mason }
1758f36f3042SChris Mason 
17598929ecfaSYan, Zheng int btrfs_transaction_blocked(struct btrfs_fs_info *info)
17608929ecfaSYan, Zheng {
17614a9d8bdeSMiao Xie 	struct btrfs_transaction *trans;
17628929ecfaSYan, Zheng 	int ret = 0;
17634a9d8bdeSMiao Xie 
1764a4abeea4SJosef Bacik 	spin_lock(&info->trans_lock);
17654a9d8bdeSMiao Xie 	trans = info->running_transaction;
17664a9d8bdeSMiao Xie 	if (trans)
17674a9d8bdeSMiao Xie 		ret = is_transaction_blocked(trans);
1768a4abeea4SJosef Bacik 	spin_unlock(&info->trans_lock);
17698929ecfaSYan, Zheng 	return ret;
17708929ecfaSYan, Zheng }
17718929ecfaSYan, Zheng 
1772bb9c12c9SSage Weil /*
1773bb9c12c9SSage Weil  * wait for the current transaction commit to start and block subsequent
1774bb9c12c9SSage Weil  * transaction joins
1775bb9c12c9SSage Weil  */
17762ff7e61eSJeff Mahoney static void wait_current_trans_commit_start(struct btrfs_fs_info *fs_info,
1777bb9c12c9SSage Weil 					    struct btrfs_transaction *trans)
1778bb9c12c9SSage Weil {
17792ff7e61eSJeff Mahoney 	wait_event(fs_info->transaction_blocked_wait,
17802ff7e61eSJeff Mahoney 		   trans->state >= TRANS_STATE_COMMIT_START || trans->aborted);
1781bb9c12c9SSage Weil }
1782bb9c12c9SSage Weil 
1783bb9c12c9SSage Weil /*
1784bb9c12c9SSage Weil  * wait for the current transaction to start and then become unblocked.
1785bb9c12c9SSage Weil  * caller holds ref.
1786bb9c12c9SSage Weil  */
17872ff7e61eSJeff Mahoney static void wait_current_trans_commit_start_and_unblock(
17882ff7e61eSJeff Mahoney 					struct btrfs_fs_info *fs_info,
1789bb9c12c9SSage Weil 					struct btrfs_transaction *trans)
1790bb9c12c9SSage Weil {
17912ff7e61eSJeff Mahoney 	wait_event(fs_info->transaction_wait,
17922ff7e61eSJeff Mahoney 		   trans->state >= TRANS_STATE_UNBLOCKED || trans->aborted);
1793bb9c12c9SSage Weil }
1794bb9c12c9SSage Weil 
1795bb9c12c9SSage Weil /*
1796bb9c12c9SSage Weil  * commit transactions asynchronously. once btrfs_commit_transaction_async
1797bb9c12c9SSage Weil  * returns, any subsequent transaction will not be allowed to join.
1798bb9c12c9SSage Weil  */
1799bb9c12c9SSage Weil struct btrfs_async_commit {
1800bb9c12c9SSage Weil 	struct btrfs_trans_handle *newtrans;
18017892b5afSMiao Xie 	struct work_struct work;
1802bb9c12c9SSage Weil };
1803bb9c12c9SSage Weil 
1804bb9c12c9SSage Weil static void do_async_commit(struct work_struct *work)
1805bb9c12c9SSage Weil {
1806bb9c12c9SSage Weil 	struct btrfs_async_commit *ac =
18077892b5afSMiao Xie 		container_of(work, struct btrfs_async_commit, work);
1808bb9c12c9SSage Weil 
18096fc4e354SSage Weil 	/*
18106fc4e354SSage Weil 	 * We've got freeze protection passed with the transaction.
18116fc4e354SSage Weil 	 * Tell lockdep about it.
18126fc4e354SSage Weil 	 */
1813b1a06a4bSLiu Bo 	if (ac->newtrans->type & __TRANS_FREEZABLE)
18143a45bb20SJeff Mahoney 		__sb_writers_acquired(ac->newtrans->fs_info->sb, SB_FREEZE_FS);
18156fc4e354SSage Weil 
1816e209db7aSSage Weil 	current->journal_info = ac->newtrans;
1817e209db7aSSage Weil 
18183a45bb20SJeff Mahoney 	btrfs_commit_transaction(ac->newtrans);
1819bb9c12c9SSage Weil 	kfree(ac);
1820bb9c12c9SSage Weil }
1821bb9c12c9SSage Weil 
1822bb9c12c9SSage Weil int btrfs_commit_transaction_async(struct btrfs_trans_handle *trans,
1823bb9c12c9SSage Weil 				   int wait_for_unblock)
1824bb9c12c9SSage Weil {
18253a45bb20SJeff Mahoney 	struct btrfs_fs_info *fs_info = trans->fs_info;
1826bb9c12c9SSage Weil 	struct btrfs_async_commit *ac;
1827bb9c12c9SSage Weil 	struct btrfs_transaction *cur_trans;
1828bb9c12c9SSage Weil 
1829bb9c12c9SSage Weil 	ac = kmalloc(sizeof(*ac), GFP_NOFS);
1830db5b493aSTsutomu Itoh 	if (!ac)
1831db5b493aSTsutomu Itoh 		return -ENOMEM;
1832bb9c12c9SSage Weil 
18337892b5afSMiao Xie 	INIT_WORK(&ac->work, do_async_commit);
18343a45bb20SJeff Mahoney 	ac->newtrans = btrfs_join_transaction(trans->root);
18353612b495STsutomu Itoh 	if (IS_ERR(ac->newtrans)) {
18363612b495STsutomu Itoh 		int err = PTR_ERR(ac->newtrans);
18373612b495STsutomu Itoh 		kfree(ac);
18383612b495STsutomu Itoh 		return err;
18393612b495STsutomu Itoh 	}
1840bb9c12c9SSage Weil 
1841bb9c12c9SSage Weil 	/* take transaction reference */
1842bb9c12c9SSage Weil 	cur_trans = trans->transaction;
18439b64f57dSElena Reshetova 	refcount_inc(&cur_trans->use_count);
1844bb9c12c9SSage Weil 
18453a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
18466fc4e354SSage Weil 
18476fc4e354SSage Weil 	/*
18486fc4e354SSage Weil 	 * Tell lockdep we've released the freeze rwsem, since the
18496fc4e354SSage Weil 	 * async commit thread will be the one to unlock it.
18506fc4e354SSage Weil 	 */
1851b1a06a4bSLiu Bo 	if (ac->newtrans->type & __TRANS_FREEZABLE)
18520b246afaSJeff Mahoney 		__sb_writers_release(fs_info->sb, SB_FREEZE_FS);
18536fc4e354SSage Weil 
18547892b5afSMiao Xie 	schedule_work(&ac->work);
1855bb9c12c9SSage Weil 
1856bb9c12c9SSage Weil 	/* wait for transaction to start and unblock */
1857bb9c12c9SSage Weil 	if (wait_for_unblock)
18582ff7e61eSJeff Mahoney 		wait_current_trans_commit_start_and_unblock(fs_info, cur_trans);
1859bb9c12c9SSage Weil 	else
18602ff7e61eSJeff Mahoney 		wait_current_trans_commit_start(fs_info, cur_trans);
1861bb9c12c9SSage Weil 
186238e88054SSage Weil 	if (current->journal_info == trans)
186338e88054SSage Weil 		current->journal_info = NULL;
186438e88054SSage Weil 
1865724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
1866bb9c12c9SSage Weil 	return 0;
1867bb9c12c9SSage Weil }
1868bb9c12c9SSage Weil 
186949b25e05SJeff Mahoney 
187097cb39bbSNikolay Borisov static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
187149b25e05SJeff Mahoney {
187297cb39bbSNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
187349b25e05SJeff Mahoney 	struct btrfs_transaction *cur_trans = trans->transaction;
187449b25e05SJeff Mahoney 
1875b50fff81SDavid Sterba 	WARN_ON(refcount_read(&trans->use_count) > 1);
187649b25e05SJeff Mahoney 
187766642832SJeff Mahoney 	btrfs_abort_transaction(trans, err);
18787b8b92afSJosef Bacik 
18790b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
188066b6135bSLiu Bo 
188125d8c284SMiao Xie 	/*
188225d8c284SMiao Xie 	 * If the transaction is removed from the list, it means this
188325d8c284SMiao Xie 	 * transaction has been committed successfully, so it is impossible
188425d8c284SMiao Xie 	 * to call the cleanup function.
188525d8c284SMiao Xie 	 */
188625d8c284SMiao Xie 	BUG_ON(list_empty(&cur_trans->list));
188766b6135bSLiu Bo 
188849b25e05SJeff Mahoney 	list_del_init(&cur_trans->list);
18890b246afaSJeff Mahoney 	if (cur_trans == fs_info->running_transaction) {
18904a9d8bdeSMiao Xie 		cur_trans->state = TRANS_STATE_COMMIT_DOING;
18910b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
1892f094ac32SLiu Bo 		wait_event(cur_trans->writer_wait,
1893f094ac32SLiu Bo 			   atomic_read(&cur_trans->num_writers) == 1);
1894f094ac32SLiu Bo 
18950b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
1896d7096fc3SJosef Bacik 	}
18970b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
189849b25e05SJeff Mahoney 
18992ff7e61eSJeff Mahoney 	btrfs_cleanup_one_transaction(trans->transaction, fs_info);
190049b25e05SJeff Mahoney 
19010b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
19020b246afaSJeff Mahoney 	if (cur_trans == fs_info->running_transaction)
19030b246afaSJeff Mahoney 		fs_info->running_transaction = NULL;
19040b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
19054a9d8bdeSMiao Xie 
1906e0228285SJosef Bacik 	if (trans->type & __TRANS_FREEZABLE)
19070b246afaSJeff Mahoney 		sb_end_intwrite(fs_info->sb);
1908724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
1909724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
191049b25e05SJeff Mahoney 
191197cb39bbSNikolay Borisov 	trace_btrfs_transaction_commit(trans->root);
191249b25e05SJeff Mahoney 
191349b25e05SJeff Mahoney 	if (current->journal_info == trans)
191449b25e05SJeff Mahoney 		current->journal_info = NULL;
19150b246afaSJeff Mahoney 	btrfs_scrub_cancel(fs_info);
191649b25e05SJeff Mahoney 
191749b25e05SJeff Mahoney 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
191849b25e05SJeff Mahoney }
191949b25e05SJeff Mahoney 
192082436617SMiao Xie static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
192182436617SMiao Xie {
1922ce8ea7ccSJosef Bacik 	/*
1923ce8ea7ccSJosef Bacik 	 * We use writeback_inodes_sb here because if we used
1924ce8ea7ccSJosef Bacik 	 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
1925ce8ea7ccSJosef Bacik 	 * Currently are holding the fs freeze lock, if we do an async flush
1926ce8ea7ccSJosef Bacik 	 * we'll do btrfs_join_transaction() and deadlock because we need to
1927ce8ea7ccSJosef Bacik 	 * wait for the fs freeze lock.  Using the direct flushing we benefit
1928ce8ea7ccSJosef Bacik 	 * from already being in a transaction and our join_transaction doesn't
1929ce8ea7ccSJosef Bacik 	 * have to re-take the fs freeze lock.
1930ce8ea7ccSJosef Bacik 	 */
19313cdde224SJeff Mahoney 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
1932ce8ea7ccSJosef Bacik 		writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
193382436617SMiao Xie 	return 0;
193482436617SMiao Xie }
193582436617SMiao Xie 
193682436617SMiao Xie static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
193782436617SMiao Xie {
19383cdde224SJeff Mahoney 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
19396374e57aSChris Mason 		btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
194082436617SMiao Xie }
194182436617SMiao Xie 
19423a45bb20SJeff Mahoney int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
194379154b1bSChris Mason {
19443a45bb20SJeff Mahoney 	struct btrfs_fs_info *fs_info = trans->fs_info;
194549b25e05SJeff Mahoney 	struct btrfs_transaction *cur_trans = trans->transaction;
19468fd17795SChris Mason 	struct btrfs_transaction *prev_trans = NULL;
194725287e0aSMiao Xie 	int ret;
194879154b1bSChris Mason 
19498d25a086SMiao Xie 	/* Stop the commit early if ->aborted is set */
195020c7bcecSSeraphime Kirkovski 	if (unlikely(READ_ONCE(cur_trans->aborted))) {
195125287e0aSMiao Xie 		ret = cur_trans->aborted;
19523a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
1953e4a2bcacSJosef Bacik 		return ret;
195425287e0aSMiao Xie 	}
195549b25e05SJeff Mahoney 
1956f45c752bSJosef Bacik 	btrfs_trans_release_metadata(trans);
1957f45c752bSJosef Bacik 	trans->block_rsv = NULL;
1958f45c752bSJosef Bacik 
195956bec294SChris Mason 	/* make a pass through all the delayed refs we have so far
196056bec294SChris Mason 	 * any runnings procs may add more while we are here
196156bec294SChris Mason 	 */
1962c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, 0);
1963e4a2bcacSJosef Bacik 	if (ret) {
19643a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
1965e4a2bcacSJosef Bacik 		return ret;
1966e4a2bcacSJosef Bacik 	}
196756bec294SChris Mason 
1968b7ec40d7SChris Mason 	cur_trans = trans->transaction;
196949b25e05SJeff Mahoney 
197056bec294SChris Mason 	/*
197156bec294SChris Mason 	 * set the flushing flag so procs in this transaction have to
197256bec294SChris Mason 	 * start sending their work down.
197356bec294SChris Mason 	 */
1974b7ec40d7SChris Mason 	cur_trans->delayed_refs.flushing = 1;
19751be41b78SJosef Bacik 	smp_wmb();
197656bec294SChris Mason 
1977ea658badSJosef Bacik 	if (!list_empty(&trans->new_bgs))
19786c686b35SNikolay Borisov 		btrfs_create_pending_block_groups(trans);
1979ea658badSJosef Bacik 
1980c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, 0);
1981e4a2bcacSJosef Bacik 	if (ret) {
19823a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
1983e4a2bcacSJosef Bacik 		return ret;
1984e4a2bcacSJosef Bacik 	}
198556bec294SChris Mason 
19863204d33cSJosef Bacik 	if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
19871bbc621eSChris Mason 		int run_it = 0;
19881bbc621eSChris Mason 
19891bbc621eSChris Mason 		/* this mutex is also taken before trying to set
19901bbc621eSChris Mason 		 * block groups readonly.  We need to make sure
19911bbc621eSChris Mason 		 * that nobody has set a block group readonly
19921bbc621eSChris Mason 		 * after a extents from that block group have been
19931bbc621eSChris Mason 		 * allocated for cache files.  btrfs_set_block_group_ro
19941bbc621eSChris Mason 		 * will wait for the transaction to commit if it
19953204d33cSJosef Bacik 		 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
19961bbc621eSChris Mason 		 *
19973204d33cSJosef Bacik 		 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
19983204d33cSJosef Bacik 		 * only one process starts all the block group IO.  It wouldn't
19991bbc621eSChris Mason 		 * hurt to have more than one go through, but there's no
20001bbc621eSChris Mason 		 * real advantage to it either.
20011bbc621eSChris Mason 		 */
20020b246afaSJeff Mahoney 		mutex_lock(&fs_info->ro_block_group_mutex);
20033204d33cSJosef Bacik 		if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
20043204d33cSJosef Bacik 				      &cur_trans->flags))
20051bbc621eSChris Mason 			run_it = 1;
20060b246afaSJeff Mahoney 		mutex_unlock(&fs_info->ro_block_group_mutex);
20071bbc621eSChris Mason 
2008f9cacae3SNikolay Borisov 		if (run_it) {
200921217054SNikolay Borisov 			ret = btrfs_start_dirty_block_groups(trans);
20101bbc621eSChris Mason 			if (ret) {
20113a45bb20SJeff Mahoney 				btrfs_end_transaction(trans);
20121bbc621eSChris Mason 				return ret;
20131bbc621eSChris Mason 			}
2014f9cacae3SNikolay Borisov 		}
2015f9cacae3SNikolay Borisov 	}
20161bbc621eSChris Mason 
20170b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
20184a9d8bdeSMiao Xie 	if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
20190b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
20209b64f57dSElena Reshetova 		refcount_inc(&cur_trans->use_count);
20213a45bb20SJeff Mahoney 		ret = btrfs_end_transaction(trans);
2022ccd467d6SChris Mason 
20232ff7e61eSJeff Mahoney 		wait_for_commit(cur_trans);
202415ee9bc7SJosef Bacik 
2025b4924a0fSLiu Bo 		if (unlikely(cur_trans->aborted))
2026b4924a0fSLiu Bo 			ret = cur_trans->aborted;
2027b4924a0fSLiu Bo 
2028724e2315SJosef Bacik 		btrfs_put_transaction(cur_trans);
202915ee9bc7SJosef Bacik 
203049b25e05SJeff Mahoney 		return ret;
203179154b1bSChris Mason 	}
20324313b399SChris Mason 
20334a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
20340b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
2035bb9c12c9SSage Weil 
20360b246afaSJeff Mahoney 	if (cur_trans->list.prev != &fs_info->trans_list) {
2037ccd467d6SChris Mason 		prev_trans = list_entry(cur_trans->list.prev,
2038ccd467d6SChris Mason 					struct btrfs_transaction, list);
20394a9d8bdeSMiao Xie 		if (prev_trans->state != TRANS_STATE_COMPLETED) {
20409b64f57dSElena Reshetova 			refcount_inc(&prev_trans->use_count);
20410b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
2042ccd467d6SChris Mason 
20432ff7e61eSJeff Mahoney 			wait_for_commit(prev_trans);
20441f9b8c8fSFilipe Manana 			ret = prev_trans->aborted;
2045ccd467d6SChris Mason 
2046724e2315SJosef Bacik 			btrfs_put_transaction(prev_trans);
20471f9b8c8fSFilipe Manana 			if (ret)
20481f9b8c8fSFilipe Manana 				goto cleanup_transaction;
2049a4abeea4SJosef Bacik 		} else {
20500b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
2051ccd467d6SChris Mason 		}
2052a4abeea4SJosef Bacik 	} else {
20530b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
2054ccd467d6SChris Mason 	}
205515ee9bc7SJosef Bacik 
20560860adfdSMiao Xie 	extwriter_counter_dec(cur_trans, trans->type);
20570860adfdSMiao Xie 
20580b246afaSJeff Mahoney 	ret = btrfs_start_delalloc_flush(fs_info);
205982436617SMiao Xie 	if (ret)
206082436617SMiao Xie 		goto cleanup_transaction;
206182436617SMiao Xie 
2062e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
206349b25e05SJeff Mahoney 	if (ret)
206449b25e05SJeff Mahoney 		goto cleanup_transaction;
206516cdcec7SMiao Xie 
2066581227d0SMiao Xie 	wait_event(cur_trans->writer_wait,
2067581227d0SMiao Xie 		   extwriter_counter_read(cur_trans) == 0);
2068ed3b3d31SChris Mason 
2069581227d0SMiao Xie 	/* some pending stuffs might be added after the previous flush. */
2070e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
2071ca469637SMiao Xie 	if (ret)
2072ca469637SMiao Xie 		goto cleanup_transaction;
2073ca469637SMiao Xie 
20740b246afaSJeff Mahoney 	btrfs_wait_delalloc_flush(fs_info);
2075cb7ab021SWang Shilong 
20762ff7e61eSJeff Mahoney 	btrfs_scrub_pause(fs_info);
2077ed0ca140SJosef Bacik 	/*
2078ed0ca140SJosef Bacik 	 * Ok now we need to make sure to block out any other joins while we
2079ed0ca140SJosef Bacik 	 * commit the transaction.  We could have started a join before setting
20804a9d8bdeSMiao Xie 	 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2081ed0ca140SJosef Bacik 	 */
20820b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
20834a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_DOING;
20840b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2085ed0ca140SJosef Bacik 	wait_event(cur_trans->writer_wait,
2086ed0ca140SJosef Bacik 		   atomic_read(&cur_trans->num_writers) == 1);
208715ee9bc7SJosef Bacik 
20882cba30f1SMiao Xie 	/* ->aborted might be set after the previous check, so check it */
208920c7bcecSSeraphime Kirkovski 	if (unlikely(READ_ONCE(cur_trans->aborted))) {
20902cba30f1SMiao Xie 		ret = cur_trans->aborted;
20916cf7f77eSWang Shilong 		goto scrub_continue;
20922cba30f1SMiao Xie 	}
20937585717fSChris Mason 	/*
20947585717fSChris Mason 	 * the reloc mutex makes sure that we stop
20957585717fSChris Mason 	 * the balancing code from coming in and moving
20967585717fSChris Mason 	 * extents around in the middle of the commit
20977585717fSChris Mason 	 */
20980b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
20997585717fSChris Mason 
210042874b3dSMiao Xie 	/*
210142874b3dSMiao Xie 	 * We needn't worry about the delayed items because we will
210242874b3dSMiao Xie 	 * deal with them in create_pending_snapshot(), which is the
210342874b3dSMiao Xie 	 * core function of the snapshot creation.
210442874b3dSMiao Xie 	 */
210508d50ca3SNikolay Borisov 	ret = create_pending_snapshots(trans);
210649b25e05SJeff Mahoney 	if (ret) {
21070b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21086cf7f77eSWang Shilong 		goto scrub_continue;
210949b25e05SJeff Mahoney 	}
21103063d29fSChris Mason 
211142874b3dSMiao Xie 	/*
211242874b3dSMiao Xie 	 * We insert the dir indexes of the snapshots and update the inode
211342874b3dSMiao Xie 	 * of the snapshots' parents after the snapshot creation, so there
211442874b3dSMiao Xie 	 * are some delayed items which are not dealt with. Now deal with
211542874b3dSMiao Xie 	 * them.
211642874b3dSMiao Xie 	 *
211742874b3dSMiao Xie 	 * We needn't worry that this operation will corrupt the snapshots,
211842874b3dSMiao Xie 	 * because all the tree which are snapshoted will be forced to COW
211942874b3dSMiao Xie 	 * the nodes and leaves.
212042874b3dSMiao Xie 	 */
2121e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
212249b25e05SJeff Mahoney 	if (ret) {
21230b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21246cf7f77eSWang Shilong 		goto scrub_continue;
212549b25e05SJeff Mahoney 	}
212616cdcec7SMiao Xie 
2127c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
212849b25e05SJeff Mahoney 	if (ret) {
21290b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21306cf7f77eSWang Shilong 		goto scrub_continue;
213149b25e05SJeff Mahoney 	}
213256bec294SChris Mason 
2133e999376fSChris Mason 	/*
2134e999376fSChris Mason 	 * make sure none of the code above managed to slip in a
2135e999376fSChris Mason 	 * delayed item
2136e999376fSChris Mason 	 */
2137ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
2138e999376fSChris Mason 
21392c90e5d6SChris Mason 	WARN_ON(cur_trans != trans->transaction);
2140dc17ff8fSChris Mason 
2141e02119d5SChris Mason 	/* btrfs_commit_tree_roots is responsible for getting the
2142e02119d5SChris Mason 	 * various roots consistent with each other.  Every pointer
2143e02119d5SChris Mason 	 * in the tree of tree roots has to point to the most up to date
2144e02119d5SChris Mason 	 * root for every subvolume and other tree.  So, we have to keep
2145e02119d5SChris Mason 	 * the tree logging code from jumping in and changing any
2146e02119d5SChris Mason 	 * of the trees.
2147e02119d5SChris Mason 	 *
2148e02119d5SChris Mason 	 * At this point in the commit, there can't be any tree-log
2149e02119d5SChris Mason 	 * writers, but a little lower down we drop the trans mutex
2150e02119d5SChris Mason 	 * and let new people in.  By holding the tree_log_mutex
2151e02119d5SChris Mason 	 * from now until after the super is written, we avoid races
2152e02119d5SChris Mason 	 * with the tree-log code.
2153e02119d5SChris Mason 	 */
21540b246afaSJeff Mahoney 	mutex_lock(&fs_info->tree_log_mutex);
21551a40e23bSZheng Yan 
21567e4443d9SNikolay Borisov 	ret = commit_fs_roots(trans);
215749b25e05SJeff Mahoney 	if (ret) {
21580b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
21590b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21606cf7f77eSWang Shilong 		goto scrub_continue;
216149b25e05SJeff Mahoney 	}
216254aa1f4dSChris Mason 
21633818aea2SQu Wenruo 	/*
21647e1876acSDavid Sterba 	 * Since the transaction is done, we can apply the pending changes
21657e1876acSDavid Sterba 	 * before the next transaction.
21663818aea2SQu Wenruo 	 */
21670b246afaSJeff Mahoney 	btrfs_apply_pending_changes(fs_info);
21683818aea2SQu Wenruo 
21695d4f98a2SYan Zheng 	/* commit_fs_roots gets rid of all the tree log roots, it is now
2170e02119d5SChris Mason 	 * safe to free the root of tree log roots
2171e02119d5SChris Mason 	 */
21720b246afaSJeff Mahoney 	btrfs_free_log_root_tree(trans, fs_info);
2173e02119d5SChris Mason 
21740ed4792aSQu Wenruo 	/*
217582bafb38SQu Wenruo 	 * commit_fs_roots() can call btrfs_save_ino_cache(), which generates
217682bafb38SQu Wenruo 	 * new delayed refs. Must handle them or qgroup can be wrong.
217782bafb38SQu Wenruo 	 */
2178c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
217982bafb38SQu Wenruo 	if (ret) {
218082bafb38SQu Wenruo 		mutex_unlock(&fs_info->tree_log_mutex);
218182bafb38SQu Wenruo 		mutex_unlock(&fs_info->reloc_mutex);
218282bafb38SQu Wenruo 		goto scrub_continue;
218382bafb38SQu Wenruo 	}
218482bafb38SQu Wenruo 
218582bafb38SQu Wenruo 	/*
21860ed4792aSQu Wenruo 	 * Since fs roots are all committed, we can get a quite accurate
21870ed4792aSQu Wenruo 	 * new_roots. So let's do quota accounting.
21880ed4792aSQu Wenruo 	 */
2189460fb20aSNikolay Borisov 	ret = btrfs_qgroup_account_extents(trans);
21900ed4792aSQu Wenruo 	if (ret < 0) {
21910b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
21920b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21930ed4792aSQu Wenruo 		goto scrub_continue;
21940ed4792aSQu Wenruo 	}
21950ed4792aSQu Wenruo 
21969386d8bcSNikolay Borisov 	ret = commit_cowonly_roots(trans);
219749b25e05SJeff Mahoney 	if (ret) {
21980b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
21990b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
22006cf7f77eSWang Shilong 		goto scrub_continue;
220149b25e05SJeff Mahoney 	}
220254aa1f4dSChris Mason 
22032cba30f1SMiao Xie 	/*
22042cba30f1SMiao Xie 	 * The tasks which save the space cache and inode cache may also
22052cba30f1SMiao Xie 	 * update ->aborted, check it.
22062cba30f1SMiao Xie 	 */
220720c7bcecSSeraphime Kirkovski 	if (unlikely(READ_ONCE(cur_trans->aborted))) {
22082cba30f1SMiao Xie 		ret = cur_trans->aborted;
22090b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
22100b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
22116cf7f77eSWang Shilong 		goto scrub_continue;
22122cba30f1SMiao Xie 	}
22132cba30f1SMiao Xie 
22148b74c03eSDavid Sterba 	btrfs_prepare_extent_commit(fs_info);
221511833d66SYan Zheng 
22160b246afaSJeff Mahoney 	cur_trans = fs_info->running_transaction;
22175f39d397SChris Mason 
22180b246afaSJeff Mahoney 	btrfs_set_root_node(&fs_info->tree_root->root_item,
22190b246afaSJeff Mahoney 			    fs_info->tree_root->node);
22200b246afaSJeff Mahoney 	list_add_tail(&fs_info->tree_root->dirty_list,
22219e351cc8SJosef Bacik 		      &cur_trans->switch_commits);
22225d4f98a2SYan Zheng 
22230b246afaSJeff Mahoney 	btrfs_set_root_node(&fs_info->chunk_root->root_item,
22240b246afaSJeff Mahoney 			    fs_info->chunk_root->node);
22250b246afaSJeff Mahoney 	list_add_tail(&fs_info->chunk_root->dirty_list,
22269e351cc8SJosef Bacik 		      &cur_trans->switch_commits);
22279e351cc8SJosef Bacik 
222816916a88SNikolay Borisov 	switch_commit_roots(cur_trans);
22295d4f98a2SYan Zheng 
2230ce93ec54SJosef Bacik 	ASSERT(list_empty(&cur_trans->dirty_bgs));
22311bbc621eSChris Mason 	ASSERT(list_empty(&cur_trans->io_bgs));
22322ff7e61eSJeff Mahoney 	update_super_roots(fs_info);
2233e02119d5SChris Mason 
22340b246afaSJeff Mahoney 	btrfs_set_super_log_root(fs_info->super_copy, 0);
22350b246afaSJeff Mahoney 	btrfs_set_super_log_root_level(fs_info->super_copy, 0);
22360b246afaSJeff Mahoney 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
22370b246afaSJeff Mahoney 	       sizeof(*fs_info->super_copy));
2238ccd467d6SChris Mason 
22390b246afaSJeff Mahoney 	btrfs_update_commit_device_size(fs_info);
2240e9b919b1SNikolay Borisov 	btrfs_update_commit_device_bytes_used(cur_trans);
2241935e5cc9SMiao Xie 
22420b246afaSJeff Mahoney 	clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
22430b246afaSJeff Mahoney 	clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2244656f30dbSFilipe Manana 
22454fbcdf66SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
22464fbcdf66SFilipe Manana 
22470b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
22484a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
22490b246afaSJeff Mahoney 	fs_info->running_transaction = NULL;
22500b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
22510b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
2252b7ec40d7SChris Mason 
22530b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
2254e6dcd2dcSChris Mason 
225570458a58SNikolay Borisov 	ret = btrfs_write_and_wait_transaction(trans);
225649b25e05SJeff Mahoney 	if (ret) {
22570b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
225808748810SDavid Sterba 				      "Error while writing out transaction");
22590b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
22606cf7f77eSWang Shilong 		goto scrub_continue;
226149b25e05SJeff Mahoney 	}
226249b25e05SJeff Mahoney 
2263eece6a9cSDavid Sterba 	ret = write_all_supers(fs_info, 0);
2264e02119d5SChris Mason 	/*
2265e02119d5SChris Mason 	 * the super is written, we can safely allow the tree-loggers
2266e02119d5SChris Mason 	 * to go about their business
2267e02119d5SChris Mason 	 */
22680b246afaSJeff Mahoney 	mutex_unlock(&fs_info->tree_log_mutex);
2269c1f32b7cSAnand Jain 	if (ret)
2270c1f32b7cSAnand Jain 		goto scrub_continue;
2271e02119d5SChris Mason 
22725ead2dd0SNikolay Borisov 	btrfs_finish_extent_commit(trans);
22734313b399SChris Mason 
22743204d33cSJosef Bacik 	if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
22750b246afaSJeff Mahoney 		btrfs_clear_space_info_full(fs_info);
227613212b54SZhao Lei 
22770b246afaSJeff Mahoney 	fs_info->last_trans_committed = cur_trans->transid;
22784a9d8bdeSMiao Xie 	/*
22794a9d8bdeSMiao Xie 	 * We needn't acquire the lock here because there is no other task
22804a9d8bdeSMiao Xie 	 * which can change it.
22814a9d8bdeSMiao Xie 	 */
22824a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMPLETED;
22832c90e5d6SChris Mason 	wake_up(&cur_trans->commit_wait);
2284a514d638SQu Wenruo 	clear_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags);
22853de4586cSChris Mason 
22860b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
228713c5a93eSJosef Bacik 	list_del_init(&cur_trans->list);
22880b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2289a4abeea4SJosef Bacik 
2290724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
2291724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
229258176a96SJosef Bacik 
22930860adfdSMiao Xie 	if (trans->type & __TRANS_FREEZABLE)
22940b246afaSJeff Mahoney 		sb_end_intwrite(fs_info->sb);
2295b2b5ef5cSJan Kara 
22963a45bb20SJeff Mahoney 	trace_btrfs_transaction_commit(trans->root);
22971abe9b8aSliubo 
22982ff7e61eSJeff Mahoney 	btrfs_scrub_continue(fs_info);
2299a2de733cSArne Jansen 
23009ed74f2dSJosef Bacik 	if (current->journal_info == trans)
23019ed74f2dSJosef Bacik 		current->journal_info = NULL;
23029ed74f2dSJosef Bacik 
23032c90e5d6SChris Mason 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
230424bbcf04SYan, Zheng 
230579154b1bSChris Mason 	return ret;
230649b25e05SJeff Mahoney 
23076cf7f77eSWang Shilong scrub_continue:
23082ff7e61eSJeff Mahoney 	btrfs_scrub_continue(fs_info);
230949b25e05SJeff Mahoney cleanup_transaction:
2310dc60c525SNikolay Borisov 	btrfs_trans_release_metadata(trans);
23114fbcdf66SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
23120e721106SJosef Bacik 	trans->block_rsv = NULL;
23130b246afaSJeff Mahoney 	btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
231449b25e05SJeff Mahoney 	if (current->journal_info == trans)
231549b25e05SJeff Mahoney 		current->journal_info = NULL;
231697cb39bbSNikolay Borisov 	cleanup_transaction(trans, ret);
231749b25e05SJeff Mahoney 
231849b25e05SJeff Mahoney 	return ret;
231979154b1bSChris Mason }
232079154b1bSChris Mason 
2321d352ac68SChris Mason /*
23229d1a2a3aSDavid Sterba  * return < 0 if error
23239d1a2a3aSDavid Sterba  * 0 if there are no more dead_roots at the time of call
23249d1a2a3aSDavid Sterba  * 1 there are more to be processed, call me again
23259d1a2a3aSDavid Sterba  *
23269d1a2a3aSDavid Sterba  * The return value indicates there are certainly more snapshots to delete, but
23279d1a2a3aSDavid Sterba  * if there comes a new one during processing, it may return 0. We don't mind,
23289d1a2a3aSDavid Sterba  * because btrfs_commit_super will poke cleaner thread and it will process it a
23299d1a2a3aSDavid Sterba  * few seconds later.
2330d352ac68SChris Mason  */
23319d1a2a3aSDavid Sterba int btrfs_clean_one_deleted_snapshot(struct btrfs_root *root)
2332e9d0b13bSChris Mason {
23339d1a2a3aSDavid Sterba 	int ret;
23345d4f98a2SYan Zheng 	struct btrfs_fs_info *fs_info = root->fs_info;
2335e9d0b13bSChris Mason 
2336a4abeea4SJosef Bacik 	spin_lock(&fs_info->trans_lock);
23379d1a2a3aSDavid Sterba 	if (list_empty(&fs_info->dead_roots)) {
23389d1a2a3aSDavid Sterba 		spin_unlock(&fs_info->trans_lock);
23399d1a2a3aSDavid Sterba 		return 0;
23409d1a2a3aSDavid Sterba 	}
23419d1a2a3aSDavid Sterba 	root = list_first_entry(&fs_info->dead_roots,
23429d1a2a3aSDavid Sterba 			struct btrfs_root, root_list);
2343cfad392bSJosef Bacik 	list_del_init(&root->root_list);
2344a4abeea4SJosef Bacik 	spin_unlock(&fs_info->trans_lock);
23455d4f98a2SYan Zheng 
23464fd786e6SMisono Tomohiro 	btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
234776dda93cSYan, Zheng 
234816cdcec7SMiao Xie 	btrfs_kill_all_delayed_nodes(root);
234916cdcec7SMiao Xie 
235076dda93cSYan, Zheng 	if (btrfs_header_backref_rev(root->node) <
235176dda93cSYan, Zheng 			BTRFS_MIXED_BACKREF_REV)
23522c536799SJeff Mahoney 		ret = btrfs_drop_snapshot(root, NULL, 0, 0);
235376dda93cSYan, Zheng 	else
23542c536799SJeff Mahoney 		ret = btrfs_drop_snapshot(root, NULL, 1, 0);
235532471dc2SDavid Sterba 
23566596a928SJosef Bacik 	return (ret < 0) ? 0 : 1;
2357e9d0b13bSChris Mason }
2358572d9ab7SDavid Sterba 
2359572d9ab7SDavid Sterba void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2360572d9ab7SDavid Sterba {
2361572d9ab7SDavid Sterba 	unsigned long prev;
2362572d9ab7SDavid Sterba 	unsigned long bit;
2363572d9ab7SDavid Sterba 
23646c9fe14fSQu Wenruo 	prev = xchg(&fs_info->pending_changes, 0);
2365572d9ab7SDavid Sterba 	if (!prev)
2366572d9ab7SDavid Sterba 		return;
2367572d9ab7SDavid Sterba 
23687e1876acSDavid Sterba 	bit = 1 << BTRFS_PENDING_SET_INODE_MAP_CACHE;
23697e1876acSDavid Sterba 	if (prev & bit)
23707e1876acSDavid Sterba 		btrfs_set_opt(fs_info->mount_opt, INODE_MAP_CACHE);
23717e1876acSDavid Sterba 	prev &= ~bit;
23727e1876acSDavid Sterba 
23737e1876acSDavid Sterba 	bit = 1 << BTRFS_PENDING_CLEAR_INODE_MAP_CACHE;
23747e1876acSDavid Sterba 	if (prev & bit)
23757e1876acSDavid Sterba 		btrfs_clear_opt(fs_info->mount_opt, INODE_MAP_CACHE);
23767e1876acSDavid Sterba 	prev &= ~bit;
23777e1876acSDavid Sterba 
2378d51033d0SDavid Sterba 	bit = 1 << BTRFS_PENDING_COMMIT;
2379d51033d0SDavid Sterba 	if (prev & bit)
2380d51033d0SDavid Sterba 		btrfs_debug(fs_info, "pending commit done");
2381d51033d0SDavid Sterba 	prev &= ~bit;
2382d51033d0SDavid Sterba 
2383572d9ab7SDavid Sterba 	if (prev)
2384572d9ab7SDavid Sterba 		btrfs_warn(fs_info,
2385572d9ab7SDavid Sterba 			"unknown pending changes left 0x%lx, ignoring", prev);
2386572d9ab7SDavid Sterba }
2387