xref: /linux/fs/btrfs/block-group.c (revision 675dfe1223a69e270b3d52cb0211c8a501455cec)
12e405ad8SJosef Bacik // SPDX-License-Identifier: GPL-2.0
22e405ad8SJosef Bacik 
352bb7a21SBoris Burkov #include <linux/sizes.h>
42ca0ec77SJohannes Thumshirn #include <linux/list_sort.h>
5784352feSDavid Sterba #include "misc.h"
62e405ad8SJosef Bacik #include "ctree.h"
72e405ad8SJosef Bacik #include "block-group.h"
83eeb3226SJosef Bacik #include "space-info.h"
99f21246dSJosef Bacik #include "disk-io.h"
109f21246dSJosef Bacik #include "free-space-cache.h"
119f21246dSJosef Bacik #include "free-space-tree.h"
12e3e0520bSJosef Bacik #include "volumes.h"
13e3e0520bSJosef Bacik #include "transaction.h"
14e3e0520bSJosef Bacik #include "ref-verify.h"
154358d963SJosef Bacik #include "sysfs.h"
164358d963SJosef Bacik #include "tree-log.h"
1777745c05SJosef Bacik #include "delalloc-space.h"
18b0643e59SDennis Zhou #include "discard.h"
1996a14336SNikolay Borisov #include "raid56.h"
2008e11a3dSNaohiro Aota #include "zoned.h"
21c7f13d42SJosef Bacik #include "fs.h"
2207e81dc9SJosef Bacik #include "accessors.h"
23a0231804SJosef Bacik #include "extent-tree.h"
242e405ad8SJosef Bacik 
2506d61cb1SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2606d61cb1SJosef Bacik int btrfs_should_fragment_free_space(struct btrfs_block_group *block_group)
2706d61cb1SJosef Bacik {
2806d61cb1SJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
2906d61cb1SJosef Bacik 
3006d61cb1SJosef Bacik 	return (btrfs_test_opt(fs_info, FRAGMENT_METADATA) &&
3106d61cb1SJosef Bacik 		block_group->flags & BTRFS_BLOCK_GROUP_METADATA) ||
3206d61cb1SJosef Bacik 	       (btrfs_test_opt(fs_info, FRAGMENT_DATA) &&
3306d61cb1SJosef Bacik 		block_group->flags &  BTRFS_BLOCK_GROUP_DATA);
3406d61cb1SJosef Bacik }
3506d61cb1SJosef Bacik #endif
3606d61cb1SJosef Bacik 
37878d7b67SJosef Bacik /*
38878d7b67SJosef Bacik  * Return target flags in extended format or 0 if restripe for this chunk_type
39878d7b67SJosef Bacik  * is not in progress
40878d7b67SJosef Bacik  *
41878d7b67SJosef Bacik  * Should be called with balance_lock held
42878d7b67SJosef Bacik  */
43e11c0406SJosef Bacik static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
44878d7b67SJosef Bacik {
45878d7b67SJosef Bacik 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
46878d7b67SJosef Bacik 	u64 target = 0;
47878d7b67SJosef Bacik 
48878d7b67SJosef Bacik 	if (!bctl)
49878d7b67SJosef Bacik 		return 0;
50878d7b67SJosef Bacik 
51878d7b67SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA &&
52878d7b67SJosef Bacik 	    bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
53878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
54878d7b67SJosef Bacik 	} else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
55878d7b67SJosef Bacik 		   bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
56878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
57878d7b67SJosef Bacik 	} else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
58878d7b67SJosef Bacik 		   bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
59878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
60878d7b67SJosef Bacik 	}
61878d7b67SJosef Bacik 
62878d7b67SJosef Bacik 	return target;
63878d7b67SJosef Bacik }
64878d7b67SJosef Bacik 
65878d7b67SJosef Bacik /*
66878d7b67SJosef Bacik  * @flags: available profiles in extended format (see ctree.h)
67878d7b67SJosef Bacik  *
68878d7b67SJosef Bacik  * Return reduced profile in chunk format.  If profile changing is in progress
69878d7b67SJosef Bacik  * (either running or paused) picks the target profile (if it's already
70878d7b67SJosef Bacik  * available), otherwise falls back to plain reducing.
71878d7b67SJosef Bacik  */
72878d7b67SJosef Bacik static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
73878d7b67SJosef Bacik {
74878d7b67SJosef Bacik 	u64 num_devices = fs_info->fs_devices->rw_devices;
75878d7b67SJosef Bacik 	u64 target;
76878d7b67SJosef Bacik 	u64 raid_type;
77878d7b67SJosef Bacik 	u64 allowed = 0;
78878d7b67SJosef Bacik 
79878d7b67SJosef Bacik 	/*
80878d7b67SJosef Bacik 	 * See if restripe for this chunk_type is in progress, if so try to
81878d7b67SJosef Bacik 	 * reduce to the target profile
82878d7b67SJosef Bacik 	 */
83878d7b67SJosef Bacik 	spin_lock(&fs_info->balance_lock);
84e11c0406SJosef Bacik 	target = get_restripe_target(fs_info, flags);
85878d7b67SJosef Bacik 	if (target) {
86878d7b67SJosef Bacik 		spin_unlock(&fs_info->balance_lock);
87878d7b67SJosef Bacik 		return extended_to_chunk(target);
88878d7b67SJosef Bacik 	}
89878d7b67SJosef Bacik 	spin_unlock(&fs_info->balance_lock);
90878d7b67SJosef Bacik 
91878d7b67SJosef Bacik 	/* First, mask out the RAID levels which aren't possible */
92878d7b67SJosef Bacik 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
93878d7b67SJosef Bacik 		if (num_devices >= btrfs_raid_array[raid_type].devs_min)
94878d7b67SJosef Bacik 			allowed |= btrfs_raid_array[raid_type].bg_flag;
95878d7b67SJosef Bacik 	}
96878d7b67SJosef Bacik 	allowed &= flags;
97878d7b67SJosef Bacik 
98878d7b67SJosef Bacik 	if (allowed & BTRFS_BLOCK_GROUP_RAID6)
99878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID6;
100878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
101878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID5;
102878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
103878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID10;
104878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
105878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID1;
106878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
107878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID0;
108878d7b67SJosef Bacik 
109878d7b67SJosef Bacik 	flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
110878d7b67SJosef Bacik 
111878d7b67SJosef Bacik 	return extended_to_chunk(flags | allowed);
112878d7b67SJosef Bacik }
113878d7b67SJosef Bacik 
114ef0a82daSJohannes Thumshirn u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
115878d7b67SJosef Bacik {
116878d7b67SJosef Bacik 	unsigned seq;
117878d7b67SJosef Bacik 	u64 flags;
118878d7b67SJosef Bacik 
119878d7b67SJosef Bacik 	do {
120878d7b67SJosef Bacik 		flags = orig_flags;
121878d7b67SJosef Bacik 		seq = read_seqbegin(&fs_info->profiles_lock);
122878d7b67SJosef Bacik 
123878d7b67SJosef Bacik 		if (flags & BTRFS_BLOCK_GROUP_DATA)
124878d7b67SJosef Bacik 			flags |= fs_info->avail_data_alloc_bits;
125878d7b67SJosef Bacik 		else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
126878d7b67SJosef Bacik 			flags |= fs_info->avail_system_alloc_bits;
127878d7b67SJosef Bacik 		else if (flags & BTRFS_BLOCK_GROUP_METADATA)
128878d7b67SJosef Bacik 			flags |= fs_info->avail_metadata_alloc_bits;
129878d7b67SJosef Bacik 	} while (read_seqretry(&fs_info->profiles_lock, seq));
130878d7b67SJosef Bacik 
131878d7b67SJosef Bacik 	return btrfs_reduce_alloc_profile(fs_info, flags);
132878d7b67SJosef Bacik }
133878d7b67SJosef Bacik 
13432da5386SDavid Sterba void btrfs_get_block_group(struct btrfs_block_group *cache)
1353cad1284SJosef Bacik {
13648aaeebeSJosef Bacik 	refcount_inc(&cache->refs);
1373cad1284SJosef Bacik }
1383cad1284SJosef Bacik 
13932da5386SDavid Sterba void btrfs_put_block_group(struct btrfs_block_group *cache)
1403cad1284SJosef Bacik {
14148aaeebeSJosef Bacik 	if (refcount_dec_and_test(&cache->refs)) {
1423cad1284SJosef Bacik 		WARN_ON(cache->pinned > 0);
14340cdc509SFilipe Manana 		/*
14440cdc509SFilipe Manana 		 * If there was a failure to cleanup a log tree, very likely due
14540cdc509SFilipe Manana 		 * to an IO failure on a writeback attempt of one or more of its
14640cdc509SFilipe Manana 		 * extent buffers, we could not do proper (and cheap) unaccounting
14740cdc509SFilipe Manana 		 * of their reserved space, so don't warn on reserved > 0 in that
14840cdc509SFilipe Manana 		 * case.
14940cdc509SFilipe Manana 		 */
15040cdc509SFilipe Manana 		if (!(cache->flags & BTRFS_BLOCK_GROUP_METADATA) ||
15140cdc509SFilipe Manana 		    !BTRFS_FS_LOG_CLEANUP_ERROR(cache->fs_info))
1523cad1284SJosef Bacik 			WARN_ON(cache->reserved > 0);
1533cad1284SJosef Bacik 
1543cad1284SJosef Bacik 		/*
155b0643e59SDennis Zhou 		 * A block_group shouldn't be on the discard_list anymore.
156b0643e59SDennis Zhou 		 * Remove the block_group from the discard_list to prevent us
157b0643e59SDennis Zhou 		 * from causing a panic due to NULL pointer dereference.
158b0643e59SDennis Zhou 		 */
159b0643e59SDennis Zhou 		if (WARN_ON(!list_empty(&cache->discard_list)))
160b0643e59SDennis Zhou 			btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
161b0643e59SDennis Zhou 						  cache);
162b0643e59SDennis Zhou 
163b0643e59SDennis Zhou 		/*
1643cad1284SJosef Bacik 		 * If not empty, someone is still holding mutex of
1653cad1284SJosef Bacik 		 * full_stripe_lock, which can only be released by caller.
1663cad1284SJosef Bacik 		 * And it will definitely cause use-after-free when caller
1673cad1284SJosef Bacik 		 * tries to release full stripe lock.
1683cad1284SJosef Bacik 		 *
1693cad1284SJosef Bacik 		 * No better way to resolve, but only to warn.
1703cad1284SJosef Bacik 		 */
1713cad1284SJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
1723cad1284SJosef Bacik 		kfree(cache->free_space_ctl);
173dafc340dSNaohiro Aota 		kfree(cache->physical_map);
1743cad1284SJosef Bacik 		kfree(cache);
1753cad1284SJosef Bacik 	}
1763cad1284SJosef Bacik }
1773cad1284SJosef Bacik 
1782e405ad8SJosef Bacik /*
1794358d963SJosef Bacik  * This adds the block group to the fs_info rb tree for the block group cache
1804358d963SJosef Bacik  */
1814358d963SJosef Bacik static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
18232da5386SDavid Sterba 				       struct btrfs_block_group *block_group)
1834358d963SJosef Bacik {
1844358d963SJosef Bacik 	struct rb_node **p;
1854358d963SJosef Bacik 	struct rb_node *parent = NULL;
18632da5386SDavid Sterba 	struct btrfs_block_group *cache;
18708dddb29SFilipe Manana 	bool leftmost = true;
1884358d963SJosef Bacik 
1899afc6649SQu Wenruo 	ASSERT(block_group->length != 0);
1909afc6649SQu Wenruo 
19116b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
19208dddb29SFilipe Manana 	p = &info->block_group_cache_tree.rb_root.rb_node;
1934358d963SJosef Bacik 
1944358d963SJosef Bacik 	while (*p) {
1954358d963SJosef Bacik 		parent = *p;
19632da5386SDavid Sterba 		cache = rb_entry(parent, struct btrfs_block_group, cache_node);
197b3470b5dSDavid Sterba 		if (block_group->start < cache->start) {
1984358d963SJosef Bacik 			p = &(*p)->rb_left;
199b3470b5dSDavid Sterba 		} else if (block_group->start > cache->start) {
2004358d963SJosef Bacik 			p = &(*p)->rb_right;
20108dddb29SFilipe Manana 			leftmost = false;
2024358d963SJosef Bacik 		} else {
20316b0c258SFilipe Manana 			write_unlock(&info->block_group_cache_lock);
2044358d963SJosef Bacik 			return -EEXIST;
2054358d963SJosef Bacik 		}
2064358d963SJosef Bacik 	}
2074358d963SJosef Bacik 
2084358d963SJosef Bacik 	rb_link_node(&block_group->cache_node, parent, p);
20908dddb29SFilipe Manana 	rb_insert_color_cached(&block_group->cache_node,
21008dddb29SFilipe Manana 			       &info->block_group_cache_tree, leftmost);
2114358d963SJosef Bacik 
21216b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
2134358d963SJosef Bacik 
2144358d963SJosef Bacik 	return 0;
2154358d963SJosef Bacik }
2164358d963SJosef Bacik 
2174358d963SJosef Bacik /*
2182e405ad8SJosef Bacik  * This will return the block group at or after bytenr if contains is 0, else
2192e405ad8SJosef Bacik  * it will return the block group that contains the bytenr
2202e405ad8SJosef Bacik  */
22132da5386SDavid Sterba static struct btrfs_block_group *block_group_cache_tree_search(
2222e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr, int contains)
2232e405ad8SJosef Bacik {
22432da5386SDavid Sterba 	struct btrfs_block_group *cache, *ret = NULL;
2252e405ad8SJosef Bacik 	struct rb_node *n;
2262e405ad8SJosef Bacik 	u64 end, start;
2272e405ad8SJosef Bacik 
22816b0c258SFilipe Manana 	read_lock(&info->block_group_cache_lock);
22908dddb29SFilipe Manana 	n = info->block_group_cache_tree.rb_root.rb_node;
2302e405ad8SJosef Bacik 
2312e405ad8SJosef Bacik 	while (n) {
23232da5386SDavid Sterba 		cache = rb_entry(n, struct btrfs_block_group, cache_node);
233b3470b5dSDavid Sterba 		end = cache->start + cache->length - 1;
234b3470b5dSDavid Sterba 		start = cache->start;
2352e405ad8SJosef Bacik 
2362e405ad8SJosef Bacik 		if (bytenr < start) {
237b3470b5dSDavid Sterba 			if (!contains && (!ret || start < ret->start))
2382e405ad8SJosef Bacik 				ret = cache;
2392e405ad8SJosef Bacik 			n = n->rb_left;
2402e405ad8SJosef Bacik 		} else if (bytenr > start) {
2412e405ad8SJosef Bacik 			if (contains && bytenr <= end) {
2422e405ad8SJosef Bacik 				ret = cache;
2432e405ad8SJosef Bacik 				break;
2442e405ad8SJosef Bacik 			}
2452e405ad8SJosef Bacik 			n = n->rb_right;
2462e405ad8SJosef Bacik 		} else {
2472e405ad8SJosef Bacik 			ret = cache;
2482e405ad8SJosef Bacik 			break;
2492e405ad8SJosef Bacik 		}
2502e405ad8SJosef Bacik 	}
25108dddb29SFilipe Manana 	if (ret)
2522e405ad8SJosef Bacik 		btrfs_get_block_group(ret);
25316b0c258SFilipe Manana 	read_unlock(&info->block_group_cache_lock);
2542e405ad8SJosef Bacik 
2552e405ad8SJosef Bacik 	return ret;
2562e405ad8SJosef Bacik }
2572e405ad8SJosef Bacik 
2582e405ad8SJosef Bacik /*
2592e405ad8SJosef Bacik  * Return the block group that starts at or after bytenr
2602e405ad8SJosef Bacik  */
26132da5386SDavid Sterba struct btrfs_block_group *btrfs_lookup_first_block_group(
2622e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr)
2632e405ad8SJosef Bacik {
2642e405ad8SJosef Bacik 	return block_group_cache_tree_search(info, bytenr, 0);
2652e405ad8SJosef Bacik }
2662e405ad8SJosef Bacik 
2672e405ad8SJosef Bacik /*
2682e405ad8SJosef Bacik  * Return the block group that contains the given bytenr
2692e405ad8SJosef Bacik  */
27032da5386SDavid Sterba struct btrfs_block_group *btrfs_lookup_block_group(
2712e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr)
2722e405ad8SJosef Bacik {
2732e405ad8SJosef Bacik 	return block_group_cache_tree_search(info, bytenr, 1);
2742e405ad8SJosef Bacik }
2752e405ad8SJosef Bacik 
27632da5386SDavid Sterba struct btrfs_block_group *btrfs_next_block_group(
27732da5386SDavid Sterba 		struct btrfs_block_group *cache)
2782e405ad8SJosef Bacik {
2792e405ad8SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
2802e405ad8SJosef Bacik 	struct rb_node *node;
2812e405ad8SJosef Bacik 
28216b0c258SFilipe Manana 	read_lock(&fs_info->block_group_cache_lock);
2832e405ad8SJosef Bacik 
2842e405ad8SJosef Bacik 	/* If our block group was removed, we need a full search. */
2852e405ad8SJosef Bacik 	if (RB_EMPTY_NODE(&cache->cache_node)) {
286b3470b5dSDavid Sterba 		const u64 next_bytenr = cache->start + cache->length;
2872e405ad8SJosef Bacik 
28816b0c258SFilipe Manana 		read_unlock(&fs_info->block_group_cache_lock);
2892e405ad8SJosef Bacik 		btrfs_put_block_group(cache);
2908b01f931SFilipe Manana 		return btrfs_lookup_first_block_group(fs_info, next_bytenr);
2912e405ad8SJosef Bacik 	}
2922e405ad8SJosef Bacik 	node = rb_next(&cache->cache_node);
2932e405ad8SJosef Bacik 	btrfs_put_block_group(cache);
2942e405ad8SJosef Bacik 	if (node) {
29532da5386SDavid Sterba 		cache = rb_entry(node, struct btrfs_block_group, cache_node);
2962e405ad8SJosef Bacik 		btrfs_get_block_group(cache);
2972e405ad8SJosef Bacik 	} else
2982e405ad8SJosef Bacik 		cache = NULL;
29916b0c258SFilipe Manana 	read_unlock(&fs_info->block_group_cache_lock);
3002e405ad8SJosef Bacik 	return cache;
3012e405ad8SJosef Bacik }
3023eeb3226SJosef Bacik 
30343dd529aSDavid Sterba /*
3042306e83eSFilipe Manana  * Check if we can do a NOCOW write for a given extent.
3052306e83eSFilipe Manana  *
3062306e83eSFilipe Manana  * @fs_info:       The filesystem information object.
3072306e83eSFilipe Manana  * @bytenr:        Logical start address of the extent.
3082306e83eSFilipe Manana  *
3092306e83eSFilipe Manana  * Check if we can do a NOCOW write for the given extent, and increments the
3102306e83eSFilipe Manana  * number of NOCOW writers in the block group that contains the extent, as long
3112306e83eSFilipe Manana  * as the block group exists and it's currently not in read-only mode.
3122306e83eSFilipe Manana  *
3132306e83eSFilipe Manana  * Returns: A non-NULL block group pointer if we can do a NOCOW write, the caller
3142306e83eSFilipe Manana  *          is responsible for calling btrfs_dec_nocow_writers() later.
3152306e83eSFilipe Manana  *
3162306e83eSFilipe Manana  *          Or NULL if we can not do a NOCOW write
3172306e83eSFilipe Manana  */
3182306e83eSFilipe Manana struct btrfs_block_group *btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info,
3192306e83eSFilipe Manana 						  u64 bytenr)
3203eeb3226SJosef Bacik {
32132da5386SDavid Sterba 	struct btrfs_block_group *bg;
3222306e83eSFilipe Manana 	bool can_nocow = true;
3233eeb3226SJosef Bacik 
3243eeb3226SJosef Bacik 	bg = btrfs_lookup_block_group(fs_info, bytenr);
3253eeb3226SJosef Bacik 	if (!bg)
3262306e83eSFilipe Manana 		return NULL;
3273eeb3226SJosef Bacik 
3283eeb3226SJosef Bacik 	spin_lock(&bg->lock);
3293eeb3226SJosef Bacik 	if (bg->ro)
3302306e83eSFilipe Manana 		can_nocow = false;
3313eeb3226SJosef Bacik 	else
3323eeb3226SJosef Bacik 		atomic_inc(&bg->nocow_writers);
3333eeb3226SJosef Bacik 	spin_unlock(&bg->lock);
3343eeb3226SJosef Bacik 
3352306e83eSFilipe Manana 	if (!can_nocow) {
3363eeb3226SJosef Bacik 		btrfs_put_block_group(bg);
3372306e83eSFilipe Manana 		return NULL;
3383eeb3226SJosef Bacik 	}
3393eeb3226SJosef Bacik 
3402306e83eSFilipe Manana 	/* No put on block group, done by btrfs_dec_nocow_writers(). */
3412306e83eSFilipe Manana 	return bg;
3422306e83eSFilipe Manana }
3433eeb3226SJosef Bacik 
34443dd529aSDavid Sterba /*
3452306e83eSFilipe Manana  * Decrement the number of NOCOW writers in a block group.
3462306e83eSFilipe Manana  *
3472306e83eSFilipe Manana  * This is meant to be called after a previous call to btrfs_inc_nocow_writers(),
3482306e83eSFilipe Manana  * and on the block group returned by that call. Typically this is called after
3492306e83eSFilipe Manana  * creating an ordered extent for a NOCOW write, to prevent races with scrub and
3502306e83eSFilipe Manana  * relocation.
3512306e83eSFilipe Manana  *
3522306e83eSFilipe Manana  * After this call, the caller should not use the block group anymore. It it wants
3532306e83eSFilipe Manana  * to use it, then it should get a reference on it before calling this function.
3542306e83eSFilipe Manana  */
3552306e83eSFilipe Manana void btrfs_dec_nocow_writers(struct btrfs_block_group *bg)
3562306e83eSFilipe Manana {
3573eeb3226SJosef Bacik 	if (atomic_dec_and_test(&bg->nocow_writers))
3583eeb3226SJosef Bacik 		wake_up_var(&bg->nocow_writers);
3592306e83eSFilipe Manana 
3602306e83eSFilipe Manana 	/* For the lookup done by a previous call to btrfs_inc_nocow_writers(). */
3613eeb3226SJosef Bacik 	btrfs_put_block_group(bg);
3623eeb3226SJosef Bacik }
3633eeb3226SJosef Bacik 
36432da5386SDavid Sterba void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
3653eeb3226SJosef Bacik {
3663eeb3226SJosef Bacik 	wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
3673eeb3226SJosef Bacik }
3683eeb3226SJosef Bacik 
3693eeb3226SJosef Bacik void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
3703eeb3226SJosef Bacik 					const u64 start)
3713eeb3226SJosef Bacik {
37232da5386SDavid Sterba 	struct btrfs_block_group *bg;
3733eeb3226SJosef Bacik 
3743eeb3226SJosef Bacik 	bg = btrfs_lookup_block_group(fs_info, start);
3753eeb3226SJosef Bacik 	ASSERT(bg);
3763eeb3226SJosef Bacik 	if (atomic_dec_and_test(&bg->reservations))
3773eeb3226SJosef Bacik 		wake_up_var(&bg->reservations);
3783eeb3226SJosef Bacik 	btrfs_put_block_group(bg);
3793eeb3226SJosef Bacik }
3803eeb3226SJosef Bacik 
38132da5386SDavid Sterba void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
3823eeb3226SJosef Bacik {
3833eeb3226SJosef Bacik 	struct btrfs_space_info *space_info = bg->space_info;
3843eeb3226SJosef Bacik 
3853eeb3226SJosef Bacik 	ASSERT(bg->ro);
3863eeb3226SJosef Bacik 
3873eeb3226SJosef Bacik 	if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
3883eeb3226SJosef Bacik 		return;
3893eeb3226SJosef Bacik 
3903eeb3226SJosef Bacik 	/*
3913eeb3226SJosef Bacik 	 * Our block group is read only but before we set it to read only,
3923eeb3226SJosef Bacik 	 * some task might have had allocated an extent from it already, but it
3933eeb3226SJosef Bacik 	 * has not yet created a respective ordered extent (and added it to a
3943eeb3226SJosef Bacik 	 * root's list of ordered extents).
3953eeb3226SJosef Bacik 	 * Therefore wait for any task currently allocating extents, since the
3963eeb3226SJosef Bacik 	 * block group's reservations counter is incremented while a read lock
3973eeb3226SJosef Bacik 	 * on the groups' semaphore is held and decremented after releasing
3983eeb3226SJosef Bacik 	 * the read access on that semaphore and creating the ordered extent.
3993eeb3226SJosef Bacik 	 */
4003eeb3226SJosef Bacik 	down_write(&space_info->groups_sem);
4013eeb3226SJosef Bacik 	up_write(&space_info->groups_sem);
4023eeb3226SJosef Bacik 
4033eeb3226SJosef Bacik 	wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
4043eeb3226SJosef Bacik }
4059f21246dSJosef Bacik 
4069f21246dSJosef Bacik struct btrfs_caching_control *btrfs_get_caching_control(
40732da5386SDavid Sterba 		struct btrfs_block_group *cache)
4089f21246dSJosef Bacik {
4099f21246dSJosef Bacik 	struct btrfs_caching_control *ctl;
4109f21246dSJosef Bacik 
4119f21246dSJosef Bacik 	spin_lock(&cache->lock);
4129f21246dSJosef Bacik 	if (!cache->caching_ctl) {
4139f21246dSJosef Bacik 		spin_unlock(&cache->lock);
4149f21246dSJosef Bacik 		return NULL;
4159f21246dSJosef Bacik 	}
4169f21246dSJosef Bacik 
4179f21246dSJosef Bacik 	ctl = cache->caching_ctl;
4189f21246dSJosef Bacik 	refcount_inc(&ctl->count);
4199f21246dSJosef Bacik 	spin_unlock(&cache->lock);
4209f21246dSJosef Bacik 	return ctl;
4219f21246dSJosef Bacik }
4229f21246dSJosef Bacik 
4239f21246dSJosef Bacik void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
4249f21246dSJosef Bacik {
4259f21246dSJosef Bacik 	if (refcount_dec_and_test(&ctl->count))
4269f21246dSJosef Bacik 		kfree(ctl);
4279f21246dSJosef Bacik }
4289f21246dSJosef Bacik 
4299f21246dSJosef Bacik /*
4309f21246dSJosef Bacik  * When we wait for progress in the block group caching, its because our
4319f21246dSJosef Bacik  * allocation attempt failed at least once.  So, we must sleep and let some
4329f21246dSJosef Bacik  * progress happen before we try again.
4339f21246dSJosef Bacik  *
4349f21246dSJosef Bacik  * This function will sleep at least once waiting for new free space to show
4359f21246dSJosef Bacik  * up, and then it will check the block group free space numbers for our min
4369f21246dSJosef Bacik  * num_bytes.  Another option is to have it go ahead and look in the rbtree for
4379f21246dSJosef Bacik  * a free extent of a given size, but this is a good start.
4389f21246dSJosef Bacik  *
4399f21246dSJosef Bacik  * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
4409f21246dSJosef Bacik  * any of the information in this block group.
4419f21246dSJosef Bacik  */
44232da5386SDavid Sterba void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
4439f21246dSJosef Bacik 					   u64 num_bytes)
4449f21246dSJosef Bacik {
4459f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
4469f21246dSJosef Bacik 
4479f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4489f21246dSJosef Bacik 	if (!caching_ctl)
4499f21246dSJosef Bacik 		return;
4509f21246dSJosef Bacik 
45132da5386SDavid Sterba 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
4529f21246dSJosef Bacik 		   (cache->free_space_ctl->free_space >= num_bytes));
4539f21246dSJosef Bacik 
4549f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4559f21246dSJosef Bacik }
4569f21246dSJosef Bacik 
457ced8ecf0SOmar Sandoval static int btrfs_caching_ctl_wait_done(struct btrfs_block_group *cache,
458ced8ecf0SOmar Sandoval 				       struct btrfs_caching_control *caching_ctl)
459ced8ecf0SOmar Sandoval {
460ced8ecf0SOmar Sandoval 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
461ced8ecf0SOmar Sandoval 	return cache->cached == BTRFS_CACHE_ERROR ? -EIO : 0;
462ced8ecf0SOmar Sandoval }
463ced8ecf0SOmar Sandoval 
464ced8ecf0SOmar Sandoval static int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
4659f21246dSJosef Bacik {
4669f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
467ced8ecf0SOmar Sandoval 	int ret;
4689f21246dSJosef Bacik 
4699f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4709f21246dSJosef Bacik 	if (!caching_ctl)
4719f21246dSJosef Bacik 		return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
472ced8ecf0SOmar Sandoval 	ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
4739f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4749f21246dSJosef Bacik 	return ret;
4759f21246dSJosef Bacik }
4769f21246dSJosef Bacik 
4779f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
47832da5386SDavid Sterba static void fragment_free_space(struct btrfs_block_group *block_group)
4799f21246dSJosef Bacik {
4809f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
481b3470b5dSDavid Sterba 	u64 start = block_group->start;
482b3470b5dSDavid Sterba 	u64 len = block_group->length;
4839f21246dSJosef Bacik 	u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
4849f21246dSJosef Bacik 		fs_info->nodesize : fs_info->sectorsize;
4859f21246dSJosef Bacik 	u64 step = chunk << 1;
4869f21246dSJosef Bacik 
4879f21246dSJosef Bacik 	while (len > chunk) {
4889f21246dSJosef Bacik 		btrfs_remove_free_space(block_group, start, chunk);
4899f21246dSJosef Bacik 		start += step;
4909f21246dSJosef Bacik 		if (len < step)
4919f21246dSJosef Bacik 			len = 0;
4929f21246dSJosef Bacik 		else
4939f21246dSJosef Bacik 			len -= step;
4949f21246dSJosef Bacik 	}
4959f21246dSJosef Bacik }
4969f21246dSJosef Bacik #endif
4979f21246dSJosef Bacik 
4989f21246dSJosef Bacik /*
4999f21246dSJosef Bacik  * This is only called by btrfs_cache_block_group, since we could have freed
5009f21246dSJosef Bacik  * extents we need to check the pinned_extents for any extents that can't be
5019f21246dSJosef Bacik  * used yet since their free space will be released as soon as the transaction
5029f21246dSJosef Bacik  * commits.
5039f21246dSJosef Bacik  */
50432da5386SDavid Sterba u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
5059f21246dSJosef Bacik {
5069f21246dSJosef Bacik 	struct btrfs_fs_info *info = block_group->fs_info;
5079f21246dSJosef Bacik 	u64 extent_start, extent_end, size, total_added = 0;
5089f21246dSJosef Bacik 	int ret;
5099f21246dSJosef Bacik 
5109f21246dSJosef Bacik 	while (start < end) {
511fe119a6eSNikolay Borisov 		ret = find_first_extent_bit(&info->excluded_extents, start,
5129f21246dSJosef Bacik 					    &extent_start, &extent_end,
5139f21246dSJosef Bacik 					    EXTENT_DIRTY | EXTENT_UPTODATE,
5149f21246dSJosef Bacik 					    NULL);
5159f21246dSJosef Bacik 		if (ret)
5169f21246dSJosef Bacik 			break;
5179f21246dSJosef Bacik 
5189f21246dSJosef Bacik 		if (extent_start <= start) {
5199f21246dSJosef Bacik 			start = extent_end + 1;
5209f21246dSJosef Bacik 		} else if (extent_start > start && extent_start < end) {
5219f21246dSJosef Bacik 			size = extent_start - start;
5229f21246dSJosef Bacik 			total_added += size;
523b0643e59SDennis Zhou 			ret = btrfs_add_free_space_async_trimmed(block_group,
524b0643e59SDennis Zhou 								 start, size);
5259f21246dSJosef Bacik 			BUG_ON(ret); /* -ENOMEM or logic error */
5269f21246dSJosef Bacik 			start = extent_end + 1;
5279f21246dSJosef Bacik 		} else {
5289f21246dSJosef Bacik 			break;
5299f21246dSJosef Bacik 		}
5309f21246dSJosef Bacik 	}
5319f21246dSJosef Bacik 
5329f21246dSJosef Bacik 	if (start < end) {
5339f21246dSJosef Bacik 		size = end - start;
5349f21246dSJosef Bacik 		total_added += size;
535b0643e59SDennis Zhou 		ret = btrfs_add_free_space_async_trimmed(block_group, start,
536b0643e59SDennis Zhou 							 size);
5379f21246dSJosef Bacik 		BUG_ON(ret); /* -ENOMEM or logic error */
5389f21246dSJosef Bacik 	}
5399f21246dSJosef Bacik 
5409f21246dSJosef Bacik 	return total_added;
5419f21246dSJosef Bacik }
5429f21246dSJosef Bacik 
543c7eec3d9SBoris Burkov /*
544c7eec3d9SBoris Burkov  * Get an arbitrary extent item index / max_index through the block group
545c7eec3d9SBoris Burkov  *
546c7eec3d9SBoris Burkov  * @block_group   the block group to sample from
547c7eec3d9SBoris Burkov  * @index:        the integral step through the block group to grab from
548c7eec3d9SBoris Burkov  * @max_index:    the granularity of the sampling
549c7eec3d9SBoris Burkov  * @key:          return value parameter for the item we find
550c7eec3d9SBoris Burkov  *
551c7eec3d9SBoris Burkov  * Pre-conditions on indices:
552c7eec3d9SBoris Burkov  * 0 <= index <= max_index
553c7eec3d9SBoris Burkov  * 0 < max_index
554c7eec3d9SBoris Burkov  *
555c7eec3d9SBoris Burkov  * Returns: 0 on success, 1 if the search didn't yield a useful item, negative
556c7eec3d9SBoris Burkov  * error code on error.
557c7eec3d9SBoris Burkov  */
558c7eec3d9SBoris Burkov static int sample_block_group_extent_item(struct btrfs_caching_control *caching_ctl,
559c7eec3d9SBoris Burkov 					  struct btrfs_block_group *block_group,
560c7eec3d9SBoris Burkov 					  int index, int max_index,
56112148367SBoris Burkov 					  struct btrfs_key *found_key)
562c7eec3d9SBoris Burkov {
563c7eec3d9SBoris Burkov 	struct btrfs_fs_info *fs_info = block_group->fs_info;
564c7eec3d9SBoris Burkov 	struct btrfs_root *extent_root;
565c7eec3d9SBoris Burkov 	u64 search_offset;
566c7eec3d9SBoris Burkov 	u64 search_end = block_group->start + block_group->length;
567c7eec3d9SBoris Burkov 	struct btrfs_path *path;
56812148367SBoris Burkov 	struct btrfs_key search_key;
56912148367SBoris Burkov 	int ret = 0;
570c7eec3d9SBoris Burkov 
571c7eec3d9SBoris Burkov 	ASSERT(index >= 0);
572c7eec3d9SBoris Burkov 	ASSERT(index <= max_index);
573c7eec3d9SBoris Burkov 	ASSERT(max_index > 0);
574c7eec3d9SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
575c7eec3d9SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
576c7eec3d9SBoris Burkov 
577c7eec3d9SBoris Burkov 	path = btrfs_alloc_path();
578c7eec3d9SBoris Burkov 	if (!path)
579c7eec3d9SBoris Burkov 		return -ENOMEM;
580c7eec3d9SBoris Burkov 
581c7eec3d9SBoris Burkov 	extent_root = btrfs_extent_root(fs_info, max_t(u64, block_group->start,
582c7eec3d9SBoris Burkov 						       BTRFS_SUPER_INFO_OFFSET));
583c7eec3d9SBoris Burkov 
584c7eec3d9SBoris Burkov 	path->skip_locking = 1;
585c7eec3d9SBoris Burkov 	path->search_commit_root = 1;
586c7eec3d9SBoris Burkov 	path->reada = READA_FORWARD;
587c7eec3d9SBoris Burkov 
588c7eec3d9SBoris Burkov 	search_offset = index * div_u64(block_group->length, max_index);
58912148367SBoris Burkov 	search_key.objectid = block_group->start + search_offset;
59012148367SBoris Burkov 	search_key.type = BTRFS_EXTENT_ITEM_KEY;
59112148367SBoris Burkov 	search_key.offset = 0;
592c7eec3d9SBoris Burkov 
59312148367SBoris Burkov 	btrfs_for_each_slot(extent_root, &search_key, found_key, path, ret) {
594c7eec3d9SBoris Burkov 		/* Success; sampled an extent item in the block group */
59512148367SBoris Burkov 		if (found_key->type == BTRFS_EXTENT_ITEM_KEY &&
59612148367SBoris Burkov 		    found_key->objectid >= block_group->start &&
59712148367SBoris Burkov 		    found_key->objectid + found_key->offset <= search_end)
59812148367SBoris Burkov 			break;
599c7eec3d9SBoris Burkov 
600c7eec3d9SBoris Burkov 		/* We can't possibly find a valid extent item anymore */
60112148367SBoris Burkov 		if (found_key->objectid >= search_end) {
602c7eec3d9SBoris Burkov 			ret = 1;
603c7eec3d9SBoris Burkov 			break;
604c7eec3d9SBoris Burkov 		}
605c7eec3d9SBoris Burkov 	}
60612148367SBoris Burkov 
607c7eec3d9SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
608c7eec3d9SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
609c7eec3d9SBoris Burkov 	btrfs_free_path(path);
610c7eec3d9SBoris Burkov 	return ret;
611c7eec3d9SBoris Burkov }
612c7eec3d9SBoris Burkov 
613c7eec3d9SBoris Burkov /*
614c7eec3d9SBoris Burkov  * Best effort attempt to compute a block group's size class while caching it.
615c7eec3d9SBoris Burkov  *
616c7eec3d9SBoris Burkov  * @block_group: the block group we are caching
617c7eec3d9SBoris Burkov  *
618c7eec3d9SBoris Burkov  * We cannot infer the size class while adding free space extents, because that
619c7eec3d9SBoris Burkov  * logic doesn't care about contiguous file extents (it doesn't differentiate
620c7eec3d9SBoris Burkov  * between a 100M extent and 100 contiguous 1M extents). So we need to read the
621c7eec3d9SBoris Burkov  * file extent items. Reading all of them is quite wasteful, because usually
622c7eec3d9SBoris Burkov  * only a handful are enough to give a good answer. Therefore, we just grab 5 of
623c7eec3d9SBoris Burkov  * them at even steps through the block group and pick the smallest size class
624c7eec3d9SBoris Burkov  * we see. Since size class is best effort, and not guaranteed in general,
625c7eec3d9SBoris Burkov  * inaccuracy is acceptable.
626c7eec3d9SBoris Burkov  *
627c7eec3d9SBoris Burkov  * To be more explicit about why this algorithm makes sense:
628c7eec3d9SBoris Burkov  *
629c7eec3d9SBoris Burkov  * If we are caching in a block group from disk, then there are three major cases
630c7eec3d9SBoris Burkov  * to consider:
631c7eec3d9SBoris Burkov  * 1. the block group is well behaved and all extents in it are the same size
632c7eec3d9SBoris Burkov  *    class.
633c7eec3d9SBoris Burkov  * 2. the block group is mostly one size class with rare exceptions for last
634c7eec3d9SBoris Burkov  *    ditch allocations
635c7eec3d9SBoris Burkov  * 3. the block group was populated before size classes and can have a totally
636c7eec3d9SBoris Burkov  *    arbitrary mix of size classes.
637c7eec3d9SBoris Burkov  *
638c7eec3d9SBoris Burkov  * In case 1, looking at any extent in the block group will yield the correct
639c7eec3d9SBoris Burkov  * result. For the mixed cases, taking the minimum size class seems like a good
640c7eec3d9SBoris Burkov  * approximation, since gaps from frees will be usable to the size class. For
641c7eec3d9SBoris Burkov  * 2., a small handful of file extents is likely to yield the right answer. For
642c7eec3d9SBoris Burkov  * 3, we can either read every file extent, or admit that this is best effort
643c7eec3d9SBoris Burkov  * anyway and try to stay fast.
644c7eec3d9SBoris Burkov  *
645c7eec3d9SBoris Burkov  * Returns: 0 on success, negative error code on error.
646c7eec3d9SBoris Burkov  */
647c7eec3d9SBoris Burkov static int load_block_group_size_class(struct btrfs_caching_control *caching_ctl,
648c7eec3d9SBoris Burkov 				       struct btrfs_block_group *block_group)
649c7eec3d9SBoris Burkov {
65012148367SBoris Burkov 	struct btrfs_fs_info *fs_info = block_group->fs_info;
651c7eec3d9SBoris Burkov 	struct btrfs_key key;
652c7eec3d9SBoris Burkov 	int i;
653c7eec3d9SBoris Burkov 	u64 min_size = block_group->length;
654c7eec3d9SBoris Burkov 	enum btrfs_block_group_size_class size_class = BTRFS_BG_SZ_NONE;
655c7eec3d9SBoris Burkov 	int ret;
656c7eec3d9SBoris Burkov 
657cb0922f2SBoris Burkov 	if (!btrfs_block_group_should_use_size_class(block_group))
658c7eec3d9SBoris Burkov 		return 0;
659c7eec3d9SBoris Burkov 
66012148367SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
66112148367SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
662c7eec3d9SBoris Burkov 	for (i = 0; i < 5; ++i) {
663c7eec3d9SBoris Burkov 		ret = sample_block_group_extent_item(caching_ctl, block_group, i, 5, &key);
664c7eec3d9SBoris Burkov 		if (ret < 0)
665c7eec3d9SBoris Burkov 			goto out;
666c7eec3d9SBoris Burkov 		if (ret > 0)
667c7eec3d9SBoris Burkov 			continue;
668c7eec3d9SBoris Burkov 		min_size = min_t(u64, min_size, key.offset);
669c7eec3d9SBoris Burkov 		size_class = btrfs_calc_block_group_size_class(min_size);
670c7eec3d9SBoris Burkov 	}
671c7eec3d9SBoris Burkov 	if (size_class != BTRFS_BG_SZ_NONE) {
672c7eec3d9SBoris Burkov 		spin_lock(&block_group->lock);
673c7eec3d9SBoris Burkov 		block_group->size_class = size_class;
674c7eec3d9SBoris Burkov 		spin_unlock(&block_group->lock);
675c7eec3d9SBoris Burkov 	}
676c7eec3d9SBoris Burkov out:
677c7eec3d9SBoris Burkov 	return ret;
678c7eec3d9SBoris Burkov }
679c7eec3d9SBoris Burkov 
6809f21246dSJosef Bacik static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
6819f21246dSJosef Bacik {
68232da5386SDavid Sterba 	struct btrfs_block_group *block_group = caching_ctl->block_group;
6839f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
68429cbcf40SJosef Bacik 	struct btrfs_root *extent_root;
6859f21246dSJosef Bacik 	struct btrfs_path *path;
6869f21246dSJosef Bacik 	struct extent_buffer *leaf;
6879f21246dSJosef Bacik 	struct btrfs_key key;
6889f21246dSJosef Bacik 	u64 total_found = 0;
6899f21246dSJosef Bacik 	u64 last = 0;
6909f21246dSJosef Bacik 	u32 nritems;
6919f21246dSJosef Bacik 	int ret;
6929f21246dSJosef Bacik 	bool wakeup = true;
6939f21246dSJosef Bacik 
6949f21246dSJosef Bacik 	path = btrfs_alloc_path();
6959f21246dSJosef Bacik 	if (!path)
6969f21246dSJosef Bacik 		return -ENOMEM;
6979f21246dSJosef Bacik 
698b3470b5dSDavid Sterba 	last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
69929cbcf40SJosef Bacik 	extent_root = btrfs_extent_root(fs_info, last);
7009f21246dSJosef Bacik 
7019f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
7029f21246dSJosef Bacik 	/*
7039f21246dSJosef Bacik 	 * If we're fragmenting we don't want to make anybody think we can
7049f21246dSJosef Bacik 	 * allocate from this block group until we've had a chance to fragment
7059f21246dSJosef Bacik 	 * the free space.
7069f21246dSJosef Bacik 	 */
7079f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group))
7089f21246dSJosef Bacik 		wakeup = false;
7099f21246dSJosef Bacik #endif
7109f21246dSJosef Bacik 	/*
7119f21246dSJosef Bacik 	 * We don't want to deadlock with somebody trying to allocate a new
7129f21246dSJosef Bacik 	 * extent for the extent root while also trying to search the extent
7139f21246dSJosef Bacik 	 * root to add free space.  So we skip locking and search the commit
7149f21246dSJosef Bacik 	 * root, since its read-only
7159f21246dSJosef Bacik 	 */
7169f21246dSJosef Bacik 	path->skip_locking = 1;
7179f21246dSJosef Bacik 	path->search_commit_root = 1;
7189f21246dSJosef Bacik 	path->reada = READA_FORWARD;
7199f21246dSJosef Bacik 
7209f21246dSJosef Bacik 	key.objectid = last;
7219f21246dSJosef Bacik 	key.offset = 0;
7229f21246dSJosef Bacik 	key.type = BTRFS_EXTENT_ITEM_KEY;
7239f21246dSJosef Bacik 
7249f21246dSJosef Bacik next:
7259f21246dSJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
7269f21246dSJosef Bacik 	if (ret < 0)
7279f21246dSJosef Bacik 		goto out;
7289f21246dSJosef Bacik 
7299f21246dSJosef Bacik 	leaf = path->nodes[0];
7309f21246dSJosef Bacik 	nritems = btrfs_header_nritems(leaf);
7319f21246dSJosef Bacik 
7329f21246dSJosef Bacik 	while (1) {
7339f21246dSJosef Bacik 		if (btrfs_fs_closing(fs_info) > 1) {
7349f21246dSJosef Bacik 			last = (u64)-1;
7359f21246dSJosef Bacik 			break;
7369f21246dSJosef Bacik 		}
7379f21246dSJosef Bacik 
7389f21246dSJosef Bacik 		if (path->slots[0] < nritems) {
7399f21246dSJosef Bacik 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7409f21246dSJosef Bacik 		} else {
7419f21246dSJosef Bacik 			ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
7429f21246dSJosef Bacik 			if (ret)
7439f21246dSJosef Bacik 				break;
7449f21246dSJosef Bacik 
7459f21246dSJosef Bacik 			if (need_resched() ||
7469f21246dSJosef Bacik 			    rwsem_is_contended(&fs_info->commit_root_sem)) {
7479f21246dSJosef Bacik 				btrfs_release_path(path);
7489f21246dSJosef Bacik 				up_read(&fs_info->commit_root_sem);
7499f21246dSJosef Bacik 				mutex_unlock(&caching_ctl->mutex);
7509f21246dSJosef Bacik 				cond_resched();
7519f21246dSJosef Bacik 				mutex_lock(&caching_ctl->mutex);
7529f21246dSJosef Bacik 				down_read(&fs_info->commit_root_sem);
7539f21246dSJosef Bacik 				goto next;
7549f21246dSJosef Bacik 			}
7559f21246dSJosef Bacik 
7569f21246dSJosef Bacik 			ret = btrfs_next_leaf(extent_root, path);
7579f21246dSJosef Bacik 			if (ret < 0)
7589f21246dSJosef Bacik 				goto out;
7599f21246dSJosef Bacik 			if (ret)
7609f21246dSJosef Bacik 				break;
7619f21246dSJosef Bacik 			leaf = path->nodes[0];
7629f21246dSJosef Bacik 			nritems = btrfs_header_nritems(leaf);
7639f21246dSJosef Bacik 			continue;
7649f21246dSJosef Bacik 		}
7659f21246dSJosef Bacik 
7669f21246dSJosef Bacik 		if (key.objectid < last) {
7679f21246dSJosef Bacik 			key.objectid = last;
7689f21246dSJosef Bacik 			key.offset = 0;
7699f21246dSJosef Bacik 			key.type = BTRFS_EXTENT_ITEM_KEY;
7709f21246dSJosef Bacik 			btrfs_release_path(path);
7719f21246dSJosef Bacik 			goto next;
7729f21246dSJosef Bacik 		}
7739f21246dSJosef Bacik 
774b3470b5dSDavid Sterba 		if (key.objectid < block_group->start) {
7759f21246dSJosef Bacik 			path->slots[0]++;
7769f21246dSJosef Bacik 			continue;
7779f21246dSJosef Bacik 		}
7789f21246dSJosef Bacik 
779b3470b5dSDavid Sterba 		if (key.objectid >= block_group->start + block_group->length)
7809f21246dSJosef Bacik 			break;
7819f21246dSJosef Bacik 
7829f21246dSJosef Bacik 		if (key.type == BTRFS_EXTENT_ITEM_KEY ||
7839f21246dSJosef Bacik 		    key.type == BTRFS_METADATA_ITEM_KEY) {
7849f21246dSJosef Bacik 			total_found += add_new_free_space(block_group, last,
7859f21246dSJosef Bacik 							  key.objectid);
7869f21246dSJosef Bacik 			if (key.type == BTRFS_METADATA_ITEM_KEY)
7879f21246dSJosef Bacik 				last = key.objectid +
7889f21246dSJosef Bacik 					fs_info->nodesize;
7899f21246dSJosef Bacik 			else
7909f21246dSJosef Bacik 				last = key.objectid + key.offset;
7919f21246dSJosef Bacik 
7929f21246dSJosef Bacik 			if (total_found > CACHING_CTL_WAKE_UP) {
7939f21246dSJosef Bacik 				total_found = 0;
7949f21246dSJosef Bacik 				if (wakeup)
7959f21246dSJosef Bacik 					wake_up(&caching_ctl->wait);
7969f21246dSJosef Bacik 			}
7979f21246dSJosef Bacik 		}
7989f21246dSJosef Bacik 		path->slots[0]++;
7999f21246dSJosef Bacik 	}
8009f21246dSJosef Bacik 	ret = 0;
8019f21246dSJosef Bacik 
8029f21246dSJosef Bacik 	total_found += add_new_free_space(block_group, last,
803b3470b5dSDavid Sterba 				block_group->start + block_group->length);
8049f21246dSJosef Bacik 
8059f21246dSJosef Bacik out:
8069f21246dSJosef Bacik 	btrfs_free_path(path);
8079f21246dSJosef Bacik 	return ret;
8089f21246dSJosef Bacik }
8099f21246dSJosef Bacik 
8109f21246dSJosef Bacik static noinline void caching_thread(struct btrfs_work *work)
8119f21246dSJosef Bacik {
81232da5386SDavid Sterba 	struct btrfs_block_group *block_group;
8139f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info;
8149f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
8159f21246dSJosef Bacik 	int ret;
8169f21246dSJosef Bacik 
8179f21246dSJosef Bacik 	caching_ctl = container_of(work, struct btrfs_caching_control, work);
8189f21246dSJosef Bacik 	block_group = caching_ctl->block_group;
8199f21246dSJosef Bacik 	fs_info = block_group->fs_info;
8209f21246dSJosef Bacik 
8219f21246dSJosef Bacik 	mutex_lock(&caching_ctl->mutex);
8229f21246dSJosef Bacik 	down_read(&fs_info->commit_root_sem);
8239f21246dSJosef Bacik 
824c7eec3d9SBoris Burkov 	load_block_group_size_class(caching_ctl, block_group);
825e747853cSJosef Bacik 	if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
826e747853cSJosef Bacik 		ret = load_free_space_cache(block_group);
827e747853cSJosef Bacik 		if (ret == 1) {
828e747853cSJosef Bacik 			ret = 0;
829e747853cSJosef Bacik 			goto done;
830e747853cSJosef Bacik 		}
831e747853cSJosef Bacik 
832e747853cSJosef Bacik 		/*
833e747853cSJosef Bacik 		 * We failed to load the space cache, set ourselves to
834e747853cSJosef Bacik 		 * CACHE_STARTED and carry on.
835e747853cSJosef Bacik 		 */
836e747853cSJosef Bacik 		spin_lock(&block_group->lock);
837e747853cSJosef Bacik 		block_group->cached = BTRFS_CACHE_STARTED;
838e747853cSJosef Bacik 		spin_unlock(&block_group->lock);
839e747853cSJosef Bacik 		wake_up(&caching_ctl->wait);
840e747853cSJosef Bacik 	}
841e747853cSJosef Bacik 
8422f96e402SJosef Bacik 	/*
8432f96e402SJosef Bacik 	 * If we are in the transaction that populated the free space tree we
8442f96e402SJosef Bacik 	 * can't actually cache from the free space tree as our commit root and
8452f96e402SJosef Bacik 	 * real root are the same, so we could change the contents of the blocks
8462f96e402SJosef Bacik 	 * while caching.  Instead do the slow caching in this case, and after
8472f96e402SJosef Bacik 	 * the transaction has committed we will be safe.
8482f96e402SJosef Bacik 	 */
8492f96e402SJosef Bacik 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
8502f96e402SJosef Bacik 	    !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
8519f21246dSJosef Bacik 		ret = load_free_space_tree(caching_ctl);
8529f21246dSJosef Bacik 	else
8539f21246dSJosef Bacik 		ret = load_extent_tree_free(caching_ctl);
854e747853cSJosef Bacik done:
8559f21246dSJosef Bacik 	spin_lock(&block_group->lock);
8569f21246dSJosef Bacik 	block_group->caching_ctl = NULL;
8579f21246dSJosef Bacik 	block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
8589f21246dSJosef Bacik 	spin_unlock(&block_group->lock);
8599f21246dSJosef Bacik 
8609f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
8619f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group)) {
8629f21246dSJosef Bacik 		u64 bytes_used;
8639f21246dSJosef Bacik 
8649f21246dSJosef Bacik 		spin_lock(&block_group->space_info->lock);
8659f21246dSJosef Bacik 		spin_lock(&block_group->lock);
866b3470b5dSDavid Sterba 		bytes_used = block_group->length - block_group->used;
8679f21246dSJosef Bacik 		block_group->space_info->bytes_used += bytes_used >> 1;
8689f21246dSJosef Bacik 		spin_unlock(&block_group->lock);
8699f21246dSJosef Bacik 		spin_unlock(&block_group->space_info->lock);
870e11c0406SJosef Bacik 		fragment_free_space(block_group);
8719f21246dSJosef Bacik 	}
8729f21246dSJosef Bacik #endif
8739f21246dSJosef Bacik 
8749f21246dSJosef Bacik 	up_read(&fs_info->commit_root_sem);
8759f21246dSJosef Bacik 	btrfs_free_excluded_extents(block_group);
8769f21246dSJosef Bacik 	mutex_unlock(&caching_ctl->mutex);
8779f21246dSJosef Bacik 
8789f21246dSJosef Bacik 	wake_up(&caching_ctl->wait);
8799f21246dSJosef Bacik 
8809f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
8819f21246dSJosef Bacik 	btrfs_put_block_group(block_group);
8829f21246dSJosef Bacik }
8839f21246dSJosef Bacik 
884ced8ecf0SOmar Sandoval int btrfs_cache_block_group(struct btrfs_block_group *cache, bool wait)
8859f21246dSJosef Bacik {
8869f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
887e747853cSJosef Bacik 	struct btrfs_caching_control *caching_ctl = NULL;
8889f21246dSJosef Bacik 	int ret = 0;
8899f21246dSJosef Bacik 
8902eda5708SNaohiro Aota 	/* Allocator for zoned filesystems does not use the cache at all */
8912eda5708SNaohiro Aota 	if (btrfs_is_zoned(fs_info))
8922eda5708SNaohiro Aota 		return 0;
8932eda5708SNaohiro Aota 
8949f21246dSJosef Bacik 	caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
8959f21246dSJosef Bacik 	if (!caching_ctl)
8969f21246dSJosef Bacik 		return -ENOMEM;
8979f21246dSJosef Bacik 
8989f21246dSJosef Bacik 	INIT_LIST_HEAD(&caching_ctl->list);
8999f21246dSJosef Bacik 	mutex_init(&caching_ctl->mutex);
9009f21246dSJosef Bacik 	init_waitqueue_head(&caching_ctl->wait);
9019f21246dSJosef Bacik 	caching_ctl->block_group = cache;
902e747853cSJosef Bacik 	refcount_set(&caching_ctl->count, 2);
903a0cac0ecSOmar Sandoval 	btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
9049f21246dSJosef Bacik 
9059f21246dSJosef Bacik 	spin_lock(&cache->lock);
9069f21246dSJosef Bacik 	if (cache->cached != BTRFS_CACHE_NO) {
9079f21246dSJosef Bacik 		kfree(caching_ctl);
908e747853cSJosef Bacik 
909e747853cSJosef Bacik 		caching_ctl = cache->caching_ctl;
910e747853cSJosef Bacik 		if (caching_ctl)
911e747853cSJosef Bacik 			refcount_inc(&caching_ctl->count);
912e747853cSJosef Bacik 		spin_unlock(&cache->lock);
913e747853cSJosef Bacik 		goto out;
9149f21246dSJosef Bacik 	}
9159f21246dSJosef Bacik 	WARN_ON(cache->caching_ctl);
9169f21246dSJosef Bacik 	cache->caching_ctl = caching_ctl;
9179f21246dSJosef Bacik 	cache->cached = BTRFS_CACHE_STARTED;
9189f21246dSJosef Bacik 	spin_unlock(&cache->lock);
9199f21246dSJosef Bacik 
92016b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
9219f21246dSJosef Bacik 	refcount_inc(&caching_ctl->count);
9229f21246dSJosef Bacik 	list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
92316b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
9249f21246dSJosef Bacik 
9259f21246dSJosef Bacik 	btrfs_get_block_group(cache);
9269f21246dSJosef Bacik 
9279f21246dSJosef Bacik 	btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
928e747853cSJosef Bacik out:
929ced8ecf0SOmar Sandoval 	if (wait && caching_ctl)
930ced8ecf0SOmar Sandoval 		ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
931e747853cSJosef Bacik 	if (caching_ctl)
932e747853cSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
9339f21246dSJosef Bacik 
9349f21246dSJosef Bacik 	return ret;
9359f21246dSJosef Bacik }
936e3e0520bSJosef Bacik 
937e3e0520bSJosef Bacik static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
938e3e0520bSJosef Bacik {
939e3e0520bSJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
940e3e0520bSJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
941e3e0520bSJosef Bacik 
942e3e0520bSJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
943e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
944e3e0520bSJosef Bacik 		fs_info->avail_data_alloc_bits &= ~extra_flags;
945e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
946e3e0520bSJosef Bacik 		fs_info->avail_metadata_alloc_bits &= ~extra_flags;
947e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
948e3e0520bSJosef Bacik 		fs_info->avail_system_alloc_bits &= ~extra_flags;
949e3e0520bSJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
950e3e0520bSJosef Bacik }
951e3e0520bSJosef Bacik 
952e3e0520bSJosef Bacik /*
953e3e0520bSJosef Bacik  * Clear incompat bits for the following feature(s):
954e3e0520bSJosef Bacik  *
955e3e0520bSJosef Bacik  * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
956e3e0520bSJosef Bacik  *            in the whole filesystem
9579c907446SDavid Sterba  *
9589c907446SDavid Sterba  * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
959e3e0520bSJosef Bacik  */
960e3e0520bSJosef Bacik static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
961e3e0520bSJosef Bacik {
9629c907446SDavid Sterba 	bool found_raid56 = false;
9639c907446SDavid Sterba 	bool found_raid1c34 = false;
9649c907446SDavid Sterba 
9659c907446SDavid Sterba 	if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
9669c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
9679c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
968e3e0520bSJosef Bacik 		struct list_head *head = &fs_info->space_info;
969e3e0520bSJosef Bacik 		struct btrfs_space_info *sinfo;
970e3e0520bSJosef Bacik 
971e3e0520bSJosef Bacik 		list_for_each_entry_rcu(sinfo, head, list) {
972e3e0520bSJosef Bacik 			down_read(&sinfo->groups_sem);
973e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
9749c907446SDavid Sterba 				found_raid56 = true;
975e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
9769c907446SDavid Sterba 				found_raid56 = true;
9779c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
9789c907446SDavid Sterba 				found_raid1c34 = true;
9799c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
9809c907446SDavid Sterba 				found_raid1c34 = true;
981e3e0520bSJosef Bacik 			up_read(&sinfo->groups_sem);
982e3e0520bSJosef Bacik 		}
983d8e6fd5cSFilipe Manana 		if (!found_raid56)
984e3e0520bSJosef Bacik 			btrfs_clear_fs_incompat(fs_info, RAID56);
985d8e6fd5cSFilipe Manana 		if (!found_raid1c34)
9869c907446SDavid Sterba 			btrfs_clear_fs_incompat(fs_info, RAID1C34);
987e3e0520bSJosef Bacik 	}
988e3e0520bSJosef Bacik }
989e3e0520bSJosef Bacik 
9907357623aSQu Wenruo static int remove_block_group_item(struct btrfs_trans_handle *trans,
9917357623aSQu Wenruo 				   struct btrfs_path *path,
9927357623aSQu Wenruo 				   struct btrfs_block_group *block_group)
9937357623aSQu Wenruo {
9947357623aSQu Wenruo 	struct btrfs_fs_info *fs_info = trans->fs_info;
9957357623aSQu Wenruo 	struct btrfs_root *root;
9967357623aSQu Wenruo 	struct btrfs_key key;
9977357623aSQu Wenruo 	int ret;
9987357623aSQu Wenruo 
999dfe8aec4SJosef Bacik 	root = btrfs_block_group_root(fs_info);
10007357623aSQu Wenruo 	key.objectid = block_group->start;
10017357623aSQu Wenruo 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
10027357623aSQu Wenruo 	key.offset = block_group->length;
10037357623aSQu Wenruo 
10047357623aSQu Wenruo 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10057357623aSQu Wenruo 	if (ret > 0)
10067357623aSQu Wenruo 		ret = -ENOENT;
10077357623aSQu Wenruo 	if (ret < 0)
10087357623aSQu Wenruo 		return ret;
10097357623aSQu Wenruo 
10107357623aSQu Wenruo 	ret = btrfs_del_item(trans, root, path);
10117357623aSQu Wenruo 	return ret;
10127357623aSQu Wenruo }
10137357623aSQu Wenruo 
1014e3e0520bSJosef Bacik int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
1015e3e0520bSJosef Bacik 			     u64 group_start, struct extent_map *em)
1016e3e0520bSJosef Bacik {
1017e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
1018e3e0520bSJosef Bacik 	struct btrfs_path *path;
101932da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1020e3e0520bSJosef Bacik 	struct btrfs_free_cluster *cluster;
1021e3e0520bSJosef Bacik 	struct inode *inode;
1022e3e0520bSJosef Bacik 	struct kobject *kobj = NULL;
1023e3e0520bSJosef Bacik 	int ret;
1024e3e0520bSJosef Bacik 	int index;
1025e3e0520bSJosef Bacik 	int factor;
1026e3e0520bSJosef Bacik 	struct btrfs_caching_control *caching_ctl = NULL;
1027e3e0520bSJosef Bacik 	bool remove_em;
1028e3e0520bSJosef Bacik 	bool remove_rsv = false;
1029e3e0520bSJosef Bacik 
1030e3e0520bSJosef Bacik 	block_group = btrfs_lookup_block_group(fs_info, group_start);
1031e3e0520bSJosef Bacik 	BUG_ON(!block_group);
1032e3e0520bSJosef Bacik 	BUG_ON(!block_group->ro);
1033e3e0520bSJosef Bacik 
1034e3e0520bSJosef Bacik 	trace_btrfs_remove_block_group(block_group);
1035e3e0520bSJosef Bacik 	/*
1036e3e0520bSJosef Bacik 	 * Free the reserved super bytes from this block group before
1037e3e0520bSJosef Bacik 	 * remove it.
1038e3e0520bSJosef Bacik 	 */
1039e3e0520bSJosef Bacik 	btrfs_free_excluded_extents(block_group);
1040b3470b5dSDavid Sterba 	btrfs_free_ref_tree_range(fs_info, block_group->start,
1041b3470b5dSDavid Sterba 				  block_group->length);
1042e3e0520bSJosef Bacik 
1043e3e0520bSJosef Bacik 	index = btrfs_bg_flags_to_raid_index(block_group->flags);
1044e3e0520bSJosef Bacik 	factor = btrfs_bg_type_to_factor(block_group->flags);
1045e3e0520bSJosef Bacik 
1046e3e0520bSJosef Bacik 	/* make sure this block group isn't part of an allocation cluster */
1047e3e0520bSJosef Bacik 	cluster = &fs_info->data_alloc_cluster;
1048e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
1049e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
1050e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
1051e3e0520bSJosef Bacik 
1052e3e0520bSJosef Bacik 	/*
1053e3e0520bSJosef Bacik 	 * make sure this block group isn't part of a metadata
1054e3e0520bSJosef Bacik 	 * allocation cluster
1055e3e0520bSJosef Bacik 	 */
1056e3e0520bSJosef Bacik 	cluster = &fs_info->meta_alloc_cluster;
1057e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
1058e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
1059e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
1060e3e0520bSJosef Bacik 
106140ab3be1SNaohiro Aota 	btrfs_clear_treelog_bg(block_group);
1062c2707a25SJohannes Thumshirn 	btrfs_clear_data_reloc_bg(block_group);
106340ab3be1SNaohiro Aota 
1064e3e0520bSJosef Bacik 	path = btrfs_alloc_path();
1065e3e0520bSJosef Bacik 	if (!path) {
1066e3e0520bSJosef Bacik 		ret = -ENOMEM;
10679fecd132SFilipe Manana 		goto out;
1068e3e0520bSJosef Bacik 	}
1069e3e0520bSJosef Bacik 
1070e3e0520bSJosef Bacik 	/*
1071e3e0520bSJosef Bacik 	 * get the inode first so any iput calls done for the io_list
1072e3e0520bSJosef Bacik 	 * aren't the final iput (no unlinks allowed now)
1073e3e0520bSJosef Bacik 	 */
1074e3e0520bSJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
1075e3e0520bSJosef Bacik 
1076e3e0520bSJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
1077e3e0520bSJosef Bacik 	/*
1078e3e0520bSJosef Bacik 	 * Make sure our free space cache IO is done before removing the
1079e3e0520bSJosef Bacik 	 * free space inode
1080e3e0520bSJosef Bacik 	 */
1081e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
1082e3e0520bSJosef Bacik 	if (!list_empty(&block_group->io_list)) {
1083e3e0520bSJosef Bacik 		list_del_init(&block_group->io_list);
1084e3e0520bSJosef Bacik 
1085e3e0520bSJosef Bacik 		WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
1086e3e0520bSJosef Bacik 
1087e3e0520bSJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
1088e3e0520bSJosef Bacik 		btrfs_wait_cache_io(trans, block_group, path);
1089e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1090e3e0520bSJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
1091e3e0520bSJosef Bacik 	}
1092e3e0520bSJosef Bacik 
1093e3e0520bSJosef Bacik 	if (!list_empty(&block_group->dirty_list)) {
1094e3e0520bSJosef Bacik 		list_del_init(&block_group->dirty_list);
1095e3e0520bSJosef Bacik 		remove_rsv = true;
1096e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1097e3e0520bSJosef Bacik 	}
1098e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1099e3e0520bSJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
1100e3e0520bSJosef Bacik 
110136b216c8SBoris Burkov 	ret = btrfs_remove_free_space_inode(trans, inode, block_group);
1102e3e0520bSJosef Bacik 	if (ret)
11039fecd132SFilipe Manana 		goto out;
1104e3e0520bSJosef Bacik 
110516b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
110608dddb29SFilipe Manana 	rb_erase_cached(&block_group->cache_node,
1107e3e0520bSJosef Bacik 			&fs_info->block_group_cache_tree);
1108e3e0520bSJosef Bacik 	RB_CLEAR_NODE(&block_group->cache_node);
1109e3e0520bSJosef Bacik 
11109fecd132SFilipe Manana 	/* Once for the block groups rbtree */
11119fecd132SFilipe Manana 	btrfs_put_block_group(block_group);
11129fecd132SFilipe Manana 
111316b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
1114e3e0520bSJosef Bacik 
1115e3e0520bSJosef Bacik 	down_write(&block_group->space_info->groups_sem);
1116e3e0520bSJosef Bacik 	/*
1117e3e0520bSJosef Bacik 	 * we must use list_del_init so people can check to see if they
1118e3e0520bSJosef Bacik 	 * are still on the list after taking the semaphore
1119e3e0520bSJosef Bacik 	 */
1120e3e0520bSJosef Bacik 	list_del_init(&block_group->list);
1121e3e0520bSJosef Bacik 	if (list_empty(&block_group->space_info->block_groups[index])) {
1122e3e0520bSJosef Bacik 		kobj = block_group->space_info->block_group_kobjs[index];
1123e3e0520bSJosef Bacik 		block_group->space_info->block_group_kobjs[index] = NULL;
1124e3e0520bSJosef Bacik 		clear_avail_alloc_bits(fs_info, block_group->flags);
1125e3e0520bSJosef Bacik 	}
1126e3e0520bSJosef Bacik 	up_write(&block_group->space_info->groups_sem);
1127e3e0520bSJosef Bacik 	clear_incompat_bg_bits(fs_info, block_group->flags);
1128e3e0520bSJosef Bacik 	if (kobj) {
1129e3e0520bSJosef Bacik 		kobject_del(kobj);
1130e3e0520bSJosef Bacik 		kobject_put(kobj);
1131e3e0520bSJosef Bacik 	}
1132e3e0520bSJosef Bacik 
1133e3e0520bSJosef Bacik 	if (block_group->cached == BTRFS_CACHE_STARTED)
1134e3e0520bSJosef Bacik 		btrfs_wait_block_group_cache_done(block_group);
11357b9c293bSJosef Bacik 
113616b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
11377b9c293bSJosef Bacik 	caching_ctl = btrfs_get_caching_control(block_group);
1138e3e0520bSJosef Bacik 	if (!caching_ctl) {
1139e3e0520bSJosef Bacik 		struct btrfs_caching_control *ctl;
1140e3e0520bSJosef Bacik 
11417b9c293bSJosef Bacik 		list_for_each_entry(ctl, &fs_info->caching_block_groups, list) {
1142e3e0520bSJosef Bacik 			if (ctl->block_group == block_group) {
1143e3e0520bSJosef Bacik 				caching_ctl = ctl;
1144e3e0520bSJosef Bacik 				refcount_inc(&caching_ctl->count);
1145e3e0520bSJosef Bacik 				break;
1146e3e0520bSJosef Bacik 			}
1147e3e0520bSJosef Bacik 		}
11487b9c293bSJosef Bacik 	}
1149e3e0520bSJosef Bacik 	if (caching_ctl)
1150e3e0520bSJosef Bacik 		list_del_init(&caching_ctl->list);
115116b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
11527b9c293bSJosef Bacik 
1153e3e0520bSJosef Bacik 	if (caching_ctl) {
1154e3e0520bSJosef Bacik 		/* Once for the caching bgs list and once for us. */
1155e3e0520bSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
1156e3e0520bSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
1157e3e0520bSJosef Bacik 	}
1158e3e0520bSJosef Bacik 
1159e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
1160e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->dirty_list));
1161e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->io_list));
1162e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1163e3e0520bSJosef Bacik 
1164e3e0520bSJosef Bacik 	btrfs_remove_free_space_cache(block_group);
1165e3e0520bSJosef Bacik 
1166e3e0520bSJosef Bacik 	spin_lock(&block_group->space_info->lock);
1167e3e0520bSJosef Bacik 	list_del_init(&block_group->ro_list);
1168e3e0520bSJosef Bacik 
1169e3e0520bSJosef Bacik 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1170e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->total_bytes
1171b3470b5dSDavid Sterba 			< block_group->length);
1172e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->bytes_readonly
1173169e0da9SNaohiro Aota 			< block_group->length - block_group->zone_unusable);
1174169e0da9SNaohiro Aota 		WARN_ON(block_group->space_info->bytes_zone_unusable
1175169e0da9SNaohiro Aota 			< block_group->zone_unusable);
1176e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->disk_total
1177b3470b5dSDavid Sterba 			< block_group->length * factor);
11783349b57fSJosef Bacik 		WARN_ON(test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE,
11793349b57fSJosef Bacik 				 &block_group->runtime_flags) &&
11806a921de5SNaohiro Aota 			block_group->space_info->active_total_bytes
11816a921de5SNaohiro Aota 			< block_group->length);
1182e3e0520bSJosef Bacik 	}
1183b3470b5dSDavid Sterba 	block_group->space_info->total_bytes -= block_group->length;
11843349b57fSJosef Bacik 	if (test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags))
11856a921de5SNaohiro Aota 		block_group->space_info->active_total_bytes -= block_group->length;
1186169e0da9SNaohiro Aota 	block_group->space_info->bytes_readonly -=
1187169e0da9SNaohiro Aota 		(block_group->length - block_group->zone_unusable);
1188169e0da9SNaohiro Aota 	block_group->space_info->bytes_zone_unusable -=
1189169e0da9SNaohiro Aota 		block_group->zone_unusable;
1190b3470b5dSDavid Sterba 	block_group->space_info->disk_total -= block_group->length * factor;
1191e3e0520bSJosef Bacik 
1192e3e0520bSJosef Bacik 	spin_unlock(&block_group->space_info->lock);
1193e3e0520bSJosef Bacik 
1194ffcb9d44SFilipe Manana 	/*
1195ffcb9d44SFilipe Manana 	 * Remove the free space for the block group from the free space tree
1196ffcb9d44SFilipe Manana 	 * and the block group's item from the extent tree before marking the
1197ffcb9d44SFilipe Manana 	 * block group as removed. This is to prevent races with tasks that
1198ffcb9d44SFilipe Manana 	 * freeze and unfreeze a block group, this task and another task
1199ffcb9d44SFilipe Manana 	 * allocating a new block group - the unfreeze task ends up removing
1200ffcb9d44SFilipe Manana 	 * the block group's extent map before the task calling this function
1201ffcb9d44SFilipe Manana 	 * deletes the block group item from the extent tree, allowing for
1202ffcb9d44SFilipe Manana 	 * another task to attempt to create another block group with the same
1203ffcb9d44SFilipe Manana 	 * item key (and failing with -EEXIST and a transaction abort).
1204ffcb9d44SFilipe Manana 	 */
1205ffcb9d44SFilipe Manana 	ret = remove_block_group_free_space(trans, block_group);
1206ffcb9d44SFilipe Manana 	if (ret)
1207ffcb9d44SFilipe Manana 		goto out;
1208ffcb9d44SFilipe Manana 
1209ffcb9d44SFilipe Manana 	ret = remove_block_group_item(trans, path, block_group);
1210ffcb9d44SFilipe Manana 	if (ret < 0)
1211ffcb9d44SFilipe Manana 		goto out;
1212ffcb9d44SFilipe Manana 
1213e3e0520bSJosef Bacik 	spin_lock(&block_group->lock);
12143349b57fSJosef Bacik 	set_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags);
12153349b57fSJosef Bacik 
1216e3e0520bSJosef Bacik 	/*
12176b7304afSFilipe Manana 	 * At this point trimming or scrub can't start on this block group,
12186b7304afSFilipe Manana 	 * because we removed the block group from the rbtree
12196b7304afSFilipe Manana 	 * fs_info->block_group_cache_tree so no one can't find it anymore and
12206b7304afSFilipe Manana 	 * even if someone already got this block group before we removed it
12216b7304afSFilipe Manana 	 * from the rbtree, they have already incremented block_group->frozen -
12226b7304afSFilipe Manana 	 * if they didn't, for the trimming case they won't find any free space
12236b7304afSFilipe Manana 	 * entries because we already removed them all when we called
12246b7304afSFilipe Manana 	 * btrfs_remove_free_space_cache().
1225e3e0520bSJosef Bacik 	 *
1226e3e0520bSJosef Bacik 	 * And we must not remove the extent map from the fs_info->mapping_tree
1227e3e0520bSJosef Bacik 	 * to prevent the same logical address range and physical device space
12286b7304afSFilipe Manana 	 * ranges from being reused for a new block group. This is needed to
12296b7304afSFilipe Manana 	 * avoid races with trimming and scrub.
12306b7304afSFilipe Manana 	 *
12316b7304afSFilipe Manana 	 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1232e3e0520bSJosef Bacik 	 * completely transactionless, so while it is trimming a range the
1233e3e0520bSJosef Bacik 	 * currently running transaction might finish and a new one start,
1234e3e0520bSJosef Bacik 	 * allowing for new block groups to be created that can reuse the same
1235e3e0520bSJosef Bacik 	 * physical device locations unless we take this special care.
1236e3e0520bSJosef Bacik 	 *
1237e3e0520bSJosef Bacik 	 * There may also be an implicit trim operation if the file system
1238e3e0520bSJosef Bacik 	 * is mounted with -odiscard. The same protections must remain
1239e3e0520bSJosef Bacik 	 * in place until the extents have been discarded completely when
1240e3e0520bSJosef Bacik 	 * the transaction commit has completed.
1241e3e0520bSJosef Bacik 	 */
12426b7304afSFilipe Manana 	remove_em = (atomic_read(&block_group->frozen) == 0);
1243e3e0520bSJosef Bacik 	spin_unlock(&block_group->lock);
1244e3e0520bSJosef Bacik 
1245e3e0520bSJosef Bacik 	if (remove_em) {
1246e3e0520bSJosef Bacik 		struct extent_map_tree *em_tree;
1247e3e0520bSJosef Bacik 
1248e3e0520bSJosef Bacik 		em_tree = &fs_info->mapping_tree;
1249e3e0520bSJosef Bacik 		write_lock(&em_tree->lock);
1250e3e0520bSJosef Bacik 		remove_extent_mapping(em_tree, em);
1251e3e0520bSJosef Bacik 		write_unlock(&em_tree->lock);
1252e3e0520bSJosef Bacik 		/* once for the tree */
1253e3e0520bSJosef Bacik 		free_extent_map(em);
1254e3e0520bSJosef Bacik 	}
1255f6033c5eSXiyu Yang 
12569fecd132SFilipe Manana out:
1257f6033c5eSXiyu Yang 	/* Once for the lookup reference */
1258f6033c5eSXiyu Yang 	btrfs_put_block_group(block_group);
1259e3e0520bSJosef Bacik 	if (remove_rsv)
1260e3e0520bSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
1261e3e0520bSJosef Bacik 	btrfs_free_path(path);
1262e3e0520bSJosef Bacik 	return ret;
1263e3e0520bSJosef Bacik }
1264e3e0520bSJosef Bacik 
1265e3e0520bSJosef Bacik struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1266e3e0520bSJosef Bacik 		struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1267e3e0520bSJosef Bacik {
1268dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
1269e3e0520bSJosef Bacik 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1270e3e0520bSJosef Bacik 	struct extent_map *em;
1271e3e0520bSJosef Bacik 	struct map_lookup *map;
1272e3e0520bSJosef Bacik 	unsigned int num_items;
1273e3e0520bSJosef Bacik 
1274e3e0520bSJosef Bacik 	read_lock(&em_tree->lock);
1275e3e0520bSJosef Bacik 	em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1276e3e0520bSJosef Bacik 	read_unlock(&em_tree->lock);
1277e3e0520bSJosef Bacik 	ASSERT(em && em->start == chunk_offset);
1278e3e0520bSJosef Bacik 
1279e3e0520bSJosef Bacik 	/*
1280e3e0520bSJosef Bacik 	 * We need to reserve 3 + N units from the metadata space info in order
1281e3e0520bSJosef Bacik 	 * to remove a block group (done at btrfs_remove_chunk() and at
1282e3e0520bSJosef Bacik 	 * btrfs_remove_block_group()), which are used for:
1283e3e0520bSJosef Bacik 	 *
1284e3e0520bSJosef Bacik 	 * 1 unit for adding the free space inode's orphan (located in the tree
1285e3e0520bSJosef Bacik 	 * of tree roots).
1286e3e0520bSJosef Bacik 	 * 1 unit for deleting the block group item (located in the extent
1287e3e0520bSJosef Bacik 	 * tree).
1288e3e0520bSJosef Bacik 	 * 1 unit for deleting the free space item (located in tree of tree
1289e3e0520bSJosef Bacik 	 * roots).
1290e3e0520bSJosef Bacik 	 * N units for deleting N device extent items corresponding to each
1291e3e0520bSJosef Bacik 	 * stripe (located in the device tree).
1292e3e0520bSJosef Bacik 	 *
1293e3e0520bSJosef Bacik 	 * In order to remove a block group we also need to reserve units in the
1294e3e0520bSJosef Bacik 	 * system space info in order to update the chunk tree (update one or
1295e3e0520bSJosef Bacik 	 * more device items and remove one chunk item), but this is done at
1296e3e0520bSJosef Bacik 	 * btrfs_remove_chunk() through a call to check_system_chunk().
1297e3e0520bSJosef Bacik 	 */
1298e3e0520bSJosef Bacik 	map = em->map_lookup;
1299e3e0520bSJosef Bacik 	num_items = 3 + map->num_stripes;
1300e3e0520bSJosef Bacik 	free_extent_map(em);
1301e3e0520bSJosef Bacik 
1302dfe8aec4SJosef Bacik 	return btrfs_start_transaction_fallback_global_rsv(root, num_items);
1303e3e0520bSJosef Bacik }
1304e3e0520bSJosef Bacik 
1305e3e0520bSJosef Bacik /*
130626ce2095SJosef Bacik  * Mark block group @cache read-only, so later write won't happen to block
130726ce2095SJosef Bacik  * group @cache.
130826ce2095SJosef Bacik  *
130926ce2095SJosef Bacik  * If @force is not set, this function will only mark the block group readonly
131026ce2095SJosef Bacik  * if we have enough free space (1M) in other metadata/system block groups.
131126ce2095SJosef Bacik  * If @force is not set, this function will mark the block group readonly
131226ce2095SJosef Bacik  * without checking free space.
131326ce2095SJosef Bacik  *
131426ce2095SJosef Bacik  * NOTE: This function doesn't care if other block groups can contain all the
131526ce2095SJosef Bacik  * data in this block group. That check should be done by relocation routine,
131626ce2095SJosef Bacik  * not this function.
131726ce2095SJosef Bacik  */
131832da5386SDavid Sterba static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
131926ce2095SJosef Bacik {
132026ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
132126ce2095SJosef Bacik 	u64 num_bytes;
132226ce2095SJosef Bacik 	int ret = -ENOSPC;
132326ce2095SJosef Bacik 
132426ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
132526ce2095SJosef Bacik 	spin_lock(&cache->lock);
132626ce2095SJosef Bacik 
1327195a49eaSFilipe Manana 	if (cache->swap_extents) {
1328195a49eaSFilipe Manana 		ret = -ETXTBSY;
1329195a49eaSFilipe Manana 		goto out;
1330195a49eaSFilipe Manana 	}
1331195a49eaSFilipe Manana 
133226ce2095SJosef Bacik 	if (cache->ro) {
133326ce2095SJosef Bacik 		cache->ro++;
133426ce2095SJosef Bacik 		ret = 0;
133526ce2095SJosef Bacik 		goto out;
133626ce2095SJosef Bacik 	}
133726ce2095SJosef Bacik 
1338b3470b5dSDavid Sterba 	num_bytes = cache->length - cache->reserved - cache->pinned -
1339169e0da9SNaohiro Aota 		    cache->bytes_super - cache->zone_unusable - cache->used;
134026ce2095SJosef Bacik 
134126ce2095SJosef Bacik 	/*
1342a30a3d20SJosef Bacik 	 * Data never overcommits, even in mixed mode, so do just the straight
1343a30a3d20SJosef Bacik 	 * check of left over space in how much we have allocated.
1344a30a3d20SJosef Bacik 	 */
1345a30a3d20SJosef Bacik 	if (force) {
1346a30a3d20SJosef Bacik 		ret = 0;
1347a30a3d20SJosef Bacik 	} else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1348a30a3d20SJosef Bacik 		u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1349a30a3d20SJosef Bacik 
1350a30a3d20SJosef Bacik 		/*
135126ce2095SJosef Bacik 		 * Here we make sure if we mark this bg RO, we still have enough
1352f8935566SJosef Bacik 		 * free space as buffer.
135326ce2095SJosef Bacik 		 */
1354a30a3d20SJosef Bacik 		if (sinfo_used + num_bytes <= sinfo->total_bytes)
1355a30a3d20SJosef Bacik 			ret = 0;
1356a30a3d20SJosef Bacik 	} else {
1357a30a3d20SJosef Bacik 		/*
1358a30a3d20SJosef Bacik 		 * We overcommit metadata, so we need to do the
1359a30a3d20SJosef Bacik 		 * btrfs_can_overcommit check here, and we need to pass in
1360a30a3d20SJosef Bacik 		 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1361a30a3d20SJosef Bacik 		 * leeway to allow us to mark this block group as read only.
1362a30a3d20SJosef Bacik 		 */
1363a30a3d20SJosef Bacik 		if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1364a30a3d20SJosef Bacik 					 BTRFS_RESERVE_NO_FLUSH))
1365a30a3d20SJosef Bacik 			ret = 0;
1366a30a3d20SJosef Bacik 	}
1367a30a3d20SJosef Bacik 
1368a30a3d20SJosef Bacik 	if (!ret) {
136926ce2095SJosef Bacik 		sinfo->bytes_readonly += num_bytes;
1370169e0da9SNaohiro Aota 		if (btrfs_is_zoned(cache->fs_info)) {
1371169e0da9SNaohiro Aota 			/* Migrate zone_unusable bytes to readonly */
1372169e0da9SNaohiro Aota 			sinfo->bytes_readonly += cache->zone_unusable;
1373169e0da9SNaohiro Aota 			sinfo->bytes_zone_unusable -= cache->zone_unusable;
1374169e0da9SNaohiro Aota 			cache->zone_unusable = 0;
1375169e0da9SNaohiro Aota 		}
137626ce2095SJosef Bacik 		cache->ro++;
137726ce2095SJosef Bacik 		list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
137826ce2095SJosef Bacik 	}
137926ce2095SJosef Bacik out:
138026ce2095SJosef Bacik 	spin_unlock(&cache->lock);
138126ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
138226ce2095SJosef Bacik 	if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
138326ce2095SJosef Bacik 		btrfs_info(cache->fs_info,
1384b3470b5dSDavid Sterba 			"unable to make block group %llu ro", cache->start);
138526ce2095SJosef Bacik 		btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
138626ce2095SJosef Bacik 	}
138726ce2095SJosef Bacik 	return ret;
138826ce2095SJosef Bacik }
138926ce2095SJosef Bacik 
1390fe119a6eSNikolay Borisov static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1391fe119a6eSNikolay Borisov 				 struct btrfs_block_group *bg)
139245bb5d6aSNikolay Borisov {
139345bb5d6aSNikolay Borisov 	struct btrfs_fs_info *fs_info = bg->fs_info;
1394fe119a6eSNikolay Borisov 	struct btrfs_transaction *prev_trans = NULL;
139545bb5d6aSNikolay Borisov 	const u64 start = bg->start;
139645bb5d6aSNikolay Borisov 	const u64 end = start + bg->length - 1;
139745bb5d6aSNikolay Borisov 	int ret;
139845bb5d6aSNikolay Borisov 
1399fe119a6eSNikolay Borisov 	spin_lock(&fs_info->trans_lock);
1400fe119a6eSNikolay Borisov 	if (trans->transaction->list.prev != &fs_info->trans_list) {
1401fe119a6eSNikolay Borisov 		prev_trans = list_last_entry(&trans->transaction->list,
1402fe119a6eSNikolay Borisov 					     struct btrfs_transaction, list);
1403fe119a6eSNikolay Borisov 		refcount_inc(&prev_trans->use_count);
1404fe119a6eSNikolay Borisov 	}
1405fe119a6eSNikolay Borisov 	spin_unlock(&fs_info->trans_lock);
1406fe119a6eSNikolay Borisov 
140745bb5d6aSNikolay Borisov 	/*
140845bb5d6aSNikolay Borisov 	 * Hold the unused_bg_unpin_mutex lock to avoid racing with
140945bb5d6aSNikolay Borisov 	 * btrfs_finish_extent_commit(). If we are at transaction N, another
141045bb5d6aSNikolay Borisov 	 * task might be running finish_extent_commit() for the previous
141145bb5d6aSNikolay Borisov 	 * transaction N - 1, and have seen a range belonging to the block
1412fe119a6eSNikolay Borisov 	 * group in pinned_extents before we were able to clear the whole block
1413fe119a6eSNikolay Borisov 	 * group range from pinned_extents. This means that task can lookup for
1414fe119a6eSNikolay Borisov 	 * the block group after we unpinned it from pinned_extents and removed
1415fe119a6eSNikolay Borisov 	 * it, leading to a BUG_ON() at unpin_extent_range().
141645bb5d6aSNikolay Borisov 	 */
141745bb5d6aSNikolay Borisov 	mutex_lock(&fs_info->unused_bg_unpin_mutex);
1418fe119a6eSNikolay Borisov 	if (prev_trans) {
1419fe119a6eSNikolay Borisov 		ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
142045bb5d6aSNikolay Borisov 					EXTENT_DIRTY);
142145bb5d6aSNikolay Borisov 		if (ret)
1422534cf531SFilipe Manana 			goto out;
1423fe119a6eSNikolay Borisov 	}
142445bb5d6aSNikolay Borisov 
1425fe119a6eSNikolay Borisov 	ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
142645bb5d6aSNikolay Borisov 				EXTENT_DIRTY);
1427534cf531SFilipe Manana out:
142845bb5d6aSNikolay Borisov 	mutex_unlock(&fs_info->unused_bg_unpin_mutex);
14295150bf19SFilipe Manana 	if (prev_trans)
14305150bf19SFilipe Manana 		btrfs_put_transaction(prev_trans);
143145bb5d6aSNikolay Borisov 
1432534cf531SFilipe Manana 	return ret == 0;
143345bb5d6aSNikolay Borisov }
143445bb5d6aSNikolay Borisov 
143526ce2095SJosef Bacik /*
1436e3e0520bSJosef Bacik  * Process the unused_bgs list and remove any that don't have any allocated
1437e3e0520bSJosef Bacik  * space inside of them.
1438e3e0520bSJosef Bacik  */
1439e3e0520bSJosef Bacik void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1440e3e0520bSJosef Bacik {
144132da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1442e3e0520bSJosef Bacik 	struct btrfs_space_info *space_info;
1443e3e0520bSJosef Bacik 	struct btrfs_trans_handle *trans;
14446e80d4f8SDennis Zhou 	const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1445e3e0520bSJosef Bacik 	int ret = 0;
1446e3e0520bSJosef Bacik 
1447e3e0520bSJosef Bacik 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1448e3e0520bSJosef Bacik 		return;
1449e3e0520bSJosef Bacik 
14502f12741fSJosef Bacik 	if (btrfs_fs_closing(fs_info))
14512f12741fSJosef Bacik 		return;
14522f12741fSJosef Bacik 
1453ddfd08cbSJosef Bacik 	/*
1454ddfd08cbSJosef Bacik 	 * Long running balances can keep us blocked here for eternity, so
1455ddfd08cbSJosef Bacik 	 * simply skip deletion if we're unable to get the mutex.
1456ddfd08cbSJosef Bacik 	 */
1457f3372065SJohannes Thumshirn 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
1458ddfd08cbSJosef Bacik 		return;
1459ddfd08cbSJosef Bacik 
1460e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1461e3e0520bSJosef Bacik 	while (!list_empty(&fs_info->unused_bgs)) {
1462e3e0520bSJosef Bacik 		int trimming;
1463e3e0520bSJosef Bacik 
1464e3e0520bSJosef Bacik 		block_group = list_first_entry(&fs_info->unused_bgs,
146532da5386SDavid Sterba 					       struct btrfs_block_group,
1466e3e0520bSJosef Bacik 					       bg_list);
1467e3e0520bSJosef Bacik 		list_del_init(&block_group->bg_list);
1468e3e0520bSJosef Bacik 
1469e3e0520bSJosef Bacik 		space_info = block_group->space_info;
1470e3e0520bSJosef Bacik 
1471e3e0520bSJosef Bacik 		if (ret || btrfs_mixed_space_info(space_info)) {
1472e3e0520bSJosef Bacik 			btrfs_put_block_group(block_group);
1473e3e0520bSJosef Bacik 			continue;
1474e3e0520bSJosef Bacik 		}
1475e3e0520bSJosef Bacik 		spin_unlock(&fs_info->unused_bgs_lock);
1476e3e0520bSJosef Bacik 
1477b0643e59SDennis Zhou 		btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1478b0643e59SDennis Zhou 
1479e3e0520bSJosef Bacik 		/* Don't want to race with allocators so take the groups_sem */
1480e3e0520bSJosef Bacik 		down_write(&space_info->groups_sem);
14816e80d4f8SDennis Zhou 
14826e80d4f8SDennis Zhou 		/*
14836e80d4f8SDennis Zhou 		 * Async discard moves the final block group discard to be prior
14846e80d4f8SDennis Zhou 		 * to the unused_bgs code path.  Therefore, if it's not fully
14856e80d4f8SDennis Zhou 		 * trimmed, punt it back to the async discard lists.
14866e80d4f8SDennis Zhou 		 */
14876e80d4f8SDennis Zhou 		if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
14886e80d4f8SDennis Zhou 		    !btrfs_is_free_space_trimmed(block_group)) {
14896e80d4f8SDennis Zhou 			trace_btrfs_skip_unused_block_group(block_group);
14906e80d4f8SDennis Zhou 			up_write(&space_info->groups_sem);
14916e80d4f8SDennis Zhou 			/* Requeue if we failed because of async discard */
14926e80d4f8SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
14936e80d4f8SDennis Zhou 						 block_group);
14946e80d4f8SDennis Zhou 			goto next;
14956e80d4f8SDennis Zhou 		}
14966e80d4f8SDennis Zhou 
1497e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1498e3e0520bSJosef Bacik 		if (block_group->reserved || block_group->pinned ||
1499bf38be65SDavid Sterba 		    block_group->used || block_group->ro ||
1500e3e0520bSJosef Bacik 		    list_is_singular(&block_group->list)) {
1501e3e0520bSJosef Bacik 			/*
1502e3e0520bSJosef Bacik 			 * We want to bail if we made new allocations or have
1503e3e0520bSJosef Bacik 			 * outstanding allocations in this block group.  We do
1504e3e0520bSJosef Bacik 			 * the ro check in case balance is currently acting on
1505e3e0520bSJosef Bacik 			 * this block group.
1506e3e0520bSJosef Bacik 			 */
1507e3e0520bSJosef Bacik 			trace_btrfs_skip_unused_block_group(block_group);
1508e3e0520bSJosef Bacik 			spin_unlock(&block_group->lock);
1509e3e0520bSJosef Bacik 			up_write(&space_info->groups_sem);
1510e3e0520bSJosef Bacik 			goto next;
1511e3e0520bSJosef Bacik 		}
1512e3e0520bSJosef Bacik 		spin_unlock(&block_group->lock);
1513e3e0520bSJosef Bacik 
1514e3e0520bSJosef Bacik 		/* We don't want to force the issue, only flip if it's ok. */
1515e11c0406SJosef Bacik 		ret = inc_block_group_ro(block_group, 0);
1516e3e0520bSJosef Bacik 		up_write(&space_info->groups_sem);
1517e3e0520bSJosef Bacik 		if (ret < 0) {
1518e3e0520bSJosef Bacik 			ret = 0;
1519e3e0520bSJosef Bacik 			goto next;
1520e3e0520bSJosef Bacik 		}
1521e3e0520bSJosef Bacik 
152274e91b12SNaohiro Aota 		ret = btrfs_zone_finish(block_group);
152374e91b12SNaohiro Aota 		if (ret < 0) {
152474e91b12SNaohiro Aota 			btrfs_dec_block_group_ro(block_group);
152574e91b12SNaohiro Aota 			if (ret == -EAGAIN)
152674e91b12SNaohiro Aota 				ret = 0;
152774e91b12SNaohiro Aota 			goto next;
152874e91b12SNaohiro Aota 		}
152974e91b12SNaohiro Aota 
1530e3e0520bSJosef Bacik 		/*
1531e3e0520bSJosef Bacik 		 * Want to do this before we do anything else so we can recover
1532e3e0520bSJosef Bacik 		 * properly if we fail to join the transaction.
1533e3e0520bSJosef Bacik 		 */
1534e3e0520bSJosef Bacik 		trans = btrfs_start_trans_remove_block_group(fs_info,
1535b3470b5dSDavid Sterba 						     block_group->start);
1536e3e0520bSJosef Bacik 		if (IS_ERR(trans)) {
1537e3e0520bSJosef Bacik 			btrfs_dec_block_group_ro(block_group);
1538e3e0520bSJosef Bacik 			ret = PTR_ERR(trans);
1539e3e0520bSJosef Bacik 			goto next;
1540e3e0520bSJosef Bacik 		}
1541e3e0520bSJosef Bacik 
1542e3e0520bSJosef Bacik 		/*
1543e3e0520bSJosef Bacik 		 * We could have pending pinned extents for this block group,
1544e3e0520bSJosef Bacik 		 * just delete them, we don't care about them anymore.
1545e3e0520bSJosef Bacik 		 */
1546534cf531SFilipe Manana 		if (!clean_pinned_extents(trans, block_group)) {
1547534cf531SFilipe Manana 			btrfs_dec_block_group_ro(block_group);
1548e3e0520bSJosef Bacik 			goto end_trans;
1549534cf531SFilipe Manana 		}
1550e3e0520bSJosef Bacik 
1551b0643e59SDennis Zhou 		/*
1552b0643e59SDennis Zhou 		 * At this point, the block_group is read only and should fail
1553b0643e59SDennis Zhou 		 * new allocations.  However, btrfs_finish_extent_commit() can
1554b0643e59SDennis Zhou 		 * cause this block_group to be placed back on the discard
1555b0643e59SDennis Zhou 		 * lists because now the block_group isn't fully discarded.
1556b0643e59SDennis Zhou 		 * Bail here and try again later after discarding everything.
1557b0643e59SDennis Zhou 		 */
1558b0643e59SDennis Zhou 		spin_lock(&fs_info->discard_ctl.lock);
1559b0643e59SDennis Zhou 		if (!list_empty(&block_group->discard_list)) {
1560b0643e59SDennis Zhou 			spin_unlock(&fs_info->discard_ctl.lock);
1561b0643e59SDennis Zhou 			btrfs_dec_block_group_ro(block_group);
1562b0643e59SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
1563b0643e59SDennis Zhou 						 block_group);
1564b0643e59SDennis Zhou 			goto end_trans;
1565b0643e59SDennis Zhou 		}
1566b0643e59SDennis Zhou 		spin_unlock(&fs_info->discard_ctl.lock);
1567b0643e59SDennis Zhou 
1568e3e0520bSJosef Bacik 		/* Reset pinned so btrfs_put_block_group doesn't complain */
1569e3e0520bSJosef Bacik 		spin_lock(&space_info->lock);
1570e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1571e3e0520bSJosef Bacik 
1572e3e0520bSJosef Bacik 		btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1573e3e0520bSJosef Bacik 						     -block_group->pinned);
1574e3e0520bSJosef Bacik 		space_info->bytes_readonly += block_group->pinned;
1575e3e0520bSJosef Bacik 		block_group->pinned = 0;
1576e3e0520bSJosef Bacik 
1577e3e0520bSJosef Bacik 		spin_unlock(&block_group->lock);
1578e3e0520bSJosef Bacik 		spin_unlock(&space_info->lock);
1579e3e0520bSJosef Bacik 
15806e80d4f8SDennis Zhou 		/*
15816e80d4f8SDennis Zhou 		 * The normal path here is an unused block group is passed here,
15826e80d4f8SDennis Zhou 		 * then trimming is handled in the transaction commit path.
15836e80d4f8SDennis Zhou 		 * Async discard interposes before this to do the trimming
15846e80d4f8SDennis Zhou 		 * before coming down the unused block group path as trimming
15856e80d4f8SDennis Zhou 		 * will no longer be done later in the transaction commit path.
15866e80d4f8SDennis Zhou 		 */
15876e80d4f8SDennis Zhou 		if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
15886e80d4f8SDennis Zhou 			goto flip_async;
15896e80d4f8SDennis Zhou 
1590dcba6e48SNaohiro Aota 		/*
1591dcba6e48SNaohiro Aota 		 * DISCARD can flip during remount. On zoned filesystems, we
1592dcba6e48SNaohiro Aota 		 * need to reset sequential-required zones.
1593dcba6e48SNaohiro Aota 		 */
1594dcba6e48SNaohiro Aota 		trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) ||
1595dcba6e48SNaohiro Aota 				btrfs_is_zoned(fs_info);
1596e3e0520bSJosef Bacik 
1597e3e0520bSJosef Bacik 		/* Implicit trim during transaction commit. */
1598e3e0520bSJosef Bacik 		if (trimming)
15996b7304afSFilipe Manana 			btrfs_freeze_block_group(block_group);
1600e3e0520bSJosef Bacik 
1601e3e0520bSJosef Bacik 		/*
1602e3e0520bSJosef Bacik 		 * Btrfs_remove_chunk will abort the transaction if things go
1603e3e0520bSJosef Bacik 		 * horribly wrong.
1604e3e0520bSJosef Bacik 		 */
1605b3470b5dSDavid Sterba 		ret = btrfs_remove_chunk(trans, block_group->start);
1606e3e0520bSJosef Bacik 
1607e3e0520bSJosef Bacik 		if (ret) {
1608e3e0520bSJosef Bacik 			if (trimming)
16096b7304afSFilipe Manana 				btrfs_unfreeze_block_group(block_group);
1610e3e0520bSJosef Bacik 			goto end_trans;
1611e3e0520bSJosef Bacik 		}
1612e3e0520bSJosef Bacik 
1613e3e0520bSJosef Bacik 		/*
1614e3e0520bSJosef Bacik 		 * If we're not mounted with -odiscard, we can just forget
1615e3e0520bSJosef Bacik 		 * about this block group. Otherwise we'll need to wait
1616e3e0520bSJosef Bacik 		 * until transaction commit to do the actual discard.
1617e3e0520bSJosef Bacik 		 */
1618e3e0520bSJosef Bacik 		if (trimming) {
1619e3e0520bSJosef Bacik 			spin_lock(&fs_info->unused_bgs_lock);
1620e3e0520bSJosef Bacik 			/*
1621e3e0520bSJosef Bacik 			 * A concurrent scrub might have added us to the list
1622e3e0520bSJosef Bacik 			 * fs_info->unused_bgs, so use a list_move operation
1623e3e0520bSJosef Bacik 			 * to add the block group to the deleted_bgs list.
1624e3e0520bSJosef Bacik 			 */
1625e3e0520bSJosef Bacik 			list_move(&block_group->bg_list,
1626e3e0520bSJosef Bacik 				  &trans->transaction->deleted_bgs);
1627e3e0520bSJosef Bacik 			spin_unlock(&fs_info->unused_bgs_lock);
1628e3e0520bSJosef Bacik 			btrfs_get_block_group(block_group);
1629e3e0520bSJosef Bacik 		}
1630e3e0520bSJosef Bacik end_trans:
1631e3e0520bSJosef Bacik 		btrfs_end_transaction(trans);
1632e3e0520bSJosef Bacik next:
1633e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1634e3e0520bSJosef Bacik 		spin_lock(&fs_info->unused_bgs_lock);
1635e3e0520bSJosef Bacik 	}
1636e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
1637f3372065SJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
16386e80d4f8SDennis Zhou 	return;
16396e80d4f8SDennis Zhou 
16406e80d4f8SDennis Zhou flip_async:
16416e80d4f8SDennis Zhou 	btrfs_end_transaction(trans);
1642f3372065SJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
16436e80d4f8SDennis Zhou 	btrfs_put_block_group(block_group);
16446e80d4f8SDennis Zhou 	btrfs_discard_punt_unused_bgs_list(fs_info);
1645e3e0520bSJosef Bacik }
1646e3e0520bSJosef Bacik 
164732da5386SDavid Sterba void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1648e3e0520bSJosef Bacik {
1649e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = bg->fs_info;
1650e3e0520bSJosef Bacik 
1651e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1652e3e0520bSJosef Bacik 	if (list_empty(&bg->bg_list)) {
1653e3e0520bSJosef Bacik 		btrfs_get_block_group(bg);
1654e3e0520bSJosef Bacik 		trace_btrfs_add_unused_block_group(bg);
1655e3e0520bSJosef Bacik 		list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1656e3e0520bSJosef Bacik 	}
1657e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
1658e3e0520bSJosef Bacik }
16594358d963SJosef Bacik 
16602ca0ec77SJohannes Thumshirn /*
16612ca0ec77SJohannes Thumshirn  * We want block groups with a low number of used bytes to be in the beginning
16622ca0ec77SJohannes Thumshirn  * of the list, so they will get reclaimed first.
16632ca0ec77SJohannes Thumshirn  */
16642ca0ec77SJohannes Thumshirn static int reclaim_bgs_cmp(void *unused, const struct list_head *a,
16652ca0ec77SJohannes Thumshirn 			   const struct list_head *b)
16662ca0ec77SJohannes Thumshirn {
16672ca0ec77SJohannes Thumshirn 	const struct btrfs_block_group *bg1, *bg2;
16682ca0ec77SJohannes Thumshirn 
16692ca0ec77SJohannes Thumshirn 	bg1 = list_entry(a, struct btrfs_block_group, bg_list);
16702ca0ec77SJohannes Thumshirn 	bg2 = list_entry(b, struct btrfs_block_group, bg_list);
16712ca0ec77SJohannes Thumshirn 
16722ca0ec77SJohannes Thumshirn 	return bg1->used > bg2->used;
16732ca0ec77SJohannes Thumshirn }
16742ca0ec77SJohannes Thumshirn 
16753687fcb0SJohannes Thumshirn static inline bool btrfs_should_reclaim(struct btrfs_fs_info *fs_info)
16763687fcb0SJohannes Thumshirn {
16773687fcb0SJohannes Thumshirn 	if (btrfs_is_zoned(fs_info))
16783687fcb0SJohannes Thumshirn 		return btrfs_zoned_should_reclaim(fs_info);
16793687fcb0SJohannes Thumshirn 	return true;
16803687fcb0SJohannes Thumshirn }
16813687fcb0SJohannes Thumshirn 
168281531225SBoris Burkov static bool should_reclaim_block_group(struct btrfs_block_group *bg, u64 bytes_freed)
168381531225SBoris Burkov {
168481531225SBoris Burkov 	const struct btrfs_space_info *space_info = bg->space_info;
168581531225SBoris Burkov 	const int reclaim_thresh = READ_ONCE(space_info->bg_reclaim_threshold);
168681531225SBoris Burkov 	const u64 new_val = bg->used;
168781531225SBoris Burkov 	const u64 old_val = new_val + bytes_freed;
168881531225SBoris Burkov 	u64 thresh;
168981531225SBoris Burkov 
169081531225SBoris Burkov 	if (reclaim_thresh == 0)
169181531225SBoris Burkov 		return false;
169281531225SBoris Burkov 
1693428c8e03SDavid Sterba 	thresh = mult_perc(bg->length, reclaim_thresh);
169481531225SBoris Burkov 
169581531225SBoris Burkov 	/*
169681531225SBoris Burkov 	 * If we were below the threshold before don't reclaim, we are likely a
169781531225SBoris Burkov 	 * brand new block group and we don't want to relocate new block groups.
169881531225SBoris Burkov 	 */
169981531225SBoris Burkov 	if (old_val < thresh)
170081531225SBoris Burkov 		return false;
170181531225SBoris Burkov 	if (new_val >= thresh)
170281531225SBoris Burkov 		return false;
170381531225SBoris Burkov 	return true;
170481531225SBoris Burkov }
170581531225SBoris Burkov 
170618bb8bbfSJohannes Thumshirn void btrfs_reclaim_bgs_work(struct work_struct *work)
170718bb8bbfSJohannes Thumshirn {
170818bb8bbfSJohannes Thumshirn 	struct btrfs_fs_info *fs_info =
170918bb8bbfSJohannes Thumshirn 		container_of(work, struct btrfs_fs_info, reclaim_bgs_work);
171018bb8bbfSJohannes Thumshirn 	struct btrfs_block_group *bg;
171118bb8bbfSJohannes Thumshirn 	struct btrfs_space_info *space_info;
171218bb8bbfSJohannes Thumshirn 
171318bb8bbfSJohannes Thumshirn 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
171418bb8bbfSJohannes Thumshirn 		return;
171518bb8bbfSJohannes Thumshirn 
17162f12741fSJosef Bacik 	if (btrfs_fs_closing(fs_info))
17172f12741fSJosef Bacik 		return;
17182f12741fSJosef Bacik 
17193687fcb0SJohannes Thumshirn 	if (!btrfs_should_reclaim(fs_info))
17203687fcb0SJohannes Thumshirn 		return;
17213687fcb0SJohannes Thumshirn 
1722ca5e4ea0SNaohiro Aota 	sb_start_write(fs_info->sb);
1723ca5e4ea0SNaohiro Aota 
1724ca5e4ea0SNaohiro Aota 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
1725ca5e4ea0SNaohiro Aota 		sb_end_write(fs_info->sb);
172618bb8bbfSJohannes Thumshirn 		return;
1727ca5e4ea0SNaohiro Aota 	}
172818bb8bbfSJohannes Thumshirn 
17299cc0b837SJohannes Thumshirn 	/*
17309cc0b837SJohannes Thumshirn 	 * Long running balances can keep us blocked here for eternity, so
17319cc0b837SJohannes Thumshirn 	 * simply skip reclaim if we're unable to get the mutex.
17329cc0b837SJohannes Thumshirn 	 */
17339cc0b837SJohannes Thumshirn 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) {
17349cc0b837SJohannes Thumshirn 		btrfs_exclop_finish(fs_info);
1735ca5e4ea0SNaohiro Aota 		sb_end_write(fs_info->sb);
17369cc0b837SJohannes Thumshirn 		return;
17379cc0b837SJohannes Thumshirn 	}
17389cc0b837SJohannes Thumshirn 
173918bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
17402ca0ec77SJohannes Thumshirn 	/*
17412ca0ec77SJohannes Thumshirn 	 * Sort happens under lock because we can't simply splice it and sort.
17422ca0ec77SJohannes Thumshirn 	 * The block groups might still be in use and reachable via bg_list,
17432ca0ec77SJohannes Thumshirn 	 * and their presence in the reclaim_bgs list must be preserved.
17442ca0ec77SJohannes Thumshirn 	 */
17452ca0ec77SJohannes Thumshirn 	list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp);
174618bb8bbfSJohannes Thumshirn 	while (!list_empty(&fs_info->reclaim_bgs)) {
17475f93e776SJohannes Thumshirn 		u64 zone_unusable;
17481cea5cf0SFilipe Manana 		int ret = 0;
17491cea5cf0SFilipe Manana 
175018bb8bbfSJohannes Thumshirn 		bg = list_first_entry(&fs_info->reclaim_bgs,
175118bb8bbfSJohannes Thumshirn 				      struct btrfs_block_group,
175218bb8bbfSJohannes Thumshirn 				      bg_list);
175318bb8bbfSJohannes Thumshirn 		list_del_init(&bg->bg_list);
175418bb8bbfSJohannes Thumshirn 
175518bb8bbfSJohannes Thumshirn 		space_info = bg->space_info;
175618bb8bbfSJohannes Thumshirn 		spin_unlock(&fs_info->unused_bgs_lock);
175718bb8bbfSJohannes Thumshirn 
175818bb8bbfSJohannes Thumshirn 		/* Don't race with allocators so take the groups_sem */
175918bb8bbfSJohannes Thumshirn 		down_write(&space_info->groups_sem);
176018bb8bbfSJohannes Thumshirn 
176118bb8bbfSJohannes Thumshirn 		spin_lock(&bg->lock);
176218bb8bbfSJohannes Thumshirn 		if (bg->reserved || bg->pinned || bg->ro) {
176318bb8bbfSJohannes Thumshirn 			/*
176418bb8bbfSJohannes Thumshirn 			 * We want to bail if we made new allocations or have
176518bb8bbfSJohannes Thumshirn 			 * outstanding allocations in this block group.  We do
176618bb8bbfSJohannes Thumshirn 			 * the ro check in case balance is currently acting on
176718bb8bbfSJohannes Thumshirn 			 * this block group.
176818bb8bbfSJohannes Thumshirn 			 */
176918bb8bbfSJohannes Thumshirn 			spin_unlock(&bg->lock);
177018bb8bbfSJohannes Thumshirn 			up_write(&space_info->groups_sem);
177118bb8bbfSJohannes Thumshirn 			goto next;
177218bb8bbfSJohannes Thumshirn 		}
1773cc4804bfSBoris Burkov 		if (bg->used == 0) {
1774cc4804bfSBoris Burkov 			/*
1775cc4804bfSBoris Burkov 			 * It is possible that we trigger relocation on a block
1776cc4804bfSBoris Burkov 			 * group as its extents are deleted and it first goes
1777cc4804bfSBoris Burkov 			 * below the threshold, then shortly after goes empty.
1778cc4804bfSBoris Burkov 			 *
1779cc4804bfSBoris Burkov 			 * In this case, relocating it does delete it, but has
1780cc4804bfSBoris Burkov 			 * some overhead in relocation specific metadata, looking
1781cc4804bfSBoris Burkov 			 * for the non-existent extents and running some extra
1782cc4804bfSBoris Burkov 			 * transactions, which we can avoid by using one of the
1783cc4804bfSBoris Burkov 			 * other mechanisms for dealing with empty block groups.
1784cc4804bfSBoris Burkov 			 */
1785cc4804bfSBoris Burkov 			if (!btrfs_test_opt(fs_info, DISCARD_ASYNC))
1786cc4804bfSBoris Burkov 				btrfs_mark_bg_unused(bg);
1787cc4804bfSBoris Burkov 			spin_unlock(&bg->lock);
1788cc4804bfSBoris Burkov 			up_write(&space_info->groups_sem);
1789cc4804bfSBoris Burkov 			goto next;
179081531225SBoris Burkov 
179181531225SBoris Burkov 		}
179281531225SBoris Burkov 		/*
179381531225SBoris Burkov 		 * The block group might no longer meet the reclaim condition by
179481531225SBoris Burkov 		 * the time we get around to reclaiming it, so to avoid
179581531225SBoris Burkov 		 * reclaiming overly full block_groups, skip reclaiming them.
179681531225SBoris Burkov 		 *
179781531225SBoris Burkov 		 * Since the decision making process also depends on the amount
179881531225SBoris Burkov 		 * being freed, pass in a fake giant value to skip that extra
179981531225SBoris Burkov 		 * check, which is more meaningful when adding to the list in
180081531225SBoris Burkov 		 * the first place.
180181531225SBoris Burkov 		 */
180281531225SBoris Burkov 		if (!should_reclaim_block_group(bg, bg->length)) {
180381531225SBoris Burkov 			spin_unlock(&bg->lock);
180481531225SBoris Burkov 			up_write(&space_info->groups_sem);
180581531225SBoris Burkov 			goto next;
1806cc4804bfSBoris Burkov 		}
180718bb8bbfSJohannes Thumshirn 		spin_unlock(&bg->lock);
180818bb8bbfSJohannes Thumshirn 
180918bb8bbfSJohannes Thumshirn 		/* Get out fast, in case we're unmounting the filesystem */
181018bb8bbfSJohannes Thumshirn 		if (btrfs_fs_closing(fs_info)) {
181118bb8bbfSJohannes Thumshirn 			up_write(&space_info->groups_sem);
181218bb8bbfSJohannes Thumshirn 			goto next;
181318bb8bbfSJohannes Thumshirn 		}
181418bb8bbfSJohannes Thumshirn 
18155f93e776SJohannes Thumshirn 		/*
18165f93e776SJohannes Thumshirn 		 * Cache the zone_unusable value before turning the block group
18175f93e776SJohannes Thumshirn 		 * to read only. As soon as the blog group is read only it's
18185f93e776SJohannes Thumshirn 		 * zone_unusable value gets moved to the block group's read-only
18195f93e776SJohannes Thumshirn 		 * bytes and isn't available for calculations anymore.
18205f93e776SJohannes Thumshirn 		 */
18215f93e776SJohannes Thumshirn 		zone_unusable = bg->zone_unusable;
182218bb8bbfSJohannes Thumshirn 		ret = inc_block_group_ro(bg, 0);
182318bb8bbfSJohannes Thumshirn 		up_write(&space_info->groups_sem);
182418bb8bbfSJohannes Thumshirn 		if (ret < 0)
182518bb8bbfSJohannes Thumshirn 			goto next;
182618bb8bbfSJohannes Thumshirn 
18275f93e776SJohannes Thumshirn 		btrfs_info(fs_info,
18285f93e776SJohannes Thumshirn 			"reclaiming chunk %llu with %llu%% used %llu%% unusable",
182995cd356cSJohannes Thumshirn 				bg->start,
183095cd356cSJohannes Thumshirn 				div64_u64(bg->used * 100, bg->length),
18315f93e776SJohannes Thumshirn 				div64_u64(zone_unusable * 100, bg->length));
183218bb8bbfSJohannes Thumshirn 		trace_btrfs_reclaim_block_group(bg);
183318bb8bbfSJohannes Thumshirn 		ret = btrfs_relocate_chunk(fs_info, bg->start);
183474944c87SJosef Bacik 		if (ret) {
183574944c87SJosef Bacik 			btrfs_dec_block_group_ro(bg);
183618bb8bbfSJohannes Thumshirn 			btrfs_err(fs_info, "error relocating chunk %llu",
183718bb8bbfSJohannes Thumshirn 				  bg->start);
183874944c87SJosef Bacik 		}
183918bb8bbfSJohannes Thumshirn 
184018bb8bbfSJohannes Thumshirn next:
18411cea5cf0SFilipe Manana 		btrfs_put_block_group(bg);
1842d96b3424SFilipe Manana 		spin_lock(&fs_info->unused_bgs_lock);
184318bb8bbfSJohannes Thumshirn 	}
184418bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
184518bb8bbfSJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
184618bb8bbfSJohannes Thumshirn 	btrfs_exclop_finish(fs_info);
1847ca5e4ea0SNaohiro Aota 	sb_end_write(fs_info->sb);
184818bb8bbfSJohannes Thumshirn }
184918bb8bbfSJohannes Thumshirn 
185018bb8bbfSJohannes Thumshirn void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
185118bb8bbfSJohannes Thumshirn {
185218bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
185318bb8bbfSJohannes Thumshirn 	if (!list_empty(&fs_info->reclaim_bgs))
185418bb8bbfSJohannes Thumshirn 		queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
185518bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
185618bb8bbfSJohannes Thumshirn }
185718bb8bbfSJohannes Thumshirn 
185818bb8bbfSJohannes Thumshirn void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
185918bb8bbfSJohannes Thumshirn {
186018bb8bbfSJohannes Thumshirn 	struct btrfs_fs_info *fs_info = bg->fs_info;
186118bb8bbfSJohannes Thumshirn 
186218bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
186318bb8bbfSJohannes Thumshirn 	if (list_empty(&bg->bg_list)) {
186418bb8bbfSJohannes Thumshirn 		btrfs_get_block_group(bg);
186518bb8bbfSJohannes Thumshirn 		trace_btrfs_add_reclaim_block_group(bg);
186618bb8bbfSJohannes Thumshirn 		list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
186718bb8bbfSJohannes Thumshirn 	}
186818bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
186918bb8bbfSJohannes Thumshirn }
187018bb8bbfSJohannes Thumshirn 
1871e3ba67a1SJohannes Thumshirn static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1872e3ba67a1SJohannes Thumshirn 			   struct btrfs_path *path)
1873e3ba67a1SJohannes Thumshirn {
1874e3ba67a1SJohannes Thumshirn 	struct extent_map_tree *em_tree;
1875e3ba67a1SJohannes Thumshirn 	struct extent_map *em;
1876e3ba67a1SJohannes Thumshirn 	struct btrfs_block_group_item bg;
1877e3ba67a1SJohannes Thumshirn 	struct extent_buffer *leaf;
1878e3ba67a1SJohannes Thumshirn 	int slot;
1879e3ba67a1SJohannes Thumshirn 	u64 flags;
1880e3ba67a1SJohannes Thumshirn 	int ret = 0;
1881e3ba67a1SJohannes Thumshirn 
1882e3ba67a1SJohannes Thumshirn 	slot = path->slots[0];
1883e3ba67a1SJohannes Thumshirn 	leaf = path->nodes[0];
1884e3ba67a1SJohannes Thumshirn 
1885e3ba67a1SJohannes Thumshirn 	em_tree = &fs_info->mapping_tree;
1886e3ba67a1SJohannes Thumshirn 	read_lock(&em_tree->lock);
1887e3ba67a1SJohannes Thumshirn 	em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1888e3ba67a1SJohannes Thumshirn 	read_unlock(&em_tree->lock);
1889e3ba67a1SJohannes Thumshirn 	if (!em) {
1890e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1891e3ba67a1SJohannes Thumshirn 			  "logical %llu len %llu found bg but no related chunk",
1892e3ba67a1SJohannes Thumshirn 			  key->objectid, key->offset);
1893e3ba67a1SJohannes Thumshirn 		return -ENOENT;
1894e3ba67a1SJohannes Thumshirn 	}
1895e3ba67a1SJohannes Thumshirn 
1896e3ba67a1SJohannes Thumshirn 	if (em->start != key->objectid || em->len != key->offset) {
1897e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1898e3ba67a1SJohannes Thumshirn 			"block group %llu len %llu mismatch with chunk %llu len %llu",
1899e3ba67a1SJohannes Thumshirn 			key->objectid, key->offset, em->start, em->len);
1900e3ba67a1SJohannes Thumshirn 		ret = -EUCLEAN;
1901e3ba67a1SJohannes Thumshirn 		goto out_free_em;
1902e3ba67a1SJohannes Thumshirn 	}
1903e3ba67a1SJohannes Thumshirn 
1904e3ba67a1SJohannes Thumshirn 	read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1905e3ba67a1SJohannes Thumshirn 			   sizeof(bg));
1906e3ba67a1SJohannes Thumshirn 	flags = btrfs_stack_block_group_flags(&bg) &
1907e3ba67a1SJohannes Thumshirn 		BTRFS_BLOCK_GROUP_TYPE_MASK;
1908e3ba67a1SJohannes Thumshirn 
1909e3ba67a1SJohannes Thumshirn 	if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1910e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1911e3ba67a1SJohannes Thumshirn "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1912e3ba67a1SJohannes Thumshirn 			  key->objectid, key->offset, flags,
1913e3ba67a1SJohannes Thumshirn 			  (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1914e3ba67a1SJohannes Thumshirn 		ret = -EUCLEAN;
1915e3ba67a1SJohannes Thumshirn 	}
1916e3ba67a1SJohannes Thumshirn 
1917e3ba67a1SJohannes Thumshirn out_free_em:
1918e3ba67a1SJohannes Thumshirn 	free_extent_map(em);
1919e3ba67a1SJohannes Thumshirn 	return ret;
1920e3ba67a1SJohannes Thumshirn }
1921e3ba67a1SJohannes Thumshirn 
19224358d963SJosef Bacik static int find_first_block_group(struct btrfs_fs_info *fs_info,
19234358d963SJosef Bacik 				  struct btrfs_path *path,
19244358d963SJosef Bacik 				  struct btrfs_key *key)
19254358d963SJosef Bacik {
1926dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
1927e3ba67a1SJohannes Thumshirn 	int ret;
19284358d963SJosef Bacik 	struct btrfs_key found_key;
19294358d963SJosef Bacik 
193036dfbbe2SGabriel Niebler 	btrfs_for_each_slot(root, key, &found_key, path, ret) {
19314358d963SJosef Bacik 		if (found_key.objectid >= key->objectid &&
19324358d963SJosef Bacik 		    found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
193336dfbbe2SGabriel Niebler 			return read_bg_from_eb(fs_info, &found_key, path);
1934e3ba67a1SJohannes Thumshirn 		}
19354358d963SJosef Bacik 	}
19364358d963SJosef Bacik 	return ret;
19374358d963SJosef Bacik }
19384358d963SJosef Bacik 
19394358d963SJosef Bacik static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
19404358d963SJosef Bacik {
19414358d963SJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
19424358d963SJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
19434358d963SJosef Bacik 
19444358d963SJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
19454358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
19464358d963SJosef Bacik 		fs_info->avail_data_alloc_bits |= extra_flags;
19474358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
19484358d963SJosef Bacik 		fs_info->avail_metadata_alloc_bits |= extra_flags;
19494358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
19504358d963SJosef Bacik 		fs_info->avail_system_alloc_bits |= extra_flags;
19514358d963SJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
19524358d963SJosef Bacik }
19534358d963SJosef Bacik 
195443dd529aSDavid Sterba /*
195543dd529aSDavid Sterba  * Map a physical disk address to a list of logical addresses.
19569ee9b979SNikolay Borisov  *
19579ee9b979SNikolay Borisov  * @fs_info:       the filesystem
195896a14336SNikolay Borisov  * @chunk_start:   logical address of block group
195996a14336SNikolay Borisov  * @physical:	   physical address to map to logical addresses
196096a14336SNikolay Borisov  * @logical:	   return array of logical addresses which map to @physical
196196a14336SNikolay Borisov  * @naddrs:	   length of @logical
196296a14336SNikolay Borisov  * @stripe_len:    size of IO stripe for the given block group
196396a14336SNikolay Borisov  *
196496a14336SNikolay Borisov  * Maps a particular @physical disk address to a list of @logical addresses.
196596a14336SNikolay Borisov  * Used primarily to exclude those portions of a block group that contain super
196696a14336SNikolay Borisov  * block copies.
196796a14336SNikolay Borisov  */
196896a14336SNikolay Borisov int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
19691eb82ef8SChristoph Hellwig 		     u64 physical, u64 **logical, int *naddrs, int *stripe_len)
197096a14336SNikolay Borisov {
197196a14336SNikolay Borisov 	struct extent_map *em;
197296a14336SNikolay Borisov 	struct map_lookup *map;
197396a14336SNikolay Borisov 	u64 *buf;
197496a14336SNikolay Borisov 	u64 bytenr;
19751776ad17SNikolay Borisov 	u64 data_stripe_length;
19761776ad17SNikolay Borisov 	u64 io_stripe_size;
19771776ad17SNikolay Borisov 	int i, nr = 0;
19781776ad17SNikolay Borisov 	int ret = 0;
197996a14336SNikolay Borisov 
198096a14336SNikolay Borisov 	em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
198196a14336SNikolay Borisov 	if (IS_ERR(em))
198296a14336SNikolay Borisov 		return -EIO;
198396a14336SNikolay Borisov 
198496a14336SNikolay Borisov 	map = em->map_lookup;
19859e22b925SNikolay Borisov 	data_stripe_length = em->orig_block_len;
19861776ad17SNikolay Borisov 	io_stripe_size = map->stripe_len;
1987138082f3SNaohiro Aota 	chunk_start = em->start;
198896a14336SNikolay Borisov 
19899e22b925SNikolay Borisov 	/* For RAID5/6 adjust to a full IO stripe length */
19909e22b925SNikolay Borisov 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
19911776ad17SNikolay Borisov 		io_stripe_size = map->stripe_len * nr_data_stripes(map);
199296a14336SNikolay Borisov 
199396a14336SNikolay Borisov 	buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
19941776ad17SNikolay Borisov 	if (!buf) {
19951776ad17SNikolay Borisov 		ret = -ENOMEM;
19961776ad17SNikolay Borisov 		goto out;
19971776ad17SNikolay Borisov 	}
199896a14336SNikolay Borisov 
199996a14336SNikolay Borisov 	for (i = 0; i < map->num_stripes; i++) {
20001776ad17SNikolay Borisov 		bool already_inserted = false;
20011776ad17SNikolay Borisov 		u64 stripe_nr;
2002138082f3SNaohiro Aota 		u64 offset;
20031776ad17SNikolay Borisov 		int j;
20041776ad17SNikolay Borisov 
20051776ad17SNikolay Borisov 		if (!in_range(physical, map->stripes[i].physical,
20061776ad17SNikolay Borisov 			      data_stripe_length))
200796a14336SNikolay Borisov 			continue;
200896a14336SNikolay Borisov 
200996a14336SNikolay Borisov 		stripe_nr = physical - map->stripes[i].physical;
2010138082f3SNaohiro Aota 		stripe_nr = div64_u64_rem(stripe_nr, map->stripe_len, &offset);
201196a14336SNikolay Borisov 
2012ac067734SDavid Sterba 		if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
2013ac067734SDavid Sterba 				 BTRFS_BLOCK_GROUP_RAID10)) {
201496a14336SNikolay Borisov 			stripe_nr = stripe_nr * map->num_stripes + i;
201596a14336SNikolay Borisov 			stripe_nr = div_u64(stripe_nr, map->sub_stripes);
201696a14336SNikolay Borisov 		}
201796a14336SNikolay Borisov 		/*
201896a14336SNikolay Borisov 		 * The remaining case would be for RAID56, multiply by
201996a14336SNikolay Borisov 		 * nr_data_stripes().  Alternatively, just use rmap_len below
202096a14336SNikolay Borisov 		 * instead of map->stripe_len
202196a14336SNikolay Borisov 		 */
202296a14336SNikolay Borisov 
2023138082f3SNaohiro Aota 		bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
20241776ad17SNikolay Borisov 
20251776ad17SNikolay Borisov 		/* Ensure we don't add duplicate addresses */
202696a14336SNikolay Borisov 		for (j = 0; j < nr; j++) {
20271776ad17SNikolay Borisov 			if (buf[j] == bytenr) {
20281776ad17SNikolay Borisov 				already_inserted = true;
202996a14336SNikolay Borisov 				break;
203096a14336SNikolay Borisov 			}
203196a14336SNikolay Borisov 		}
20321776ad17SNikolay Borisov 
20331776ad17SNikolay Borisov 		if (!already_inserted)
20341776ad17SNikolay Borisov 			buf[nr++] = bytenr;
203596a14336SNikolay Borisov 	}
203696a14336SNikolay Borisov 
203796a14336SNikolay Borisov 	*logical = buf;
203896a14336SNikolay Borisov 	*naddrs = nr;
20391776ad17SNikolay Borisov 	*stripe_len = io_stripe_size;
20401776ad17SNikolay Borisov out:
204196a14336SNikolay Borisov 	free_extent_map(em);
20421776ad17SNikolay Borisov 	return ret;
204396a14336SNikolay Borisov }
204496a14336SNikolay Borisov 
204532da5386SDavid Sterba static int exclude_super_stripes(struct btrfs_block_group *cache)
20464358d963SJosef Bacik {
20474358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
204812659251SNaohiro Aota 	const bool zoned = btrfs_is_zoned(fs_info);
20494358d963SJosef Bacik 	u64 bytenr;
20504358d963SJosef Bacik 	u64 *logical;
20514358d963SJosef Bacik 	int stripe_len;
20524358d963SJosef Bacik 	int i, nr, ret;
20534358d963SJosef Bacik 
2054b3470b5dSDavid Sterba 	if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
2055b3470b5dSDavid Sterba 		stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
20564358d963SJosef Bacik 		cache->bytes_super += stripe_len;
2057b3470b5dSDavid Sterba 		ret = btrfs_add_excluded_extent(fs_info, cache->start,
20584358d963SJosef Bacik 						stripe_len);
20594358d963SJosef Bacik 		if (ret)
20604358d963SJosef Bacik 			return ret;
20614358d963SJosef Bacik 	}
20624358d963SJosef Bacik 
20634358d963SJosef Bacik 	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
20644358d963SJosef Bacik 		bytenr = btrfs_sb_offset(i);
20651eb82ef8SChristoph Hellwig 		ret = btrfs_rmap_block(fs_info, cache->start,
20664358d963SJosef Bacik 				       bytenr, &logical, &nr, &stripe_len);
20674358d963SJosef Bacik 		if (ret)
20684358d963SJosef Bacik 			return ret;
20694358d963SJosef Bacik 
207012659251SNaohiro Aota 		/* Shouldn't have super stripes in sequential zones */
207112659251SNaohiro Aota 		if (zoned && nr) {
207212659251SNaohiro Aota 			btrfs_err(fs_info,
207312659251SNaohiro Aota 			"zoned: block group %llu must not contain super block",
207412659251SNaohiro Aota 				  cache->start);
207512659251SNaohiro Aota 			return -EUCLEAN;
207612659251SNaohiro Aota 		}
207712659251SNaohiro Aota 
20784358d963SJosef Bacik 		while (nr--) {
207996f9b0f2SNikolay Borisov 			u64 len = min_t(u64, stripe_len,
208096f9b0f2SNikolay Borisov 				cache->start + cache->length - logical[nr]);
20814358d963SJosef Bacik 
20824358d963SJosef Bacik 			cache->bytes_super += len;
208396f9b0f2SNikolay Borisov 			ret = btrfs_add_excluded_extent(fs_info, logical[nr],
208496f9b0f2SNikolay Borisov 							len);
20854358d963SJosef Bacik 			if (ret) {
20864358d963SJosef Bacik 				kfree(logical);
20874358d963SJosef Bacik 				return ret;
20884358d963SJosef Bacik 			}
20894358d963SJosef Bacik 		}
20904358d963SJosef Bacik 
20914358d963SJosef Bacik 		kfree(logical);
20924358d963SJosef Bacik 	}
20934358d963SJosef Bacik 	return 0;
20944358d963SJosef Bacik }
20954358d963SJosef Bacik 
209632da5386SDavid Sterba static struct btrfs_block_group *btrfs_create_block_group_cache(
20979afc6649SQu Wenruo 		struct btrfs_fs_info *fs_info, u64 start)
20984358d963SJosef Bacik {
209932da5386SDavid Sterba 	struct btrfs_block_group *cache;
21004358d963SJosef Bacik 
21014358d963SJosef Bacik 	cache = kzalloc(sizeof(*cache), GFP_NOFS);
21024358d963SJosef Bacik 	if (!cache)
21034358d963SJosef Bacik 		return NULL;
21044358d963SJosef Bacik 
21054358d963SJosef Bacik 	cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
21064358d963SJosef Bacik 					GFP_NOFS);
21074358d963SJosef Bacik 	if (!cache->free_space_ctl) {
21084358d963SJosef Bacik 		kfree(cache);
21094358d963SJosef Bacik 		return NULL;
21104358d963SJosef Bacik 	}
21114358d963SJosef Bacik 
2112b3470b5dSDavid Sterba 	cache->start = start;
21134358d963SJosef Bacik 
21144358d963SJosef Bacik 	cache->fs_info = fs_info;
21154358d963SJosef Bacik 	cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
21164358d963SJosef Bacik 
21176e80d4f8SDennis Zhou 	cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
21186e80d4f8SDennis Zhou 
211948aaeebeSJosef Bacik 	refcount_set(&cache->refs, 1);
21204358d963SJosef Bacik 	spin_lock_init(&cache->lock);
21214358d963SJosef Bacik 	init_rwsem(&cache->data_rwsem);
21224358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->list);
21234358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->cluster_list);
21244358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->bg_list);
21254358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->ro_list);
2126b0643e59SDennis Zhou 	INIT_LIST_HEAD(&cache->discard_list);
21274358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->dirty_list);
21284358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->io_list);
2129afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&cache->active_bg_list);
2130cd79909bSJosef Bacik 	btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
21316b7304afSFilipe Manana 	atomic_set(&cache->frozen, 0);
21324358d963SJosef Bacik 	mutex_init(&cache->free_space_lock);
2133c29abab4SJosef Bacik 	cache->full_stripe_locks_root.root = RB_ROOT;
2134c29abab4SJosef Bacik 	mutex_init(&cache->full_stripe_locks_root.lock);
21354358d963SJosef Bacik 
21364358d963SJosef Bacik 	return cache;
21374358d963SJosef Bacik }
21384358d963SJosef Bacik 
21394358d963SJosef Bacik /*
21404358d963SJosef Bacik  * Iterate all chunks and verify that each of them has the corresponding block
21414358d963SJosef Bacik  * group
21424358d963SJosef Bacik  */
21434358d963SJosef Bacik static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
21444358d963SJosef Bacik {
21454358d963SJosef Bacik 	struct extent_map_tree *map_tree = &fs_info->mapping_tree;
21464358d963SJosef Bacik 	struct extent_map *em;
214732da5386SDavid Sterba 	struct btrfs_block_group *bg;
21484358d963SJosef Bacik 	u64 start = 0;
21494358d963SJosef Bacik 	int ret = 0;
21504358d963SJosef Bacik 
21514358d963SJosef Bacik 	while (1) {
21524358d963SJosef Bacik 		read_lock(&map_tree->lock);
21534358d963SJosef Bacik 		/*
21544358d963SJosef Bacik 		 * lookup_extent_mapping will return the first extent map
21554358d963SJosef Bacik 		 * intersecting the range, so setting @len to 1 is enough to
21564358d963SJosef Bacik 		 * get the first chunk.
21574358d963SJosef Bacik 		 */
21584358d963SJosef Bacik 		em = lookup_extent_mapping(map_tree, start, 1);
21594358d963SJosef Bacik 		read_unlock(&map_tree->lock);
21604358d963SJosef Bacik 		if (!em)
21614358d963SJosef Bacik 			break;
21624358d963SJosef Bacik 
21634358d963SJosef Bacik 		bg = btrfs_lookup_block_group(fs_info, em->start);
21644358d963SJosef Bacik 		if (!bg) {
21654358d963SJosef Bacik 			btrfs_err(fs_info,
21664358d963SJosef Bacik 	"chunk start=%llu len=%llu doesn't have corresponding block group",
21674358d963SJosef Bacik 				     em->start, em->len);
21684358d963SJosef Bacik 			ret = -EUCLEAN;
21694358d963SJosef Bacik 			free_extent_map(em);
21704358d963SJosef Bacik 			break;
21714358d963SJosef Bacik 		}
2172b3470b5dSDavid Sterba 		if (bg->start != em->start || bg->length != em->len ||
21734358d963SJosef Bacik 		    (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
21744358d963SJosef Bacik 		    (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
21754358d963SJosef Bacik 			btrfs_err(fs_info,
21764358d963SJosef Bacik "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
21774358d963SJosef Bacik 				em->start, em->len,
21784358d963SJosef Bacik 				em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
2179b3470b5dSDavid Sterba 				bg->start, bg->length,
21804358d963SJosef Bacik 				bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
21814358d963SJosef Bacik 			ret = -EUCLEAN;
21824358d963SJosef Bacik 			free_extent_map(em);
21834358d963SJosef Bacik 			btrfs_put_block_group(bg);
21844358d963SJosef Bacik 			break;
21854358d963SJosef Bacik 		}
21864358d963SJosef Bacik 		start = em->start + em->len;
21874358d963SJosef Bacik 		free_extent_map(em);
21884358d963SJosef Bacik 		btrfs_put_block_group(bg);
21894358d963SJosef Bacik 	}
21904358d963SJosef Bacik 	return ret;
21914358d963SJosef Bacik }
21924358d963SJosef Bacik 
2193ffb9e0f0SQu Wenruo static int read_one_block_group(struct btrfs_fs_info *info,
21944afd2fe8SJohannes Thumshirn 				struct btrfs_block_group_item *bgi,
2195d49a2ddbSQu Wenruo 				const struct btrfs_key *key,
2196ffb9e0f0SQu Wenruo 				int need_clear)
2197ffb9e0f0SQu Wenruo {
219832da5386SDavid Sterba 	struct btrfs_block_group *cache;
2199ffb9e0f0SQu Wenruo 	const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
2200ffb9e0f0SQu Wenruo 	int ret;
2201ffb9e0f0SQu Wenruo 
2202d49a2ddbSQu Wenruo 	ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
2203ffb9e0f0SQu Wenruo 
22049afc6649SQu Wenruo 	cache = btrfs_create_block_group_cache(info, key->objectid);
2205ffb9e0f0SQu Wenruo 	if (!cache)
2206ffb9e0f0SQu Wenruo 		return -ENOMEM;
2207ffb9e0f0SQu Wenruo 
22084afd2fe8SJohannes Thumshirn 	cache->length = key->offset;
22094afd2fe8SJohannes Thumshirn 	cache->used = btrfs_stack_block_group_used(bgi);
22107248e0ceSQu Wenruo 	cache->commit_used = cache->used;
22114afd2fe8SJohannes Thumshirn 	cache->flags = btrfs_stack_block_group_flags(bgi);
2212f7238e50SJosef Bacik 	cache->global_root_id = btrfs_stack_block_group_chunk_objectid(bgi);
22139afc6649SQu Wenruo 
2214e3e39c72SMarcos Paulo de Souza 	set_free_space_tree_thresholds(cache);
2215e3e39c72SMarcos Paulo de Souza 
2216ffb9e0f0SQu Wenruo 	if (need_clear) {
2217ffb9e0f0SQu Wenruo 		/*
2218ffb9e0f0SQu Wenruo 		 * When we mount with old space cache, we need to
2219ffb9e0f0SQu Wenruo 		 * set BTRFS_DC_CLEAR and set dirty flag.
2220ffb9e0f0SQu Wenruo 		 *
2221ffb9e0f0SQu Wenruo 		 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
2222ffb9e0f0SQu Wenruo 		 *    truncate the old free space cache inode and
2223ffb9e0f0SQu Wenruo 		 *    setup a new one.
2224ffb9e0f0SQu Wenruo 		 * b) Setting 'dirty flag' makes sure that we flush
2225ffb9e0f0SQu Wenruo 		 *    the new space cache info onto disk.
2226ffb9e0f0SQu Wenruo 		 */
2227ffb9e0f0SQu Wenruo 		if (btrfs_test_opt(info, SPACE_CACHE))
2228ffb9e0f0SQu Wenruo 			cache->disk_cache_state = BTRFS_DC_CLEAR;
2229ffb9e0f0SQu Wenruo 	}
2230ffb9e0f0SQu Wenruo 	if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
2231ffb9e0f0SQu Wenruo 	    (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
2232ffb9e0f0SQu Wenruo 			btrfs_err(info,
2233ffb9e0f0SQu Wenruo "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2234ffb9e0f0SQu Wenruo 				  cache->start);
2235ffb9e0f0SQu Wenruo 			ret = -EINVAL;
2236ffb9e0f0SQu Wenruo 			goto error;
2237ffb9e0f0SQu Wenruo 	}
2238ffb9e0f0SQu Wenruo 
2239a94794d5SNaohiro Aota 	ret = btrfs_load_block_group_zone_info(cache, false);
224008e11a3dSNaohiro Aota 	if (ret) {
224108e11a3dSNaohiro Aota 		btrfs_err(info, "zoned: failed to load zone info of bg %llu",
224208e11a3dSNaohiro Aota 			  cache->start);
224308e11a3dSNaohiro Aota 		goto error;
224408e11a3dSNaohiro Aota 	}
224508e11a3dSNaohiro Aota 
2246ffb9e0f0SQu Wenruo 	/*
2247ffb9e0f0SQu Wenruo 	 * We need to exclude the super stripes now so that the space info has
2248ffb9e0f0SQu Wenruo 	 * super bytes accounted for, otherwise we'll think we have more space
2249ffb9e0f0SQu Wenruo 	 * than we actually do.
2250ffb9e0f0SQu Wenruo 	 */
2251ffb9e0f0SQu Wenruo 	ret = exclude_super_stripes(cache);
2252ffb9e0f0SQu Wenruo 	if (ret) {
2253ffb9e0f0SQu Wenruo 		/* We may have excluded something, so call this just in case. */
2254ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2255ffb9e0f0SQu Wenruo 		goto error;
2256ffb9e0f0SQu Wenruo 	}
2257ffb9e0f0SQu Wenruo 
2258ffb9e0f0SQu Wenruo 	/*
2259169e0da9SNaohiro Aota 	 * For zoned filesystem, space after the allocation offset is the only
2260169e0da9SNaohiro Aota 	 * free space for a block group. So, we don't need any caching work.
2261169e0da9SNaohiro Aota 	 * btrfs_calc_zone_unusable() will set the amount of free space and
2262169e0da9SNaohiro Aota 	 * zone_unusable space.
2263169e0da9SNaohiro Aota 	 *
2264169e0da9SNaohiro Aota 	 * For regular filesystem, check for two cases, either we are full, and
2265169e0da9SNaohiro Aota 	 * therefore don't need to bother with the caching work since we won't
2266169e0da9SNaohiro Aota 	 * find any space, or we are empty, and we can just add all the space
2267169e0da9SNaohiro Aota 	 * in and be done with it.  This saves us _a_lot_ of time, particularly
2268169e0da9SNaohiro Aota 	 * in the full case.
2269ffb9e0f0SQu Wenruo 	 */
2270169e0da9SNaohiro Aota 	if (btrfs_is_zoned(info)) {
2271169e0da9SNaohiro Aota 		btrfs_calc_zone_unusable(cache);
2272c46c4247SNaohiro Aota 		/* Should not have any excluded extents. Just in case, though. */
2273c46c4247SNaohiro Aota 		btrfs_free_excluded_extents(cache);
2274169e0da9SNaohiro Aota 	} else if (cache->length == cache->used) {
2275ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
2276ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2277ffb9e0f0SQu Wenruo 	} else if (cache->used == 0) {
2278ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
22799afc6649SQu Wenruo 		add_new_free_space(cache, cache->start,
22809afc6649SQu Wenruo 				   cache->start + cache->length);
2281ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2282ffb9e0f0SQu Wenruo 	}
2283ffb9e0f0SQu Wenruo 
2284ffb9e0f0SQu Wenruo 	ret = btrfs_add_block_group_cache(info, cache);
2285ffb9e0f0SQu Wenruo 	if (ret) {
2286ffb9e0f0SQu Wenruo 		btrfs_remove_free_space_cache(cache);
2287ffb9e0f0SQu Wenruo 		goto error;
2288ffb9e0f0SQu Wenruo 	}
2289ffb9e0f0SQu Wenruo 	trace_btrfs_add_block_group(info, cache, 0);
2290723de71dSJosef Bacik 	btrfs_add_bg_to_space_info(info, cache);
2291ffb9e0f0SQu Wenruo 
2292ffb9e0f0SQu Wenruo 	set_avail_alloc_bits(info, cache->flags);
2293a09f23c3SAnand Jain 	if (btrfs_chunk_writeable(info, cache->start)) {
2294a09f23c3SAnand Jain 		if (cache->used == 0) {
2295ffb9e0f0SQu Wenruo 			ASSERT(list_empty(&cache->bg_list));
22966e80d4f8SDennis Zhou 			if (btrfs_test_opt(info, DISCARD_ASYNC))
22976e80d4f8SDennis Zhou 				btrfs_discard_queue_work(&info->discard_ctl, cache);
22986e80d4f8SDennis Zhou 			else
2299ffb9e0f0SQu Wenruo 				btrfs_mark_bg_unused(cache);
2300ffb9e0f0SQu Wenruo 		}
2301a09f23c3SAnand Jain 	} else {
2302a09f23c3SAnand Jain 		inc_block_group_ro(cache, 1);
2303a09f23c3SAnand Jain 	}
2304a09f23c3SAnand Jain 
2305ffb9e0f0SQu Wenruo 	return 0;
2306ffb9e0f0SQu Wenruo error:
2307ffb9e0f0SQu Wenruo 	btrfs_put_block_group(cache);
2308ffb9e0f0SQu Wenruo 	return ret;
2309ffb9e0f0SQu Wenruo }
2310ffb9e0f0SQu Wenruo 
231142437a63SJosef Bacik static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
231242437a63SJosef Bacik {
231342437a63SJosef Bacik 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
231442437a63SJosef Bacik 	struct rb_node *node;
231542437a63SJosef Bacik 	int ret = 0;
231642437a63SJosef Bacik 
231742437a63SJosef Bacik 	for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
231842437a63SJosef Bacik 		struct extent_map *em;
231942437a63SJosef Bacik 		struct map_lookup *map;
232042437a63SJosef Bacik 		struct btrfs_block_group *bg;
232142437a63SJosef Bacik 
232242437a63SJosef Bacik 		em = rb_entry(node, struct extent_map, rb_node);
232342437a63SJosef Bacik 		map = em->map_lookup;
232442437a63SJosef Bacik 		bg = btrfs_create_block_group_cache(fs_info, em->start);
232542437a63SJosef Bacik 		if (!bg) {
232642437a63SJosef Bacik 			ret = -ENOMEM;
232742437a63SJosef Bacik 			break;
232842437a63SJosef Bacik 		}
232942437a63SJosef Bacik 
233042437a63SJosef Bacik 		/* Fill dummy cache as FULL */
233142437a63SJosef Bacik 		bg->length = em->len;
233242437a63SJosef Bacik 		bg->flags = map->type;
233342437a63SJosef Bacik 		bg->cached = BTRFS_CACHE_FINISHED;
233442437a63SJosef Bacik 		bg->used = em->len;
233542437a63SJosef Bacik 		bg->flags = map->type;
233642437a63SJosef Bacik 		ret = btrfs_add_block_group_cache(fs_info, bg);
23372b29726cSQu Wenruo 		/*
23382b29726cSQu Wenruo 		 * We may have some valid block group cache added already, in
23392b29726cSQu Wenruo 		 * that case we skip to the next one.
23402b29726cSQu Wenruo 		 */
23412b29726cSQu Wenruo 		if (ret == -EEXIST) {
23422b29726cSQu Wenruo 			ret = 0;
23432b29726cSQu Wenruo 			btrfs_put_block_group(bg);
23442b29726cSQu Wenruo 			continue;
23452b29726cSQu Wenruo 		}
23462b29726cSQu Wenruo 
234742437a63SJosef Bacik 		if (ret) {
234842437a63SJosef Bacik 			btrfs_remove_free_space_cache(bg);
234942437a63SJosef Bacik 			btrfs_put_block_group(bg);
235042437a63SJosef Bacik 			break;
235142437a63SJosef Bacik 		}
23522b29726cSQu Wenruo 
2353723de71dSJosef Bacik 		btrfs_add_bg_to_space_info(fs_info, bg);
235442437a63SJosef Bacik 
235542437a63SJosef Bacik 		set_avail_alloc_bits(fs_info, bg->flags);
235642437a63SJosef Bacik 	}
235742437a63SJosef Bacik 	if (!ret)
235842437a63SJosef Bacik 		btrfs_init_global_block_rsv(fs_info);
235942437a63SJosef Bacik 	return ret;
236042437a63SJosef Bacik }
236142437a63SJosef Bacik 
23624358d963SJosef Bacik int btrfs_read_block_groups(struct btrfs_fs_info *info)
23634358d963SJosef Bacik {
2364dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(info);
23654358d963SJosef Bacik 	struct btrfs_path *path;
23664358d963SJosef Bacik 	int ret;
236732da5386SDavid Sterba 	struct btrfs_block_group *cache;
23684358d963SJosef Bacik 	struct btrfs_space_info *space_info;
23694358d963SJosef Bacik 	struct btrfs_key key;
23704358d963SJosef Bacik 	int need_clear = 0;
23714358d963SJosef Bacik 	u64 cache_gen;
23724358d963SJosef Bacik 
237381d5d614SQu Wenruo 	/*
237481d5d614SQu Wenruo 	 * Either no extent root (with ibadroots rescue option) or we have
237581d5d614SQu Wenruo 	 * unsupported RO options. The fs can never be mounted read-write, so no
237681d5d614SQu Wenruo 	 * need to waste time searching block group items.
237781d5d614SQu Wenruo 	 *
237881d5d614SQu Wenruo 	 * This also allows new extent tree related changes to be RO compat,
237981d5d614SQu Wenruo 	 * no need for a full incompat flag.
238081d5d614SQu Wenruo 	 */
238181d5d614SQu Wenruo 	if (!root || (btrfs_super_compat_ro_flags(info->super_copy) &
238281d5d614SQu Wenruo 		      ~BTRFS_FEATURE_COMPAT_RO_SUPP))
238342437a63SJosef Bacik 		return fill_dummy_bgs(info);
238442437a63SJosef Bacik 
23854358d963SJosef Bacik 	key.objectid = 0;
23864358d963SJosef Bacik 	key.offset = 0;
23874358d963SJosef Bacik 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
23884358d963SJosef Bacik 	path = btrfs_alloc_path();
23894358d963SJosef Bacik 	if (!path)
23904358d963SJosef Bacik 		return -ENOMEM;
23914358d963SJosef Bacik 
23924358d963SJosef Bacik 	cache_gen = btrfs_super_cache_generation(info->super_copy);
23934358d963SJosef Bacik 	if (btrfs_test_opt(info, SPACE_CACHE) &&
23944358d963SJosef Bacik 	    btrfs_super_generation(info->super_copy) != cache_gen)
23954358d963SJosef Bacik 		need_clear = 1;
23964358d963SJosef Bacik 	if (btrfs_test_opt(info, CLEAR_CACHE))
23974358d963SJosef Bacik 		need_clear = 1;
23984358d963SJosef Bacik 
23994358d963SJosef Bacik 	while (1) {
24004afd2fe8SJohannes Thumshirn 		struct btrfs_block_group_item bgi;
24014afd2fe8SJohannes Thumshirn 		struct extent_buffer *leaf;
24024afd2fe8SJohannes Thumshirn 		int slot;
24034afd2fe8SJohannes Thumshirn 
24044358d963SJosef Bacik 		ret = find_first_block_group(info, path, &key);
24054358d963SJosef Bacik 		if (ret > 0)
24064358d963SJosef Bacik 			break;
24074358d963SJosef Bacik 		if (ret != 0)
24084358d963SJosef Bacik 			goto error;
24094358d963SJosef Bacik 
24104afd2fe8SJohannes Thumshirn 		leaf = path->nodes[0];
24114afd2fe8SJohannes Thumshirn 		slot = path->slots[0];
24124afd2fe8SJohannes Thumshirn 
24134afd2fe8SJohannes Thumshirn 		read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
24144afd2fe8SJohannes Thumshirn 				   sizeof(bgi));
24154afd2fe8SJohannes Thumshirn 
24164afd2fe8SJohannes Thumshirn 		btrfs_item_key_to_cpu(leaf, &key, slot);
24174afd2fe8SJohannes Thumshirn 		btrfs_release_path(path);
24184afd2fe8SJohannes Thumshirn 		ret = read_one_block_group(info, &bgi, &key, need_clear);
2419ffb9e0f0SQu Wenruo 		if (ret < 0)
24204358d963SJosef Bacik 			goto error;
2421ffb9e0f0SQu Wenruo 		key.objectid += key.offset;
2422ffb9e0f0SQu Wenruo 		key.offset = 0;
24234358d963SJosef Bacik 	}
24247837fa88SJosef Bacik 	btrfs_release_path(path);
24254358d963SJosef Bacik 
242672804905SJosef Bacik 	list_for_each_entry(space_info, &info->space_info, list) {
242749ea112dSJosef Bacik 		int i;
242849ea112dSJosef Bacik 
242949ea112dSJosef Bacik 		for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
243049ea112dSJosef Bacik 			if (list_empty(&space_info->block_groups[i]))
243149ea112dSJosef Bacik 				continue;
243249ea112dSJosef Bacik 			cache = list_first_entry(&space_info->block_groups[i],
243349ea112dSJosef Bacik 						 struct btrfs_block_group,
243449ea112dSJosef Bacik 						 list);
243549ea112dSJosef Bacik 			btrfs_sysfs_add_block_group_type(cache);
243649ea112dSJosef Bacik 		}
243749ea112dSJosef Bacik 
24384358d963SJosef Bacik 		if (!(btrfs_get_alloc_profile(info, space_info->flags) &
24394358d963SJosef Bacik 		      (BTRFS_BLOCK_GROUP_RAID10 |
24404358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID1_MASK |
24414358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID56_MASK |
24424358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_DUP)))
24434358d963SJosef Bacik 			continue;
24444358d963SJosef Bacik 		/*
24454358d963SJosef Bacik 		 * Avoid allocating from un-mirrored block group if there are
24464358d963SJosef Bacik 		 * mirrored block groups.
24474358d963SJosef Bacik 		 */
24484358d963SJosef Bacik 		list_for_each_entry(cache,
24494358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_RAID0],
24504358d963SJosef Bacik 				list)
2451e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
24524358d963SJosef Bacik 		list_for_each_entry(cache,
24534358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_SINGLE],
24544358d963SJosef Bacik 				list)
2455e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
24564358d963SJosef Bacik 	}
24574358d963SJosef Bacik 
24584358d963SJosef Bacik 	btrfs_init_global_block_rsv(info);
24594358d963SJosef Bacik 	ret = check_chunk_block_group_mappings(info);
24604358d963SJosef Bacik error:
24614358d963SJosef Bacik 	btrfs_free_path(path);
24622b29726cSQu Wenruo 	/*
24632b29726cSQu Wenruo 	 * We've hit some error while reading the extent tree, and have
24642b29726cSQu Wenruo 	 * rescue=ibadroots mount option.
24652b29726cSQu Wenruo 	 * Try to fill the tree using dummy block groups so that the user can
24662b29726cSQu Wenruo 	 * continue to mount and grab their data.
24672b29726cSQu Wenruo 	 */
24682b29726cSQu Wenruo 	if (ret && btrfs_test_opt(info, IGNOREBADROOTS))
24692b29726cSQu Wenruo 		ret = fill_dummy_bgs(info);
24704358d963SJosef Bacik 	return ret;
24714358d963SJosef Bacik }
24724358d963SJosef Bacik 
247379bd3712SFilipe Manana /*
247479bd3712SFilipe Manana  * This function, insert_block_group_item(), belongs to the phase 2 of chunk
247579bd3712SFilipe Manana  * allocation.
247679bd3712SFilipe Manana  *
247779bd3712SFilipe Manana  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
247879bd3712SFilipe Manana  * phases.
247979bd3712SFilipe Manana  */
248097f4728aSQu Wenruo static int insert_block_group_item(struct btrfs_trans_handle *trans,
248197f4728aSQu Wenruo 				   struct btrfs_block_group *block_group)
248297f4728aSQu Wenruo {
248397f4728aSQu Wenruo 	struct btrfs_fs_info *fs_info = trans->fs_info;
248497f4728aSQu Wenruo 	struct btrfs_block_group_item bgi;
2485dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
248697f4728aSQu Wenruo 	struct btrfs_key key;
2487*675dfe12SFilipe Manana 	u64 old_commit_used;
2488*675dfe12SFilipe Manana 	int ret;
248997f4728aSQu Wenruo 
249097f4728aSQu Wenruo 	spin_lock(&block_group->lock);
249197f4728aSQu Wenruo 	btrfs_set_stack_block_group_used(&bgi, block_group->used);
249297f4728aSQu Wenruo 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
2493f7238e50SJosef Bacik 						   block_group->global_root_id);
249497f4728aSQu Wenruo 	btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2495*675dfe12SFilipe Manana 	old_commit_used = block_group->commit_used;
2496*675dfe12SFilipe Manana 	block_group->commit_used = block_group->used;
249797f4728aSQu Wenruo 	key.objectid = block_group->start;
249897f4728aSQu Wenruo 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
249997f4728aSQu Wenruo 	key.offset = block_group->length;
250097f4728aSQu Wenruo 	spin_unlock(&block_group->lock);
250197f4728aSQu Wenruo 
2502*675dfe12SFilipe Manana 	ret = btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2503*675dfe12SFilipe Manana 	if (ret < 0) {
2504*675dfe12SFilipe Manana 		spin_lock(&block_group->lock);
2505*675dfe12SFilipe Manana 		block_group->commit_used = old_commit_used;
2506*675dfe12SFilipe Manana 		spin_unlock(&block_group->lock);
2507*675dfe12SFilipe Manana 	}
2508*675dfe12SFilipe Manana 
2509*675dfe12SFilipe Manana 	return ret;
251097f4728aSQu Wenruo }
251197f4728aSQu Wenruo 
25122eadb9e7SNikolay Borisov static int insert_dev_extent(struct btrfs_trans_handle *trans,
25132eadb9e7SNikolay Borisov 			    struct btrfs_device *device, u64 chunk_offset,
25142eadb9e7SNikolay Borisov 			    u64 start, u64 num_bytes)
25152eadb9e7SNikolay Borisov {
25162eadb9e7SNikolay Borisov 	struct btrfs_fs_info *fs_info = device->fs_info;
25172eadb9e7SNikolay Borisov 	struct btrfs_root *root = fs_info->dev_root;
25182eadb9e7SNikolay Borisov 	struct btrfs_path *path;
25192eadb9e7SNikolay Borisov 	struct btrfs_dev_extent *extent;
25202eadb9e7SNikolay Borisov 	struct extent_buffer *leaf;
25212eadb9e7SNikolay Borisov 	struct btrfs_key key;
25222eadb9e7SNikolay Borisov 	int ret;
25232eadb9e7SNikolay Borisov 
25242eadb9e7SNikolay Borisov 	WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
25252eadb9e7SNikolay Borisov 	WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
25262eadb9e7SNikolay Borisov 	path = btrfs_alloc_path();
25272eadb9e7SNikolay Borisov 	if (!path)
25282eadb9e7SNikolay Borisov 		return -ENOMEM;
25292eadb9e7SNikolay Borisov 
25302eadb9e7SNikolay Borisov 	key.objectid = device->devid;
25312eadb9e7SNikolay Borisov 	key.type = BTRFS_DEV_EXTENT_KEY;
25322eadb9e7SNikolay Borisov 	key.offset = start;
25332eadb9e7SNikolay Borisov 	ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent));
25342eadb9e7SNikolay Borisov 	if (ret)
25352eadb9e7SNikolay Borisov 		goto out;
25362eadb9e7SNikolay Borisov 
25372eadb9e7SNikolay Borisov 	leaf = path->nodes[0];
25382eadb9e7SNikolay Borisov 	extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
25392eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID);
25402eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_objectid(leaf, extent,
25412eadb9e7SNikolay Borisov 					    BTRFS_FIRST_CHUNK_TREE_OBJECTID);
25422eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
25432eadb9e7SNikolay Borisov 
25442eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_length(leaf, extent, num_bytes);
25452eadb9e7SNikolay Borisov 	btrfs_mark_buffer_dirty(leaf);
25462eadb9e7SNikolay Borisov out:
25472eadb9e7SNikolay Borisov 	btrfs_free_path(path);
25482eadb9e7SNikolay Borisov 	return ret;
25492eadb9e7SNikolay Borisov }
25502eadb9e7SNikolay Borisov 
25512eadb9e7SNikolay Borisov /*
25522eadb9e7SNikolay Borisov  * This function belongs to phase 2.
25532eadb9e7SNikolay Borisov  *
25542eadb9e7SNikolay Borisov  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
25552eadb9e7SNikolay Borisov  * phases.
25562eadb9e7SNikolay Borisov  */
25572eadb9e7SNikolay Borisov static int insert_dev_extents(struct btrfs_trans_handle *trans,
25582eadb9e7SNikolay Borisov 				   u64 chunk_offset, u64 chunk_size)
25592eadb9e7SNikolay Borisov {
25602eadb9e7SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
25612eadb9e7SNikolay Borisov 	struct btrfs_device *device;
25622eadb9e7SNikolay Borisov 	struct extent_map *em;
25632eadb9e7SNikolay Borisov 	struct map_lookup *map;
25642eadb9e7SNikolay Borisov 	u64 dev_offset;
25652eadb9e7SNikolay Borisov 	u64 stripe_size;
25662eadb9e7SNikolay Borisov 	int i;
25672eadb9e7SNikolay Borisov 	int ret = 0;
25682eadb9e7SNikolay Borisov 
25692eadb9e7SNikolay Borisov 	em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
25702eadb9e7SNikolay Borisov 	if (IS_ERR(em))
25712eadb9e7SNikolay Borisov 		return PTR_ERR(em);
25722eadb9e7SNikolay Borisov 
25732eadb9e7SNikolay Borisov 	map = em->map_lookup;
25742eadb9e7SNikolay Borisov 	stripe_size = em->orig_block_len;
25752eadb9e7SNikolay Borisov 
25762eadb9e7SNikolay Borisov 	/*
25772eadb9e7SNikolay Borisov 	 * Take the device list mutex to prevent races with the final phase of
25782eadb9e7SNikolay Borisov 	 * a device replace operation that replaces the device object associated
25792eadb9e7SNikolay Borisov 	 * with the map's stripes, because the device object's id can change
25802eadb9e7SNikolay Borisov 	 * at any time during that final phase of the device replace operation
25812eadb9e7SNikolay Borisov 	 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
25822eadb9e7SNikolay Borisov 	 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
25832eadb9e7SNikolay Borisov 	 * resulting in persisting a device extent item with such ID.
25842eadb9e7SNikolay Borisov 	 */
25852eadb9e7SNikolay Borisov 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
25862eadb9e7SNikolay Borisov 	for (i = 0; i < map->num_stripes; i++) {
25872eadb9e7SNikolay Borisov 		device = map->stripes[i].dev;
25882eadb9e7SNikolay Borisov 		dev_offset = map->stripes[i].physical;
25892eadb9e7SNikolay Borisov 
25902eadb9e7SNikolay Borisov 		ret = insert_dev_extent(trans, device, chunk_offset, dev_offset,
25912eadb9e7SNikolay Borisov 				       stripe_size);
25922eadb9e7SNikolay Borisov 		if (ret)
25932eadb9e7SNikolay Borisov 			break;
25942eadb9e7SNikolay Borisov 	}
25952eadb9e7SNikolay Borisov 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
25962eadb9e7SNikolay Borisov 
25972eadb9e7SNikolay Borisov 	free_extent_map(em);
25982eadb9e7SNikolay Borisov 	return ret;
25992eadb9e7SNikolay Borisov }
26002eadb9e7SNikolay Borisov 
260179bd3712SFilipe Manana /*
260279bd3712SFilipe Manana  * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
260379bd3712SFilipe Manana  * chunk allocation.
260479bd3712SFilipe Manana  *
260579bd3712SFilipe Manana  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
260679bd3712SFilipe Manana  * phases.
260779bd3712SFilipe Manana  */
26084358d963SJosef Bacik void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
26094358d963SJosef Bacik {
26104358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
261132da5386SDavid Sterba 	struct btrfs_block_group *block_group;
26124358d963SJosef Bacik 	int ret = 0;
26134358d963SJosef Bacik 
26144358d963SJosef Bacik 	while (!list_empty(&trans->new_bgs)) {
261549ea112dSJosef Bacik 		int index;
261649ea112dSJosef Bacik 
26174358d963SJosef Bacik 		block_group = list_first_entry(&trans->new_bgs,
261832da5386SDavid Sterba 					       struct btrfs_block_group,
26194358d963SJosef Bacik 					       bg_list);
26204358d963SJosef Bacik 		if (ret)
26214358d963SJosef Bacik 			goto next;
26224358d963SJosef Bacik 
262349ea112dSJosef Bacik 		index = btrfs_bg_flags_to_raid_index(block_group->flags);
262449ea112dSJosef Bacik 
262597f4728aSQu Wenruo 		ret = insert_block_group_item(trans, block_group);
26264358d963SJosef Bacik 		if (ret)
26274358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
26283349b57fSJosef Bacik 		if (!test_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED,
26293349b57fSJosef Bacik 			      &block_group->runtime_flags)) {
263079bd3712SFilipe Manana 			mutex_lock(&fs_info->chunk_mutex);
263179bd3712SFilipe Manana 			ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group);
263279bd3712SFilipe Manana 			mutex_unlock(&fs_info->chunk_mutex);
263379bd3712SFilipe Manana 			if (ret)
263479bd3712SFilipe Manana 				btrfs_abort_transaction(trans, ret);
263579bd3712SFilipe Manana 		}
26362eadb9e7SNikolay Borisov 		ret = insert_dev_extents(trans, block_group->start,
263797f4728aSQu Wenruo 					 block_group->length);
26384358d963SJosef Bacik 		if (ret)
26394358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
26404358d963SJosef Bacik 		add_block_group_free_space(trans, block_group);
264149ea112dSJosef Bacik 
264249ea112dSJosef Bacik 		/*
264349ea112dSJosef Bacik 		 * If we restriped during balance, we may have added a new raid
264449ea112dSJosef Bacik 		 * type, so now add the sysfs entries when it is safe to do so.
264549ea112dSJosef Bacik 		 * We don't have to worry about locking here as it's handled in
264649ea112dSJosef Bacik 		 * btrfs_sysfs_add_block_group_type.
264749ea112dSJosef Bacik 		 */
264849ea112dSJosef Bacik 		if (block_group->space_info->block_group_kobjs[index] == NULL)
264949ea112dSJosef Bacik 			btrfs_sysfs_add_block_group_type(block_group);
265049ea112dSJosef Bacik 
26514358d963SJosef Bacik 		/* Already aborted the transaction if it failed. */
26524358d963SJosef Bacik next:
26534358d963SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
26544358d963SJosef Bacik 		list_del_init(&block_group->bg_list);
26554358d963SJosef Bacik 	}
26564358d963SJosef Bacik 	btrfs_trans_release_chunk_metadata(trans);
26574358d963SJosef Bacik }
26584358d963SJosef Bacik 
2659f7238e50SJosef Bacik /*
2660f7238e50SJosef Bacik  * For extent tree v2 we use the block_group_item->chunk_offset to point at our
2661f7238e50SJosef Bacik  * global root id.  For v1 it's always set to BTRFS_FIRST_CHUNK_TREE_OBJECTID.
2662f7238e50SJosef Bacik  */
2663f7238e50SJosef Bacik static u64 calculate_global_root_id(struct btrfs_fs_info *fs_info, u64 offset)
2664f7238e50SJosef Bacik {
2665f7238e50SJosef Bacik 	u64 div = SZ_1G;
2666f7238e50SJosef Bacik 	u64 index;
2667f7238e50SJosef Bacik 
2668f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2669f7238e50SJosef Bacik 		return BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2670f7238e50SJosef Bacik 
2671f7238e50SJosef Bacik 	/* If we have a smaller fs index based on 128MiB. */
2672f7238e50SJosef Bacik 	if (btrfs_super_total_bytes(fs_info->super_copy) <= (SZ_1G * 10ULL))
2673f7238e50SJosef Bacik 		div = SZ_128M;
2674f7238e50SJosef Bacik 
2675f7238e50SJosef Bacik 	offset = div64_u64(offset, div);
2676f7238e50SJosef Bacik 	div64_u64_rem(offset, fs_info->nr_global_roots, &index);
2677f7238e50SJosef Bacik 	return index;
2678f7238e50SJosef Bacik }
2679f7238e50SJosef Bacik 
268079bd3712SFilipe Manana struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
268179bd3712SFilipe Manana 						 u64 bytes_used, u64 type,
268279bd3712SFilipe Manana 						 u64 chunk_offset, u64 size)
26834358d963SJosef Bacik {
26844358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
268532da5386SDavid Sterba 	struct btrfs_block_group *cache;
26864358d963SJosef Bacik 	int ret;
26874358d963SJosef Bacik 
26884358d963SJosef Bacik 	btrfs_set_log_full_commit(trans);
26894358d963SJosef Bacik 
26909afc6649SQu Wenruo 	cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
26914358d963SJosef Bacik 	if (!cache)
269279bd3712SFilipe Manana 		return ERR_PTR(-ENOMEM);
26934358d963SJosef Bacik 
26949afc6649SQu Wenruo 	cache->length = size;
2695e3e39c72SMarcos Paulo de Souza 	set_free_space_tree_thresholds(cache);
2696bf38be65SDavid Sterba 	cache->used = bytes_used;
26974358d963SJosef Bacik 	cache->flags = type;
26984358d963SJosef Bacik 	cache->cached = BTRFS_CACHE_FINISHED;
2699f7238e50SJosef Bacik 	cache->global_root_id = calculate_global_root_id(fs_info, cache->start);
2700f7238e50SJosef Bacik 
2701997e3e2eSBoris Burkov 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
27020d7764ffSDavid Sterba 		set_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE, &cache->runtime_flags);
270308e11a3dSNaohiro Aota 
2704a94794d5SNaohiro Aota 	ret = btrfs_load_block_group_zone_info(cache, true);
270508e11a3dSNaohiro Aota 	if (ret) {
270608e11a3dSNaohiro Aota 		btrfs_put_block_group(cache);
270779bd3712SFilipe Manana 		return ERR_PTR(ret);
270808e11a3dSNaohiro Aota 	}
270908e11a3dSNaohiro Aota 
27104358d963SJosef Bacik 	ret = exclude_super_stripes(cache);
27114358d963SJosef Bacik 	if (ret) {
27124358d963SJosef Bacik 		/* We may have excluded something, so call this just in case */
27134358d963SJosef Bacik 		btrfs_free_excluded_extents(cache);
27144358d963SJosef Bacik 		btrfs_put_block_group(cache);
271579bd3712SFilipe Manana 		return ERR_PTR(ret);
27164358d963SJosef Bacik 	}
27174358d963SJosef Bacik 
27184358d963SJosef Bacik 	add_new_free_space(cache, chunk_offset, chunk_offset + size);
27194358d963SJosef Bacik 
27204358d963SJosef Bacik 	btrfs_free_excluded_extents(cache);
27214358d963SJosef Bacik 
27224358d963SJosef Bacik 	/*
27234358d963SJosef Bacik 	 * Ensure the corresponding space_info object is created and
27244358d963SJosef Bacik 	 * assigned to our block group. We want our bg to be added to the rbtree
27254358d963SJosef Bacik 	 * with its ->space_info set.
27264358d963SJosef Bacik 	 */
27274358d963SJosef Bacik 	cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
27284358d963SJosef Bacik 	ASSERT(cache->space_info);
27294358d963SJosef Bacik 
27304358d963SJosef Bacik 	ret = btrfs_add_block_group_cache(fs_info, cache);
27314358d963SJosef Bacik 	if (ret) {
27324358d963SJosef Bacik 		btrfs_remove_free_space_cache(cache);
27334358d963SJosef Bacik 		btrfs_put_block_group(cache);
273479bd3712SFilipe Manana 		return ERR_PTR(ret);
27354358d963SJosef Bacik 	}
27364358d963SJosef Bacik 
27374358d963SJosef Bacik 	/*
27384358d963SJosef Bacik 	 * Now that our block group has its ->space_info set and is inserted in
27394358d963SJosef Bacik 	 * the rbtree, update the space info's counters.
27404358d963SJosef Bacik 	 */
27414358d963SJosef Bacik 	trace_btrfs_add_block_group(fs_info, cache, 1);
2742723de71dSJosef Bacik 	btrfs_add_bg_to_space_info(fs_info, cache);
27434358d963SJosef Bacik 	btrfs_update_global_block_rsv(fs_info);
27444358d963SJosef Bacik 
27459d4b0a12SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
27469d4b0a12SJosef Bacik 	if (btrfs_should_fragment_free_space(cache)) {
27479d4b0a12SJosef Bacik 		u64 new_bytes_used = size - bytes_used;
27489d4b0a12SJosef Bacik 
27499d4b0a12SJosef Bacik 		cache->space_info->bytes_used += new_bytes_used >> 1;
27509d4b0a12SJosef Bacik 		fragment_free_space(cache);
27519d4b0a12SJosef Bacik 	}
27529d4b0a12SJosef Bacik #endif
27534358d963SJosef Bacik 
27544358d963SJosef Bacik 	list_add_tail(&cache->bg_list, &trans->new_bgs);
27554358d963SJosef Bacik 	trans->delayed_ref_updates++;
27564358d963SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
27574358d963SJosef Bacik 
27584358d963SJosef Bacik 	set_avail_alloc_bits(fs_info, type);
275979bd3712SFilipe Manana 	return cache;
27604358d963SJosef Bacik }
276126ce2095SJosef Bacik 
2762b12de528SQu Wenruo /*
2763b12de528SQu Wenruo  * Mark one block group RO, can be called several times for the same block
2764b12de528SQu Wenruo  * group.
2765b12de528SQu Wenruo  *
2766b12de528SQu Wenruo  * @cache:		the destination block group
2767b12de528SQu Wenruo  * @do_chunk_alloc:	whether need to do chunk pre-allocation, this is to
2768b12de528SQu Wenruo  * 			ensure we still have some free space after marking this
2769b12de528SQu Wenruo  * 			block group RO.
2770b12de528SQu Wenruo  */
2771b12de528SQu Wenruo int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2772b12de528SQu Wenruo 			     bool do_chunk_alloc)
277326ce2095SJosef Bacik {
277426ce2095SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
277526ce2095SJosef Bacik 	struct btrfs_trans_handle *trans;
2776dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
277726ce2095SJosef Bacik 	u64 alloc_flags;
277826ce2095SJosef Bacik 	int ret;
2779b6e9f16cSNikolay Borisov 	bool dirty_bg_running;
278026ce2095SJosef Bacik 
27812d192fc4SQu Wenruo 	/*
27822d192fc4SQu Wenruo 	 * This can only happen when we are doing read-only scrub on read-only
27832d192fc4SQu Wenruo 	 * mount.
27842d192fc4SQu Wenruo 	 * In that case we should not start a new transaction on read-only fs.
27852d192fc4SQu Wenruo 	 * Thus here we skip all chunk allocations.
27862d192fc4SQu Wenruo 	 */
27872d192fc4SQu Wenruo 	if (sb_rdonly(fs_info->sb)) {
27882d192fc4SQu Wenruo 		mutex_lock(&fs_info->ro_block_group_mutex);
27892d192fc4SQu Wenruo 		ret = inc_block_group_ro(cache, 0);
27902d192fc4SQu Wenruo 		mutex_unlock(&fs_info->ro_block_group_mutex);
27912d192fc4SQu Wenruo 		return ret;
27922d192fc4SQu Wenruo 	}
27932d192fc4SQu Wenruo 
2794b6e9f16cSNikolay Borisov 	do {
2795dfe8aec4SJosef Bacik 		trans = btrfs_join_transaction(root);
279626ce2095SJosef Bacik 		if (IS_ERR(trans))
279726ce2095SJosef Bacik 			return PTR_ERR(trans);
279826ce2095SJosef Bacik 
2799b6e9f16cSNikolay Borisov 		dirty_bg_running = false;
2800b6e9f16cSNikolay Borisov 
280126ce2095SJosef Bacik 		/*
2802b6e9f16cSNikolay Borisov 		 * We're not allowed to set block groups readonly after the dirty
2803b6e9f16cSNikolay Borisov 		 * block group cache has started writing.  If it already started,
2804b6e9f16cSNikolay Borisov 		 * back off and let this transaction commit.
280526ce2095SJosef Bacik 		 */
280626ce2095SJosef Bacik 		mutex_lock(&fs_info->ro_block_group_mutex);
280726ce2095SJosef Bacik 		if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
280826ce2095SJosef Bacik 			u64 transid = trans->transid;
280926ce2095SJosef Bacik 
281026ce2095SJosef Bacik 			mutex_unlock(&fs_info->ro_block_group_mutex);
281126ce2095SJosef Bacik 			btrfs_end_transaction(trans);
281226ce2095SJosef Bacik 
281326ce2095SJosef Bacik 			ret = btrfs_wait_for_commit(fs_info, transid);
281426ce2095SJosef Bacik 			if (ret)
281526ce2095SJosef Bacik 				return ret;
2816b6e9f16cSNikolay Borisov 			dirty_bg_running = true;
281726ce2095SJosef Bacik 		}
2818b6e9f16cSNikolay Borisov 	} while (dirty_bg_running);
281926ce2095SJosef Bacik 
2820b12de528SQu Wenruo 	if (do_chunk_alloc) {
282126ce2095SJosef Bacik 		/*
2822b12de528SQu Wenruo 		 * If we are changing raid levels, try to allocate a
2823b12de528SQu Wenruo 		 * corresponding block group with the new raid level.
282426ce2095SJosef Bacik 		 */
2825349e120eSJosef Bacik 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
282626ce2095SJosef Bacik 		if (alloc_flags != cache->flags) {
2827b12de528SQu Wenruo 			ret = btrfs_chunk_alloc(trans, alloc_flags,
2828b12de528SQu Wenruo 						CHUNK_ALLOC_FORCE);
282926ce2095SJosef Bacik 			/*
283026ce2095SJosef Bacik 			 * ENOSPC is allowed here, we may have enough space
2831b12de528SQu Wenruo 			 * already allocated at the new raid level to carry on
283226ce2095SJosef Bacik 			 */
283326ce2095SJosef Bacik 			if (ret == -ENOSPC)
283426ce2095SJosef Bacik 				ret = 0;
283526ce2095SJosef Bacik 			if (ret < 0)
283626ce2095SJosef Bacik 				goto out;
283726ce2095SJosef Bacik 		}
2838b12de528SQu Wenruo 	}
283926ce2095SJosef Bacik 
2840a7a63accSJosef Bacik 	ret = inc_block_group_ro(cache, 0);
2841195a49eaSFilipe Manana 	if (!do_chunk_alloc || ret == -ETXTBSY)
2842b12de528SQu Wenruo 		goto unlock_out;
284326ce2095SJosef Bacik 	if (!ret)
284426ce2095SJosef Bacik 		goto out;
284526ce2095SJosef Bacik 	alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
284626ce2095SJosef Bacik 	ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
284726ce2095SJosef Bacik 	if (ret < 0)
284826ce2095SJosef Bacik 		goto out;
2849b6a98021SNaohiro Aota 	/*
2850b6a98021SNaohiro Aota 	 * We have allocated a new chunk. We also need to activate that chunk to
2851b6a98021SNaohiro Aota 	 * grant metadata tickets for zoned filesystem.
2852b6a98021SNaohiro Aota 	 */
2853b6a98021SNaohiro Aota 	ret = btrfs_zoned_activate_one_bg(fs_info, cache->space_info, true);
2854b6a98021SNaohiro Aota 	if (ret < 0)
2855b6a98021SNaohiro Aota 		goto out;
2856b6a98021SNaohiro Aota 
2857e11c0406SJosef Bacik 	ret = inc_block_group_ro(cache, 0);
2858195a49eaSFilipe Manana 	if (ret == -ETXTBSY)
2859195a49eaSFilipe Manana 		goto unlock_out;
286026ce2095SJosef Bacik out:
286126ce2095SJosef Bacik 	if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2862349e120eSJosef Bacik 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
286326ce2095SJosef Bacik 		mutex_lock(&fs_info->chunk_mutex);
286426ce2095SJosef Bacik 		check_system_chunk(trans, alloc_flags);
286526ce2095SJosef Bacik 		mutex_unlock(&fs_info->chunk_mutex);
286626ce2095SJosef Bacik 	}
2867b12de528SQu Wenruo unlock_out:
286826ce2095SJosef Bacik 	mutex_unlock(&fs_info->ro_block_group_mutex);
286926ce2095SJosef Bacik 
287026ce2095SJosef Bacik 	btrfs_end_transaction(trans);
287126ce2095SJosef Bacik 	return ret;
287226ce2095SJosef Bacik }
287326ce2095SJosef Bacik 
287432da5386SDavid Sterba void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
287526ce2095SJosef Bacik {
287626ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
287726ce2095SJosef Bacik 	u64 num_bytes;
287826ce2095SJosef Bacik 
287926ce2095SJosef Bacik 	BUG_ON(!cache->ro);
288026ce2095SJosef Bacik 
288126ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
288226ce2095SJosef Bacik 	spin_lock(&cache->lock);
288326ce2095SJosef Bacik 	if (!--cache->ro) {
2884169e0da9SNaohiro Aota 		if (btrfs_is_zoned(cache->fs_info)) {
2885169e0da9SNaohiro Aota 			/* Migrate zone_unusable bytes back */
288698173255SNaohiro Aota 			cache->zone_unusable =
288798173255SNaohiro Aota 				(cache->alloc_offset - cache->used) +
288898173255SNaohiro Aota 				(cache->length - cache->zone_capacity);
2889169e0da9SNaohiro Aota 			sinfo->bytes_zone_unusable += cache->zone_unusable;
2890169e0da9SNaohiro Aota 			sinfo->bytes_readonly -= cache->zone_unusable;
2891169e0da9SNaohiro Aota 		}
2892f9f28e5bSNaohiro Aota 		num_bytes = cache->length - cache->reserved -
2893f9f28e5bSNaohiro Aota 			    cache->pinned - cache->bytes_super -
2894f9f28e5bSNaohiro Aota 			    cache->zone_unusable - cache->used;
2895f9f28e5bSNaohiro Aota 		sinfo->bytes_readonly -= num_bytes;
289626ce2095SJosef Bacik 		list_del_init(&cache->ro_list);
289726ce2095SJosef Bacik 	}
289826ce2095SJosef Bacik 	spin_unlock(&cache->lock);
289926ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
290026ce2095SJosef Bacik }
290177745c05SJosef Bacik 
29023be4d8efSQu Wenruo static int update_block_group_item(struct btrfs_trans_handle *trans,
290377745c05SJosef Bacik 				   struct btrfs_path *path,
290432da5386SDavid Sterba 				   struct btrfs_block_group *cache)
290577745c05SJosef Bacik {
290677745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
290777745c05SJosef Bacik 	int ret;
2908dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
290977745c05SJosef Bacik 	unsigned long bi;
291077745c05SJosef Bacik 	struct extent_buffer *leaf;
2911bf38be65SDavid Sterba 	struct btrfs_block_group_item bgi;
2912b3470b5dSDavid Sterba 	struct btrfs_key key;
29137248e0ceSQu Wenruo 	u64 old_commit_used;
29147248e0ceSQu Wenruo 	u64 used;
29157248e0ceSQu Wenruo 
29167248e0ceSQu Wenruo 	/*
29177248e0ceSQu Wenruo 	 * Block group items update can be triggered out of commit transaction
29187248e0ceSQu Wenruo 	 * critical section, thus we need a consistent view of used bytes.
29197248e0ceSQu Wenruo 	 * We cannot use cache->used directly outside of the spin lock, as it
29207248e0ceSQu Wenruo 	 * may be changed.
29217248e0ceSQu Wenruo 	 */
29227248e0ceSQu Wenruo 	spin_lock(&cache->lock);
29237248e0ceSQu Wenruo 	old_commit_used = cache->commit_used;
29247248e0ceSQu Wenruo 	used = cache->used;
29257248e0ceSQu Wenruo 	/* No change in used bytes, can safely skip it. */
29267248e0ceSQu Wenruo 	if (cache->commit_used == used) {
29277248e0ceSQu Wenruo 		spin_unlock(&cache->lock);
29287248e0ceSQu Wenruo 		return 0;
29297248e0ceSQu Wenruo 	}
29307248e0ceSQu Wenruo 	cache->commit_used = used;
29317248e0ceSQu Wenruo 	spin_unlock(&cache->lock);
293277745c05SJosef Bacik 
2933b3470b5dSDavid Sterba 	key.objectid = cache->start;
2934b3470b5dSDavid Sterba 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2935b3470b5dSDavid Sterba 	key.offset = cache->length;
2936b3470b5dSDavid Sterba 
29373be4d8efSQu Wenruo 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
293877745c05SJosef Bacik 	if (ret) {
293977745c05SJosef Bacik 		if (ret > 0)
294077745c05SJosef Bacik 			ret = -ENOENT;
294177745c05SJosef Bacik 		goto fail;
294277745c05SJosef Bacik 	}
294377745c05SJosef Bacik 
294477745c05SJosef Bacik 	leaf = path->nodes[0];
294577745c05SJosef Bacik 	bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
29467248e0ceSQu Wenruo 	btrfs_set_stack_block_group_used(&bgi, used);
2947de0dc456SDavid Sterba 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
2948f7238e50SJosef Bacik 						   cache->global_root_id);
2949de0dc456SDavid Sterba 	btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2950bf38be65SDavid Sterba 	write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
295177745c05SJosef Bacik 	btrfs_mark_buffer_dirty(leaf);
295277745c05SJosef Bacik fail:
295377745c05SJosef Bacik 	btrfs_release_path(path);
29547248e0ceSQu Wenruo 	/* We didn't update the block group item, need to revert @commit_used. */
29557248e0ceSQu Wenruo 	if (ret < 0) {
29567248e0ceSQu Wenruo 		spin_lock(&cache->lock);
29577248e0ceSQu Wenruo 		cache->commit_used = old_commit_used;
29587248e0ceSQu Wenruo 		spin_unlock(&cache->lock);
29597248e0ceSQu Wenruo 	}
296077745c05SJosef Bacik 	return ret;
296177745c05SJosef Bacik 
296277745c05SJosef Bacik }
296377745c05SJosef Bacik 
296432da5386SDavid Sterba static int cache_save_setup(struct btrfs_block_group *block_group,
296577745c05SJosef Bacik 			    struct btrfs_trans_handle *trans,
296677745c05SJosef Bacik 			    struct btrfs_path *path)
296777745c05SJosef Bacik {
296877745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
296977745c05SJosef Bacik 	struct btrfs_root *root = fs_info->tree_root;
297077745c05SJosef Bacik 	struct inode *inode = NULL;
297177745c05SJosef Bacik 	struct extent_changeset *data_reserved = NULL;
297277745c05SJosef Bacik 	u64 alloc_hint = 0;
297377745c05SJosef Bacik 	int dcs = BTRFS_DC_ERROR;
29740044ae11SQu Wenruo 	u64 cache_size = 0;
297577745c05SJosef Bacik 	int retries = 0;
297677745c05SJosef Bacik 	int ret = 0;
297777745c05SJosef Bacik 
2978af456a2cSBoris Burkov 	if (!btrfs_test_opt(fs_info, SPACE_CACHE))
2979af456a2cSBoris Burkov 		return 0;
2980af456a2cSBoris Burkov 
298177745c05SJosef Bacik 	/*
298277745c05SJosef Bacik 	 * If this block group is smaller than 100 megs don't bother caching the
298377745c05SJosef Bacik 	 * block group.
298477745c05SJosef Bacik 	 */
2985b3470b5dSDavid Sterba 	if (block_group->length < (100 * SZ_1M)) {
298677745c05SJosef Bacik 		spin_lock(&block_group->lock);
298777745c05SJosef Bacik 		block_group->disk_cache_state = BTRFS_DC_WRITTEN;
298877745c05SJosef Bacik 		spin_unlock(&block_group->lock);
298977745c05SJosef Bacik 		return 0;
299077745c05SJosef Bacik 	}
299177745c05SJosef Bacik 
2992bf31f87fSDavid Sterba 	if (TRANS_ABORTED(trans))
299377745c05SJosef Bacik 		return 0;
299477745c05SJosef Bacik again:
299577745c05SJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
299677745c05SJosef Bacik 	if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
299777745c05SJosef Bacik 		ret = PTR_ERR(inode);
299877745c05SJosef Bacik 		btrfs_release_path(path);
299977745c05SJosef Bacik 		goto out;
300077745c05SJosef Bacik 	}
300177745c05SJosef Bacik 
300277745c05SJosef Bacik 	if (IS_ERR(inode)) {
300377745c05SJosef Bacik 		BUG_ON(retries);
300477745c05SJosef Bacik 		retries++;
300577745c05SJosef Bacik 
300677745c05SJosef Bacik 		if (block_group->ro)
300777745c05SJosef Bacik 			goto out_free;
300877745c05SJosef Bacik 
300977745c05SJosef Bacik 		ret = create_free_space_inode(trans, block_group, path);
301077745c05SJosef Bacik 		if (ret)
301177745c05SJosef Bacik 			goto out_free;
301277745c05SJosef Bacik 		goto again;
301377745c05SJosef Bacik 	}
301477745c05SJosef Bacik 
301577745c05SJosef Bacik 	/*
301677745c05SJosef Bacik 	 * We want to set the generation to 0, that way if anything goes wrong
301777745c05SJosef Bacik 	 * from here on out we know not to trust this cache when we load up next
301877745c05SJosef Bacik 	 * time.
301977745c05SJosef Bacik 	 */
302077745c05SJosef Bacik 	BTRFS_I(inode)->generation = 0;
30219a56fcd1SNikolay Borisov 	ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
302277745c05SJosef Bacik 	if (ret) {
302377745c05SJosef Bacik 		/*
302477745c05SJosef Bacik 		 * So theoretically we could recover from this, simply set the
302577745c05SJosef Bacik 		 * super cache generation to 0 so we know to invalidate the
302677745c05SJosef Bacik 		 * cache, but then we'd have to keep track of the block groups
302777745c05SJosef Bacik 		 * that fail this way so we know we _have_ to reset this cache
302877745c05SJosef Bacik 		 * before the next commit or risk reading stale cache.  So to
302977745c05SJosef Bacik 		 * limit our exposure to horrible edge cases lets just abort the
303077745c05SJosef Bacik 		 * transaction, this only happens in really bad situations
303177745c05SJosef Bacik 		 * anyway.
303277745c05SJosef Bacik 		 */
303377745c05SJosef Bacik 		btrfs_abort_transaction(trans, ret);
303477745c05SJosef Bacik 		goto out_put;
303577745c05SJosef Bacik 	}
303677745c05SJosef Bacik 	WARN_ON(ret);
303777745c05SJosef Bacik 
303877745c05SJosef Bacik 	/* We've already setup this transaction, go ahead and exit */
303977745c05SJosef Bacik 	if (block_group->cache_generation == trans->transid &&
304077745c05SJosef Bacik 	    i_size_read(inode)) {
304177745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
304277745c05SJosef Bacik 		goto out_put;
304377745c05SJosef Bacik 	}
304477745c05SJosef Bacik 
304577745c05SJosef Bacik 	if (i_size_read(inode) > 0) {
304677745c05SJosef Bacik 		ret = btrfs_check_trunc_cache_free_space(fs_info,
304777745c05SJosef Bacik 					&fs_info->global_block_rsv);
304877745c05SJosef Bacik 		if (ret)
304977745c05SJosef Bacik 			goto out_put;
305077745c05SJosef Bacik 
305177745c05SJosef Bacik 		ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
305277745c05SJosef Bacik 		if (ret)
305377745c05SJosef Bacik 			goto out_put;
305477745c05SJosef Bacik 	}
305577745c05SJosef Bacik 
305677745c05SJosef Bacik 	spin_lock(&block_group->lock);
305777745c05SJosef Bacik 	if (block_group->cached != BTRFS_CACHE_FINISHED ||
305877745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE)) {
305977745c05SJosef Bacik 		/*
306077745c05SJosef Bacik 		 * don't bother trying to write stuff out _if_
306177745c05SJosef Bacik 		 * a) we're not cached,
306277745c05SJosef Bacik 		 * b) we're with nospace_cache mount option,
306377745c05SJosef Bacik 		 * c) we're with v2 space_cache (FREE_SPACE_TREE).
306477745c05SJosef Bacik 		 */
306577745c05SJosef Bacik 		dcs = BTRFS_DC_WRITTEN;
306677745c05SJosef Bacik 		spin_unlock(&block_group->lock);
306777745c05SJosef Bacik 		goto out_put;
306877745c05SJosef Bacik 	}
306977745c05SJosef Bacik 	spin_unlock(&block_group->lock);
307077745c05SJosef Bacik 
307177745c05SJosef Bacik 	/*
307277745c05SJosef Bacik 	 * We hit an ENOSPC when setting up the cache in this transaction, just
307377745c05SJosef Bacik 	 * skip doing the setup, we've already cleared the cache so we're safe.
307477745c05SJosef Bacik 	 */
307577745c05SJosef Bacik 	if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
307677745c05SJosef Bacik 		ret = -ENOSPC;
307777745c05SJosef Bacik 		goto out_put;
307877745c05SJosef Bacik 	}
307977745c05SJosef Bacik 
308077745c05SJosef Bacik 	/*
308177745c05SJosef Bacik 	 * Try to preallocate enough space based on how big the block group is.
308277745c05SJosef Bacik 	 * Keep in mind this has to include any pinned space which could end up
308377745c05SJosef Bacik 	 * taking up quite a bit since it's not folded into the other space
308477745c05SJosef Bacik 	 * cache.
308577745c05SJosef Bacik 	 */
30860044ae11SQu Wenruo 	cache_size = div_u64(block_group->length, SZ_256M);
30870044ae11SQu Wenruo 	if (!cache_size)
30880044ae11SQu Wenruo 		cache_size = 1;
308977745c05SJosef Bacik 
30900044ae11SQu Wenruo 	cache_size *= 16;
30910044ae11SQu Wenruo 	cache_size *= fs_info->sectorsize;
309277745c05SJosef Bacik 
309336ea6f3eSNikolay Borisov 	ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
30941daedb1dSJosef Bacik 					  cache_size, false);
309577745c05SJosef Bacik 	if (ret)
309677745c05SJosef Bacik 		goto out_put;
309777745c05SJosef Bacik 
30980044ae11SQu Wenruo 	ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
30990044ae11SQu Wenruo 					      cache_size, cache_size,
310077745c05SJosef Bacik 					      &alloc_hint);
310177745c05SJosef Bacik 	/*
310277745c05SJosef Bacik 	 * Our cache requires contiguous chunks so that we don't modify a bunch
310377745c05SJosef Bacik 	 * of metadata or split extents when writing the cache out, which means
310477745c05SJosef Bacik 	 * we can enospc if we are heavily fragmented in addition to just normal
310577745c05SJosef Bacik 	 * out of space conditions.  So if we hit this just skip setting up any
310677745c05SJosef Bacik 	 * other block groups for this transaction, maybe we'll unpin enough
310777745c05SJosef Bacik 	 * space the next time around.
310877745c05SJosef Bacik 	 */
310977745c05SJosef Bacik 	if (!ret)
311077745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
311177745c05SJosef Bacik 	else if (ret == -ENOSPC)
311277745c05SJosef Bacik 		set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
311377745c05SJosef Bacik 
311477745c05SJosef Bacik out_put:
311577745c05SJosef Bacik 	iput(inode);
311677745c05SJosef Bacik out_free:
311777745c05SJosef Bacik 	btrfs_release_path(path);
311877745c05SJosef Bacik out:
311977745c05SJosef Bacik 	spin_lock(&block_group->lock);
312077745c05SJosef Bacik 	if (!ret && dcs == BTRFS_DC_SETUP)
312177745c05SJosef Bacik 		block_group->cache_generation = trans->transid;
312277745c05SJosef Bacik 	block_group->disk_cache_state = dcs;
312377745c05SJosef Bacik 	spin_unlock(&block_group->lock);
312477745c05SJosef Bacik 
312577745c05SJosef Bacik 	extent_changeset_free(data_reserved);
312677745c05SJosef Bacik 	return ret;
312777745c05SJosef Bacik }
312877745c05SJosef Bacik 
312977745c05SJosef Bacik int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
313077745c05SJosef Bacik {
313177745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
313232da5386SDavid Sterba 	struct btrfs_block_group *cache, *tmp;
313377745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
313477745c05SJosef Bacik 	struct btrfs_path *path;
313577745c05SJosef Bacik 
313677745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs) ||
313777745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE))
313877745c05SJosef Bacik 		return 0;
313977745c05SJosef Bacik 
314077745c05SJosef Bacik 	path = btrfs_alloc_path();
314177745c05SJosef Bacik 	if (!path)
314277745c05SJosef Bacik 		return -ENOMEM;
314377745c05SJosef Bacik 
314477745c05SJosef Bacik 	/* Could add new block groups, use _safe just in case */
314577745c05SJosef Bacik 	list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
314677745c05SJosef Bacik 				 dirty_list) {
314777745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_CLEAR)
314877745c05SJosef Bacik 			cache_save_setup(cache, trans, path);
314977745c05SJosef Bacik 	}
315077745c05SJosef Bacik 
315177745c05SJosef Bacik 	btrfs_free_path(path);
315277745c05SJosef Bacik 	return 0;
315377745c05SJosef Bacik }
315477745c05SJosef Bacik 
315577745c05SJosef Bacik /*
315677745c05SJosef Bacik  * Transaction commit does final block group cache writeback during a critical
315777745c05SJosef Bacik  * section where nothing is allowed to change the FS.  This is required in
315877745c05SJosef Bacik  * order for the cache to actually match the block group, but can introduce a
315977745c05SJosef Bacik  * lot of latency into the commit.
316077745c05SJosef Bacik  *
316177745c05SJosef Bacik  * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
316277745c05SJosef Bacik  * There's a chance we'll have to redo some of it if the block group changes
316377745c05SJosef Bacik  * again during the commit, but it greatly reduces the commit latency by
316477745c05SJosef Bacik  * getting rid of the easy block groups while we're still allowing others to
316577745c05SJosef Bacik  * join the commit.
316677745c05SJosef Bacik  */
316777745c05SJosef Bacik int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
316877745c05SJosef Bacik {
316977745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
317032da5386SDavid Sterba 	struct btrfs_block_group *cache;
317177745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
317277745c05SJosef Bacik 	int ret = 0;
317377745c05SJosef Bacik 	int should_put;
317477745c05SJosef Bacik 	struct btrfs_path *path = NULL;
317577745c05SJosef Bacik 	LIST_HEAD(dirty);
317677745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
317777745c05SJosef Bacik 	int loops = 0;
317877745c05SJosef Bacik 
317977745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
318077745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs)) {
318177745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
318277745c05SJosef Bacik 		return 0;
318377745c05SJosef Bacik 	}
318477745c05SJosef Bacik 	list_splice_init(&cur_trans->dirty_bgs, &dirty);
318577745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
318677745c05SJosef Bacik 
318777745c05SJosef Bacik again:
318877745c05SJosef Bacik 	/* Make sure all the block groups on our dirty list actually exist */
318977745c05SJosef Bacik 	btrfs_create_pending_block_groups(trans);
319077745c05SJosef Bacik 
319177745c05SJosef Bacik 	if (!path) {
319277745c05SJosef Bacik 		path = btrfs_alloc_path();
3193938fcbfbSJosef Bacik 		if (!path) {
3194938fcbfbSJosef Bacik 			ret = -ENOMEM;
3195938fcbfbSJosef Bacik 			goto out;
3196938fcbfbSJosef Bacik 		}
319777745c05SJosef Bacik 	}
319877745c05SJosef Bacik 
319977745c05SJosef Bacik 	/*
320077745c05SJosef Bacik 	 * cache_write_mutex is here only to save us from balance or automatic
320177745c05SJosef Bacik 	 * removal of empty block groups deleting this block group while we are
320277745c05SJosef Bacik 	 * writing out the cache
320377745c05SJosef Bacik 	 */
320477745c05SJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
320577745c05SJosef Bacik 	while (!list_empty(&dirty)) {
320677745c05SJosef Bacik 		bool drop_reserve = true;
320777745c05SJosef Bacik 
320832da5386SDavid Sterba 		cache = list_first_entry(&dirty, struct btrfs_block_group,
320977745c05SJosef Bacik 					 dirty_list);
321077745c05SJosef Bacik 		/*
321177745c05SJosef Bacik 		 * This can happen if something re-dirties a block group that
321277745c05SJosef Bacik 		 * is already under IO.  Just wait for it to finish and then do
321377745c05SJosef Bacik 		 * it all again
321477745c05SJosef Bacik 		 */
321577745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
321677745c05SJosef Bacik 			list_del_init(&cache->io_list);
321777745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
321877745c05SJosef Bacik 			btrfs_put_block_group(cache);
321977745c05SJosef Bacik 		}
322077745c05SJosef Bacik 
322177745c05SJosef Bacik 
322277745c05SJosef Bacik 		/*
322377745c05SJosef Bacik 		 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
322477745c05SJosef Bacik 		 * it should update the cache_state.  Don't delete until after
322577745c05SJosef Bacik 		 * we wait.
322677745c05SJosef Bacik 		 *
322777745c05SJosef Bacik 		 * Since we're not running in the commit critical section
322877745c05SJosef Bacik 		 * we need the dirty_bgs_lock to protect from update_block_group
322977745c05SJosef Bacik 		 */
323077745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
323177745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
323277745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
323377745c05SJosef Bacik 
323477745c05SJosef Bacik 		should_put = 1;
323577745c05SJosef Bacik 
323677745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
323777745c05SJosef Bacik 
323877745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_SETUP) {
323977745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
324077745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
324177745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
324277745c05SJosef Bacik 				should_put = 0;
324377745c05SJosef Bacik 
324477745c05SJosef Bacik 				/*
324577745c05SJosef Bacik 				 * The cache_write_mutex is protecting the
324677745c05SJosef Bacik 				 * io_list, also refer to the definition of
324777745c05SJosef Bacik 				 * btrfs_transaction::io_bgs for more details
324877745c05SJosef Bacik 				 */
324977745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
325077745c05SJosef Bacik 			} else {
325177745c05SJosef Bacik 				/*
325277745c05SJosef Bacik 				 * If we failed to write the cache, the
325377745c05SJosef Bacik 				 * generation will be bad and life goes on
325477745c05SJosef Bacik 				 */
325577745c05SJosef Bacik 				ret = 0;
325677745c05SJosef Bacik 			}
325777745c05SJosef Bacik 		}
325877745c05SJosef Bacik 		if (!ret) {
32593be4d8efSQu Wenruo 			ret = update_block_group_item(trans, path, cache);
326077745c05SJosef Bacik 			/*
326177745c05SJosef Bacik 			 * Our block group might still be attached to the list
326277745c05SJosef Bacik 			 * of new block groups in the transaction handle of some
326377745c05SJosef Bacik 			 * other task (struct btrfs_trans_handle->new_bgs). This
326477745c05SJosef Bacik 			 * means its block group item isn't yet in the extent
326577745c05SJosef Bacik 			 * tree. If this happens ignore the error, as we will
326677745c05SJosef Bacik 			 * try again later in the critical section of the
326777745c05SJosef Bacik 			 * transaction commit.
326877745c05SJosef Bacik 			 */
326977745c05SJosef Bacik 			if (ret == -ENOENT) {
327077745c05SJosef Bacik 				ret = 0;
327177745c05SJosef Bacik 				spin_lock(&cur_trans->dirty_bgs_lock);
327277745c05SJosef Bacik 				if (list_empty(&cache->dirty_list)) {
327377745c05SJosef Bacik 					list_add_tail(&cache->dirty_list,
327477745c05SJosef Bacik 						      &cur_trans->dirty_bgs);
327577745c05SJosef Bacik 					btrfs_get_block_group(cache);
327677745c05SJosef Bacik 					drop_reserve = false;
327777745c05SJosef Bacik 				}
327877745c05SJosef Bacik 				spin_unlock(&cur_trans->dirty_bgs_lock);
327977745c05SJosef Bacik 			} else if (ret) {
328077745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
328177745c05SJosef Bacik 			}
328277745c05SJosef Bacik 		}
328377745c05SJosef Bacik 
328477745c05SJosef Bacik 		/* If it's not on the io list, we need to put the block group */
328577745c05SJosef Bacik 		if (should_put)
328677745c05SJosef Bacik 			btrfs_put_block_group(cache);
328777745c05SJosef Bacik 		if (drop_reserve)
328877745c05SJosef Bacik 			btrfs_delayed_refs_rsv_release(fs_info, 1);
328977745c05SJosef Bacik 		/*
329077745c05SJosef Bacik 		 * Avoid blocking other tasks for too long. It might even save
329177745c05SJosef Bacik 		 * us from writing caches for block groups that are going to be
329277745c05SJosef Bacik 		 * removed.
329377745c05SJosef Bacik 		 */
329477745c05SJosef Bacik 		mutex_unlock(&trans->transaction->cache_write_mutex);
3295938fcbfbSJosef Bacik 		if (ret)
3296938fcbfbSJosef Bacik 			goto out;
329777745c05SJosef Bacik 		mutex_lock(&trans->transaction->cache_write_mutex);
329877745c05SJosef Bacik 	}
329977745c05SJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
330077745c05SJosef Bacik 
330177745c05SJosef Bacik 	/*
330277745c05SJosef Bacik 	 * Go through delayed refs for all the stuff we've just kicked off
330377745c05SJosef Bacik 	 * and then loop back (just once)
330477745c05SJosef Bacik 	 */
330534d1eb0eSJosef Bacik 	if (!ret)
330677745c05SJosef Bacik 		ret = btrfs_run_delayed_refs(trans, 0);
330777745c05SJosef Bacik 	if (!ret && loops == 0) {
330877745c05SJosef Bacik 		loops++;
330977745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
331077745c05SJosef Bacik 		list_splice_init(&cur_trans->dirty_bgs, &dirty);
331177745c05SJosef Bacik 		/*
331277745c05SJosef Bacik 		 * dirty_bgs_lock protects us from concurrent block group
331377745c05SJosef Bacik 		 * deletes too (not just cache_write_mutex).
331477745c05SJosef Bacik 		 */
331577745c05SJosef Bacik 		if (!list_empty(&dirty)) {
331677745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
331777745c05SJosef Bacik 			goto again;
331877745c05SJosef Bacik 		}
331977745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
3320938fcbfbSJosef Bacik 	}
3321938fcbfbSJosef Bacik out:
3322938fcbfbSJosef Bacik 	if (ret < 0) {
3323938fcbfbSJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
3324938fcbfbSJosef Bacik 		list_splice_init(&dirty, &cur_trans->dirty_bgs);
3325938fcbfbSJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
332677745c05SJosef Bacik 		btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
332777745c05SJosef Bacik 	}
332877745c05SJosef Bacik 
332977745c05SJosef Bacik 	btrfs_free_path(path);
333077745c05SJosef Bacik 	return ret;
333177745c05SJosef Bacik }
333277745c05SJosef Bacik 
333377745c05SJosef Bacik int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
333477745c05SJosef Bacik {
333577745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
333632da5386SDavid Sterba 	struct btrfs_block_group *cache;
333777745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
333877745c05SJosef Bacik 	int ret = 0;
333977745c05SJosef Bacik 	int should_put;
334077745c05SJosef Bacik 	struct btrfs_path *path;
334177745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
334277745c05SJosef Bacik 
334377745c05SJosef Bacik 	path = btrfs_alloc_path();
334477745c05SJosef Bacik 	if (!path)
334577745c05SJosef Bacik 		return -ENOMEM;
334677745c05SJosef Bacik 
334777745c05SJosef Bacik 	/*
334877745c05SJosef Bacik 	 * Even though we are in the critical section of the transaction commit,
334977745c05SJosef Bacik 	 * we can still have concurrent tasks adding elements to this
335077745c05SJosef Bacik 	 * transaction's list of dirty block groups. These tasks correspond to
335177745c05SJosef Bacik 	 * endio free space workers started when writeback finishes for a
335277745c05SJosef Bacik 	 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
335377745c05SJosef Bacik 	 * allocate new block groups as a result of COWing nodes of the root
335477745c05SJosef Bacik 	 * tree when updating the free space inode. The writeback for the space
335577745c05SJosef Bacik 	 * caches is triggered by an earlier call to
335677745c05SJosef Bacik 	 * btrfs_start_dirty_block_groups() and iterations of the following
335777745c05SJosef Bacik 	 * loop.
335877745c05SJosef Bacik 	 * Also we want to do the cache_save_setup first and then run the
335977745c05SJosef Bacik 	 * delayed refs to make sure we have the best chance at doing this all
336077745c05SJosef Bacik 	 * in one shot.
336177745c05SJosef Bacik 	 */
336277745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
336377745c05SJosef Bacik 	while (!list_empty(&cur_trans->dirty_bgs)) {
336477745c05SJosef Bacik 		cache = list_first_entry(&cur_trans->dirty_bgs,
336532da5386SDavid Sterba 					 struct btrfs_block_group,
336677745c05SJosef Bacik 					 dirty_list);
336777745c05SJosef Bacik 
336877745c05SJosef Bacik 		/*
336977745c05SJosef Bacik 		 * This can happen if cache_save_setup re-dirties a block group
337077745c05SJosef Bacik 		 * that is already under IO.  Just wait for it to finish and
337177745c05SJosef Bacik 		 * then do it all again
337277745c05SJosef Bacik 		 */
337377745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
337477745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
337577745c05SJosef Bacik 			list_del_init(&cache->io_list);
337677745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
337777745c05SJosef Bacik 			btrfs_put_block_group(cache);
337877745c05SJosef Bacik 			spin_lock(&cur_trans->dirty_bgs_lock);
337977745c05SJosef Bacik 		}
338077745c05SJosef Bacik 
338177745c05SJosef Bacik 		/*
338277745c05SJosef Bacik 		 * Don't remove from the dirty list until after we've waited on
338377745c05SJosef Bacik 		 * any pending IO
338477745c05SJosef Bacik 		 */
338577745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
338677745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
338777745c05SJosef Bacik 		should_put = 1;
338877745c05SJosef Bacik 
338977745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
339077745c05SJosef Bacik 
339177745c05SJosef Bacik 		if (!ret)
339277745c05SJosef Bacik 			ret = btrfs_run_delayed_refs(trans,
339377745c05SJosef Bacik 						     (unsigned long) -1);
339477745c05SJosef Bacik 
339577745c05SJosef Bacik 		if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
339677745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
339777745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
339877745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
339977745c05SJosef Bacik 				should_put = 0;
340077745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
340177745c05SJosef Bacik 			} else {
340277745c05SJosef Bacik 				/*
340377745c05SJosef Bacik 				 * If we failed to write the cache, the
340477745c05SJosef Bacik 				 * generation will be bad and life goes on
340577745c05SJosef Bacik 				 */
340677745c05SJosef Bacik 				ret = 0;
340777745c05SJosef Bacik 			}
340877745c05SJosef Bacik 		}
340977745c05SJosef Bacik 		if (!ret) {
34103be4d8efSQu Wenruo 			ret = update_block_group_item(trans, path, cache);
341177745c05SJosef Bacik 			/*
341277745c05SJosef Bacik 			 * One of the free space endio workers might have
341377745c05SJosef Bacik 			 * created a new block group while updating a free space
341477745c05SJosef Bacik 			 * cache's inode (at inode.c:btrfs_finish_ordered_io())
341577745c05SJosef Bacik 			 * and hasn't released its transaction handle yet, in
341677745c05SJosef Bacik 			 * which case the new block group is still attached to
341777745c05SJosef Bacik 			 * its transaction handle and its creation has not
341877745c05SJosef Bacik 			 * finished yet (no block group item in the extent tree
341977745c05SJosef Bacik 			 * yet, etc). If this is the case, wait for all free
342077745c05SJosef Bacik 			 * space endio workers to finish and retry. This is a
3421260db43cSRandy Dunlap 			 * very rare case so no need for a more efficient and
342277745c05SJosef Bacik 			 * complex approach.
342377745c05SJosef Bacik 			 */
342477745c05SJosef Bacik 			if (ret == -ENOENT) {
342577745c05SJosef Bacik 				wait_event(cur_trans->writer_wait,
342677745c05SJosef Bacik 				   atomic_read(&cur_trans->num_writers) == 1);
34273be4d8efSQu Wenruo 				ret = update_block_group_item(trans, path, cache);
342877745c05SJosef Bacik 			}
342977745c05SJosef Bacik 			if (ret)
343077745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
343177745c05SJosef Bacik 		}
343277745c05SJosef Bacik 
343377745c05SJosef Bacik 		/* If its not on the io list, we need to put the block group */
343477745c05SJosef Bacik 		if (should_put)
343577745c05SJosef Bacik 			btrfs_put_block_group(cache);
343677745c05SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
343777745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
343877745c05SJosef Bacik 	}
343977745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
344077745c05SJosef Bacik 
344177745c05SJosef Bacik 	/*
344277745c05SJosef Bacik 	 * Refer to the definition of io_bgs member for details why it's safe
344377745c05SJosef Bacik 	 * to use it without any locking
344477745c05SJosef Bacik 	 */
344577745c05SJosef Bacik 	while (!list_empty(io)) {
344632da5386SDavid Sterba 		cache = list_first_entry(io, struct btrfs_block_group,
344777745c05SJosef Bacik 					 io_list);
344877745c05SJosef Bacik 		list_del_init(&cache->io_list);
344977745c05SJosef Bacik 		btrfs_wait_cache_io(trans, cache, path);
345077745c05SJosef Bacik 		btrfs_put_block_group(cache);
345177745c05SJosef Bacik 	}
345277745c05SJosef Bacik 
345377745c05SJosef Bacik 	btrfs_free_path(path);
345477745c05SJosef Bacik 	return ret;
345577745c05SJosef Bacik }
3456606d1bf1SJosef Bacik 
3457606d1bf1SJosef Bacik int btrfs_update_block_group(struct btrfs_trans_handle *trans,
345811b66fa6SAnand Jain 			     u64 bytenr, u64 num_bytes, bool alloc)
3459606d1bf1SJosef Bacik {
3460606d1bf1SJosef Bacik 	struct btrfs_fs_info *info = trans->fs_info;
346132da5386SDavid Sterba 	struct btrfs_block_group *cache = NULL;
3462606d1bf1SJosef Bacik 	u64 total = num_bytes;
3463606d1bf1SJosef Bacik 	u64 old_val;
3464606d1bf1SJosef Bacik 	u64 byte_in_group;
3465606d1bf1SJosef Bacik 	int factor;
3466606d1bf1SJosef Bacik 	int ret = 0;
3467606d1bf1SJosef Bacik 
3468606d1bf1SJosef Bacik 	/* Block accounting for super block */
3469606d1bf1SJosef Bacik 	spin_lock(&info->delalloc_root_lock);
3470606d1bf1SJosef Bacik 	old_val = btrfs_super_bytes_used(info->super_copy);
3471606d1bf1SJosef Bacik 	if (alloc)
3472606d1bf1SJosef Bacik 		old_val += num_bytes;
3473606d1bf1SJosef Bacik 	else
3474606d1bf1SJosef Bacik 		old_val -= num_bytes;
3475606d1bf1SJosef Bacik 	btrfs_set_super_bytes_used(info->super_copy, old_val);
3476606d1bf1SJosef Bacik 	spin_unlock(&info->delalloc_root_lock);
3477606d1bf1SJosef Bacik 
3478606d1bf1SJosef Bacik 	while (total) {
3479efbf35a1SJosef Bacik 		bool reclaim = false;
3480ac2f1e63SJosef Bacik 
3481606d1bf1SJosef Bacik 		cache = btrfs_lookup_block_group(info, bytenr);
3482606d1bf1SJosef Bacik 		if (!cache) {
3483606d1bf1SJosef Bacik 			ret = -ENOENT;
3484606d1bf1SJosef Bacik 			break;
3485606d1bf1SJosef Bacik 		}
3486606d1bf1SJosef Bacik 		factor = btrfs_bg_type_to_factor(cache->flags);
3487606d1bf1SJosef Bacik 
3488606d1bf1SJosef Bacik 		/*
3489606d1bf1SJosef Bacik 		 * If this block group has free space cache written out, we
3490606d1bf1SJosef Bacik 		 * need to make sure to load it if we are removing space.  This
3491606d1bf1SJosef Bacik 		 * is because we need the unpinning stage to actually add the
3492606d1bf1SJosef Bacik 		 * space back to the block group, otherwise we will leak space.
3493606d1bf1SJosef Bacik 		 */
349432da5386SDavid Sterba 		if (!alloc && !btrfs_block_group_done(cache))
3495ced8ecf0SOmar Sandoval 			btrfs_cache_block_group(cache, true);
3496606d1bf1SJosef Bacik 
3497b3470b5dSDavid Sterba 		byte_in_group = bytenr - cache->start;
3498b3470b5dSDavid Sterba 		WARN_ON(byte_in_group > cache->length);
3499606d1bf1SJosef Bacik 
3500606d1bf1SJosef Bacik 		spin_lock(&cache->space_info->lock);
3501606d1bf1SJosef Bacik 		spin_lock(&cache->lock);
3502606d1bf1SJosef Bacik 
3503606d1bf1SJosef Bacik 		if (btrfs_test_opt(info, SPACE_CACHE) &&
3504606d1bf1SJosef Bacik 		    cache->disk_cache_state < BTRFS_DC_CLEAR)
3505606d1bf1SJosef Bacik 			cache->disk_cache_state = BTRFS_DC_CLEAR;
3506606d1bf1SJosef Bacik 
3507bf38be65SDavid Sterba 		old_val = cache->used;
3508b3470b5dSDavid Sterba 		num_bytes = min(total, cache->length - byte_in_group);
3509606d1bf1SJosef Bacik 		if (alloc) {
3510606d1bf1SJosef Bacik 			old_val += num_bytes;
3511bf38be65SDavid Sterba 			cache->used = old_val;
3512606d1bf1SJosef Bacik 			cache->reserved -= num_bytes;
3513606d1bf1SJosef Bacik 			cache->space_info->bytes_reserved -= num_bytes;
3514606d1bf1SJosef Bacik 			cache->space_info->bytes_used += num_bytes;
3515606d1bf1SJosef Bacik 			cache->space_info->disk_used += num_bytes * factor;
3516606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
3517606d1bf1SJosef Bacik 			spin_unlock(&cache->space_info->lock);
3518606d1bf1SJosef Bacik 		} else {
3519606d1bf1SJosef Bacik 			old_val -= num_bytes;
3520bf38be65SDavid Sterba 			cache->used = old_val;
3521606d1bf1SJosef Bacik 			cache->pinned += num_bytes;
3522606d1bf1SJosef Bacik 			btrfs_space_info_update_bytes_pinned(info,
3523606d1bf1SJosef Bacik 					cache->space_info, num_bytes);
3524606d1bf1SJosef Bacik 			cache->space_info->bytes_used -= num_bytes;
3525606d1bf1SJosef Bacik 			cache->space_info->disk_used -= num_bytes * factor;
3526ac2f1e63SJosef Bacik 
3527ac2f1e63SJosef Bacik 			reclaim = should_reclaim_block_group(cache, num_bytes);
352852bb7a21SBoris Burkov 
3529606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
3530606d1bf1SJosef Bacik 			spin_unlock(&cache->space_info->lock);
3531606d1bf1SJosef Bacik 
3532fe119a6eSNikolay Borisov 			set_extent_dirty(&trans->transaction->pinned_extents,
3533606d1bf1SJosef Bacik 					 bytenr, bytenr + num_bytes - 1,
3534606d1bf1SJosef Bacik 					 GFP_NOFS | __GFP_NOFAIL);
3535606d1bf1SJosef Bacik 		}
3536606d1bf1SJosef Bacik 
3537606d1bf1SJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
3538606d1bf1SJosef Bacik 		if (list_empty(&cache->dirty_list)) {
3539606d1bf1SJosef Bacik 			list_add_tail(&cache->dirty_list,
3540606d1bf1SJosef Bacik 				      &trans->transaction->dirty_bgs);
3541606d1bf1SJosef Bacik 			trans->delayed_ref_updates++;
3542606d1bf1SJosef Bacik 			btrfs_get_block_group(cache);
3543606d1bf1SJosef Bacik 		}
3544606d1bf1SJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
3545606d1bf1SJosef Bacik 
3546606d1bf1SJosef Bacik 		/*
3547606d1bf1SJosef Bacik 		 * No longer have used bytes in this block group, queue it for
3548606d1bf1SJosef Bacik 		 * deletion. We do this after adding the block group to the
3549606d1bf1SJosef Bacik 		 * dirty list to avoid races between cleaner kthread and space
3550606d1bf1SJosef Bacik 		 * cache writeout.
3551606d1bf1SJosef Bacik 		 */
35526e80d4f8SDennis Zhou 		if (!alloc && old_val == 0) {
35536e80d4f8SDennis Zhou 			if (!btrfs_test_opt(info, DISCARD_ASYNC))
3554606d1bf1SJosef Bacik 				btrfs_mark_bg_unused(cache);
3555ac2f1e63SJosef Bacik 		} else if (!alloc && reclaim) {
3556ac2f1e63SJosef Bacik 			btrfs_mark_bg_to_reclaim(cache);
35576e80d4f8SDennis Zhou 		}
3558606d1bf1SJosef Bacik 
3559606d1bf1SJosef Bacik 		btrfs_put_block_group(cache);
3560606d1bf1SJosef Bacik 		total -= num_bytes;
3561606d1bf1SJosef Bacik 		bytenr += num_bytes;
3562606d1bf1SJosef Bacik 	}
3563606d1bf1SJosef Bacik 
3564606d1bf1SJosef Bacik 	/* Modified block groups are accounted for in the delayed_refs_rsv. */
3565606d1bf1SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
3566606d1bf1SJosef Bacik 	return ret;
3567606d1bf1SJosef Bacik }
3568606d1bf1SJosef Bacik 
356943dd529aSDavid Sterba /*
357043dd529aSDavid Sterba  * Update the block_group and space info counters.
357143dd529aSDavid Sterba  *
3572606d1bf1SJosef Bacik  * @cache:	The cache we are manipulating
3573606d1bf1SJosef Bacik  * @ram_bytes:  The number of bytes of file content, and will be same to
3574606d1bf1SJosef Bacik  *              @num_bytes except for the compress path.
3575606d1bf1SJosef Bacik  * @num_bytes:	The number of bytes in question
3576606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
3577606d1bf1SJosef Bacik  *
3578606d1bf1SJosef Bacik  * This is called by the allocator when it reserves space. If this is a
3579606d1bf1SJosef Bacik  * reservation and the block group has become read only we cannot make the
3580606d1bf1SJosef Bacik  * reservation and return -EAGAIN, otherwise this function always succeeds.
3581606d1bf1SJosef Bacik  */
358232da5386SDavid Sterba int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
358352bb7a21SBoris Burkov 			     u64 ram_bytes, u64 num_bytes, int delalloc,
358452bb7a21SBoris Burkov 			     bool force_wrong_size_class)
3585606d1bf1SJosef Bacik {
3586606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
358752bb7a21SBoris Burkov 	enum btrfs_block_group_size_class size_class;
3588606d1bf1SJosef Bacik 	int ret = 0;
3589606d1bf1SJosef Bacik 
3590606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
3591606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
3592606d1bf1SJosef Bacik 	if (cache->ro) {
3593606d1bf1SJosef Bacik 		ret = -EAGAIN;
359452bb7a21SBoris Burkov 		goto out;
359552bb7a21SBoris Burkov 	}
359652bb7a21SBoris Burkov 
3597cb0922f2SBoris Burkov 	if (btrfs_block_group_should_use_size_class(cache)) {
359852bb7a21SBoris Burkov 		size_class = btrfs_calc_block_group_size_class(num_bytes);
359952bb7a21SBoris Burkov 		ret = btrfs_use_block_group_size_class(cache, size_class, force_wrong_size_class);
360052bb7a21SBoris Burkov 		if (ret)
360152bb7a21SBoris Burkov 			goto out;
360252bb7a21SBoris Burkov 	}
3603606d1bf1SJosef Bacik 	cache->reserved += num_bytes;
3604606d1bf1SJosef Bacik 	space_info->bytes_reserved += num_bytes;
3605a43c3835SJosef Bacik 	trace_btrfs_space_reservation(cache->fs_info, "space_info",
3606a43c3835SJosef Bacik 				      space_info->flags, num_bytes, 1);
3607606d1bf1SJosef Bacik 	btrfs_space_info_update_bytes_may_use(cache->fs_info,
3608606d1bf1SJosef Bacik 					      space_info, -ram_bytes);
3609606d1bf1SJosef Bacik 	if (delalloc)
3610606d1bf1SJosef Bacik 		cache->delalloc_bytes += num_bytes;
361199ffb43eSJosef Bacik 
361299ffb43eSJosef Bacik 	/*
361352bb7a21SBoris Burkov 	 * Compression can use less space than we reserved, so wake tickets if
361452bb7a21SBoris Burkov 	 * that happens.
361599ffb43eSJosef Bacik 	 */
361699ffb43eSJosef Bacik 	if (num_bytes < ram_bytes)
361799ffb43eSJosef Bacik 		btrfs_try_granting_tickets(cache->fs_info, space_info);
361852bb7a21SBoris Burkov out:
3619606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
3620606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
3621606d1bf1SJosef Bacik 	return ret;
3622606d1bf1SJosef Bacik }
3623606d1bf1SJosef Bacik 
362443dd529aSDavid Sterba /*
362543dd529aSDavid Sterba  * Update the block_group and space info counters.
362643dd529aSDavid Sterba  *
3627606d1bf1SJosef Bacik  * @cache:      The cache we are manipulating
3628606d1bf1SJosef Bacik  * @num_bytes:  The number of bytes in question
3629606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
3630606d1bf1SJosef Bacik  *
3631606d1bf1SJosef Bacik  * This is called by somebody who is freeing space that was never actually used
3632606d1bf1SJosef Bacik  * on disk.  For example if you reserve some space for a new leaf in transaction
3633606d1bf1SJosef Bacik  * A and before transaction A commits you free that leaf, you call this with
3634606d1bf1SJosef Bacik  * reserve set to 0 in order to clear the reservation.
3635606d1bf1SJosef Bacik  */
363632da5386SDavid Sterba void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3637606d1bf1SJosef Bacik 			       u64 num_bytes, int delalloc)
3638606d1bf1SJosef Bacik {
3639606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
3640606d1bf1SJosef Bacik 
3641606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
3642606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
3643606d1bf1SJosef Bacik 	if (cache->ro)
3644606d1bf1SJosef Bacik 		space_info->bytes_readonly += num_bytes;
3645606d1bf1SJosef Bacik 	cache->reserved -= num_bytes;
3646606d1bf1SJosef Bacik 	space_info->bytes_reserved -= num_bytes;
3647606d1bf1SJosef Bacik 	space_info->max_extent_size = 0;
3648606d1bf1SJosef Bacik 
3649606d1bf1SJosef Bacik 	if (delalloc)
3650606d1bf1SJosef Bacik 		cache->delalloc_bytes -= num_bytes;
3651606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
36523308234aSJosef Bacik 
36533308234aSJosef Bacik 	btrfs_try_granting_tickets(cache->fs_info, space_info);
3654606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
3655606d1bf1SJosef Bacik }
365607730d87SJosef Bacik 
365707730d87SJosef Bacik static void force_metadata_allocation(struct btrfs_fs_info *info)
365807730d87SJosef Bacik {
365907730d87SJosef Bacik 	struct list_head *head = &info->space_info;
366007730d87SJosef Bacik 	struct btrfs_space_info *found;
366107730d87SJosef Bacik 
366272804905SJosef Bacik 	list_for_each_entry(found, head, list) {
366307730d87SJosef Bacik 		if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
366407730d87SJosef Bacik 			found->force_alloc = CHUNK_ALLOC_FORCE;
366507730d87SJosef Bacik 	}
366607730d87SJosef Bacik }
366707730d87SJosef Bacik 
366807730d87SJosef Bacik static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
366907730d87SJosef Bacik 			      struct btrfs_space_info *sinfo, int force)
367007730d87SJosef Bacik {
367107730d87SJosef Bacik 	u64 bytes_used = btrfs_space_info_used(sinfo, false);
367207730d87SJosef Bacik 	u64 thresh;
367307730d87SJosef Bacik 
367407730d87SJosef Bacik 	if (force == CHUNK_ALLOC_FORCE)
367507730d87SJosef Bacik 		return 1;
367607730d87SJosef Bacik 
367707730d87SJosef Bacik 	/*
367807730d87SJosef Bacik 	 * in limited mode, we want to have some free space up to
367907730d87SJosef Bacik 	 * about 1% of the FS size.
368007730d87SJosef Bacik 	 */
368107730d87SJosef Bacik 	if (force == CHUNK_ALLOC_LIMITED) {
368207730d87SJosef Bacik 		thresh = btrfs_super_total_bytes(fs_info->super_copy);
3683428c8e03SDavid Sterba 		thresh = max_t(u64, SZ_64M, mult_perc(thresh, 1));
368407730d87SJosef Bacik 
368507730d87SJosef Bacik 		if (sinfo->total_bytes - bytes_used < thresh)
368607730d87SJosef Bacik 			return 1;
368707730d87SJosef Bacik 	}
368807730d87SJosef Bacik 
3689428c8e03SDavid Sterba 	if (bytes_used + SZ_2M < mult_perc(sinfo->total_bytes, 80))
369007730d87SJosef Bacik 		return 0;
369107730d87SJosef Bacik 	return 1;
369207730d87SJosef Bacik }
369307730d87SJosef Bacik 
369407730d87SJosef Bacik int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
369507730d87SJosef Bacik {
369607730d87SJosef Bacik 	u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
369707730d87SJosef Bacik 
369807730d87SJosef Bacik 	return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
369907730d87SJosef Bacik }
370007730d87SJosef Bacik 
3701820c363bSNaohiro Aota static struct btrfs_block_group *do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags)
370279bd3712SFilipe Manana {
370379bd3712SFilipe Manana 	struct btrfs_block_group *bg;
370479bd3712SFilipe Manana 	int ret;
370579bd3712SFilipe Manana 
370607730d87SJosef Bacik 	/*
370779bd3712SFilipe Manana 	 * Check if we have enough space in the system space info because we
370879bd3712SFilipe Manana 	 * will need to update device items in the chunk btree and insert a new
370979bd3712SFilipe Manana 	 * chunk item in the chunk btree as well. This will allocate a new
371079bd3712SFilipe Manana 	 * system block group if needed.
371179bd3712SFilipe Manana 	 */
371279bd3712SFilipe Manana 	check_system_chunk(trans, flags);
371379bd3712SFilipe Manana 
3714f6f39f7aSNikolay Borisov 	bg = btrfs_create_chunk(trans, flags);
371579bd3712SFilipe Manana 	if (IS_ERR(bg)) {
371679bd3712SFilipe Manana 		ret = PTR_ERR(bg);
371779bd3712SFilipe Manana 		goto out;
371879bd3712SFilipe Manana 	}
371979bd3712SFilipe Manana 
372079bd3712SFilipe Manana 	ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
372179bd3712SFilipe Manana 	/*
372279bd3712SFilipe Manana 	 * Normally we are not expected to fail with -ENOSPC here, since we have
372379bd3712SFilipe Manana 	 * previously reserved space in the system space_info and allocated one
3724ecd84d54SFilipe Manana 	 * new system chunk if necessary. However there are three exceptions:
372579bd3712SFilipe Manana 	 *
372679bd3712SFilipe Manana 	 * 1) We may have enough free space in the system space_info but all the
372779bd3712SFilipe Manana 	 *    existing system block groups have a profile which can not be used
372879bd3712SFilipe Manana 	 *    for extent allocation.
372979bd3712SFilipe Manana 	 *
373079bd3712SFilipe Manana 	 *    This happens when mounting in degraded mode. For example we have a
373179bd3712SFilipe Manana 	 *    RAID1 filesystem with 2 devices, lose one device and mount the fs
373279bd3712SFilipe Manana 	 *    using the other device in degraded mode. If we then allocate a chunk,
373379bd3712SFilipe Manana 	 *    we may have enough free space in the existing system space_info, but
373479bd3712SFilipe Manana 	 *    none of the block groups can be used for extent allocation since they
373579bd3712SFilipe Manana 	 *    have a RAID1 profile, and because we are in degraded mode with a
373679bd3712SFilipe Manana 	 *    single device, we are forced to allocate a new system chunk with a
373779bd3712SFilipe Manana 	 *    SINGLE profile. Making check_system_chunk() iterate over all system
373879bd3712SFilipe Manana 	 *    block groups and check if they have a usable profile and enough space
373979bd3712SFilipe Manana 	 *    can be slow on very large filesystems, so we tolerate the -ENOSPC and
374079bd3712SFilipe Manana 	 *    try again after forcing allocation of a new system chunk. Like this
374179bd3712SFilipe Manana 	 *    we avoid paying the cost of that search in normal circumstances, when
374279bd3712SFilipe Manana 	 *    we were not mounted in degraded mode;
374379bd3712SFilipe Manana 	 *
374479bd3712SFilipe Manana 	 * 2) We had enough free space info the system space_info, and one suitable
374579bd3712SFilipe Manana 	 *    block group to allocate from when we called check_system_chunk()
374679bd3712SFilipe Manana 	 *    above. However right after we called it, the only system block group
374779bd3712SFilipe Manana 	 *    with enough free space got turned into RO mode by a running scrub,
374879bd3712SFilipe Manana 	 *    and in this case we have to allocate a new one and retry. We only
374979bd3712SFilipe Manana 	 *    need do this allocate and retry once, since we have a transaction
3750ecd84d54SFilipe Manana 	 *    handle and scrub uses the commit root to search for block groups;
3751ecd84d54SFilipe Manana 	 *
3752ecd84d54SFilipe Manana 	 * 3) We had one system block group with enough free space when we called
3753ecd84d54SFilipe Manana 	 *    check_system_chunk(), but after that, right before we tried to
3754ecd84d54SFilipe Manana 	 *    allocate the last extent buffer we needed, a discard operation came
3755ecd84d54SFilipe Manana 	 *    in and it temporarily removed the last free space entry from the
3756ecd84d54SFilipe Manana 	 *    block group (discard removes a free space entry, discards it, and
3757ecd84d54SFilipe Manana 	 *    then adds back the entry to the block group cache).
375879bd3712SFilipe Manana 	 */
375979bd3712SFilipe Manana 	if (ret == -ENOSPC) {
376079bd3712SFilipe Manana 		const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info);
376179bd3712SFilipe Manana 		struct btrfs_block_group *sys_bg;
376279bd3712SFilipe Manana 
3763f6f39f7aSNikolay Borisov 		sys_bg = btrfs_create_chunk(trans, sys_flags);
376479bd3712SFilipe Manana 		if (IS_ERR(sys_bg)) {
376579bd3712SFilipe Manana 			ret = PTR_ERR(sys_bg);
376679bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
376779bd3712SFilipe Manana 			goto out;
376879bd3712SFilipe Manana 		}
376979bd3712SFilipe Manana 
377079bd3712SFilipe Manana 		ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
377179bd3712SFilipe Manana 		if (ret) {
377279bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
377379bd3712SFilipe Manana 			goto out;
377479bd3712SFilipe Manana 		}
377579bd3712SFilipe Manana 
377679bd3712SFilipe Manana 		ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
377779bd3712SFilipe Manana 		if (ret) {
377879bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
377979bd3712SFilipe Manana 			goto out;
378079bd3712SFilipe Manana 		}
378179bd3712SFilipe Manana 	} else if (ret) {
378279bd3712SFilipe Manana 		btrfs_abort_transaction(trans, ret);
378379bd3712SFilipe Manana 		goto out;
378479bd3712SFilipe Manana 	}
378579bd3712SFilipe Manana out:
378679bd3712SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
378779bd3712SFilipe Manana 
3788820c363bSNaohiro Aota 	if (ret)
3789820c363bSNaohiro Aota 		return ERR_PTR(ret);
3790820c363bSNaohiro Aota 
3791820c363bSNaohiro Aota 	btrfs_get_block_group(bg);
3792820c363bSNaohiro Aota 	return bg;
379379bd3712SFilipe Manana }
379479bd3712SFilipe Manana 
379579bd3712SFilipe Manana /*
379679bd3712SFilipe Manana  * Chunk allocation is done in 2 phases:
379779bd3712SFilipe Manana  *
379879bd3712SFilipe Manana  * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
379979bd3712SFilipe Manana  *    the chunk, the chunk mapping, create its block group and add the items
380079bd3712SFilipe Manana  *    that belong in the chunk btree to it - more specifically, we need to
380179bd3712SFilipe Manana  *    update device items in the chunk btree and add a new chunk item to it.
380279bd3712SFilipe Manana  *
380379bd3712SFilipe Manana  * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
380479bd3712SFilipe Manana  *    group item to the extent btree and the device extent items to the devices
380579bd3712SFilipe Manana  *    btree.
380679bd3712SFilipe Manana  *
380779bd3712SFilipe Manana  * This is done to prevent deadlocks. For example when COWing a node from the
380879bd3712SFilipe Manana  * extent btree we are holding a write lock on the node's parent and if we
380979bd3712SFilipe Manana  * trigger chunk allocation and attempted to insert the new block group item
381079bd3712SFilipe Manana  * in the extent btree right way, we could deadlock because the path for the
381179bd3712SFilipe Manana  * insertion can include that parent node. At first glance it seems impossible
381279bd3712SFilipe Manana  * to trigger chunk allocation after starting a transaction since tasks should
381379bd3712SFilipe Manana  * reserve enough transaction units (metadata space), however while that is true
381479bd3712SFilipe Manana  * most of the time, chunk allocation may still be triggered for several reasons:
381579bd3712SFilipe Manana  *
381679bd3712SFilipe Manana  * 1) When reserving metadata, we check if there is enough free space in the
381779bd3712SFilipe Manana  *    metadata space_info and therefore don't trigger allocation of a new chunk.
381879bd3712SFilipe Manana  *    However later when the task actually tries to COW an extent buffer from
381979bd3712SFilipe Manana  *    the extent btree or from the device btree for example, it is forced to
382079bd3712SFilipe Manana  *    allocate a new block group (chunk) because the only one that had enough
382179bd3712SFilipe Manana  *    free space was just turned to RO mode by a running scrub for example (or
382279bd3712SFilipe Manana  *    device replace, block group reclaim thread, etc), so we can not use it
382379bd3712SFilipe Manana  *    for allocating an extent and end up being forced to allocate a new one;
382479bd3712SFilipe Manana  *
382579bd3712SFilipe Manana  * 2) Because we only check that the metadata space_info has enough free bytes,
382679bd3712SFilipe Manana  *    we end up not allocating a new metadata chunk in that case. However if
382779bd3712SFilipe Manana  *    the filesystem was mounted in degraded mode, none of the existing block
382879bd3712SFilipe Manana  *    groups might be suitable for extent allocation due to their incompatible
382979bd3712SFilipe Manana  *    profile (for e.g. mounting a 2 devices filesystem, where all block groups
383079bd3712SFilipe Manana  *    use a RAID1 profile, in degraded mode using a single device). In this case
383179bd3712SFilipe Manana  *    when the task attempts to COW some extent buffer of the extent btree for
383279bd3712SFilipe Manana  *    example, it will trigger allocation of a new metadata block group with a
383379bd3712SFilipe Manana  *    suitable profile (SINGLE profile in the example of the degraded mount of
383479bd3712SFilipe Manana  *    the RAID1 filesystem);
383579bd3712SFilipe Manana  *
383679bd3712SFilipe Manana  * 3) The task has reserved enough transaction units / metadata space, but when
383779bd3712SFilipe Manana  *    it attempts to COW an extent buffer from the extent or device btree for
383879bd3712SFilipe Manana  *    example, it does not find any free extent in any metadata block group,
383979bd3712SFilipe Manana  *    therefore forced to try to allocate a new metadata block group.
384079bd3712SFilipe Manana  *    This is because some other task allocated all available extents in the
384179bd3712SFilipe Manana  *    meanwhile - this typically happens with tasks that don't reserve space
384279bd3712SFilipe Manana  *    properly, either intentionally or as a bug. One example where this is
384379bd3712SFilipe Manana  *    done intentionally is fsync, as it does not reserve any transaction units
384479bd3712SFilipe Manana  *    and ends up allocating a variable number of metadata extents for log
3845ecd84d54SFilipe Manana  *    tree extent buffers;
3846ecd84d54SFilipe Manana  *
3847ecd84d54SFilipe Manana  * 4) The task has reserved enough transaction units / metadata space, but right
3848ecd84d54SFilipe Manana  *    before it tries to allocate the last extent buffer it needs, a discard
3849ecd84d54SFilipe Manana  *    operation comes in and, temporarily, removes the last free space entry from
3850ecd84d54SFilipe Manana  *    the only metadata block group that had free space (discard starts by
3851ecd84d54SFilipe Manana  *    removing a free space entry from a block group, then does the discard
3852ecd84d54SFilipe Manana  *    operation and, once it's done, it adds back the free space entry to the
3853ecd84d54SFilipe Manana  *    block group).
385479bd3712SFilipe Manana  *
385579bd3712SFilipe Manana  * We also need this 2 phases setup when adding a device to a filesystem with
385679bd3712SFilipe Manana  * a seed device - we must create new metadata and system chunks without adding
385779bd3712SFilipe Manana  * any of the block group items to the chunk, extent and device btrees. If we
385879bd3712SFilipe Manana  * did not do it this way, we would get ENOSPC when attempting to update those
385979bd3712SFilipe Manana  * btrees, since all the chunks from the seed device are read-only.
386079bd3712SFilipe Manana  *
386179bd3712SFilipe Manana  * Phase 1 does the updates and insertions to the chunk btree because if we had
386279bd3712SFilipe Manana  * it done in phase 2 and have a thundering herd of tasks allocating chunks in
386379bd3712SFilipe Manana  * parallel, we risk having too many system chunks allocated by many tasks if
386479bd3712SFilipe Manana  * many tasks reach phase 1 without the previous ones completing phase 2. In the
386579bd3712SFilipe Manana  * extreme case this leads to exhaustion of the system chunk array in the
386679bd3712SFilipe Manana  * superblock. This is easier to trigger if using a btree node/leaf size of 64K
386779bd3712SFilipe Manana  * and with RAID filesystems (so we have more device items in the chunk btree).
386879bd3712SFilipe Manana  * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
386979bd3712SFilipe Manana  * the system chunk array due to concurrent allocations") provides more details.
387079bd3712SFilipe Manana  *
38712bb2e00eSFilipe Manana  * Allocation of system chunks does not happen through this function. A task that
38722bb2e00eSFilipe Manana  * needs to update the chunk btree (the only btree that uses system chunks), must
38732bb2e00eSFilipe Manana  * preallocate chunk space by calling either check_system_chunk() or
38742bb2e00eSFilipe Manana  * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or
38752bb2e00eSFilipe Manana  * metadata chunk or when removing a chunk, while the later is used before doing
38762bb2e00eSFilipe Manana  * a modification to the chunk btree - use cases for the later are adding,
38772bb2e00eSFilipe Manana  * removing and resizing a device as well as relocation of a system chunk.
38782bb2e00eSFilipe Manana  * See the comment below for more details.
387979bd3712SFilipe Manana  *
388079bd3712SFilipe Manana  * The reservation of system space, done through check_system_chunk(), as well
388179bd3712SFilipe Manana  * as all the updates and insertions into the chunk btree must be done while
388279bd3712SFilipe Manana  * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
388379bd3712SFilipe Manana  * an extent buffer from the chunks btree we never trigger allocation of a new
388479bd3712SFilipe Manana  * system chunk, which would result in a deadlock (trying to lock twice an
388579bd3712SFilipe Manana  * extent buffer of the chunk btree, first time before triggering the chunk
388679bd3712SFilipe Manana  * allocation and the second time during chunk allocation while attempting to
388779bd3712SFilipe Manana  * update the chunks btree). The system chunk array is also updated while holding
388879bd3712SFilipe Manana  * that mutex. The same logic applies to removing chunks - we must reserve system
388979bd3712SFilipe Manana  * space, update the chunk btree and the system chunk array in the superblock
389079bd3712SFilipe Manana  * while holding fs_info->chunk_mutex.
389179bd3712SFilipe Manana  *
389279bd3712SFilipe Manana  * This function, btrfs_chunk_alloc(), belongs to phase 1.
389379bd3712SFilipe Manana  *
389479bd3712SFilipe Manana  * If @force is CHUNK_ALLOC_FORCE:
389507730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
389607730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
389779bd3712SFilipe Manana  * If @force is NOT CHUNK_ALLOC_FORCE:
389807730d87SJosef Bacik  *    - return 0 if it doesn't need to allocate a new chunk,
389907730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
390007730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
390107730d87SJosef Bacik  */
390207730d87SJosef Bacik int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
390307730d87SJosef Bacik 		      enum btrfs_chunk_alloc_enum force)
390407730d87SJosef Bacik {
390507730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
390607730d87SJosef Bacik 	struct btrfs_space_info *space_info;
3907820c363bSNaohiro Aota 	struct btrfs_block_group *ret_bg;
390807730d87SJosef Bacik 	bool wait_for_alloc = false;
390907730d87SJosef Bacik 	bool should_alloc = false;
3910760e69c4SNaohiro Aota 	bool from_extent_allocation = false;
391107730d87SJosef Bacik 	int ret = 0;
391207730d87SJosef Bacik 
3913760e69c4SNaohiro Aota 	if (force == CHUNK_ALLOC_FORCE_FOR_EXTENT) {
3914760e69c4SNaohiro Aota 		from_extent_allocation = true;
3915760e69c4SNaohiro Aota 		force = CHUNK_ALLOC_FORCE;
3916760e69c4SNaohiro Aota 	}
3917760e69c4SNaohiro Aota 
391807730d87SJosef Bacik 	/* Don't re-enter if we're already allocating a chunk */
391907730d87SJosef Bacik 	if (trans->allocating_chunk)
392007730d87SJosef Bacik 		return -ENOSPC;
392179bd3712SFilipe Manana 	/*
39222bb2e00eSFilipe Manana 	 * Allocation of system chunks can not happen through this path, as we
39232bb2e00eSFilipe Manana 	 * could end up in a deadlock if we are allocating a data or metadata
39242bb2e00eSFilipe Manana 	 * chunk and there is another task modifying the chunk btree.
39252bb2e00eSFilipe Manana 	 *
39262bb2e00eSFilipe Manana 	 * This is because while we are holding the chunk mutex, we will attempt
39272bb2e00eSFilipe Manana 	 * to add the new chunk item to the chunk btree or update an existing
39282bb2e00eSFilipe Manana 	 * device item in the chunk btree, while the other task that is modifying
39292bb2e00eSFilipe Manana 	 * the chunk btree is attempting to COW an extent buffer while holding a
39302bb2e00eSFilipe Manana 	 * lock on it and on its parent - if the COW operation triggers a system
39312bb2e00eSFilipe Manana 	 * chunk allocation, then we can deadlock because we are holding the
39322bb2e00eSFilipe Manana 	 * chunk mutex and we may need to access that extent buffer or its parent
39332bb2e00eSFilipe Manana 	 * in order to add the chunk item or update a device item.
39342bb2e00eSFilipe Manana 	 *
39352bb2e00eSFilipe Manana 	 * Tasks that want to modify the chunk tree should reserve system space
39362bb2e00eSFilipe Manana 	 * before updating the chunk btree, by calling either
39372bb2e00eSFilipe Manana 	 * btrfs_reserve_chunk_metadata() or check_system_chunk().
39382bb2e00eSFilipe Manana 	 * It's possible that after a task reserves the space, it still ends up
39392bb2e00eSFilipe Manana 	 * here - this happens in the cases described above at do_chunk_alloc().
39402bb2e00eSFilipe Manana 	 * The task will have to either retry or fail.
394179bd3712SFilipe Manana 	 */
39422bb2e00eSFilipe Manana 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
394379bd3712SFilipe Manana 		return -ENOSPC;
394407730d87SJosef Bacik 
394507730d87SJosef Bacik 	space_info = btrfs_find_space_info(fs_info, flags);
394607730d87SJosef Bacik 	ASSERT(space_info);
394707730d87SJosef Bacik 
394807730d87SJosef Bacik 	do {
394907730d87SJosef Bacik 		spin_lock(&space_info->lock);
395007730d87SJosef Bacik 		if (force < space_info->force_alloc)
395107730d87SJosef Bacik 			force = space_info->force_alloc;
395207730d87SJosef Bacik 		should_alloc = should_alloc_chunk(fs_info, space_info, force);
395307730d87SJosef Bacik 		if (space_info->full) {
395407730d87SJosef Bacik 			/* No more free physical space */
395507730d87SJosef Bacik 			if (should_alloc)
395607730d87SJosef Bacik 				ret = -ENOSPC;
395707730d87SJosef Bacik 			else
395807730d87SJosef Bacik 				ret = 0;
395907730d87SJosef Bacik 			spin_unlock(&space_info->lock);
396007730d87SJosef Bacik 			return ret;
396107730d87SJosef Bacik 		} else if (!should_alloc) {
396207730d87SJosef Bacik 			spin_unlock(&space_info->lock);
396307730d87SJosef Bacik 			return 0;
396407730d87SJosef Bacik 		} else if (space_info->chunk_alloc) {
396507730d87SJosef Bacik 			/*
396607730d87SJosef Bacik 			 * Someone is already allocating, so we need to block
396707730d87SJosef Bacik 			 * until this someone is finished and then loop to
396807730d87SJosef Bacik 			 * recheck if we should continue with our allocation
396907730d87SJosef Bacik 			 * attempt.
397007730d87SJosef Bacik 			 */
397107730d87SJosef Bacik 			wait_for_alloc = true;
39721314ca78SJosef Bacik 			force = CHUNK_ALLOC_NO_FORCE;
397307730d87SJosef Bacik 			spin_unlock(&space_info->lock);
397407730d87SJosef Bacik 			mutex_lock(&fs_info->chunk_mutex);
397507730d87SJosef Bacik 			mutex_unlock(&fs_info->chunk_mutex);
397607730d87SJosef Bacik 		} else {
397707730d87SJosef Bacik 			/* Proceed with allocation */
397807730d87SJosef Bacik 			space_info->chunk_alloc = 1;
397907730d87SJosef Bacik 			wait_for_alloc = false;
398007730d87SJosef Bacik 			spin_unlock(&space_info->lock);
398107730d87SJosef Bacik 		}
398207730d87SJosef Bacik 
398307730d87SJosef Bacik 		cond_resched();
398407730d87SJosef Bacik 	} while (wait_for_alloc);
398507730d87SJosef Bacik 
398607730d87SJosef Bacik 	mutex_lock(&fs_info->chunk_mutex);
398707730d87SJosef Bacik 	trans->allocating_chunk = true;
398807730d87SJosef Bacik 
398907730d87SJosef Bacik 	/*
399007730d87SJosef Bacik 	 * If we have mixed data/metadata chunks we want to make sure we keep
399107730d87SJosef Bacik 	 * allocating mixed chunks instead of individual chunks.
399207730d87SJosef Bacik 	 */
399307730d87SJosef Bacik 	if (btrfs_mixed_space_info(space_info))
399407730d87SJosef Bacik 		flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
399507730d87SJosef Bacik 
399607730d87SJosef Bacik 	/*
399707730d87SJosef Bacik 	 * if we're doing a data chunk, go ahead and make sure that
399807730d87SJosef Bacik 	 * we keep a reasonable number of metadata chunks allocated in the
399907730d87SJosef Bacik 	 * FS as well.
400007730d87SJosef Bacik 	 */
400107730d87SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
400207730d87SJosef Bacik 		fs_info->data_chunk_allocations++;
400307730d87SJosef Bacik 		if (!(fs_info->data_chunk_allocations %
400407730d87SJosef Bacik 		      fs_info->metadata_ratio))
400507730d87SJosef Bacik 			force_metadata_allocation(fs_info);
400607730d87SJosef Bacik 	}
400707730d87SJosef Bacik 
4008820c363bSNaohiro Aota 	ret_bg = do_chunk_alloc(trans, flags);
400907730d87SJosef Bacik 	trans->allocating_chunk = false;
401007730d87SJosef Bacik 
4011760e69c4SNaohiro Aota 	if (IS_ERR(ret_bg)) {
4012820c363bSNaohiro Aota 		ret = PTR_ERR(ret_bg);
4013760e69c4SNaohiro Aota 	} else if (from_extent_allocation) {
4014760e69c4SNaohiro Aota 		/*
4015760e69c4SNaohiro Aota 		 * New block group is likely to be used soon. Try to activate
4016760e69c4SNaohiro Aota 		 * it now. Failure is OK for now.
4017760e69c4SNaohiro Aota 		 */
4018760e69c4SNaohiro Aota 		btrfs_zone_activate(ret_bg);
4019760e69c4SNaohiro Aota 	}
4020760e69c4SNaohiro Aota 
4021760e69c4SNaohiro Aota 	if (!ret)
4022820c363bSNaohiro Aota 		btrfs_put_block_group(ret_bg);
4023820c363bSNaohiro Aota 
402407730d87SJosef Bacik 	spin_lock(&space_info->lock);
402507730d87SJosef Bacik 	if (ret < 0) {
402607730d87SJosef Bacik 		if (ret == -ENOSPC)
402707730d87SJosef Bacik 			space_info->full = 1;
402807730d87SJosef Bacik 		else
402907730d87SJosef Bacik 			goto out;
403007730d87SJosef Bacik 	} else {
403107730d87SJosef Bacik 		ret = 1;
403207730d87SJosef Bacik 		space_info->max_extent_size = 0;
403307730d87SJosef Bacik 	}
403407730d87SJosef Bacik 
403507730d87SJosef Bacik 	space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
403607730d87SJosef Bacik out:
403707730d87SJosef Bacik 	space_info->chunk_alloc = 0;
403807730d87SJosef Bacik 	spin_unlock(&space_info->lock);
403907730d87SJosef Bacik 	mutex_unlock(&fs_info->chunk_mutex);
404007730d87SJosef Bacik 
404107730d87SJosef Bacik 	return ret;
404207730d87SJosef Bacik }
404307730d87SJosef Bacik 
404407730d87SJosef Bacik static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
404507730d87SJosef Bacik {
404607730d87SJosef Bacik 	u64 num_dev;
404707730d87SJosef Bacik 
404807730d87SJosef Bacik 	num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
404907730d87SJosef Bacik 	if (!num_dev)
405007730d87SJosef Bacik 		num_dev = fs_info->fs_devices->rw_devices;
405107730d87SJosef Bacik 
405207730d87SJosef Bacik 	return num_dev;
405307730d87SJosef Bacik }
405407730d87SJosef Bacik 
40552bb2e00eSFilipe Manana static void reserve_chunk_space(struct btrfs_trans_handle *trans,
40562bb2e00eSFilipe Manana 				u64 bytes,
40572bb2e00eSFilipe Manana 				u64 type)
405807730d87SJosef Bacik {
405907730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
406007730d87SJosef Bacik 	struct btrfs_space_info *info;
406107730d87SJosef Bacik 	u64 left;
406207730d87SJosef Bacik 	int ret = 0;
406307730d87SJosef Bacik 
406407730d87SJosef Bacik 	/*
406507730d87SJosef Bacik 	 * Needed because we can end up allocating a system chunk and for an
406607730d87SJosef Bacik 	 * atomic and race free space reservation in the chunk block reserve.
406707730d87SJosef Bacik 	 */
406807730d87SJosef Bacik 	lockdep_assert_held(&fs_info->chunk_mutex);
406907730d87SJosef Bacik 
407007730d87SJosef Bacik 	info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
407107730d87SJosef Bacik 	spin_lock(&info->lock);
407207730d87SJosef Bacik 	left = info->total_bytes - btrfs_space_info_used(info, true);
407307730d87SJosef Bacik 	spin_unlock(&info->lock);
407407730d87SJosef Bacik 
40752bb2e00eSFilipe Manana 	if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
407607730d87SJosef Bacik 		btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
40772bb2e00eSFilipe Manana 			   left, bytes, type);
407807730d87SJosef Bacik 		btrfs_dump_space_info(fs_info, info, 0, 0);
407907730d87SJosef Bacik 	}
408007730d87SJosef Bacik 
40812bb2e00eSFilipe Manana 	if (left < bytes) {
408207730d87SJosef Bacik 		u64 flags = btrfs_system_alloc_profile(fs_info);
408379bd3712SFilipe Manana 		struct btrfs_block_group *bg;
408407730d87SJosef Bacik 
408507730d87SJosef Bacik 		/*
408607730d87SJosef Bacik 		 * Ignore failure to create system chunk. We might end up not
408707730d87SJosef Bacik 		 * needing it, as we might not need to COW all nodes/leafs from
408807730d87SJosef Bacik 		 * the paths we visit in the chunk tree (they were already COWed
408907730d87SJosef Bacik 		 * or created in the current transaction for example).
409007730d87SJosef Bacik 		 */
4091f6f39f7aSNikolay Borisov 		bg = btrfs_create_chunk(trans, flags);
409279bd3712SFilipe Manana 		if (IS_ERR(bg)) {
409379bd3712SFilipe Manana 			ret = PTR_ERR(bg);
40942bb2e00eSFilipe Manana 		} else {
409579bd3712SFilipe Manana 			/*
4096b6a98021SNaohiro Aota 			 * We have a new chunk. We also need to activate it for
4097b6a98021SNaohiro Aota 			 * zoned filesystem.
4098b6a98021SNaohiro Aota 			 */
4099b6a98021SNaohiro Aota 			ret = btrfs_zoned_activate_one_bg(fs_info, info, true);
4100b6a98021SNaohiro Aota 			if (ret < 0)
4101b6a98021SNaohiro Aota 				return;
4102b6a98021SNaohiro Aota 
4103b6a98021SNaohiro Aota 			/*
410479bd3712SFilipe Manana 			 * If we fail to add the chunk item here, we end up
410579bd3712SFilipe Manana 			 * trying again at phase 2 of chunk allocation, at
410679bd3712SFilipe Manana 			 * btrfs_create_pending_block_groups(). So ignore
41072bb2e00eSFilipe Manana 			 * any error here. An ENOSPC here could happen, due to
41082bb2e00eSFilipe Manana 			 * the cases described at do_chunk_alloc() - the system
41092bb2e00eSFilipe Manana 			 * block group we just created was just turned into RO
41102bb2e00eSFilipe Manana 			 * mode by a scrub for example, or a running discard
41112bb2e00eSFilipe Manana 			 * temporarily removed its free space entries, etc.
411279bd3712SFilipe Manana 			 */
411379bd3712SFilipe Manana 			btrfs_chunk_alloc_add_chunk_item(trans, bg);
411479bd3712SFilipe Manana 		}
411507730d87SJosef Bacik 	}
411607730d87SJosef Bacik 
411707730d87SJosef Bacik 	if (!ret) {
41189270501cSJosef Bacik 		ret = btrfs_block_rsv_add(fs_info,
411907730d87SJosef Bacik 					  &fs_info->chunk_block_rsv,
41202bb2e00eSFilipe Manana 					  bytes, BTRFS_RESERVE_NO_FLUSH);
41211cb3db1cSFilipe Manana 		if (!ret)
41222bb2e00eSFilipe Manana 			trans->chunk_bytes_reserved += bytes;
412307730d87SJosef Bacik 	}
412407730d87SJosef Bacik }
412507730d87SJosef Bacik 
41262bb2e00eSFilipe Manana /*
41272bb2e00eSFilipe Manana  * Reserve space in the system space for allocating or removing a chunk.
41282bb2e00eSFilipe Manana  * The caller must be holding fs_info->chunk_mutex.
41292bb2e00eSFilipe Manana  */
41302bb2e00eSFilipe Manana void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
41312bb2e00eSFilipe Manana {
41322bb2e00eSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
41332bb2e00eSFilipe Manana 	const u64 num_devs = get_profile_num_devs(fs_info, type);
41342bb2e00eSFilipe Manana 	u64 bytes;
41352bb2e00eSFilipe Manana 
41362bb2e00eSFilipe Manana 	/* num_devs device items to update and 1 chunk item to add or remove. */
41372bb2e00eSFilipe Manana 	bytes = btrfs_calc_metadata_size(fs_info, num_devs) +
41382bb2e00eSFilipe Manana 		btrfs_calc_insert_metadata_size(fs_info, 1);
41392bb2e00eSFilipe Manana 
41402bb2e00eSFilipe Manana 	reserve_chunk_space(trans, bytes, type);
41412bb2e00eSFilipe Manana }
41422bb2e00eSFilipe Manana 
41432bb2e00eSFilipe Manana /*
41442bb2e00eSFilipe Manana  * Reserve space in the system space, if needed, for doing a modification to the
41452bb2e00eSFilipe Manana  * chunk btree.
41462bb2e00eSFilipe Manana  *
41472bb2e00eSFilipe Manana  * @trans:		A transaction handle.
41482bb2e00eSFilipe Manana  * @is_item_insertion:	Indicate if the modification is for inserting a new item
41492bb2e00eSFilipe Manana  *			in the chunk btree or if it's for the deletion or update
41502bb2e00eSFilipe Manana  *			of an existing item.
41512bb2e00eSFilipe Manana  *
41522bb2e00eSFilipe Manana  * This is used in a context where we need to update the chunk btree outside
41532bb2e00eSFilipe Manana  * block group allocation and removal, to avoid a deadlock with a concurrent
41542bb2e00eSFilipe Manana  * task that is allocating a metadata or data block group and therefore needs to
41552bb2e00eSFilipe Manana  * update the chunk btree while holding the chunk mutex. After the update to the
41562bb2e00eSFilipe Manana  * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called.
41572bb2e00eSFilipe Manana  *
41582bb2e00eSFilipe Manana  */
41592bb2e00eSFilipe Manana void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans,
41602bb2e00eSFilipe Manana 				  bool is_item_insertion)
41612bb2e00eSFilipe Manana {
41622bb2e00eSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
41632bb2e00eSFilipe Manana 	u64 bytes;
41642bb2e00eSFilipe Manana 
41652bb2e00eSFilipe Manana 	if (is_item_insertion)
41662bb2e00eSFilipe Manana 		bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
41672bb2e00eSFilipe Manana 	else
41682bb2e00eSFilipe Manana 		bytes = btrfs_calc_metadata_size(fs_info, 1);
41692bb2e00eSFilipe Manana 
41702bb2e00eSFilipe Manana 	mutex_lock(&fs_info->chunk_mutex);
41712bb2e00eSFilipe Manana 	reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM);
41722bb2e00eSFilipe Manana 	mutex_unlock(&fs_info->chunk_mutex);
41732bb2e00eSFilipe Manana }
41742bb2e00eSFilipe Manana 
41753e43c279SJosef Bacik void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
41763e43c279SJosef Bacik {
417732da5386SDavid Sterba 	struct btrfs_block_group *block_group;
41783e43c279SJosef Bacik 
417950c31eaaSJosef Bacik 	block_group = btrfs_lookup_first_block_group(info, 0);
41803e43c279SJosef Bacik 	while (block_group) {
41813e43c279SJosef Bacik 		btrfs_wait_block_group_cache_done(block_group);
41823e43c279SJosef Bacik 		spin_lock(&block_group->lock);
418350c31eaaSJosef Bacik 		if (test_and_clear_bit(BLOCK_GROUP_FLAG_IREF,
418450c31eaaSJosef Bacik 				       &block_group->runtime_flags)) {
418550c31eaaSJosef Bacik 			struct inode *inode = block_group->inode;
41863e43c279SJosef Bacik 
41873e43c279SJosef Bacik 			block_group->inode = NULL;
41883e43c279SJosef Bacik 			spin_unlock(&block_group->lock);
418950c31eaaSJosef Bacik 
41903e43c279SJosef Bacik 			ASSERT(block_group->io_ctl.inode == NULL);
41913e43c279SJosef Bacik 			iput(inode);
419250c31eaaSJosef Bacik 		} else {
419350c31eaaSJosef Bacik 			spin_unlock(&block_group->lock);
419450c31eaaSJosef Bacik 		}
419550c31eaaSJosef Bacik 		block_group = btrfs_next_block_group(block_group);
41963e43c279SJosef Bacik 	}
41973e43c279SJosef Bacik }
41983e43c279SJosef Bacik 
41993e43c279SJosef Bacik /*
42003e43c279SJosef Bacik  * Must be called only after stopping all workers, since we could have block
42013e43c279SJosef Bacik  * group caching kthreads running, and therefore they could race with us if we
42023e43c279SJosef Bacik  * freed the block groups before stopping them.
42033e43c279SJosef Bacik  */
42043e43c279SJosef Bacik int btrfs_free_block_groups(struct btrfs_fs_info *info)
42053e43c279SJosef Bacik {
420632da5386SDavid Sterba 	struct btrfs_block_group *block_group;
42073e43c279SJosef Bacik 	struct btrfs_space_info *space_info;
42083e43c279SJosef Bacik 	struct btrfs_caching_control *caching_ctl;
42093e43c279SJosef Bacik 	struct rb_node *n;
42103e43c279SJosef Bacik 
421116b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
42123e43c279SJosef Bacik 	while (!list_empty(&info->caching_block_groups)) {
42133e43c279SJosef Bacik 		caching_ctl = list_entry(info->caching_block_groups.next,
42143e43c279SJosef Bacik 					 struct btrfs_caching_control, list);
42153e43c279SJosef Bacik 		list_del(&caching_ctl->list);
42163e43c279SJosef Bacik 		btrfs_put_caching_control(caching_ctl);
42173e43c279SJosef Bacik 	}
421816b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
42193e43c279SJosef Bacik 
42203e43c279SJosef Bacik 	spin_lock(&info->unused_bgs_lock);
42213e43c279SJosef Bacik 	while (!list_empty(&info->unused_bgs)) {
42223e43c279SJosef Bacik 		block_group = list_first_entry(&info->unused_bgs,
422332da5386SDavid Sterba 					       struct btrfs_block_group,
42243e43c279SJosef Bacik 					       bg_list);
42253e43c279SJosef Bacik 		list_del_init(&block_group->bg_list);
42263e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
42273e43c279SJosef Bacik 	}
42283e43c279SJosef Bacik 
422918bb8bbfSJohannes Thumshirn 	while (!list_empty(&info->reclaim_bgs)) {
423018bb8bbfSJohannes Thumshirn 		block_group = list_first_entry(&info->reclaim_bgs,
423118bb8bbfSJohannes Thumshirn 					       struct btrfs_block_group,
423218bb8bbfSJohannes Thumshirn 					       bg_list);
423318bb8bbfSJohannes Thumshirn 		list_del_init(&block_group->bg_list);
423418bb8bbfSJohannes Thumshirn 		btrfs_put_block_group(block_group);
423518bb8bbfSJohannes Thumshirn 	}
423618bb8bbfSJohannes Thumshirn 	spin_unlock(&info->unused_bgs_lock);
423718bb8bbfSJohannes Thumshirn 
4238afba2bc0SNaohiro Aota 	spin_lock(&info->zone_active_bgs_lock);
4239afba2bc0SNaohiro Aota 	while (!list_empty(&info->zone_active_bgs)) {
4240afba2bc0SNaohiro Aota 		block_group = list_first_entry(&info->zone_active_bgs,
4241afba2bc0SNaohiro Aota 					       struct btrfs_block_group,
4242afba2bc0SNaohiro Aota 					       active_bg_list);
4243afba2bc0SNaohiro Aota 		list_del_init(&block_group->active_bg_list);
4244afba2bc0SNaohiro Aota 		btrfs_put_block_group(block_group);
4245afba2bc0SNaohiro Aota 	}
4246afba2bc0SNaohiro Aota 	spin_unlock(&info->zone_active_bgs_lock);
4247afba2bc0SNaohiro Aota 
424816b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
424908dddb29SFilipe Manana 	while ((n = rb_last(&info->block_group_cache_tree.rb_root)) != NULL) {
425032da5386SDavid Sterba 		block_group = rb_entry(n, struct btrfs_block_group,
42513e43c279SJosef Bacik 				       cache_node);
425208dddb29SFilipe Manana 		rb_erase_cached(&block_group->cache_node,
42533e43c279SJosef Bacik 				&info->block_group_cache_tree);
42543e43c279SJosef Bacik 		RB_CLEAR_NODE(&block_group->cache_node);
425516b0c258SFilipe Manana 		write_unlock(&info->block_group_cache_lock);
42563e43c279SJosef Bacik 
42573e43c279SJosef Bacik 		down_write(&block_group->space_info->groups_sem);
42583e43c279SJosef Bacik 		list_del(&block_group->list);
42593e43c279SJosef Bacik 		up_write(&block_group->space_info->groups_sem);
42603e43c279SJosef Bacik 
42613e43c279SJosef Bacik 		/*
42623e43c279SJosef Bacik 		 * We haven't cached this block group, which means we could
42633e43c279SJosef Bacik 		 * possibly have excluded extents on this block group.
42643e43c279SJosef Bacik 		 */
42653e43c279SJosef Bacik 		if (block_group->cached == BTRFS_CACHE_NO ||
42663e43c279SJosef Bacik 		    block_group->cached == BTRFS_CACHE_ERROR)
42673e43c279SJosef Bacik 			btrfs_free_excluded_extents(block_group);
42683e43c279SJosef Bacik 
42693e43c279SJosef Bacik 		btrfs_remove_free_space_cache(block_group);
42703e43c279SJosef Bacik 		ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
42713e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->dirty_list));
42723e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->io_list));
42733e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->bg_list));
427448aaeebeSJosef Bacik 		ASSERT(refcount_read(&block_group->refs) == 1);
4275195a49eaSFilipe Manana 		ASSERT(block_group->swap_extents == 0);
42763e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
42773e43c279SJosef Bacik 
427816b0c258SFilipe Manana 		write_lock(&info->block_group_cache_lock);
42793e43c279SJosef Bacik 	}
428016b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
42813e43c279SJosef Bacik 
42823e43c279SJosef Bacik 	btrfs_release_global_block_rsv(info);
42833e43c279SJosef Bacik 
42843e43c279SJosef Bacik 	while (!list_empty(&info->space_info)) {
42853e43c279SJosef Bacik 		space_info = list_entry(info->space_info.next,
42863e43c279SJosef Bacik 					struct btrfs_space_info,
42873e43c279SJosef Bacik 					list);
42883e43c279SJosef Bacik 
42893e43c279SJosef Bacik 		/*
42903e43c279SJosef Bacik 		 * Do not hide this behind enospc_debug, this is actually
42913e43c279SJosef Bacik 		 * important and indicates a real bug if this happens.
42923e43c279SJosef Bacik 		 */
42933e43c279SJosef Bacik 		if (WARN_ON(space_info->bytes_pinned > 0 ||
42943e43c279SJosef Bacik 			    space_info->bytes_may_use > 0))
42953e43c279SJosef Bacik 			btrfs_dump_space_info(info, space_info, 0, 0);
429640cdc509SFilipe Manana 
429740cdc509SFilipe Manana 		/*
429840cdc509SFilipe Manana 		 * If there was a failure to cleanup a log tree, very likely due
429940cdc509SFilipe Manana 		 * to an IO failure on a writeback attempt of one or more of its
430040cdc509SFilipe Manana 		 * extent buffers, we could not do proper (and cheap) unaccounting
430140cdc509SFilipe Manana 		 * of their reserved space, so don't warn on bytes_reserved > 0 in
430240cdc509SFilipe Manana 		 * that case.
430340cdc509SFilipe Manana 		 */
430440cdc509SFilipe Manana 		if (!(space_info->flags & BTRFS_BLOCK_GROUP_METADATA) ||
430540cdc509SFilipe Manana 		    !BTRFS_FS_LOG_CLEANUP_ERROR(info)) {
430640cdc509SFilipe Manana 			if (WARN_ON(space_info->bytes_reserved > 0))
430740cdc509SFilipe Manana 				btrfs_dump_space_info(info, space_info, 0, 0);
430840cdc509SFilipe Manana 		}
430940cdc509SFilipe Manana 
4310d611add4SFilipe Manana 		WARN_ON(space_info->reclaim_size > 0);
43113e43c279SJosef Bacik 		list_del(&space_info->list);
43123e43c279SJosef Bacik 		btrfs_sysfs_remove_space_info(space_info);
43133e43c279SJosef Bacik 	}
43143e43c279SJosef Bacik 	return 0;
43153e43c279SJosef Bacik }
4316684b752bSFilipe Manana 
4317684b752bSFilipe Manana void btrfs_freeze_block_group(struct btrfs_block_group *cache)
4318684b752bSFilipe Manana {
4319684b752bSFilipe Manana 	atomic_inc(&cache->frozen);
4320684b752bSFilipe Manana }
4321684b752bSFilipe Manana 
4322684b752bSFilipe Manana void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
4323684b752bSFilipe Manana {
4324684b752bSFilipe Manana 	struct btrfs_fs_info *fs_info = block_group->fs_info;
4325684b752bSFilipe Manana 	struct extent_map_tree *em_tree;
4326684b752bSFilipe Manana 	struct extent_map *em;
4327684b752bSFilipe Manana 	bool cleanup;
4328684b752bSFilipe Manana 
4329684b752bSFilipe Manana 	spin_lock(&block_group->lock);
4330684b752bSFilipe Manana 	cleanup = (atomic_dec_and_test(&block_group->frozen) &&
43313349b57fSJosef Bacik 		   test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags));
4332684b752bSFilipe Manana 	spin_unlock(&block_group->lock);
4333684b752bSFilipe Manana 
4334684b752bSFilipe Manana 	if (cleanup) {
4335684b752bSFilipe Manana 		em_tree = &fs_info->mapping_tree;
4336684b752bSFilipe Manana 		write_lock(&em_tree->lock);
4337684b752bSFilipe Manana 		em = lookup_extent_mapping(em_tree, block_group->start,
4338684b752bSFilipe Manana 					   1);
4339684b752bSFilipe Manana 		BUG_ON(!em); /* logic error, can't happen */
4340684b752bSFilipe Manana 		remove_extent_mapping(em_tree, em);
4341684b752bSFilipe Manana 		write_unlock(&em_tree->lock);
4342684b752bSFilipe Manana 
4343684b752bSFilipe Manana 		/* once for us and once for the tree */
4344684b752bSFilipe Manana 		free_extent_map(em);
4345684b752bSFilipe Manana 		free_extent_map(em);
4346684b752bSFilipe Manana 
4347684b752bSFilipe Manana 		/*
4348684b752bSFilipe Manana 		 * We may have left one free space entry and other possible
4349684b752bSFilipe Manana 		 * tasks trimming this block group have left 1 entry each one.
4350684b752bSFilipe Manana 		 * Free them if any.
4351684b752bSFilipe Manana 		 */
4352fc80f7acSJosef Bacik 		btrfs_remove_free_space_cache(block_group);
4353684b752bSFilipe Manana 	}
4354684b752bSFilipe Manana }
4355195a49eaSFilipe Manana 
4356195a49eaSFilipe Manana bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
4357195a49eaSFilipe Manana {
4358195a49eaSFilipe Manana 	bool ret = true;
4359195a49eaSFilipe Manana 
4360195a49eaSFilipe Manana 	spin_lock(&bg->lock);
4361195a49eaSFilipe Manana 	if (bg->ro)
4362195a49eaSFilipe Manana 		ret = false;
4363195a49eaSFilipe Manana 	else
4364195a49eaSFilipe Manana 		bg->swap_extents++;
4365195a49eaSFilipe Manana 	spin_unlock(&bg->lock);
4366195a49eaSFilipe Manana 
4367195a49eaSFilipe Manana 	return ret;
4368195a49eaSFilipe Manana }
4369195a49eaSFilipe Manana 
4370195a49eaSFilipe Manana void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
4371195a49eaSFilipe Manana {
4372195a49eaSFilipe Manana 	spin_lock(&bg->lock);
4373195a49eaSFilipe Manana 	ASSERT(!bg->ro);
4374195a49eaSFilipe Manana 	ASSERT(bg->swap_extents >= amount);
4375195a49eaSFilipe Manana 	bg->swap_extents -= amount;
4376195a49eaSFilipe Manana 	spin_unlock(&bg->lock);
4377195a49eaSFilipe Manana }
437852bb7a21SBoris Burkov 
437952bb7a21SBoris Burkov enum btrfs_block_group_size_class btrfs_calc_block_group_size_class(u64 size)
438052bb7a21SBoris Burkov {
438152bb7a21SBoris Burkov 	if (size <= SZ_128K)
438252bb7a21SBoris Burkov 		return BTRFS_BG_SZ_SMALL;
438352bb7a21SBoris Burkov 	if (size <= SZ_8M)
438452bb7a21SBoris Burkov 		return BTRFS_BG_SZ_MEDIUM;
438552bb7a21SBoris Burkov 	return BTRFS_BG_SZ_LARGE;
438652bb7a21SBoris Burkov }
438752bb7a21SBoris Burkov 
438852bb7a21SBoris Burkov /*
438952bb7a21SBoris Burkov  * Handle a block group allocating an extent in a size class
439052bb7a21SBoris Burkov  *
439152bb7a21SBoris Burkov  * @bg:				The block group we allocated in.
439252bb7a21SBoris Burkov  * @size_class:			The size class of the allocation.
439352bb7a21SBoris Burkov  * @force_wrong_size_class:	Whether we are desperate enough to allow
439452bb7a21SBoris Burkov  *				mismatched size classes.
439552bb7a21SBoris Burkov  *
439652bb7a21SBoris Burkov  * Returns: 0 if the size class was valid for this block_group, -EAGAIN in the
439752bb7a21SBoris Burkov  * case of a race that leads to the wrong size class without
439852bb7a21SBoris Burkov  * force_wrong_size_class set.
439952bb7a21SBoris Burkov  *
440052bb7a21SBoris Burkov  * find_free_extent will skip block groups with a mismatched size class until
440152bb7a21SBoris Burkov  * it really needs to avoid ENOSPC. In that case it will set
440252bb7a21SBoris Burkov  * force_wrong_size_class. However, if a block group is newly allocated and
440352bb7a21SBoris Burkov  * doesn't yet have a size class, then it is possible for two allocations of
440452bb7a21SBoris Burkov  * different sizes to race and both try to use it. The loser is caught here and
440552bb7a21SBoris Burkov  * has to retry.
440652bb7a21SBoris Burkov  */
440752bb7a21SBoris Burkov int btrfs_use_block_group_size_class(struct btrfs_block_group *bg,
440852bb7a21SBoris Burkov 				     enum btrfs_block_group_size_class size_class,
440952bb7a21SBoris Burkov 				     bool force_wrong_size_class)
441052bb7a21SBoris Burkov {
441152bb7a21SBoris Burkov 	ASSERT(size_class != BTRFS_BG_SZ_NONE);
441252bb7a21SBoris Burkov 
441352bb7a21SBoris Burkov 	/* The new allocation is in the right size class, do nothing */
441452bb7a21SBoris Burkov 	if (bg->size_class == size_class)
441552bb7a21SBoris Burkov 		return 0;
441652bb7a21SBoris Burkov 	/*
441752bb7a21SBoris Burkov 	 * The new allocation is in a mismatched size class.
441852bb7a21SBoris Burkov 	 * This means one of two things:
441952bb7a21SBoris Burkov 	 *
442052bb7a21SBoris Burkov 	 * 1. Two tasks in find_free_extent for different size_classes raced
442152bb7a21SBoris Burkov 	 *    and hit the same empty block_group. Make the loser try again.
442252bb7a21SBoris Burkov 	 * 2. A call to find_free_extent got desperate enough to set
442352bb7a21SBoris Burkov 	 *    'force_wrong_slab'. Don't change the size_class, but allow the
442452bb7a21SBoris Burkov 	 *    allocation.
442552bb7a21SBoris Burkov 	 */
442652bb7a21SBoris Burkov 	if (bg->size_class != BTRFS_BG_SZ_NONE) {
442752bb7a21SBoris Burkov 		if (force_wrong_size_class)
442852bb7a21SBoris Burkov 			return 0;
442952bb7a21SBoris Burkov 		return -EAGAIN;
443052bb7a21SBoris Burkov 	}
443152bb7a21SBoris Burkov 	/*
443252bb7a21SBoris Burkov 	 * The happy new block group case: the new allocation is the first
443352bb7a21SBoris Burkov 	 * one in the block_group so we set size_class.
443452bb7a21SBoris Burkov 	 */
443552bb7a21SBoris Burkov 	bg->size_class = size_class;
443652bb7a21SBoris Burkov 
443752bb7a21SBoris Burkov 	return 0;
443852bb7a21SBoris Burkov }
4439cb0922f2SBoris Burkov 
4440cb0922f2SBoris Burkov bool btrfs_block_group_should_use_size_class(struct btrfs_block_group *bg)
4441cb0922f2SBoris Burkov {
4442cb0922f2SBoris Burkov 	if (btrfs_is_zoned(bg->fs_info))
4443cb0922f2SBoris Burkov 		return false;
4444cb0922f2SBoris Burkov 	if (!btrfs_is_block_group_data_only(bg))
4445cb0922f2SBoris Burkov 		return false;
4446cb0922f2SBoris Burkov 	return true;
4447cb0922f2SBoris Burkov }
4448