xref: /openbmc/linux/fs/btrfs/transaction.c (revision 88090ad3)
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>
13602cbe91SDavid Sterba #include "misc.h"
1479154b1bSChris Mason #include "ctree.h"
1579154b1bSChris Mason #include "disk-io.h"
1679154b1bSChris Mason #include "transaction.h"
17925baeddSChris Mason #include "locking.h"
18e02119d5SChris Mason #include "tree-log.h"
19581bb050SLi Zefan #include "inode-map.h"
20733f4fbbSStefan Behrens #include "volumes.h"
218dabb742SStefan Behrens #include "dev-replace.h"
22fcebe456SJosef Bacik #include "qgroup.h"
23aac0023cSJosef Bacik #include "block-group.h"
249c343784SJosef Bacik #include "space-info.h"
2579154b1bSChris Mason 
260f7d52f4SChris Mason #define BTRFS_ROOT_TRANS_TAG 0
270f7d52f4SChris Mason 
2861c047b5SQu Wenruo /*
2961c047b5SQu Wenruo  * Transaction states and transitions
3061c047b5SQu Wenruo  *
3161c047b5SQu Wenruo  * No running transaction (fs tree blocks are not modified)
3261c047b5SQu Wenruo  * |
3361c047b5SQu Wenruo  * | To next stage:
3461c047b5SQu Wenruo  * |  Call start_transaction() variants. Except btrfs_join_transaction_nostart().
3561c047b5SQu Wenruo  * V
3661c047b5SQu Wenruo  * Transaction N [[TRANS_STATE_RUNNING]]
3761c047b5SQu Wenruo  * |
3861c047b5SQu Wenruo  * | New trans handles can be attached to transaction N by calling all
3961c047b5SQu Wenruo  * | start_transaction() variants.
4061c047b5SQu Wenruo  * |
4161c047b5SQu Wenruo  * | To next stage:
4261c047b5SQu Wenruo  * |  Call btrfs_commit_transaction() on any trans handle attached to
4361c047b5SQu Wenruo  * |  transaction N
4461c047b5SQu Wenruo  * V
4561c047b5SQu Wenruo  * Transaction N [[TRANS_STATE_COMMIT_START]]
4661c047b5SQu Wenruo  * |
4761c047b5SQu Wenruo  * | Will wait for previous running transaction to completely finish if there
4861c047b5SQu Wenruo  * | is one
4961c047b5SQu Wenruo  * |
5061c047b5SQu Wenruo  * | Then one of the following happes:
5161c047b5SQu Wenruo  * | - Wait for all other trans handle holders to release.
5261c047b5SQu Wenruo  * |   The btrfs_commit_transaction() caller will do the commit work.
5361c047b5SQu Wenruo  * | - Wait for current transaction to be committed by others.
5461c047b5SQu Wenruo  * |   Other btrfs_commit_transaction() caller will do the commit work.
5561c047b5SQu Wenruo  * |
5661c047b5SQu Wenruo  * | At this stage, only btrfs_join_transaction*() variants can attach
5761c047b5SQu Wenruo  * | to this running transaction.
5861c047b5SQu Wenruo  * | All other variants will wait for current one to finish and attach to
5961c047b5SQu Wenruo  * | transaction N+1.
6061c047b5SQu Wenruo  * |
6161c047b5SQu Wenruo  * | To next stage:
6261c047b5SQu Wenruo  * |  Caller is chosen to commit transaction N, and all other trans handle
6361c047b5SQu Wenruo  * |  haven been released.
6461c047b5SQu Wenruo  * V
6561c047b5SQu Wenruo  * Transaction N [[TRANS_STATE_COMMIT_DOING]]
6661c047b5SQu Wenruo  * |
6761c047b5SQu Wenruo  * | The heavy lifting transaction work is started.
6861c047b5SQu Wenruo  * | From running delayed refs (modifying extent tree) to creating pending
6961c047b5SQu Wenruo  * | snapshots, running qgroups.
7061c047b5SQu Wenruo  * | In short, modify supporting trees to reflect modifications of subvolume
7161c047b5SQu Wenruo  * | trees.
7261c047b5SQu Wenruo  * |
7361c047b5SQu Wenruo  * | At this stage, all start_transaction() calls will wait for this
7461c047b5SQu Wenruo  * | transaction to finish and attach to transaction N+1.
7561c047b5SQu Wenruo  * |
7661c047b5SQu Wenruo  * | To next stage:
7761c047b5SQu Wenruo  * |  Until all supporting trees are updated.
7861c047b5SQu Wenruo  * V
7961c047b5SQu Wenruo  * Transaction N [[TRANS_STATE_UNBLOCKED]]
8061c047b5SQu Wenruo  * |						    Transaction N+1
8161c047b5SQu Wenruo  * | All needed trees are modified, thus we only    [[TRANS_STATE_RUNNING]]
8261c047b5SQu Wenruo  * | need to write them back to disk and update	    |
8361c047b5SQu Wenruo  * | super blocks.				    |
8461c047b5SQu Wenruo  * |						    |
8561c047b5SQu Wenruo  * | At this stage, new transaction is allowed to   |
8661c047b5SQu Wenruo  * | start.					    |
8761c047b5SQu Wenruo  * | All new start_transaction() calls will be	    |
8861c047b5SQu Wenruo  * | attached to transid N+1.			    |
8961c047b5SQu Wenruo  * |						    |
9061c047b5SQu Wenruo  * | To next stage:				    |
9161c047b5SQu Wenruo  * |  Until all tree blocks are super blocks are    |
9261c047b5SQu Wenruo  * |  written to block devices			    |
9361c047b5SQu Wenruo  * V						    |
9461c047b5SQu Wenruo  * Transaction N [[TRANS_STATE_COMPLETED]]	    V
9561c047b5SQu Wenruo  *   All tree blocks and super blocks are written.  Transaction N+1
9661c047b5SQu Wenruo  *   This transaction is finished and all its	    [[TRANS_STATE_COMMIT_START]]
9761c047b5SQu Wenruo  *   data structures will be cleaned up.	    | Life goes on
9861c047b5SQu Wenruo  */
99e8c9f186SDavid Sterba static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
1004a9d8bdeSMiao Xie 	[TRANS_STATE_RUNNING]		= 0U,
101bcf3a3e7SNikolay Borisov 	[TRANS_STATE_COMMIT_START]	= (__TRANS_START | __TRANS_ATTACH),
102bcf3a3e7SNikolay Borisov 	[TRANS_STATE_COMMIT_DOING]	= (__TRANS_START |
1034a9d8bdeSMiao Xie 					   __TRANS_ATTACH |
104a6d155d2SFilipe Manana 					   __TRANS_JOIN |
105a6d155d2SFilipe Manana 					   __TRANS_JOIN_NOSTART),
106bcf3a3e7SNikolay Borisov 	[TRANS_STATE_UNBLOCKED]		= (__TRANS_START |
1074a9d8bdeSMiao Xie 					   __TRANS_ATTACH |
1084a9d8bdeSMiao Xie 					   __TRANS_JOIN |
109a6d155d2SFilipe Manana 					   __TRANS_JOIN_NOLOCK |
110a6d155d2SFilipe Manana 					   __TRANS_JOIN_NOSTART),
111bcf3a3e7SNikolay Borisov 	[TRANS_STATE_COMPLETED]		= (__TRANS_START |
1124a9d8bdeSMiao Xie 					   __TRANS_ATTACH |
1134a9d8bdeSMiao Xie 					   __TRANS_JOIN |
114a6d155d2SFilipe Manana 					   __TRANS_JOIN_NOLOCK |
115a6d155d2SFilipe Manana 					   __TRANS_JOIN_NOSTART),
1164a9d8bdeSMiao Xie };
1174a9d8bdeSMiao Xie 
118724e2315SJosef Bacik void btrfs_put_transaction(struct btrfs_transaction *transaction)
11979154b1bSChris Mason {
1209b64f57dSElena Reshetova 	WARN_ON(refcount_read(&transaction->use_count) == 0);
1219b64f57dSElena Reshetova 	if (refcount_dec_and_test(&transaction->use_count)) {
122a4abeea4SJosef Bacik 		BUG_ON(!list_empty(&transaction->list));
1235c9d028bSLiu Bo 		WARN_ON(!RB_EMPTY_ROOT(
1245c9d028bSLiu Bo 				&transaction->delayed_refs.href_root.rb_root));
12581f7eb00SJeff Mahoney 		WARN_ON(!RB_EMPTY_ROOT(
12681f7eb00SJeff Mahoney 				&transaction->delayed_refs.dirty_extent_root));
1271262133bSJosef Bacik 		if (transaction->delayed_refs.pending_csums)
128ab8d0fc4SJeff Mahoney 			btrfs_err(transaction->fs_info,
129ab8d0fc4SJeff Mahoney 				  "pending csums is %llu",
1301262133bSJosef Bacik 				  transaction->delayed_refs.pending_csums);
1317785a663SFilipe Manana 		/*
1327785a663SFilipe Manana 		 * If any block groups are found in ->deleted_bgs then it's
1337785a663SFilipe Manana 		 * because the transaction was aborted and a commit did not
1347785a663SFilipe Manana 		 * happen (things failed before writing the new superblock
1357785a663SFilipe Manana 		 * and calling btrfs_finish_extent_commit()), so we can not
1367785a663SFilipe Manana 		 * discard the physical locations of the block groups.
1377785a663SFilipe Manana 		 */
1387785a663SFilipe Manana 		while (!list_empty(&transaction->deleted_bgs)) {
13932da5386SDavid Sterba 			struct btrfs_block_group *cache;
1407785a663SFilipe Manana 
1417785a663SFilipe Manana 			cache = list_first_entry(&transaction->deleted_bgs,
14232da5386SDavid Sterba 						 struct btrfs_block_group,
1437785a663SFilipe Manana 						 bg_list);
1447785a663SFilipe Manana 			list_del_init(&cache->bg_list);
1456b7304afSFilipe Manana 			btrfs_unfreeze_block_group(cache);
1467785a663SFilipe Manana 			btrfs_put_block_group(cache);
1477785a663SFilipe Manana 		}
148bbbf7243SNikolay Borisov 		WARN_ON(!list_empty(&transaction->dev_update_list));
1494b5faeacSDavid Sterba 		kfree(transaction);
15079154b1bSChris Mason 	}
15178fae27eSChris Mason }
15279154b1bSChris Mason 
153889bfa39SJosef Bacik static noinline void switch_commit_roots(struct btrfs_trans_handle *trans)
154817d52f8SJosef Bacik {
155889bfa39SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
15616916a88SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
1579e351cc8SJosef Bacik 	struct btrfs_root *root, *tmp;
1589e351cc8SJosef Bacik 
1599e351cc8SJosef Bacik 	down_write(&fs_info->commit_root_sem);
160889bfa39SJosef Bacik 	list_for_each_entry_safe(root, tmp, &cur_trans->switch_commits,
1619e351cc8SJosef Bacik 				 dirty_list) {
1629e351cc8SJosef Bacik 		list_del_init(&root->dirty_list);
163817d52f8SJosef Bacik 		free_extent_buffer(root->commit_root);
164817d52f8SJosef Bacik 		root->commit_root = btrfs_root_node(root);
1654fd786e6SMisono Tomohiro 		if (is_fstree(root->root_key.objectid))
1669e351cc8SJosef Bacik 			btrfs_unpin_free_ino(root);
16741e7acd3SNikolay Borisov 		extent_io_tree_release(&root->dirty_log_pages);
168370a11b8SQu Wenruo 		btrfs_qgroup_clean_swapped_blocks(root);
1699e351cc8SJosef Bacik 	}
1702b9dbef2SJosef Bacik 
1712b9dbef2SJosef Bacik 	/* We can free old roots now. */
172889bfa39SJosef Bacik 	spin_lock(&cur_trans->dropped_roots_lock);
173889bfa39SJosef Bacik 	while (!list_empty(&cur_trans->dropped_roots)) {
174889bfa39SJosef Bacik 		root = list_first_entry(&cur_trans->dropped_roots,
1752b9dbef2SJosef Bacik 					struct btrfs_root, root_list);
1762b9dbef2SJosef Bacik 		list_del_init(&root->root_list);
177889bfa39SJosef Bacik 		spin_unlock(&cur_trans->dropped_roots_lock);
178889bfa39SJosef Bacik 		btrfs_free_log(trans, root);
1792b9dbef2SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, root);
180889bfa39SJosef Bacik 		spin_lock(&cur_trans->dropped_roots_lock);
1812b9dbef2SJosef Bacik 	}
182889bfa39SJosef Bacik 	spin_unlock(&cur_trans->dropped_roots_lock);
1839e351cc8SJosef Bacik 	up_write(&fs_info->commit_root_sem);
184817d52f8SJosef Bacik }
185817d52f8SJosef Bacik 
1860860adfdSMiao Xie static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
1870860adfdSMiao Xie 					 unsigned int type)
1880860adfdSMiao Xie {
1890860adfdSMiao Xie 	if (type & TRANS_EXTWRITERS)
1900860adfdSMiao Xie 		atomic_inc(&trans->num_extwriters);
1910860adfdSMiao Xie }
1920860adfdSMiao Xie 
1930860adfdSMiao Xie static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
1940860adfdSMiao Xie 					 unsigned int type)
1950860adfdSMiao Xie {
1960860adfdSMiao Xie 	if (type & TRANS_EXTWRITERS)
1970860adfdSMiao Xie 		atomic_dec(&trans->num_extwriters);
1980860adfdSMiao Xie }
1990860adfdSMiao Xie 
2000860adfdSMiao Xie static inline void extwriter_counter_init(struct btrfs_transaction *trans,
2010860adfdSMiao Xie 					  unsigned int type)
2020860adfdSMiao Xie {
2030860adfdSMiao Xie 	atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
2040860adfdSMiao Xie }
2050860adfdSMiao Xie 
2060860adfdSMiao Xie static inline int extwriter_counter_read(struct btrfs_transaction *trans)
2070860adfdSMiao Xie {
2080860adfdSMiao Xie 	return atomic_read(&trans->num_extwriters);
209178260b2SMiao Xie }
210178260b2SMiao Xie 
211d352ac68SChris Mason /*
212fb6dea26SJosef Bacik  * To be called after all the new block groups attached to the transaction
213fb6dea26SJosef Bacik  * handle have been created (btrfs_create_pending_block_groups()).
214fb6dea26SJosef Bacik  */
215fb6dea26SJosef Bacik void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
216fb6dea26SJosef Bacik {
217fb6dea26SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
218fb6dea26SJosef Bacik 
219fb6dea26SJosef Bacik 	if (!trans->chunk_bytes_reserved)
220fb6dea26SJosef Bacik 		return;
221fb6dea26SJosef Bacik 
222fb6dea26SJosef Bacik 	WARN_ON_ONCE(!list_empty(&trans->new_bgs));
223fb6dea26SJosef Bacik 
224fb6dea26SJosef Bacik 	btrfs_block_rsv_release(fs_info, &fs_info->chunk_block_rsv,
22563f018beSNikolay Borisov 				trans->chunk_bytes_reserved, NULL);
226fb6dea26SJosef Bacik 	trans->chunk_bytes_reserved = 0;
227fb6dea26SJosef Bacik }
228fb6dea26SJosef Bacik 
229fb6dea26SJosef Bacik /*
230d352ac68SChris Mason  * either allocate a new transaction or hop into the existing one
231d352ac68SChris Mason  */
2322ff7e61eSJeff Mahoney static noinline int join_transaction(struct btrfs_fs_info *fs_info,
2332ff7e61eSJeff Mahoney 				     unsigned int type)
23479154b1bSChris Mason {
23579154b1bSChris Mason 	struct btrfs_transaction *cur_trans;
236a4abeea4SJosef Bacik 
23719ae4e81SJan Schmidt 	spin_lock(&fs_info->trans_lock);
238d43317dcSChris Mason loop:
23949b25e05SJeff Mahoney 	/* The file system has been taken offline. No new transactions. */
24087533c47SMiao Xie 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
24119ae4e81SJan Schmidt 		spin_unlock(&fs_info->trans_lock);
24249b25e05SJeff Mahoney 		return -EROFS;
24349b25e05SJeff Mahoney 	}
24449b25e05SJeff Mahoney 
24519ae4e81SJan Schmidt 	cur_trans = fs_info->running_transaction;
246a4abeea4SJosef Bacik 	if (cur_trans) {
247bf31f87fSDavid Sterba 		if (TRANS_ABORTED(cur_trans)) {
24819ae4e81SJan Schmidt 			spin_unlock(&fs_info->trans_lock);
24949b25e05SJeff Mahoney 			return cur_trans->aborted;
250871383beSDavid Sterba 		}
2514a9d8bdeSMiao Xie 		if (btrfs_blocked_trans_types[cur_trans->state] & type) {
252178260b2SMiao Xie 			spin_unlock(&fs_info->trans_lock);
253178260b2SMiao Xie 			return -EBUSY;
254178260b2SMiao Xie 		}
2559b64f57dSElena Reshetova 		refcount_inc(&cur_trans->use_count);
256a4abeea4SJosef Bacik 		atomic_inc(&cur_trans->num_writers);
2570860adfdSMiao Xie 		extwriter_counter_inc(cur_trans, type);
25819ae4e81SJan Schmidt 		spin_unlock(&fs_info->trans_lock);
259a4abeea4SJosef Bacik 		return 0;
260a4abeea4SJosef Bacik 	}
26119ae4e81SJan Schmidt 	spin_unlock(&fs_info->trans_lock);
262a4abeea4SJosef Bacik 
263354aa0fbSMiao Xie 	/*
264354aa0fbSMiao Xie 	 * If we are ATTACH, we just want to catch the current transaction,
265354aa0fbSMiao Xie 	 * and commit it. If there is no transaction, just return ENOENT.
266354aa0fbSMiao Xie 	 */
267354aa0fbSMiao Xie 	if (type == TRANS_ATTACH)
268354aa0fbSMiao Xie 		return -ENOENT;
269354aa0fbSMiao Xie 
2704a9d8bdeSMiao Xie 	/*
2714a9d8bdeSMiao Xie 	 * JOIN_NOLOCK only happens during the transaction commit, so
2724a9d8bdeSMiao Xie 	 * it is impossible that ->running_transaction is NULL
2734a9d8bdeSMiao Xie 	 */
2744a9d8bdeSMiao Xie 	BUG_ON(type == TRANS_JOIN_NOLOCK);
2754a9d8bdeSMiao Xie 
2764b5faeacSDavid Sterba 	cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
277db5b493aSTsutomu Itoh 	if (!cur_trans)
278db5b493aSTsutomu Itoh 		return -ENOMEM;
279d43317dcSChris Mason 
28019ae4e81SJan Schmidt 	spin_lock(&fs_info->trans_lock);
28119ae4e81SJan Schmidt 	if (fs_info->running_transaction) {
282d43317dcSChris Mason 		/*
283d43317dcSChris Mason 		 * someone started a transaction after we unlocked.  Make sure
2844a9d8bdeSMiao Xie 		 * to redo the checks above
285d43317dcSChris Mason 		 */
2864b5faeacSDavid Sterba 		kfree(cur_trans);
287d43317dcSChris Mason 		goto loop;
28887533c47SMiao Xie 	} else if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
289e4b50e14SDan Carpenter 		spin_unlock(&fs_info->trans_lock);
2904b5faeacSDavid Sterba 		kfree(cur_trans);
2917b8b92afSJosef Bacik 		return -EROFS;
292a4abeea4SJosef Bacik 	}
293d43317dcSChris Mason 
294ab8d0fc4SJeff Mahoney 	cur_trans->fs_info = fs_info;
29548778179SFilipe Manana 	atomic_set(&cur_trans->pending_ordered, 0);
29648778179SFilipe Manana 	init_waitqueue_head(&cur_trans->pending_wait);
29713c5a93eSJosef Bacik 	atomic_set(&cur_trans->num_writers, 1);
2980860adfdSMiao Xie 	extwriter_counter_init(cur_trans, type);
29979154b1bSChris Mason 	init_waitqueue_head(&cur_trans->writer_wait);
30079154b1bSChris Mason 	init_waitqueue_head(&cur_trans->commit_wait);
3014a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_RUNNING;
302a4abeea4SJosef Bacik 	/*
303a4abeea4SJosef Bacik 	 * One for this trans handle, one so it will live on until we
304a4abeea4SJosef Bacik 	 * commit the transaction.
305a4abeea4SJosef Bacik 	 */
3069b64f57dSElena Reshetova 	refcount_set(&cur_trans->use_count, 2);
3073204d33cSJosef Bacik 	cur_trans->flags = 0;
308afd48513SArnd Bergmann 	cur_trans->start_time = ktime_get_seconds();
30956bec294SChris Mason 
310a099d0fdSAlexandru Moise 	memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
311a099d0fdSAlexandru Moise 
3125c9d028bSLiu Bo 	cur_trans->delayed_refs.href_root = RB_ROOT_CACHED;
3133368d001SQu Wenruo 	cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
314d7df2c79SJosef Bacik 	atomic_set(&cur_trans->delayed_refs.num_entries, 0);
31520b297d6SJan Schmidt 
31620b297d6SJan Schmidt 	/*
31720b297d6SJan Schmidt 	 * although the tree mod log is per file system and not per transaction,
31820b297d6SJan Schmidt 	 * the log must never go across transaction boundaries.
31920b297d6SJan Schmidt 	 */
32020b297d6SJan Schmidt 	smp_mb();
32131b1a2bdSJulia Lawall 	if (!list_empty(&fs_info->tree_mod_seq_list))
3225d163e0eSJeff Mahoney 		WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
32331b1a2bdSJulia Lawall 	if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
3245d163e0eSJeff Mahoney 		WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
325fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
32620b297d6SJan Schmidt 
32756bec294SChris Mason 	spin_lock_init(&cur_trans->delayed_refs.lock);
32856bec294SChris Mason 
3293063d29fSChris Mason 	INIT_LIST_HEAD(&cur_trans->pending_snapshots);
330bbbf7243SNikolay Borisov 	INIT_LIST_HEAD(&cur_trans->dev_update_list);
3319e351cc8SJosef Bacik 	INIT_LIST_HEAD(&cur_trans->switch_commits);
332ce93ec54SJosef Bacik 	INIT_LIST_HEAD(&cur_trans->dirty_bgs);
3331bbc621eSChris Mason 	INIT_LIST_HEAD(&cur_trans->io_bgs);
3342b9dbef2SJosef Bacik 	INIT_LIST_HEAD(&cur_trans->dropped_roots);
3351bbc621eSChris Mason 	mutex_init(&cur_trans->cache_write_mutex);
336ce93ec54SJosef Bacik 	spin_lock_init(&cur_trans->dirty_bgs_lock);
337e33e17eeSJeff Mahoney 	INIT_LIST_HEAD(&cur_trans->deleted_bgs);
3382b9dbef2SJosef Bacik 	spin_lock_init(&cur_trans->dropped_roots_lock);
33919ae4e81SJan Schmidt 	list_add_tail(&cur_trans->list, &fs_info->trans_list);
340c258d6e3SQu Wenruo 	extent_io_tree_init(fs_info, &cur_trans->dirty_pages,
34143eb5f29SQu Wenruo 			IO_TREE_TRANS_DIRTY_PAGES, fs_info->btree_inode);
342fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &cur_trans->pinned_extents,
343fe119a6eSNikolay Borisov 			IO_TREE_FS_PINNED_EXTENTS, NULL);
34419ae4e81SJan Schmidt 	fs_info->generation++;
34519ae4e81SJan Schmidt 	cur_trans->transid = fs_info->generation;
34619ae4e81SJan Schmidt 	fs_info->running_transaction = cur_trans;
34749b25e05SJeff Mahoney 	cur_trans->aborted = 0;
34819ae4e81SJan Schmidt 	spin_unlock(&fs_info->trans_lock);
34915ee9bc7SJosef Bacik 
35079154b1bSChris Mason 	return 0;
35179154b1bSChris Mason }
35279154b1bSChris Mason 
353d352ac68SChris Mason /*
35492a7cc42SQu Wenruo  * This does all the record keeping required to make sure that a shareable root
35592a7cc42SQu Wenruo  * is properly recorded in a given transaction.  This is required to make sure
35692a7cc42SQu Wenruo  * the old root from before we joined the transaction is deleted when the
35792a7cc42SQu Wenruo  * transaction commits.
358d352ac68SChris Mason  */
3597585717fSChris Mason static int record_root_in_trans(struct btrfs_trans_handle *trans,
3606426c7adSQu Wenruo 			       struct btrfs_root *root,
3616426c7adSQu Wenruo 			       int force)
3626702ed49SChris Mason {
3630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3640b246afaSJeff Mahoney 
36592a7cc42SQu Wenruo 	if ((test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
3666426c7adSQu Wenruo 	    root->last_trans < trans->transid) || force) {
3670b246afaSJeff Mahoney 		WARN_ON(root == fs_info->extent_root);
3684d31778aSQu Wenruo 		WARN_ON(!force && root->commit_root != root->node);
3695d4f98a2SYan Zheng 
3707585717fSChris Mason 		/*
37127cdeb70SMiao Xie 		 * see below for IN_TRANS_SETUP usage rules
3727585717fSChris Mason 		 * we have the reloc mutex held now, so there
3737585717fSChris Mason 		 * is only one writer in this function
3747585717fSChris Mason 		 */
37527cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
3767585717fSChris Mason 
37727cdeb70SMiao Xie 		/* make sure readers find IN_TRANS_SETUP before
3787585717fSChris Mason 		 * they find our root->last_trans update
3797585717fSChris Mason 		 */
3807585717fSChris Mason 		smp_wmb();
3817585717fSChris Mason 
3820b246afaSJeff Mahoney 		spin_lock(&fs_info->fs_roots_radix_lock);
3836426c7adSQu Wenruo 		if (root->last_trans == trans->transid && !force) {
3840b246afaSJeff Mahoney 			spin_unlock(&fs_info->fs_roots_radix_lock);
385a4abeea4SJosef Bacik 			return 0;
386a4abeea4SJosef Bacik 		}
3870b246afaSJeff Mahoney 		radix_tree_tag_set(&fs_info->fs_roots_radix,
3886702ed49SChris Mason 				   (unsigned long)root->root_key.objectid,
3896702ed49SChris Mason 				   BTRFS_ROOT_TRANS_TAG);
3900b246afaSJeff Mahoney 		spin_unlock(&fs_info->fs_roots_radix_lock);
3917585717fSChris Mason 		root->last_trans = trans->transid;
3927585717fSChris Mason 
3937585717fSChris Mason 		/* this is pretty tricky.  We don't want to
3947585717fSChris Mason 		 * take the relocation lock in btrfs_record_root_in_trans
3957585717fSChris Mason 		 * unless we're really doing the first setup for this root in
3967585717fSChris Mason 		 * this transaction.
3977585717fSChris Mason 		 *
3987585717fSChris Mason 		 * Normally we'd use root->last_trans as a flag to decide
3997585717fSChris Mason 		 * if we want to take the expensive mutex.
4007585717fSChris Mason 		 *
4017585717fSChris Mason 		 * But, we have to set root->last_trans before we
4027585717fSChris Mason 		 * init the relocation root, otherwise, we trip over warnings
4037585717fSChris Mason 		 * in ctree.c.  The solution used here is to flag ourselves
40427cdeb70SMiao Xie 		 * with root IN_TRANS_SETUP.  When this is 1, we're still
4057585717fSChris Mason 		 * fixing up the reloc trees and everyone must wait.
4067585717fSChris Mason 		 *
4077585717fSChris Mason 		 * When this is zero, they can trust root->last_trans and fly
4087585717fSChris Mason 		 * through btrfs_record_root_in_trans without having to take the
4097585717fSChris Mason 		 * lock.  smp_wmb() makes sure that all the writes above are
4107585717fSChris Mason 		 * done before we pop in the zero below
4117585717fSChris Mason 		 */
4125d4f98a2SYan Zheng 		btrfs_init_reloc_root(trans, root);
413c7548af6SChris Mason 		smp_mb__before_atomic();
41427cdeb70SMiao Xie 		clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
4156702ed49SChris Mason 	}
4165d4f98a2SYan Zheng 	return 0;
4176702ed49SChris Mason }
4185d4f98a2SYan Zheng 
4197585717fSChris Mason 
4202b9dbef2SJosef Bacik void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
4212b9dbef2SJosef Bacik 			    struct btrfs_root *root)
4222b9dbef2SJosef Bacik {
4230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4242b9dbef2SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
4252b9dbef2SJosef Bacik 
4262b9dbef2SJosef Bacik 	/* Add ourselves to the transaction dropped list */
4272b9dbef2SJosef Bacik 	spin_lock(&cur_trans->dropped_roots_lock);
4282b9dbef2SJosef Bacik 	list_add_tail(&root->root_list, &cur_trans->dropped_roots);
4292b9dbef2SJosef Bacik 	spin_unlock(&cur_trans->dropped_roots_lock);
4302b9dbef2SJosef Bacik 
4312b9dbef2SJosef Bacik 	/* Make sure we don't try to update the root at commit time */
4320b246afaSJeff Mahoney 	spin_lock(&fs_info->fs_roots_radix_lock);
4330b246afaSJeff Mahoney 	radix_tree_tag_clear(&fs_info->fs_roots_radix,
4342b9dbef2SJosef Bacik 			     (unsigned long)root->root_key.objectid,
4352b9dbef2SJosef Bacik 			     BTRFS_ROOT_TRANS_TAG);
4360b246afaSJeff Mahoney 	spin_unlock(&fs_info->fs_roots_radix_lock);
4372b9dbef2SJosef Bacik }
4382b9dbef2SJosef Bacik 
4397585717fSChris Mason int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
4407585717fSChris Mason 			       struct btrfs_root *root)
4417585717fSChris Mason {
4420b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4430b246afaSJeff Mahoney 
44492a7cc42SQu Wenruo 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4457585717fSChris Mason 		return 0;
4467585717fSChris Mason 
4477585717fSChris Mason 	/*
44827cdeb70SMiao Xie 	 * see record_root_in_trans for comments about IN_TRANS_SETUP usage
4497585717fSChris Mason 	 * and barriers
4507585717fSChris Mason 	 */
4517585717fSChris Mason 	smp_rmb();
4527585717fSChris Mason 	if (root->last_trans == trans->transid &&
45327cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
4547585717fSChris Mason 		return 0;
4557585717fSChris Mason 
4560b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
4576426c7adSQu Wenruo 	record_root_in_trans(trans, root, 0);
4580b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
4597585717fSChris Mason 
4607585717fSChris Mason 	return 0;
4617585717fSChris Mason }
4627585717fSChris Mason 
4634a9d8bdeSMiao Xie static inline int is_transaction_blocked(struct btrfs_transaction *trans)
4644a9d8bdeSMiao Xie {
4653296bf56SQu Wenruo 	return (trans->state >= TRANS_STATE_COMMIT_START &&
466501407aaSJosef Bacik 		trans->state < TRANS_STATE_UNBLOCKED &&
467bf31f87fSDavid Sterba 		!TRANS_ABORTED(trans));
4684a9d8bdeSMiao Xie }
4694a9d8bdeSMiao Xie 
470d352ac68SChris Mason /* wait for commit against the current transaction to become unblocked
471d352ac68SChris Mason  * when this is done, it is safe to start a new transaction, but the current
472d352ac68SChris Mason  * transaction might not be fully on disk.
473d352ac68SChris Mason  */
4742ff7e61eSJeff Mahoney static void wait_current_trans(struct btrfs_fs_info *fs_info)
47579154b1bSChris Mason {
476f9295749SChris Mason 	struct btrfs_transaction *cur_trans;
47779154b1bSChris Mason 
4780b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
4790b246afaSJeff Mahoney 	cur_trans = fs_info->running_transaction;
4804a9d8bdeSMiao Xie 	if (cur_trans && is_transaction_blocked(cur_trans)) {
4819b64f57dSElena Reshetova 		refcount_inc(&cur_trans->use_count);
4820b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
48372d63ed6SLi Zefan 
4840b246afaSJeff Mahoney 		wait_event(fs_info->transaction_wait,
485501407aaSJosef Bacik 			   cur_trans->state >= TRANS_STATE_UNBLOCKED ||
486bf31f87fSDavid Sterba 			   TRANS_ABORTED(cur_trans));
487724e2315SJosef Bacik 		btrfs_put_transaction(cur_trans);
488a4abeea4SJosef Bacik 	} else {
4890b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
490f9295749SChris Mason 	}
49137d1aeeeSChris Mason }
49237d1aeeeSChris Mason 
4932ff7e61eSJeff Mahoney static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
49437d1aeeeSChris Mason {
4950b246afaSJeff Mahoney 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
496a4abeea4SJosef Bacik 		return 0;
497a4abeea4SJosef Bacik 
49892e2f7e3SNikolay Borisov 	if (type == TRANS_START)
499a4abeea4SJosef Bacik 		return 1;
500a4abeea4SJosef Bacik 
501a22285a6SYan, Zheng 	return 0;
502a22285a6SYan, Zheng }
503a22285a6SYan, Zheng 
50420dd2cbfSMiao Xie static inline bool need_reserve_reloc_root(struct btrfs_root *root)
50520dd2cbfSMiao Xie {
5060b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5070b246afaSJeff Mahoney 
5080b246afaSJeff Mahoney 	if (!fs_info->reloc_ctl ||
50992a7cc42SQu Wenruo 	    !test_bit(BTRFS_ROOT_SHAREABLE, &root->state) ||
51020dd2cbfSMiao Xie 	    root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
51120dd2cbfSMiao Xie 	    root->reloc_root)
51220dd2cbfSMiao Xie 		return false;
51320dd2cbfSMiao Xie 
51420dd2cbfSMiao Xie 	return true;
51520dd2cbfSMiao Xie }
51620dd2cbfSMiao Xie 
51708e007d2SMiao Xie static struct btrfs_trans_handle *
5185aed1dd8SAlexandru Moise start_transaction(struct btrfs_root *root, unsigned int num_items,
519003d7c59SJeff Mahoney 		  unsigned int type, enum btrfs_reserve_flush_enum flush,
520003d7c59SJeff Mahoney 		  bool enforce_qgroups)
521a22285a6SYan, Zheng {
5220b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
523ba2c4d4eSJosef Bacik 	struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
524a22285a6SYan, Zheng 	struct btrfs_trans_handle *h;
525a22285a6SYan, Zheng 	struct btrfs_transaction *cur_trans;
526b5009945SJosef Bacik 	u64 num_bytes = 0;
527c5567237SArne Jansen 	u64 qgroup_reserved = 0;
52820dd2cbfSMiao Xie 	bool reloc_reserved = false;
5299c343784SJosef Bacik 	bool do_chunk_alloc = false;
53020dd2cbfSMiao Xie 	int ret;
531acce952bSliubo 
53246c4e71eSFilipe Manana 	/* Send isn't supposed to start transactions. */
5332755a0deSDavid Sterba 	ASSERT(current->journal_info != BTRFS_SEND_TRANS_STUB);
53446c4e71eSFilipe Manana 
5350b246afaSJeff Mahoney 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
536acce952bSliubo 		return ERR_PTR(-EROFS);
5372a1eb461SJosef Bacik 
53846c4e71eSFilipe Manana 	if (current->journal_info) {
5390860adfdSMiao Xie 		WARN_ON(type & TRANS_EXTWRITERS);
5402a1eb461SJosef Bacik 		h = current->journal_info;
541b50fff81SDavid Sterba 		refcount_inc(&h->use_count);
542b50fff81SDavid Sterba 		WARN_ON(refcount_read(&h->use_count) > 2);
5432a1eb461SJosef Bacik 		h->orig_rsv = h->block_rsv;
5442a1eb461SJosef Bacik 		h->block_rsv = NULL;
5452a1eb461SJosef Bacik 		goto got_it;
5462a1eb461SJosef Bacik 	}
547b5009945SJosef Bacik 
548b5009945SJosef Bacik 	/*
549b5009945SJosef Bacik 	 * Do the reservation before we join the transaction so we can do all
550b5009945SJosef Bacik 	 * the appropriate flushing if need be.
551b5009945SJosef Bacik 	 */
552003d7c59SJeff Mahoney 	if (num_items && root != fs_info->chunk_root) {
553ba2c4d4eSJosef Bacik 		struct btrfs_block_rsv *rsv = &fs_info->trans_block_rsv;
554ba2c4d4eSJosef Bacik 		u64 delayed_refs_bytes = 0;
555ba2c4d4eSJosef Bacik 
5560b246afaSJeff Mahoney 		qgroup_reserved = num_items * fs_info->nodesize;
557733e03a0SQu Wenruo 		ret = btrfs_qgroup_reserve_meta_pertrans(root, qgroup_reserved,
558003d7c59SJeff Mahoney 				enforce_qgroups);
559c5567237SArne Jansen 		if (ret)
560c5567237SArne Jansen 			return ERR_PTR(ret);
561c5567237SArne Jansen 
562ba2c4d4eSJosef Bacik 		/*
563ba2c4d4eSJosef Bacik 		 * We want to reserve all the bytes we may need all at once, so
564ba2c4d4eSJosef Bacik 		 * we only do 1 enospc flushing cycle per transaction start.  We
565ba2c4d4eSJosef Bacik 		 * accomplish this by simply assuming we'll do 2 x num_items
566ba2c4d4eSJosef Bacik 		 * worth of delayed refs updates in this trans handle, and
567ba2c4d4eSJosef Bacik 		 * refill that amount for whatever is missing in the reserve.
568ba2c4d4eSJosef Bacik 		 */
5692bd36e7bSJosef Bacik 		num_bytes = btrfs_calc_insert_metadata_size(fs_info, num_items);
5707f9fe614SJosef Bacik 		if (flush == BTRFS_RESERVE_FLUSH_ALL &&
5717f9fe614SJosef Bacik 		    delayed_refs_rsv->full == 0) {
572ba2c4d4eSJosef Bacik 			delayed_refs_bytes = num_bytes;
573ba2c4d4eSJosef Bacik 			num_bytes <<= 1;
574ba2c4d4eSJosef Bacik 		}
575ba2c4d4eSJosef Bacik 
57620dd2cbfSMiao Xie 		/*
57720dd2cbfSMiao Xie 		 * Do the reservation for the relocation root creation
57820dd2cbfSMiao Xie 		 */
579ee39b432SDavid Sterba 		if (need_reserve_reloc_root(root)) {
5800b246afaSJeff Mahoney 			num_bytes += fs_info->nodesize;
58120dd2cbfSMiao Xie 			reloc_reserved = true;
58220dd2cbfSMiao Xie 		}
58320dd2cbfSMiao Xie 
584ba2c4d4eSJosef Bacik 		ret = btrfs_block_rsv_add(root, rsv, num_bytes, flush);
585ba2c4d4eSJosef Bacik 		if (ret)
586ba2c4d4eSJosef Bacik 			goto reserve_fail;
587ba2c4d4eSJosef Bacik 		if (delayed_refs_bytes) {
588ba2c4d4eSJosef Bacik 			btrfs_migrate_to_delayed_refs_rsv(fs_info, rsv,
589ba2c4d4eSJosef Bacik 							  delayed_refs_bytes);
590ba2c4d4eSJosef Bacik 			num_bytes -= delayed_refs_bytes;
591ba2c4d4eSJosef Bacik 		}
5929c343784SJosef Bacik 
5939c343784SJosef Bacik 		if (rsv->space_info->force_alloc)
5949c343784SJosef Bacik 			do_chunk_alloc = true;
595ba2c4d4eSJosef Bacik 	} else if (num_items == 0 && flush == BTRFS_RESERVE_FLUSH_ALL &&
596ba2c4d4eSJosef Bacik 		   !delayed_refs_rsv->full) {
597ba2c4d4eSJosef Bacik 		/*
598ba2c4d4eSJosef Bacik 		 * Some people call with btrfs_start_transaction(root, 0)
599ba2c4d4eSJosef Bacik 		 * because they can be throttled, but have some other mechanism
600ba2c4d4eSJosef Bacik 		 * for reserving space.  We still want these guys to refill the
601ba2c4d4eSJosef Bacik 		 * delayed block_rsv so just add 1 items worth of reservation
602ba2c4d4eSJosef Bacik 		 * here.
603ba2c4d4eSJosef Bacik 		 */
604ba2c4d4eSJosef Bacik 		ret = btrfs_delayed_refs_rsv_refill(fs_info, flush);
605b5009945SJosef Bacik 		if (ret)
606843fcf35SMiao Xie 			goto reserve_fail;
607b5009945SJosef Bacik 	}
608a22285a6SYan, Zheng again:
609f2f767e7SAlexandru Moise 	h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
610843fcf35SMiao Xie 	if (!h) {
611843fcf35SMiao Xie 		ret = -ENOMEM;
612843fcf35SMiao Xie 		goto alloc_fail;
613843fcf35SMiao Xie 	}
614a22285a6SYan, Zheng 
61598114659SJosef Bacik 	/*
61698114659SJosef Bacik 	 * If we are JOIN_NOLOCK we're already committing a transaction and
61798114659SJosef Bacik 	 * waiting on this guy, so we don't need to do the sb_start_intwrite
61898114659SJosef Bacik 	 * because we're already holding a ref.  We need this because we could
61998114659SJosef Bacik 	 * have raced in and did an fsync() on a file which can kick a commit
62098114659SJosef Bacik 	 * and then we deadlock with somebody doing a freeze.
621354aa0fbSMiao Xie 	 *
622354aa0fbSMiao Xie 	 * If we are ATTACH, it means we just want to catch the current
623354aa0fbSMiao Xie 	 * transaction and commit it, so we needn't do sb_start_intwrite().
62498114659SJosef Bacik 	 */
6250860adfdSMiao Xie 	if (type & __TRANS_FREEZABLE)
6260b246afaSJeff Mahoney 		sb_start_intwrite(fs_info->sb);
627b2b5ef5cSJan Kara 
6282ff7e61eSJeff Mahoney 	if (may_wait_transaction(fs_info, type))
6292ff7e61eSJeff Mahoney 		wait_current_trans(fs_info);
630a22285a6SYan, Zheng 
631a4abeea4SJosef Bacik 	do {
6322ff7e61eSJeff Mahoney 		ret = join_transaction(fs_info, type);
633178260b2SMiao Xie 		if (ret == -EBUSY) {
6342ff7e61eSJeff Mahoney 			wait_current_trans(fs_info);
635a6d155d2SFilipe Manana 			if (unlikely(type == TRANS_ATTACH ||
636a6d155d2SFilipe Manana 				     type == TRANS_JOIN_NOSTART))
637178260b2SMiao Xie 				ret = -ENOENT;
638178260b2SMiao Xie 		}
639a4abeea4SJosef Bacik 	} while (ret == -EBUSY);
640a4abeea4SJosef Bacik 
641a43f7f82SLiu Bo 	if (ret < 0)
642843fcf35SMiao Xie 		goto join_fail;
6430f7d52f4SChris Mason 
6440b246afaSJeff Mahoney 	cur_trans = fs_info->running_transaction;
645a22285a6SYan, Zheng 
646a22285a6SYan, Zheng 	h->transid = cur_trans->transid;
647a22285a6SYan, Zheng 	h->transaction = cur_trans;
648d13603efSArne Jansen 	h->root = root;
649b50fff81SDavid Sterba 	refcount_set(&h->use_count, 1);
65064b63580SJeff Mahoney 	h->fs_info = root->fs_info;
6517174109cSQu Wenruo 
652a698d075SMiao Xie 	h->type = type;
653d9a0540aSFilipe Manana 	h->can_flush_pending_bgs = true;
654ea658badSJosef Bacik 	INIT_LIST_HEAD(&h->new_bgs);
655b7ec40d7SChris Mason 
656a22285a6SYan, Zheng 	smp_mb();
6573296bf56SQu Wenruo 	if (cur_trans->state >= TRANS_STATE_COMMIT_START &&
6582ff7e61eSJeff Mahoney 	    may_wait_transaction(fs_info, type)) {
659abdd2e80SFilipe Manana 		current->journal_info = h;
6603a45bb20SJeff Mahoney 		btrfs_commit_transaction(h);
661a22285a6SYan, Zheng 		goto again;
662a22285a6SYan, Zheng 	}
6639ed74f2dSJosef Bacik 
664b5009945SJosef Bacik 	if (num_bytes) {
6650b246afaSJeff Mahoney 		trace_btrfs_space_reservation(fs_info, "transaction",
6662bcc0328SLiu Bo 					      h->transid, num_bytes, 1);
6670b246afaSJeff Mahoney 		h->block_rsv = &fs_info->trans_block_rsv;
668b5009945SJosef Bacik 		h->bytes_reserved = num_bytes;
66920dd2cbfSMiao Xie 		h->reloc_reserved = reloc_reserved;
670a22285a6SYan, Zheng 	}
671a22285a6SYan, Zheng 
6722a1eb461SJosef Bacik got_it:
673bcf3a3e7SNikolay Borisov 	if (!current->journal_info)
674a22285a6SYan, Zheng 		current->journal_info = h;
675fcc99734SQu Wenruo 
676fcc99734SQu Wenruo 	/*
6779c343784SJosef Bacik 	 * If the space_info is marked ALLOC_FORCE then we'll get upgraded to
6789c343784SJosef Bacik 	 * ALLOC_FORCE the first run through, and then we won't allocate for
6799c343784SJosef Bacik 	 * anybody else who races in later.  We don't care about the return
6809c343784SJosef Bacik 	 * value here.
6819c343784SJosef Bacik 	 */
6829c343784SJosef Bacik 	if (do_chunk_alloc && num_bytes) {
6839c343784SJosef Bacik 		u64 flags = h->block_rsv->space_info->flags;
6849c343784SJosef Bacik 
6859c343784SJosef Bacik 		btrfs_chunk_alloc(h, btrfs_get_alloc_profile(fs_info, flags),
6869c343784SJosef Bacik 				  CHUNK_ALLOC_NO_FORCE);
6879c343784SJosef Bacik 	}
6889c343784SJosef Bacik 
6899c343784SJosef Bacik 	/*
690fcc99734SQu Wenruo 	 * btrfs_record_root_in_trans() needs to alloc new extents, and may
691fcc99734SQu Wenruo 	 * call btrfs_join_transaction() while we're also starting a
692fcc99734SQu Wenruo 	 * transaction.
693fcc99734SQu Wenruo 	 *
694fcc99734SQu Wenruo 	 * Thus it need to be called after current->journal_info initialized,
695fcc99734SQu Wenruo 	 * or we can deadlock.
696fcc99734SQu Wenruo 	 */
697fcc99734SQu Wenruo 	btrfs_record_root_in_trans(h, root);
698fcc99734SQu Wenruo 
69979154b1bSChris Mason 	return h;
700843fcf35SMiao Xie 
701843fcf35SMiao Xie join_fail:
7020860adfdSMiao Xie 	if (type & __TRANS_FREEZABLE)
7030b246afaSJeff Mahoney 		sb_end_intwrite(fs_info->sb);
704843fcf35SMiao Xie 	kmem_cache_free(btrfs_trans_handle_cachep, h);
705843fcf35SMiao Xie alloc_fail:
706843fcf35SMiao Xie 	if (num_bytes)
7072ff7e61eSJeff Mahoney 		btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
70863f018beSNikolay Borisov 					num_bytes, NULL);
709843fcf35SMiao Xie reserve_fail:
710733e03a0SQu Wenruo 	btrfs_qgroup_free_meta_pertrans(root, qgroup_reserved);
711843fcf35SMiao Xie 	return ERR_PTR(ret);
71279154b1bSChris Mason }
71379154b1bSChris Mason 
714f9295749SChris Mason struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
7155aed1dd8SAlexandru Moise 						   unsigned int num_items)
716f9295749SChris Mason {
71708e007d2SMiao Xie 	return start_transaction(root, num_items, TRANS_START,
718003d7c59SJeff Mahoney 				 BTRFS_RESERVE_FLUSH_ALL, true);
719f9295749SChris Mason }
720003d7c59SJeff Mahoney 
7218eab77ffSFilipe Manana struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
7228eab77ffSFilipe Manana 					struct btrfs_root *root,
7237f9fe614SJosef Bacik 					unsigned int num_items)
7248eab77ffSFilipe Manana {
7257f9fe614SJosef Bacik 	return start_transaction(root, num_items, TRANS_START,
7267f9fe614SJosef Bacik 				 BTRFS_RESERVE_FLUSH_ALL_STEAL, false);
7278eab77ffSFilipe Manana }
7288407aa46SMiao Xie 
7297a7eaa40SJosef Bacik struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
730f9295749SChris Mason {
731003d7c59SJeff Mahoney 	return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
732003d7c59SJeff Mahoney 				 true);
733f9295749SChris Mason }
734f9295749SChris Mason 
7358d510121SNikolay Borisov struct btrfs_trans_handle *btrfs_join_transaction_spacecache(struct btrfs_root *root)
7360af3d00bSJosef Bacik {
737575a75d6SAlexandru Moise 	return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
738003d7c59SJeff Mahoney 				 BTRFS_RESERVE_NO_FLUSH, true);
7390af3d00bSJosef Bacik }
7400af3d00bSJosef Bacik 
741d4edf39bSMiao Xie /*
742a6d155d2SFilipe Manana  * Similar to regular join but it never starts a transaction when none is
743a6d155d2SFilipe Manana  * running or after waiting for the current one to finish.
744a6d155d2SFilipe Manana  */
745a6d155d2SFilipe Manana struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
746a6d155d2SFilipe Manana {
747a6d155d2SFilipe Manana 	return start_transaction(root, 0, TRANS_JOIN_NOSTART,
748a6d155d2SFilipe Manana 				 BTRFS_RESERVE_NO_FLUSH, true);
749a6d155d2SFilipe Manana }
750a6d155d2SFilipe Manana 
751a6d155d2SFilipe Manana /*
752d4edf39bSMiao Xie  * btrfs_attach_transaction() - catch the running transaction
753d4edf39bSMiao Xie  *
754d4edf39bSMiao Xie  * It is used when we want to commit the current the transaction, but
755d4edf39bSMiao Xie  * don't want to start a new one.
756d4edf39bSMiao Xie  *
757d4edf39bSMiao Xie  * Note: If this function return -ENOENT, it just means there is no
758d4edf39bSMiao Xie  * running transaction. But it is possible that the inactive transaction
759d4edf39bSMiao Xie  * is still in the memory, not fully on disk. If you hope there is no
760d4edf39bSMiao Xie  * inactive transaction in the fs when -ENOENT is returned, you should
761d4edf39bSMiao Xie  * invoke
762d4edf39bSMiao Xie  *     btrfs_attach_transaction_barrier()
763d4edf39bSMiao Xie  */
764354aa0fbSMiao Xie struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
76560376ce4SJosef Bacik {
766575a75d6SAlexandru Moise 	return start_transaction(root, 0, TRANS_ATTACH,
767003d7c59SJeff Mahoney 				 BTRFS_RESERVE_NO_FLUSH, true);
76860376ce4SJosef Bacik }
76960376ce4SJosef Bacik 
770d4edf39bSMiao Xie /*
77190b6d283SWang Sheng-Hui  * btrfs_attach_transaction_barrier() - catch the running transaction
772d4edf39bSMiao Xie  *
77352042d8eSAndrea Gelmini  * It is similar to the above function, the difference is this one
774d4edf39bSMiao Xie  * will wait for all the inactive transactions until they fully
775d4edf39bSMiao Xie  * complete.
776d4edf39bSMiao Xie  */
777d4edf39bSMiao Xie struct btrfs_trans_handle *
778d4edf39bSMiao Xie btrfs_attach_transaction_barrier(struct btrfs_root *root)
779d4edf39bSMiao Xie {
780d4edf39bSMiao Xie 	struct btrfs_trans_handle *trans;
781d4edf39bSMiao Xie 
782575a75d6SAlexandru Moise 	trans = start_transaction(root, 0, TRANS_ATTACH,
783003d7c59SJeff Mahoney 				  BTRFS_RESERVE_NO_FLUSH, true);
7848d9e220cSAl Viro 	if (trans == ERR_PTR(-ENOENT))
7852ff7e61eSJeff Mahoney 		btrfs_wait_for_commit(root->fs_info, 0);
786d4edf39bSMiao Xie 
787d4edf39bSMiao Xie 	return trans;
788d4edf39bSMiao Xie }
789d4edf39bSMiao Xie 
790d352ac68SChris Mason /* wait for a transaction commit to be fully complete */
7912ff7e61eSJeff Mahoney static noinline void wait_for_commit(struct btrfs_transaction *commit)
79289ce8a63SChris Mason {
7934a9d8bdeSMiao Xie 	wait_event(commit->commit_wait, commit->state == TRANS_STATE_COMPLETED);
79489ce8a63SChris Mason }
79589ce8a63SChris Mason 
7962ff7e61eSJeff Mahoney int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
79746204592SSage Weil {
79846204592SSage Weil 	struct btrfs_transaction *cur_trans = NULL, *t;
7998cd2807fSMiao Xie 	int ret = 0;
80046204592SSage Weil 
80146204592SSage Weil 	if (transid) {
8020b246afaSJeff Mahoney 		if (transid <= fs_info->last_trans_committed)
803a4abeea4SJosef Bacik 			goto out;
80446204592SSage Weil 
80546204592SSage Weil 		/* find specified transaction */
8060b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
8070b246afaSJeff Mahoney 		list_for_each_entry(t, &fs_info->trans_list, list) {
80846204592SSage Weil 			if (t->transid == transid) {
80946204592SSage Weil 				cur_trans = t;
8109b64f57dSElena Reshetova 				refcount_inc(&cur_trans->use_count);
8118cd2807fSMiao Xie 				ret = 0;
81246204592SSage Weil 				break;
81346204592SSage Weil 			}
8148cd2807fSMiao Xie 			if (t->transid > transid) {
8158cd2807fSMiao Xie 				ret = 0;
81646204592SSage Weil 				break;
81746204592SSage Weil 			}
8188cd2807fSMiao Xie 		}
8190b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
82042383020SSage Weil 
82142383020SSage Weil 		/*
82242383020SSage Weil 		 * The specified transaction doesn't exist, or we
82342383020SSage Weil 		 * raced with btrfs_commit_transaction
82442383020SSage Weil 		 */
82542383020SSage Weil 		if (!cur_trans) {
8260b246afaSJeff Mahoney 			if (transid > fs_info->last_trans_committed)
82742383020SSage Weil 				ret = -EINVAL;
8288cd2807fSMiao Xie 			goto out;
82942383020SSage Weil 		}
83046204592SSage Weil 	} else {
83146204592SSage Weil 		/* find newest transaction that is committing | committed */
8320b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
8330b246afaSJeff Mahoney 		list_for_each_entry_reverse(t, &fs_info->trans_list,
83446204592SSage Weil 					    list) {
8354a9d8bdeSMiao Xie 			if (t->state >= TRANS_STATE_COMMIT_START) {
8364a9d8bdeSMiao Xie 				if (t->state == TRANS_STATE_COMPLETED)
8373473f3c0SJosef Bacik 					break;
83846204592SSage Weil 				cur_trans = t;
8399b64f57dSElena Reshetova 				refcount_inc(&cur_trans->use_count);
84046204592SSage Weil 				break;
84146204592SSage Weil 			}
84246204592SSage Weil 		}
8430b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
84446204592SSage Weil 		if (!cur_trans)
845a4abeea4SJosef Bacik 			goto out;  /* nothing committing|committed */
84646204592SSage Weil 	}
84746204592SSage Weil 
8482ff7e61eSJeff Mahoney 	wait_for_commit(cur_trans);
849724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
850a4abeea4SJosef Bacik out:
85146204592SSage Weil 	return ret;
85246204592SSage Weil }
85346204592SSage Weil 
8542ff7e61eSJeff Mahoney void btrfs_throttle(struct btrfs_fs_info *fs_info)
85537d1aeeeSChris Mason {
8562ff7e61eSJeff Mahoney 	wait_current_trans(fs_info);
85737d1aeeeSChris Mason }
85837d1aeeeSChris Mason 
8592ff7e61eSJeff Mahoney static int should_end_transaction(struct btrfs_trans_handle *trans)
8608929ecfaSYan, Zheng {
8612ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = trans->fs_info;
8620b246afaSJeff Mahoney 
86364403612SJosef Bacik 	if (btrfs_check_space_for_delayed_refs(fs_info))
8641be41b78SJosef Bacik 		return 1;
86536ba022aSJosef Bacik 
8662ff7e61eSJeff Mahoney 	return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
8678929ecfaSYan, Zheng }
8688929ecfaSYan, Zheng 
8693a45bb20SJeff Mahoney int btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
8708929ecfaSYan, Zheng {
8718929ecfaSYan, Zheng 	struct btrfs_transaction *cur_trans = trans->transaction;
8728929ecfaSYan, Zheng 
873a4abeea4SJosef Bacik 	smp_mb();
8743296bf56SQu Wenruo 	if (cur_trans->state >= TRANS_STATE_COMMIT_START ||
8754a9d8bdeSMiao Xie 	    cur_trans->delayed_refs.flushing)
8768929ecfaSYan, Zheng 		return 1;
8778929ecfaSYan, Zheng 
8782ff7e61eSJeff Mahoney 	return should_end_transaction(trans);
8798929ecfaSYan, Zheng }
8808929ecfaSYan, Zheng 
881dc60c525SNikolay Borisov static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
882dc60c525SNikolay Borisov 
8830e34693fSNikolay Borisov {
884dc60c525SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
885dc60c525SNikolay Borisov 
8860e34693fSNikolay Borisov 	if (!trans->block_rsv) {
8870e34693fSNikolay Borisov 		ASSERT(!trans->bytes_reserved);
8880e34693fSNikolay Borisov 		return;
8890e34693fSNikolay Borisov 	}
8900e34693fSNikolay Borisov 
8910e34693fSNikolay Borisov 	if (!trans->bytes_reserved)
8920e34693fSNikolay Borisov 		return;
8930e34693fSNikolay Borisov 
8940e34693fSNikolay Borisov 	ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
8950e34693fSNikolay Borisov 	trace_btrfs_space_reservation(fs_info, "transaction",
8960e34693fSNikolay Borisov 				      trans->transid, trans->bytes_reserved, 0);
8970e34693fSNikolay Borisov 	btrfs_block_rsv_release(fs_info, trans->block_rsv,
89863f018beSNikolay Borisov 				trans->bytes_reserved, NULL);
8990e34693fSNikolay Borisov 	trans->bytes_reserved = 0;
9000e34693fSNikolay Borisov }
9010e34693fSNikolay Borisov 
90289ce8a63SChris Mason static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
9033a45bb20SJeff Mahoney 				   int throttle)
90479154b1bSChris Mason {
9053a45bb20SJeff Mahoney 	struct btrfs_fs_info *info = trans->fs_info;
9068929ecfaSYan, Zheng 	struct btrfs_transaction *cur_trans = trans->transaction;
9074edc2ca3SDave Jones 	int err = 0;
908d6e4a428SChris Mason 
909b50fff81SDavid Sterba 	if (refcount_read(&trans->use_count) > 1) {
910b50fff81SDavid Sterba 		refcount_dec(&trans->use_count);
9112a1eb461SJosef Bacik 		trans->block_rsv = trans->orig_rsv;
9122a1eb461SJosef Bacik 		return 0;
9132a1eb461SJosef Bacik 	}
9142a1eb461SJosef Bacik 
915dc60c525SNikolay Borisov 	btrfs_trans_release_metadata(trans);
9164c13d758SJosef Bacik 	trans->block_rsv = NULL;
917c5567237SArne Jansen 
9186c686b35SNikolay Borisov 	btrfs_create_pending_block_groups(trans);
919ea658badSJosef Bacik 
9204fbcdf66SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
9214fbcdf66SFilipe Manana 
9220860adfdSMiao Xie 	if (trans->type & __TRANS_FREEZABLE)
9230b246afaSJeff Mahoney 		sb_end_intwrite(info->sb);
9246df7881aSJosef Bacik 
9258929ecfaSYan, Zheng 	WARN_ON(cur_trans != info->running_transaction);
92613c5a93eSJosef Bacik 	WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
92713c5a93eSJosef Bacik 	atomic_dec(&cur_trans->num_writers);
9280860adfdSMiao Xie 	extwriter_counter_dec(cur_trans, trans->type);
92989ce8a63SChris Mason 
930093258e6SDavid Sterba 	cond_wake_up(&cur_trans->writer_wait);
931724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
9329ed74f2dSJosef Bacik 
9339ed74f2dSJosef Bacik 	if (current->journal_info == trans)
9349ed74f2dSJosef Bacik 		current->journal_info = NULL;
935ab78c84dSChris Mason 
93624bbcf04SYan, Zheng 	if (throttle)
9372ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(info);
93824bbcf04SYan, Zheng 
939bf31f87fSDavid Sterba 	if (TRANS_ABORTED(trans) ||
9400b246afaSJeff Mahoney 	    test_bit(BTRFS_FS_STATE_ERROR, &info->fs_state)) {
9414e121c06SJosef Bacik 		wake_up_process(info->transaction_kthread);
942fbabd4a3SJosef Bacik 		if (TRANS_ABORTED(trans))
943fbabd4a3SJosef Bacik 			err = trans->aborted;
944fbabd4a3SJosef Bacik 		else
945fbabd4a3SJosef Bacik 			err = -EROFS;
9464e121c06SJosef Bacik 	}
94749b25e05SJeff Mahoney 
9484edc2ca3SDave Jones 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
9494edc2ca3SDave Jones 	return err;
95079154b1bSChris Mason }
95179154b1bSChris Mason 
9523a45bb20SJeff Mahoney int btrfs_end_transaction(struct btrfs_trans_handle *trans)
95389ce8a63SChris Mason {
9543a45bb20SJeff Mahoney 	return __btrfs_end_transaction(trans, 0);
95589ce8a63SChris Mason }
95689ce8a63SChris Mason 
9573a45bb20SJeff Mahoney int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
95889ce8a63SChris Mason {
9593a45bb20SJeff Mahoney 	return __btrfs_end_transaction(trans, 1);
96016cdcec7SMiao Xie }
96116cdcec7SMiao Xie 
962d352ac68SChris Mason /*
963d352ac68SChris Mason  * when btree blocks are allocated, they have some corresponding bits set for
964d352ac68SChris Mason  * them in one of two extent_io trees.  This is used to make sure all of
965690587d1SChris Mason  * those extents are sent to disk but does not wait on them
966d352ac68SChris Mason  */
9672ff7e61eSJeff Mahoney int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
9688cef4e16SYan, Zheng 			       struct extent_io_tree *dirty_pages, int mark)
96979154b1bSChris Mason {
970777e6bd7SChris Mason 	int err = 0;
9717c4452b9SChris Mason 	int werr = 0;
9720b246afaSJeff Mahoney 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
973e6138876SJosef Bacik 	struct extent_state *cached_state = NULL;
974777e6bd7SChris Mason 	u64 start = 0;
9755f39d397SChris Mason 	u64 end;
9767c4452b9SChris Mason 
9776300463bSLiu Bo 	atomic_inc(&BTRFS_I(fs_info->btree_inode)->sync_writers);
9781728366eSJosef Bacik 	while (!find_first_extent_bit(dirty_pages, start, &start, &end,
979e6138876SJosef Bacik 				      mark, &cached_state)) {
980663dfbb0SFilipe Manana 		bool wait_writeback = false;
981663dfbb0SFilipe Manana 
982663dfbb0SFilipe Manana 		err = convert_extent_bit(dirty_pages, start, end,
983663dfbb0SFilipe Manana 					 EXTENT_NEED_WAIT,
984210aa277SDavid Sterba 					 mark, &cached_state);
985663dfbb0SFilipe Manana 		/*
986663dfbb0SFilipe Manana 		 * convert_extent_bit can return -ENOMEM, which is most of the
987663dfbb0SFilipe Manana 		 * time a temporary error. So when it happens, ignore the error
988663dfbb0SFilipe Manana 		 * and wait for writeback of this range to finish - because we
989663dfbb0SFilipe Manana 		 * failed to set the bit EXTENT_NEED_WAIT for the range, a call
990bf89d38fSJeff Mahoney 		 * to __btrfs_wait_marked_extents() would not know that
991bf89d38fSJeff Mahoney 		 * writeback for this range started and therefore wouldn't
992bf89d38fSJeff Mahoney 		 * wait for it to finish - we don't want to commit a
993bf89d38fSJeff Mahoney 		 * superblock that points to btree nodes/leafs for which
994bf89d38fSJeff Mahoney 		 * writeback hasn't finished yet (and without errors).
995663dfbb0SFilipe Manana 		 * We cleanup any entries left in the io tree when committing
99641e7acd3SNikolay Borisov 		 * the transaction (through extent_io_tree_release()).
997663dfbb0SFilipe Manana 		 */
998663dfbb0SFilipe Manana 		if (err == -ENOMEM) {
999663dfbb0SFilipe Manana 			err = 0;
1000663dfbb0SFilipe Manana 			wait_writeback = true;
1001663dfbb0SFilipe Manana 		}
1002663dfbb0SFilipe Manana 		if (!err)
10031728366eSJosef Bacik 			err = filemap_fdatawrite_range(mapping, start, end);
10047c4452b9SChris Mason 		if (err)
10057c4452b9SChris Mason 			werr = err;
1006663dfbb0SFilipe Manana 		else if (wait_writeback)
1007663dfbb0SFilipe Manana 			werr = filemap_fdatawait_range(mapping, start, end);
1008e38e2ed7SFilipe Manana 		free_extent_state(cached_state);
1009663dfbb0SFilipe Manana 		cached_state = NULL;
10101728366eSJosef Bacik 		cond_resched();
10111728366eSJosef Bacik 		start = end + 1;
10127c4452b9SChris Mason 	}
10136300463bSLiu Bo 	atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
1014690587d1SChris Mason 	return werr;
1015690587d1SChris Mason }
1016690587d1SChris Mason 
1017690587d1SChris Mason /*
1018690587d1SChris Mason  * when btree blocks are allocated, they have some corresponding bits set for
1019690587d1SChris Mason  * them in one of two extent_io trees.  This is used to make sure all of
1020690587d1SChris Mason  * those extents are on disk for transaction or log commit.  We wait
1021690587d1SChris Mason  * on all the pages and clear them from the dirty pages state tree
1022690587d1SChris Mason  */
1023bf89d38fSJeff Mahoney static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
1024bf89d38fSJeff Mahoney 				       struct extent_io_tree *dirty_pages)
1025690587d1SChris Mason {
1026690587d1SChris Mason 	int err = 0;
1027690587d1SChris Mason 	int werr = 0;
10280b246afaSJeff Mahoney 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
1029e6138876SJosef Bacik 	struct extent_state *cached_state = NULL;
1030690587d1SChris Mason 	u64 start = 0;
1031690587d1SChris Mason 	u64 end;
1032690587d1SChris Mason 
10331728366eSJosef Bacik 	while (!find_first_extent_bit(dirty_pages, start, &start, &end,
1034e6138876SJosef Bacik 				      EXTENT_NEED_WAIT, &cached_state)) {
1035663dfbb0SFilipe Manana 		/*
1036663dfbb0SFilipe Manana 		 * Ignore -ENOMEM errors returned by clear_extent_bit().
1037663dfbb0SFilipe Manana 		 * When committing the transaction, we'll remove any entries
1038663dfbb0SFilipe Manana 		 * left in the io tree. For a log commit, we don't remove them
1039663dfbb0SFilipe Manana 		 * after committing the log because the tree can be accessed
1040663dfbb0SFilipe Manana 		 * concurrently - we do it only at transaction commit time when
104141e7acd3SNikolay Borisov 		 * it's safe to do it (through extent_io_tree_release()).
1042663dfbb0SFilipe Manana 		 */
1043663dfbb0SFilipe Manana 		err = clear_extent_bit(dirty_pages, start, end,
1044ae0f1625SDavid Sterba 				       EXTENT_NEED_WAIT, 0, 0, &cached_state);
1045663dfbb0SFilipe Manana 		if (err == -ENOMEM)
1046663dfbb0SFilipe Manana 			err = 0;
1047663dfbb0SFilipe Manana 		if (!err)
10481728366eSJosef Bacik 			err = filemap_fdatawait_range(mapping, start, end);
1049777e6bd7SChris Mason 		if (err)
1050777e6bd7SChris Mason 			werr = err;
1051e38e2ed7SFilipe Manana 		free_extent_state(cached_state);
1052e38e2ed7SFilipe Manana 		cached_state = NULL;
1053777e6bd7SChris Mason 		cond_resched();
10541728366eSJosef Bacik 		start = end + 1;
1055777e6bd7SChris Mason 	}
10567c4452b9SChris Mason 	if (err)
10577c4452b9SChris Mason 		werr = err;
1058bf89d38fSJeff Mahoney 	return werr;
1059bf89d38fSJeff Mahoney }
1060656f30dbSFilipe Manana 
1061b9fae2ebSFilipe Manana static int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1062bf89d38fSJeff Mahoney 		       struct extent_io_tree *dirty_pages)
1063bf89d38fSJeff Mahoney {
1064bf89d38fSJeff Mahoney 	bool errors = false;
1065bf89d38fSJeff Mahoney 	int err;
1066bf89d38fSJeff Mahoney 
1067bf89d38fSJeff Mahoney 	err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1068bf89d38fSJeff Mahoney 	if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1069bf89d38fSJeff Mahoney 		errors = true;
1070bf89d38fSJeff Mahoney 
1071bf89d38fSJeff Mahoney 	if (errors && !err)
1072bf89d38fSJeff Mahoney 		err = -EIO;
1073bf89d38fSJeff Mahoney 	return err;
1074bf89d38fSJeff Mahoney }
1075bf89d38fSJeff Mahoney 
1076bf89d38fSJeff Mahoney int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1077bf89d38fSJeff Mahoney {
1078bf89d38fSJeff Mahoney 	struct btrfs_fs_info *fs_info = log_root->fs_info;
1079bf89d38fSJeff Mahoney 	struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1080bf89d38fSJeff Mahoney 	bool errors = false;
1081bf89d38fSJeff Mahoney 	int err;
1082bf89d38fSJeff Mahoney 
1083bf89d38fSJeff Mahoney 	ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1084bf89d38fSJeff Mahoney 
1085bf89d38fSJeff Mahoney 	err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1086656f30dbSFilipe Manana 	if ((mark & EXTENT_DIRTY) &&
10870b246afaSJeff Mahoney 	    test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1088656f30dbSFilipe Manana 		errors = true;
1089656f30dbSFilipe Manana 
1090656f30dbSFilipe Manana 	if ((mark & EXTENT_NEW) &&
10910b246afaSJeff Mahoney 	    test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1092656f30dbSFilipe Manana 		errors = true;
1093656f30dbSFilipe Manana 
1094bf89d38fSJeff Mahoney 	if (errors && !err)
1095bf89d38fSJeff Mahoney 		err = -EIO;
1096bf89d38fSJeff Mahoney 	return err;
109779154b1bSChris Mason }
109879154b1bSChris Mason 
1099690587d1SChris Mason /*
1100c9b577c0SNikolay Borisov  * When btree blocks are allocated the corresponding extents are marked dirty.
1101c9b577c0SNikolay Borisov  * This function ensures such extents are persisted on disk for transaction or
1102c9b577c0SNikolay Borisov  * log commit.
1103c9b577c0SNikolay Borisov  *
1104c9b577c0SNikolay Borisov  * @trans: transaction whose dirty pages we'd like to write
1105690587d1SChris Mason  */
110670458a58SNikolay Borisov static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1107d0c803c4SChris Mason {
1108663dfbb0SFilipe Manana 	int ret;
1109c9b577c0SNikolay Borisov 	int ret2;
1110c9b577c0SNikolay Borisov 	struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
111170458a58SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
1112c9b577c0SNikolay Borisov 	struct blk_plug plug;
1113663dfbb0SFilipe Manana 
1114c9b577c0SNikolay Borisov 	blk_start_plug(&plug);
1115c9b577c0SNikolay Borisov 	ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1116c9b577c0SNikolay Borisov 	blk_finish_plug(&plug);
1117c9b577c0SNikolay Borisov 	ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1118c9b577c0SNikolay Borisov 
111941e7acd3SNikolay Borisov 	extent_io_tree_release(&trans->transaction->dirty_pages);
1120663dfbb0SFilipe Manana 
1121c9b577c0SNikolay Borisov 	if (ret)
1122663dfbb0SFilipe Manana 		return ret;
1123c9b577c0SNikolay Borisov 	else if (ret2)
1124c9b577c0SNikolay Borisov 		return ret2;
1125c9b577c0SNikolay Borisov 	else
1126c9b577c0SNikolay Borisov 		return 0;
1127d0c803c4SChris Mason }
1128d0c803c4SChris Mason 
1129d352ac68SChris Mason /*
1130d352ac68SChris Mason  * this is used to update the root pointer in the tree of tree roots.
1131d352ac68SChris Mason  *
1132d352ac68SChris Mason  * But, in the case of the extent allocation tree, updating the root
1133d352ac68SChris Mason  * pointer may allocate blocks which may change the root of the extent
1134d352ac68SChris Mason  * allocation tree.
1135d352ac68SChris Mason  *
1136d352ac68SChris Mason  * So, this loops and repeats and makes sure the cowonly root didn't
1137d352ac68SChris Mason  * change while the root pointer was being updated in the metadata.
1138d352ac68SChris Mason  */
11390b86a832SChris Mason static int update_cowonly_root(struct btrfs_trans_handle *trans,
114079154b1bSChris Mason 			       struct btrfs_root *root)
114179154b1bSChris Mason {
114279154b1bSChris Mason 	int ret;
11430b86a832SChris Mason 	u64 old_root_bytenr;
114486b9f2ecSYan, Zheng 	u64 old_root_used;
11450b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11460b246afaSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
114779154b1bSChris Mason 
114886b9f2ecSYan, Zheng 	old_root_used = btrfs_root_used(&root->root_item);
114956bec294SChris Mason 
115079154b1bSChris Mason 	while (1) {
11510b86a832SChris Mason 		old_root_bytenr = btrfs_root_bytenr(&root->root_item);
115286b9f2ecSYan, Zheng 		if (old_root_bytenr == root->node->start &&
1153ea526d18SJosef Bacik 		    old_root_used == btrfs_root_used(&root->root_item))
115479154b1bSChris Mason 			break;
115587ef2bb4SChris Mason 
11565d4f98a2SYan Zheng 		btrfs_set_root_node(&root->root_item, root->node);
115779154b1bSChris Mason 		ret = btrfs_update_root(trans, tree_root,
11580b86a832SChris Mason 					&root->root_key,
11590b86a832SChris Mason 					&root->root_item);
116049b25e05SJeff Mahoney 		if (ret)
116149b25e05SJeff Mahoney 			return ret;
116256bec294SChris Mason 
116386b9f2ecSYan, Zheng 		old_root_used = btrfs_root_used(&root->root_item);
1164e7070be1SJosef Bacik 	}
1165276e680dSYan Zheng 
11660b86a832SChris Mason 	return 0;
11670b86a832SChris Mason }
11680b86a832SChris Mason 
1169d352ac68SChris Mason /*
1170d352ac68SChris Mason  * update all the cowonly tree roots on disk
117149b25e05SJeff Mahoney  *
117249b25e05SJeff Mahoney  * The error handling in this function may not be obvious. Any of the
117349b25e05SJeff Mahoney  * failures will cause the file system to go offline. We still need
117449b25e05SJeff Mahoney  * to clean up the delayed refs.
1175d352ac68SChris Mason  */
11769386d8bcSNikolay Borisov static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
11770b86a832SChris Mason {
11789386d8bcSNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
1179ea526d18SJosef Bacik 	struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
11801bbc621eSChris Mason 	struct list_head *io_bgs = &trans->transaction->io_bgs;
11810b86a832SChris Mason 	struct list_head *next;
118284234f3aSYan Zheng 	struct extent_buffer *eb;
118356bec294SChris Mason 	int ret;
118484234f3aSYan Zheng 
118584234f3aSYan Zheng 	eb = btrfs_lock_root_node(fs_info->tree_root);
118649b25e05SJeff Mahoney 	ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
11879631e4ccSJosef Bacik 			      0, &eb, BTRFS_NESTING_COW);
118884234f3aSYan Zheng 	btrfs_tree_unlock(eb);
118984234f3aSYan Zheng 	free_extent_buffer(eb);
11900b86a832SChris Mason 
119149b25e05SJeff Mahoney 	if (ret)
119249b25e05SJeff Mahoney 		return ret;
119349b25e05SJeff Mahoney 
1194c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
119549b25e05SJeff Mahoney 	if (ret)
119649b25e05SJeff Mahoney 		return ret;
119787ef2bb4SChris Mason 
1198196c9d8dSDavid Sterba 	ret = btrfs_run_dev_stats(trans);
1199c16ce190SJosef Bacik 	if (ret)
1200c16ce190SJosef Bacik 		return ret;
12012b584c68SDavid Sterba 	ret = btrfs_run_dev_replace(trans);
1202c16ce190SJosef Bacik 	if (ret)
1203c16ce190SJosef Bacik 		return ret;
1204280f8bd2SLu Fengqi 	ret = btrfs_run_qgroups(trans);
1205c16ce190SJosef Bacik 	if (ret)
1206c16ce190SJosef Bacik 		return ret;
1207546adb0dSJan Schmidt 
1208bbebb3e0SDavid Sterba 	ret = btrfs_setup_space_cache(trans);
1209dcdf7f6dSJosef Bacik 	if (ret)
1210dcdf7f6dSJosef Bacik 		return ret;
1211dcdf7f6dSJosef Bacik 
1212546adb0dSJan Schmidt 	/* run_qgroups might have added some more refs */
1213c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1214c16ce190SJosef Bacik 	if (ret)
1215c16ce190SJosef Bacik 		return ret;
1216ea526d18SJosef Bacik again:
12170b86a832SChris Mason 	while (!list_empty(&fs_info->dirty_cowonly_roots)) {
12182ff7e61eSJeff Mahoney 		struct btrfs_root *root;
12190b86a832SChris Mason 		next = fs_info->dirty_cowonly_roots.next;
12200b86a832SChris Mason 		list_del_init(next);
12210b86a832SChris Mason 		root = list_entry(next, struct btrfs_root, dirty_list);
1222e7070be1SJosef Bacik 		clear_bit(BTRFS_ROOT_DIRTY, &root->state);
122387ef2bb4SChris Mason 
12249e351cc8SJosef Bacik 		if (root != fs_info->extent_root)
12259e351cc8SJosef Bacik 			list_add_tail(&root->dirty_list,
12269e351cc8SJosef Bacik 				      &trans->transaction->switch_commits);
122749b25e05SJeff Mahoney 		ret = update_cowonly_root(trans, root);
122849b25e05SJeff Mahoney 		if (ret)
122949b25e05SJeff Mahoney 			return ret;
1230c79a70b1SNikolay Borisov 		ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1231ea526d18SJosef Bacik 		if (ret)
1232ea526d18SJosef Bacik 			return ret;
123379154b1bSChris Mason 	}
1234276e680dSYan Zheng 
12351bbc621eSChris Mason 	while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
12365742d15fSDavid Sterba 		ret = btrfs_write_dirty_block_groups(trans);
1237ea526d18SJosef Bacik 		if (ret)
1238ea526d18SJosef Bacik 			return ret;
1239c79a70b1SNikolay Borisov 		ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1240ea526d18SJosef Bacik 		if (ret)
1241ea526d18SJosef Bacik 			return ret;
1242ea526d18SJosef Bacik 	}
1243ea526d18SJosef Bacik 
1244ea526d18SJosef Bacik 	if (!list_empty(&fs_info->dirty_cowonly_roots))
1245ea526d18SJosef Bacik 		goto again;
1246ea526d18SJosef Bacik 
12479e351cc8SJosef Bacik 	list_add_tail(&fs_info->extent_root->dirty_list,
12489e351cc8SJosef Bacik 		      &trans->transaction->switch_commits);
12499f6cbcbbSDavid Sterba 
12509f6cbcbbSDavid Sterba 	/* Update dev-replace pointer once everything is committed */
12519f6cbcbbSDavid Sterba 	fs_info->dev_replace.committed_cursor_left =
12529f6cbcbbSDavid Sterba 		fs_info->dev_replace.cursor_left_last_write_of_item;
12538dabb742SStefan Behrens 
125479154b1bSChris Mason 	return 0;
125579154b1bSChris Mason }
125679154b1bSChris Mason 
1257d352ac68SChris Mason /*
1258d352ac68SChris Mason  * dead roots are old snapshots that need to be deleted.  This allocates
1259d352ac68SChris Mason  * a dirty root struct and adds it into the list of dead roots that need to
1260d352ac68SChris Mason  * be deleted
1261d352ac68SChris Mason  */
1262cfad392bSJosef Bacik void btrfs_add_dead_root(struct btrfs_root *root)
12635eda7b5eSChris Mason {
12640b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12650b246afaSJeff Mahoney 
12660b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
1267dc9492c1SJosef Bacik 	if (list_empty(&root->root_list)) {
1268dc9492c1SJosef Bacik 		btrfs_grab_root(root);
12690b246afaSJeff Mahoney 		list_add_tail(&root->root_list, &fs_info->dead_roots);
1270dc9492c1SJosef Bacik 	}
12710b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
12725eda7b5eSChris Mason }
12735eda7b5eSChris Mason 
1274d352ac68SChris Mason /*
12755d4f98a2SYan Zheng  * update all the cowonly tree roots on disk
1276d352ac68SChris Mason  */
12777e4443d9SNikolay Borisov static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
12780f7d52f4SChris Mason {
12797e4443d9SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
12800f7d52f4SChris Mason 	struct btrfs_root *gang[8];
12810f7d52f4SChris Mason 	int i;
12820f7d52f4SChris Mason 	int ret;
128354aa1f4dSChris Mason 	int err = 0;
128454aa1f4dSChris Mason 
1285a4abeea4SJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
12860f7d52f4SChris Mason 	while (1) {
12875d4f98a2SYan Zheng 		ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
12885d4f98a2SYan Zheng 						 (void **)gang, 0,
12890f7d52f4SChris Mason 						 ARRAY_SIZE(gang),
12900f7d52f4SChris Mason 						 BTRFS_ROOT_TRANS_TAG);
12910f7d52f4SChris Mason 		if (ret == 0)
12920f7d52f4SChris Mason 			break;
12930f7d52f4SChris Mason 		for (i = 0; i < ret; i++) {
12945b4aacefSJeff Mahoney 			struct btrfs_root *root = gang[i];
12955d4f98a2SYan Zheng 			radix_tree_tag_clear(&fs_info->fs_roots_radix,
12962619ba1fSChris Mason 					(unsigned long)root->root_key.objectid,
12970f7d52f4SChris Mason 					BTRFS_ROOT_TRANS_TAG);
1298a4abeea4SJosef Bacik 			spin_unlock(&fs_info->fs_roots_radix_lock);
129931153d81SYan Zheng 
1300e02119d5SChris Mason 			btrfs_free_log(trans, root);
13015d4f98a2SYan Zheng 			btrfs_update_reloc_root(trans, root);
1302e02119d5SChris Mason 
130382d5902dSLi Zefan 			btrfs_save_ino_cache(root, trans);
130482d5902dSLi Zefan 
1305f1ebcc74SLiu Bo 			/* see comments in should_cow_block() */
130627cdeb70SMiao Xie 			clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1307c7548af6SChris Mason 			smp_mb__after_atomic();
1308f1ebcc74SLiu Bo 
1309978d910dSYan Zheng 			if (root->commit_root != root->node) {
13109e351cc8SJosef Bacik 				list_add_tail(&root->dirty_list,
13119e351cc8SJosef Bacik 					&trans->transaction->switch_commits);
1312978d910dSYan Zheng 				btrfs_set_root_node(&root->root_item,
1313978d910dSYan Zheng 						    root->node);
1314978d910dSYan Zheng 			}
131531153d81SYan Zheng 
13165d4f98a2SYan Zheng 			err = btrfs_update_root(trans, fs_info->tree_root,
13170f7d52f4SChris Mason 						&root->root_key,
13180f7d52f4SChris Mason 						&root->root_item);
1319a4abeea4SJosef Bacik 			spin_lock(&fs_info->fs_roots_radix_lock);
132054aa1f4dSChris Mason 			if (err)
132154aa1f4dSChris Mason 				break;
1322733e03a0SQu Wenruo 			btrfs_qgroup_free_meta_all_pertrans(root);
13230f7d52f4SChris Mason 		}
13249f3a7427SChris Mason 	}
1325a4abeea4SJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
132654aa1f4dSChris Mason 	return err;
13270f7d52f4SChris Mason }
13280f7d52f4SChris Mason 
1329d352ac68SChris Mason /*
1330de78b51aSEric Sandeen  * defrag a given btree.
1331de78b51aSEric Sandeen  * Every leaf in the btree is read and defragged.
1332d352ac68SChris Mason  */
1333de78b51aSEric Sandeen int btrfs_defrag_root(struct btrfs_root *root)
1334e9d0b13bSChris Mason {
1335e9d0b13bSChris Mason 	struct btrfs_fs_info *info = root->fs_info;
1336e9d0b13bSChris Mason 	struct btrfs_trans_handle *trans;
13378929ecfaSYan, Zheng 	int ret;
1338e9d0b13bSChris Mason 
133927cdeb70SMiao Xie 	if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1340e9d0b13bSChris Mason 		return 0;
13418929ecfaSYan, Zheng 
13426b80053dSChris Mason 	while (1) {
13438929ecfaSYan, Zheng 		trans = btrfs_start_transaction(root, 0);
13448929ecfaSYan, Zheng 		if (IS_ERR(trans))
13458929ecfaSYan, Zheng 			return PTR_ERR(trans);
13468929ecfaSYan, Zheng 
1347de78b51aSEric Sandeen 		ret = btrfs_defrag_leaves(trans, root);
13488929ecfaSYan, Zheng 
13493a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
13502ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(info);
1351e9d0b13bSChris Mason 		cond_resched();
1352e9d0b13bSChris Mason 
1353ab8d0fc4SJeff Mahoney 		if (btrfs_fs_closing(info) || ret != -EAGAIN)
1354e9d0b13bSChris Mason 			break;
1355210549ebSDavid Sterba 
1356ab8d0fc4SJeff Mahoney 		if (btrfs_defrag_cancelled(info)) {
1357ab8d0fc4SJeff Mahoney 			btrfs_debug(info, "defrag_root cancelled");
1358210549ebSDavid Sterba 			ret = -EAGAIN;
1359210549ebSDavid Sterba 			break;
1360210549ebSDavid Sterba 		}
1361e9d0b13bSChris Mason 	}
136227cdeb70SMiao Xie 	clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
13638929ecfaSYan, Zheng 	return ret;
1364e9d0b13bSChris Mason }
1365e9d0b13bSChris Mason 
1366d352ac68SChris Mason /*
13676426c7adSQu Wenruo  * Do all special snapshot related qgroup dirty hack.
13686426c7adSQu Wenruo  *
13696426c7adSQu Wenruo  * Will do all needed qgroup inherit and dirty hack like switch commit
13706426c7adSQu Wenruo  * roots inside one transaction and write all btree into disk, to make
13716426c7adSQu Wenruo  * qgroup works.
13726426c7adSQu Wenruo  */
13736426c7adSQu Wenruo static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
13746426c7adSQu Wenruo 				   struct btrfs_root *src,
13756426c7adSQu Wenruo 				   struct btrfs_root *parent,
13766426c7adSQu Wenruo 				   struct btrfs_qgroup_inherit *inherit,
13776426c7adSQu Wenruo 				   u64 dst_objectid)
13786426c7adSQu Wenruo {
13796426c7adSQu Wenruo 	struct btrfs_fs_info *fs_info = src->fs_info;
13806426c7adSQu Wenruo 	int ret;
13816426c7adSQu Wenruo 
13826426c7adSQu Wenruo 	/*
13836426c7adSQu Wenruo 	 * Save some performance in the case that qgroups are not
13846426c7adSQu Wenruo 	 * enabled. If this check races with the ioctl, rescan will
13856426c7adSQu Wenruo 	 * kick in anyway.
13866426c7adSQu Wenruo 	 */
13879ea6e2b5SDavid Sterba 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
13886426c7adSQu Wenruo 		return 0;
13896426c7adSQu Wenruo 
13906426c7adSQu Wenruo 	/*
139152042d8eSAndrea Gelmini 	 * Ensure dirty @src will be committed.  Or, after coming
13924d31778aSQu Wenruo 	 * commit_fs_roots() and switch_commit_roots(), any dirty but not
13934d31778aSQu Wenruo 	 * recorded root will never be updated again, causing an outdated root
13944d31778aSQu Wenruo 	 * item.
13954d31778aSQu Wenruo 	 */
13964d31778aSQu Wenruo 	record_root_in_trans(trans, src, 1);
13974d31778aSQu Wenruo 
13984d31778aSQu Wenruo 	/*
13996426c7adSQu Wenruo 	 * We are going to commit transaction, see btrfs_commit_transaction()
14006426c7adSQu Wenruo 	 * comment for reason locking tree_log_mutex
14016426c7adSQu Wenruo 	 */
14026426c7adSQu Wenruo 	mutex_lock(&fs_info->tree_log_mutex);
14036426c7adSQu Wenruo 
14047e4443d9SNikolay Borisov 	ret = commit_fs_roots(trans);
14056426c7adSQu Wenruo 	if (ret)
14066426c7adSQu Wenruo 		goto out;
1407460fb20aSNikolay Borisov 	ret = btrfs_qgroup_account_extents(trans);
14086426c7adSQu Wenruo 	if (ret < 0)
14096426c7adSQu Wenruo 		goto out;
14106426c7adSQu Wenruo 
14116426c7adSQu Wenruo 	/* Now qgroup are all updated, we can inherit it to new qgroups */
1412a9377422SLu Fengqi 	ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
14136426c7adSQu Wenruo 				   inherit);
14146426c7adSQu Wenruo 	if (ret < 0)
14156426c7adSQu Wenruo 		goto out;
14166426c7adSQu Wenruo 
14176426c7adSQu Wenruo 	/*
14186426c7adSQu Wenruo 	 * Now we do a simplified commit transaction, which will:
14196426c7adSQu Wenruo 	 * 1) commit all subvolume and extent tree
14206426c7adSQu Wenruo 	 *    To ensure all subvolume and extent tree have a valid
14216426c7adSQu Wenruo 	 *    commit_root to accounting later insert_dir_item()
14226426c7adSQu Wenruo 	 * 2) write all btree blocks onto disk
14236426c7adSQu Wenruo 	 *    This is to make sure later btree modification will be cowed
14246426c7adSQu Wenruo 	 *    Or commit_root can be populated and cause wrong qgroup numbers
14256426c7adSQu Wenruo 	 * In this simplified commit, we don't really care about other trees
14266426c7adSQu Wenruo 	 * like chunk and root tree, as they won't affect qgroup.
14276426c7adSQu Wenruo 	 * And we don't write super to avoid half committed status.
14286426c7adSQu Wenruo 	 */
14299386d8bcSNikolay Borisov 	ret = commit_cowonly_roots(trans);
14306426c7adSQu Wenruo 	if (ret)
14316426c7adSQu Wenruo 		goto out;
1432889bfa39SJosef Bacik 	switch_commit_roots(trans);
143370458a58SNikolay Borisov 	ret = btrfs_write_and_wait_transaction(trans);
14346426c7adSQu Wenruo 	if (ret)
1435f7af3934SDavid Sterba 		btrfs_handle_fs_error(fs_info, ret,
14366426c7adSQu Wenruo 			"Error while writing out transaction for qgroup");
14376426c7adSQu Wenruo 
14386426c7adSQu Wenruo out:
14396426c7adSQu Wenruo 	mutex_unlock(&fs_info->tree_log_mutex);
14406426c7adSQu Wenruo 
14416426c7adSQu Wenruo 	/*
14426426c7adSQu Wenruo 	 * Force parent root to be updated, as we recorded it before so its
14436426c7adSQu Wenruo 	 * last_trans == cur_transid.
14446426c7adSQu Wenruo 	 * Or it won't be committed again onto disk after later
14456426c7adSQu Wenruo 	 * insert_dir_item()
14466426c7adSQu Wenruo 	 */
14476426c7adSQu Wenruo 	if (!ret)
14486426c7adSQu Wenruo 		record_root_in_trans(trans, parent, 1);
14496426c7adSQu Wenruo 	return ret;
14506426c7adSQu Wenruo }
14516426c7adSQu Wenruo 
14526426c7adSQu Wenruo /*
1453d352ac68SChris Mason  * new snapshots need to be created at a very specific time in the
1454aec8030aSMiao Xie  * transaction commit.  This does the actual creation.
1455aec8030aSMiao Xie  *
1456aec8030aSMiao Xie  * Note:
1457aec8030aSMiao Xie  * If the error which may affect the commitment of the current transaction
1458aec8030aSMiao Xie  * happens, we should return the error number. If the error which just affect
1459aec8030aSMiao Xie  * the creation of the pending snapshots, just return 0.
1460d352ac68SChris Mason  */
146180b6794dSChris Mason static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
14623063d29fSChris Mason 				   struct btrfs_pending_snapshot *pending)
14633063d29fSChris Mason {
146408d50ca3SNikolay Borisov 
146508d50ca3SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
14663063d29fSChris Mason 	struct btrfs_key key;
146780b6794dSChris Mason 	struct btrfs_root_item *new_root_item;
14683063d29fSChris Mason 	struct btrfs_root *tree_root = fs_info->tree_root;
14693063d29fSChris Mason 	struct btrfs_root *root = pending->root;
14706bdb72deSSage Weil 	struct btrfs_root *parent_root;
147198c9942aSLiu Bo 	struct btrfs_block_rsv *rsv;
14726bdb72deSSage Weil 	struct inode *parent_inode;
147342874b3dSMiao Xie 	struct btrfs_path *path;
147442874b3dSMiao Xie 	struct btrfs_dir_item *dir_item;
1475a22285a6SYan, Zheng 	struct dentry *dentry;
14763063d29fSChris Mason 	struct extent_buffer *tmp;
1477925baeddSChris Mason 	struct extent_buffer *old;
147895582b00SDeepa Dinamani 	struct timespec64 cur_time;
1479aec8030aSMiao Xie 	int ret = 0;
1480d68fc57bSYan, Zheng 	u64 to_reserve = 0;
14816bdb72deSSage Weil 	u64 index = 0;
1482a22285a6SYan, Zheng 	u64 objectid;
1483b83cc969SLi Zefan 	u64 root_flags;
14843063d29fSChris Mason 
14858546b570SDavid Sterba 	ASSERT(pending->path);
14868546b570SDavid Sterba 	path = pending->path;
148742874b3dSMiao Xie 
1488b0c0ea63SDavid Sterba 	ASSERT(pending->root_item);
1489b0c0ea63SDavid Sterba 	new_root_item = pending->root_item;
1490a22285a6SYan, Zheng 
1491aec8030aSMiao Xie 	pending->error = btrfs_find_free_objectid(tree_root, &objectid);
1492aec8030aSMiao Xie 	if (pending->error)
14936fa9700eSMiao Xie 		goto no_free_objectid;
14943063d29fSChris Mason 
1495d6726335SQu Wenruo 	/*
1496d6726335SQu Wenruo 	 * Make qgroup to skip current new snapshot's qgroupid, as it is
1497d6726335SQu Wenruo 	 * accounted by later btrfs_qgroup_inherit().
1498d6726335SQu Wenruo 	 */
1499d6726335SQu Wenruo 	btrfs_set_skip_qgroup(trans, objectid);
1500d6726335SQu Wenruo 
1501147d256eSZhaolei 	btrfs_reloc_pre_snapshot(pending, &to_reserve);
1502d68fc57bSYan, Zheng 
1503d68fc57bSYan, Zheng 	if (to_reserve > 0) {
1504aec8030aSMiao Xie 		pending->error = btrfs_block_rsv_add(root,
1505aec8030aSMiao Xie 						     &pending->block_rsv,
150608e007d2SMiao Xie 						     to_reserve,
150708e007d2SMiao Xie 						     BTRFS_RESERVE_NO_FLUSH);
1508aec8030aSMiao Xie 		if (pending->error)
1509d6726335SQu Wenruo 			goto clear_skip_qgroup;
1510d68fc57bSYan, Zheng 	}
1511d68fc57bSYan, Zheng 
15123063d29fSChris Mason 	key.objectid = objectid;
1513a22285a6SYan, Zheng 	key.offset = (u64)-1;
1514a22285a6SYan, Zheng 	key.type = BTRFS_ROOT_ITEM_KEY;
15153063d29fSChris Mason 
15166fa9700eSMiao Xie 	rsv = trans->block_rsv;
1517a22285a6SYan, Zheng 	trans->block_rsv = &pending->block_rsv;
15182382c5ccSLiu Bo 	trans->bytes_reserved = trans->block_rsv->reserved;
15190b246afaSJeff Mahoney 	trace_btrfs_space_reservation(fs_info, "transaction",
152088d3a5aaSJosef Bacik 				      trans->transid,
152188d3a5aaSJosef Bacik 				      trans->bytes_reserved, 1);
1522a22285a6SYan, Zheng 	dentry = pending->dentry;
1523e9662f70SMiao Xie 	parent_inode = pending->dir;
1524a22285a6SYan, Zheng 	parent_root = BTRFS_I(parent_inode)->root;
15256426c7adSQu Wenruo 	record_root_in_trans(trans, parent_root, 0);
1526a22285a6SYan, Zheng 
1527c2050a45SDeepa Dinamani 	cur_time = current_time(parent_inode);
152804b285f3SDeepa Dinamani 
15296bdb72deSSage Weil 	/*
15306bdb72deSSage Weil 	 * insert the directory item
15316bdb72deSSage Weil 	 */
1532877574e2SNikolay Borisov 	ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
153349b25e05SJeff Mahoney 	BUG_ON(ret); /* -ENOMEM */
153442874b3dSMiao Xie 
153542874b3dSMiao Xie 	/* check if there is a file/dir which has the same name. */
153642874b3dSMiao Xie 	dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
15374a0cc7caSNikolay Borisov 					 btrfs_ino(BTRFS_I(parent_inode)),
153842874b3dSMiao Xie 					 dentry->d_name.name,
153942874b3dSMiao Xie 					 dentry->d_name.len, 0);
154042874b3dSMiao Xie 	if (dir_item != NULL && !IS_ERR(dir_item)) {
1541fe66a05aSChris Mason 		pending->error = -EEXIST;
1542aec8030aSMiao Xie 		goto dir_item_existed;
154342874b3dSMiao Xie 	} else if (IS_ERR(dir_item)) {
154442874b3dSMiao Xie 		ret = PTR_ERR(dir_item);
154566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15468732d44fSMiao Xie 		goto fail;
154779787eaaSJeff Mahoney 	}
154842874b3dSMiao Xie 	btrfs_release_path(path);
15496bdb72deSSage Weil 
1550e999376fSChris Mason 	/*
1551e999376fSChris Mason 	 * pull in the delayed directory update
1552e999376fSChris Mason 	 * and the delayed inode item
1553e999376fSChris Mason 	 * otherwise we corrupt the FS during
1554e999376fSChris Mason 	 * snapshot
1555e999376fSChris Mason 	 */
1556e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
15578732d44fSMiao Xie 	if (ret) {	/* Transaction aborted */
155866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15598732d44fSMiao Xie 		goto fail;
15608732d44fSMiao Xie 	}
1561e999376fSChris Mason 
15626426c7adSQu Wenruo 	record_root_in_trans(trans, root, 0);
15636bdb72deSSage Weil 	btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
15646bdb72deSSage Weil 	memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
156508fe4db1SLi Zefan 	btrfs_check_and_init_root_item(new_root_item);
15666bdb72deSSage Weil 
1567b83cc969SLi Zefan 	root_flags = btrfs_root_flags(new_root_item);
1568b83cc969SLi Zefan 	if (pending->readonly)
1569b83cc969SLi Zefan 		root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1570b83cc969SLi Zefan 	else
1571b83cc969SLi Zefan 		root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1572b83cc969SLi Zefan 	btrfs_set_root_flags(new_root_item, root_flags);
1573b83cc969SLi Zefan 
15748ea05e3aSAlexander Block 	btrfs_set_root_generation_v2(new_root_item,
15758ea05e3aSAlexander Block 			trans->transid);
1576807fc790SAndy Shevchenko 	generate_random_guid(new_root_item->uuid);
15778ea05e3aSAlexander Block 	memcpy(new_root_item->parent_uuid, root->root_item.uuid,
15788ea05e3aSAlexander Block 			BTRFS_UUID_SIZE);
157970023da2SStefan Behrens 	if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
158070023da2SStefan Behrens 		memset(new_root_item->received_uuid, 0,
158170023da2SStefan Behrens 		       sizeof(new_root_item->received_uuid));
15828ea05e3aSAlexander Block 		memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
15838ea05e3aSAlexander Block 		memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
15848ea05e3aSAlexander Block 		btrfs_set_root_stransid(new_root_item, 0);
15858ea05e3aSAlexander Block 		btrfs_set_root_rtransid(new_root_item, 0);
158670023da2SStefan Behrens 	}
15873cae210fSQu Wenruo 	btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
15883cae210fSQu Wenruo 	btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
158970023da2SStefan Behrens 	btrfs_set_root_otransid(new_root_item, trans->transid);
15908ea05e3aSAlexander Block 
1591925baeddSChris Mason 	old = btrfs_lock_root_node(root);
15929631e4ccSJosef Bacik 	ret = btrfs_cow_block(trans, root, old, NULL, 0, &old,
15939631e4ccSJosef Bacik 			      BTRFS_NESTING_COW);
159479787eaaSJeff Mahoney 	if (ret) {
159579787eaaSJeff Mahoney 		btrfs_tree_unlock(old);
159679787eaaSJeff Mahoney 		free_extent_buffer(old);
159766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
15988732d44fSMiao Xie 		goto fail;
159979787eaaSJeff Mahoney 	}
160049b25e05SJeff Mahoney 
16018bead258SDavid Sterba 	btrfs_set_lock_blocking_write(old);
16023063d29fSChris Mason 
160349b25e05SJeff Mahoney 	ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
160479787eaaSJeff Mahoney 	/* clean up in any case */
1605925baeddSChris Mason 	btrfs_tree_unlock(old);
1606925baeddSChris Mason 	free_extent_buffer(old);
16078732d44fSMiao Xie 	if (ret) {
160866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16098732d44fSMiao Xie 		goto fail;
16108732d44fSMiao Xie 	}
1611f1ebcc74SLiu Bo 	/* see comments in should_cow_block() */
161227cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1613f1ebcc74SLiu Bo 	smp_wmb();
1614f1ebcc74SLiu Bo 
16155d4f98a2SYan Zheng 	btrfs_set_root_node(new_root_item, tmp);
1616a22285a6SYan, Zheng 	/* record when the snapshot was created in key.offset */
1617a22285a6SYan, Zheng 	key.offset = trans->transid;
1618a22285a6SYan, Zheng 	ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1619925baeddSChris Mason 	btrfs_tree_unlock(tmp);
16203063d29fSChris Mason 	free_extent_buffer(tmp);
16218732d44fSMiao Xie 	if (ret) {
162266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16238732d44fSMiao Xie 		goto fail;
16248732d44fSMiao Xie 	}
16250660b5afSChris Mason 
1626a22285a6SYan, Zheng 	/*
1627a22285a6SYan, Zheng 	 * insert root back/forward references
1628a22285a6SYan, Zheng 	 */
16296025c19fSLu Fengqi 	ret = btrfs_add_root_ref(trans, objectid,
1630a22285a6SYan, Zheng 				 parent_root->root_key.objectid,
16314a0cc7caSNikolay Borisov 				 btrfs_ino(BTRFS_I(parent_inode)), index,
1632a22285a6SYan, Zheng 				 dentry->d_name.name, dentry->d_name.len);
16338732d44fSMiao Xie 	if (ret) {
163466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16358732d44fSMiao Xie 		goto fail;
16368732d44fSMiao Xie 	}
1637a22285a6SYan, Zheng 
1638a22285a6SYan, Zheng 	key.offset = (u64)-1;
16392dfb1e43SQu Wenruo 	pending->snap = btrfs_get_new_fs_root(fs_info, objectid, pending->anon_dev);
164079787eaaSJeff Mahoney 	if (IS_ERR(pending->snap)) {
164179787eaaSJeff Mahoney 		ret = PTR_ERR(pending->snap);
16422d892ccdSFilipe Manana 		pending->snap = NULL;
164366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16448732d44fSMiao Xie 		goto fail;
164579787eaaSJeff Mahoney 	}
1646d68fc57bSYan, Zheng 
164749b25e05SJeff Mahoney 	ret = btrfs_reloc_post_snapshot(trans, pending);
16488732d44fSMiao Xie 	if (ret) {
164966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16508732d44fSMiao Xie 		goto fail;
16518732d44fSMiao Xie 	}
1652361048f5SMiao Xie 
1653c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
16548732d44fSMiao Xie 	if (ret) {
165566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16568732d44fSMiao Xie 		goto fail;
16578732d44fSMiao Xie 	}
165842874b3dSMiao Xie 
16596426c7adSQu Wenruo 	/*
16606426c7adSQu Wenruo 	 * Do special qgroup accounting for snapshot, as we do some qgroup
16616426c7adSQu Wenruo 	 * snapshot hack to do fast snapshot.
16626426c7adSQu Wenruo 	 * To co-operate with that hack, we do hack again.
16636426c7adSQu Wenruo 	 * Or snapshot will be greatly slowed down by a subtree qgroup rescan
16646426c7adSQu Wenruo 	 */
16656426c7adSQu Wenruo 	ret = qgroup_account_snapshot(trans, root, parent_root,
16666426c7adSQu Wenruo 				      pending->inherit, objectid);
16676426c7adSQu Wenruo 	if (ret < 0)
16686426c7adSQu Wenruo 		goto fail;
16696426c7adSQu Wenruo 
1670684572dfSLu Fengqi 	ret = btrfs_insert_dir_item(trans, dentry->d_name.name,
1671684572dfSLu Fengqi 				    dentry->d_name.len, BTRFS_I(parent_inode),
1672684572dfSLu Fengqi 				    &key, BTRFS_FT_DIR, index);
167342874b3dSMiao Xie 	/* We have check then name at the beginning, so it is impossible. */
16749c52057cSChris Mason 	BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
16758732d44fSMiao Xie 	if (ret) {
167666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
16778732d44fSMiao Xie 		goto fail;
16788732d44fSMiao Xie 	}
167942874b3dSMiao Xie 
16806ef06d27SNikolay Borisov 	btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
168142874b3dSMiao Xie 					 dentry->d_name.len * 2);
168204b285f3SDeepa Dinamani 	parent_inode->i_mtime = parent_inode->i_ctime =
1683c2050a45SDeepa Dinamani 		current_time(parent_inode);
1684be6aef60SJosef Bacik 	ret = btrfs_update_inode_fallback(trans, parent_root, parent_inode);
1685dd5f9615SStefan Behrens 	if (ret) {
168666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1687dd5f9615SStefan Behrens 		goto fail;
1688dd5f9615SStefan Behrens 	}
1689807fc790SAndy Shevchenko 	ret = btrfs_uuid_tree_add(trans, new_root_item->uuid,
1690807fc790SAndy Shevchenko 				  BTRFS_UUID_KEY_SUBVOL,
1691cdb345a8SLu Fengqi 				  objectid);
1692dd5f9615SStefan Behrens 	if (ret) {
169366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1694dd5f9615SStefan Behrens 		goto fail;
1695dd5f9615SStefan Behrens 	}
1696dd5f9615SStefan Behrens 	if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1697cdb345a8SLu Fengqi 		ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1698dd5f9615SStefan Behrens 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1699dd5f9615SStefan Behrens 					  objectid);
1700dd5f9615SStefan Behrens 		if (ret && ret != -EEXIST) {
170166642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
1702dd5f9615SStefan Behrens 			goto fail;
1703dd5f9615SStefan Behrens 		}
1704dd5f9615SStefan Behrens 	}
1705d6726335SQu Wenruo 
1706c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1707d6726335SQu Wenruo 	if (ret) {
170866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1709d6726335SQu Wenruo 		goto fail;
1710d6726335SQu Wenruo 	}
1711d6726335SQu Wenruo 
17123063d29fSChris Mason fail:
1713aec8030aSMiao Xie 	pending->error = ret;
1714aec8030aSMiao Xie dir_item_existed:
171598c9942aSLiu Bo 	trans->block_rsv = rsv;
17162382c5ccSLiu Bo 	trans->bytes_reserved = 0;
1717d6726335SQu Wenruo clear_skip_qgroup:
1718d6726335SQu Wenruo 	btrfs_clear_skip_qgroup(trans);
17196fa9700eSMiao Xie no_free_objectid:
17206fa9700eSMiao Xie 	kfree(new_root_item);
1721b0c0ea63SDavid Sterba 	pending->root_item = NULL;
172242874b3dSMiao Xie 	btrfs_free_path(path);
17238546b570SDavid Sterba 	pending->path = NULL;
17248546b570SDavid Sterba 
172549b25e05SJeff Mahoney 	return ret;
17263063d29fSChris Mason }
17273063d29fSChris Mason 
1728d352ac68SChris Mason /*
1729d352ac68SChris Mason  * create all the snapshots we've scheduled for creation
1730d352ac68SChris Mason  */
173108d50ca3SNikolay Borisov static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
17323063d29fSChris Mason {
1733aec8030aSMiao Xie 	struct btrfs_pending_snapshot *pending, *next;
17343063d29fSChris Mason 	struct list_head *head = &trans->transaction->pending_snapshots;
1735aec8030aSMiao Xie 	int ret = 0;
17363de4586cSChris Mason 
1737aec8030aSMiao Xie 	list_for_each_entry_safe(pending, next, head, list) {
1738aec8030aSMiao Xie 		list_del(&pending->list);
173908d50ca3SNikolay Borisov 		ret = create_pending_snapshot(trans, pending);
1740aec8030aSMiao Xie 		if (ret)
1741aec8030aSMiao Xie 			break;
1742aec8030aSMiao Xie 	}
1743aec8030aSMiao Xie 	return ret;
17443de4586cSChris Mason }
17453de4586cSChris Mason 
17462ff7e61eSJeff Mahoney static void update_super_roots(struct btrfs_fs_info *fs_info)
17475d4f98a2SYan Zheng {
17485d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
17495d4f98a2SYan Zheng 	struct btrfs_super_block *super;
17505d4f98a2SYan Zheng 
17510b246afaSJeff Mahoney 	super = fs_info->super_copy;
17525d4f98a2SYan Zheng 
17530b246afaSJeff Mahoney 	root_item = &fs_info->chunk_root->root_item;
1754093e037cSDavid Sterba 	super->chunk_root = root_item->bytenr;
1755093e037cSDavid Sterba 	super->chunk_root_generation = root_item->generation;
1756093e037cSDavid Sterba 	super->chunk_root_level = root_item->level;
17575d4f98a2SYan Zheng 
17580b246afaSJeff Mahoney 	root_item = &fs_info->tree_root->root_item;
1759093e037cSDavid Sterba 	super->root = root_item->bytenr;
1760093e037cSDavid Sterba 	super->generation = root_item->generation;
1761093e037cSDavid Sterba 	super->root_level = root_item->level;
17620b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, SPACE_CACHE))
1763093e037cSDavid Sterba 		super->cache_generation = root_item->generation;
17640b246afaSJeff Mahoney 	if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1765093e037cSDavid Sterba 		super->uuid_tree_generation = root_item->generation;
17665d4f98a2SYan Zheng }
17675d4f98a2SYan Zheng 
1768f36f3042SChris Mason int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1769f36f3042SChris Mason {
17704a9d8bdeSMiao Xie 	struct btrfs_transaction *trans;
1771f36f3042SChris Mason 	int ret = 0;
17724a9d8bdeSMiao Xie 
1773a4abeea4SJosef Bacik 	spin_lock(&info->trans_lock);
17744a9d8bdeSMiao Xie 	trans = info->running_transaction;
17754a9d8bdeSMiao Xie 	if (trans)
17764a9d8bdeSMiao Xie 		ret = (trans->state >= TRANS_STATE_COMMIT_START);
1777a4abeea4SJosef Bacik 	spin_unlock(&info->trans_lock);
1778f36f3042SChris Mason 	return ret;
1779f36f3042SChris Mason }
1780f36f3042SChris Mason 
17818929ecfaSYan, Zheng int btrfs_transaction_blocked(struct btrfs_fs_info *info)
17828929ecfaSYan, Zheng {
17834a9d8bdeSMiao Xie 	struct btrfs_transaction *trans;
17848929ecfaSYan, Zheng 	int ret = 0;
17854a9d8bdeSMiao Xie 
1786a4abeea4SJosef Bacik 	spin_lock(&info->trans_lock);
17874a9d8bdeSMiao Xie 	trans = info->running_transaction;
17884a9d8bdeSMiao Xie 	if (trans)
17894a9d8bdeSMiao Xie 		ret = is_transaction_blocked(trans);
1790a4abeea4SJosef Bacik 	spin_unlock(&info->trans_lock);
17918929ecfaSYan, Zheng 	return ret;
17928929ecfaSYan, Zheng }
17938929ecfaSYan, Zheng 
1794bb9c12c9SSage Weil /*
1795bb9c12c9SSage Weil  * wait for the current transaction commit to start and block subsequent
1796bb9c12c9SSage Weil  * transaction joins
1797bb9c12c9SSage Weil  */
17982ff7e61eSJeff Mahoney static void wait_current_trans_commit_start(struct btrfs_fs_info *fs_info,
1799bb9c12c9SSage Weil 					    struct btrfs_transaction *trans)
1800bb9c12c9SSage Weil {
18012ff7e61eSJeff Mahoney 	wait_event(fs_info->transaction_blocked_wait,
1802bf31f87fSDavid Sterba 		   trans->state >= TRANS_STATE_COMMIT_START ||
1803bf31f87fSDavid Sterba 		   TRANS_ABORTED(trans));
1804bb9c12c9SSage Weil }
1805bb9c12c9SSage Weil 
1806bb9c12c9SSage Weil /*
1807bb9c12c9SSage Weil  * wait for the current transaction to start and then become unblocked.
1808bb9c12c9SSage Weil  * caller holds ref.
1809bb9c12c9SSage Weil  */
18102ff7e61eSJeff Mahoney static void wait_current_trans_commit_start_and_unblock(
18112ff7e61eSJeff Mahoney 					struct btrfs_fs_info *fs_info,
1812bb9c12c9SSage Weil 					struct btrfs_transaction *trans)
1813bb9c12c9SSage Weil {
18142ff7e61eSJeff Mahoney 	wait_event(fs_info->transaction_wait,
1815bf31f87fSDavid Sterba 		   trans->state >= TRANS_STATE_UNBLOCKED ||
1816bf31f87fSDavid Sterba 		   TRANS_ABORTED(trans));
1817bb9c12c9SSage Weil }
1818bb9c12c9SSage Weil 
1819bb9c12c9SSage Weil /*
1820bb9c12c9SSage Weil  * commit transactions asynchronously. once btrfs_commit_transaction_async
1821bb9c12c9SSage Weil  * returns, any subsequent transaction will not be allowed to join.
1822bb9c12c9SSage Weil  */
1823bb9c12c9SSage Weil struct btrfs_async_commit {
1824bb9c12c9SSage Weil 	struct btrfs_trans_handle *newtrans;
18257892b5afSMiao Xie 	struct work_struct work;
1826bb9c12c9SSage Weil };
1827bb9c12c9SSage Weil 
1828bb9c12c9SSage Weil static void do_async_commit(struct work_struct *work)
1829bb9c12c9SSage Weil {
1830bb9c12c9SSage Weil 	struct btrfs_async_commit *ac =
18317892b5afSMiao Xie 		container_of(work, struct btrfs_async_commit, work);
1832bb9c12c9SSage Weil 
18336fc4e354SSage Weil 	/*
18346fc4e354SSage Weil 	 * We've got freeze protection passed with the transaction.
18356fc4e354SSage Weil 	 * Tell lockdep about it.
18366fc4e354SSage Weil 	 */
1837b1a06a4bSLiu Bo 	if (ac->newtrans->type & __TRANS_FREEZABLE)
18383a45bb20SJeff Mahoney 		__sb_writers_acquired(ac->newtrans->fs_info->sb, SB_FREEZE_FS);
18396fc4e354SSage Weil 
1840e209db7aSSage Weil 	current->journal_info = ac->newtrans;
1841e209db7aSSage Weil 
18423a45bb20SJeff Mahoney 	btrfs_commit_transaction(ac->newtrans);
1843bb9c12c9SSage Weil 	kfree(ac);
1844bb9c12c9SSage Weil }
1845bb9c12c9SSage Weil 
1846bb9c12c9SSage Weil int btrfs_commit_transaction_async(struct btrfs_trans_handle *trans,
1847bb9c12c9SSage Weil 				   int wait_for_unblock)
1848bb9c12c9SSage Weil {
18493a45bb20SJeff Mahoney 	struct btrfs_fs_info *fs_info = trans->fs_info;
1850bb9c12c9SSage Weil 	struct btrfs_async_commit *ac;
1851bb9c12c9SSage Weil 	struct btrfs_transaction *cur_trans;
1852bb9c12c9SSage Weil 
1853bb9c12c9SSage Weil 	ac = kmalloc(sizeof(*ac), GFP_NOFS);
1854db5b493aSTsutomu Itoh 	if (!ac)
1855db5b493aSTsutomu Itoh 		return -ENOMEM;
1856bb9c12c9SSage Weil 
18577892b5afSMiao Xie 	INIT_WORK(&ac->work, do_async_commit);
18583a45bb20SJeff Mahoney 	ac->newtrans = btrfs_join_transaction(trans->root);
18593612b495STsutomu Itoh 	if (IS_ERR(ac->newtrans)) {
18603612b495STsutomu Itoh 		int err = PTR_ERR(ac->newtrans);
18613612b495STsutomu Itoh 		kfree(ac);
18623612b495STsutomu Itoh 		return err;
18633612b495STsutomu Itoh 	}
1864bb9c12c9SSage Weil 
1865bb9c12c9SSage Weil 	/* take transaction reference */
1866bb9c12c9SSage Weil 	cur_trans = trans->transaction;
18679b64f57dSElena Reshetova 	refcount_inc(&cur_trans->use_count);
1868bb9c12c9SSage Weil 
18693a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
18706fc4e354SSage Weil 
18716fc4e354SSage Weil 	/*
18726fc4e354SSage Weil 	 * Tell lockdep we've released the freeze rwsem, since the
18736fc4e354SSage Weil 	 * async commit thread will be the one to unlock it.
18746fc4e354SSage Weil 	 */
1875b1a06a4bSLiu Bo 	if (ac->newtrans->type & __TRANS_FREEZABLE)
18760b246afaSJeff Mahoney 		__sb_writers_release(fs_info->sb, SB_FREEZE_FS);
18776fc4e354SSage Weil 
18787892b5afSMiao Xie 	schedule_work(&ac->work);
1879bb9c12c9SSage Weil 
1880bb9c12c9SSage Weil 	/* wait for transaction to start and unblock */
1881bb9c12c9SSage Weil 	if (wait_for_unblock)
18822ff7e61eSJeff Mahoney 		wait_current_trans_commit_start_and_unblock(fs_info, cur_trans);
1883bb9c12c9SSage Weil 	else
18842ff7e61eSJeff Mahoney 		wait_current_trans_commit_start(fs_info, cur_trans);
1885bb9c12c9SSage Weil 
188638e88054SSage Weil 	if (current->journal_info == trans)
188738e88054SSage Weil 		current->journal_info = NULL;
188838e88054SSage Weil 
1889724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
1890bb9c12c9SSage Weil 	return 0;
1891bb9c12c9SSage Weil }
1892bb9c12c9SSage Weil 
189349b25e05SJeff Mahoney 
189497cb39bbSNikolay Borisov static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
189549b25e05SJeff Mahoney {
189697cb39bbSNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
189749b25e05SJeff Mahoney 	struct btrfs_transaction *cur_trans = trans->transaction;
189849b25e05SJeff Mahoney 
1899b50fff81SDavid Sterba 	WARN_ON(refcount_read(&trans->use_count) > 1);
190049b25e05SJeff Mahoney 
190166642832SJeff Mahoney 	btrfs_abort_transaction(trans, err);
19027b8b92afSJosef Bacik 
19030b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
190466b6135bSLiu Bo 
190525d8c284SMiao Xie 	/*
190625d8c284SMiao Xie 	 * If the transaction is removed from the list, it means this
190725d8c284SMiao Xie 	 * transaction has been committed successfully, so it is impossible
190825d8c284SMiao Xie 	 * to call the cleanup function.
190925d8c284SMiao Xie 	 */
191025d8c284SMiao Xie 	BUG_ON(list_empty(&cur_trans->list));
191166b6135bSLiu Bo 
191249b25e05SJeff Mahoney 	list_del_init(&cur_trans->list);
19130b246afaSJeff Mahoney 	if (cur_trans == fs_info->running_transaction) {
19144a9d8bdeSMiao Xie 		cur_trans->state = TRANS_STATE_COMMIT_DOING;
19150b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
1916f094ac32SLiu Bo 		wait_event(cur_trans->writer_wait,
1917f094ac32SLiu Bo 			   atomic_read(&cur_trans->num_writers) == 1);
1918f094ac32SLiu Bo 
19190b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
1920d7096fc3SJosef Bacik 	}
19210b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
192249b25e05SJeff Mahoney 
19232ff7e61eSJeff Mahoney 	btrfs_cleanup_one_transaction(trans->transaction, fs_info);
192449b25e05SJeff Mahoney 
19250b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
19260b246afaSJeff Mahoney 	if (cur_trans == fs_info->running_transaction)
19270b246afaSJeff Mahoney 		fs_info->running_transaction = NULL;
19280b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
19294a9d8bdeSMiao Xie 
1930e0228285SJosef Bacik 	if (trans->type & __TRANS_FREEZABLE)
19310b246afaSJeff Mahoney 		sb_end_intwrite(fs_info->sb);
1932724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
1933724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
193449b25e05SJeff Mahoney 
193597cb39bbSNikolay Borisov 	trace_btrfs_transaction_commit(trans->root);
193649b25e05SJeff Mahoney 
193749b25e05SJeff Mahoney 	if (current->journal_info == trans)
193849b25e05SJeff Mahoney 		current->journal_info = NULL;
19390b246afaSJeff Mahoney 	btrfs_scrub_cancel(fs_info);
194049b25e05SJeff Mahoney 
194149b25e05SJeff Mahoney 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
194249b25e05SJeff Mahoney }
194349b25e05SJeff Mahoney 
1944c7cc64a9SDavid Sterba /*
1945c7cc64a9SDavid Sterba  * Release reserved delayed ref space of all pending block groups of the
1946c7cc64a9SDavid Sterba  * transaction and remove them from the list
1947c7cc64a9SDavid Sterba  */
1948c7cc64a9SDavid Sterba static void btrfs_cleanup_pending_block_groups(struct btrfs_trans_handle *trans)
1949c7cc64a9SDavid Sterba {
1950c7cc64a9SDavid Sterba        struct btrfs_fs_info *fs_info = trans->fs_info;
195132da5386SDavid Sterba        struct btrfs_block_group *block_group, *tmp;
1952c7cc64a9SDavid Sterba 
1953c7cc64a9SDavid Sterba        list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
1954c7cc64a9SDavid Sterba                btrfs_delayed_refs_rsv_release(fs_info, 1);
1955c7cc64a9SDavid Sterba                list_del_init(&block_group->bg_list);
1956c7cc64a9SDavid Sterba        }
1957c7cc64a9SDavid Sterba }
1958c7cc64a9SDavid Sterba 
1959*88090ad3SFilipe Manana static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
196082436617SMiao Xie {
1961ce8ea7ccSJosef Bacik 	/*
1962ce8ea7ccSJosef Bacik 	 * We use writeback_inodes_sb here because if we used
1963ce8ea7ccSJosef Bacik 	 * btrfs_start_delalloc_roots we would deadlock with fs freeze.
1964ce8ea7ccSJosef Bacik 	 * Currently are holding the fs freeze lock, if we do an async flush
1965ce8ea7ccSJosef Bacik 	 * we'll do btrfs_join_transaction() and deadlock because we need to
1966ce8ea7ccSJosef Bacik 	 * wait for the fs freeze lock.  Using the direct flushing we benefit
1967ce8ea7ccSJosef Bacik 	 * from already being in a transaction and our join_transaction doesn't
1968ce8ea7ccSJosef Bacik 	 * have to re-take the fs freeze lock.
1969ce8ea7ccSJosef Bacik 	 */
1970*88090ad3SFilipe Manana 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
1971ce8ea7ccSJosef Bacik 		writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
197282436617SMiao Xie 	return 0;
197382436617SMiao Xie }
197482436617SMiao Xie 
1975*88090ad3SFilipe Manana static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
197682436617SMiao Xie {
1977*88090ad3SFilipe Manana 	if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
19786374e57aSChris Mason 		btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
197982436617SMiao Xie }
198082436617SMiao Xie 
19813a45bb20SJeff Mahoney int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
198279154b1bSChris Mason {
19833a45bb20SJeff Mahoney 	struct btrfs_fs_info *fs_info = trans->fs_info;
198449b25e05SJeff Mahoney 	struct btrfs_transaction *cur_trans = trans->transaction;
19858fd17795SChris Mason 	struct btrfs_transaction *prev_trans = NULL;
198625287e0aSMiao Xie 	int ret;
198779154b1bSChris Mason 
198835b814f3SNikolay Borisov 	ASSERT(refcount_read(&trans->use_count) == 1);
198935b814f3SNikolay Borisov 
1990d62b23c9SJosef Bacik 	/*
1991d62b23c9SJosef Bacik 	 * Some places just start a transaction to commit it.  We need to make
1992d62b23c9SJosef Bacik 	 * sure that if this commit fails that the abort code actually marks the
1993d62b23c9SJosef Bacik 	 * transaction as failed, so set trans->dirty to make the abort code do
1994d62b23c9SJosef Bacik 	 * the right thing.
1995d62b23c9SJosef Bacik 	 */
1996d62b23c9SJosef Bacik 	trans->dirty = true;
1997d62b23c9SJosef Bacik 
19988d25a086SMiao Xie 	/* Stop the commit early if ->aborted is set */
1999bf31f87fSDavid Sterba 	if (TRANS_ABORTED(cur_trans)) {
200025287e0aSMiao Xie 		ret = cur_trans->aborted;
20013a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
2002e4a2bcacSJosef Bacik 		return ret;
200325287e0aSMiao Xie 	}
200449b25e05SJeff Mahoney 
2005f45c752bSJosef Bacik 	btrfs_trans_release_metadata(trans);
2006f45c752bSJosef Bacik 	trans->block_rsv = NULL;
2007f45c752bSJosef Bacik 
200856bec294SChris Mason 	/* make a pass through all the delayed refs we have so far
200956bec294SChris Mason 	 * any runnings procs may add more while we are here
201056bec294SChris Mason 	 */
2011c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, 0);
2012e4a2bcacSJosef Bacik 	if (ret) {
20133a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
2014e4a2bcacSJosef Bacik 		return ret;
2015e4a2bcacSJosef Bacik 	}
201656bec294SChris Mason 
2017b7ec40d7SChris Mason 	cur_trans = trans->transaction;
201849b25e05SJeff Mahoney 
201956bec294SChris Mason 	/*
202056bec294SChris Mason 	 * set the flushing flag so procs in this transaction have to
202156bec294SChris Mason 	 * start sending their work down.
202256bec294SChris Mason 	 */
2023b7ec40d7SChris Mason 	cur_trans->delayed_refs.flushing = 1;
20241be41b78SJosef Bacik 	smp_wmb();
202556bec294SChris Mason 
20266c686b35SNikolay Borisov 	btrfs_create_pending_block_groups(trans);
2027ea658badSJosef Bacik 
2028c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, 0);
2029e4a2bcacSJosef Bacik 	if (ret) {
20303a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
2031e4a2bcacSJosef Bacik 		return ret;
2032e4a2bcacSJosef Bacik 	}
203356bec294SChris Mason 
20343204d33cSJosef Bacik 	if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
20351bbc621eSChris Mason 		int run_it = 0;
20361bbc621eSChris Mason 
20371bbc621eSChris Mason 		/* this mutex is also taken before trying to set
20381bbc621eSChris Mason 		 * block groups readonly.  We need to make sure
20391bbc621eSChris Mason 		 * that nobody has set a block group readonly
20401bbc621eSChris Mason 		 * after a extents from that block group have been
20411bbc621eSChris Mason 		 * allocated for cache files.  btrfs_set_block_group_ro
20421bbc621eSChris Mason 		 * will wait for the transaction to commit if it
20433204d33cSJosef Bacik 		 * finds BTRFS_TRANS_DIRTY_BG_RUN set.
20441bbc621eSChris Mason 		 *
20453204d33cSJosef Bacik 		 * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
20463204d33cSJosef Bacik 		 * only one process starts all the block group IO.  It wouldn't
20471bbc621eSChris Mason 		 * hurt to have more than one go through, but there's no
20481bbc621eSChris Mason 		 * real advantage to it either.
20491bbc621eSChris Mason 		 */
20500b246afaSJeff Mahoney 		mutex_lock(&fs_info->ro_block_group_mutex);
20513204d33cSJosef Bacik 		if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
20523204d33cSJosef Bacik 				      &cur_trans->flags))
20531bbc621eSChris Mason 			run_it = 1;
20540b246afaSJeff Mahoney 		mutex_unlock(&fs_info->ro_block_group_mutex);
20551bbc621eSChris Mason 
2056f9cacae3SNikolay Borisov 		if (run_it) {
205721217054SNikolay Borisov 			ret = btrfs_start_dirty_block_groups(trans);
20581bbc621eSChris Mason 			if (ret) {
20593a45bb20SJeff Mahoney 				btrfs_end_transaction(trans);
20601bbc621eSChris Mason 				return ret;
20611bbc621eSChris Mason 			}
2062f9cacae3SNikolay Borisov 		}
2063f9cacae3SNikolay Borisov 	}
20641bbc621eSChris Mason 
20650b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
20664a9d8bdeSMiao Xie 	if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
20670b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
20689b64f57dSElena Reshetova 		refcount_inc(&cur_trans->use_count);
20693a45bb20SJeff Mahoney 		ret = btrfs_end_transaction(trans);
2070ccd467d6SChris Mason 
20712ff7e61eSJeff Mahoney 		wait_for_commit(cur_trans);
207215ee9bc7SJosef Bacik 
2073bf31f87fSDavid Sterba 		if (TRANS_ABORTED(cur_trans))
2074b4924a0fSLiu Bo 			ret = cur_trans->aborted;
2075b4924a0fSLiu Bo 
2076724e2315SJosef Bacik 		btrfs_put_transaction(cur_trans);
207715ee9bc7SJosef Bacik 
207849b25e05SJeff Mahoney 		return ret;
207979154b1bSChris Mason 	}
20804313b399SChris Mason 
20814a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
20820b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
2083bb9c12c9SSage Weil 
20840b246afaSJeff Mahoney 	if (cur_trans->list.prev != &fs_info->trans_list) {
2085ccd467d6SChris Mason 		prev_trans = list_entry(cur_trans->list.prev,
2086ccd467d6SChris Mason 					struct btrfs_transaction, list);
20874a9d8bdeSMiao Xie 		if (prev_trans->state != TRANS_STATE_COMPLETED) {
20889b64f57dSElena Reshetova 			refcount_inc(&prev_trans->use_count);
20890b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
2090ccd467d6SChris Mason 
20912ff7e61eSJeff Mahoney 			wait_for_commit(prev_trans);
2092bf31f87fSDavid Sterba 			ret = READ_ONCE(prev_trans->aborted);
2093ccd467d6SChris Mason 
2094724e2315SJosef Bacik 			btrfs_put_transaction(prev_trans);
20951f9b8c8fSFilipe Manana 			if (ret)
20961f9b8c8fSFilipe Manana 				goto cleanup_transaction;
2097a4abeea4SJosef Bacik 		} else {
20980b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
2099ccd467d6SChris Mason 		}
2100a4abeea4SJosef Bacik 	} else {
21010b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
2102cb2d3dadSFilipe Manana 		/*
2103cb2d3dadSFilipe Manana 		 * The previous transaction was aborted and was already removed
2104cb2d3dadSFilipe Manana 		 * from the list of transactions at fs_info->trans_list. So we
2105cb2d3dadSFilipe Manana 		 * abort to prevent writing a new superblock that reflects a
2106cb2d3dadSFilipe Manana 		 * corrupt state (pointing to trees with unwritten nodes/leafs).
2107cb2d3dadSFilipe Manana 		 */
2108cb2d3dadSFilipe Manana 		if (test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state)) {
2109cb2d3dadSFilipe Manana 			ret = -EROFS;
2110cb2d3dadSFilipe Manana 			goto cleanup_transaction;
2111cb2d3dadSFilipe Manana 		}
2112ccd467d6SChris Mason 	}
211315ee9bc7SJosef Bacik 
21140860adfdSMiao Xie 	extwriter_counter_dec(cur_trans, trans->type);
21150860adfdSMiao Xie 
2116*88090ad3SFilipe Manana 	ret = btrfs_start_delalloc_flush(fs_info);
211782436617SMiao Xie 	if (ret)
211882436617SMiao Xie 		goto cleanup_transaction;
211982436617SMiao Xie 
2120e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
212149b25e05SJeff Mahoney 	if (ret)
212249b25e05SJeff Mahoney 		goto cleanup_transaction;
212316cdcec7SMiao Xie 
2124581227d0SMiao Xie 	wait_event(cur_trans->writer_wait,
2125581227d0SMiao Xie 		   extwriter_counter_read(cur_trans) == 0);
2126ed3b3d31SChris Mason 
2127581227d0SMiao Xie 	/* some pending stuffs might be added after the previous flush. */
2128e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
2129ca469637SMiao Xie 	if (ret)
2130ca469637SMiao Xie 		goto cleanup_transaction;
2131ca469637SMiao Xie 
2132*88090ad3SFilipe Manana 	btrfs_wait_delalloc_flush(fs_info);
2133cb7ab021SWang Shilong 
213448778179SFilipe Manana 	/*
213548778179SFilipe Manana 	 * Wait for all ordered extents started by a fast fsync that joined this
213648778179SFilipe Manana 	 * transaction. Otherwise if this transaction commits before the ordered
213748778179SFilipe Manana 	 * extents complete we lose logged data after a power failure.
213848778179SFilipe Manana 	 */
213948778179SFilipe Manana 	wait_event(cur_trans->pending_wait,
214048778179SFilipe Manana 		   atomic_read(&cur_trans->pending_ordered) == 0);
214148778179SFilipe Manana 
21422ff7e61eSJeff Mahoney 	btrfs_scrub_pause(fs_info);
2143ed0ca140SJosef Bacik 	/*
2144ed0ca140SJosef Bacik 	 * Ok now we need to make sure to block out any other joins while we
2145ed0ca140SJosef Bacik 	 * commit the transaction.  We could have started a join before setting
21464a9d8bdeSMiao Xie 	 * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2147ed0ca140SJosef Bacik 	 */
21480b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
21494a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_DOING;
21500b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2151ed0ca140SJosef Bacik 	wait_event(cur_trans->writer_wait,
2152ed0ca140SJosef Bacik 		   atomic_read(&cur_trans->num_writers) == 1);
215315ee9bc7SJosef Bacik 
2154bf31f87fSDavid Sterba 	if (TRANS_ABORTED(cur_trans)) {
21552cba30f1SMiao Xie 		ret = cur_trans->aborted;
21566cf7f77eSWang Shilong 		goto scrub_continue;
21572cba30f1SMiao Xie 	}
21587585717fSChris Mason 	/*
21597585717fSChris Mason 	 * the reloc mutex makes sure that we stop
21607585717fSChris Mason 	 * the balancing code from coming in and moving
21617585717fSChris Mason 	 * extents around in the middle of the commit
21627585717fSChris Mason 	 */
21630b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
21647585717fSChris Mason 
216542874b3dSMiao Xie 	/*
216642874b3dSMiao Xie 	 * We needn't worry about the delayed items because we will
216742874b3dSMiao Xie 	 * deal with them in create_pending_snapshot(), which is the
216842874b3dSMiao Xie 	 * core function of the snapshot creation.
216942874b3dSMiao Xie 	 */
217008d50ca3SNikolay Borisov 	ret = create_pending_snapshots(trans);
217156e9f6eaSDavid Sterba 	if (ret)
217256e9f6eaSDavid Sterba 		goto unlock_reloc;
21733063d29fSChris Mason 
217442874b3dSMiao Xie 	/*
217542874b3dSMiao Xie 	 * We insert the dir indexes of the snapshots and update the inode
217642874b3dSMiao Xie 	 * of the snapshots' parents after the snapshot creation, so there
217742874b3dSMiao Xie 	 * are some delayed items which are not dealt with. Now deal with
217842874b3dSMiao Xie 	 * them.
217942874b3dSMiao Xie 	 *
218042874b3dSMiao Xie 	 * We needn't worry that this operation will corrupt the snapshots,
218142874b3dSMiao Xie 	 * because all the tree which are snapshoted will be forced to COW
218242874b3dSMiao Xie 	 * the nodes and leaves.
218342874b3dSMiao Xie 	 */
2184e5c304e6SNikolay Borisov 	ret = btrfs_run_delayed_items(trans);
218556e9f6eaSDavid Sterba 	if (ret)
218656e9f6eaSDavid Sterba 		goto unlock_reloc;
218716cdcec7SMiao Xie 
2188c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
218956e9f6eaSDavid Sterba 	if (ret)
219056e9f6eaSDavid Sterba 		goto unlock_reloc;
219156bec294SChris Mason 
2192e999376fSChris Mason 	/*
2193e999376fSChris Mason 	 * make sure none of the code above managed to slip in a
2194e999376fSChris Mason 	 * delayed item
2195e999376fSChris Mason 	 */
2196ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
2197e999376fSChris Mason 
21982c90e5d6SChris Mason 	WARN_ON(cur_trans != trans->transaction);
2199dc17ff8fSChris Mason 
2200e02119d5SChris Mason 	/* btrfs_commit_tree_roots is responsible for getting the
2201e02119d5SChris Mason 	 * various roots consistent with each other.  Every pointer
2202e02119d5SChris Mason 	 * in the tree of tree roots has to point to the most up to date
2203e02119d5SChris Mason 	 * root for every subvolume and other tree.  So, we have to keep
2204e02119d5SChris Mason 	 * the tree logging code from jumping in and changing any
2205e02119d5SChris Mason 	 * of the trees.
2206e02119d5SChris Mason 	 *
2207e02119d5SChris Mason 	 * At this point in the commit, there can't be any tree-log
2208e02119d5SChris Mason 	 * writers, but a little lower down we drop the trans mutex
2209e02119d5SChris Mason 	 * and let new people in.  By holding the tree_log_mutex
2210e02119d5SChris Mason 	 * from now until after the super is written, we avoid races
2211e02119d5SChris Mason 	 * with the tree-log code.
2212e02119d5SChris Mason 	 */
22130b246afaSJeff Mahoney 	mutex_lock(&fs_info->tree_log_mutex);
22141a40e23bSZheng Yan 
22157e4443d9SNikolay Borisov 	ret = commit_fs_roots(trans);
221656e9f6eaSDavid Sterba 	if (ret)
221756e9f6eaSDavid Sterba 		goto unlock_tree_log;
221854aa1f4dSChris Mason 
22193818aea2SQu Wenruo 	/*
22207e1876acSDavid Sterba 	 * Since the transaction is done, we can apply the pending changes
22217e1876acSDavid Sterba 	 * before the next transaction.
22223818aea2SQu Wenruo 	 */
22230b246afaSJeff Mahoney 	btrfs_apply_pending_changes(fs_info);
22243818aea2SQu Wenruo 
22255d4f98a2SYan Zheng 	/* commit_fs_roots gets rid of all the tree log roots, it is now
2226e02119d5SChris Mason 	 * safe to free the root of tree log roots
2227e02119d5SChris Mason 	 */
22280b246afaSJeff Mahoney 	btrfs_free_log_root_tree(trans, fs_info);
2229e02119d5SChris Mason 
22300ed4792aSQu Wenruo 	/*
223182bafb38SQu Wenruo 	 * commit_fs_roots() can call btrfs_save_ino_cache(), which generates
223282bafb38SQu Wenruo 	 * new delayed refs. Must handle them or qgroup can be wrong.
223382bafb38SQu Wenruo 	 */
2234c79a70b1SNikolay Borisov 	ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
223556e9f6eaSDavid Sterba 	if (ret)
223656e9f6eaSDavid Sterba 		goto unlock_tree_log;
223782bafb38SQu Wenruo 
223882bafb38SQu Wenruo 	/*
22390ed4792aSQu Wenruo 	 * Since fs roots are all committed, we can get a quite accurate
22400ed4792aSQu Wenruo 	 * new_roots. So let's do quota accounting.
22410ed4792aSQu Wenruo 	 */
2242460fb20aSNikolay Borisov 	ret = btrfs_qgroup_account_extents(trans);
224356e9f6eaSDavid Sterba 	if (ret < 0)
224456e9f6eaSDavid Sterba 		goto unlock_tree_log;
22450ed4792aSQu Wenruo 
22469386d8bcSNikolay Borisov 	ret = commit_cowonly_roots(trans);
224756e9f6eaSDavid Sterba 	if (ret)
224856e9f6eaSDavid Sterba 		goto unlock_tree_log;
224954aa1f4dSChris Mason 
22502cba30f1SMiao Xie 	/*
22512cba30f1SMiao Xie 	 * The tasks which save the space cache and inode cache may also
22522cba30f1SMiao Xie 	 * update ->aborted, check it.
22532cba30f1SMiao Xie 	 */
2254bf31f87fSDavid Sterba 	if (TRANS_ABORTED(cur_trans)) {
22552cba30f1SMiao Xie 		ret = cur_trans->aborted;
225656e9f6eaSDavid Sterba 		goto unlock_tree_log;
22572cba30f1SMiao Xie 	}
22582cba30f1SMiao Xie 
22598b74c03eSDavid Sterba 	btrfs_prepare_extent_commit(fs_info);
226011833d66SYan Zheng 
22610b246afaSJeff Mahoney 	cur_trans = fs_info->running_transaction;
22625f39d397SChris Mason 
22630b246afaSJeff Mahoney 	btrfs_set_root_node(&fs_info->tree_root->root_item,
22640b246afaSJeff Mahoney 			    fs_info->tree_root->node);
22650b246afaSJeff Mahoney 	list_add_tail(&fs_info->tree_root->dirty_list,
22669e351cc8SJosef Bacik 		      &cur_trans->switch_commits);
22675d4f98a2SYan Zheng 
22680b246afaSJeff Mahoney 	btrfs_set_root_node(&fs_info->chunk_root->root_item,
22690b246afaSJeff Mahoney 			    fs_info->chunk_root->node);
22700b246afaSJeff Mahoney 	list_add_tail(&fs_info->chunk_root->dirty_list,
22719e351cc8SJosef Bacik 		      &cur_trans->switch_commits);
22729e351cc8SJosef Bacik 
2273889bfa39SJosef Bacik 	switch_commit_roots(trans);
22745d4f98a2SYan Zheng 
2275ce93ec54SJosef Bacik 	ASSERT(list_empty(&cur_trans->dirty_bgs));
22761bbc621eSChris Mason 	ASSERT(list_empty(&cur_trans->io_bgs));
22772ff7e61eSJeff Mahoney 	update_super_roots(fs_info);
2278e02119d5SChris Mason 
22790b246afaSJeff Mahoney 	btrfs_set_super_log_root(fs_info->super_copy, 0);
22800b246afaSJeff Mahoney 	btrfs_set_super_log_root_level(fs_info->super_copy, 0);
22810b246afaSJeff Mahoney 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
22820b246afaSJeff Mahoney 	       sizeof(*fs_info->super_copy));
2283ccd467d6SChris Mason 
2284bbbf7243SNikolay Borisov 	btrfs_commit_device_sizes(cur_trans);
2285935e5cc9SMiao Xie 
22860b246afaSJeff Mahoney 	clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
22870b246afaSJeff Mahoney 	clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2288656f30dbSFilipe Manana 
22894fbcdf66SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
22904fbcdf66SFilipe Manana 
22910b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
22924a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
22930b246afaSJeff Mahoney 	fs_info->running_transaction = NULL;
22940b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
22950b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
2296b7ec40d7SChris Mason 
22970b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
2298e6dcd2dcSChris Mason 
229970458a58SNikolay Borisov 	ret = btrfs_write_and_wait_transaction(trans);
230049b25e05SJeff Mahoney 	if (ret) {
23010b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
230208748810SDavid Sterba 				      "Error while writing out transaction");
230356e9f6eaSDavid Sterba 		/*
230456e9f6eaSDavid Sterba 		 * reloc_mutex has been unlocked, tree_log_mutex is still held
230556e9f6eaSDavid Sterba 		 * but we can't jump to unlock_tree_log causing double unlock
230656e9f6eaSDavid Sterba 		 */
23070b246afaSJeff Mahoney 		mutex_unlock(&fs_info->tree_log_mutex);
23086cf7f77eSWang Shilong 		goto scrub_continue;
230949b25e05SJeff Mahoney 	}
231049b25e05SJeff Mahoney 
2311eece6a9cSDavid Sterba 	ret = write_all_supers(fs_info, 0);
2312e02119d5SChris Mason 	/*
2313e02119d5SChris Mason 	 * the super is written, we can safely allow the tree-loggers
2314e02119d5SChris Mason 	 * to go about their business
2315e02119d5SChris Mason 	 */
23160b246afaSJeff Mahoney 	mutex_unlock(&fs_info->tree_log_mutex);
2317c1f32b7cSAnand Jain 	if (ret)
2318c1f32b7cSAnand Jain 		goto scrub_continue;
2319e02119d5SChris Mason 
23205ead2dd0SNikolay Borisov 	btrfs_finish_extent_commit(trans);
23214313b399SChris Mason 
23223204d33cSJosef Bacik 	if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
23230b246afaSJeff Mahoney 		btrfs_clear_space_info_full(fs_info);
232413212b54SZhao Lei 
23250b246afaSJeff Mahoney 	fs_info->last_trans_committed = cur_trans->transid;
23264a9d8bdeSMiao Xie 	/*
23274a9d8bdeSMiao Xie 	 * We needn't acquire the lock here because there is no other task
23284a9d8bdeSMiao Xie 	 * which can change it.
23294a9d8bdeSMiao Xie 	 */
23304a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMPLETED;
23312c90e5d6SChris Mason 	wake_up(&cur_trans->commit_wait);
23323de4586cSChris Mason 
23330b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
233413c5a93eSJosef Bacik 	list_del_init(&cur_trans->list);
23350b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2336a4abeea4SJosef Bacik 
2337724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
2338724e2315SJosef Bacik 	btrfs_put_transaction(cur_trans);
233958176a96SJosef Bacik 
23400860adfdSMiao Xie 	if (trans->type & __TRANS_FREEZABLE)
23410b246afaSJeff Mahoney 		sb_end_intwrite(fs_info->sb);
2342b2b5ef5cSJan Kara 
23433a45bb20SJeff Mahoney 	trace_btrfs_transaction_commit(trans->root);
23441abe9b8aSliubo 
23452ff7e61eSJeff Mahoney 	btrfs_scrub_continue(fs_info);
2346a2de733cSArne Jansen 
23479ed74f2dSJosef Bacik 	if (current->journal_info == trans)
23489ed74f2dSJosef Bacik 		current->journal_info = NULL;
23499ed74f2dSJosef Bacik 
23502c90e5d6SChris Mason 	kmem_cache_free(btrfs_trans_handle_cachep, trans);
235124bbcf04SYan, Zheng 
235279154b1bSChris Mason 	return ret;
235349b25e05SJeff Mahoney 
235456e9f6eaSDavid Sterba unlock_tree_log:
235556e9f6eaSDavid Sterba 	mutex_unlock(&fs_info->tree_log_mutex);
235656e9f6eaSDavid Sterba unlock_reloc:
235756e9f6eaSDavid Sterba 	mutex_unlock(&fs_info->reloc_mutex);
23586cf7f77eSWang Shilong scrub_continue:
23592ff7e61eSJeff Mahoney 	btrfs_scrub_continue(fs_info);
236049b25e05SJeff Mahoney cleanup_transaction:
2361dc60c525SNikolay Borisov 	btrfs_trans_release_metadata(trans);
2362c7cc64a9SDavid Sterba 	btrfs_cleanup_pending_block_groups(trans);
23634fbcdf66SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
23640e721106SJosef Bacik 	trans->block_rsv = NULL;
23650b246afaSJeff Mahoney 	btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
236649b25e05SJeff Mahoney 	if (current->journal_info == trans)
236749b25e05SJeff Mahoney 		current->journal_info = NULL;
236897cb39bbSNikolay Borisov 	cleanup_transaction(trans, ret);
236949b25e05SJeff Mahoney 
237049b25e05SJeff Mahoney 	return ret;
237179154b1bSChris Mason }
237279154b1bSChris Mason 
2373d352ac68SChris Mason /*
23749d1a2a3aSDavid Sterba  * return < 0 if error
23759d1a2a3aSDavid Sterba  * 0 if there are no more dead_roots at the time of call
23769d1a2a3aSDavid Sterba  * 1 there are more to be processed, call me again
23779d1a2a3aSDavid Sterba  *
23789d1a2a3aSDavid Sterba  * The return value indicates there are certainly more snapshots to delete, but
23799d1a2a3aSDavid Sterba  * if there comes a new one during processing, it may return 0. We don't mind,
23809d1a2a3aSDavid Sterba  * because btrfs_commit_super will poke cleaner thread and it will process it a
23819d1a2a3aSDavid Sterba  * few seconds later.
2382d352ac68SChris Mason  */
23839d1a2a3aSDavid Sterba int btrfs_clean_one_deleted_snapshot(struct btrfs_root *root)
2384e9d0b13bSChris Mason {
23859d1a2a3aSDavid Sterba 	int ret;
23865d4f98a2SYan Zheng 	struct btrfs_fs_info *fs_info = root->fs_info;
2387e9d0b13bSChris Mason 
2388a4abeea4SJosef Bacik 	spin_lock(&fs_info->trans_lock);
23899d1a2a3aSDavid Sterba 	if (list_empty(&fs_info->dead_roots)) {
23909d1a2a3aSDavid Sterba 		spin_unlock(&fs_info->trans_lock);
23919d1a2a3aSDavid Sterba 		return 0;
23929d1a2a3aSDavid Sterba 	}
23939d1a2a3aSDavid Sterba 	root = list_first_entry(&fs_info->dead_roots,
23949d1a2a3aSDavid Sterba 			struct btrfs_root, root_list);
2395cfad392bSJosef Bacik 	list_del_init(&root->root_list);
2396a4abeea4SJosef Bacik 	spin_unlock(&fs_info->trans_lock);
23975d4f98a2SYan Zheng 
23984fd786e6SMisono Tomohiro 	btrfs_debug(fs_info, "cleaner removing %llu", root->root_key.objectid);
239976dda93cSYan, Zheng 
240016cdcec7SMiao Xie 	btrfs_kill_all_delayed_nodes(root);
24010e996e7fSJosef Bacik 	if (root->ino_cache_inode) {
24020e996e7fSJosef Bacik 		iput(root->ino_cache_inode);
24030e996e7fSJosef Bacik 		root->ino_cache_inode = NULL;
24040e996e7fSJosef Bacik 	}
240516cdcec7SMiao Xie 
240676dda93cSYan, Zheng 	if (btrfs_header_backref_rev(root->node) <
240776dda93cSYan, Zheng 			BTRFS_MIXED_BACKREF_REV)
24080078a9f9SNikolay Borisov 		ret = btrfs_drop_snapshot(root, 0, 0);
240976dda93cSYan, Zheng 	else
24100078a9f9SNikolay Borisov 		ret = btrfs_drop_snapshot(root, 1, 0);
241132471dc2SDavid Sterba 
2412dc9492c1SJosef Bacik 	btrfs_put_root(root);
24136596a928SJosef Bacik 	return (ret < 0) ? 0 : 1;
2414e9d0b13bSChris Mason }
2415572d9ab7SDavid Sterba 
2416572d9ab7SDavid Sterba void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2417572d9ab7SDavid Sterba {
2418572d9ab7SDavid Sterba 	unsigned long prev;
2419572d9ab7SDavid Sterba 	unsigned long bit;
2420572d9ab7SDavid Sterba 
24216c9fe14fSQu Wenruo 	prev = xchg(&fs_info->pending_changes, 0);
2422572d9ab7SDavid Sterba 	if (!prev)
2423572d9ab7SDavid Sterba 		return;
2424572d9ab7SDavid Sterba 
24257e1876acSDavid Sterba 	bit = 1 << BTRFS_PENDING_SET_INODE_MAP_CACHE;
24267e1876acSDavid Sterba 	if (prev & bit)
24277e1876acSDavid Sterba 		btrfs_set_opt(fs_info->mount_opt, INODE_MAP_CACHE);
24287e1876acSDavid Sterba 	prev &= ~bit;
24297e1876acSDavid Sterba 
24307e1876acSDavid Sterba 	bit = 1 << BTRFS_PENDING_CLEAR_INODE_MAP_CACHE;
24317e1876acSDavid Sterba 	if (prev & bit)
24327e1876acSDavid Sterba 		btrfs_clear_opt(fs_info->mount_opt, INODE_MAP_CACHE);
24337e1876acSDavid Sterba 	prev &= ~bit;
24347e1876acSDavid Sterba 
2435d51033d0SDavid Sterba 	bit = 1 << BTRFS_PENDING_COMMIT;
2436d51033d0SDavid Sterba 	if (prev & bit)
2437d51033d0SDavid Sterba 		btrfs_debug(fs_info, "pending commit done");
2438d51033d0SDavid Sterba 	prev &= ~bit;
2439d51033d0SDavid Sterba 
2440572d9ab7SDavid Sterba 	if (prev)
2441572d9ab7SDavid Sterba 		btrfs_warn(fs_info,
2442572d9ab7SDavid Sterba 			"unknown pending changes left 0x%lx, ignoring", prev);
2443572d9ab7SDavid Sterba }
2444