xref: /openbmc/linux/fs/btrfs/transaction.c (revision bbbf7243)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
36cbd5570SChris Mason  * Copyright (C) 2007 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
679154b1bSChris Mason #include <linux/fs.h>
75a0e3ad6STejun Heo #include <linux/slab.h>
834088780SChris Mason #include <linux/sched.h>
9d3c2fdcfSChris Mason #include <linux/writeback.h>
105f39d397SChris Mason #include <linux/pagemap.h>
115f2cc086SChris Mason #include <linux/blkdev.h>
128ea05e3aSAlexander Block #include <linux/uuid.h>
1379154b1bSChris Mason #include "ctree.h"
1479154b1bSChris Mason #include "disk-io.h"
1579154b1bSChris Mason #include "transaction.h"
16925baeddSChris Mason #include "locking.h"
17e02119d5SChris Mason #include "tree-log.h"
18581bb050SLi Zefan #include "inode-map.h"
19733f4fbbSStefan Behrens #include "volumes.h"
208dabb742SStefan Behrens #include "dev-replace.h"
21fcebe456SJosef Bacik #include "qgroup.h"
2279154b1bSChris Mason 
230f7d52f4SChris Mason #define BTRFS_ROOT_TRANS_TAG 0
240f7d52f4SChris Mason 
25e8c9f186SDavid Sterba static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
264a9d8bdeSMiao Xie 	[TRANS_STATE_RUNNING]		= 0U,
27bcf3a3e7SNikolay Borisov 	[TRANS_STATE_BLOCKED]		=  __TRANS_START,
28bcf3a3e7SNikolay Borisov 	[TRANS_STATE_COMMIT_START]	= (__TRANS_START | __TRANS_ATTACH),
29bcf3a3e7SNikolay Borisov 	[TRANS_STATE_COMMIT_DOING]	= (__TRANS_START |
304a9d8bdeSMiao Xie 					   __TRANS_ATTACH |
314a9d8bdeSMiao Xie 					   __TRANS_JOIN),
32bcf3a3e7SNikolay Borisov 	[TRANS_STATE_UNBLOCKED]		= (__TRANS_START |
334a9d8bdeSMiao Xie 					   __TRANS_ATTACH |
344a9d8bdeSMiao Xie 					   __TRANS_JOIN |
354a9d8bdeSMiao Xie 					   __TRANS_JOIN_NOLOCK),
36bcf3a3e7SNikolay Borisov 	[TRANS_STATE_COMPLETED]		= (__TRANS_START |
374a9d8bdeSMiao Xie 					   __TRANS_ATTACH |
384a9d8bdeSMiao Xie 					   __TRANS_JOIN |
394a9d8bdeSMiao Xie 					   __TRANS_JOIN_NOLOCK),
404a9d8bdeSMiao Xie };
414a9d8bdeSMiao Xie 
42724e2315SJosef Bacik void btrfs_put_transaction(struct btrfs_transaction *transaction)
4379154b1bSChris Mason {
449b64f57dSElena Reshetova 	WARN_ON(refcount_read(&transaction->use_count) == 0);
459b64f57dSElena Reshetova 	if (refcount_dec_and_test(&transaction->use_count)) {
46a4abeea4SJosef Bacik 		BUG_ON(!list_empty(&transaction->list));
475c9d028bSLiu Bo 		WARN_ON(!RB_EMPTY_ROOT(
485c9d028bSLiu Bo 				&transaction->delayed_refs.href_root.rb_root));
491262133bSJosef Bacik 		if (transaction->delayed_refs.pending_csums)
50ab8d0fc4SJeff Mahoney 			btrfs_err(transaction->fs_info,
51ab8d0fc4SJeff Mahoney 				  "pending csums is %llu",
521262133bSJosef Bacik 				  transaction->delayed_refs.pending_csums);
536df9a95eSJosef Bacik 		while (!list_empty(&transaction->pending_chunks)) {
546df9a95eSJosef Bacik 			struct extent_map *em;
556df9a95eSJosef Bacik 
566df9a95eSJosef Bacik 			em = list_first_entry(&transaction->pending_chunks,
576df9a95eSJosef Bacik 					      struct extent_map, list);
586df9a95eSJosef Bacik 			list_del_init(&em->list);
596df9a95eSJosef Bacik 			free_extent_map(em);
606df9a95eSJosef Bacik 		}
617785a663SFilipe Manana 		/*
627785a663SFilipe Manana 		 * If any block groups are found in ->deleted_bgs then it's
637785a663SFilipe Manana 		 * because the transaction was aborted and a commit did not
647785a663SFilipe Manana 		 * happen (things failed before writing the new superblock
657785a663SFilipe Manana 		 * and calling btrfs_finish_extent_commit()), so we can not
667785a663SFilipe Manana 		 * discard the physical locations of the block groups.
677785a663SFilipe Manana 		 */
687785a663SFilipe Manana 		while (!list_empty(&transaction->deleted_bgs)) {
697785a663SFilipe Manana 			struct btrfs_block_group_cache *cache;
707785a663SFilipe Manana 
717785a663SFilipe Manana 			cache = list_first_entry(&transaction->deleted_bgs,
727785a663SFilipe Manana 						 struct btrfs_block_group_cache,
737785a663SFilipe Manana 						 bg_list);
747785a663SFilipe Manana 			list_del_init(&cache->bg_list);
757785a663SFilipe Manana 			btrfs_put_block_group_trimming(cache);
767785a663SFilipe Manana 			btrfs_put_block_group(cache);
777785a663SFilipe Manana 		}
78bbbf7243SNikolay Borisov 		WARN_ON(!list_empty(&transaction->dev_update_list));
794b5faeacSDavid Sterba 		kfree(transaction);
8079154b1bSChris Mason 	}
8178fae27eSChris Mason }
8279154b1bSChris Mason 
83663dfbb0SFilipe Manana static void clear_btree_io_tree(struct extent_io_tree *tree)
84663dfbb0SFilipe Manana {
85663dfbb0SFilipe Manana 	spin_lock(&tree->lock);
86b666a9cdSDavid Sterba 	/*
87b666a9cdSDavid Sterba 	 * Do a single barrier for the waitqueue_active check here, the state
88b666a9cdSDavid Sterba 	 * of the waitqueue should not change once clear_btree_io_tree is
89b666a9cdSDavid Sterba 	 * called.
90b666a9cdSDavid Sterba 	 */
91b666a9cdSDavid Sterba 	smp_mb();
92663dfbb0SFilipe Manana 	while (!RB_EMPTY_ROOT(&tree->state)) {
93663dfbb0SFilipe Manana 		struct rb_node *node;
94663dfbb0SFilipe Manana 		struct extent_state *state;
95663dfbb0SFilipe Manana 
96663dfbb0SFilipe Manana 		node = rb_first(&tree->state);
97663dfbb0SFilipe Manana 		state = rb_entry(node, struct extent_state, rb_node);
98663dfbb0SFilipe Manana 		rb_erase(&state->rb_node, &tree->state);
99663dfbb0SFilipe Manana 		RB_CLEAR_NODE(&state->rb_node);
100663dfbb0SFilipe Manana 		/*
101663dfbb0SFilipe Manana 		 * btree io trees aren't supposed to have tasks waiting for
102663dfbb0SFilipe Manana 		 * changes in the flags of extent states ever.
103663dfbb0SFilipe Manana 		 */
104663dfbb0SFilipe Manana 		ASSERT(!waitqueue_active(&state->wq));
105663dfbb0SFilipe Manana 		free_extent_state(state);
106351810c1SDavid Sterba 
107351810c1SDavid Sterba 		cond_resched_lock(&tree->lock);
108663dfbb0SFilipe Manana 	}
109663dfbb0SFilipe Manana 	spin_unlock(&tree->lock);
110663dfbb0SFilipe Manana }
111663dfbb0SFilipe Manana 
11216916a88SNikolay Borisov static noinline void switch_commit_roots(struct btrfs_transaction *trans)
113817d52f8SJosef Bacik {
11416916a88SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
1159e351cc8SJosef Bacik 	struct btrfs_root *root, *tmp;
1169e351cc8SJosef Bacik 
1179e351cc8SJosef Bacik 	down_write(&fs_info->commit_root_sem);
1189e351cc8SJosef Bacik 	list_for_each_entry_safe(root, tmp, &trans->switch_commits,
1199e351cc8SJosef Bacik 				 dirty_list) {
1209e351cc8SJosef Bacik 		list_del_init(&root->dirty_list);
121817d52f8SJosef Bacik 		free_extent_buffer(root->commit_root);
122817d52f8SJosef Bacik 		root->commit_root = btrfs_root_node(root);
1234fd786e6SMisono Tomohiro 		if (is_fstree(root->root_key.objectid))
1249e351cc8SJosef Bacik 			btrfs_unpin_free_ino(root);
125663dfbb0SFilipe Manana 		clear_btree_io_tree(&root->dirty_log_pages);
126370a11b8SQu Wenruo 		btrfs_qgroup_clean_swapped_blocks(root);
1279e351cc8SJosef Bacik 	}
1282b9dbef2SJosef Bacik 
1292b9dbef2SJosef Bacik 	/* We can free old roots now. */
1302b9dbef2SJosef Bacik 	spin_lock(&trans->dropped_roots_lock);
1312b9dbef2SJosef Bacik 	while (!list_empty(&trans->dropped_roots)) {
1322b9dbef2SJosef Bacik 		root = list_first_entry(&trans->dropped_roots,
1332b9dbef2SJosef Bacik 					struct btrfs_root, root_list);
1342b9dbef2SJosef Bacik 		list_del_init(&root->root_list);
1352b9dbef2SJosef Bacik 		spin_unlock(&trans->dropped_roots_lock);
1362b9dbef2SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, root);
1372b9dbef2SJosef Bacik 		spin_lock(&trans->dropped_roots_lock);
1382b9dbef2SJosef Bacik 	}
1392b9dbef2SJosef Bacik 	spin_unlock(&trans->dropped_roots_lock);
1409e351cc8SJosef Bacik 	up_write(&fs_info->commit_root_sem);
141817d52f8SJosef Bacik }
142817d52f8SJosef Bacik 
1430860adfdSMiao Xie static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
1440860adfdSMiao Xie 					 unsigned int type)
1450860adfdSMiao Xie {
1460860adfdSMiao Xie 	if (type & TRANS_EXTWRITERS)
1470860adfdSMiao Xie 		atomic_inc(&trans->num_extwriters);
1480860adfdSMiao Xie }
1490860adfdSMiao Xie 
1500860adfdSMiao Xie static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
1510860adfdSMiao Xie 					 unsigned int type)
1520860adfdSMiao Xie {
1530860adfdSMiao Xie 	if (type & TRANS_EXTWRITERS)
1540860adfdSMiao Xie 		atomic_dec(&trans->num_extwriters);
1550860adfdSMiao Xie }
1560860adfdSMiao Xie 
1570860adfdSMiao Xie static inline void extwriter_counter_init(struct btrfs_transaction *trans,
1580860adfdSMiao Xie 					  unsigned int type)
1590860adfdSMiao Xie {
1600860adfdSMiao Xie 	atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
1610860adfdSMiao Xie }
1620860adfdSMiao Xie 
1630860adfdSMiao Xie static inline int extwriter_counter_read(struct btrfs_transaction *trans)
1640860adfdSMiao Xie {
1650860adfdSMiao Xie 	return atomic_read(&trans->num_extwriters);
166178260b2SMiao Xie }
167178260b2SMiao Xie 
168d352ac68SChris Mason /*
169d352ac68SChris Mason  * either allocate a new transaction or hop into the existing one
170d352ac68SChris Mason  */
1712ff7e61eSJeff Mahoney static noinline int join_transaction(struct btrfs_fs_info *fs_info,
1722ff7e61eSJeff Mahoney 				     unsigned int type)
17379154b1bSChris Mason {
17479154b1bSChris Mason 	struct btrfs_transaction *cur_trans;
175a4abeea4SJosef Bacik 
17619ae4e81SJan Schmidt 	spin_lock(&fs_info->trans_lock);
177d43317dcSChris Mason loop:
17849b25e05SJeff Mahoney 	/* The file system has been taken offline. No new transactions. */
17987533c47SMiao Xie 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
18019ae4e81SJan Schmidt 		spin_unlock(&fs_info->trans_lock);
18149b25e05SJeff Mahoney 		return -EROFS;
18249b25e05SJeff Mahoney 	}
18349b25e05SJeff Mahoney 
18419ae4e81SJan Schmidt 	cur_trans = fs_info->running_transaction;
185a4abeea4SJosef Bacik 	if (cur_trans) {
186871383beSDavid Sterba 		if (cur_trans->aborted) {
18719ae4e81SJan Schmidt 			spin_unlock(&fs_info->trans_lock);
18849b25e05SJeff Mahoney 			return cur_trans->aborted;
189871383beSDavid Sterba 		}
1904a9d8bdeSMiao Xie 		if (btrfs_blocked_trans_types[cur_trans->state] & type) {
191178260b2SMiao Xie 			spin_unlock(&fs_info->trans_lock);
192178260b2SMiao Xie 			return -EBUSY;
193178260b2SMiao Xie 		}
1949b64f57dSElena Reshetova 		refcount_inc(&cur_trans->use_count);
195a4abeea4SJosef Bacik 		atomic_inc(&cur_trans->num_writers);
1960860adfdSMiao Xie 		extwriter_counter_inc(cur_trans, type);
19719ae4e81SJan Schmidt 		spin_unlock(&fs_info->trans_lock);
198a4abeea4SJosef Bacik 		return 0;
199a4abeea4SJosef Bacik 	}
20019ae4e81SJan Schmidt 	spin_unlock(&fs_info->trans_lock);
201a4abeea4SJosef Bacik 
202354aa0fbSMiao Xie 	/*
203354aa0fbSMiao Xie 	 * If we are ATTACH, we just want to catch the current transaction,
204354aa0fbSMiao Xie 	 * and commit it. If there is no transaction, just return ENOENT.
205354aa0fbSMiao Xie 	 */
206354aa0fbSMiao Xie 	if (type == TRANS_ATTACH)
207354aa0fbSMiao Xie 		return -ENOENT;
208354aa0fbSMiao Xie 
2094a9d8bdeSMiao Xie 	/*
2104a9d8bdeSMiao Xie 	 * JOIN_NOLOCK only happens during the transaction commit, so
2114a9d8bdeSMiao Xie 	 * it is impossible that ->running_transaction is NULL
2124a9d8bdeSMiao Xie 	 */
2134a9d8bdeSMiao Xie 	BUG_ON(type == TRANS_JOIN_NOLOCK);
2144a9d8bdeSMiao Xie 
2154b5faeacSDavid Sterba 	cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
216db5b493aSTsutomu Itoh 	if (!cur_trans)
217db5b493aSTsutomu Itoh 		return -ENOMEM;
218d43317dcSChris Mason 
21919ae4e81SJan Schmidt 	spin_lock(&fs_info->trans_lock);
22019ae4e81SJan Schmidt 	if (fs_info->running_transaction) {
221d43317dcSChris Mason 		/*
222d43317dcSChris Mason 		 * someone started a transaction after we unlocked.  Make sure
2234a9d8bdeSMiao Xie 		 * to redo the checks above
224d43317dcSChris Mason 		 */
2254b5faeacSDavid Sterba 		kfree(cur_trans);
226d43317dcSChris Mason 		goto loop;
22787533c47SMiao Xie 	} else if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
228e4b50e14SDan Carpenter 		spin_unlock(&fs_info->trans_lock);
2294b5faeacSDavid Sterba 		kfree(cur_trans);
2307b8b92afSJosef Bacik 		return -EROFS;
231a4abeea4SJosef Bacik 	}
232d43317dcSChris Mason 
233ab8d0fc4SJeff Mahoney 	cur_trans->fs_info = fs_info;
23413c5a93eSJosef Bacik 	atomic_set(&cur_trans->num_writers, 1);
2350860adfdSMiao Xie 	extwriter_counter_init(cur_trans, type);
23679154b1bSChris Mason 	init_waitqueue_head(&cur_trans->writer_wait);
23779154b1bSChris Mason 	init_waitqueue_head(&cur_trans->commit_wait);
2384a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_RUNNING;
239a4abeea4SJosef Bacik 	/*
240a4abeea4SJosef Bacik 	 * One for this trans handle, one so it will live on until we
241a4abeea4SJosef Bacik 	 * commit the transaction.
242a4abeea4SJosef Bacik 	 */
2439b64f57dSElena Reshetova 	refcount_set(&cur_trans->use_count, 2);
2443204d33cSJosef Bacik 	cur_trans->flags = 0;
245afd48513SArnd Bergmann 	cur_trans->start_time = ktime_get_seconds();
24656bec294SChris Mason 
247a099d0fdSAlexandru Moise 	memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
248a099d0fdSAlexandru Moise 
2495c9d028bSLiu Bo 	cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
2503368d001SQu Wenruo 	cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
251d7df2c79SJosef Bacik 	atomic_set(&cur_trans->delayed_refs.num_entries, 0);
25220b297d6SJan Schmidt 
25320b297d6SJan Schmidt 	/*
25420b297d6SJan Schmidt 	 * although the tree mod log is per file system and not per transaction,
25520b297d6SJan Schmidt 	 * the log must never go across transaction boundaries.
25620b297d6SJan Schmidt 	 */
25720b297d6SJan Schmidt 	smp_mb();
25831b1a2bdSJulia Lawall 	if (!list_empty(&fs_info->tree_mod_seq_list))
2595d163e0eSJeff Mahoney 		WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
26031b1a2bdSJulia Lawall 	if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
2615d163e0eSJeff Mahoney 		WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
262fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
26320b297d6SJan Schmidt 
26456bec294SChris Mason 	spin_lock_init(&cur_trans->delayed_refs.lock);
26556bec294SChris Mason 
2663063d29fSChris Mason 	INIT_LIST_HEAD(&cur_trans->pending_snapshots);
2676df9a95eSJosef Bacik 	INIT_LIST_HEAD(&cur_trans->pending_chunks);
268bbbf7243SNikolay Borisov 	INIT_LIST_HEAD(&cur_trans->dev_update_list);
2699e351cc8SJosef Bacik 	INIT_LIST_HEAD(&cur_trans->switch_commits);
270ce93ec54SJosef Bacik 	INIT_LIST_HEAD(&cur_trans->dirty_bgs);
2711bbc621eSChris Mason 	INIT_LIST_HEAD(&cur_trans->io_bgs);
2722b9dbef2SJosef Bacik 	INIT_LIST_HEAD(&cur_trans->dropped_roots);
2731bbc621eSChris Mason 	mutex_init(&cur_trans->cache_write_mutex);
274cb723e49SJosef Bacik 	cur_trans->num_dirty_bgs = 0;
275ce93ec54SJosef Bacik 	spin_lock_init(&cur_trans->dirty_bgs_lock);
276e33e17eeSJeff Mahoney 	INIT_LIST_HEAD(&cur_trans->deleted_bgs);
2772b9dbef2SJosef Bacik 	spin_lock_init(&cur_trans->dropped_roots_lock);
27819ae4e81SJan Schmidt 	list_add_tail(&cur_trans->list, &fs_info->trans_list);
279c258d6e3SQu Wenruo 	extent_io_tree_init(fs_info, &cur_trans->dirty_pages,
28043eb5f29SQu Wenruo 			IO_TREE_TRANS_DIRTY_PAGES, fs_info->btree_inode);
28119ae4e81SJan Schmidt 	fs_info->generation++;
28219ae4e81SJan Schmidt 	cur_trans->transid = fs_info->generation;
28319ae4e81SJan Schmidt 	fs_info->running_transaction = cur_trans;
28449b25e05SJeff Mahoney 	cur_trans->aborted = 0;
28519ae4e81SJan Schmidt 	spin_unlock(&fs_info->trans_lock);
28615ee9bc7SJosef Bacik 
28779154b1bSChris Mason 	return 0;
28879154b1bSChris Mason }
28979154b1bSChris Mason 
290d352ac68SChris Mason /*
291d397712bSChris Mason  * this does all the record keeping required to make sure that a reference
292d397712bSChris Mason  * counted root is properly recorded in a given transaction.  This is required
293d397712bSChris Mason  * to make sure the old root from before we joined the transaction is deleted
294d397712bSChris Mason  * when the transaction commits
295d352ac68SChris Mason  */
2967585717fSChris Mason static int record_root_in_trans(struct btrfs_trans_handle *trans,
2976426c7adSQu Wenruo 			       struct btrfs_root *root,
2986426c7adSQu Wenruo 			       int force)
2996702ed49SChris Mason {
3000b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3010b246afaSJeff Mahoney 
3026426c7adSQu Wenruo 	if ((test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
3036426c7adSQu Wenruo 	    root->last_trans < trans->transid) || force) {
3040b246afaSJeff Mahoney 		WARN_ON(root == fs_info->extent_root);
3054d31778aSQu Wenruo 		WARN_ON(!force && root->commit_root != root->node);
3065d4f98a2SYan Zheng 
3077585717fSChris Mason 		/*
30827cdeb70SMiao Xie 		 * see below for IN_TRANS_SETUP usage rules
3097585717fSChris Mason 		 * we have the reloc mutex held now, so there
3107585717fSChris Mason 		 * is only one writer in this function
3117585717fSChris Mason 		 */
31227cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
3137585717fSChris Mason 
31427cdeb70SMiao Xie 		/* make sure readers find IN_TRANS_SETUP before
3157585717fSChris Mason 		 * they find our root->last_trans update
3167585717fSChris Mason 		 */
3177585717fSChris Mason 		smp_wmb();
3187585717fSChris Mason 
3190b246afaSJeff Mahoney 		spin_lock(&fs_info->fs_roots_radix_lock);
3206426c7adSQu Wenruo 		if (root->last_trans == trans->transid && !force) {
3210b246afaSJeff Mahoney 			spin_unlock(&fs_info->fs_roots_radix_lock);
322a4abeea4SJosef Bacik 			return 0;
323a4abeea4SJosef Bacik 		}
3240b246afaSJeff Mahoney 		radix_tree_tag_set(&fs_info->fs_roots_radix,
3256702ed49SChris Mason 				   (unsigned long)root->root_key.objectid,
3266702ed49SChris Mason 				   BTRFS_ROOT_TRANS_TAG);
3270b246afaSJeff Mahoney 		spin_unlock(&fs_info->fs_roots_radix_lock);
3287585717fSChris Mason 		root->last_trans = trans->transid;
3297585717fSChris Mason 
3307585717fSChris Mason 		/* this is pretty tricky.  We don't want to
3317585717fSChris Mason 		 * take the relocation lock in btrfs_record_root_in_trans
3327585717fSChris Mason 		 * unless we're really doing the first setup for this root in
3337585717fSChris Mason 		 * this transaction.
3347585717fSChris Mason 		 *
3357585717fSChris Mason 		 * Normally we'd use root->last_trans as a flag to decide
3367585717fSChris Mason 		 * if we want to take the expensive mutex.
3377585717fSChris Mason 		 *
3387585717fSChris Mason 		 * But, we have to set root->last_trans before we
3397585717fSChris Mason 		 * init the relocation root, otherwise, we trip over warnings
3407585717fSChris Mason 		 * in ctree.c.  The solution used here is to flag ourselves
34127cdeb70SMiao Xie 		 * with root IN_TRANS_SETUP.  When this is 1, we're still
3427585717fSChris Mason 		 * fixing up the reloc trees and everyone must wait.
3437585717fSChris Mason 		 *
3447585717fSChris Mason 		 * When this is zero, they can trust root->last_trans and fly
3457585717fSChris Mason 		 * through btrfs_record_root_in_trans without having to take the
3467585717fSChris Mason 		 * lock.  smp_wmb() makes sure that all the writes above are
3477585717fSChris Mason 		 * done before we pop in the zero below
3487585717fSChris Mason 		 */
3495d4f98a2SYan Zheng 		btrfs_init_reloc_root(trans, root);
350c7548af6SChris Mason 		smp_mb__before_atomic();
35127cdeb70SMiao Xie 		clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
3526702ed49SChris Mason 	}
3535d4f98a2SYan Zheng 	return 0;
3546702ed49SChris Mason }
3555d4f98a2SYan Zheng 
3567585717fSChris Mason 
3572b9dbef2SJosef Bacik void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
3582b9dbef2SJosef Bacik 			    struct btrfs_root *root)
3592b9dbef2SJosef Bacik {
3600b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3612b9dbef2SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
3622b9dbef2SJosef Bacik 
3632b9dbef2SJosef Bacik 	/* Add ourselves to the transaction dropped list */
3642b9dbef2SJosef Bacik 	spin_lock(&cur_trans->dropped_roots_lock);
3652b9dbef2SJosef Bacik 	list_add_tail(&root->root_list, &cur_trans->dropped_roots);
3662b9dbef2SJosef Bacik 	spin_unlock(&cur_trans->dropped_roots_lock);
3672b9dbef2SJosef Bacik 
3682b9dbef2SJosef Bacik 	/* Make sure we don't try to update the root at commit time */
3690b246afaSJeff Mahoney 	spin_lock(&fs_info->fs_roots_radix_lock);
3700b246afaSJeff Mahoney 	radix_tree_tag_clear(&fs_info->fs_roots_radix,
3712b9dbef2SJosef Bacik 			     (unsigned long)root->root_key.objectid,
3722b9dbef2SJosef Bacik 			     BTRFS_ROOT_TRANS_TAG);
3730b246afaSJeff Mahoney 	spin_unlock(&fs_info->fs_roots_radix_lock);
3742b9dbef2SJosef Bacik }
3752b9dbef2SJosef Bacik 
3767585717fSChris Mason int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
3777585717fSChris Mason 			       struct btrfs_root *root)
3787585717fSChris Mason {
3790b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3800b246afaSJeff Mahoney 
38127cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
3827585717fSChris Mason 		return 0;
3837585717fSChris Mason 
3847585717fSChris Mason 	/*
38527cdeb70SMiao Xie 	 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
3867585717fSChris Mason 	 * and barriers
3877585717fSChris Mason 	 */
3887585717fSChris Mason 	smp_rmb();
3897585717fSChris Mason 	if (root->last_trans == trans->transid &&
39027cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
3917585717fSChris Mason 		return 0;
3927585717fSChris Mason 
3930b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
3946426c7adSQu Wenruo 	record_root_in_trans(trans, root, 0);
3950b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
3967585717fSChris Mason 
3977585717fSChris Mason 	return 0;
3987585717fSChris Mason }
3997585717fSChris Mason 
4004a9d8bdeSMiao Xie static inline int is_transaction_blocked(struct btrfs_transaction *trans)
4014a9d8bdeSMiao Xie {
4024a9d8bdeSMiao Xie 	return (trans->state >= TRANS_STATE_BLOCKED &&
403501407aaSJosef Bacik 		trans->state < TRANS_STATE_UNBLOCKED &&
404501407aaSJosef Bacik 		!trans->aborted);
4054a9d8bdeSMiao Xie }
4064a9d8bdeSMiao Xie 
407d352ac68SChris Mason /* wait for commit against the current transaction to become unblocked
408d352ac68SChris Mason  * when this is done, it is safe to start a new transaction, but the current
409d352ac68SChris Mason  * transaction might not be fully on disk.
410d352ac68SChris Mason  */
4112ff7e61eSJeff Mahoney static void wait_current_trans(struct btrfs_fs_info *fs_info)
41279154b1bSChris Mason {
413f9295749SChris Mason 	struct btrfs_transaction *cur_trans;
41479154b1bSChris Mason 
4150b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
4160b246afaSJeff Mahoney 	cur_trans = fs_info->running_transaction;
4174a9d8bdeSMiao Xie 	if (cur_trans && is_transaction_blocked(cur_trans)) {
4189b64f57dSElena Reshetova 		refcount_inc(&cur_trans->use_count);
4190b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
42072d63ed6SLi Zefan 
4210b246afaSJeff Mahoney 		wait_event(fs_info->transaction_wait,
422501407aaSJosef Bacik 			   cur_trans->state >= TRANS_STATE_UNBLOCKED ||
423501407aaSJosef Bacik 			   cur_trans->aborted);
424724e2315SJosef Bacik 		btrfs_put_transaction(cur_trans);
425a4abeea4SJosef Bacik 	} else {
4260b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
427f9295749SChris Mason 	}
42837d1aeeeSChris Mason }
42937d1aeeeSChris Mason 
4302ff7e61eSJeff Mahoney static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
43137d1aeeeSChris Mason {
4320b246afaSJeff Mahoney 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
433a4abeea4SJosef Bacik 		return 0;
434a4abeea4SJosef Bacik 
43592e2f7e3SNikolay Borisov 	if (type == TRANS_START)
436a4abeea4SJosef Bacik 		return 1;
437a4abeea4SJosef Bacik 
438a22285a6SYan, Zheng 	return 0;
439a22285a6SYan, Zheng }
440a22285a6SYan, Zheng 
44120dd2cbfSMiao Xie static inline bool need_reserve_reloc_root(struct btrfs_root *root)
44220dd2cbfSMiao Xie {
4430b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4440b246afaSJeff Mahoney 
4450b246afaSJeff Mahoney 	if (!fs_info->reloc_ctl ||
44627cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
44720dd2cbfSMiao Xie 	    root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
44820dd2cbfSMiao Xie 	    root->reloc_root)
44920dd2cbfSMiao Xie 		return false;
45020dd2cbfSMiao Xie 
45120dd2cbfSMiao Xie 	return true;
45220dd2cbfSMiao Xie }
45320dd2cbfSMiao Xie 
45408e007d2SMiao Xie static struct btrfs_trans_handle *
4555aed1dd8SAlexandru Moise start_transaction(struct btrfs_root *root, unsigned int num_items,
456003d7c59SJeff Mahoney 		  unsigned int type, enum btrfs_reserve_flush_enum flush,
457003d7c59SJeff Mahoney 		  bool enforce_qgroups)
458a22285a6SYan, Zheng {
4590b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
460ba2c4d4eSJosef Bacik 	struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
461a22285a6SYan, Zheng 	struct btrfs_trans_handle *h;
462a22285a6SYan, Zheng 	struct btrfs_transaction *cur_trans;
463b5009945SJosef Bacik 	u64 num_bytes = 0;
464c5567237SArne Jansen 	u64 qgroup_reserved = 0;
46520dd2cbfSMiao Xie 	bool reloc_reserved = false;
46620dd2cbfSMiao Xie 	int ret;
467acce952bSliubo 
46846c4e71eSFilipe Manana 	/* Send isn't supposed to start transactions. */
4692755a0deSDavid Sterba 	ASSERT(current->journal_info != BTRFS_SEND_TRANS_STUB);
47046c4e71eSFilipe Manana 
4710b246afaSJeff Mahoney 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
472acce952bSliubo 		return ERR_PTR(-EROFS);
4732a1eb461SJosef Bacik 
47446c4e71eSFilipe Manana 	if (current->journal_info) {
4750860adfdSMiao Xie 		WARN_ON(type & TRANS_EXTWRITERS);
4762a1eb461SJosef Bacik 		h = current->journal_info;
477b50fff81SDavid Sterba 		refcount_inc(&h->use_count);
478b50fff81SDavid Sterba 		WARN_ON(refcount_read(&h->use_count) > 2);
4792a1eb461SJosef Bacik 		h->orig_rsv = h->block_rsv;
4802a1eb461SJosef Bacik 		h->block_rsv = NULL;
4812a1eb461SJosef Bacik 		goto got_it;
4822a1eb461SJosef Bacik 	}
483b5009945SJosef Bacik 
484b5009945SJosef Bacik 	/*
485b5009945SJosef Bacik 	 * Do the reservation before we join the transaction so we can do all
486b5009945SJosef Bacik 	 * the appropriate flushing if need be.
487b5009945SJosef Bacik 	 */
488003d7c59SJeff Mahoney 	if (num_items && root != fs_info->chunk_root) {
489ba2c4d4eSJosef Bacik 		struct btrfs_block_rsv *rsv = &fs_info->trans_block_rsv;
490ba2c4d4eSJosef Bacik 		u64 delayed_refs_bytes = 0;
491ba2c4d4eSJosef Bacik 
4920b246afaSJeff Mahoney 		qgroup_reserved = num_items * fs_info->nodesize;
493733e03a0SQu Wenruo 		ret = btrfs_qgroup_reserve_meta_pertrans(root, qgroup_reserved,
494003d7c59SJeff Mahoney 				enforce_qgroups);
495c5567237SArne Jansen 		if (ret)
496c5567237SArne Jansen 			return ERR_PTR(ret);
497c5567237SArne Jansen 
498ba2c4d4eSJosef Bacik 		/*
499ba2c4d4eSJosef Bacik 		 * We want to reserve all the bytes we may need all at once, so
500ba2c4d4eSJosef Bacik 		 * we only do 1 enospc flushing cycle per transaction start.  We
501ba2c4d4eSJosef Bacik 		 * accomplish this by simply assuming we'll do 2 x num_items
502ba2c4d4eSJosef Bacik 		 * worth of delayed refs updates in this trans handle, and
503ba2c4d4eSJosef Bacik 		 * refill that amount for whatever is missing in the reserve.
504ba2c4d4eSJosef Bacik 		 */
5050b246afaSJeff Mahoney 		num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
506ba2c4d4eSJosef Bacik 		if (delayed_refs_rsv->full == 0) {
507ba2c4d4eSJosef Bacik 			delayed_refs_bytes = num_bytes;
508ba2c4d4eSJosef Bacik 			num_bytes <<= 1;
509ba2c4d4eSJosef Bacik 		}
510ba2c4d4eSJosef Bacik 
51120dd2cbfSMiao Xie 		/*
51220dd2cbfSMiao Xie 		 * Do the reservation for the relocation root creation
51320dd2cbfSMiao Xie 		 */
514ee39b432SDavid Sterba 		if (need_reserve_reloc_root(root)) {
5150b246afaSJeff Mahoney 			num_bytes += fs_info->nodesize;
51620dd2cbfSMiao Xie 			reloc_reserved = true;
51720dd2cbfSMiao Xie 		}
51820dd2cbfSMiao Xie 
519ba2c4d4eSJosef Bacik 		ret = btrfs_block_rsv_add(root, rsv, num_bytes, flush);
520ba2c4d4eSJosef Bacik 		if (ret)
521ba2c4d4eSJosef Bacik 			goto reserve_fail;
522ba2c4d4eSJosef Bacik 		if (delayed_refs_bytes) {
523ba2c4d4eSJosef Bacik 			btrfs_migrate_to_delayed_refs_rsv(fs_info, rsv,
524ba2c4d4eSJosef Bacik 							  delayed_refs_bytes);
525ba2c4d4eSJosef Bacik 			num_bytes -= delayed_refs_bytes;
526ba2c4d4eSJosef Bacik 		}
527ba2c4d4eSJosef Bacik 	} else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
528ba2c4d4eSJosef Bacik 		   !delayed_refs_rsv->full) {
529ba2c4d4eSJosef Bacik 		/*
530ba2c4d4eSJosef Bacik 		 * Some people call with btrfs_start_transaction(root, 0)
531ba2c4d4eSJosef Bacik 		 * because they can be throttled, but have some other mechanism
532ba2c4d4eSJosef Bacik 		 * for reserving space.  We still want these guys to refill the
533ba2c4d4eSJosef Bacik 		 * delayed block_rsv so just add 1 items worth of reservation
534ba2c4d4eSJosef Bacik 		 * here.
535ba2c4d4eSJosef Bacik 		 */
536ba2c4d4eSJosef Bacik 		ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
537b5009945SJosef Bacik 		if (ret)
538843fcf35SMiao Xie 			goto reserve_fail;
539b5009945SJosef Bacik 	}
540a22285a6SYan, Zheng again:
541f2f767e7SAlexandru Moise 	h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
542843fcf35SMiao Xie 	if (!h) {
543843fcf35SMiao Xie 		ret = -ENOMEM;
544843fcf35SMiao Xie 		goto alloc_fail;
545843fcf35SMiao Xie 	}
546a22285a6SYan, Zheng 
54798114659SJosef Bacik 	/*
54898114659SJosef Bacik 	 * If we are JOIN_NOLOCK we're already committing a transaction and
54998114659SJosef Bacik 	 * waiting on this guy, so we don't need to do the sb_start_intwrite
55098114659SJosef Bacik 	 * because we're already holding a ref.  We need this because we could
55198114659SJosef Bacik 	 * have raced in and did an fsync() on a file which can kick a commit
55298114659SJosef Bacik 	 * and then we deadlock with somebody doing a freeze.
553354aa0fbSMiao Xie 	 *
554354aa0fbSMiao Xie 	 * If we are ATTACH, it means we just want to catch the current
555354aa0fbSMiao Xie 	 * transaction and commit it, so we needn't do sb_start_intwrite().
55698114659SJosef Bacik 	 */
5570860adfdSMiao Xie 	if (type & __TRANS_FREEZABLE)
5580b246afaSJeff Mahoney 		sb_start_intwrite(fs_info->sb);
559b2b5ef5cSJan Kara 
5602ff7e61eSJeff Mahoney 	if (may_wait_transaction(fs_info, type))
5612ff7e61eSJeff Mahoney 		wait_current_trans(fs_info);
562a22285a6SYan, Zheng 
563a4abeea4SJosef Bacik 	do {
5642ff7e61eSJeff Mahoney 		ret = join_transaction(fs_info, type);
565178260b2SMiao Xie 		if (ret == -EBUSY) {
5662ff7e61eSJeff Mahoney 			wait_current_trans(fs_info);
567178260b2SMiao Xie 			if (unlikely(type == TRANS_ATTACH))
568178260b2SMiao Xie 				ret = -ENOENT;
569178260b2SMiao Xie 		}
570a4abeea4SJosef Bacik 	} while (ret == -EBUSY);
571a4abeea4SJosef Bacik 
572a43f7f82SLiu Bo 	if (ret < 0)
573843fcf35SMiao Xie 		goto join_fail;
5740f7d52f4SChris Mason 
5750b246afaSJeff Mahoney 	cur_trans = fs_info->running_transaction;
576a22285a6SYan, Zheng 
577a22285a6SYan, Zheng 	h->transid = cur_trans->transid;
578a22285a6SYan, Zheng 	h->transaction = cur_trans;
579d13603efSArne Jansen 	h->root = root;
580b50fff81SDavid Sterba 	refcount_set(&h->use_count, 1);
58164b63580SJeff Mahoney 	h->fs_info = root->fs_info;
5827174109cSQu Wenruo 
583a698d075SMiao Xie 	h->type = type;
584d9a0540aSFilipe Manana 	h->can_flush_pending_bgs = true;
585ea658badSJosef Bacik 	INIT_LIST_HEAD(&h->new_bgs);
586b7ec40d7SChris Mason 
587a22285a6SYan, Zheng 	smp_mb();
5884a9d8bdeSMiao Xie 	if (cur_trans->state >= TRANS_STATE_BLOCKED &&
5892ff7e61eSJeff Mahoney 	    may_wait_transaction(fs_info, type)) {
590abdd2e80SFilipe Manana 		current->journal_info = h;
5913a45bb20SJeff Mahoney 		btrfs_commit_transaction(h);
592a22285a6SYan, Zheng 		goto again;
593a22285a6SYan, Zheng 	}
5949ed74f2dSJosef Bacik 
595b5009945SJosef Bacik 	if (num_bytes) {
5960b246afaSJeff Mahoney 		trace_btrfs_space_reservation(fs_info, "transaction",
5972bcc0328SLiu Bo 					      h->transid, num_bytes, 1);
5980b246afaSJeff Mahoney 		h->block_rsv = &fs_info->trans_block_rsv;
599b5009945SJosef Bacik 		h->bytes_reserved = num_bytes;
60020dd2cbfSMiao Xie 		h->reloc_reserved = reloc_reserved;
601a22285a6SYan, Zheng 	}
602a22285a6SYan, Zheng 
6032a1eb461SJosef Bacik got_it:
604a4abeea4SJosef Bacik 	btrfs_record_root_in_trans(h, root);
605a22285a6SYan, Zheng 
606bcf3a3e7SNikolay Borisov 	if (!current->journal_info)
607a22285a6SYan, Zheng 		current->journal_info = h;
60879154b1bSChris Mason 	return h;
609843fcf35SMiao Xie 
610843fcf35SMiao Xie join_fail:
6110860adfdSMiao Xie 	if (type & __TRANS_FREEZABLE)
6120b246afaSJeff Mahoney 		sb_end_intwrite(fs_info->sb);
613843fcf35SMiao Xie 	kmem_cache_free(btrfs_trans_handle_cachep, h);
614843fcf35SMiao Xie alloc_fail:
615843fcf35SMiao Xie 	if (num_bytes)
6162ff7e61eSJeff Mahoney 		btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
617843fcf35SMiao Xie 					num_bytes);
618843fcf35SMiao Xie reserve_fail:
619733e03a0SQu Wenruo 	btrfs_qgroup_free_meta_pertrans(root, qgroup_reserved);
620843fcf35SMiao Xie 	return ERR_PTR(ret);
62179154b1bSChris Mason }
62279154b1bSChris Mason 
623f9295749SChris Mason struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
6245aed1dd8SAlexandru Moise 						   unsigned int num_items)
625f9295749SChris Mason {
62608e007d2SMiao Xie 	return start_transaction(root, num_items, TRANS_START,
627003d7c59SJeff Mahoney 				 BTRFS_RESERVE_FLUSH_ALL, true);
628f9295749SChris Mason }
629003d7c59SJeff Mahoney 
6308eab77ffSFilipe Manana struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
6318eab77ffSFilipe Manana 					struct btrfs_root *root,
6328eab77ffSFilipe Manana 					unsigned int num_items,
6338eab77ffSFilipe Manana 					int min_factor)
6348eab77ffSFilipe Manana {
6350b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6368eab77ffSFilipe Manana 	struct btrfs_trans_handle *trans;
6378eab77ffSFilipe Manana 	u64 num_bytes;
6388eab77ffSFilipe Manana 	int ret;
6398eab77ffSFilipe Manana 
640003d7c59SJeff Mahoney 	/*
641003d7c59SJeff Mahoney 	 * We have two callers: unlink and block group removal.  The
642003d7c59SJeff Mahoney 	 * former should succeed even if we will temporarily exceed
643003d7c59SJeff Mahoney 	 * quota and the latter operates on the extent root so
644003d7c59SJeff Mahoney 	 * qgroup enforcement is ignored anyway.
645003d7c59SJeff Mahoney 	 */
646003d7c59SJeff Mahoney 	trans = start_transaction(root, num_items, TRANS_START,
647003d7c59SJeff Mahoney 				  BTRFS_RESERVE_FLUSH_ALL, false);
6488eab77ffSFilipe Manana 	if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
6498eab77ffSFilipe Manana 		return trans;
6508eab77ffSFilipe Manana 
6518eab77ffSFilipe Manana 	trans = btrfs_start_transaction(root, 0);
6528eab77ffSFilipe Manana 	if (IS_ERR(trans))
6538eab77ffSFilipe Manana 		return trans;
6548eab77ffSFilipe Manana 
6550b246afaSJeff Mahoney 	num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
6560b246afaSJeff Mahoney 	ret = btrfs_cond_migrate_bytes(fs_info, &fs_info->trans_block_rsv,
6570b246afaSJeff Mahoney 				       num_bytes, min_factor);
6588eab77ffSFilipe Manana 	if (ret) {
6593a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
6608eab77ffSFilipe Manana 		return ERR_PTR(ret);
6618eab77ffSFilipe Manana 	}
6628eab77ffSFilipe Manana 
6630b246afaSJeff Mahoney 	trans->block_rsv = &fs_info->trans_block_rsv;
6648eab77ffSFilipe Manana 	trans->bytes_reserved = num_bytes;
6650b246afaSJeff Mahoney 	trace_btrfs_space_reservation(fs_info, "transaction",
66688d3a5aaSJosef Bacik 				      trans->transid, num_bytes, 1);
6678eab77ffSFilipe Manana 
6688eab77ffSFilipe Manana 	return trans;
6698eab77ffSFilipe Manana }
6708407aa46SMiao Xie 
6717a7eaa40SJosef Bacik struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
672f9295749SChris Mason {
673003d7c59SJeff Mahoney 	return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
674003d7c59SJeff Mahoney 				 true);
675f9295749SChris Mason }
676f9295749SChris Mason 
6777a7eaa40SJosef Bacik struct btrfs_trans_handle *btrfs_join_transaction_nolock(struct btrfs_root *root)
6780af3d00bSJosef Bacik {
679575a75d6SAlexandru Moise 	return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
680003d7c59SJeff Mahoney 				 BTRFS_RESERVE_NO_FLUSH, true);
6810af3d00bSJosef Bacik }
6820af3d00bSJosef Bacik 
683d4edf39bSMiao Xie /*
684d4edf39bSMiao Xie  * btrfs_attach_transaction() - catch the running transaction
685d4edf39bSMiao Xie  *
686d4edf39bSMiao Xie  * It is used when we want to commit the current the transaction, but
687d4edf39bSMiao Xie  * don't want to start a new one.
688d4edf39bSMiao Xie  *
689d4edf39bSMiao Xie  * Note: If this function return -ENOENT, it just means there is no
690d4edf39bSMiao Xie  * running transaction. But it is possible that the inactive transaction
691d4edf39bSMiao Xie  * is still in the memory, not fully on disk. If you hope there is no
692d4edf39bSMiao Xie  * inactive transaction in the fs when -ENOENT is returned, you should
693d4edf39bSMiao Xie  * invoke
694d4edf39bSMiao Xie  *     btrfs_attach_transaction_barrier()
695d4edf39bSMiao Xie  */
696354aa0fbSMiao Xie struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
69760376ce4SJosef Bacik {
698575a75d6SAlexandru Moise 	return start_transaction(root, 0, TRANS_ATTACH,
699003d7c59SJeff Mahoney 				 BTRFS_RESERVE_NO_FLUSH, true);
70060376ce4SJosef Bacik }
70160376ce4SJosef Bacik 
702d4edf39bSMiao Xie /*
70390b6d283SWang Sheng-Hui  * btrfs_attach_transaction_barrier() - catch the running transaction
704d4edf39bSMiao Xie  *
70552042d8eSAndrea Gelmini  * It is similar to the above function, the difference is this one
706d4edf39bSMiao Xie  * will wait for all the inactive transactions until they fully
707d4edf39bSMiao Xie  * complete.
708d4edf39bSMiao Xie  */
709d4edf39bSMiao Xie struct btrfs_trans_handle *
710d4edf39bSMiao Xie btrfs_attach_transaction_barrier(struct btrfs_root *root)
711d4edf39bSMiao Xie {
712d4edf39bSMiao Xie 	struct btrfs_trans_handle *trans;
713d4edf39bSMiao Xie 
714575a75d6SAlexandru Moise 	trans = start_transaction(root, 0, TRANS_ATTACH,
715003d7c59SJeff Mahoney 				  BTRFS_RESERVE_NO_FLUSH, true);
7168d9e220cSAl Viro 	if (trans == ERR_PTR(-ENOENT))
7172ff7e61eSJeff Mahoney 		btrfs_wait_for_commit(root->fs_info, 0);
718d4edf39bSMiao Xie 
719d4edf39bSMiao Xie 	return trans;
720d4edf39bSMiao Xie }
721d4edf39bSMiao Xie 
722d352ac68SChris Mason /* wait for a transaction commit to be fully complete */
7232ff7e61eSJeff Mahoney static noinline void wait_for_commit(struct btrfs_transaction *commit)
72489ce8a63SChris Mason {
7254a9d8bdeSMiao Xie 	wait_event(commit->commit_wait, commit->state == TRANS_STATE_COMPLETED);
72689ce8a63SChris Mason }
72789ce8a63SChris Mason 
7282ff7e61eSJeff Mahoney int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
72946204592SSage Weil {
73046204592SSage Weil 	struct btrfs_transaction *cur_trans = NULL, *t;
7318cd2807fSMiao Xie 	int ret = 0;
73246204592SSage Weil 
73346204592SSage Weil 	if (transid) {
7340b246afaSJeff Mahoney 		if (transid <= fs_info->last_trans_committed)
735a4abeea4SJosef Bacik 			goto out;
73646204592SSage Weil 
73746204592SSage Weil 		/* find specified transaction */
7380b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
7390b246afaSJeff Mahoney 		list_for_each_entry(t, &fs_info->trans_list, list) {
74046204592SSage Weil 			if (t->transid == transid) {
74146204592SSage Weil 				cur_trans = t;
7429b64f57dSElena Reshetova 				refcount_inc(&cur_trans->use_count);
7438cd2807fSMiao Xie 				ret = 0;
74446204592SSage Weil 				break;
74546204592SSage Weil 			}
7468cd2807fSMiao Xie 			if (t->transid > transid) {
7478cd2807fSMiao Xie 				ret = 0;
74846204592SSage Weil 				break;
74946204592SSage Weil 			}
7508cd2807fSMiao Xie 		}
7510b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
75242383020SSage Weil 
75342383020SSage Weil 		/*
75442383020SSage Weil 		 * The specified transaction doesn't exist, or we
75542383020SSage Weil 		 * raced with btrfs_commit_transaction
75642383020SSage Weil 		 */
75742383020SSage Weil 		if (!cur_trans) {
7580b246afaSJeff Mahoney 			if (transid > fs_info->last_trans_committed)
75942383020SSage Weil 				ret = -EINVAL;
7608cd2807fSMiao Xie 			goto out;
76142383020SSage Weil 		}
76246204592SSage Weil 	} else {
76346204592SSage Weil 		/* find newest transaction that is committing | committed */
7640b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
7650b246afaSJeff Mahoney 		list_for_each_entry_reverse(t, &fs_info->trans_list,
76646204592SSage Weil 					    list) {
7674a9d8bdeSMiao Xie 			if (t->state >= TRANS_STATE_COMMIT_START) {
7684a9d8bdeSMiao Xie 				if (t->state == TRANS_STATE_COMPLETED)
7693473f3c0SJosef Bacik 					break;
77046204592SSage Weil 				cur_trans = t;
7719b64f57dSElena Reshetova 				refcount_inc(&cur_trans->use_count);
77246204592SSage Weil 				break;
77346204592SSage Weil 			}
77446204592SSage Weil 		}
7750b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
77646204592SSage Weil 		if (!cur_trans)
777a4abeea4SJosef Bacik 			goto out;  /* nothing committing|committed */
77846204592SSage Weil 	}
77946204592SSage Weil 
7802ff7e61eSJeff Mahoney 	wait_for_commit(cur_trans);
781724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
782a4abeea4SJosef Bacik out:
78346204592SSage Weil 	return ret;
78446204592SSage Weil }
78546204592SSage Weil 
7862ff7e61eSJeff Mahoney void btrfs_throttle(struct btrfs_fs_info *fs_info)
78737d1aeeeSChris Mason {
7882ff7e61eSJeff Mahoney 	wait_current_trans(fs_info);
78937d1aeeeSChris Mason }
79037d1aeeeSChris Mason 
7912ff7e61eSJeff Mahoney static int should_end_transaction(struct btrfs_trans_handle *trans)
7928929ecfaSYan, Zheng {
7932ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = trans->fs_info;
7940b246afaSJeff Mahoney 
79564403612SJosef Bacik 	if (btrfs_check_space_for_delayed_refs(fs_info))
7961be41b78SJosef Bacik 		return 1;
79736ba022aSJosef Bacik 
7982ff7e61eSJeff Mahoney 	return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
7998929ecfaSYan, Zheng }
8008929ecfaSYan, Zheng 
8013a45bb20SJeff Mahoney int btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
8028929ecfaSYan, Zheng {
8038929ecfaSYan, Zheng 	struct btrfs_transaction *cur_trans = trans->transaction;
8048929ecfaSYan, Zheng 
805a4abeea4SJosef Bacik 	smp_mb();
8064a9d8bdeSMiao Xie 	if (cur_trans->state >= TRANS_STATE_BLOCKED ||
8074a9d8bdeSMiao Xie 	    cur_trans->delayed_refs.flushing)
8088929ecfaSYan, Zheng 		return 1;
8098929ecfaSYan, Zheng 
8102ff7e61eSJeff Mahoney 	return should_end_transaction(trans);
8118929ecfaSYan, Zheng }
8128929ecfaSYan, Zheng 
813dc60c525SNikolay Borisov static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
814dc60c525SNikolay Borisov 
8150e34693fSNikolay Borisov {
816dc60c525SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
817dc60c525SNikolay Borisov 
8180e34693fSNikolay Borisov 	if (!trans->block_rsv) {
8190e34693fSNikolay Borisov 		ASSERT(!trans->bytes_reserved);
8200e34693fSNikolay Borisov 		return;
8210e34693fSNikolay Borisov 	}
8220e34693fSNikolay Borisov 
8230e34693fSNikolay Borisov 	if (!trans->bytes_reserved)
8240e34693fSNikolay Borisov 		return;
8250e34693fSNikolay Borisov 
8260e34693fSNikolay Borisov 	ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
8270e34693fSNikolay Borisov 	trace_btrfs_space_reservation(fs_info, "transaction",
8280e34693fSNikolay Borisov 				      trans->transid, trans->bytes_reserved, 0);
8290e34693fSNikolay Borisov 	btrfs_block_rsv_release(fs_info, trans->block_rsv,
8300e34693fSNikolay Borisov 				trans->bytes_reserved);
8310e34693fSNikolay Borisov 	trans->bytes_reserved = 0;
8320e34693fSNikolay Borisov }
8330e34693fSNikolay Borisov 
83489ce8a63SChris Mason static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
8353a45bb20SJeff Mahoney 				   int throttle)
83679154b1bSChris Mason {
8373a45bb20SJeff Mahoney 	struct btrfs_fs_info *info = trans->fs_info;
8388929ecfaSYan, Zheng 	struct btrfs_transaction *cur_trans = trans->transaction;
839a698d075SMiao Xie 	int lock = (trans->type != TRANS_JOIN_NOLOCK);
8404edc2ca3SDave Jones 	int err = 0;
841d6e4a428SChris Mason 
842b50fff81SDavid Sterba 	if (refcount_read(&trans->use_count) > 1) {
843b50fff81SDavid Sterba 		refcount_dec(&trans->use_count);
8442a1eb461SJosef Bacik 		trans->block_rsv = trans->orig_rsv;
8452a1eb461SJosef Bacik 		return 0;
8462a1eb461SJosef Bacik 	}
8472a1eb461SJosef Bacik 
848dc60c525SNikolay Borisov 	btrfs_trans_release_metadata(trans);
8494c13d758SJosef Bacik 	trans->block_rsv = NULL;
850c5567237SArne Jansen 
8516c686b35SNikolay Borisov 	btrfs_create_pending_block_groups(trans);
852ea658badSJosef Bacik 
8534fbcdf66SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
8544fbcdf66SFilipe Manana 
85520c7bcecSSeraphime Kirkovski 	if (lock && READ_ONCE(cur_trans->state) == TRANS_STATE_BLOCKED) {
8563bbb24b2SJosef Bacik 		if (throttle)
8573a45bb20SJeff Mahoney 			return btrfs_commit_transaction(trans);
8583bbb24b2SJosef Bacik 		else
8598929ecfaSYan, Zheng 			wake_up_process(info->transaction_kthread);
8608929ecfaSYan, Zheng 	}
8618929ecfaSYan, Zheng 
8620860adfdSMiao Xie 	if (trans->type & __TRANS_FREEZABLE)
8630b246afaSJeff Mahoney 		sb_end_intwrite(info->sb);
8646df7881aSJosef Bacik 
8658929ecfaSYan, Zheng 	WARN_ON(cur_trans != info->running_transaction);
86613c5a93eSJosef Bacik 	WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
86713c5a93eSJosef Bacik 	atomic_dec(&cur_trans->num_writers);
8680860adfdSMiao Xie 	extwriter_counter_dec(cur_trans, trans->type);
86989ce8a63SChris Mason 
870093258e6SDavid Sterba 	cond_wake_up(&cur_trans->writer_wait);
871724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
8729ed74f2dSJosef Bacik 
8739ed74f2dSJosef Bacik 	if (current->journal_info == trans)
8749ed74f2dSJosef Bacik 		current->journal_info = NULL;
875ab78c84dSChris Mason 
87624bbcf04SYan, Zheng 	if (throttle)
8772ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(info);
87824bbcf04SYan, Zheng 
87949b25e05SJeff Mahoney 	if (trans->aborted ||
8800b246afaSJeff Mahoney 	    test_bit(BTRFS_FS_STATE_ERROR, &info->fs_state)) {
8814e121c06SJosef Bacik 		wake_up_process(info->transaction_kthread);
8824edc2ca3SDave Jones 		err = -EIO;
8834e121c06SJosef Bacik 	}
88449b25e05SJeff Mahoney 
8854edc2ca3SDave Jones 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
8864edc2ca3SDave Jones 	return err;
88779154b1bSChris Mason }
88879154b1bSChris Mason 
8893a45bb20SJeff Mahoney int btrfs_end_transaction(struct btrfs_trans_handle *trans)
89089ce8a63SChris Mason {
8913a45bb20SJeff Mahoney 	return __btrfs_end_transaction(trans, 0);
89289ce8a63SChris Mason }
89389ce8a63SChris Mason 
8943a45bb20SJeff Mahoney int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
89589ce8a63SChris Mason {
8963a45bb20SJeff Mahoney 	return __btrfs_end_transaction(trans, 1);
89716cdcec7SMiao Xie }
89816cdcec7SMiao Xie 
899d352ac68SChris Mason /*
900d352ac68SChris Mason  * when btree blocks are allocated, they have some corresponding bits set for
901d352ac68SChris Mason  * them in one of two extent_io trees.  This is used to make sure all of
902690587d1SChris Mason  * those extents are sent to disk but does not wait on them
903d352ac68SChris Mason  */
9042ff7e61eSJeff Mahoney int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
9058cef4e16SYan, Zheng 			       struct extent_io_tree *dirty_pages, int mark)
90679154b1bSChris Mason {
907777e6bd7SChris Mason 	int err = 0;
9087c4452b9SChris Mason 	int werr = 0;
9090b246afaSJeff Mahoney 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
910e6138876SJosef Bacik 	struct extent_state *cached_state = NULL;
911777e6bd7SChris Mason 	u64 start = 0;
9125f39d397SChris Mason 	u64 end;
9137c4452b9SChris Mason 
9146300463bSLiu Bo 	atomic_inc(&BTRFS_I(fs_info->btree_inode)->sync_writers);
9151728366eSJosef Bacik 	while (!find_first_extent_bit(dirty_pages, start, &start, &end,
916e6138876SJosef Bacik 				      mark, &cached_state)) {
917663dfbb0SFilipe Manana 		bool wait_writeback = false;
918663dfbb0SFilipe Manana 
919663dfbb0SFilipe Manana 		err = convert_extent_bit(dirty_pages, start, end,
920663dfbb0SFilipe Manana 					 EXTENT_NEED_WAIT,
921210aa277SDavid Sterba 					 mark, &cached_state);
922663dfbb0SFilipe Manana 		/*
923663dfbb0SFilipe Manana 		 * convert_extent_bit can return -ENOMEM, which is most of the
924663dfbb0SFilipe Manana 		 * time a temporary error. So when it happens, ignore the error
925663dfbb0SFilipe Manana 		 * and wait for writeback of this range to finish - because we
926663dfbb0SFilipe Manana 		 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
927bf89d38fSJeff Mahoney 		 * to __btrfs_wait_marked_extents() would not know that
928bf89d38fSJeff Mahoney 		 * writeback for this range started and therefore wouldn't
929bf89d38fSJeff Mahoney 		 * wait for it to finish - we don't want to commit a
930bf89d38fSJeff Mahoney 		 * superblock that points to btree nodes/leafs for which
931bf89d38fSJeff Mahoney 		 * writeback hasn't finished yet (and without errors).
932663dfbb0SFilipe Manana 		 * We cleanup any entries left in the io tree when committing
933663dfbb0SFilipe Manana 		 * the transaction (through clear_btree_io_tree()).
934663dfbb0SFilipe Manana 		 */
935663dfbb0SFilipe Manana 		if (err == -ENOMEM) {
936663dfbb0SFilipe Manana 			err = 0;
937663dfbb0SFilipe Manana 			wait_writeback = true;
938663dfbb0SFilipe Manana 		}
939663dfbb0SFilipe Manana 		if (!err)
9401728366eSJosef Bacik 			err = filemap_fdatawrite_range(mapping, start, end);
9417c4452b9SChris Mason 		if (err)
9427c4452b9SChris Mason 			werr = err;
943663dfbb0SFilipe Manana 		else if (wait_writeback)
944663dfbb0SFilipe Manana 			werr = filemap_fdatawait_range(mapping, start, end);
945e38e2ed7SFilipe Manana 		free_extent_state(cached_state);
946663dfbb0SFilipe Manana 		cached_state = NULL;
9471728366eSJosef Bacik 		cond_resched();
9481728366eSJosef Bacik 		start = end + 1;
9497c4452b9SChris Mason 	}
9506300463bSLiu Bo 	atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
951690587d1SChris Mason 	return werr;
952690587d1SChris Mason }
953690587d1SChris Mason 
954690587d1SChris Mason /*
955690587d1SChris Mason  * when btree blocks are allocated, they have some corresponding bits set for
956690587d1SChris Mason  * them in one of two extent_io trees.  This is used to make sure all of
957690587d1SChris Mason  * those extents are on disk for transaction or log commit.  We wait
958690587d1SChris Mason  * on all the pages and clear them from the dirty pages state tree
959690587d1SChris Mason  */
960bf89d38fSJeff Mahoney static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
961bf89d38fSJeff Mahoney 				       struct extent_io_tree *dirty_pages)
962690587d1SChris Mason {
963690587d1SChris Mason 	int err = 0;
964690587d1SChris Mason 	int werr = 0;
9650b246afaSJeff Mahoney 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
966e6138876SJosef Bacik 	struct extent_state *cached_state = NULL;
967690587d1SChris Mason 	u64 start = 0;
968690587d1SChris Mason 	u64 end;
969690587d1SChris Mason 
9701728366eSJosef Bacik 	while (!find_first_extent_bit(dirty_pages, start, &start, &end,
971e6138876SJosef Bacik 				      EXTENT_NEED_WAIT, &cached_state)) {
972663dfbb0SFilipe Manana 		/*
973663dfbb0SFilipe Manana 		 * Ignore -ENOMEM errors returned by clear_extent_bit().
974663dfbb0SFilipe Manana 		 * When committing the transaction, we'll remove any entries
975663dfbb0SFilipe Manana 		 * left in the io tree. For a log commit, we don't remove them
976663dfbb0SFilipe Manana 		 * after committing the log because the tree can be accessed
977663dfbb0SFilipe Manana 		 * concurrently - we do it only at transaction commit time when
978663dfbb0SFilipe Manana 		 * it's safe to do it (through clear_btree_io_tree()).
979663dfbb0SFilipe Manana 		 */
980663dfbb0SFilipe Manana 		err = clear_extent_bit(dirty_pages, start, end,
981ae0f1625SDavid Sterba 				       EXTENT_NEED_WAIT, 0, 0, &cached_state);
982663dfbb0SFilipe Manana 		if (err == -ENOMEM)
983663dfbb0SFilipe Manana 			err = 0;
984663dfbb0SFilipe Manana 		if (!err)
9851728366eSJosef Bacik 			err = filemap_fdatawait_range(mapping, start, end);
986777e6bd7SChris Mason 		if (err)
987777e6bd7SChris Mason 			werr = err;
988e38e2ed7SFilipe Manana 		free_extent_state(cached_state);
989e38e2ed7SFilipe Manana 		cached_state = NULL;
990777e6bd7SChris Mason 		cond_resched();
9911728366eSJosef Bacik 		start = end + 1;
992777e6bd7SChris Mason 	}
9937c4452b9SChris Mason 	if (err)
9947c4452b9SChris Mason 		werr = err;
995bf89d38fSJeff Mahoney 	return werr;
996bf89d38fSJeff Mahoney }
997656f30dbSFilipe Manana 
998bf89d38fSJeff Mahoney int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
999bf89d38fSJeff Mahoney 		       struct extent_io_tree *dirty_pages)
1000bf89d38fSJeff Mahoney {
1001bf89d38fSJeff Mahoney 	bool errors = false;
1002bf89d38fSJeff Mahoney 	int err;
1003bf89d38fSJeff Mahoney 
1004bf89d38fSJeff Mahoney 	err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1005bf89d38fSJeff Mahoney 	if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1006bf89d38fSJeff Mahoney 		errors = true;
1007bf89d38fSJeff Mahoney 
1008bf89d38fSJeff Mahoney 	if (errors && !err)
1009bf89d38fSJeff Mahoney 		err = -EIO;
1010bf89d38fSJeff Mahoney 	return err;
1011bf89d38fSJeff Mahoney }
1012bf89d38fSJeff Mahoney 
1013bf89d38fSJeff Mahoney int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1014bf89d38fSJeff Mahoney {
1015bf89d38fSJeff Mahoney 	struct btrfs_fs_info *fs_info = log_root->fs_info;
1016bf89d38fSJeff Mahoney 	struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1017bf89d38fSJeff Mahoney 	bool errors = false;
1018bf89d38fSJeff Mahoney 	int err;
1019bf89d38fSJeff Mahoney 
1020bf89d38fSJeff Mahoney 	ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1021bf89d38fSJeff Mahoney 
1022bf89d38fSJeff Mahoney 	err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1023656f30dbSFilipe Manana 	if ((mark & EXTENT_DIRTY) &&
10240b246afaSJeff Mahoney 	    test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1025656f30dbSFilipe Manana 		errors = true;
1026656f30dbSFilipe Manana 
1027656f30dbSFilipe Manana 	if ((mark & EXTENT_NEW) &&
10280b246afaSJeff Mahoney 	    test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1029656f30dbSFilipe Manana 		errors = true;
1030656f30dbSFilipe Manana 
1031bf89d38fSJeff Mahoney 	if (errors && !err)
1032bf89d38fSJeff Mahoney 		err = -EIO;
1033bf89d38fSJeff Mahoney 	return err;
103479154b1bSChris Mason }
103579154b1bSChris Mason 
1036690587d1SChris Mason /*
1037c9b577c0SNikolay Borisov  * When btree blocks are allocated the corresponding extents are marked dirty.
1038c9b577c0SNikolay Borisov  * This function ensures such extents are persisted on disk for transaction or
1039c9b577c0SNikolay Borisov  * log commit.
1040c9b577c0SNikolay Borisov  *
1041c9b577c0SNikolay Borisov  * @trans: transaction whose dirty pages we'd like to write
1042690587d1SChris Mason  */
104370458a58SNikolay Borisov static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1044d0c803c4SChris Mason {
1045663dfbb0SFilipe Manana 	int ret;
1046c9b577c0SNikolay Borisov 	int ret2;
1047c9b577c0SNikolay Borisov 	struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
104870458a58SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
1049c9b577c0SNikolay Borisov 	struct blk_plug plug;
1050663dfbb0SFilipe Manana 
1051c9b577c0SNikolay Borisov 	blk_start_plug(&plug);
1052c9b577c0SNikolay Borisov 	ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1053c9b577c0SNikolay Borisov 	blk_finish_plug(&plug);
1054c9b577c0SNikolay Borisov 	ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1055c9b577c0SNikolay Borisov 
1056663dfbb0SFilipe Manana 	clear_btree_io_tree(&trans->transaction->dirty_pages);
1057663dfbb0SFilipe Manana 
1058c9b577c0SNikolay Borisov 	if (ret)
1059663dfbb0SFilipe Manana 		return ret;
1060c9b577c0SNikolay Borisov 	else if (ret2)
1061c9b577c0SNikolay Borisov 		return ret2;
1062c9b577c0SNikolay Borisov 	else
1063c9b577c0SNikolay Borisov 		return 0;
1064d0c803c4SChris Mason }
1065d0c803c4SChris Mason 
1066d352ac68SChris Mason /*
1067d352ac68SChris Mason  * this is used to update the root pointer in the tree of tree roots.
1068d352ac68SChris Mason  *
1069d352ac68SChris Mason  * But, in the case of the extent allocation tree, updating the root
1070d352ac68SChris Mason  * pointer may allocate blocks which may change the root of the extent
1071d352ac68SChris Mason  * allocation tree.
1072d352ac68SChris Mason  *
1073d352ac68SChris Mason  * So, this loops and repeats and makes sure the cowonly root didn't
1074d352ac68SChris Mason  * change while the root pointer was being updated in the metadata.
1075d352ac68SChris Mason  */
10760b86a832SChris Mason static int update_cowonly_root(struct btrfs_trans_handle *trans,
107779154b1bSChris Mason 			       struct btrfs_root *root)
107879154b1bSChris Mason {
107979154b1bSChris Mason 	int ret;
10800b86a832SChris Mason 	u64 old_root_bytenr;
108186b9f2ecSYan, Zheng 	u64 old_root_used;
10820b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10830b246afaSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
108479154b1bSChris Mason 
108586b9f2ecSYan, Zheng 	old_root_used = btrfs_root_used(&root->root_item);
108656bec294SChris Mason 
108779154b1bSChris Mason 	while (1) {
10880b86a832SChris Mason 		old_root_bytenr = btrfs_root_bytenr(&root->root_item);
108986b9f2ecSYan, Zheng 		if (old_root_bytenr == root->node->start &&
1090ea526d18SJosef Bacik 		    old_root_used == btrfs_root_used(&root->root_item))
109179154b1bSChris Mason 			break;
109287ef2bb4SChris Mason 
10935d4f98a2SYan Zheng 		btrfs_set_root_node(&root->root_item, root->node);
109479154b1bSChris Mason 		ret = btrfs_update_root(trans, tree_root,
10950b86a832SChris Mason 					&root->root_key,
10960b86a832SChris Mason 					&root->root_item);
109749b25e05SJeff Mahoney 		if (ret)
109849b25e05SJeff Mahoney 			return ret;
109956bec294SChris Mason 
110086b9f2ecSYan, Zheng 		old_root_used = btrfs_root_used(&root->root_item);
1101e7070be1SJosef Bacik 	}
1102276e680dSYan Zheng 
11030b86a832SChris Mason 	return 0;
11040b86a832SChris Mason }
11050b86a832SChris Mason 
1106d352ac68SChris Mason /*
1107d352ac68SChris Mason  * update all the cowonly tree roots on disk
110849b25e05SJeff Mahoney  *
110949b25e05SJeff Mahoney  * The error handling in this function may not be obvious. Any of the
111049b25e05SJeff Mahoney  * failures will cause the file system to go offline. We still need
111149b25e05SJeff Mahoney  * to clean up the delayed refs.
1112d352ac68SChris Mason  */
11139386d8bcSNikolay Borisov static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
11140b86a832SChris Mason {
11159386d8bcSNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
1116ea526d18SJosef Bacik 	struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
11171bbc621eSChris Mason 	struct list_head *io_bgs = &trans->transaction->io_bgs;
11180b86a832SChris Mason 	struct list_head *next;
111984234f3aSYan Zheng 	struct extent_buffer *eb;
112056bec294SChris Mason 	int ret;
112184234f3aSYan Zheng 
112284234f3aSYan Zheng 	eb = btrfs_lock_root_node(fs_info->tree_root);
112349b25e05SJeff Mahoney 	ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
112449b25e05SJeff Mahoney 			      0, &eb);
112584234f3aSYan Zheng 	btrfs_tree_unlock(eb);
112684234f3aSYan Zheng 	free_extent_buffer(eb);
11270b86a832SChris Mason 
112849b25e05SJeff Mahoney 	if (ret)
112949b25e05SJeff Mahoney 		return ret;
113049b25e05SJeff Mahoney 
1131c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
113249b25e05SJeff Mahoney 	if (ret)
113349b25e05SJeff Mahoney 		return ret;
113487ef2bb4SChris Mason 
11350b246afaSJeff Mahoney 	ret = btrfs_run_dev_stats(trans, fs_info);
1136c16ce190SJosef Bacik 	if (ret)
1137c16ce190SJosef Bacik 		return ret;
11380b246afaSJeff Mahoney 	ret = btrfs_run_dev_replace(trans, fs_info);
1139c16ce190SJosef Bacik 	if (ret)
1140c16ce190SJosef Bacik 		return ret;
1141280f8bd2SLu Fengqi 	ret = btrfs_run_qgroups(trans);
1142c16ce190SJosef Bacik 	if (ret)
1143c16ce190SJosef Bacik 		return ret;
1144546adb0dSJan Schmidt 
11452ff7e61eSJeff Mahoney 	ret = btrfs_setup_space_cache(trans, fs_info);
1146dcdf7f6dSJosef Bacik 	if (ret)
1147dcdf7f6dSJosef Bacik 		return ret;
1148dcdf7f6dSJosef Bacik 
1149546adb0dSJan Schmidt 	/* run_qgroups might have added some more refs */
1150c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1151c16ce190SJosef Bacik 	if (ret)
1152c16ce190SJosef Bacik 		return ret;
1153ea526d18SJosef Bacik again:
11540b86a832SChris Mason 	while (!list_empty(&fs_info->dirty_cowonly_roots)) {
11552ff7e61eSJeff Mahoney 		struct btrfs_root *root;
11560b86a832SChris Mason 		next = fs_info->dirty_cowonly_roots.next;
11570b86a832SChris Mason 		list_del_init(next);
11580b86a832SChris Mason 		root = list_entry(next, struct btrfs_root, dirty_list);
1159e7070be1SJosef Bacik 		clear_bit(BTRFS_ROOT_DIRTY, &root->state);
116087ef2bb4SChris Mason 
11619e351cc8SJosef Bacik 		if (root != fs_info->extent_root)
11629e351cc8SJosef Bacik 			list_add_tail(&root->dirty_list,
11639e351cc8SJosef Bacik 				      &trans->transaction->switch_commits);
116449b25e05SJeff Mahoney 		ret = update_cowonly_root(trans, root);
116549b25e05SJeff Mahoney 		if (ret)
116649b25e05SJeff Mahoney 			return ret;
1167c79a70b1SNikolay Borisov 		ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1168ea526d18SJosef Bacik 		if (ret)
1169ea526d18SJosef Bacik 			return ret;
117079154b1bSChris Mason 	}
1171276e680dSYan Zheng 
11721bbc621eSChris Mason 	while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
11732ff7e61eSJeff Mahoney 		ret = btrfs_write_dirty_block_groups(trans, fs_info);
1174ea526d18SJosef Bacik 		if (ret)
1175ea526d18SJosef Bacik 			return ret;
1176c79a70b1SNikolay Borisov 		ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1177ea526d18SJosef Bacik 		if (ret)
1178ea526d18SJosef Bacik 			return ret;
1179ea526d18SJosef Bacik 	}
1180ea526d18SJosef Bacik 
1181ea526d18SJosef Bacik 	if (!list_empty(&fs_info->dirty_cowonly_roots))
1182ea526d18SJosef Bacik 		goto again;
1183ea526d18SJosef Bacik 
11849e351cc8SJosef Bacik 	list_add_tail(&fs_info->extent_root->dirty_list,
11859e351cc8SJosef Bacik 		      &trans->transaction->switch_commits);
11869f6cbcbbSDavid Sterba 
11879f6cbcbbSDavid Sterba 	/* Update dev-replace pointer once everything is committed */
11889f6cbcbbSDavid Sterba 	fs_info->dev_replace.committed_cursor_left =
11899f6cbcbbSDavid Sterba 		fs_info->dev_replace.cursor_left_last_write_of_item;
11908dabb742SStefan Behrens 
119179154b1bSChris Mason 	return 0;
119279154b1bSChris Mason }
119379154b1bSChris Mason 
1194d352ac68SChris Mason /*
1195d352ac68SChris Mason  * dead roots are old snapshots that need to be deleted.  This allocates
1196d352ac68SChris Mason  * a dirty root struct and adds it into the list of dead roots that need to
1197d352ac68SChris Mason  * be deleted
1198d352ac68SChris Mason  */
1199cfad392bSJosef Bacik void btrfs_add_dead_root(struct btrfs_root *root)
12005eda7b5eSChris Mason {
12010b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12020b246afaSJeff Mahoney 
12030b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
1204cfad392bSJosef Bacik 	if (list_empty(&root->root_list))
12050b246afaSJeff Mahoney 		list_add_tail(&root->root_list, &fs_info->dead_roots);
12060b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
12075eda7b5eSChris Mason }
12085eda7b5eSChris Mason 
1209d352ac68SChris Mason /*
12105d4f98a2SYan Zheng  * update all the cowonly tree roots on disk
1211d352ac68SChris Mason  */
12127e4443d9SNikolay Borisov static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
12130f7d52f4SChris Mason {
12147e4443d9SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
12150f7d52f4SChris Mason 	struct btrfs_root *gang[8];
12160f7d52f4SChris Mason 	int i;
12170f7d52f4SChris Mason 	int ret;
121854aa1f4dSChris Mason 	int err = 0;
121954aa1f4dSChris Mason 
1220a4abeea4SJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
12210f7d52f4SChris Mason 	while (1) {
12225d4f98a2SYan Zheng 		ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
12235d4f98a2SYan Zheng 						 (void **)gang, 0,
12240f7d52f4SChris Mason 						 ARRAY_SIZE(gang),
12250f7d52f4SChris Mason 						 BTRFS_ROOT_TRANS_TAG);
12260f7d52f4SChris Mason 		if (ret == 0)
12270f7d52f4SChris Mason 			break;
12280f7d52f4SChris Mason 		for (i = 0; i < ret; i++) {
12295b4aacefSJeff Mahoney 			struct btrfs_root *root = gang[i];
12305d4f98a2SYan Zheng 			radix_tree_tag_clear(&fs_info->fs_roots_radix,
12312619ba1fSChris Mason 					(unsigned long)root->root_key.objectid,
12320f7d52f4SChris Mason 					BTRFS_ROOT_TRANS_TAG);
1233a4abeea4SJosef Bacik 			spin_unlock(&fs_info->fs_roots_radix_lock);
123431153d81SYan Zheng 
1235e02119d5SChris Mason 			btrfs_free_log(trans, root);
12365d4f98a2SYan Zheng 			btrfs_update_reloc_root(trans, root);
1237e02119d5SChris Mason 
123882d5902dSLi Zefan 			btrfs_save_ino_cache(root, trans);
123982d5902dSLi Zefan 
1240f1ebcc74SLiu Bo 			/* see comments in should_cow_block() */
124127cdeb70SMiao Xie 			clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1242c7548af6SChris Mason 			smp_mb__after_atomic();
1243f1ebcc74SLiu Bo 
1244978d910dSYan Zheng 			if (root->commit_root != root->node) {
12459e351cc8SJosef Bacik 				list_add_tail(&root->dirty_list,
12469e351cc8SJosef Bacik 					&trans->transaction->switch_commits);
1247978d910dSYan Zheng 				btrfs_set_root_node(&root->root_item,
1248978d910dSYan Zheng 						    root->node);
1249978d910dSYan Zheng 			}
125031153d81SYan Zheng 
12515d4f98a2SYan Zheng 			err = btrfs_update_root(trans, fs_info->tree_root,
12520f7d52f4SChris Mason 						&root->root_key,
12530f7d52f4SChris Mason 						&root->root_item);
1254a4abeea4SJosef Bacik 			spin_lock(&fs_info->fs_roots_radix_lock);
125554aa1f4dSChris Mason 			if (err)
125654aa1f4dSChris Mason 				break;
1257733e03a0SQu Wenruo 			btrfs_qgroup_free_meta_all_pertrans(root);
12580f7d52f4SChris Mason 		}
12599f3a7427SChris Mason 	}
1260a4abeea4SJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
126154aa1f4dSChris Mason 	return err;
12620f7d52f4SChris Mason }
12630f7d52f4SChris Mason 
1264d352ac68SChris Mason /*
1265de78b51aSEric Sandeen  * defrag a given btree.
1266de78b51aSEric Sandeen  * Every leaf in the btree is read and defragged.
1267d352ac68SChris Mason  */
1268de78b51aSEric Sandeen int btrfs_defrag_root(struct btrfs_root *root)
1269e9d0b13bSChris Mason {
1270e9d0b13bSChris Mason 	struct btrfs_fs_info *info = root->fs_info;
1271e9d0b13bSChris Mason 	struct btrfs_trans_handle *trans;
12728929ecfaSYan, Zheng 	int ret;
1273e9d0b13bSChris Mason 
127427cdeb70SMiao Xie 	if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1275e9d0b13bSChris Mason 		return 0;
12768929ecfaSYan, Zheng 
12776b80053dSChris Mason 	while (1) {
12788929ecfaSYan, Zheng 		trans = btrfs_start_transaction(root, 0);
12798929ecfaSYan, Zheng 		if (IS_ERR(trans))
12808929ecfaSYan, Zheng 			return PTR_ERR(trans);
12818929ecfaSYan, Zheng 
1282de78b51aSEric Sandeen 		ret = btrfs_defrag_leaves(trans, root);
12838929ecfaSYan, Zheng 
12843a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
12852ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(info);
1286e9d0b13bSChris Mason 		cond_resched();
1287e9d0b13bSChris Mason 
1288ab8d0fc4SJeff Mahoney 		if (btrfs_fs_closing(info) || ret != -EAGAIN)
1289e9d0b13bSChris Mason 			break;
1290210549ebSDavid Sterba 
1291ab8d0fc4SJeff Mahoney 		if (btrfs_defrag_cancelled(info)) {
1292ab8d0fc4SJeff Mahoney 			btrfs_debug(info, "defrag_root cancelled");
1293210549ebSDavid Sterba 			ret = -EAGAIN;
1294210549ebSDavid Sterba 			break;
1295210549ebSDavid Sterba 		}
1296e9d0b13bSChris Mason 	}
129727cdeb70SMiao Xie 	clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
12988929ecfaSYan, Zheng 	return ret;
1299e9d0b13bSChris Mason }
1300e9d0b13bSChris Mason 
1301d352ac68SChris Mason /*
13026426c7adSQu Wenruo  * Do all special snapshot related qgroup dirty hack.
13036426c7adSQu Wenruo  *
13046426c7adSQu Wenruo  * Will do all needed qgroup inherit and dirty hack like switch commit
13056426c7adSQu Wenruo  * roots inside one transaction and write all btree into disk, to make
13066426c7adSQu Wenruo  * qgroup works.
13076426c7adSQu Wenruo  */
13086426c7adSQu Wenruo static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
13096426c7adSQu Wenruo 				   struct btrfs_root *src,
13106426c7adSQu Wenruo 				   struct btrfs_root *parent,
13116426c7adSQu Wenruo 				   struct btrfs_qgroup_inherit *inherit,
13126426c7adSQu Wenruo 				   u64 dst_objectid)
13136426c7adSQu Wenruo {
13146426c7adSQu Wenruo 	struct btrfs_fs_info *fs_info = src->fs_info;
13156426c7adSQu Wenruo 	int ret;
13166426c7adSQu Wenruo 
13176426c7adSQu Wenruo 	/*
13186426c7adSQu Wenruo 	 * Save some performance in the case that qgroups are not
13196426c7adSQu Wenruo 	 * enabled. If this check races with the ioctl, rescan will
13206426c7adSQu Wenruo 	 * kick in anyway.
13216426c7adSQu Wenruo 	 */
13229ea6e2b5SDavid Sterba 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
13236426c7adSQu Wenruo 		return 0;
13246426c7adSQu Wenruo 
13256426c7adSQu Wenruo 	/*
132652042d8eSAndrea Gelmini 	 * Ensure dirty @src will be committed.  Or, after coming
13274d31778aSQu Wenruo 	 * commit_fs_roots() and switch_commit_roots(), any dirty but not
13284d31778aSQu Wenruo 	 * recorded root will never be updated again, causing an outdated root
13294d31778aSQu Wenruo 	 * item.
13304d31778aSQu Wenruo 	 */
13314d31778aSQu Wenruo 	record_root_in_trans(trans, src, 1);
13324d31778aSQu Wenruo 
13334d31778aSQu Wenruo 	/*
13346426c7adSQu Wenruo 	 * We are going to commit transaction, see btrfs_commit_transaction()
13356426c7adSQu Wenruo 	 * comment for reason locking tree_log_mutex
13366426c7adSQu Wenruo 	 */
13376426c7adSQu Wenruo 	mutex_lock(&fs_info->tree_log_mutex);
13386426c7adSQu Wenruo 
13397e4443d9SNikolay Borisov 	ret = commit_fs_roots(trans);
13406426c7adSQu Wenruo 	if (ret)
13416426c7adSQu Wenruo 		goto out;
1342460fb20aSNikolay Borisov 	ret = btrfs_qgroup_account_extents(trans);
13436426c7adSQu Wenruo 	if (ret < 0)
13446426c7adSQu Wenruo 		goto out;
13456426c7adSQu Wenruo 
13466426c7adSQu Wenruo 	/* Now qgroup are all updated, we can inherit it to new qgroups */
1347a9377422SLu Fengqi 	ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
13486426c7adSQu Wenruo 				   inherit);
13496426c7adSQu Wenruo 	if (ret < 0)
13506426c7adSQu Wenruo 		goto out;
13516426c7adSQu Wenruo 
13526426c7adSQu Wenruo 	/*
13536426c7adSQu Wenruo 	 * Now we do a simplified commit transaction, which will:
13546426c7adSQu Wenruo 	 * 1) commit all subvolume and extent tree
13556426c7adSQu Wenruo 	 *    To ensure all subvolume and extent tree have a valid
13566426c7adSQu Wenruo 	 *    commit_root to accounting later insert_dir_item()
13576426c7adSQu Wenruo 	 * 2) write all btree blocks onto disk
13586426c7adSQu Wenruo 	 *    This is to make sure later btree modification will be cowed
13596426c7adSQu Wenruo 	 *    Or commit_root can be populated and cause wrong qgroup numbers
13606426c7adSQu Wenruo 	 * In this simplified commit, we don't really care about other trees
13616426c7adSQu Wenruo 	 * like chunk and root tree, as they won't affect qgroup.
13626426c7adSQu Wenruo 	 * And we don't write super to avoid half committed status.
13636426c7adSQu Wenruo 	 */
13649386d8bcSNikolay Borisov 	ret = commit_cowonly_roots(trans);
13656426c7adSQu Wenruo 	if (ret)
13666426c7adSQu Wenruo 		goto out;
136716916a88SNikolay Borisov 	switch_commit_roots(trans->transaction);
136870458a58SNikolay Borisov 	ret = btrfs_write_and_wait_transaction(trans);
13696426c7adSQu Wenruo 	if (ret)
1370f7af3934SDavid Sterba 		btrfs_handle_fs_error(fs_info, ret,
13716426c7adSQu Wenruo 			"Error while writing out transaction for qgroup");
13726426c7adSQu Wenruo 
13736426c7adSQu Wenruo out:
13746426c7adSQu Wenruo 	mutex_unlock(&fs_info->tree_log_mutex);
13756426c7adSQu Wenruo 
13766426c7adSQu Wenruo 	/*
13776426c7adSQu Wenruo 	 * Force parent root to be updated, as we recorded it before so its
13786426c7adSQu Wenruo 	 * last_trans == cur_transid.
13796426c7adSQu Wenruo 	 * Or it won't be committed again onto disk after later
13806426c7adSQu Wenruo 	 * insert_dir_item()
13816426c7adSQu Wenruo 	 */
13826426c7adSQu Wenruo 	if (!ret)
13836426c7adSQu Wenruo 		record_root_in_trans(trans, parent, 1);
13846426c7adSQu Wenruo 	return ret;
13856426c7adSQu Wenruo }
13866426c7adSQu Wenruo 
13876426c7adSQu Wenruo /*
1388d352ac68SChris Mason  * new snapshots need to be created at a very specific time in the
1389aec8030aSMiao Xie  * transaction commit.  This does the actual creation.
1390aec8030aSMiao Xie  *
1391aec8030aSMiao Xie  * Note:
1392aec8030aSMiao Xie  * If the error which may affect the commitment of the current transaction
1393aec8030aSMiao Xie  * happens, we should return the error number. If the error which just affect
1394aec8030aSMiao Xie  * the creation of the pending snapshots, just return 0.
1395d352ac68SChris Mason  */
139680b6794dSChris Mason static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
13973063d29fSChris Mason 				   struct btrfs_pending_snapshot *pending)
13983063d29fSChris Mason {
139908d50ca3SNikolay Borisov 
140008d50ca3SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
14013063d29fSChris Mason 	struct btrfs_key key;
140280b6794dSChris Mason 	struct btrfs_root_item *new_root_item;
14033063d29fSChris Mason 	struct btrfs_root *tree_root = fs_info->tree_root;
14043063d29fSChris Mason 	struct btrfs_root *root = pending->root;
14056bdb72deSSage Weil 	struct btrfs_root *parent_root;
140698c9942aSLiu Bo 	struct btrfs_block_rsv *rsv;
14076bdb72deSSage Weil 	struct inode *parent_inode;
140842874b3dSMiao Xie 	struct btrfs_path *path;
140942874b3dSMiao Xie 	struct btrfs_dir_item *dir_item;
1410a22285a6SYan, Zheng 	struct dentry *dentry;
14113063d29fSChris Mason 	struct extent_buffer *tmp;
1412925baeddSChris Mason 	struct extent_buffer *old;
141395582b00SDeepa Dinamani 	struct timespec64 cur_time;
1414aec8030aSMiao Xie 	int ret = 0;
1415d68fc57bSYan, Zheng 	u64 to_reserve = 0;
14166bdb72deSSage Weil 	u64 index = 0;
1417a22285a6SYan, Zheng 	u64 objectid;
1418b83cc969SLi Zefan 	u64 root_flags;
14198ea05e3aSAlexander Block 	uuid_le new_uuid;
14203063d29fSChris Mason 
14218546b570SDavid Sterba 	ASSERT(pending->path);
14228546b570SDavid Sterba 	path = pending->path;
142342874b3dSMiao Xie 
1424b0c0ea63SDavid Sterba 	ASSERT(pending->root_item);
1425b0c0ea63SDavid Sterba 	new_root_item = pending->root_item;
1426a22285a6SYan, Zheng 
1427aec8030aSMiao Xie 	pending->error = btrfs_find_free_objectid(tree_root, &objectid);
1428aec8030aSMiao Xie 	if (pending->error)
14296fa9700eSMiao Xie 		goto no_free_objectid;
14303063d29fSChris Mason 
1431d6726335SQu Wenruo 	/*
1432d6726335SQu Wenruo 	 * Make qgroup to skip current new snapshot's qgroupid, as it is
1433d6726335SQu Wenruo 	 * accounted by later btrfs_qgroup_inherit().
1434d6726335SQu Wenruo 	 */
1435d6726335SQu Wenruo 	btrfs_set_skip_qgroup(trans, objectid);
1436d6726335SQu Wenruo 
1437147d256eSZhaolei 	btrfs_reloc_pre_snapshot(pending, &to_reserve);
1438d68fc57bSYan, Zheng 
1439d68fc57bSYan, Zheng 	if (to_reserve > 0) {
1440aec8030aSMiao Xie 		pending->error = btrfs_block_rsv_add(root,
1441aec8030aSMiao Xie 						     &pending->block_rsv,
144208e007d2SMiao Xie 						     to_reserve,
144308e007d2SMiao Xie 						     BTRFS_RESERVE_NO_FLUSH);
1444aec8030aSMiao Xie 		if (pending->error)
1445d6726335SQu Wenruo 			goto clear_skip_qgroup;
1446d68fc57bSYan, Zheng 	}
1447d68fc57bSYan, Zheng 
14483063d29fSChris Mason 	key.objectid = objectid;
1449a22285a6SYan, Zheng 	key.offset = (u64)-1;
1450a22285a6SYan, Zheng 	key.type = BTRFS_ROOT_ITEM_KEY;
14513063d29fSChris Mason 
14526fa9700eSMiao Xie 	rsv = trans->block_rsv;
1453a22285a6SYan, Zheng 	trans->block_rsv = &pending->block_rsv;
14542382c5ccSLiu Bo 	trans->bytes_reserved = trans->block_rsv->reserved;
14550b246afaSJeff Mahoney 	trace_btrfs_space_reservation(fs_info, "transaction",
145688d3a5aaSJosef Bacik 				      trans->transid,
145788d3a5aaSJosef Bacik 				      trans->bytes_reserved, 1);
1458a22285a6SYan, Zheng 	dentry = pending->dentry;
1459e9662f70SMiao Xie 	parent_inode = pending->dir;
1460a22285a6SYan, Zheng 	parent_root = BTRFS_I(parent_inode)->root;
14616426c7adSQu Wenruo 	record_root_in_trans(trans, parent_root, 0);
1462a22285a6SYan, Zheng 
1463c2050a45SDeepa Dinamani 	cur_time = current_time(parent_inode);
146404b285f3SDeepa Dinamani 
14656bdb72deSSage Weil 	/*
14666bdb72deSSage Weil 	 * insert the directory item
14676bdb72deSSage Weil 	 */
1468877574e2SNikolay Borisov 	ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
146949b25e05SJeff Mahoney 	BUG_ON(ret); /* -ENOMEM */
147042874b3dSMiao Xie 
147142874b3dSMiao Xie 	/* check if there is a file/dir which has the same name. */
147242874b3dSMiao Xie 	dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
14734a0cc7caSNikolay Borisov 					 btrfs_ino(BTRFS_I(parent_inode)),
147442874b3dSMiao Xie 					 dentry->d_name.name,
147542874b3dSMiao Xie 					 dentry->d_name.len, 0);
147642874b3dSMiao Xie 	if (dir_item != NULL && !IS_ERR(dir_item)) {
1477fe66a05aSChris Mason 		pending->error = -EEXIST;
1478aec8030aSMiao Xie 		goto dir_item_existed;
147942874b3dSMiao Xie 	} else if (IS_ERR(dir_item)) {
148042874b3dSMiao Xie 		ret = PTR_ERR(dir_item);
148166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
14828732d44fSMiao Xie 		goto fail;
148379787eaaSJeff Mahoney 	}
148442874b3dSMiao Xie 	btrfs_release_path(path);
14856bdb72deSSage Weil 
1486e999376fSChris Mason 	/*
1487e999376fSChris Mason 	 * pull in the delayed directory update
1488e999376fSChris Mason 	 * and the delayed inode item
1489e999376fSChris Mason 	 * otherwise we corrupt the FS during
1490e999376fSChris Mason 	 * snapshot
1491e999376fSChris Mason 	 */
1492e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
14938732d44fSMiao Xie 	if (ret) {	/* Transaction aborted */
149466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
14958732d44fSMiao Xie 		goto fail;
14968732d44fSMiao Xie 	}
1497e999376fSChris Mason 
14986426c7adSQu Wenruo 	record_root_in_trans(trans, root, 0);
14996bdb72deSSage Weil 	btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
15006bdb72deSSage Weil 	memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
150108fe4db1SLi Zefan 	btrfs_check_and_init_root_item(new_root_item);
15026bdb72deSSage Weil 
1503b83cc969SLi Zefan 	root_flags = btrfs_root_flags(new_root_item);
1504b83cc969SLi Zefan 	if (pending->readonly)
1505b83cc969SLi Zefan 		root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1506b83cc969SLi Zefan 	else
1507b83cc969SLi Zefan 		root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1508b83cc969SLi Zefan 	btrfs_set_root_flags(new_root_item, root_flags);
1509b83cc969SLi Zefan 
15108ea05e3aSAlexander Block 	btrfs_set_root_generation_v2(new_root_item,
15118ea05e3aSAlexander Block 			trans->transid);
15128ea05e3aSAlexander Block 	uuid_le_gen(&new_uuid);
15138ea05e3aSAlexander Block 	memcpy(new_root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
15148ea05e3aSAlexander Block 	memcpy(new_root_item->parent_uuid, root->root_item.uuid,
15158ea05e3aSAlexander Block 			BTRFS_UUID_SIZE);
151670023da2SStefan Behrens 	if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
151770023da2SStefan Behrens 		memset(new_root_item->received_uuid, 0,
151870023da2SStefan Behrens 		       sizeof(new_root_item->received_uuid));
15198ea05e3aSAlexander Block 		memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
15208ea05e3aSAlexander Block 		memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
15218ea05e3aSAlexander Block 		btrfs_set_root_stransid(new_root_item, 0);
15228ea05e3aSAlexander Block 		btrfs_set_root_rtransid(new_root_item, 0);
152370023da2SStefan Behrens 	}
15243cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
15253cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
152670023da2SStefan Behrens 	btrfs_set_root_otransid(new_root_item, trans->transid);
15278ea05e3aSAlexander Block 
1528925baeddSChris Mason 	old = btrfs_lock_root_node(root);
152949b25e05SJeff Mahoney 	ret = btrfs_cow_block(trans, root, old, NULL, 0, &old);
153079787eaaSJeff Mahoney 	if (ret) {
153179787eaaSJeff Mahoney 		btrfs_tree_unlock(old);
153279787eaaSJeff Mahoney 		free_extent_buffer(old);
153366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15348732d44fSMiao Xie 		goto fail;
153579787eaaSJeff Mahoney 	}
153649b25e05SJeff Mahoney 
15378bead258SDavid Sterba 	btrfs_set_lock_blocking_write(old);
15383063d29fSChris Mason 
153949b25e05SJeff Mahoney 	ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
154079787eaaSJeff Mahoney 	/* clean up in any case */
1541925baeddSChris Mason 	btrfs_tree_unlock(old);
1542925baeddSChris Mason 	free_extent_buffer(old);
15438732d44fSMiao Xie 	if (ret) {
154466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15458732d44fSMiao Xie 		goto fail;
15468732d44fSMiao Xie 	}
1547f1ebcc74SLiu Bo 	/* see comments in should_cow_block() */
154827cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1549f1ebcc74SLiu Bo 	smp_wmb();
1550f1ebcc74SLiu Bo 
15515d4f98a2SYan Zheng 	btrfs_set_root_node(new_root_item, tmp);
1552a22285a6SYan, Zheng 	/* record when the snapshot was created in key.offset */
1553a22285a6SYan, Zheng 	key.offset = trans->transid;
1554a22285a6SYan, Zheng 	ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1555925baeddSChris Mason 	btrfs_tree_unlock(tmp);
15563063d29fSChris Mason 	free_extent_buffer(tmp);
15578732d44fSMiao Xie 	if (ret) {
155866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15598732d44fSMiao Xie 		goto fail;
15608732d44fSMiao Xie 	}
15610660b5afSChris Mason 
1562a22285a6SYan, Zheng 	/*
1563a22285a6SYan, Zheng 	 * insert root back/forward references
1564a22285a6SYan, Zheng 	 */
15656025c19fSLu Fengqi 	ret = btrfs_add_root_ref(trans, objectid,
1566a22285a6SYan, Zheng 				 parent_root->root_key.objectid,
15674a0cc7caSNikolay Borisov 				 btrfs_ino(BTRFS_I(parent_inode)), index,
1568a22285a6SYan, Zheng 				 dentry->d_name.name, dentry->d_name.len);
15698732d44fSMiao Xie 	if (ret) {
157066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15718732d44fSMiao Xie 		goto fail;
15728732d44fSMiao Xie 	}
1573a22285a6SYan, Zheng 
1574a22285a6SYan, Zheng 	key.offset = (u64)-1;
15750b246afaSJeff Mahoney 	pending->snap = btrfs_read_fs_root_no_name(fs_info, &key);
157679787eaaSJeff Mahoney 	if (IS_ERR(pending->snap)) {
157779787eaaSJeff Mahoney 		ret = PTR_ERR(pending->snap);
157866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15798732d44fSMiao Xie 		goto fail;
158079787eaaSJeff Mahoney 	}
1581d68fc57bSYan, Zheng 
158249b25e05SJeff Mahoney 	ret = btrfs_reloc_post_snapshot(trans, pending);
15838732d44fSMiao Xie 	if (ret) {
158466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15858732d44fSMiao Xie 		goto fail;
15868732d44fSMiao Xie 	}
1587361048f5SMiao Xie 
1588c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
15898732d44fSMiao Xie 	if (ret) {
159066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15918732d44fSMiao Xie 		goto fail;
15928732d44fSMiao Xie 	}
159342874b3dSMiao Xie 
15946426c7adSQu Wenruo 	/*
15956426c7adSQu Wenruo 	 * Do special qgroup accounting for snapshot, as we do some qgroup
15966426c7adSQu Wenruo 	 * snapshot hack to do fast snapshot.
15976426c7adSQu Wenruo 	 * To co-operate with that hack, we do hack again.
15986426c7adSQu Wenruo 	 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
15996426c7adSQu Wenruo 	 */
16006426c7adSQu Wenruo 	ret = qgroup_account_snapshot(trans, root, parent_root,
16016426c7adSQu Wenruo 				      pending->inherit, objectid);
16026426c7adSQu Wenruo 	if (ret < 0)
16036426c7adSQu Wenruo 		goto fail;
16046426c7adSQu Wenruo 
1605684572dfSLu Fengqi 	ret = btrfs_insert_dir_item(trans, dentry->d_name.name,
1606684572dfSLu Fengqi 				    dentry->d_name.len, BTRFS_I(parent_inode),
1607684572dfSLu Fengqi 				    &key, BTRFS_FT_DIR, index);
160842874b3dSMiao Xie 	/* We have check then name at the beginning, so it is impossible. */
16099c52057cSChris Mason 	BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
16108732d44fSMiao Xie 	if (ret) {
161166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16128732d44fSMiao Xie 		goto fail;
16138732d44fSMiao Xie 	}
161442874b3dSMiao Xie 
16156ef06d27SNikolay Borisov 	btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
161642874b3dSMiao Xie 					 dentry->d_name.len * 2);
161704b285f3SDeepa Dinamani 	parent_inode->i_mtime = parent_inode->i_ctime =
1618c2050a45SDeepa Dinamani 		current_time(parent_inode);
1619be6aef60SJosef Bacik 	ret = btrfs_update_inode_fallback(trans, parent_root, parent_inode);
1620dd5f9615SStefan Behrens 	if (ret) {
162166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1622dd5f9615SStefan Behrens 		goto fail;
1623dd5f9615SStefan Behrens 	}
1624cdb345a8SLu Fengqi 	ret = btrfs_uuid_tree_add(trans, new_uuid.b, BTRFS_UUID_KEY_SUBVOL,
1625cdb345a8SLu Fengqi 				  objectid);
1626dd5f9615SStefan Behrens 	if (ret) {
162766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1628dd5f9615SStefan Behrens 		goto fail;
1629dd5f9615SStefan Behrens 	}
1630dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1631cdb345a8SLu Fengqi 		ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1632dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1633dd5f9615SStefan Behrens 					  objectid);
1634dd5f9615SStefan Behrens 		if (ret && ret != -EEXIST) {
163566642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
1636dd5f9615SStefan Behrens 			goto fail;
1637dd5f9615SStefan Behrens 		}
1638dd5f9615SStefan Behrens 	}
1639d6726335SQu Wenruo 
1640c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1641d6726335SQu Wenruo 	if (ret) {
164266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1643d6726335SQu Wenruo 		goto fail;
1644d6726335SQu Wenruo 	}
1645d6726335SQu Wenruo 
16463063d29fSChris Mason fail:
1647aec8030aSMiao Xie 	pending->error = ret;
1648aec8030aSMiao Xie dir_item_existed:
164998c9942aSLiu Bo 	trans->block_rsv = rsv;
16502382c5ccSLiu Bo 	trans->bytes_reserved = 0;
1651d6726335SQu Wenruo clear_skip_qgroup:
1652d6726335SQu Wenruo 	btrfs_clear_skip_qgroup(trans);
16536fa9700eSMiao Xie no_free_objectid:
16546fa9700eSMiao Xie 	kfree(new_root_item);
1655b0c0ea63SDavid Sterba 	pending->root_item = NULL;
165642874b3dSMiao Xie 	btrfs_free_path(path);
16578546b570SDavid Sterba 	pending->path = NULL;
16588546b570SDavid Sterba 
165949b25e05SJeff Mahoney 	return ret;
16603063d29fSChris Mason }
16613063d29fSChris Mason 
1662d352ac68SChris Mason /*
1663d352ac68SChris Mason  * create all the snapshots we've scheduled for creation
1664d352ac68SChris Mason  */
166508d50ca3SNikolay Borisov static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
16663063d29fSChris Mason {
1667aec8030aSMiao Xie 	struct btrfs_pending_snapshot *pending, *next;
16683063d29fSChris Mason 	struct list_head *head = &trans->transaction->pending_snapshots;
1669aec8030aSMiao Xie 	int ret = 0;
16703de4586cSChris Mason 
1671aec8030aSMiao Xie 	list_for_each_entry_safe(pending, next, head, list) {
1672aec8030aSMiao Xie 		list_del(&pending->list);
167308d50ca3SNikolay Borisov 		ret = create_pending_snapshot(trans, pending);
1674aec8030aSMiao Xie 		if (ret)
1675aec8030aSMiao Xie 			break;
1676aec8030aSMiao Xie 	}
1677aec8030aSMiao Xie 	return ret;
16783de4586cSChris Mason }
16793de4586cSChris Mason 
16802ff7e61eSJeff Mahoney static void update_super_roots(struct btrfs_fs_info *fs_info)
16815d4f98a2SYan Zheng {
16825d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
16835d4f98a2SYan Zheng 	struct btrfs_super_block *super;
16845d4f98a2SYan Zheng 
16850b246afaSJeff Mahoney 	super = fs_info->super_copy;
16865d4f98a2SYan Zheng 
16870b246afaSJeff Mahoney 	root_item = &fs_info->chunk_root->root_item;
1688093e037cSDavid Sterba 	super->chunk_root = root_item->bytenr;
1689093e037cSDavid Sterba 	super->chunk_root_generation = root_item->generation;
1690093e037cSDavid Sterba 	super->chunk_root_level = root_item->level;
16915d4f98a2SYan Zheng 
16920b246afaSJeff Mahoney 	root_item = &fs_info->tree_root->root_item;
1693093e037cSDavid Sterba 	super->root = root_item->bytenr;
1694093e037cSDavid Sterba 	super->generation = root_item->generation;
1695093e037cSDavid Sterba 	super->root_level = root_item->level;
16960b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, SPACE_CACHE))
1697093e037cSDavid Sterba 		super->cache_generation = root_item->generation;
16980b246afaSJeff Mahoney 	if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1699093e037cSDavid Sterba 		super->uuid_tree_generation = root_item->generation;
17005d4f98a2SYan Zheng }
17015d4f98a2SYan Zheng 
1702f36f3042SChris Mason int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1703f36f3042SChris Mason {
17044a9d8bdeSMiao Xie 	struct btrfs_transaction *trans;
1705f36f3042SChris Mason 	int ret = 0;
17064a9d8bdeSMiao Xie 
1707a4abeea4SJosef Bacik 	spin_lock(&info->trans_lock);
17084a9d8bdeSMiao Xie 	trans = info->running_transaction;
17094a9d8bdeSMiao Xie 	if (trans)
17104a9d8bdeSMiao Xie 		ret = (trans->state >= TRANS_STATE_COMMIT_START);
1711a4abeea4SJosef Bacik 	spin_unlock(&info->trans_lock);
1712f36f3042SChris Mason 	return ret;
1713f36f3042SChris Mason }
1714f36f3042SChris Mason 
17158929ecfaSYan, Zheng int btrfs_transaction_blocked(struct btrfs_fs_info *info)
17168929ecfaSYan, Zheng {
17174a9d8bdeSMiao Xie 	struct btrfs_transaction *trans;
17188929ecfaSYan, Zheng 	int ret = 0;
17194a9d8bdeSMiao Xie 
1720a4abeea4SJosef Bacik 	spin_lock(&info->trans_lock);
17214a9d8bdeSMiao Xie 	trans = info->running_transaction;
17224a9d8bdeSMiao Xie 	if (trans)
17234a9d8bdeSMiao Xie 		ret = is_transaction_blocked(trans);
1724a4abeea4SJosef Bacik 	spin_unlock(&info->trans_lock);
17258929ecfaSYan, Zheng 	return ret;
17268929ecfaSYan, Zheng }
17278929ecfaSYan, Zheng 
1728bb9c12c9SSage Weil /*
1729bb9c12c9SSage Weil  * wait for the current transaction commit to start and block subsequent
1730bb9c12c9SSage Weil  * transaction joins
1731bb9c12c9SSage Weil  */
17322ff7e61eSJeff Mahoney static void wait_current_trans_commit_start(struct btrfs_fs_info *fs_info,
1733bb9c12c9SSage Weil 					    struct btrfs_transaction *trans)
1734bb9c12c9SSage Weil {
17352ff7e61eSJeff Mahoney 	wait_event(fs_info->transaction_blocked_wait,
17362ff7e61eSJeff Mahoney 		   trans->state >= TRANS_STATE_COMMIT_START || trans->aborted);
1737bb9c12c9SSage Weil }
1738bb9c12c9SSage Weil 
1739bb9c12c9SSage Weil /*
1740bb9c12c9SSage Weil  * wait for the current transaction to start and then become unblocked.
1741bb9c12c9SSage Weil  * caller holds ref.
1742bb9c12c9SSage Weil  */
17432ff7e61eSJeff Mahoney static void wait_current_trans_commit_start_and_unblock(
17442ff7e61eSJeff Mahoney 					struct btrfs_fs_info *fs_info,
1745bb9c12c9SSage Weil 					struct btrfs_transaction *trans)
1746bb9c12c9SSage Weil {
17472ff7e61eSJeff Mahoney 	wait_event(fs_info->transaction_wait,
17482ff7e61eSJeff Mahoney 		   trans->state >= TRANS_STATE_UNBLOCKED || trans->aborted);
1749bb9c12c9SSage Weil }
1750bb9c12c9SSage Weil 
1751bb9c12c9SSage Weil /*
1752bb9c12c9SSage Weil  * commit transactions asynchronously. once btrfs_commit_transaction_async
1753bb9c12c9SSage Weil  * returns, any subsequent transaction will not be allowed to join.
1754bb9c12c9SSage Weil  */
1755bb9c12c9SSage Weil struct btrfs_async_commit {
1756bb9c12c9SSage Weil 	struct btrfs_trans_handle *newtrans;
17577892b5afSMiao Xie 	struct work_struct work;
1758bb9c12c9SSage Weil };
1759bb9c12c9SSage Weil 
1760bb9c12c9SSage Weil static void do_async_commit(struct work_struct *work)
1761bb9c12c9SSage Weil {
1762bb9c12c9SSage Weil 	struct btrfs_async_commit *ac =
17637892b5afSMiao Xie 		container_of(work, struct btrfs_async_commit, work);
1764bb9c12c9SSage Weil 
17656fc4e354SSage Weil 	/*
17666fc4e354SSage Weil 	 * We've got freeze protection passed with the transaction.
17676fc4e354SSage Weil 	 * Tell lockdep about it.
17686fc4e354SSage Weil 	 */
1769b1a06a4bSLiu Bo 	if (ac->newtrans->type & __TRANS_FREEZABLE)
17703a45bb20SJeff Mahoney 		__sb_writers_acquired(ac->newtrans->fs_info->sb, SB_FREEZE_FS);
17716fc4e354SSage Weil 
1772e209db7aSSage Weil 	current->journal_info = ac->newtrans;
1773e209db7aSSage Weil 
17743a45bb20SJeff Mahoney 	btrfs_commit_transaction(ac->newtrans);
1775bb9c12c9SSage Weil 	kfree(ac);
1776bb9c12c9SSage Weil }
1777bb9c12c9SSage Weil 
1778bb9c12c9SSage Weil int btrfs_commit_transaction_async(struct btrfs_trans_handle *trans,
1779bb9c12c9SSage Weil 				   int wait_for_unblock)
1780bb9c12c9SSage Weil {
17813a45bb20SJeff Mahoney 	struct btrfs_fs_info *fs_info = trans->fs_info;
1782bb9c12c9SSage Weil 	struct btrfs_async_commit *ac;
1783bb9c12c9SSage Weil 	struct btrfs_transaction *cur_trans;
1784bb9c12c9SSage Weil 
1785bb9c12c9SSage Weil 	ac = kmalloc(sizeof(*ac), GFP_NOFS);
1786db5b493aSTsutomu Itoh 	if (!ac)
1787db5b493aSTsutomu Itoh 		return -ENOMEM;
1788bb9c12c9SSage Weil 
17897892b5afSMiao Xie 	INIT_WORK(&ac->work, do_async_commit);
17903a45bb20SJeff Mahoney 	ac->newtrans = btrfs_join_transaction(trans->root);
17913612b495STsutomu Itoh 	if (IS_ERR(ac->newtrans)) {
17923612b495STsutomu Itoh 		int err = PTR_ERR(ac->newtrans);
17933612b495STsutomu Itoh 		kfree(ac);
17943612b495STsutomu Itoh 		return err;
17953612b495STsutomu Itoh 	}
1796bb9c12c9SSage Weil 
1797bb9c12c9SSage Weil 	/* take transaction reference */
1798bb9c12c9SSage Weil 	cur_trans = trans->transaction;
17999b64f57dSElena Reshetova 	refcount_inc(&cur_trans->use_count);
1800bb9c12c9SSage Weil 
18013a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
18026fc4e354SSage Weil 
18036fc4e354SSage Weil 	/*
18046fc4e354SSage Weil 	 * Tell lockdep we've released the freeze rwsem, since the
18056fc4e354SSage Weil 	 * async commit thread will be the one to unlock it.
18066fc4e354SSage Weil 	 */
1807b1a06a4bSLiu Bo 	if (ac->newtrans->type & __TRANS_FREEZABLE)
18080b246afaSJeff Mahoney 		__sb_writers_release(fs_info->sb, SB_FREEZE_FS);
18096fc4e354SSage Weil 
18107892b5afSMiao Xie 	schedule_work(&ac->work);
1811bb9c12c9SSage Weil 
1812bb9c12c9SSage Weil 	/* wait for transaction to start and unblock */
1813bb9c12c9SSage Weil 	if (wait_for_unblock)
18142ff7e61eSJeff Mahoney 		wait_current_trans_commit_start_and_unblock(fs_info, cur_trans);
1815bb9c12c9SSage Weil 	else
18162ff7e61eSJeff Mahoney 		wait_current_trans_commit_start(fs_info, cur_trans);
1817bb9c12c9SSage Weil 
181838e88054SSage Weil 	if (current->journal_info == trans)
181938e88054SSage Weil 		current->journal_info = NULL;
182038e88054SSage Weil 
1821724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
1822bb9c12c9SSage Weil 	return 0;
1823bb9c12c9SSage Weil }
1824bb9c12c9SSage Weil 
182549b25e05SJeff Mahoney 
182697cb39bbSNikolay Borisov static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
182749b25e05SJeff Mahoney {
182897cb39bbSNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
182949b25e05SJeff Mahoney 	struct btrfs_transaction *cur_trans = trans->transaction;
183049b25e05SJeff Mahoney 
1831b50fff81SDavid Sterba 	WARN_ON(refcount_read(&trans->use_count) > 1);
183249b25e05SJeff Mahoney 
183366642832SJeff Mahoney 	btrfs_abort_transaction(trans, err);
18347b8b92afSJosef Bacik 
18350b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
183666b6135bSLiu Bo 
183725d8c284SMiao Xie 	/*
183825d8c284SMiao Xie 	 * If the transaction is removed from the list, it means this
183925d8c284SMiao Xie 	 * transaction has been committed successfully, so it is impossible
184025d8c284SMiao Xie 	 * to call the cleanup function.
184125d8c284SMiao Xie 	 */
184225d8c284SMiao Xie 	BUG_ON(list_empty(&cur_trans->list));
184366b6135bSLiu Bo 
184449b25e05SJeff Mahoney 	list_del_init(&cur_trans->list);
18450b246afaSJeff Mahoney 	if (cur_trans == fs_info->running_transaction) {
18464a9d8bdeSMiao Xie 		cur_trans->state = TRANS_STATE_COMMIT_DOING;
18470b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
1848f094ac32SLiu Bo 		wait_event(cur_trans->writer_wait,
1849f094ac32SLiu Bo 			   atomic_read(&cur_trans->num_writers) == 1);
1850f094ac32SLiu Bo 
18510b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
1852d7096fc3SJosef Bacik 	}
18530b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
185449b25e05SJeff Mahoney 
18552ff7e61eSJeff Mahoney 	btrfs_cleanup_one_transaction(trans->transaction, fs_info);
185649b25e05SJeff Mahoney 
18570b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
18580b246afaSJeff Mahoney 	if (cur_trans == fs_info->running_transaction)
18590b246afaSJeff Mahoney 		fs_info->running_transaction = NULL;
18600b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
18614a9d8bdeSMiao Xie 
1862e0228285SJosef Bacik 	if (trans->type & __TRANS_FREEZABLE)
18630b246afaSJeff Mahoney 		sb_end_intwrite(fs_info->sb);
1864724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
1865724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
186649b25e05SJeff Mahoney 
186797cb39bbSNikolay Borisov 	trace_btrfs_transaction_commit(trans->root);
186849b25e05SJeff Mahoney 
186949b25e05SJeff Mahoney 	if (current->journal_info == trans)
187049b25e05SJeff Mahoney 		current->journal_info = NULL;
18710b246afaSJeff Mahoney 	btrfs_scrub_cancel(fs_info);
187249b25e05SJeff Mahoney 
187349b25e05SJeff Mahoney 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
187449b25e05SJeff Mahoney }
187549b25e05SJeff Mahoney 
1876c7cc64a9SDavid Sterba /*
1877c7cc64a9SDavid Sterba  * Release reserved delayed ref space of all pending block groups of the
1878c7cc64a9SDavid Sterba  * transaction and remove them from the list
1879c7cc64a9SDavid Sterba  */
1880c7cc64a9SDavid Sterba static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
1881c7cc64a9SDavid Sterba {
1882c7cc64a9SDavid Sterba        struct btrfs_fs_info *fs_info = trans->fs_info;
1883c7cc64a9SDavid Sterba        struct btrfs_block_group_cache *block_group, *tmp;
1884c7cc64a9SDavid Sterba 
1885c7cc64a9SDavid Sterba        list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
1886c7cc64a9SDavid Sterba                btrfs_delayed_refs_rsv_release(fs_info, 1);
1887c7cc64a9SDavid Sterba                list_del_init(&block_group->bg_list);
1888c7cc64a9SDavid Sterba        }
1889c7cc64a9SDavid Sterba }
1890c7cc64a9SDavid Sterba 
1891609e804dSFilipe Manana static inline int btrfs_start_delalloc_flush(struct btrfs_trans_handle *trans)
189282436617SMiao Xie {
1893609e804dSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
1894609e804dSFilipe Manana 
1895ce8ea7ccSJosef Bacik 	/*
1896ce8ea7ccSJosef Bacik 	 * We use writeback_inodes_sb here because if we used
1897ce8ea7ccSJosef Bacik 	 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
1898ce8ea7ccSJosef Bacik 	 * Currently are holding the fs freeze lock, if we do an async flush
1899ce8ea7ccSJosef Bacik 	 * we'll do btrfs_join_transaction() and deadlock because we need to
1900ce8ea7ccSJosef Bacik 	 * wait for the fs freeze lock.  Using the direct flushing we benefit
1901ce8ea7ccSJosef Bacik 	 * from already being in a transaction and our join_transaction doesn't
1902ce8ea7ccSJosef Bacik 	 * have to re-take the fs freeze lock.
1903ce8ea7ccSJosef Bacik 	 */
1904609e804dSFilipe Manana 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT)) {
1905ce8ea7ccSJosef Bacik 		writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
1906609e804dSFilipe Manana 	} else {
1907609e804dSFilipe Manana 		struct btrfs_pending_snapshot *pending;
1908609e804dSFilipe Manana 		struct list_head *head = &trans->transaction->pending_snapshots;
1909609e804dSFilipe Manana 
1910609e804dSFilipe Manana 		/*
1911609e804dSFilipe Manana 		 * Flush dellaloc for any root that is going to be snapshotted.
1912609e804dSFilipe Manana 		 * This is done to avoid a corrupted version of files, in the
1913609e804dSFilipe Manana 		 * snapshots, that had both buffered and direct IO writes (even
1914609e804dSFilipe Manana 		 * if they were done sequentially) due to an unordered update of
1915609e804dSFilipe Manana 		 * the inode's size on disk.
1916609e804dSFilipe Manana 		 */
1917609e804dSFilipe Manana 		list_for_each_entry(pending, head, list) {
1918609e804dSFilipe Manana 			int ret;
1919609e804dSFilipe Manana 
1920609e804dSFilipe Manana 			ret = btrfs_start_delalloc_snapshot(pending->root);
1921609e804dSFilipe Manana 			if (ret)
1922609e804dSFilipe Manana 				return ret;
1923609e804dSFilipe Manana 		}
1924609e804dSFilipe Manana 	}
192582436617SMiao Xie 	return 0;
192682436617SMiao Xie }
192782436617SMiao Xie 
1928609e804dSFilipe Manana static inline void btrfs_wait_delalloc_flush(struct btrfs_trans_handle *trans)
192982436617SMiao Xie {
1930609e804dSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
1931609e804dSFilipe Manana 
1932609e804dSFilipe Manana 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT)) {
19336374e57aSChris Mason 		btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
1934609e804dSFilipe Manana 	} else {
1935609e804dSFilipe Manana 		struct btrfs_pending_snapshot *pending;
1936609e804dSFilipe Manana 		struct list_head *head = &trans->transaction->pending_snapshots;
1937609e804dSFilipe Manana 
1938609e804dSFilipe Manana 		/*
1939609e804dSFilipe Manana 		 * Wait for any dellaloc that we started previously for the roots
1940609e804dSFilipe Manana 		 * that are going to be snapshotted. This is to avoid a corrupted
1941609e804dSFilipe Manana 		 * version of files in the snapshots that had both buffered and
1942609e804dSFilipe Manana 		 * direct IO writes (even if they were done sequentially).
1943609e804dSFilipe Manana 		 */
1944609e804dSFilipe Manana 		list_for_each_entry(pending, head, list)
1945609e804dSFilipe Manana 			btrfs_wait_ordered_extents(pending->root,
1946609e804dSFilipe Manana 						   U64_MAX, 0, U64_MAX);
1947609e804dSFilipe Manana 	}
194882436617SMiao Xie }
194982436617SMiao Xie 
19503a45bb20SJeff Mahoney int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
195179154b1bSChris Mason {
19523a45bb20SJeff Mahoney 	struct btrfs_fs_info *fs_info = trans->fs_info;
195349b25e05SJeff Mahoney 	struct btrfs_transaction *cur_trans = trans->transaction;
19548fd17795SChris Mason 	struct btrfs_transaction *prev_trans = NULL;
195525287e0aSMiao Xie 	int ret;
195679154b1bSChris Mason 
19578d25a086SMiao Xie 	/* Stop the commit early if ->aborted is set */
195820c7bcecSSeraphime Kirkovski 	if (unlikely(READ_ONCE(cur_trans->aborted))) {
195925287e0aSMiao Xie 		ret = cur_trans->aborted;
19603a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
1961e4a2bcacSJosef Bacik 		return ret;
196225287e0aSMiao Xie 	}
196349b25e05SJeff Mahoney 
1964f45c752bSJosef Bacik 	btrfs_trans_release_metadata(trans);
1965f45c752bSJosef Bacik 	trans->block_rsv = NULL;
1966f45c752bSJosef Bacik 
196756bec294SChris Mason 	/* make a pass through all the delayed refs we have so far
196856bec294SChris Mason 	 * any runnings procs may add more while we are here
196956bec294SChris Mason 	 */
1970c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, 0);
1971e4a2bcacSJosef Bacik 	if (ret) {
19723a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
1973e4a2bcacSJosef Bacik 		return ret;
1974e4a2bcacSJosef Bacik 	}
197556bec294SChris Mason 
1976b7ec40d7SChris Mason 	cur_trans = trans->transaction;
197749b25e05SJeff Mahoney 
197856bec294SChris Mason 	/*
197956bec294SChris Mason 	 * set the flushing flag so procs in this transaction have to
198056bec294SChris Mason 	 * start sending their work down.
198156bec294SChris Mason 	 */
1982b7ec40d7SChris Mason 	cur_trans->delayed_refs.flushing = 1;
19831be41b78SJosef Bacik 	smp_wmb();
198456bec294SChris Mason 
19856c686b35SNikolay Borisov 	btrfs_create_pending_block_groups(trans);
1986ea658badSJosef Bacik 
1987c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, 0);
1988e4a2bcacSJosef Bacik 	if (ret) {
19893a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
1990e4a2bcacSJosef Bacik 		return ret;
1991e4a2bcacSJosef Bacik 	}
199256bec294SChris Mason 
19933204d33cSJosef Bacik 	if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
19941bbc621eSChris Mason 		int run_it = 0;
19951bbc621eSChris Mason 
19961bbc621eSChris Mason 		/* this mutex is also taken before trying to set
19971bbc621eSChris Mason 		 * block groups readonly.  We need to make sure
19981bbc621eSChris Mason 		 * that nobody has set a block group readonly
19991bbc621eSChris Mason 		 * after a extents from that block group have been
20001bbc621eSChris Mason 		 * allocated for cache files.  btrfs_set_block_group_ro
20011bbc621eSChris Mason 		 * will wait for the transaction to commit if it
20023204d33cSJosef Bacik 		 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
20031bbc621eSChris Mason 		 *
20043204d33cSJosef Bacik 		 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
20053204d33cSJosef Bacik 		 * only one process starts all the block group IO.  It wouldn't
20061bbc621eSChris Mason 		 * hurt to have more than one go through, but there's no
20071bbc621eSChris Mason 		 * real advantage to it either.
20081bbc621eSChris Mason 		 */
20090b246afaSJeff Mahoney 		mutex_lock(&fs_info->ro_block_group_mutex);
20103204d33cSJosef Bacik 		if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
20113204d33cSJosef Bacik 				      &cur_trans->flags))
20121bbc621eSChris Mason 			run_it = 1;
20130b246afaSJeff Mahoney 		mutex_unlock(&fs_info->ro_block_group_mutex);
20141bbc621eSChris Mason 
2015f9cacae3SNikolay Borisov 		if (run_it) {
201621217054SNikolay Borisov 			ret = btrfs_start_dirty_block_groups(trans);
20171bbc621eSChris Mason 			if (ret) {
20183a45bb20SJeff Mahoney 				btrfs_end_transaction(trans);
20191bbc621eSChris Mason 				return ret;
20201bbc621eSChris Mason 			}
2021f9cacae3SNikolay Borisov 		}
2022f9cacae3SNikolay Borisov 	}
20231bbc621eSChris Mason 
20240b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
20254a9d8bdeSMiao Xie 	if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
20260b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
20279b64f57dSElena Reshetova 		refcount_inc(&cur_trans->use_count);
20283a45bb20SJeff Mahoney 		ret = btrfs_end_transaction(trans);
2029ccd467d6SChris Mason 
20302ff7e61eSJeff Mahoney 		wait_for_commit(cur_trans);
203115ee9bc7SJosef Bacik 
2032b4924a0fSLiu Bo 		if (unlikely(cur_trans->aborted))
2033b4924a0fSLiu Bo 			ret = cur_trans->aborted;
2034b4924a0fSLiu Bo 
2035724e2315SJosef Bacik 		btrfs_put_transaction(cur_trans);
203615ee9bc7SJosef Bacik 
203749b25e05SJeff Mahoney 		return ret;
203879154b1bSChris Mason 	}
20394313b399SChris Mason 
20404a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
20410b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
2042bb9c12c9SSage Weil 
20430b246afaSJeff Mahoney 	if (cur_trans->list.prev != &fs_info->trans_list) {
2044ccd467d6SChris Mason 		prev_trans = list_entry(cur_trans->list.prev,
2045ccd467d6SChris Mason 					struct btrfs_transaction, list);
20464a9d8bdeSMiao Xie 		if (prev_trans->state != TRANS_STATE_COMPLETED) {
20479b64f57dSElena Reshetova 			refcount_inc(&prev_trans->use_count);
20480b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
2049ccd467d6SChris Mason 
20502ff7e61eSJeff Mahoney 			wait_for_commit(prev_trans);
20511f9b8c8fSFilipe Manana 			ret = prev_trans->aborted;
2052ccd467d6SChris Mason 
2053724e2315SJosef Bacik 			btrfs_put_transaction(prev_trans);
20541f9b8c8fSFilipe Manana 			if (ret)
20551f9b8c8fSFilipe Manana 				goto cleanup_transaction;
2056a4abeea4SJosef Bacik 		} else {
20570b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
2058ccd467d6SChris Mason 		}
2059a4abeea4SJosef Bacik 	} else {
20600b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
2061ccd467d6SChris Mason 	}
206215ee9bc7SJosef Bacik 
20630860adfdSMiao Xie 	extwriter_counter_dec(cur_trans, trans->type);
20640860adfdSMiao Xie 
2065609e804dSFilipe Manana 	ret = btrfs_start_delalloc_flush(trans);
206682436617SMiao Xie 	if (ret)
206782436617SMiao Xie 		goto cleanup_transaction;
206882436617SMiao Xie 
2069e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
207049b25e05SJeff Mahoney 	if (ret)
207149b25e05SJeff Mahoney 		goto cleanup_transaction;
207216cdcec7SMiao Xie 
2073581227d0SMiao Xie 	wait_event(cur_trans->writer_wait,
2074581227d0SMiao Xie 		   extwriter_counter_read(cur_trans) == 0);
2075ed3b3d31SChris Mason 
2076581227d0SMiao Xie 	/* some pending stuffs might be added after the previous flush. */
2077e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
2078ca469637SMiao Xie 	if (ret)
2079ca469637SMiao Xie 		goto cleanup_transaction;
2080ca469637SMiao Xie 
2081609e804dSFilipe Manana 	btrfs_wait_delalloc_flush(trans);
2082cb7ab021SWang Shilong 
20832ff7e61eSJeff Mahoney 	btrfs_scrub_pause(fs_info);
2084ed0ca140SJosef Bacik 	/*
2085ed0ca140SJosef Bacik 	 * Ok now we need to make sure to block out any other joins while we
2086ed0ca140SJosef Bacik 	 * commit the transaction.  We could have started a join before setting
20874a9d8bdeSMiao Xie 	 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2088ed0ca140SJosef Bacik 	 */
20890b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
20904a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_DOING;
20910b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2092ed0ca140SJosef Bacik 	wait_event(cur_trans->writer_wait,
2093ed0ca140SJosef Bacik 		   atomic_read(&cur_trans->num_writers) == 1);
209415ee9bc7SJosef Bacik 
20952cba30f1SMiao Xie 	/* ->aborted might be set after the previous check, so check it */
209620c7bcecSSeraphime Kirkovski 	if (unlikely(READ_ONCE(cur_trans->aborted))) {
20972cba30f1SMiao Xie 		ret = cur_trans->aborted;
20986cf7f77eSWang Shilong 		goto scrub_continue;
20992cba30f1SMiao Xie 	}
21007585717fSChris Mason 	/*
21017585717fSChris Mason 	 * the reloc mutex makes sure that we stop
21027585717fSChris Mason 	 * the balancing code from coming in and moving
21037585717fSChris Mason 	 * extents around in the middle of the commit
21047585717fSChris Mason 	 */
21050b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
21067585717fSChris Mason 
210742874b3dSMiao Xie 	/*
210842874b3dSMiao Xie 	 * We needn't worry about the delayed items because we will
210942874b3dSMiao Xie 	 * deal with them in create_pending_snapshot(), which is the
211042874b3dSMiao Xie 	 * core function of the snapshot creation.
211142874b3dSMiao Xie 	 */
211208d50ca3SNikolay Borisov 	ret = create_pending_snapshots(trans);
211349b25e05SJeff Mahoney 	if (ret) {
21140b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21156cf7f77eSWang Shilong 		goto scrub_continue;
211649b25e05SJeff Mahoney 	}
21173063d29fSChris Mason 
211842874b3dSMiao Xie 	/*
211942874b3dSMiao Xie 	 * We insert the dir indexes of the snapshots and update the inode
212042874b3dSMiao Xie 	 * of the snapshots' parents after the snapshot creation, so there
212142874b3dSMiao Xie 	 * are some delayed items which are not dealt with. Now deal with
212242874b3dSMiao Xie 	 * them.
212342874b3dSMiao Xie 	 *
212442874b3dSMiao Xie 	 * We needn't worry that this operation will corrupt the snapshots,
212542874b3dSMiao Xie 	 * because all the tree which are snapshoted will be forced to COW
212642874b3dSMiao Xie 	 * the nodes and leaves.
212742874b3dSMiao Xie 	 */
2128e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
212949b25e05SJeff Mahoney 	if (ret) {
21300b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21316cf7f77eSWang Shilong 		goto scrub_continue;
213249b25e05SJeff Mahoney 	}
213316cdcec7SMiao Xie 
2134c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
213549b25e05SJeff Mahoney 	if (ret) {
21360b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21376cf7f77eSWang Shilong 		goto scrub_continue;
213849b25e05SJeff Mahoney 	}
213956bec294SChris Mason 
2140e999376fSChris Mason 	/*
2141e999376fSChris Mason 	 * make sure none of the code above managed to slip in a
2142e999376fSChris Mason 	 * delayed item
2143e999376fSChris Mason 	 */
2144ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
2145e999376fSChris Mason 
21462c90e5d6SChris Mason 	WARN_ON(cur_trans != trans->transaction);
2147dc17ff8fSChris Mason 
2148e02119d5SChris Mason 	/* btrfs_commit_tree_roots is responsible for getting the
2149e02119d5SChris Mason 	 * various roots consistent with each other.  Every pointer
2150e02119d5SChris Mason 	 * in the tree of tree roots has to point to the most up to date
2151e02119d5SChris Mason 	 * root for every subvolume and other tree.  So, we have to keep
2152e02119d5SChris Mason 	 * the tree logging code from jumping in and changing any
2153e02119d5SChris Mason 	 * of the trees.
2154e02119d5SChris Mason 	 *
2155e02119d5SChris Mason 	 * At this point in the commit, there can't be any tree-log
2156e02119d5SChris Mason 	 * writers, but a little lower down we drop the trans mutex
2157e02119d5SChris Mason 	 * and let new people in.  By holding the tree_log_mutex
2158e02119d5SChris Mason 	 * from now until after the super is written, we avoid races
2159e02119d5SChris Mason 	 * with the tree-log code.
2160e02119d5SChris Mason 	 */
21610b246afaSJeff Mahoney 	mutex_lock(&fs_info->tree_log_mutex);
21621a40e23bSZheng Yan 
21637e4443d9SNikolay Borisov 	ret = commit_fs_roots(trans);
216449b25e05SJeff Mahoney 	if (ret) {
21650b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
21660b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
21676cf7f77eSWang Shilong 		goto scrub_continue;
216849b25e05SJeff Mahoney 	}
216954aa1f4dSChris Mason 
21703818aea2SQu Wenruo 	/*
21717e1876acSDavid Sterba 	 * Since the transaction is done, we can apply the pending changes
21727e1876acSDavid Sterba 	 * before the next transaction.
21733818aea2SQu Wenruo 	 */
21740b246afaSJeff Mahoney 	btrfs_apply_pending_changes(fs_info);
21753818aea2SQu Wenruo 
21765d4f98a2SYan Zheng 	/* commit_fs_roots gets rid of all the tree log roots, it is now
2177e02119d5SChris Mason 	 * safe to free the root of tree log roots
2178e02119d5SChris Mason 	 */
21790b246afaSJeff Mahoney 	btrfs_free_log_root_tree(trans, fs_info);
2180e02119d5SChris Mason 
21810ed4792aSQu Wenruo 	/*
218282bafb38SQu Wenruo 	 * commit_fs_roots() can call btrfs_save_ino_cache(), which generates
218382bafb38SQu Wenruo 	 * new delayed refs. Must handle them or qgroup can be wrong.
218482bafb38SQu Wenruo 	 */
2185c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
218682bafb38SQu Wenruo 	if (ret) {
218782bafb38SQu Wenruo 		mutex_unlock(&fs_info->tree_log_mutex);
218882bafb38SQu Wenruo 		mutex_unlock(&fs_info->reloc_mutex);
218982bafb38SQu Wenruo 		goto scrub_continue;
219082bafb38SQu Wenruo 	}
219182bafb38SQu Wenruo 
219282bafb38SQu Wenruo 	/*
21930ed4792aSQu Wenruo 	 * Since fs roots are all committed, we can get a quite accurate
21940ed4792aSQu Wenruo 	 * new_roots. So let's do quota accounting.
21950ed4792aSQu Wenruo 	 */
2196460fb20aSNikolay Borisov 	ret = btrfs_qgroup_account_extents(trans);
21970ed4792aSQu Wenruo 	if (ret < 0) {
21980b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
21990b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
22000ed4792aSQu Wenruo 		goto scrub_continue;
22010ed4792aSQu Wenruo 	}
22020ed4792aSQu Wenruo 
22039386d8bcSNikolay Borisov 	ret = commit_cowonly_roots(trans);
220449b25e05SJeff Mahoney 	if (ret) {
22050b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
22060b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
22076cf7f77eSWang Shilong 		goto scrub_continue;
220849b25e05SJeff Mahoney 	}
220954aa1f4dSChris Mason 
22102cba30f1SMiao Xie 	/*
22112cba30f1SMiao Xie 	 * The tasks which save the space cache and inode cache may also
22122cba30f1SMiao Xie 	 * update ->aborted, check it.
22132cba30f1SMiao Xie 	 */
221420c7bcecSSeraphime Kirkovski 	if (unlikely(READ_ONCE(cur_trans->aborted))) {
22152cba30f1SMiao Xie 		ret = cur_trans->aborted;
22160b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
22170b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
22186cf7f77eSWang Shilong 		goto scrub_continue;
22192cba30f1SMiao Xie 	}
22202cba30f1SMiao Xie 
22218b74c03eSDavid Sterba 	btrfs_prepare_extent_commit(fs_info);
222211833d66SYan Zheng 
22230b246afaSJeff Mahoney 	cur_trans = fs_info->running_transaction;
22245f39d397SChris Mason 
22250b246afaSJeff Mahoney 	btrfs_set_root_node(&fs_info->tree_root->root_item,
22260b246afaSJeff Mahoney 			    fs_info->tree_root->node);
22270b246afaSJeff Mahoney 	list_add_tail(&fs_info->tree_root->dirty_list,
22289e351cc8SJosef Bacik 		      &cur_trans->switch_commits);
22295d4f98a2SYan Zheng 
22300b246afaSJeff Mahoney 	btrfs_set_root_node(&fs_info->chunk_root->root_item,
22310b246afaSJeff Mahoney 			    fs_info->chunk_root->node);
22320b246afaSJeff Mahoney 	list_add_tail(&fs_info->chunk_root->dirty_list,
22339e351cc8SJosef Bacik 		      &cur_trans->switch_commits);
22349e351cc8SJosef Bacik 
223516916a88SNikolay Borisov 	switch_commit_roots(cur_trans);
22365d4f98a2SYan Zheng 
2237ce93ec54SJosef Bacik 	ASSERT(list_empty(&cur_trans->dirty_bgs));
22381bbc621eSChris Mason 	ASSERT(list_empty(&cur_trans->io_bgs));
22392ff7e61eSJeff Mahoney 	update_super_roots(fs_info);
2240e02119d5SChris Mason 
22410b246afaSJeff Mahoney 	btrfs_set_super_log_root(fs_info->super_copy, 0);
22420b246afaSJeff Mahoney 	btrfs_set_super_log_root_level(fs_info->super_copy, 0);
22430b246afaSJeff Mahoney 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
22440b246afaSJeff Mahoney 	       sizeof(*fs_info->super_copy));
2245ccd467d6SChris Mason 
2246bbbf7243SNikolay Borisov 	btrfs_commit_device_sizes(cur_trans);
2247935e5cc9SMiao Xie 
22480b246afaSJeff Mahoney 	clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
22490b246afaSJeff Mahoney 	clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2250656f30dbSFilipe Manana 
22514fbcdf66SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
22524fbcdf66SFilipe Manana 
22530b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
22544a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
22550b246afaSJeff Mahoney 	fs_info->running_transaction = NULL;
22560b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
22570b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
2258b7ec40d7SChris Mason 
22590b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
2260e6dcd2dcSChris Mason 
226170458a58SNikolay Borisov 	ret = btrfs_write_and_wait_transaction(trans);
226249b25e05SJeff Mahoney 	if (ret) {
22630b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
226408748810SDavid Sterba 				      "Error while writing out transaction");
22650b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
22666cf7f77eSWang Shilong 		goto scrub_continue;
226749b25e05SJeff Mahoney 	}
226849b25e05SJeff Mahoney 
2269eece6a9cSDavid Sterba 	ret = write_all_supers(fs_info, 0);
2270e02119d5SChris Mason 	/*
2271e02119d5SChris Mason 	 * the super is written, we can safely allow the tree-loggers
2272e02119d5SChris Mason 	 * to go about their business
2273e02119d5SChris Mason 	 */
22740b246afaSJeff Mahoney 	mutex_unlock(&fs_info->tree_log_mutex);
2275c1f32b7cSAnand Jain 	if (ret)
2276c1f32b7cSAnand Jain 		goto scrub_continue;
2277e02119d5SChris Mason 
22785ead2dd0SNikolay Borisov 	btrfs_finish_extent_commit(trans);
22794313b399SChris Mason 
22803204d33cSJosef Bacik 	if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
22810b246afaSJeff Mahoney 		btrfs_clear_space_info_full(fs_info);
228213212b54SZhao Lei 
22830b246afaSJeff Mahoney 	fs_info->last_trans_committed = cur_trans->transid;
22844a9d8bdeSMiao Xie 	/*
22854a9d8bdeSMiao Xie 	 * We needn't acquire the lock here because there is no other task
22864a9d8bdeSMiao Xie 	 * which can change it.
22874a9d8bdeSMiao Xie 	 */
22884a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMPLETED;
22892c90e5d6SChris Mason 	wake_up(&cur_trans->commit_wait);
2290a514d638SQu Wenruo 	clear_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags);
22913de4586cSChris Mason 
22920b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
229313c5a93eSJosef Bacik 	list_del_init(&cur_trans->list);
22940b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2295a4abeea4SJosef Bacik 
2296724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
2297724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
229858176a96SJosef Bacik 
22990860adfdSMiao Xie 	if (trans->type & __TRANS_FREEZABLE)
23000b246afaSJeff Mahoney 		sb_end_intwrite(fs_info->sb);
2301b2b5ef5cSJan Kara 
23023a45bb20SJeff Mahoney 	trace_btrfs_transaction_commit(trans->root);
23031abe9b8aSliubo 
23042ff7e61eSJeff Mahoney 	btrfs_scrub_continue(fs_info);
2305a2de733cSArne Jansen 
23069ed74f2dSJosef Bacik 	if (current->journal_info == trans)
23079ed74f2dSJosef Bacik 		current->journal_info = NULL;
23089ed74f2dSJosef Bacik 
23092c90e5d6SChris Mason 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
231024bbcf04SYan, Zheng 
231179154b1bSChris Mason 	return ret;
231249b25e05SJeff Mahoney 
23136cf7f77eSWang Shilong scrub_continue:
23142ff7e61eSJeff Mahoney 	btrfs_scrub_continue(fs_info);
231549b25e05SJeff Mahoney cleanup_transaction:
2316dc60c525SNikolay Borisov 	btrfs_trans_release_metadata(trans);
2317c7cc64a9SDavid Sterba 	btrfs_cleanup_pending_block_groups(trans);
23184fbcdf66SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
23190e721106SJosef Bacik 	trans->block_rsv = NULL;
23200b246afaSJeff Mahoney 	btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
232149b25e05SJeff Mahoney 	if (current->journal_info == trans)
232249b25e05SJeff Mahoney 		current->journal_info = NULL;
232397cb39bbSNikolay Borisov 	cleanup_transaction(trans, ret);
232449b25e05SJeff Mahoney 
232549b25e05SJeff Mahoney 	return ret;
232679154b1bSChris Mason }
232779154b1bSChris Mason 
2328d352ac68SChris Mason /*
23299d1a2a3aSDavid Sterba  * return < 0 if error
23309d1a2a3aSDavid Sterba  * 0 if there are no more dead_roots at the time of call
23319d1a2a3aSDavid Sterba  * 1 there are more to be processed, call me again
23329d1a2a3aSDavid Sterba  *
23339d1a2a3aSDavid Sterba  * The return value indicates there are certainly more snapshots to delete, but
23349d1a2a3aSDavid Sterba  * if there comes a new one during processing, it may return 0. We don't mind,
23359d1a2a3aSDavid Sterba  * because btrfs_commit_super will poke cleaner thread and it will process it a
23369d1a2a3aSDavid Sterba  * few seconds later.
2337d352ac68SChris Mason  */
23389d1a2a3aSDavid Sterba int btrfs_clean_one_deleted_snapshot(struct btrfs_root *root)
2339e9d0b13bSChris Mason {
23409d1a2a3aSDavid Sterba 	int ret;
23415d4f98a2SYan Zheng 	struct btrfs_fs_info *fs_info = root->fs_info;
2342e9d0b13bSChris Mason 
2343a4abeea4SJosef Bacik 	spin_lock(&fs_info->trans_lock);
23449d1a2a3aSDavid Sterba 	if (list_empty(&fs_info->dead_roots)) {
23459d1a2a3aSDavid Sterba 		spin_unlock(&fs_info->trans_lock);
23469d1a2a3aSDavid Sterba 		return 0;
23479d1a2a3aSDavid Sterba 	}
23489d1a2a3aSDavid Sterba 	root = list_first_entry(&fs_info->dead_roots,
23499d1a2a3aSDavid Sterba 			struct btrfs_root, root_list);
2350cfad392bSJosef Bacik 	list_del_init(&root->root_list);
2351a4abeea4SJosef Bacik 	spin_unlock(&fs_info->trans_lock);
23525d4f98a2SYan Zheng 
23534fd786e6SMisono Tomohiro 	btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
235476dda93cSYan, Zheng 
235516cdcec7SMiao Xie 	btrfs_kill_all_delayed_nodes(root);
235616cdcec7SMiao Xie 
235776dda93cSYan, Zheng 	if (btrfs_header_backref_rev(root->node) <
235876dda93cSYan, Zheng 			BTRFS_MIXED_BACKREF_REV)
23592c536799SJeff Mahoney 		ret = btrfs_drop_snapshot(root, NULL, 0, 0);
236076dda93cSYan, Zheng 	else
23612c536799SJeff Mahoney 		ret = btrfs_drop_snapshot(root, NULL, 1, 0);
236232471dc2SDavid Sterba 
23636596a928SJosef Bacik 	return (ret < 0) ? 0 : 1;
2364e9d0b13bSChris Mason }
2365572d9ab7SDavid Sterba 
2366572d9ab7SDavid Sterba void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2367572d9ab7SDavid Sterba {
2368572d9ab7SDavid Sterba 	unsigned long prev;
2369572d9ab7SDavid Sterba 	unsigned long bit;
2370572d9ab7SDavid Sterba 
23716c9fe14fSQu Wenruo 	prev = xchg(&fs_info->pending_changes, 0);
2372572d9ab7SDavid Sterba 	if (!prev)
2373572d9ab7SDavid Sterba 		return;
2374572d9ab7SDavid Sterba 
23757e1876acSDavid Sterba 	bit = 1 << BTRFS_PENDING_SET_INODE_MAP_CACHE;
23767e1876acSDavid Sterba 	if (prev & bit)
23777e1876acSDavid Sterba 		btrfs_set_opt(fs_info->mount_opt, INODE_MAP_CACHE);
23787e1876acSDavid Sterba 	prev &= ~bit;
23797e1876acSDavid Sterba 
23807e1876acSDavid Sterba 	bit = 1 << BTRFS_PENDING_CLEAR_INODE_MAP_CACHE;
23817e1876acSDavid Sterba 	if (prev & bit)
23827e1876acSDavid Sterba 		btrfs_clear_opt(fs_info->mount_opt, INODE_MAP_CACHE);
23837e1876acSDavid Sterba 	prev &= ~bit;
23847e1876acSDavid Sterba 
2385d51033d0SDavid Sterba 	bit = 1 << BTRFS_PENDING_COMMIT;
2386d51033d0SDavid Sterba 	if (prev & bit)
2387d51033d0SDavid Sterba 		btrfs_debug(fs_info, "pending commit done");
2388d51033d0SDavid Sterba 	prev &= ~bit;
2389d51033d0SDavid Sterba 
2390572d9ab7SDavid Sterba 	if (prev)
2391572d9ab7SDavid Sterba 		btrfs_warn(fs_info,
2392572d9ab7SDavid Sterba 			"unknown pending changes left 0x%lx, ignoring", prev);
2393572d9ab7SDavid Sterba }
2394