xref: /linux/fs/btrfs/block-group.c (revision 0657b20c5a76c938612f8409735a8830d257866e)
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 
98160fe8f6SMatt Corallo 	/* Select the highest-redundancy RAID level. */
99160fe8f6SMatt Corallo 	if (allowed & BTRFS_BLOCK_GROUP_RAID1C4)
100160fe8f6SMatt Corallo 		allowed = BTRFS_BLOCK_GROUP_RAID1C4;
101160fe8f6SMatt Corallo 	else if (allowed & BTRFS_BLOCK_GROUP_RAID6)
102878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID6;
103160fe8f6SMatt Corallo 	else if (allowed & BTRFS_BLOCK_GROUP_RAID1C3)
104160fe8f6SMatt Corallo 		allowed = BTRFS_BLOCK_GROUP_RAID1C3;
105878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
106878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID5;
107878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
108878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID10;
109878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
110878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID1;
111160fe8f6SMatt Corallo 	else if (allowed & BTRFS_BLOCK_GROUP_DUP)
112160fe8f6SMatt Corallo 		allowed = BTRFS_BLOCK_GROUP_DUP;
113878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
114878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID0;
115878d7b67SJosef Bacik 
116878d7b67SJosef Bacik 	flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
117878d7b67SJosef Bacik 
118878d7b67SJosef Bacik 	return extended_to_chunk(flags | allowed);
119878d7b67SJosef Bacik }
120878d7b67SJosef Bacik 
121ef0a82daSJohannes Thumshirn u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
122878d7b67SJosef Bacik {
123878d7b67SJosef Bacik 	unsigned seq;
124878d7b67SJosef Bacik 	u64 flags;
125878d7b67SJosef Bacik 
126878d7b67SJosef Bacik 	do {
127878d7b67SJosef Bacik 		flags = orig_flags;
128878d7b67SJosef Bacik 		seq = read_seqbegin(&fs_info->profiles_lock);
129878d7b67SJosef Bacik 
130878d7b67SJosef Bacik 		if (flags & BTRFS_BLOCK_GROUP_DATA)
131878d7b67SJosef Bacik 			flags |= fs_info->avail_data_alloc_bits;
132878d7b67SJosef Bacik 		else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
133878d7b67SJosef Bacik 			flags |= fs_info->avail_system_alloc_bits;
134878d7b67SJosef Bacik 		else if (flags & BTRFS_BLOCK_GROUP_METADATA)
135878d7b67SJosef Bacik 			flags |= fs_info->avail_metadata_alloc_bits;
136878d7b67SJosef Bacik 	} while (read_seqretry(&fs_info->profiles_lock, seq));
137878d7b67SJosef Bacik 
138878d7b67SJosef Bacik 	return btrfs_reduce_alloc_profile(fs_info, flags);
139878d7b67SJosef Bacik }
140878d7b67SJosef Bacik 
14132da5386SDavid Sterba void btrfs_get_block_group(struct btrfs_block_group *cache)
1423cad1284SJosef Bacik {
14348aaeebeSJosef Bacik 	refcount_inc(&cache->refs);
1443cad1284SJosef Bacik }
1453cad1284SJosef Bacik 
14632da5386SDavid Sterba void btrfs_put_block_group(struct btrfs_block_group *cache)
1473cad1284SJosef Bacik {
14848aaeebeSJosef Bacik 	if (refcount_dec_and_test(&cache->refs)) {
1493cad1284SJosef Bacik 		WARN_ON(cache->pinned > 0);
15040cdc509SFilipe Manana 		/*
15140cdc509SFilipe Manana 		 * If there was a failure to cleanup a log tree, very likely due
15240cdc509SFilipe Manana 		 * to an IO failure on a writeback attempt of one or more of its
15340cdc509SFilipe Manana 		 * extent buffers, we could not do proper (and cheap) unaccounting
15440cdc509SFilipe Manana 		 * of their reserved space, so don't warn on reserved > 0 in that
15540cdc509SFilipe Manana 		 * case.
15640cdc509SFilipe Manana 		 */
15740cdc509SFilipe Manana 		if (!(cache->flags & BTRFS_BLOCK_GROUP_METADATA) ||
15840cdc509SFilipe Manana 		    !BTRFS_FS_LOG_CLEANUP_ERROR(cache->fs_info))
1593cad1284SJosef Bacik 			WARN_ON(cache->reserved > 0);
1603cad1284SJosef Bacik 
1613cad1284SJosef Bacik 		/*
162b0643e59SDennis Zhou 		 * A block_group shouldn't be on the discard_list anymore.
163b0643e59SDennis Zhou 		 * Remove the block_group from the discard_list to prevent us
164b0643e59SDennis Zhou 		 * from causing a panic due to NULL pointer dereference.
165b0643e59SDennis Zhou 		 */
166b0643e59SDennis Zhou 		if (WARN_ON(!list_empty(&cache->discard_list)))
167b0643e59SDennis Zhou 			btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
168b0643e59SDennis Zhou 						  cache);
169b0643e59SDennis Zhou 
1703cad1284SJosef Bacik 		kfree(cache->free_space_ctl);
171dafc340dSNaohiro Aota 		kfree(cache->physical_map);
1723cad1284SJosef Bacik 		kfree(cache);
1733cad1284SJosef Bacik 	}
1743cad1284SJosef Bacik }
1753cad1284SJosef Bacik 
1762e405ad8SJosef Bacik /*
1774358d963SJosef Bacik  * This adds the block group to the fs_info rb tree for the block group cache
1784358d963SJosef Bacik  */
1794358d963SJosef Bacik static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
18032da5386SDavid Sterba 				       struct btrfs_block_group *block_group)
1814358d963SJosef Bacik {
1824358d963SJosef Bacik 	struct rb_node **p;
1834358d963SJosef Bacik 	struct rb_node *parent = NULL;
18432da5386SDavid Sterba 	struct btrfs_block_group *cache;
18508dddb29SFilipe Manana 	bool leftmost = true;
1864358d963SJosef Bacik 
1879afc6649SQu Wenruo 	ASSERT(block_group->length != 0);
1889afc6649SQu Wenruo 
18916b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
19008dddb29SFilipe Manana 	p = &info->block_group_cache_tree.rb_root.rb_node;
1914358d963SJosef Bacik 
1924358d963SJosef Bacik 	while (*p) {
1934358d963SJosef Bacik 		parent = *p;
19432da5386SDavid Sterba 		cache = rb_entry(parent, struct btrfs_block_group, cache_node);
195b3470b5dSDavid Sterba 		if (block_group->start < cache->start) {
1964358d963SJosef Bacik 			p = &(*p)->rb_left;
197b3470b5dSDavid Sterba 		} else if (block_group->start > cache->start) {
1984358d963SJosef Bacik 			p = &(*p)->rb_right;
19908dddb29SFilipe Manana 			leftmost = false;
2004358d963SJosef Bacik 		} else {
20116b0c258SFilipe Manana 			write_unlock(&info->block_group_cache_lock);
2024358d963SJosef Bacik 			return -EEXIST;
2034358d963SJosef Bacik 		}
2044358d963SJosef Bacik 	}
2054358d963SJosef Bacik 
2064358d963SJosef Bacik 	rb_link_node(&block_group->cache_node, parent, p);
20708dddb29SFilipe Manana 	rb_insert_color_cached(&block_group->cache_node,
20808dddb29SFilipe Manana 			       &info->block_group_cache_tree, leftmost);
2094358d963SJosef Bacik 
21016b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
2114358d963SJosef Bacik 
2124358d963SJosef Bacik 	return 0;
2134358d963SJosef Bacik }
2144358d963SJosef Bacik 
2154358d963SJosef Bacik /*
2162e405ad8SJosef Bacik  * This will return the block group at or after bytenr if contains is 0, else
2172e405ad8SJosef Bacik  * it will return the block group that contains the bytenr
2182e405ad8SJosef Bacik  */
21932da5386SDavid Sterba static struct btrfs_block_group *block_group_cache_tree_search(
2202e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr, int contains)
2212e405ad8SJosef Bacik {
22232da5386SDavid Sterba 	struct btrfs_block_group *cache, *ret = NULL;
2232e405ad8SJosef Bacik 	struct rb_node *n;
2242e405ad8SJosef Bacik 	u64 end, start;
2252e405ad8SJosef Bacik 
22616b0c258SFilipe Manana 	read_lock(&info->block_group_cache_lock);
22708dddb29SFilipe Manana 	n = info->block_group_cache_tree.rb_root.rb_node;
2282e405ad8SJosef Bacik 
2292e405ad8SJosef Bacik 	while (n) {
23032da5386SDavid Sterba 		cache = rb_entry(n, struct btrfs_block_group, cache_node);
231b3470b5dSDavid Sterba 		end = cache->start + cache->length - 1;
232b3470b5dSDavid Sterba 		start = cache->start;
2332e405ad8SJosef Bacik 
2342e405ad8SJosef Bacik 		if (bytenr < start) {
235b3470b5dSDavid Sterba 			if (!contains && (!ret || start < ret->start))
2362e405ad8SJosef Bacik 				ret = cache;
2372e405ad8SJosef Bacik 			n = n->rb_left;
2382e405ad8SJosef Bacik 		} else if (bytenr > start) {
2392e405ad8SJosef Bacik 			if (contains && bytenr <= end) {
2402e405ad8SJosef Bacik 				ret = cache;
2412e405ad8SJosef Bacik 				break;
2422e405ad8SJosef Bacik 			}
2432e405ad8SJosef Bacik 			n = n->rb_right;
2442e405ad8SJosef Bacik 		} else {
2452e405ad8SJosef Bacik 			ret = cache;
2462e405ad8SJosef Bacik 			break;
2472e405ad8SJosef Bacik 		}
2482e405ad8SJosef Bacik 	}
24908dddb29SFilipe Manana 	if (ret)
2502e405ad8SJosef Bacik 		btrfs_get_block_group(ret);
25116b0c258SFilipe Manana 	read_unlock(&info->block_group_cache_lock);
2522e405ad8SJosef Bacik 
2532e405ad8SJosef Bacik 	return ret;
2542e405ad8SJosef Bacik }
2552e405ad8SJosef Bacik 
2562e405ad8SJosef Bacik /*
2572e405ad8SJosef Bacik  * Return the block group that starts at or after bytenr
2582e405ad8SJosef Bacik  */
25932da5386SDavid Sterba struct btrfs_block_group *btrfs_lookup_first_block_group(
2602e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr)
2612e405ad8SJosef Bacik {
2622e405ad8SJosef Bacik 	return block_group_cache_tree_search(info, bytenr, 0);
2632e405ad8SJosef Bacik }
2642e405ad8SJosef Bacik 
2652e405ad8SJosef Bacik /*
2662e405ad8SJosef Bacik  * Return the block group that contains the given bytenr
2672e405ad8SJosef Bacik  */
26832da5386SDavid Sterba struct btrfs_block_group *btrfs_lookup_block_group(
2692e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr)
2702e405ad8SJosef Bacik {
2712e405ad8SJosef Bacik 	return block_group_cache_tree_search(info, bytenr, 1);
2722e405ad8SJosef Bacik }
2732e405ad8SJosef Bacik 
27432da5386SDavid Sterba struct btrfs_block_group *btrfs_next_block_group(
27532da5386SDavid Sterba 		struct btrfs_block_group *cache)
2762e405ad8SJosef Bacik {
2772e405ad8SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
2782e405ad8SJosef Bacik 	struct rb_node *node;
2792e405ad8SJosef Bacik 
28016b0c258SFilipe Manana 	read_lock(&fs_info->block_group_cache_lock);
2812e405ad8SJosef Bacik 
2822e405ad8SJosef Bacik 	/* If our block group was removed, we need a full search. */
2832e405ad8SJosef Bacik 	if (RB_EMPTY_NODE(&cache->cache_node)) {
284b3470b5dSDavid Sterba 		const u64 next_bytenr = cache->start + cache->length;
2852e405ad8SJosef Bacik 
28616b0c258SFilipe Manana 		read_unlock(&fs_info->block_group_cache_lock);
2872e405ad8SJosef Bacik 		btrfs_put_block_group(cache);
2888b01f931SFilipe Manana 		return btrfs_lookup_first_block_group(fs_info, next_bytenr);
2892e405ad8SJosef Bacik 	}
2902e405ad8SJosef Bacik 	node = rb_next(&cache->cache_node);
2912e405ad8SJosef Bacik 	btrfs_put_block_group(cache);
2922e405ad8SJosef Bacik 	if (node) {
29332da5386SDavid Sterba 		cache = rb_entry(node, struct btrfs_block_group, cache_node);
2942e405ad8SJosef Bacik 		btrfs_get_block_group(cache);
2952e405ad8SJosef Bacik 	} else
2962e405ad8SJosef Bacik 		cache = NULL;
29716b0c258SFilipe Manana 	read_unlock(&fs_info->block_group_cache_lock);
2982e405ad8SJosef Bacik 	return cache;
2992e405ad8SJosef Bacik }
3003eeb3226SJosef Bacik 
30143dd529aSDavid Sterba /*
3022306e83eSFilipe Manana  * Check if we can do a NOCOW write for a given extent.
3032306e83eSFilipe Manana  *
3042306e83eSFilipe Manana  * @fs_info:       The filesystem information object.
3052306e83eSFilipe Manana  * @bytenr:        Logical start address of the extent.
3062306e83eSFilipe Manana  *
3072306e83eSFilipe Manana  * Check if we can do a NOCOW write for the given extent, and increments the
3082306e83eSFilipe Manana  * number of NOCOW writers in the block group that contains the extent, as long
3092306e83eSFilipe Manana  * as the block group exists and it's currently not in read-only mode.
3102306e83eSFilipe Manana  *
3112306e83eSFilipe Manana  * Returns: A non-NULL block group pointer if we can do a NOCOW write, the caller
3122306e83eSFilipe Manana  *          is responsible for calling btrfs_dec_nocow_writers() later.
3132306e83eSFilipe Manana  *
3142306e83eSFilipe Manana  *          Or NULL if we can not do a NOCOW write
3152306e83eSFilipe Manana  */
3162306e83eSFilipe Manana struct btrfs_block_group *btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info,
3172306e83eSFilipe Manana 						  u64 bytenr)
3183eeb3226SJosef Bacik {
31932da5386SDavid Sterba 	struct btrfs_block_group *bg;
3202306e83eSFilipe Manana 	bool can_nocow = true;
3213eeb3226SJosef Bacik 
3223eeb3226SJosef Bacik 	bg = btrfs_lookup_block_group(fs_info, bytenr);
3233eeb3226SJosef Bacik 	if (!bg)
3242306e83eSFilipe Manana 		return NULL;
3253eeb3226SJosef Bacik 
3263eeb3226SJosef Bacik 	spin_lock(&bg->lock);
3273eeb3226SJosef Bacik 	if (bg->ro)
3282306e83eSFilipe Manana 		can_nocow = false;
3293eeb3226SJosef Bacik 	else
3303eeb3226SJosef Bacik 		atomic_inc(&bg->nocow_writers);
3313eeb3226SJosef Bacik 	spin_unlock(&bg->lock);
3323eeb3226SJosef Bacik 
3332306e83eSFilipe Manana 	if (!can_nocow) {
3343eeb3226SJosef Bacik 		btrfs_put_block_group(bg);
3352306e83eSFilipe Manana 		return NULL;
3363eeb3226SJosef Bacik 	}
3373eeb3226SJosef Bacik 
3382306e83eSFilipe Manana 	/* No put on block group, done by btrfs_dec_nocow_writers(). */
3392306e83eSFilipe Manana 	return bg;
3402306e83eSFilipe Manana }
3413eeb3226SJosef Bacik 
34243dd529aSDavid Sterba /*
3432306e83eSFilipe Manana  * Decrement the number of NOCOW writers in a block group.
3442306e83eSFilipe Manana  *
3452306e83eSFilipe Manana  * This is meant to be called after a previous call to btrfs_inc_nocow_writers(),
3462306e83eSFilipe Manana  * and on the block group returned by that call. Typically this is called after
3472306e83eSFilipe Manana  * creating an ordered extent for a NOCOW write, to prevent races with scrub and
3482306e83eSFilipe Manana  * relocation.
3492306e83eSFilipe Manana  *
3502306e83eSFilipe Manana  * After this call, the caller should not use the block group anymore. It it wants
3512306e83eSFilipe Manana  * to use it, then it should get a reference on it before calling this function.
3522306e83eSFilipe Manana  */
3532306e83eSFilipe Manana void btrfs_dec_nocow_writers(struct btrfs_block_group *bg)
3542306e83eSFilipe Manana {
3553eeb3226SJosef Bacik 	if (atomic_dec_and_test(&bg->nocow_writers))
3563eeb3226SJosef Bacik 		wake_up_var(&bg->nocow_writers);
3572306e83eSFilipe Manana 
3582306e83eSFilipe Manana 	/* For the lookup done by a previous call to btrfs_inc_nocow_writers(). */
3593eeb3226SJosef Bacik 	btrfs_put_block_group(bg);
3603eeb3226SJosef Bacik }
3613eeb3226SJosef Bacik 
36232da5386SDavid Sterba void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
3633eeb3226SJosef Bacik {
3643eeb3226SJosef Bacik 	wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
3653eeb3226SJosef Bacik }
3663eeb3226SJosef Bacik 
3673eeb3226SJosef Bacik void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
3683eeb3226SJosef Bacik 					const u64 start)
3693eeb3226SJosef Bacik {
37032da5386SDavid Sterba 	struct btrfs_block_group *bg;
3713eeb3226SJosef Bacik 
3723eeb3226SJosef Bacik 	bg = btrfs_lookup_block_group(fs_info, start);
3733eeb3226SJosef Bacik 	ASSERT(bg);
3743eeb3226SJosef Bacik 	if (atomic_dec_and_test(&bg->reservations))
3753eeb3226SJosef Bacik 		wake_up_var(&bg->reservations);
3763eeb3226SJosef Bacik 	btrfs_put_block_group(bg);
3773eeb3226SJosef Bacik }
3783eeb3226SJosef Bacik 
37932da5386SDavid Sterba void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
3803eeb3226SJosef Bacik {
3813eeb3226SJosef Bacik 	struct btrfs_space_info *space_info = bg->space_info;
3823eeb3226SJosef Bacik 
3833eeb3226SJosef Bacik 	ASSERT(bg->ro);
3843eeb3226SJosef Bacik 
3853eeb3226SJosef Bacik 	if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
3863eeb3226SJosef Bacik 		return;
3873eeb3226SJosef Bacik 
3883eeb3226SJosef Bacik 	/*
3893eeb3226SJosef Bacik 	 * Our block group is read only but before we set it to read only,
3903eeb3226SJosef Bacik 	 * some task might have had allocated an extent from it already, but it
3913eeb3226SJosef Bacik 	 * has not yet created a respective ordered extent (and added it to a
3923eeb3226SJosef Bacik 	 * root's list of ordered extents).
3933eeb3226SJosef Bacik 	 * Therefore wait for any task currently allocating extents, since the
3943eeb3226SJosef Bacik 	 * block group's reservations counter is incremented while a read lock
3953eeb3226SJosef Bacik 	 * on the groups' semaphore is held and decremented after releasing
3963eeb3226SJosef Bacik 	 * the read access on that semaphore and creating the ordered extent.
3973eeb3226SJosef Bacik 	 */
3983eeb3226SJosef Bacik 	down_write(&space_info->groups_sem);
3993eeb3226SJosef Bacik 	up_write(&space_info->groups_sem);
4003eeb3226SJosef Bacik 
4013eeb3226SJosef Bacik 	wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
4023eeb3226SJosef Bacik }
4039f21246dSJosef Bacik 
4049f21246dSJosef Bacik struct btrfs_caching_control *btrfs_get_caching_control(
40532da5386SDavid Sterba 		struct btrfs_block_group *cache)
4069f21246dSJosef Bacik {
4079f21246dSJosef Bacik 	struct btrfs_caching_control *ctl;
4089f21246dSJosef Bacik 
4099f21246dSJosef Bacik 	spin_lock(&cache->lock);
4109f21246dSJosef Bacik 	if (!cache->caching_ctl) {
4119f21246dSJosef Bacik 		spin_unlock(&cache->lock);
4129f21246dSJosef Bacik 		return NULL;
4139f21246dSJosef Bacik 	}
4149f21246dSJosef Bacik 
4159f21246dSJosef Bacik 	ctl = cache->caching_ctl;
4169f21246dSJosef Bacik 	refcount_inc(&ctl->count);
4179f21246dSJosef Bacik 	spin_unlock(&cache->lock);
4189f21246dSJosef Bacik 	return ctl;
4199f21246dSJosef Bacik }
4209f21246dSJosef Bacik 
4219f21246dSJosef Bacik void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
4229f21246dSJosef Bacik {
4239f21246dSJosef Bacik 	if (refcount_dec_and_test(&ctl->count))
4249f21246dSJosef Bacik 		kfree(ctl);
4259f21246dSJosef Bacik }
4269f21246dSJosef Bacik 
4279f21246dSJosef Bacik /*
4289f21246dSJosef Bacik  * When we wait for progress in the block group caching, its because our
4299f21246dSJosef Bacik  * allocation attempt failed at least once.  So, we must sleep and let some
4309f21246dSJosef Bacik  * progress happen before we try again.
4319f21246dSJosef Bacik  *
4329f21246dSJosef Bacik  * This function will sleep at least once waiting for new free space to show
4339f21246dSJosef Bacik  * up, and then it will check the block group free space numbers for our min
4349f21246dSJosef Bacik  * num_bytes.  Another option is to have it go ahead and look in the rbtree for
4359f21246dSJosef Bacik  * a free extent of a given size, but this is a good start.
4369f21246dSJosef Bacik  *
4379f21246dSJosef Bacik  * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
4389f21246dSJosef Bacik  * any of the information in this block group.
4399f21246dSJosef Bacik  */
44032da5386SDavid Sterba void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
4419f21246dSJosef Bacik 					   u64 num_bytes)
4429f21246dSJosef Bacik {
4439f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
4449f21246dSJosef Bacik 
4459f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4469f21246dSJosef Bacik 	if (!caching_ctl)
4479f21246dSJosef Bacik 		return;
4489f21246dSJosef Bacik 
44932da5386SDavid Sterba 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
4509f21246dSJosef Bacik 		   (cache->free_space_ctl->free_space >= num_bytes));
4519f21246dSJosef Bacik 
4529f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4539f21246dSJosef Bacik }
4549f21246dSJosef Bacik 
455ced8ecf0SOmar Sandoval static int btrfs_caching_ctl_wait_done(struct btrfs_block_group *cache,
456ced8ecf0SOmar Sandoval 				       struct btrfs_caching_control *caching_ctl)
457ced8ecf0SOmar Sandoval {
458ced8ecf0SOmar Sandoval 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
459ced8ecf0SOmar Sandoval 	return cache->cached == BTRFS_CACHE_ERROR ? -EIO : 0;
460ced8ecf0SOmar Sandoval }
461ced8ecf0SOmar Sandoval 
462ced8ecf0SOmar Sandoval static int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
4639f21246dSJosef Bacik {
4649f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
465ced8ecf0SOmar Sandoval 	int ret;
4669f21246dSJosef Bacik 
4679f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4689f21246dSJosef Bacik 	if (!caching_ctl)
4699f21246dSJosef Bacik 		return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
470ced8ecf0SOmar Sandoval 	ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
4719f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4729f21246dSJosef Bacik 	return ret;
4739f21246dSJosef Bacik }
4749f21246dSJosef Bacik 
4759f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
47632da5386SDavid Sterba static void fragment_free_space(struct btrfs_block_group *block_group)
4779f21246dSJosef Bacik {
4789f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
479b3470b5dSDavid Sterba 	u64 start = block_group->start;
480b3470b5dSDavid Sterba 	u64 len = block_group->length;
4819f21246dSJosef Bacik 	u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
4829f21246dSJosef Bacik 		fs_info->nodesize : fs_info->sectorsize;
4839f21246dSJosef Bacik 	u64 step = chunk << 1;
4849f21246dSJosef Bacik 
4859f21246dSJosef Bacik 	while (len > chunk) {
4869f21246dSJosef Bacik 		btrfs_remove_free_space(block_group, start, chunk);
4879f21246dSJosef Bacik 		start += step;
4889f21246dSJosef Bacik 		if (len < step)
4899f21246dSJosef Bacik 			len = 0;
4909f21246dSJosef Bacik 		else
4919f21246dSJosef Bacik 			len -= step;
4929f21246dSJosef Bacik 	}
4939f21246dSJosef Bacik }
4949f21246dSJosef Bacik #endif
4959f21246dSJosef Bacik 
4969f21246dSJosef Bacik /*
4979f21246dSJosef Bacik  * This is only called by btrfs_cache_block_group, since we could have freed
4989f21246dSJosef Bacik  * extents we need to check the pinned_extents for any extents that can't be
4999f21246dSJosef Bacik  * used yet since their free space will be released as soon as the transaction
5009f21246dSJosef Bacik  * commits.
5019f21246dSJosef Bacik  */
50232da5386SDavid Sterba u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
5039f21246dSJosef Bacik {
5049f21246dSJosef Bacik 	struct btrfs_fs_info *info = block_group->fs_info;
5059f21246dSJosef Bacik 	u64 extent_start, extent_end, size, total_added = 0;
5069f21246dSJosef Bacik 	int ret;
5079f21246dSJosef Bacik 
5089f21246dSJosef Bacik 	while (start < end) {
509fe119a6eSNikolay Borisov 		ret = find_first_extent_bit(&info->excluded_extents, start,
5109f21246dSJosef Bacik 					    &extent_start, &extent_end,
5119f21246dSJosef Bacik 					    EXTENT_DIRTY | EXTENT_UPTODATE,
5129f21246dSJosef Bacik 					    NULL);
5139f21246dSJosef Bacik 		if (ret)
5149f21246dSJosef Bacik 			break;
5159f21246dSJosef Bacik 
5169f21246dSJosef Bacik 		if (extent_start <= start) {
5179f21246dSJosef Bacik 			start = extent_end + 1;
5189f21246dSJosef Bacik 		} else if (extent_start > start && extent_start < end) {
5199f21246dSJosef Bacik 			size = extent_start - start;
5209f21246dSJosef Bacik 			total_added += size;
521b0643e59SDennis Zhou 			ret = btrfs_add_free_space_async_trimmed(block_group,
522b0643e59SDennis Zhou 								 start, size);
5239f21246dSJosef Bacik 			BUG_ON(ret); /* -ENOMEM or logic error */
5249f21246dSJosef Bacik 			start = extent_end + 1;
5259f21246dSJosef Bacik 		} else {
5269f21246dSJosef Bacik 			break;
5279f21246dSJosef Bacik 		}
5289f21246dSJosef Bacik 	}
5299f21246dSJosef Bacik 
5309f21246dSJosef Bacik 	if (start < end) {
5319f21246dSJosef Bacik 		size = end - start;
5329f21246dSJosef Bacik 		total_added += size;
533b0643e59SDennis Zhou 		ret = btrfs_add_free_space_async_trimmed(block_group, start,
534b0643e59SDennis Zhou 							 size);
5359f21246dSJosef Bacik 		BUG_ON(ret); /* -ENOMEM or logic error */
5369f21246dSJosef Bacik 	}
5379f21246dSJosef Bacik 
5389f21246dSJosef Bacik 	return total_added;
5399f21246dSJosef Bacik }
5409f21246dSJosef Bacik 
541c7eec3d9SBoris Burkov /*
542c7eec3d9SBoris Burkov  * Get an arbitrary extent item index / max_index through the block group
543c7eec3d9SBoris Burkov  *
544c7eec3d9SBoris Burkov  * @block_group   the block group to sample from
545c7eec3d9SBoris Burkov  * @index:        the integral step through the block group to grab from
546c7eec3d9SBoris Burkov  * @max_index:    the granularity of the sampling
547c7eec3d9SBoris Burkov  * @key:          return value parameter for the item we find
548c7eec3d9SBoris Burkov  *
549c7eec3d9SBoris Burkov  * Pre-conditions on indices:
550c7eec3d9SBoris Burkov  * 0 <= index <= max_index
551c7eec3d9SBoris Burkov  * 0 < max_index
552c7eec3d9SBoris Burkov  *
553c7eec3d9SBoris Burkov  * Returns: 0 on success, 1 if the search didn't yield a useful item, negative
554c7eec3d9SBoris Burkov  * error code on error.
555c7eec3d9SBoris Burkov  */
556c7eec3d9SBoris Burkov static int sample_block_group_extent_item(struct btrfs_caching_control *caching_ctl,
557c7eec3d9SBoris Burkov 					  struct btrfs_block_group *block_group,
558c7eec3d9SBoris Burkov 					  int index, int max_index,
55912148367SBoris Burkov 					  struct btrfs_key *found_key)
560c7eec3d9SBoris Burkov {
561c7eec3d9SBoris Burkov 	struct btrfs_fs_info *fs_info = block_group->fs_info;
562c7eec3d9SBoris Burkov 	struct btrfs_root *extent_root;
563c7eec3d9SBoris Burkov 	u64 search_offset;
564c7eec3d9SBoris Burkov 	u64 search_end = block_group->start + block_group->length;
565c7eec3d9SBoris Burkov 	struct btrfs_path *path;
56612148367SBoris Burkov 	struct btrfs_key search_key;
56712148367SBoris Burkov 	int ret = 0;
568c7eec3d9SBoris Burkov 
569c7eec3d9SBoris Burkov 	ASSERT(index >= 0);
570c7eec3d9SBoris Burkov 	ASSERT(index <= max_index);
571c7eec3d9SBoris Burkov 	ASSERT(max_index > 0);
572c7eec3d9SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
573c7eec3d9SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
574c7eec3d9SBoris Burkov 
575c7eec3d9SBoris Burkov 	path = btrfs_alloc_path();
576c7eec3d9SBoris Burkov 	if (!path)
577c7eec3d9SBoris Burkov 		return -ENOMEM;
578c7eec3d9SBoris Burkov 
579c7eec3d9SBoris Burkov 	extent_root = btrfs_extent_root(fs_info, max_t(u64, block_group->start,
580c7eec3d9SBoris Burkov 						       BTRFS_SUPER_INFO_OFFSET));
581c7eec3d9SBoris Burkov 
582c7eec3d9SBoris Burkov 	path->skip_locking = 1;
583c7eec3d9SBoris Burkov 	path->search_commit_root = 1;
584c7eec3d9SBoris Burkov 	path->reada = READA_FORWARD;
585c7eec3d9SBoris Burkov 
586c7eec3d9SBoris Burkov 	search_offset = index * div_u64(block_group->length, max_index);
58712148367SBoris Burkov 	search_key.objectid = block_group->start + search_offset;
58812148367SBoris Burkov 	search_key.type = BTRFS_EXTENT_ITEM_KEY;
58912148367SBoris Burkov 	search_key.offset = 0;
590c7eec3d9SBoris Burkov 
59112148367SBoris Burkov 	btrfs_for_each_slot(extent_root, &search_key, found_key, path, ret) {
592c7eec3d9SBoris Burkov 		/* Success; sampled an extent item in the block group */
59312148367SBoris Burkov 		if (found_key->type == BTRFS_EXTENT_ITEM_KEY &&
59412148367SBoris Burkov 		    found_key->objectid >= block_group->start &&
59512148367SBoris Burkov 		    found_key->objectid + found_key->offset <= search_end)
59612148367SBoris Burkov 			break;
597c7eec3d9SBoris Burkov 
598c7eec3d9SBoris Burkov 		/* We can't possibly find a valid extent item anymore */
59912148367SBoris Burkov 		if (found_key->objectid >= search_end) {
600c7eec3d9SBoris Burkov 			ret = 1;
601c7eec3d9SBoris Burkov 			break;
602c7eec3d9SBoris Burkov 		}
603c7eec3d9SBoris Burkov 	}
60412148367SBoris Burkov 
605c7eec3d9SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
606c7eec3d9SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
607c7eec3d9SBoris Burkov 	btrfs_free_path(path);
608c7eec3d9SBoris Burkov 	return ret;
609c7eec3d9SBoris Burkov }
610c7eec3d9SBoris Burkov 
611c7eec3d9SBoris Burkov /*
612c7eec3d9SBoris Burkov  * Best effort attempt to compute a block group's size class while caching it.
613c7eec3d9SBoris Burkov  *
614c7eec3d9SBoris Burkov  * @block_group: the block group we are caching
615c7eec3d9SBoris Burkov  *
616c7eec3d9SBoris Burkov  * We cannot infer the size class while adding free space extents, because that
617c7eec3d9SBoris Burkov  * logic doesn't care about contiguous file extents (it doesn't differentiate
618c7eec3d9SBoris Burkov  * between a 100M extent and 100 contiguous 1M extents). So we need to read the
619c7eec3d9SBoris Burkov  * file extent items. Reading all of them is quite wasteful, because usually
620c7eec3d9SBoris Burkov  * only a handful are enough to give a good answer. Therefore, we just grab 5 of
621c7eec3d9SBoris Burkov  * them at even steps through the block group and pick the smallest size class
622c7eec3d9SBoris Burkov  * we see. Since size class is best effort, and not guaranteed in general,
623c7eec3d9SBoris Burkov  * inaccuracy is acceptable.
624c7eec3d9SBoris Burkov  *
625c7eec3d9SBoris Burkov  * To be more explicit about why this algorithm makes sense:
626c7eec3d9SBoris Burkov  *
627c7eec3d9SBoris Burkov  * If we are caching in a block group from disk, then there are three major cases
628c7eec3d9SBoris Burkov  * to consider:
629c7eec3d9SBoris Burkov  * 1. the block group is well behaved and all extents in it are the same size
630c7eec3d9SBoris Burkov  *    class.
631c7eec3d9SBoris Burkov  * 2. the block group is mostly one size class with rare exceptions for last
632c7eec3d9SBoris Burkov  *    ditch allocations
633c7eec3d9SBoris Burkov  * 3. the block group was populated before size classes and can have a totally
634c7eec3d9SBoris Burkov  *    arbitrary mix of size classes.
635c7eec3d9SBoris Burkov  *
636c7eec3d9SBoris Burkov  * In case 1, looking at any extent in the block group will yield the correct
637c7eec3d9SBoris Burkov  * result. For the mixed cases, taking the minimum size class seems like a good
638c7eec3d9SBoris Burkov  * approximation, since gaps from frees will be usable to the size class. For
639c7eec3d9SBoris Burkov  * 2., a small handful of file extents is likely to yield the right answer. For
640c7eec3d9SBoris Burkov  * 3, we can either read every file extent, or admit that this is best effort
641c7eec3d9SBoris Burkov  * anyway and try to stay fast.
642c7eec3d9SBoris Burkov  *
643c7eec3d9SBoris Burkov  * Returns: 0 on success, negative error code on error.
644c7eec3d9SBoris Burkov  */
645c7eec3d9SBoris Burkov static int load_block_group_size_class(struct btrfs_caching_control *caching_ctl,
646c7eec3d9SBoris Burkov 				       struct btrfs_block_group *block_group)
647c7eec3d9SBoris Burkov {
64812148367SBoris Burkov 	struct btrfs_fs_info *fs_info = block_group->fs_info;
649c7eec3d9SBoris Burkov 	struct btrfs_key key;
650c7eec3d9SBoris Burkov 	int i;
651c7eec3d9SBoris Burkov 	u64 min_size = block_group->length;
652c7eec3d9SBoris Burkov 	enum btrfs_block_group_size_class size_class = BTRFS_BG_SZ_NONE;
653c7eec3d9SBoris Burkov 	int ret;
654c7eec3d9SBoris Burkov 
655cb0922f2SBoris Burkov 	if (!btrfs_block_group_should_use_size_class(block_group))
656c7eec3d9SBoris Burkov 		return 0;
657c7eec3d9SBoris Burkov 
65812148367SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
65912148367SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
660c7eec3d9SBoris Burkov 	for (i = 0; i < 5; ++i) {
661c7eec3d9SBoris Burkov 		ret = sample_block_group_extent_item(caching_ctl, block_group, i, 5, &key);
662c7eec3d9SBoris Burkov 		if (ret < 0)
663c7eec3d9SBoris Burkov 			goto out;
664c7eec3d9SBoris Burkov 		if (ret > 0)
665c7eec3d9SBoris Burkov 			continue;
666c7eec3d9SBoris Burkov 		min_size = min_t(u64, min_size, key.offset);
667c7eec3d9SBoris Burkov 		size_class = btrfs_calc_block_group_size_class(min_size);
668c7eec3d9SBoris Burkov 	}
669c7eec3d9SBoris Burkov 	if (size_class != BTRFS_BG_SZ_NONE) {
670c7eec3d9SBoris Burkov 		spin_lock(&block_group->lock);
671c7eec3d9SBoris Burkov 		block_group->size_class = size_class;
672c7eec3d9SBoris Burkov 		spin_unlock(&block_group->lock);
673c7eec3d9SBoris Burkov 	}
674c7eec3d9SBoris Burkov out:
675c7eec3d9SBoris Burkov 	return ret;
676c7eec3d9SBoris Burkov }
677c7eec3d9SBoris Burkov 
6789f21246dSJosef Bacik static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
6799f21246dSJosef Bacik {
68032da5386SDavid Sterba 	struct btrfs_block_group *block_group = caching_ctl->block_group;
6819f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
68229cbcf40SJosef Bacik 	struct btrfs_root *extent_root;
6839f21246dSJosef Bacik 	struct btrfs_path *path;
6849f21246dSJosef Bacik 	struct extent_buffer *leaf;
6859f21246dSJosef Bacik 	struct btrfs_key key;
6869f21246dSJosef Bacik 	u64 total_found = 0;
6879f21246dSJosef Bacik 	u64 last = 0;
6889f21246dSJosef Bacik 	u32 nritems;
6899f21246dSJosef Bacik 	int ret;
6909f21246dSJosef Bacik 	bool wakeup = true;
6919f21246dSJosef Bacik 
6929f21246dSJosef Bacik 	path = btrfs_alloc_path();
6939f21246dSJosef Bacik 	if (!path)
6949f21246dSJosef Bacik 		return -ENOMEM;
6959f21246dSJosef Bacik 
696b3470b5dSDavid Sterba 	last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
69729cbcf40SJosef Bacik 	extent_root = btrfs_extent_root(fs_info, last);
6989f21246dSJosef Bacik 
6999f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
7009f21246dSJosef Bacik 	/*
7019f21246dSJosef Bacik 	 * If we're fragmenting we don't want to make anybody think we can
7029f21246dSJosef Bacik 	 * allocate from this block group until we've had a chance to fragment
7039f21246dSJosef Bacik 	 * the free space.
7049f21246dSJosef Bacik 	 */
7059f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group))
7069f21246dSJosef Bacik 		wakeup = false;
7079f21246dSJosef Bacik #endif
7089f21246dSJosef Bacik 	/*
7099f21246dSJosef Bacik 	 * We don't want to deadlock with somebody trying to allocate a new
7109f21246dSJosef Bacik 	 * extent for the extent root while also trying to search the extent
7119f21246dSJosef Bacik 	 * root to add free space.  So we skip locking and search the commit
7129f21246dSJosef Bacik 	 * root, since its read-only
7139f21246dSJosef Bacik 	 */
7149f21246dSJosef Bacik 	path->skip_locking = 1;
7159f21246dSJosef Bacik 	path->search_commit_root = 1;
7169f21246dSJosef Bacik 	path->reada = READA_FORWARD;
7179f21246dSJosef Bacik 
7189f21246dSJosef Bacik 	key.objectid = last;
7199f21246dSJosef Bacik 	key.offset = 0;
7209f21246dSJosef Bacik 	key.type = BTRFS_EXTENT_ITEM_KEY;
7219f21246dSJosef Bacik 
7229f21246dSJosef Bacik next:
7239f21246dSJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
7249f21246dSJosef Bacik 	if (ret < 0)
7259f21246dSJosef Bacik 		goto out;
7269f21246dSJosef Bacik 
7279f21246dSJosef Bacik 	leaf = path->nodes[0];
7289f21246dSJosef Bacik 	nritems = btrfs_header_nritems(leaf);
7299f21246dSJosef Bacik 
7309f21246dSJosef Bacik 	while (1) {
7319f21246dSJosef Bacik 		if (btrfs_fs_closing(fs_info) > 1) {
7329f21246dSJosef Bacik 			last = (u64)-1;
7339f21246dSJosef Bacik 			break;
7349f21246dSJosef Bacik 		}
7359f21246dSJosef Bacik 
7369f21246dSJosef Bacik 		if (path->slots[0] < nritems) {
7379f21246dSJosef Bacik 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7389f21246dSJosef Bacik 		} else {
7399f21246dSJosef Bacik 			ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
7409f21246dSJosef Bacik 			if (ret)
7419f21246dSJosef Bacik 				break;
7429f21246dSJosef Bacik 
7439f21246dSJosef Bacik 			if (need_resched() ||
7449f21246dSJosef Bacik 			    rwsem_is_contended(&fs_info->commit_root_sem)) {
7459f21246dSJosef Bacik 				btrfs_release_path(path);
7469f21246dSJosef Bacik 				up_read(&fs_info->commit_root_sem);
7479f21246dSJosef Bacik 				mutex_unlock(&caching_ctl->mutex);
7489f21246dSJosef Bacik 				cond_resched();
7499f21246dSJosef Bacik 				mutex_lock(&caching_ctl->mutex);
7509f21246dSJosef Bacik 				down_read(&fs_info->commit_root_sem);
7519f21246dSJosef Bacik 				goto next;
7529f21246dSJosef Bacik 			}
7539f21246dSJosef Bacik 
7549f21246dSJosef Bacik 			ret = btrfs_next_leaf(extent_root, path);
7559f21246dSJosef Bacik 			if (ret < 0)
7569f21246dSJosef Bacik 				goto out;
7579f21246dSJosef Bacik 			if (ret)
7589f21246dSJosef Bacik 				break;
7599f21246dSJosef Bacik 			leaf = path->nodes[0];
7609f21246dSJosef Bacik 			nritems = btrfs_header_nritems(leaf);
7619f21246dSJosef Bacik 			continue;
7629f21246dSJosef Bacik 		}
7639f21246dSJosef Bacik 
7649f21246dSJosef Bacik 		if (key.objectid < last) {
7659f21246dSJosef Bacik 			key.objectid = last;
7669f21246dSJosef Bacik 			key.offset = 0;
7679f21246dSJosef Bacik 			key.type = BTRFS_EXTENT_ITEM_KEY;
7689f21246dSJosef Bacik 			btrfs_release_path(path);
7699f21246dSJosef Bacik 			goto next;
7709f21246dSJosef Bacik 		}
7719f21246dSJosef Bacik 
772b3470b5dSDavid Sterba 		if (key.objectid < block_group->start) {
7739f21246dSJosef Bacik 			path->slots[0]++;
7749f21246dSJosef Bacik 			continue;
7759f21246dSJosef Bacik 		}
7769f21246dSJosef Bacik 
777b3470b5dSDavid Sterba 		if (key.objectid >= block_group->start + block_group->length)
7789f21246dSJosef Bacik 			break;
7799f21246dSJosef Bacik 
7809f21246dSJosef Bacik 		if (key.type == BTRFS_EXTENT_ITEM_KEY ||
7819f21246dSJosef Bacik 		    key.type == BTRFS_METADATA_ITEM_KEY) {
7829f21246dSJosef Bacik 			total_found += add_new_free_space(block_group, last,
7839f21246dSJosef Bacik 							  key.objectid);
7849f21246dSJosef Bacik 			if (key.type == BTRFS_METADATA_ITEM_KEY)
7859f21246dSJosef Bacik 				last = key.objectid +
7869f21246dSJosef Bacik 					fs_info->nodesize;
7879f21246dSJosef Bacik 			else
7889f21246dSJosef Bacik 				last = key.objectid + key.offset;
7899f21246dSJosef Bacik 
7909f21246dSJosef Bacik 			if (total_found > CACHING_CTL_WAKE_UP) {
7919f21246dSJosef Bacik 				total_found = 0;
7929f21246dSJosef Bacik 				if (wakeup)
7939f21246dSJosef Bacik 					wake_up(&caching_ctl->wait);
7949f21246dSJosef Bacik 			}
7959f21246dSJosef Bacik 		}
7969f21246dSJosef Bacik 		path->slots[0]++;
7979f21246dSJosef Bacik 	}
7989f21246dSJosef Bacik 	ret = 0;
7999f21246dSJosef Bacik 
8009f21246dSJosef Bacik 	total_found += add_new_free_space(block_group, last,
801b3470b5dSDavid Sterba 				block_group->start + block_group->length);
8029f21246dSJosef Bacik 
8039f21246dSJosef Bacik out:
8049f21246dSJosef Bacik 	btrfs_free_path(path);
8059f21246dSJosef Bacik 	return ret;
8069f21246dSJosef Bacik }
8079f21246dSJosef Bacik 
8089f21246dSJosef Bacik static noinline void caching_thread(struct btrfs_work *work)
8099f21246dSJosef Bacik {
81032da5386SDavid Sterba 	struct btrfs_block_group *block_group;
8119f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info;
8129f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
8139f21246dSJosef Bacik 	int ret;
8149f21246dSJosef Bacik 
8159f21246dSJosef Bacik 	caching_ctl = container_of(work, struct btrfs_caching_control, work);
8169f21246dSJosef Bacik 	block_group = caching_ctl->block_group;
8179f21246dSJosef Bacik 	fs_info = block_group->fs_info;
8189f21246dSJosef Bacik 
8199f21246dSJosef Bacik 	mutex_lock(&caching_ctl->mutex);
8209f21246dSJosef Bacik 	down_read(&fs_info->commit_root_sem);
8219f21246dSJosef Bacik 
822c7eec3d9SBoris Burkov 	load_block_group_size_class(caching_ctl, block_group);
823e747853cSJosef Bacik 	if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
824e747853cSJosef Bacik 		ret = load_free_space_cache(block_group);
825e747853cSJosef Bacik 		if (ret == 1) {
826e747853cSJosef Bacik 			ret = 0;
827e747853cSJosef Bacik 			goto done;
828e747853cSJosef Bacik 		}
829e747853cSJosef Bacik 
830e747853cSJosef Bacik 		/*
831e747853cSJosef Bacik 		 * We failed to load the space cache, set ourselves to
832e747853cSJosef Bacik 		 * CACHE_STARTED and carry on.
833e747853cSJosef Bacik 		 */
834e747853cSJosef Bacik 		spin_lock(&block_group->lock);
835e747853cSJosef Bacik 		block_group->cached = BTRFS_CACHE_STARTED;
836e747853cSJosef Bacik 		spin_unlock(&block_group->lock);
837e747853cSJosef Bacik 		wake_up(&caching_ctl->wait);
838e747853cSJosef Bacik 	}
839e747853cSJosef Bacik 
8402f96e402SJosef Bacik 	/*
8412f96e402SJosef Bacik 	 * If we are in the transaction that populated the free space tree we
8422f96e402SJosef Bacik 	 * can't actually cache from the free space tree as our commit root and
8432f96e402SJosef Bacik 	 * real root are the same, so we could change the contents of the blocks
8442f96e402SJosef Bacik 	 * while caching.  Instead do the slow caching in this case, and after
8452f96e402SJosef Bacik 	 * the transaction has committed we will be safe.
8462f96e402SJosef Bacik 	 */
8472f96e402SJosef Bacik 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
8482f96e402SJosef Bacik 	    !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
8499f21246dSJosef Bacik 		ret = load_free_space_tree(caching_ctl);
8509f21246dSJosef Bacik 	else
8519f21246dSJosef Bacik 		ret = load_extent_tree_free(caching_ctl);
852e747853cSJosef Bacik done:
8539f21246dSJosef Bacik 	spin_lock(&block_group->lock);
8549f21246dSJosef Bacik 	block_group->caching_ctl = NULL;
8559f21246dSJosef Bacik 	block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
8569f21246dSJosef Bacik 	spin_unlock(&block_group->lock);
8579f21246dSJosef Bacik 
8589f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
8599f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group)) {
8609f21246dSJosef Bacik 		u64 bytes_used;
8619f21246dSJosef Bacik 
8629f21246dSJosef Bacik 		spin_lock(&block_group->space_info->lock);
8639f21246dSJosef Bacik 		spin_lock(&block_group->lock);
864b3470b5dSDavid Sterba 		bytes_used = block_group->length - block_group->used;
8659f21246dSJosef Bacik 		block_group->space_info->bytes_used += bytes_used >> 1;
8669f21246dSJosef Bacik 		spin_unlock(&block_group->lock);
8679f21246dSJosef Bacik 		spin_unlock(&block_group->space_info->lock);
868e11c0406SJosef Bacik 		fragment_free_space(block_group);
8699f21246dSJosef Bacik 	}
8709f21246dSJosef Bacik #endif
8719f21246dSJosef Bacik 
8729f21246dSJosef Bacik 	up_read(&fs_info->commit_root_sem);
8739f21246dSJosef Bacik 	btrfs_free_excluded_extents(block_group);
8749f21246dSJosef Bacik 	mutex_unlock(&caching_ctl->mutex);
8759f21246dSJosef Bacik 
8769f21246dSJosef Bacik 	wake_up(&caching_ctl->wait);
8779f21246dSJosef Bacik 
8789f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
8799f21246dSJosef Bacik 	btrfs_put_block_group(block_group);
8809f21246dSJosef Bacik }
8819f21246dSJosef Bacik 
882ced8ecf0SOmar Sandoval int btrfs_cache_block_group(struct btrfs_block_group *cache, bool wait)
8839f21246dSJosef Bacik {
8849f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
885e747853cSJosef Bacik 	struct btrfs_caching_control *caching_ctl = NULL;
8869f21246dSJosef Bacik 	int ret = 0;
8879f21246dSJosef Bacik 
8882eda5708SNaohiro Aota 	/* Allocator for zoned filesystems does not use the cache at all */
8892eda5708SNaohiro Aota 	if (btrfs_is_zoned(fs_info))
8902eda5708SNaohiro Aota 		return 0;
8912eda5708SNaohiro Aota 
8929f21246dSJosef Bacik 	caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
8939f21246dSJosef Bacik 	if (!caching_ctl)
8949f21246dSJosef Bacik 		return -ENOMEM;
8959f21246dSJosef Bacik 
8969f21246dSJosef Bacik 	INIT_LIST_HEAD(&caching_ctl->list);
8979f21246dSJosef Bacik 	mutex_init(&caching_ctl->mutex);
8989f21246dSJosef Bacik 	init_waitqueue_head(&caching_ctl->wait);
8999f21246dSJosef Bacik 	caching_ctl->block_group = cache;
900e747853cSJosef Bacik 	refcount_set(&caching_ctl->count, 2);
901a0cac0ecSOmar Sandoval 	btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
9029f21246dSJosef Bacik 
9039f21246dSJosef Bacik 	spin_lock(&cache->lock);
9049f21246dSJosef Bacik 	if (cache->cached != BTRFS_CACHE_NO) {
9059f21246dSJosef Bacik 		kfree(caching_ctl);
906e747853cSJosef Bacik 
907e747853cSJosef Bacik 		caching_ctl = cache->caching_ctl;
908e747853cSJosef Bacik 		if (caching_ctl)
909e747853cSJosef Bacik 			refcount_inc(&caching_ctl->count);
910e747853cSJosef Bacik 		spin_unlock(&cache->lock);
911e747853cSJosef Bacik 		goto out;
9129f21246dSJosef Bacik 	}
9139f21246dSJosef Bacik 	WARN_ON(cache->caching_ctl);
9149f21246dSJosef Bacik 	cache->caching_ctl = caching_ctl;
9159f21246dSJosef Bacik 	cache->cached = BTRFS_CACHE_STARTED;
9169f21246dSJosef Bacik 	spin_unlock(&cache->lock);
9179f21246dSJosef Bacik 
91816b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
9199f21246dSJosef Bacik 	refcount_inc(&caching_ctl->count);
9209f21246dSJosef Bacik 	list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
92116b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
9229f21246dSJosef Bacik 
9239f21246dSJosef Bacik 	btrfs_get_block_group(cache);
9249f21246dSJosef Bacik 
9259f21246dSJosef Bacik 	btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
926e747853cSJosef Bacik out:
927ced8ecf0SOmar Sandoval 	if (wait && caching_ctl)
928ced8ecf0SOmar Sandoval 		ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
929e747853cSJosef Bacik 	if (caching_ctl)
930e747853cSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
9319f21246dSJosef Bacik 
9329f21246dSJosef Bacik 	return ret;
9339f21246dSJosef Bacik }
934e3e0520bSJosef Bacik 
935e3e0520bSJosef Bacik static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
936e3e0520bSJosef Bacik {
937e3e0520bSJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
938e3e0520bSJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
939e3e0520bSJosef Bacik 
940e3e0520bSJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
941e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
942e3e0520bSJosef Bacik 		fs_info->avail_data_alloc_bits &= ~extra_flags;
943e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
944e3e0520bSJosef Bacik 		fs_info->avail_metadata_alloc_bits &= ~extra_flags;
945e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
946e3e0520bSJosef Bacik 		fs_info->avail_system_alloc_bits &= ~extra_flags;
947e3e0520bSJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
948e3e0520bSJosef Bacik }
949e3e0520bSJosef Bacik 
950e3e0520bSJosef Bacik /*
951e3e0520bSJosef Bacik  * Clear incompat bits for the following feature(s):
952e3e0520bSJosef Bacik  *
953e3e0520bSJosef Bacik  * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
954e3e0520bSJosef Bacik  *            in the whole filesystem
9559c907446SDavid Sterba  *
9569c907446SDavid Sterba  * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
957e3e0520bSJosef Bacik  */
958e3e0520bSJosef Bacik static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
959e3e0520bSJosef Bacik {
9609c907446SDavid Sterba 	bool found_raid56 = false;
9619c907446SDavid Sterba 	bool found_raid1c34 = false;
9629c907446SDavid Sterba 
9639c907446SDavid Sterba 	if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
9649c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
9659c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
966e3e0520bSJosef Bacik 		struct list_head *head = &fs_info->space_info;
967e3e0520bSJosef Bacik 		struct btrfs_space_info *sinfo;
968e3e0520bSJosef Bacik 
969e3e0520bSJosef Bacik 		list_for_each_entry_rcu(sinfo, head, list) {
970e3e0520bSJosef Bacik 			down_read(&sinfo->groups_sem);
971e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
9729c907446SDavid Sterba 				found_raid56 = true;
973e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
9749c907446SDavid Sterba 				found_raid56 = true;
9759c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
9769c907446SDavid Sterba 				found_raid1c34 = true;
9779c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
9789c907446SDavid Sterba 				found_raid1c34 = true;
979e3e0520bSJosef Bacik 			up_read(&sinfo->groups_sem);
980e3e0520bSJosef Bacik 		}
981d8e6fd5cSFilipe Manana 		if (!found_raid56)
982e3e0520bSJosef Bacik 			btrfs_clear_fs_incompat(fs_info, RAID56);
983d8e6fd5cSFilipe Manana 		if (!found_raid1c34)
9849c907446SDavid Sterba 			btrfs_clear_fs_incompat(fs_info, RAID1C34);
985e3e0520bSJosef Bacik 	}
986e3e0520bSJosef Bacik }
987e3e0520bSJosef Bacik 
9887357623aSQu Wenruo static int remove_block_group_item(struct btrfs_trans_handle *trans,
9897357623aSQu Wenruo 				   struct btrfs_path *path,
9907357623aSQu Wenruo 				   struct btrfs_block_group *block_group)
9917357623aSQu Wenruo {
9927357623aSQu Wenruo 	struct btrfs_fs_info *fs_info = trans->fs_info;
9937357623aSQu Wenruo 	struct btrfs_root *root;
9947357623aSQu Wenruo 	struct btrfs_key key;
9957357623aSQu Wenruo 	int ret;
9967357623aSQu Wenruo 
997dfe8aec4SJosef Bacik 	root = btrfs_block_group_root(fs_info);
9987357623aSQu Wenruo 	key.objectid = block_group->start;
9997357623aSQu Wenruo 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
10007357623aSQu Wenruo 	key.offset = block_group->length;
10017357623aSQu Wenruo 
10027357623aSQu Wenruo 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10037357623aSQu Wenruo 	if (ret > 0)
10047357623aSQu Wenruo 		ret = -ENOENT;
10057357623aSQu Wenruo 	if (ret < 0)
10067357623aSQu Wenruo 		return ret;
10077357623aSQu Wenruo 
10087357623aSQu Wenruo 	ret = btrfs_del_item(trans, root, path);
10097357623aSQu Wenruo 	return ret;
10107357623aSQu Wenruo }
10117357623aSQu Wenruo 
1012e3e0520bSJosef Bacik int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
1013e3e0520bSJosef Bacik 			     u64 group_start, struct extent_map *em)
1014e3e0520bSJosef Bacik {
1015e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
1016e3e0520bSJosef Bacik 	struct btrfs_path *path;
101732da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1018e3e0520bSJosef Bacik 	struct btrfs_free_cluster *cluster;
1019e3e0520bSJosef Bacik 	struct inode *inode;
1020e3e0520bSJosef Bacik 	struct kobject *kobj = NULL;
1021e3e0520bSJosef Bacik 	int ret;
1022e3e0520bSJosef Bacik 	int index;
1023e3e0520bSJosef Bacik 	int factor;
1024e3e0520bSJosef Bacik 	struct btrfs_caching_control *caching_ctl = NULL;
1025e3e0520bSJosef Bacik 	bool remove_em;
1026e3e0520bSJosef Bacik 	bool remove_rsv = false;
1027e3e0520bSJosef Bacik 
1028e3e0520bSJosef Bacik 	block_group = btrfs_lookup_block_group(fs_info, group_start);
1029e3e0520bSJosef Bacik 	BUG_ON(!block_group);
1030e3e0520bSJosef Bacik 	BUG_ON(!block_group->ro);
1031e3e0520bSJosef Bacik 
1032e3e0520bSJosef Bacik 	trace_btrfs_remove_block_group(block_group);
1033e3e0520bSJosef Bacik 	/*
1034e3e0520bSJosef Bacik 	 * Free the reserved super bytes from this block group before
1035e3e0520bSJosef Bacik 	 * remove it.
1036e3e0520bSJosef Bacik 	 */
1037e3e0520bSJosef Bacik 	btrfs_free_excluded_extents(block_group);
1038b3470b5dSDavid Sterba 	btrfs_free_ref_tree_range(fs_info, block_group->start,
1039b3470b5dSDavid Sterba 				  block_group->length);
1040e3e0520bSJosef Bacik 
1041e3e0520bSJosef Bacik 	index = btrfs_bg_flags_to_raid_index(block_group->flags);
1042e3e0520bSJosef Bacik 	factor = btrfs_bg_type_to_factor(block_group->flags);
1043e3e0520bSJosef Bacik 
1044e3e0520bSJosef Bacik 	/* make sure this block group isn't part of an allocation cluster */
1045e3e0520bSJosef Bacik 	cluster = &fs_info->data_alloc_cluster;
1046e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
1047e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
1048e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
1049e3e0520bSJosef Bacik 
1050e3e0520bSJosef Bacik 	/*
1051e3e0520bSJosef Bacik 	 * make sure this block group isn't part of a metadata
1052e3e0520bSJosef Bacik 	 * allocation cluster
1053e3e0520bSJosef Bacik 	 */
1054e3e0520bSJosef Bacik 	cluster = &fs_info->meta_alloc_cluster;
1055e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
1056e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
1057e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
1058e3e0520bSJosef Bacik 
105940ab3be1SNaohiro Aota 	btrfs_clear_treelog_bg(block_group);
1060c2707a25SJohannes Thumshirn 	btrfs_clear_data_reloc_bg(block_group);
106140ab3be1SNaohiro Aota 
1062e3e0520bSJosef Bacik 	path = btrfs_alloc_path();
1063e3e0520bSJosef Bacik 	if (!path) {
1064e3e0520bSJosef Bacik 		ret = -ENOMEM;
10659fecd132SFilipe Manana 		goto out;
1066e3e0520bSJosef Bacik 	}
1067e3e0520bSJosef Bacik 
1068e3e0520bSJosef Bacik 	/*
1069e3e0520bSJosef Bacik 	 * get the inode first so any iput calls done for the io_list
1070e3e0520bSJosef Bacik 	 * aren't the final iput (no unlinks allowed now)
1071e3e0520bSJosef Bacik 	 */
1072e3e0520bSJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
1073e3e0520bSJosef Bacik 
1074e3e0520bSJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
1075e3e0520bSJosef Bacik 	/*
1076e3e0520bSJosef Bacik 	 * Make sure our free space cache IO is done before removing the
1077e3e0520bSJosef Bacik 	 * free space inode
1078e3e0520bSJosef Bacik 	 */
1079e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
1080e3e0520bSJosef Bacik 	if (!list_empty(&block_group->io_list)) {
1081e3e0520bSJosef Bacik 		list_del_init(&block_group->io_list);
1082e3e0520bSJosef Bacik 
1083e3e0520bSJosef Bacik 		WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
1084e3e0520bSJosef Bacik 
1085e3e0520bSJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
1086e3e0520bSJosef Bacik 		btrfs_wait_cache_io(trans, block_group, path);
1087e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1088e3e0520bSJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
1089e3e0520bSJosef Bacik 	}
1090e3e0520bSJosef Bacik 
1091e3e0520bSJosef Bacik 	if (!list_empty(&block_group->dirty_list)) {
1092e3e0520bSJosef Bacik 		list_del_init(&block_group->dirty_list);
1093e3e0520bSJosef Bacik 		remove_rsv = true;
1094e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1095e3e0520bSJosef Bacik 	}
1096e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1097e3e0520bSJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
1098e3e0520bSJosef Bacik 
109936b216c8SBoris Burkov 	ret = btrfs_remove_free_space_inode(trans, inode, block_group);
1100e3e0520bSJosef Bacik 	if (ret)
11019fecd132SFilipe Manana 		goto out;
1102e3e0520bSJosef Bacik 
110316b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
110408dddb29SFilipe Manana 	rb_erase_cached(&block_group->cache_node,
1105e3e0520bSJosef Bacik 			&fs_info->block_group_cache_tree);
1106e3e0520bSJosef Bacik 	RB_CLEAR_NODE(&block_group->cache_node);
1107e3e0520bSJosef Bacik 
11089fecd132SFilipe Manana 	/* Once for the block groups rbtree */
11099fecd132SFilipe Manana 	btrfs_put_block_group(block_group);
11109fecd132SFilipe Manana 
111116b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
1112e3e0520bSJosef Bacik 
1113e3e0520bSJosef Bacik 	down_write(&block_group->space_info->groups_sem);
1114e3e0520bSJosef Bacik 	/*
1115e3e0520bSJosef Bacik 	 * we must use list_del_init so people can check to see if they
1116e3e0520bSJosef Bacik 	 * are still on the list after taking the semaphore
1117e3e0520bSJosef Bacik 	 */
1118e3e0520bSJosef Bacik 	list_del_init(&block_group->list);
1119e3e0520bSJosef Bacik 	if (list_empty(&block_group->space_info->block_groups[index])) {
1120e3e0520bSJosef Bacik 		kobj = block_group->space_info->block_group_kobjs[index];
1121e3e0520bSJosef Bacik 		block_group->space_info->block_group_kobjs[index] = NULL;
1122e3e0520bSJosef Bacik 		clear_avail_alloc_bits(fs_info, block_group->flags);
1123e3e0520bSJosef Bacik 	}
1124e3e0520bSJosef Bacik 	up_write(&block_group->space_info->groups_sem);
1125e3e0520bSJosef Bacik 	clear_incompat_bg_bits(fs_info, block_group->flags);
1126e3e0520bSJosef Bacik 	if (kobj) {
1127e3e0520bSJosef Bacik 		kobject_del(kobj);
1128e3e0520bSJosef Bacik 		kobject_put(kobj);
1129e3e0520bSJosef Bacik 	}
1130e3e0520bSJosef Bacik 
1131e3e0520bSJosef Bacik 	if (block_group->cached == BTRFS_CACHE_STARTED)
1132e3e0520bSJosef Bacik 		btrfs_wait_block_group_cache_done(block_group);
11337b9c293bSJosef Bacik 
113416b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
11357b9c293bSJosef Bacik 	caching_ctl = btrfs_get_caching_control(block_group);
1136e3e0520bSJosef Bacik 	if (!caching_ctl) {
1137e3e0520bSJosef Bacik 		struct btrfs_caching_control *ctl;
1138e3e0520bSJosef Bacik 
11397b9c293bSJosef Bacik 		list_for_each_entry(ctl, &fs_info->caching_block_groups, list) {
1140e3e0520bSJosef Bacik 			if (ctl->block_group == block_group) {
1141e3e0520bSJosef Bacik 				caching_ctl = ctl;
1142e3e0520bSJosef Bacik 				refcount_inc(&caching_ctl->count);
1143e3e0520bSJosef Bacik 				break;
1144e3e0520bSJosef Bacik 			}
1145e3e0520bSJosef Bacik 		}
11467b9c293bSJosef Bacik 	}
1147e3e0520bSJosef Bacik 	if (caching_ctl)
1148e3e0520bSJosef Bacik 		list_del_init(&caching_ctl->list);
114916b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
11507b9c293bSJosef Bacik 
1151e3e0520bSJosef Bacik 	if (caching_ctl) {
1152e3e0520bSJosef Bacik 		/* Once for the caching bgs list and once for us. */
1153e3e0520bSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
1154e3e0520bSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
1155e3e0520bSJosef Bacik 	}
1156e3e0520bSJosef Bacik 
1157e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
1158e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->dirty_list));
1159e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->io_list));
1160e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1161e3e0520bSJosef Bacik 
1162e3e0520bSJosef Bacik 	btrfs_remove_free_space_cache(block_group);
1163e3e0520bSJosef Bacik 
1164e3e0520bSJosef Bacik 	spin_lock(&block_group->space_info->lock);
1165e3e0520bSJosef Bacik 	list_del_init(&block_group->ro_list);
1166e3e0520bSJosef Bacik 
1167e3e0520bSJosef Bacik 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1168e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->total_bytes
1169b3470b5dSDavid Sterba 			< block_group->length);
1170e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->bytes_readonly
1171169e0da9SNaohiro Aota 			< block_group->length - block_group->zone_unusable);
1172169e0da9SNaohiro Aota 		WARN_ON(block_group->space_info->bytes_zone_unusable
1173169e0da9SNaohiro Aota 			< block_group->zone_unusable);
1174e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->disk_total
1175b3470b5dSDavid Sterba 			< block_group->length * factor);
1176e3e0520bSJosef Bacik 	}
1177b3470b5dSDavid Sterba 	block_group->space_info->total_bytes -= block_group->length;
1178169e0da9SNaohiro Aota 	block_group->space_info->bytes_readonly -=
1179169e0da9SNaohiro Aota 		(block_group->length - block_group->zone_unusable);
1180169e0da9SNaohiro Aota 	block_group->space_info->bytes_zone_unusable -=
1181169e0da9SNaohiro Aota 		block_group->zone_unusable;
1182b3470b5dSDavid Sterba 	block_group->space_info->disk_total -= block_group->length * factor;
1183e3e0520bSJosef Bacik 
1184e3e0520bSJosef Bacik 	spin_unlock(&block_group->space_info->lock);
1185e3e0520bSJosef Bacik 
1186ffcb9d44SFilipe Manana 	/*
1187ffcb9d44SFilipe Manana 	 * Remove the free space for the block group from the free space tree
1188ffcb9d44SFilipe Manana 	 * and the block group's item from the extent tree before marking the
1189ffcb9d44SFilipe Manana 	 * block group as removed. This is to prevent races with tasks that
1190ffcb9d44SFilipe Manana 	 * freeze and unfreeze a block group, this task and another task
1191ffcb9d44SFilipe Manana 	 * allocating a new block group - the unfreeze task ends up removing
1192ffcb9d44SFilipe Manana 	 * the block group's extent map before the task calling this function
1193ffcb9d44SFilipe Manana 	 * deletes the block group item from the extent tree, allowing for
1194ffcb9d44SFilipe Manana 	 * another task to attempt to create another block group with the same
1195ffcb9d44SFilipe Manana 	 * item key (and failing with -EEXIST and a transaction abort).
1196ffcb9d44SFilipe Manana 	 */
1197ffcb9d44SFilipe Manana 	ret = remove_block_group_free_space(trans, block_group);
1198ffcb9d44SFilipe Manana 	if (ret)
1199ffcb9d44SFilipe Manana 		goto out;
1200ffcb9d44SFilipe Manana 
1201ffcb9d44SFilipe Manana 	ret = remove_block_group_item(trans, path, block_group);
1202ffcb9d44SFilipe Manana 	if (ret < 0)
1203ffcb9d44SFilipe Manana 		goto out;
1204ffcb9d44SFilipe Manana 
1205e3e0520bSJosef Bacik 	spin_lock(&block_group->lock);
12063349b57fSJosef Bacik 	set_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags);
12073349b57fSJosef Bacik 
1208e3e0520bSJosef Bacik 	/*
12096b7304afSFilipe Manana 	 * At this point trimming or scrub can't start on this block group,
12106b7304afSFilipe Manana 	 * because we removed the block group from the rbtree
12116b7304afSFilipe Manana 	 * fs_info->block_group_cache_tree so no one can't find it anymore and
12126b7304afSFilipe Manana 	 * even if someone already got this block group before we removed it
12136b7304afSFilipe Manana 	 * from the rbtree, they have already incremented block_group->frozen -
12146b7304afSFilipe Manana 	 * if they didn't, for the trimming case they won't find any free space
12156b7304afSFilipe Manana 	 * entries because we already removed them all when we called
12166b7304afSFilipe Manana 	 * btrfs_remove_free_space_cache().
1217e3e0520bSJosef Bacik 	 *
1218e3e0520bSJosef Bacik 	 * And we must not remove the extent map from the fs_info->mapping_tree
1219e3e0520bSJosef Bacik 	 * to prevent the same logical address range and physical device space
12206b7304afSFilipe Manana 	 * ranges from being reused for a new block group. This is needed to
12216b7304afSFilipe Manana 	 * avoid races with trimming and scrub.
12226b7304afSFilipe Manana 	 *
12236b7304afSFilipe Manana 	 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1224e3e0520bSJosef Bacik 	 * completely transactionless, so while it is trimming a range the
1225e3e0520bSJosef Bacik 	 * currently running transaction might finish and a new one start,
1226e3e0520bSJosef Bacik 	 * allowing for new block groups to be created that can reuse the same
1227e3e0520bSJosef Bacik 	 * physical device locations unless we take this special care.
1228e3e0520bSJosef Bacik 	 *
1229e3e0520bSJosef Bacik 	 * There may also be an implicit trim operation if the file system
1230e3e0520bSJosef Bacik 	 * is mounted with -odiscard. The same protections must remain
1231e3e0520bSJosef Bacik 	 * in place until the extents have been discarded completely when
1232e3e0520bSJosef Bacik 	 * the transaction commit has completed.
1233e3e0520bSJosef Bacik 	 */
12346b7304afSFilipe Manana 	remove_em = (atomic_read(&block_group->frozen) == 0);
1235e3e0520bSJosef Bacik 	spin_unlock(&block_group->lock);
1236e3e0520bSJosef Bacik 
1237e3e0520bSJosef Bacik 	if (remove_em) {
1238e3e0520bSJosef Bacik 		struct extent_map_tree *em_tree;
1239e3e0520bSJosef Bacik 
1240e3e0520bSJosef Bacik 		em_tree = &fs_info->mapping_tree;
1241e3e0520bSJosef Bacik 		write_lock(&em_tree->lock);
1242e3e0520bSJosef Bacik 		remove_extent_mapping(em_tree, em);
1243e3e0520bSJosef Bacik 		write_unlock(&em_tree->lock);
1244e3e0520bSJosef Bacik 		/* once for the tree */
1245e3e0520bSJosef Bacik 		free_extent_map(em);
1246e3e0520bSJosef Bacik 	}
1247f6033c5eSXiyu Yang 
12489fecd132SFilipe Manana out:
1249f6033c5eSXiyu Yang 	/* Once for the lookup reference */
1250f6033c5eSXiyu Yang 	btrfs_put_block_group(block_group);
1251e3e0520bSJosef Bacik 	if (remove_rsv)
1252e3e0520bSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
1253e3e0520bSJosef Bacik 	btrfs_free_path(path);
1254e3e0520bSJosef Bacik 	return ret;
1255e3e0520bSJosef Bacik }
1256e3e0520bSJosef Bacik 
1257e3e0520bSJosef Bacik struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1258e3e0520bSJosef Bacik 		struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1259e3e0520bSJosef Bacik {
1260dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
1261e3e0520bSJosef Bacik 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1262e3e0520bSJosef Bacik 	struct extent_map *em;
1263e3e0520bSJosef Bacik 	struct map_lookup *map;
1264e3e0520bSJosef Bacik 	unsigned int num_items;
1265e3e0520bSJosef Bacik 
1266e3e0520bSJosef Bacik 	read_lock(&em_tree->lock);
1267e3e0520bSJosef Bacik 	em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1268e3e0520bSJosef Bacik 	read_unlock(&em_tree->lock);
1269e3e0520bSJosef Bacik 	ASSERT(em && em->start == chunk_offset);
1270e3e0520bSJosef Bacik 
1271e3e0520bSJosef Bacik 	/*
1272e3e0520bSJosef Bacik 	 * We need to reserve 3 + N units from the metadata space info in order
1273e3e0520bSJosef Bacik 	 * to remove a block group (done at btrfs_remove_chunk() and at
1274e3e0520bSJosef Bacik 	 * btrfs_remove_block_group()), which are used for:
1275e3e0520bSJosef Bacik 	 *
1276e3e0520bSJosef Bacik 	 * 1 unit for adding the free space inode's orphan (located in the tree
1277e3e0520bSJosef Bacik 	 * of tree roots).
1278e3e0520bSJosef Bacik 	 * 1 unit for deleting the block group item (located in the extent
1279e3e0520bSJosef Bacik 	 * tree).
1280e3e0520bSJosef Bacik 	 * 1 unit for deleting the free space item (located in tree of tree
1281e3e0520bSJosef Bacik 	 * roots).
1282e3e0520bSJosef Bacik 	 * N units for deleting N device extent items corresponding to each
1283e3e0520bSJosef Bacik 	 * stripe (located in the device tree).
1284e3e0520bSJosef Bacik 	 *
1285e3e0520bSJosef Bacik 	 * In order to remove a block group we also need to reserve units in the
1286e3e0520bSJosef Bacik 	 * system space info in order to update the chunk tree (update one or
1287e3e0520bSJosef Bacik 	 * more device items and remove one chunk item), but this is done at
1288e3e0520bSJosef Bacik 	 * btrfs_remove_chunk() through a call to check_system_chunk().
1289e3e0520bSJosef Bacik 	 */
1290e3e0520bSJosef Bacik 	map = em->map_lookup;
1291e3e0520bSJosef Bacik 	num_items = 3 + map->num_stripes;
1292e3e0520bSJosef Bacik 	free_extent_map(em);
1293e3e0520bSJosef Bacik 
1294dfe8aec4SJosef Bacik 	return btrfs_start_transaction_fallback_global_rsv(root, num_items);
1295e3e0520bSJosef Bacik }
1296e3e0520bSJosef Bacik 
1297e3e0520bSJosef Bacik /*
129826ce2095SJosef Bacik  * Mark block group @cache read-only, so later write won't happen to block
129926ce2095SJosef Bacik  * group @cache.
130026ce2095SJosef Bacik  *
130126ce2095SJosef Bacik  * If @force is not set, this function will only mark the block group readonly
130226ce2095SJosef Bacik  * if we have enough free space (1M) in other metadata/system block groups.
130326ce2095SJosef Bacik  * If @force is not set, this function will mark the block group readonly
130426ce2095SJosef Bacik  * without checking free space.
130526ce2095SJosef Bacik  *
130626ce2095SJosef Bacik  * NOTE: This function doesn't care if other block groups can contain all the
130726ce2095SJosef Bacik  * data in this block group. That check should be done by relocation routine,
130826ce2095SJosef Bacik  * not this function.
130926ce2095SJosef Bacik  */
131032da5386SDavid Sterba static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
131126ce2095SJosef Bacik {
131226ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
131326ce2095SJosef Bacik 	u64 num_bytes;
131426ce2095SJosef Bacik 	int ret = -ENOSPC;
131526ce2095SJosef Bacik 
131626ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
131726ce2095SJosef Bacik 	spin_lock(&cache->lock);
131826ce2095SJosef Bacik 
1319195a49eaSFilipe Manana 	if (cache->swap_extents) {
1320195a49eaSFilipe Manana 		ret = -ETXTBSY;
1321195a49eaSFilipe Manana 		goto out;
1322195a49eaSFilipe Manana 	}
1323195a49eaSFilipe Manana 
132426ce2095SJosef Bacik 	if (cache->ro) {
132526ce2095SJosef Bacik 		cache->ro++;
132626ce2095SJosef Bacik 		ret = 0;
132726ce2095SJosef Bacik 		goto out;
132826ce2095SJosef Bacik 	}
132926ce2095SJosef Bacik 
1330b3470b5dSDavid Sterba 	num_bytes = cache->length - cache->reserved - cache->pinned -
1331169e0da9SNaohiro Aota 		    cache->bytes_super - cache->zone_unusable - cache->used;
133226ce2095SJosef Bacik 
133326ce2095SJosef Bacik 	/*
1334a30a3d20SJosef Bacik 	 * Data never overcommits, even in mixed mode, so do just the straight
1335a30a3d20SJosef Bacik 	 * check of left over space in how much we have allocated.
1336a30a3d20SJosef Bacik 	 */
1337a30a3d20SJosef Bacik 	if (force) {
1338a30a3d20SJosef Bacik 		ret = 0;
1339a30a3d20SJosef Bacik 	} else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1340a30a3d20SJosef Bacik 		u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1341a30a3d20SJosef Bacik 
1342a30a3d20SJosef Bacik 		/*
134326ce2095SJosef Bacik 		 * Here we make sure if we mark this bg RO, we still have enough
1344f8935566SJosef Bacik 		 * free space as buffer.
134526ce2095SJosef Bacik 		 */
1346a30a3d20SJosef Bacik 		if (sinfo_used + num_bytes <= sinfo->total_bytes)
1347a30a3d20SJosef Bacik 			ret = 0;
1348a30a3d20SJosef Bacik 	} else {
1349a30a3d20SJosef Bacik 		/*
1350a30a3d20SJosef Bacik 		 * We overcommit metadata, so we need to do the
1351a30a3d20SJosef Bacik 		 * btrfs_can_overcommit check here, and we need to pass in
1352a30a3d20SJosef Bacik 		 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1353a30a3d20SJosef Bacik 		 * leeway to allow us to mark this block group as read only.
1354a30a3d20SJosef Bacik 		 */
1355a30a3d20SJosef Bacik 		if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1356a30a3d20SJosef Bacik 					 BTRFS_RESERVE_NO_FLUSH))
1357a30a3d20SJosef Bacik 			ret = 0;
1358a30a3d20SJosef Bacik 	}
1359a30a3d20SJosef Bacik 
1360a30a3d20SJosef Bacik 	if (!ret) {
136126ce2095SJosef Bacik 		sinfo->bytes_readonly += num_bytes;
1362169e0da9SNaohiro Aota 		if (btrfs_is_zoned(cache->fs_info)) {
1363169e0da9SNaohiro Aota 			/* Migrate zone_unusable bytes to readonly */
1364169e0da9SNaohiro Aota 			sinfo->bytes_readonly += cache->zone_unusable;
1365169e0da9SNaohiro Aota 			sinfo->bytes_zone_unusable -= cache->zone_unusable;
1366169e0da9SNaohiro Aota 			cache->zone_unusable = 0;
1367169e0da9SNaohiro Aota 		}
136826ce2095SJosef Bacik 		cache->ro++;
136926ce2095SJosef Bacik 		list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
137026ce2095SJosef Bacik 	}
137126ce2095SJosef Bacik out:
137226ce2095SJosef Bacik 	spin_unlock(&cache->lock);
137326ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
137426ce2095SJosef Bacik 	if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
137526ce2095SJosef Bacik 		btrfs_info(cache->fs_info,
1376b3470b5dSDavid Sterba 			"unable to make block group %llu ro", cache->start);
137726ce2095SJosef Bacik 		btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
137826ce2095SJosef Bacik 	}
137926ce2095SJosef Bacik 	return ret;
138026ce2095SJosef Bacik }
138126ce2095SJosef Bacik 
1382fe119a6eSNikolay Borisov static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1383fe119a6eSNikolay Borisov 				 struct btrfs_block_group *bg)
138445bb5d6aSNikolay Borisov {
138545bb5d6aSNikolay Borisov 	struct btrfs_fs_info *fs_info = bg->fs_info;
1386fe119a6eSNikolay Borisov 	struct btrfs_transaction *prev_trans = NULL;
138745bb5d6aSNikolay Borisov 	const u64 start = bg->start;
138845bb5d6aSNikolay Borisov 	const u64 end = start + bg->length - 1;
138945bb5d6aSNikolay Borisov 	int ret;
139045bb5d6aSNikolay Borisov 
1391fe119a6eSNikolay Borisov 	spin_lock(&fs_info->trans_lock);
1392fe119a6eSNikolay Borisov 	if (trans->transaction->list.prev != &fs_info->trans_list) {
1393fe119a6eSNikolay Borisov 		prev_trans = list_last_entry(&trans->transaction->list,
1394fe119a6eSNikolay Borisov 					     struct btrfs_transaction, list);
1395fe119a6eSNikolay Borisov 		refcount_inc(&prev_trans->use_count);
1396fe119a6eSNikolay Borisov 	}
1397fe119a6eSNikolay Borisov 	spin_unlock(&fs_info->trans_lock);
1398fe119a6eSNikolay Borisov 
139945bb5d6aSNikolay Borisov 	/*
140045bb5d6aSNikolay Borisov 	 * Hold the unused_bg_unpin_mutex lock to avoid racing with
140145bb5d6aSNikolay Borisov 	 * btrfs_finish_extent_commit(). If we are at transaction N, another
140245bb5d6aSNikolay Borisov 	 * task might be running finish_extent_commit() for the previous
140345bb5d6aSNikolay Borisov 	 * transaction N - 1, and have seen a range belonging to the block
1404fe119a6eSNikolay Borisov 	 * group in pinned_extents before we were able to clear the whole block
1405fe119a6eSNikolay Borisov 	 * group range from pinned_extents. This means that task can lookup for
1406fe119a6eSNikolay Borisov 	 * the block group after we unpinned it from pinned_extents and removed
1407fe119a6eSNikolay Borisov 	 * it, leading to a BUG_ON() at unpin_extent_range().
140845bb5d6aSNikolay Borisov 	 */
140945bb5d6aSNikolay Borisov 	mutex_lock(&fs_info->unused_bg_unpin_mutex);
1410fe119a6eSNikolay Borisov 	if (prev_trans) {
1411fe119a6eSNikolay Borisov 		ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
141245bb5d6aSNikolay Borisov 					EXTENT_DIRTY);
141345bb5d6aSNikolay Borisov 		if (ret)
1414534cf531SFilipe Manana 			goto out;
1415fe119a6eSNikolay Borisov 	}
141645bb5d6aSNikolay Borisov 
1417fe119a6eSNikolay Borisov 	ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
141845bb5d6aSNikolay Borisov 				EXTENT_DIRTY);
1419534cf531SFilipe Manana out:
142045bb5d6aSNikolay Borisov 	mutex_unlock(&fs_info->unused_bg_unpin_mutex);
14215150bf19SFilipe Manana 	if (prev_trans)
14225150bf19SFilipe Manana 		btrfs_put_transaction(prev_trans);
142345bb5d6aSNikolay Borisov 
1424534cf531SFilipe Manana 	return ret == 0;
142545bb5d6aSNikolay Borisov }
142645bb5d6aSNikolay Borisov 
142726ce2095SJosef Bacik /*
1428e3e0520bSJosef Bacik  * Process the unused_bgs list and remove any that don't have any allocated
1429e3e0520bSJosef Bacik  * space inside of them.
1430e3e0520bSJosef Bacik  */
1431e3e0520bSJosef Bacik void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1432e3e0520bSJosef Bacik {
143332da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1434e3e0520bSJosef Bacik 	struct btrfs_space_info *space_info;
1435e3e0520bSJosef Bacik 	struct btrfs_trans_handle *trans;
14366e80d4f8SDennis Zhou 	const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1437e3e0520bSJosef Bacik 	int ret = 0;
1438e3e0520bSJosef Bacik 
1439e3e0520bSJosef Bacik 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1440e3e0520bSJosef Bacik 		return;
1441e3e0520bSJosef Bacik 
14422f12741fSJosef Bacik 	if (btrfs_fs_closing(fs_info))
14432f12741fSJosef Bacik 		return;
14442f12741fSJosef Bacik 
1445ddfd08cbSJosef Bacik 	/*
1446ddfd08cbSJosef Bacik 	 * Long running balances can keep us blocked here for eternity, so
1447ddfd08cbSJosef Bacik 	 * simply skip deletion if we're unable to get the mutex.
1448ddfd08cbSJosef Bacik 	 */
1449f3372065SJohannes Thumshirn 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
1450ddfd08cbSJosef Bacik 		return;
1451ddfd08cbSJosef Bacik 
1452e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1453e3e0520bSJosef Bacik 	while (!list_empty(&fs_info->unused_bgs)) {
1454e3e0520bSJosef Bacik 		int trimming;
1455e3e0520bSJosef Bacik 
1456e3e0520bSJosef Bacik 		block_group = list_first_entry(&fs_info->unused_bgs,
145732da5386SDavid Sterba 					       struct btrfs_block_group,
1458e3e0520bSJosef Bacik 					       bg_list);
1459e3e0520bSJosef Bacik 		list_del_init(&block_group->bg_list);
1460e3e0520bSJosef Bacik 
1461e3e0520bSJosef Bacik 		space_info = block_group->space_info;
1462e3e0520bSJosef Bacik 
1463e3e0520bSJosef Bacik 		if (ret || btrfs_mixed_space_info(space_info)) {
1464e3e0520bSJosef Bacik 			btrfs_put_block_group(block_group);
1465e3e0520bSJosef Bacik 			continue;
1466e3e0520bSJosef Bacik 		}
1467e3e0520bSJosef Bacik 		spin_unlock(&fs_info->unused_bgs_lock);
1468e3e0520bSJosef Bacik 
1469b0643e59SDennis Zhou 		btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1470b0643e59SDennis Zhou 
1471e3e0520bSJosef Bacik 		/* Don't want to race with allocators so take the groups_sem */
1472e3e0520bSJosef Bacik 		down_write(&space_info->groups_sem);
14736e80d4f8SDennis Zhou 
14746e80d4f8SDennis Zhou 		/*
14756e80d4f8SDennis Zhou 		 * Async discard moves the final block group discard to be prior
14766e80d4f8SDennis Zhou 		 * to the unused_bgs code path.  Therefore, if it's not fully
14776e80d4f8SDennis Zhou 		 * trimmed, punt it back to the async discard lists.
14786e80d4f8SDennis Zhou 		 */
14796e80d4f8SDennis Zhou 		if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
14806e80d4f8SDennis Zhou 		    !btrfs_is_free_space_trimmed(block_group)) {
14816e80d4f8SDennis Zhou 			trace_btrfs_skip_unused_block_group(block_group);
14826e80d4f8SDennis Zhou 			up_write(&space_info->groups_sem);
14836e80d4f8SDennis Zhou 			/* Requeue if we failed because of async discard */
14846e80d4f8SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
14856e80d4f8SDennis Zhou 						 block_group);
14866e80d4f8SDennis Zhou 			goto next;
14876e80d4f8SDennis Zhou 		}
14886e80d4f8SDennis Zhou 
1489e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1490e3e0520bSJosef Bacik 		if (block_group->reserved || block_group->pinned ||
1491bf38be65SDavid Sterba 		    block_group->used || block_group->ro ||
1492e3e0520bSJosef Bacik 		    list_is_singular(&block_group->list)) {
1493e3e0520bSJosef Bacik 			/*
1494e3e0520bSJosef Bacik 			 * We want to bail if we made new allocations or have
1495e3e0520bSJosef Bacik 			 * outstanding allocations in this block group.  We do
1496e3e0520bSJosef Bacik 			 * the ro check in case balance is currently acting on
1497e3e0520bSJosef Bacik 			 * this block group.
1498e3e0520bSJosef Bacik 			 */
1499e3e0520bSJosef Bacik 			trace_btrfs_skip_unused_block_group(block_group);
1500e3e0520bSJosef Bacik 			spin_unlock(&block_group->lock);
1501e3e0520bSJosef Bacik 			up_write(&space_info->groups_sem);
1502e3e0520bSJosef Bacik 			goto next;
1503e3e0520bSJosef Bacik 		}
1504e3e0520bSJosef Bacik 		spin_unlock(&block_group->lock);
1505e3e0520bSJosef Bacik 
1506e3e0520bSJosef Bacik 		/* We don't want to force the issue, only flip if it's ok. */
1507e11c0406SJosef Bacik 		ret = inc_block_group_ro(block_group, 0);
1508e3e0520bSJosef Bacik 		up_write(&space_info->groups_sem);
1509e3e0520bSJosef Bacik 		if (ret < 0) {
1510e3e0520bSJosef Bacik 			ret = 0;
1511e3e0520bSJosef Bacik 			goto next;
1512e3e0520bSJosef Bacik 		}
1513e3e0520bSJosef Bacik 
151474e91b12SNaohiro Aota 		ret = btrfs_zone_finish(block_group);
151574e91b12SNaohiro Aota 		if (ret < 0) {
151674e91b12SNaohiro Aota 			btrfs_dec_block_group_ro(block_group);
151774e91b12SNaohiro Aota 			if (ret == -EAGAIN)
151874e91b12SNaohiro Aota 				ret = 0;
151974e91b12SNaohiro Aota 			goto next;
152074e91b12SNaohiro Aota 		}
152174e91b12SNaohiro Aota 
1522e3e0520bSJosef Bacik 		/*
1523e3e0520bSJosef Bacik 		 * Want to do this before we do anything else so we can recover
1524e3e0520bSJosef Bacik 		 * properly if we fail to join the transaction.
1525e3e0520bSJosef Bacik 		 */
1526e3e0520bSJosef Bacik 		trans = btrfs_start_trans_remove_block_group(fs_info,
1527b3470b5dSDavid Sterba 						     block_group->start);
1528e3e0520bSJosef Bacik 		if (IS_ERR(trans)) {
1529e3e0520bSJosef Bacik 			btrfs_dec_block_group_ro(block_group);
1530e3e0520bSJosef Bacik 			ret = PTR_ERR(trans);
1531e3e0520bSJosef Bacik 			goto next;
1532e3e0520bSJosef Bacik 		}
1533e3e0520bSJosef Bacik 
1534e3e0520bSJosef Bacik 		/*
1535e3e0520bSJosef Bacik 		 * We could have pending pinned extents for this block group,
1536e3e0520bSJosef Bacik 		 * just delete them, we don't care about them anymore.
1537e3e0520bSJosef Bacik 		 */
1538534cf531SFilipe Manana 		if (!clean_pinned_extents(trans, block_group)) {
1539534cf531SFilipe Manana 			btrfs_dec_block_group_ro(block_group);
1540e3e0520bSJosef Bacik 			goto end_trans;
1541534cf531SFilipe Manana 		}
1542e3e0520bSJosef Bacik 
1543b0643e59SDennis Zhou 		/*
1544b0643e59SDennis Zhou 		 * At this point, the block_group is read only and should fail
1545b0643e59SDennis Zhou 		 * new allocations.  However, btrfs_finish_extent_commit() can
1546b0643e59SDennis Zhou 		 * cause this block_group to be placed back on the discard
1547b0643e59SDennis Zhou 		 * lists because now the block_group isn't fully discarded.
1548b0643e59SDennis Zhou 		 * Bail here and try again later after discarding everything.
1549b0643e59SDennis Zhou 		 */
1550b0643e59SDennis Zhou 		spin_lock(&fs_info->discard_ctl.lock);
1551b0643e59SDennis Zhou 		if (!list_empty(&block_group->discard_list)) {
1552b0643e59SDennis Zhou 			spin_unlock(&fs_info->discard_ctl.lock);
1553b0643e59SDennis Zhou 			btrfs_dec_block_group_ro(block_group);
1554b0643e59SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
1555b0643e59SDennis Zhou 						 block_group);
1556b0643e59SDennis Zhou 			goto end_trans;
1557b0643e59SDennis Zhou 		}
1558b0643e59SDennis Zhou 		spin_unlock(&fs_info->discard_ctl.lock);
1559b0643e59SDennis Zhou 
1560e3e0520bSJosef Bacik 		/* Reset pinned so btrfs_put_block_group doesn't complain */
1561e3e0520bSJosef Bacik 		spin_lock(&space_info->lock);
1562e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1563e3e0520bSJosef Bacik 
1564e3e0520bSJosef Bacik 		btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1565e3e0520bSJosef Bacik 						     -block_group->pinned);
1566e3e0520bSJosef Bacik 		space_info->bytes_readonly += block_group->pinned;
1567e3e0520bSJosef Bacik 		block_group->pinned = 0;
1568e3e0520bSJosef Bacik 
1569e3e0520bSJosef Bacik 		spin_unlock(&block_group->lock);
1570e3e0520bSJosef Bacik 		spin_unlock(&space_info->lock);
1571e3e0520bSJosef Bacik 
15726e80d4f8SDennis Zhou 		/*
15736e80d4f8SDennis Zhou 		 * The normal path here is an unused block group is passed here,
15746e80d4f8SDennis Zhou 		 * then trimming is handled in the transaction commit path.
15756e80d4f8SDennis Zhou 		 * Async discard interposes before this to do the trimming
15766e80d4f8SDennis Zhou 		 * before coming down the unused block group path as trimming
15776e80d4f8SDennis Zhou 		 * will no longer be done later in the transaction commit path.
15786e80d4f8SDennis Zhou 		 */
15796e80d4f8SDennis Zhou 		if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
15806e80d4f8SDennis Zhou 			goto flip_async;
15816e80d4f8SDennis Zhou 
1582dcba6e48SNaohiro Aota 		/*
1583dcba6e48SNaohiro Aota 		 * DISCARD can flip during remount. On zoned filesystems, we
1584dcba6e48SNaohiro Aota 		 * need to reset sequential-required zones.
1585dcba6e48SNaohiro Aota 		 */
1586dcba6e48SNaohiro Aota 		trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) ||
1587dcba6e48SNaohiro Aota 				btrfs_is_zoned(fs_info);
1588e3e0520bSJosef Bacik 
1589e3e0520bSJosef Bacik 		/* Implicit trim during transaction commit. */
1590e3e0520bSJosef Bacik 		if (trimming)
15916b7304afSFilipe Manana 			btrfs_freeze_block_group(block_group);
1592e3e0520bSJosef Bacik 
1593e3e0520bSJosef Bacik 		/*
1594e3e0520bSJosef Bacik 		 * Btrfs_remove_chunk will abort the transaction if things go
1595e3e0520bSJosef Bacik 		 * horribly wrong.
1596e3e0520bSJosef Bacik 		 */
1597b3470b5dSDavid Sterba 		ret = btrfs_remove_chunk(trans, block_group->start);
1598e3e0520bSJosef Bacik 
1599e3e0520bSJosef Bacik 		if (ret) {
1600e3e0520bSJosef Bacik 			if (trimming)
16016b7304afSFilipe Manana 				btrfs_unfreeze_block_group(block_group);
1602e3e0520bSJosef Bacik 			goto end_trans;
1603e3e0520bSJosef Bacik 		}
1604e3e0520bSJosef Bacik 
1605e3e0520bSJosef Bacik 		/*
1606e3e0520bSJosef Bacik 		 * If we're not mounted with -odiscard, we can just forget
1607e3e0520bSJosef Bacik 		 * about this block group. Otherwise we'll need to wait
1608e3e0520bSJosef Bacik 		 * until transaction commit to do the actual discard.
1609e3e0520bSJosef Bacik 		 */
1610e3e0520bSJosef Bacik 		if (trimming) {
1611e3e0520bSJosef Bacik 			spin_lock(&fs_info->unused_bgs_lock);
1612e3e0520bSJosef Bacik 			/*
1613e3e0520bSJosef Bacik 			 * A concurrent scrub might have added us to the list
1614e3e0520bSJosef Bacik 			 * fs_info->unused_bgs, so use a list_move operation
1615e3e0520bSJosef Bacik 			 * to add the block group to the deleted_bgs list.
1616e3e0520bSJosef Bacik 			 */
1617e3e0520bSJosef Bacik 			list_move(&block_group->bg_list,
1618e3e0520bSJosef Bacik 				  &trans->transaction->deleted_bgs);
1619e3e0520bSJosef Bacik 			spin_unlock(&fs_info->unused_bgs_lock);
1620e3e0520bSJosef Bacik 			btrfs_get_block_group(block_group);
1621e3e0520bSJosef Bacik 		}
1622e3e0520bSJosef Bacik end_trans:
1623e3e0520bSJosef Bacik 		btrfs_end_transaction(trans);
1624e3e0520bSJosef Bacik next:
1625e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1626e3e0520bSJosef Bacik 		spin_lock(&fs_info->unused_bgs_lock);
1627e3e0520bSJosef Bacik 	}
1628e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
1629f3372065SJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
16306e80d4f8SDennis Zhou 	return;
16316e80d4f8SDennis Zhou 
16326e80d4f8SDennis Zhou flip_async:
16336e80d4f8SDennis Zhou 	btrfs_end_transaction(trans);
1634f3372065SJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
16356e80d4f8SDennis Zhou 	btrfs_put_block_group(block_group);
16366e80d4f8SDennis Zhou 	btrfs_discard_punt_unused_bgs_list(fs_info);
1637e3e0520bSJosef Bacik }
1638e3e0520bSJosef Bacik 
163932da5386SDavid Sterba void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1640e3e0520bSJosef Bacik {
1641e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = bg->fs_info;
1642e3e0520bSJosef Bacik 
1643e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1644e3e0520bSJosef Bacik 	if (list_empty(&bg->bg_list)) {
1645e3e0520bSJosef Bacik 		btrfs_get_block_group(bg);
1646*0657b20cSFilipe Manana 		trace_btrfs_add_unused_block_group(bg);
1647e3e0520bSJosef Bacik 		list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1648*0657b20cSFilipe Manana 	} else if (!test_bit(BLOCK_GROUP_FLAG_NEW, &bg->runtime_flags)) {
1649a9f18971SNaohiro Aota 		/* Pull out the block group from the reclaim_bgs list. */
1650*0657b20cSFilipe Manana 		trace_btrfs_add_unused_block_group(bg);
1651a9f18971SNaohiro Aota 		list_move_tail(&bg->bg_list, &fs_info->unused_bgs);
1652e3e0520bSJosef Bacik 	}
1653e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
1654e3e0520bSJosef Bacik }
16554358d963SJosef Bacik 
16562ca0ec77SJohannes Thumshirn /*
16572ca0ec77SJohannes Thumshirn  * We want block groups with a low number of used bytes to be in the beginning
16582ca0ec77SJohannes Thumshirn  * of the list, so they will get reclaimed first.
16592ca0ec77SJohannes Thumshirn  */
16602ca0ec77SJohannes Thumshirn static int reclaim_bgs_cmp(void *unused, const struct list_head *a,
16612ca0ec77SJohannes Thumshirn 			   const struct list_head *b)
16622ca0ec77SJohannes Thumshirn {
16632ca0ec77SJohannes Thumshirn 	const struct btrfs_block_group *bg1, *bg2;
16642ca0ec77SJohannes Thumshirn 
16652ca0ec77SJohannes Thumshirn 	bg1 = list_entry(a, struct btrfs_block_group, bg_list);
16662ca0ec77SJohannes Thumshirn 	bg2 = list_entry(b, struct btrfs_block_group, bg_list);
16672ca0ec77SJohannes Thumshirn 
16682ca0ec77SJohannes Thumshirn 	return bg1->used > bg2->used;
16692ca0ec77SJohannes Thumshirn }
16702ca0ec77SJohannes Thumshirn 
16713687fcb0SJohannes Thumshirn static inline bool btrfs_should_reclaim(struct btrfs_fs_info *fs_info)
16723687fcb0SJohannes Thumshirn {
16733687fcb0SJohannes Thumshirn 	if (btrfs_is_zoned(fs_info))
16743687fcb0SJohannes Thumshirn 		return btrfs_zoned_should_reclaim(fs_info);
16753687fcb0SJohannes Thumshirn 	return true;
16763687fcb0SJohannes Thumshirn }
16773687fcb0SJohannes Thumshirn 
167881531225SBoris Burkov static bool should_reclaim_block_group(struct btrfs_block_group *bg, u64 bytes_freed)
167981531225SBoris Burkov {
168081531225SBoris Burkov 	const struct btrfs_space_info *space_info = bg->space_info;
168181531225SBoris Burkov 	const int reclaim_thresh = READ_ONCE(space_info->bg_reclaim_threshold);
168281531225SBoris Burkov 	const u64 new_val = bg->used;
168381531225SBoris Burkov 	const u64 old_val = new_val + bytes_freed;
168481531225SBoris Burkov 	u64 thresh;
168581531225SBoris Burkov 
168681531225SBoris Burkov 	if (reclaim_thresh == 0)
168781531225SBoris Burkov 		return false;
168881531225SBoris Burkov 
1689428c8e03SDavid Sterba 	thresh = mult_perc(bg->length, reclaim_thresh);
169081531225SBoris Burkov 
169181531225SBoris Burkov 	/*
169281531225SBoris Burkov 	 * If we were below the threshold before don't reclaim, we are likely a
169381531225SBoris Burkov 	 * brand new block group and we don't want to relocate new block groups.
169481531225SBoris Burkov 	 */
169581531225SBoris Burkov 	if (old_val < thresh)
169681531225SBoris Burkov 		return false;
169781531225SBoris Burkov 	if (new_val >= thresh)
169881531225SBoris Burkov 		return false;
169981531225SBoris Burkov 	return true;
170081531225SBoris Burkov }
170181531225SBoris Burkov 
170218bb8bbfSJohannes Thumshirn void btrfs_reclaim_bgs_work(struct work_struct *work)
170318bb8bbfSJohannes Thumshirn {
170418bb8bbfSJohannes Thumshirn 	struct btrfs_fs_info *fs_info =
170518bb8bbfSJohannes Thumshirn 		container_of(work, struct btrfs_fs_info, reclaim_bgs_work);
170618bb8bbfSJohannes Thumshirn 	struct btrfs_block_group *bg;
170718bb8bbfSJohannes Thumshirn 	struct btrfs_space_info *space_info;
170818bb8bbfSJohannes Thumshirn 
170918bb8bbfSJohannes Thumshirn 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
171018bb8bbfSJohannes Thumshirn 		return;
171118bb8bbfSJohannes Thumshirn 
17122f12741fSJosef Bacik 	if (btrfs_fs_closing(fs_info))
17132f12741fSJosef Bacik 		return;
17142f12741fSJosef Bacik 
17153687fcb0SJohannes Thumshirn 	if (!btrfs_should_reclaim(fs_info))
17163687fcb0SJohannes Thumshirn 		return;
17173687fcb0SJohannes Thumshirn 
1718ca5e4ea0SNaohiro Aota 	sb_start_write(fs_info->sb);
1719ca5e4ea0SNaohiro Aota 
1720ca5e4ea0SNaohiro Aota 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
1721ca5e4ea0SNaohiro Aota 		sb_end_write(fs_info->sb);
172218bb8bbfSJohannes Thumshirn 		return;
1723ca5e4ea0SNaohiro Aota 	}
172418bb8bbfSJohannes Thumshirn 
17259cc0b837SJohannes Thumshirn 	/*
17269cc0b837SJohannes Thumshirn 	 * Long running balances can keep us blocked here for eternity, so
17279cc0b837SJohannes Thumshirn 	 * simply skip reclaim if we're unable to get the mutex.
17289cc0b837SJohannes Thumshirn 	 */
17299cc0b837SJohannes Thumshirn 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) {
17309cc0b837SJohannes Thumshirn 		btrfs_exclop_finish(fs_info);
1731ca5e4ea0SNaohiro Aota 		sb_end_write(fs_info->sb);
17329cc0b837SJohannes Thumshirn 		return;
17339cc0b837SJohannes Thumshirn 	}
17349cc0b837SJohannes Thumshirn 
173518bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
17362ca0ec77SJohannes Thumshirn 	/*
17372ca0ec77SJohannes Thumshirn 	 * Sort happens under lock because we can't simply splice it and sort.
17382ca0ec77SJohannes Thumshirn 	 * The block groups might still be in use and reachable via bg_list,
17392ca0ec77SJohannes Thumshirn 	 * and their presence in the reclaim_bgs list must be preserved.
17402ca0ec77SJohannes Thumshirn 	 */
17412ca0ec77SJohannes Thumshirn 	list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp);
174218bb8bbfSJohannes Thumshirn 	while (!list_empty(&fs_info->reclaim_bgs)) {
17435f93e776SJohannes Thumshirn 		u64 zone_unusable;
17441cea5cf0SFilipe Manana 		int ret = 0;
17451cea5cf0SFilipe Manana 
174618bb8bbfSJohannes Thumshirn 		bg = list_first_entry(&fs_info->reclaim_bgs,
174718bb8bbfSJohannes Thumshirn 				      struct btrfs_block_group,
174818bb8bbfSJohannes Thumshirn 				      bg_list);
174918bb8bbfSJohannes Thumshirn 		list_del_init(&bg->bg_list);
175018bb8bbfSJohannes Thumshirn 
175118bb8bbfSJohannes Thumshirn 		space_info = bg->space_info;
175218bb8bbfSJohannes Thumshirn 		spin_unlock(&fs_info->unused_bgs_lock);
175318bb8bbfSJohannes Thumshirn 
175418bb8bbfSJohannes Thumshirn 		/* Don't race with allocators so take the groups_sem */
175518bb8bbfSJohannes Thumshirn 		down_write(&space_info->groups_sem);
175618bb8bbfSJohannes Thumshirn 
175718bb8bbfSJohannes Thumshirn 		spin_lock(&bg->lock);
175818bb8bbfSJohannes Thumshirn 		if (bg->reserved || bg->pinned || bg->ro) {
175918bb8bbfSJohannes Thumshirn 			/*
176018bb8bbfSJohannes Thumshirn 			 * We want to bail if we made new allocations or have
176118bb8bbfSJohannes Thumshirn 			 * outstanding allocations in this block group.  We do
176218bb8bbfSJohannes Thumshirn 			 * the ro check in case balance is currently acting on
176318bb8bbfSJohannes Thumshirn 			 * this block group.
176418bb8bbfSJohannes Thumshirn 			 */
176518bb8bbfSJohannes Thumshirn 			spin_unlock(&bg->lock);
176618bb8bbfSJohannes Thumshirn 			up_write(&space_info->groups_sem);
176718bb8bbfSJohannes Thumshirn 			goto next;
176818bb8bbfSJohannes Thumshirn 		}
1769cc4804bfSBoris Burkov 		if (bg->used == 0) {
1770cc4804bfSBoris Burkov 			/*
1771cc4804bfSBoris Burkov 			 * It is possible that we trigger relocation on a block
1772cc4804bfSBoris Burkov 			 * group as its extents are deleted and it first goes
1773cc4804bfSBoris Burkov 			 * below the threshold, then shortly after goes empty.
1774cc4804bfSBoris Burkov 			 *
1775cc4804bfSBoris Burkov 			 * In this case, relocating it does delete it, but has
1776cc4804bfSBoris Burkov 			 * some overhead in relocation specific metadata, looking
1777cc4804bfSBoris Burkov 			 * for the non-existent extents and running some extra
1778cc4804bfSBoris Burkov 			 * transactions, which we can avoid by using one of the
1779cc4804bfSBoris Burkov 			 * other mechanisms for dealing with empty block groups.
1780cc4804bfSBoris Burkov 			 */
1781cc4804bfSBoris Burkov 			if (!btrfs_test_opt(fs_info, DISCARD_ASYNC))
1782cc4804bfSBoris Burkov 				btrfs_mark_bg_unused(bg);
1783cc4804bfSBoris Burkov 			spin_unlock(&bg->lock);
1784cc4804bfSBoris Burkov 			up_write(&space_info->groups_sem);
1785cc4804bfSBoris Burkov 			goto next;
178681531225SBoris Burkov 
178781531225SBoris Burkov 		}
178881531225SBoris Burkov 		/*
178981531225SBoris Burkov 		 * The block group might no longer meet the reclaim condition by
179081531225SBoris Burkov 		 * the time we get around to reclaiming it, so to avoid
179181531225SBoris Burkov 		 * reclaiming overly full block_groups, skip reclaiming them.
179281531225SBoris Burkov 		 *
179381531225SBoris Burkov 		 * Since the decision making process also depends on the amount
179481531225SBoris Burkov 		 * being freed, pass in a fake giant value to skip that extra
179581531225SBoris Burkov 		 * check, which is more meaningful when adding to the list in
179681531225SBoris Burkov 		 * the first place.
179781531225SBoris Burkov 		 */
179881531225SBoris Burkov 		if (!should_reclaim_block_group(bg, bg->length)) {
179981531225SBoris Burkov 			spin_unlock(&bg->lock);
180081531225SBoris Burkov 			up_write(&space_info->groups_sem);
180181531225SBoris Burkov 			goto next;
1802cc4804bfSBoris Burkov 		}
180318bb8bbfSJohannes Thumshirn 		spin_unlock(&bg->lock);
180418bb8bbfSJohannes Thumshirn 
180593463ff7SNaohiro Aota 		/*
180693463ff7SNaohiro Aota 		 * Get out fast, in case we're read-only or unmounting the
180793463ff7SNaohiro Aota 		 * filesystem. It is OK to drop block groups from the list even
180893463ff7SNaohiro Aota 		 * for the read-only case. As we did sb_start_write(),
180993463ff7SNaohiro Aota 		 * "mount -o remount,ro" won't happen and read-only filesystem
181093463ff7SNaohiro Aota 		 * means it is forced read-only due to a fatal error. So, it
181193463ff7SNaohiro Aota 		 * never gets back to read-write to let us reclaim again.
181293463ff7SNaohiro Aota 		 */
181393463ff7SNaohiro Aota 		if (btrfs_need_cleaner_sleep(fs_info)) {
181418bb8bbfSJohannes Thumshirn 			up_write(&space_info->groups_sem);
181518bb8bbfSJohannes Thumshirn 			goto next;
181618bb8bbfSJohannes Thumshirn 		}
181718bb8bbfSJohannes Thumshirn 
18185f93e776SJohannes Thumshirn 		/*
18195f93e776SJohannes Thumshirn 		 * Cache the zone_unusable value before turning the block group
18205f93e776SJohannes Thumshirn 		 * to read only. As soon as the blog group is read only it's
18215f93e776SJohannes Thumshirn 		 * zone_unusable value gets moved to the block group's read-only
18225f93e776SJohannes Thumshirn 		 * bytes and isn't available for calculations anymore.
18235f93e776SJohannes Thumshirn 		 */
18245f93e776SJohannes Thumshirn 		zone_unusable = bg->zone_unusable;
182518bb8bbfSJohannes Thumshirn 		ret = inc_block_group_ro(bg, 0);
182618bb8bbfSJohannes Thumshirn 		up_write(&space_info->groups_sem);
182718bb8bbfSJohannes Thumshirn 		if (ret < 0)
182818bb8bbfSJohannes Thumshirn 			goto next;
182918bb8bbfSJohannes Thumshirn 
18305f93e776SJohannes Thumshirn 		btrfs_info(fs_info,
18315f93e776SJohannes Thumshirn 			"reclaiming chunk %llu with %llu%% used %llu%% unusable",
183295cd356cSJohannes Thumshirn 				bg->start,
183395cd356cSJohannes Thumshirn 				div64_u64(bg->used * 100, bg->length),
18345f93e776SJohannes Thumshirn 				div64_u64(zone_unusable * 100, bg->length));
183518bb8bbfSJohannes Thumshirn 		trace_btrfs_reclaim_block_group(bg);
183618bb8bbfSJohannes Thumshirn 		ret = btrfs_relocate_chunk(fs_info, bg->start);
183774944c87SJosef Bacik 		if (ret) {
183874944c87SJosef Bacik 			btrfs_dec_block_group_ro(bg);
183918bb8bbfSJohannes Thumshirn 			btrfs_err(fs_info, "error relocating chunk %llu",
184018bb8bbfSJohannes Thumshirn 				  bg->start);
184174944c87SJosef Bacik 		}
184218bb8bbfSJohannes Thumshirn 
184318bb8bbfSJohannes Thumshirn next:
18447e271809SNaohiro Aota 		if (ret)
18457e271809SNaohiro Aota 			btrfs_mark_bg_to_reclaim(bg);
18461cea5cf0SFilipe Manana 		btrfs_put_block_group(bg);
18473ed01616SNaohiro Aota 
18483ed01616SNaohiro Aota 		mutex_unlock(&fs_info->reclaim_bgs_lock);
18493ed01616SNaohiro Aota 		/*
18503ed01616SNaohiro Aota 		 * Reclaiming all the block groups in the list can take really
18513ed01616SNaohiro Aota 		 * long.  Prioritize cleaning up unused block groups.
18523ed01616SNaohiro Aota 		 */
18533ed01616SNaohiro Aota 		btrfs_delete_unused_bgs(fs_info);
18543ed01616SNaohiro Aota 		/*
18553ed01616SNaohiro Aota 		 * If we are interrupted by a balance, we can just bail out. The
18563ed01616SNaohiro Aota 		 * cleaner thread restart again if necessary.
18573ed01616SNaohiro Aota 		 */
18583ed01616SNaohiro Aota 		if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
18593ed01616SNaohiro Aota 			goto end;
1860d96b3424SFilipe Manana 		spin_lock(&fs_info->unused_bgs_lock);
186118bb8bbfSJohannes Thumshirn 	}
186218bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
186318bb8bbfSJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
18643ed01616SNaohiro Aota end:
186518bb8bbfSJohannes Thumshirn 	btrfs_exclop_finish(fs_info);
1866ca5e4ea0SNaohiro Aota 	sb_end_write(fs_info->sb);
186718bb8bbfSJohannes Thumshirn }
186818bb8bbfSJohannes Thumshirn 
186918bb8bbfSJohannes Thumshirn void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
187018bb8bbfSJohannes Thumshirn {
187118bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
187218bb8bbfSJohannes Thumshirn 	if (!list_empty(&fs_info->reclaim_bgs))
187318bb8bbfSJohannes Thumshirn 		queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
187418bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
187518bb8bbfSJohannes Thumshirn }
187618bb8bbfSJohannes Thumshirn 
187718bb8bbfSJohannes Thumshirn void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
187818bb8bbfSJohannes Thumshirn {
187918bb8bbfSJohannes Thumshirn 	struct btrfs_fs_info *fs_info = bg->fs_info;
188018bb8bbfSJohannes Thumshirn 
188118bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
188218bb8bbfSJohannes Thumshirn 	if (list_empty(&bg->bg_list)) {
188318bb8bbfSJohannes Thumshirn 		btrfs_get_block_group(bg);
188418bb8bbfSJohannes Thumshirn 		trace_btrfs_add_reclaim_block_group(bg);
188518bb8bbfSJohannes Thumshirn 		list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
188618bb8bbfSJohannes Thumshirn 	}
188718bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
188818bb8bbfSJohannes Thumshirn }
188918bb8bbfSJohannes Thumshirn 
1890e3ba67a1SJohannes Thumshirn static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1891e3ba67a1SJohannes Thumshirn 			   struct btrfs_path *path)
1892e3ba67a1SJohannes Thumshirn {
1893e3ba67a1SJohannes Thumshirn 	struct extent_map_tree *em_tree;
1894e3ba67a1SJohannes Thumshirn 	struct extent_map *em;
1895e3ba67a1SJohannes Thumshirn 	struct btrfs_block_group_item bg;
1896e3ba67a1SJohannes Thumshirn 	struct extent_buffer *leaf;
1897e3ba67a1SJohannes Thumshirn 	int slot;
1898e3ba67a1SJohannes Thumshirn 	u64 flags;
1899e3ba67a1SJohannes Thumshirn 	int ret = 0;
1900e3ba67a1SJohannes Thumshirn 
1901e3ba67a1SJohannes Thumshirn 	slot = path->slots[0];
1902e3ba67a1SJohannes Thumshirn 	leaf = path->nodes[0];
1903e3ba67a1SJohannes Thumshirn 
1904e3ba67a1SJohannes Thumshirn 	em_tree = &fs_info->mapping_tree;
1905e3ba67a1SJohannes Thumshirn 	read_lock(&em_tree->lock);
1906e3ba67a1SJohannes Thumshirn 	em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1907e3ba67a1SJohannes Thumshirn 	read_unlock(&em_tree->lock);
1908e3ba67a1SJohannes Thumshirn 	if (!em) {
1909e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1910e3ba67a1SJohannes Thumshirn 			  "logical %llu len %llu found bg but no related chunk",
1911e3ba67a1SJohannes Thumshirn 			  key->objectid, key->offset);
1912e3ba67a1SJohannes Thumshirn 		return -ENOENT;
1913e3ba67a1SJohannes Thumshirn 	}
1914e3ba67a1SJohannes Thumshirn 
1915e3ba67a1SJohannes Thumshirn 	if (em->start != key->objectid || em->len != key->offset) {
1916e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1917e3ba67a1SJohannes Thumshirn 			"block group %llu len %llu mismatch with chunk %llu len %llu",
1918e3ba67a1SJohannes Thumshirn 			key->objectid, key->offset, em->start, em->len);
1919e3ba67a1SJohannes Thumshirn 		ret = -EUCLEAN;
1920e3ba67a1SJohannes Thumshirn 		goto out_free_em;
1921e3ba67a1SJohannes Thumshirn 	}
1922e3ba67a1SJohannes Thumshirn 
1923e3ba67a1SJohannes Thumshirn 	read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1924e3ba67a1SJohannes Thumshirn 			   sizeof(bg));
1925e3ba67a1SJohannes Thumshirn 	flags = btrfs_stack_block_group_flags(&bg) &
1926e3ba67a1SJohannes Thumshirn 		BTRFS_BLOCK_GROUP_TYPE_MASK;
1927e3ba67a1SJohannes Thumshirn 
1928e3ba67a1SJohannes Thumshirn 	if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1929e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1930e3ba67a1SJohannes Thumshirn "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1931e3ba67a1SJohannes Thumshirn 			  key->objectid, key->offset, flags,
1932e3ba67a1SJohannes Thumshirn 			  (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1933e3ba67a1SJohannes Thumshirn 		ret = -EUCLEAN;
1934e3ba67a1SJohannes Thumshirn 	}
1935e3ba67a1SJohannes Thumshirn 
1936e3ba67a1SJohannes Thumshirn out_free_em:
1937e3ba67a1SJohannes Thumshirn 	free_extent_map(em);
1938e3ba67a1SJohannes Thumshirn 	return ret;
1939e3ba67a1SJohannes Thumshirn }
1940e3ba67a1SJohannes Thumshirn 
19414358d963SJosef Bacik static int find_first_block_group(struct btrfs_fs_info *fs_info,
19424358d963SJosef Bacik 				  struct btrfs_path *path,
19434358d963SJosef Bacik 				  struct btrfs_key *key)
19444358d963SJosef Bacik {
1945dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
1946e3ba67a1SJohannes Thumshirn 	int ret;
19474358d963SJosef Bacik 	struct btrfs_key found_key;
19484358d963SJosef Bacik 
194936dfbbe2SGabriel Niebler 	btrfs_for_each_slot(root, key, &found_key, path, ret) {
19504358d963SJosef Bacik 		if (found_key.objectid >= key->objectid &&
19514358d963SJosef Bacik 		    found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
195236dfbbe2SGabriel Niebler 			return read_bg_from_eb(fs_info, &found_key, path);
1953e3ba67a1SJohannes Thumshirn 		}
19544358d963SJosef Bacik 	}
19554358d963SJosef Bacik 	return ret;
19564358d963SJosef Bacik }
19574358d963SJosef Bacik 
19584358d963SJosef Bacik static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
19594358d963SJosef Bacik {
19604358d963SJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
19614358d963SJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
19624358d963SJosef Bacik 
19634358d963SJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
19644358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
19654358d963SJosef Bacik 		fs_info->avail_data_alloc_bits |= extra_flags;
19664358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
19674358d963SJosef Bacik 		fs_info->avail_metadata_alloc_bits |= extra_flags;
19684358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
19694358d963SJosef Bacik 		fs_info->avail_system_alloc_bits |= extra_flags;
19704358d963SJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
19714358d963SJosef Bacik }
19724358d963SJosef Bacik 
197343dd529aSDavid Sterba /*
197443dd529aSDavid Sterba  * Map a physical disk address to a list of logical addresses.
19759ee9b979SNikolay Borisov  *
19769ee9b979SNikolay Borisov  * @fs_info:       the filesystem
197796a14336SNikolay Borisov  * @chunk_start:   logical address of block group
197896a14336SNikolay Borisov  * @physical:	   physical address to map to logical addresses
197996a14336SNikolay Borisov  * @logical:	   return array of logical addresses which map to @physical
198096a14336SNikolay Borisov  * @naddrs:	   length of @logical
198196a14336SNikolay Borisov  * @stripe_len:    size of IO stripe for the given block group
198296a14336SNikolay Borisov  *
198396a14336SNikolay Borisov  * Maps a particular @physical disk address to a list of @logical addresses.
198496a14336SNikolay Borisov  * Used primarily to exclude those portions of a block group that contain super
198596a14336SNikolay Borisov  * block copies.
198696a14336SNikolay Borisov  */
198796a14336SNikolay Borisov int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
19881eb82ef8SChristoph Hellwig 		     u64 physical, u64 **logical, int *naddrs, int *stripe_len)
198996a14336SNikolay Borisov {
199096a14336SNikolay Borisov 	struct extent_map *em;
199196a14336SNikolay Borisov 	struct map_lookup *map;
199296a14336SNikolay Borisov 	u64 *buf;
199396a14336SNikolay Borisov 	u64 bytenr;
19941776ad17SNikolay Borisov 	u64 data_stripe_length;
19951776ad17SNikolay Borisov 	u64 io_stripe_size;
19961776ad17SNikolay Borisov 	int i, nr = 0;
19971776ad17SNikolay Borisov 	int ret = 0;
199896a14336SNikolay Borisov 
199996a14336SNikolay Borisov 	em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
200096a14336SNikolay Borisov 	if (IS_ERR(em))
200196a14336SNikolay Borisov 		return -EIO;
200296a14336SNikolay Borisov 
200396a14336SNikolay Borisov 	map = em->map_lookup;
20049e22b925SNikolay Borisov 	data_stripe_length = em->orig_block_len;
2005a97699d1SQu Wenruo 	io_stripe_size = BTRFS_STRIPE_LEN;
2006138082f3SNaohiro Aota 	chunk_start = em->start;
200796a14336SNikolay Borisov 
20089e22b925SNikolay Borisov 	/* For RAID5/6 adjust to a full IO stripe length */
20099e22b925SNikolay Borisov 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
2010a97699d1SQu Wenruo 		io_stripe_size = nr_data_stripes(map) << BTRFS_STRIPE_LEN_SHIFT;
201196a14336SNikolay Borisov 
201296a14336SNikolay Borisov 	buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
20131776ad17SNikolay Borisov 	if (!buf) {
20141776ad17SNikolay Borisov 		ret = -ENOMEM;
20151776ad17SNikolay Borisov 		goto out;
20161776ad17SNikolay Borisov 	}
201796a14336SNikolay Borisov 
201896a14336SNikolay Borisov 	for (i = 0; i < map->num_stripes; i++) {
20191776ad17SNikolay Borisov 		bool already_inserted = false;
20206ded22c1SQu Wenruo 		u32 stripe_nr;
20216ded22c1SQu Wenruo 		u32 offset;
20221776ad17SNikolay Borisov 		int j;
20231776ad17SNikolay Borisov 
20241776ad17SNikolay Borisov 		if (!in_range(physical, map->stripes[i].physical,
20251776ad17SNikolay Borisov 			      data_stripe_length))
202696a14336SNikolay Borisov 			continue;
202796a14336SNikolay Borisov 
2028a97699d1SQu Wenruo 		stripe_nr = (physical - map->stripes[i].physical) >>
2029a97699d1SQu Wenruo 			    BTRFS_STRIPE_LEN_SHIFT;
2030a97699d1SQu Wenruo 		offset = (physical - map->stripes[i].physical) &
2031a97699d1SQu Wenruo 			 BTRFS_STRIPE_LEN_MASK;
203296a14336SNikolay Borisov 
2033ac067734SDavid Sterba 		if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
20346ded22c1SQu Wenruo 				 BTRFS_BLOCK_GROUP_RAID10))
20356ded22c1SQu Wenruo 			stripe_nr = div_u64(stripe_nr * map->num_stripes + i,
20366ded22c1SQu Wenruo 					    map->sub_stripes);
203796a14336SNikolay Borisov 		/*
203896a14336SNikolay Borisov 		 * The remaining case would be for RAID56, multiply by
203996a14336SNikolay Borisov 		 * nr_data_stripes().  Alternatively, just use rmap_len below
204096a14336SNikolay Borisov 		 * instead of map->stripe_len
204196a14336SNikolay Borisov 		 */
2042138082f3SNaohiro Aota 		bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
20431776ad17SNikolay Borisov 
20441776ad17SNikolay Borisov 		/* Ensure we don't add duplicate addresses */
204596a14336SNikolay Borisov 		for (j = 0; j < nr; j++) {
20461776ad17SNikolay Borisov 			if (buf[j] == bytenr) {
20471776ad17SNikolay Borisov 				already_inserted = true;
204896a14336SNikolay Borisov 				break;
204996a14336SNikolay Borisov 			}
205096a14336SNikolay Borisov 		}
20511776ad17SNikolay Borisov 
20521776ad17SNikolay Borisov 		if (!already_inserted)
20531776ad17SNikolay Borisov 			buf[nr++] = bytenr;
205496a14336SNikolay Borisov 	}
205596a14336SNikolay Borisov 
205696a14336SNikolay Borisov 	*logical = buf;
205796a14336SNikolay Borisov 	*naddrs = nr;
20581776ad17SNikolay Borisov 	*stripe_len = io_stripe_size;
20591776ad17SNikolay Borisov out:
206096a14336SNikolay Borisov 	free_extent_map(em);
20611776ad17SNikolay Borisov 	return ret;
206296a14336SNikolay Borisov }
206396a14336SNikolay Borisov 
206432da5386SDavid Sterba static int exclude_super_stripes(struct btrfs_block_group *cache)
20654358d963SJosef Bacik {
20664358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
206712659251SNaohiro Aota 	const bool zoned = btrfs_is_zoned(fs_info);
20684358d963SJosef Bacik 	u64 bytenr;
20694358d963SJosef Bacik 	u64 *logical;
20704358d963SJosef Bacik 	int stripe_len;
20714358d963SJosef Bacik 	int i, nr, ret;
20724358d963SJosef Bacik 
2073b3470b5dSDavid Sterba 	if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
2074b3470b5dSDavid Sterba 		stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
20754358d963SJosef Bacik 		cache->bytes_super += stripe_len;
2076b3470b5dSDavid Sterba 		ret = btrfs_add_excluded_extent(fs_info, cache->start,
20774358d963SJosef Bacik 						stripe_len);
20784358d963SJosef Bacik 		if (ret)
20794358d963SJosef Bacik 			return ret;
20804358d963SJosef Bacik 	}
20814358d963SJosef Bacik 
20824358d963SJosef Bacik 	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
20834358d963SJosef Bacik 		bytenr = btrfs_sb_offset(i);
20841eb82ef8SChristoph Hellwig 		ret = btrfs_rmap_block(fs_info, cache->start,
20854358d963SJosef Bacik 				       bytenr, &logical, &nr, &stripe_len);
20864358d963SJosef Bacik 		if (ret)
20874358d963SJosef Bacik 			return ret;
20884358d963SJosef Bacik 
208912659251SNaohiro Aota 		/* Shouldn't have super stripes in sequential zones */
209012659251SNaohiro Aota 		if (zoned && nr) {
209112659251SNaohiro Aota 			btrfs_err(fs_info,
209212659251SNaohiro Aota 			"zoned: block group %llu must not contain super block",
209312659251SNaohiro Aota 				  cache->start);
209412659251SNaohiro Aota 			return -EUCLEAN;
209512659251SNaohiro Aota 		}
209612659251SNaohiro Aota 
20974358d963SJosef Bacik 		while (nr--) {
209896f9b0f2SNikolay Borisov 			u64 len = min_t(u64, stripe_len,
209996f9b0f2SNikolay Borisov 				cache->start + cache->length - logical[nr]);
21004358d963SJosef Bacik 
21014358d963SJosef Bacik 			cache->bytes_super += len;
210296f9b0f2SNikolay Borisov 			ret = btrfs_add_excluded_extent(fs_info, logical[nr],
210396f9b0f2SNikolay Borisov 							len);
21044358d963SJosef Bacik 			if (ret) {
21054358d963SJosef Bacik 				kfree(logical);
21064358d963SJosef Bacik 				return ret;
21074358d963SJosef Bacik 			}
21084358d963SJosef Bacik 		}
21094358d963SJosef Bacik 
21104358d963SJosef Bacik 		kfree(logical);
21114358d963SJosef Bacik 	}
21124358d963SJosef Bacik 	return 0;
21134358d963SJosef Bacik }
21144358d963SJosef Bacik 
211532da5386SDavid Sterba static struct btrfs_block_group *btrfs_create_block_group_cache(
21169afc6649SQu Wenruo 		struct btrfs_fs_info *fs_info, u64 start)
21174358d963SJosef Bacik {
211832da5386SDavid Sterba 	struct btrfs_block_group *cache;
21194358d963SJosef Bacik 
21204358d963SJosef Bacik 	cache = kzalloc(sizeof(*cache), GFP_NOFS);
21214358d963SJosef Bacik 	if (!cache)
21224358d963SJosef Bacik 		return NULL;
21234358d963SJosef Bacik 
21244358d963SJosef Bacik 	cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
21254358d963SJosef Bacik 					GFP_NOFS);
21264358d963SJosef Bacik 	if (!cache->free_space_ctl) {
21274358d963SJosef Bacik 		kfree(cache);
21284358d963SJosef Bacik 		return NULL;
21294358d963SJosef Bacik 	}
21304358d963SJosef Bacik 
2131b3470b5dSDavid Sterba 	cache->start = start;
21324358d963SJosef Bacik 
21334358d963SJosef Bacik 	cache->fs_info = fs_info;
21344358d963SJosef Bacik 	cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
21354358d963SJosef Bacik 
21366e80d4f8SDennis Zhou 	cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
21376e80d4f8SDennis Zhou 
213848aaeebeSJosef Bacik 	refcount_set(&cache->refs, 1);
21394358d963SJosef Bacik 	spin_lock_init(&cache->lock);
21404358d963SJosef Bacik 	init_rwsem(&cache->data_rwsem);
21414358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->list);
21424358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->cluster_list);
21434358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->bg_list);
21444358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->ro_list);
2145b0643e59SDennis Zhou 	INIT_LIST_HEAD(&cache->discard_list);
21464358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->dirty_list);
21474358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->io_list);
2148afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&cache->active_bg_list);
2149cd79909bSJosef Bacik 	btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
21506b7304afSFilipe Manana 	atomic_set(&cache->frozen, 0);
21514358d963SJosef Bacik 	mutex_init(&cache->free_space_lock);
21524358d963SJosef Bacik 
21534358d963SJosef Bacik 	return cache;
21544358d963SJosef Bacik }
21554358d963SJosef Bacik 
21564358d963SJosef Bacik /*
21574358d963SJosef Bacik  * Iterate all chunks and verify that each of them has the corresponding block
21584358d963SJosef Bacik  * group
21594358d963SJosef Bacik  */
21604358d963SJosef Bacik static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
21614358d963SJosef Bacik {
21624358d963SJosef Bacik 	struct extent_map_tree *map_tree = &fs_info->mapping_tree;
21634358d963SJosef Bacik 	struct extent_map *em;
216432da5386SDavid Sterba 	struct btrfs_block_group *bg;
21654358d963SJosef Bacik 	u64 start = 0;
21664358d963SJosef Bacik 	int ret = 0;
21674358d963SJosef Bacik 
21684358d963SJosef Bacik 	while (1) {
21694358d963SJosef Bacik 		read_lock(&map_tree->lock);
21704358d963SJosef Bacik 		/*
21714358d963SJosef Bacik 		 * lookup_extent_mapping will return the first extent map
21724358d963SJosef Bacik 		 * intersecting the range, so setting @len to 1 is enough to
21734358d963SJosef Bacik 		 * get the first chunk.
21744358d963SJosef Bacik 		 */
21754358d963SJosef Bacik 		em = lookup_extent_mapping(map_tree, start, 1);
21764358d963SJosef Bacik 		read_unlock(&map_tree->lock);
21774358d963SJosef Bacik 		if (!em)
21784358d963SJosef Bacik 			break;
21794358d963SJosef Bacik 
21804358d963SJosef Bacik 		bg = btrfs_lookup_block_group(fs_info, em->start);
21814358d963SJosef Bacik 		if (!bg) {
21824358d963SJosef Bacik 			btrfs_err(fs_info,
21834358d963SJosef Bacik 	"chunk start=%llu len=%llu doesn't have corresponding block group",
21844358d963SJosef Bacik 				     em->start, em->len);
21854358d963SJosef Bacik 			ret = -EUCLEAN;
21864358d963SJosef Bacik 			free_extent_map(em);
21874358d963SJosef Bacik 			break;
21884358d963SJosef Bacik 		}
2189b3470b5dSDavid Sterba 		if (bg->start != em->start || bg->length != em->len ||
21904358d963SJosef Bacik 		    (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
21914358d963SJosef Bacik 		    (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
21924358d963SJosef Bacik 			btrfs_err(fs_info,
21934358d963SJosef Bacik "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
21944358d963SJosef Bacik 				em->start, em->len,
21954358d963SJosef Bacik 				em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
2196b3470b5dSDavid Sterba 				bg->start, bg->length,
21974358d963SJosef Bacik 				bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
21984358d963SJosef Bacik 			ret = -EUCLEAN;
21994358d963SJosef Bacik 			free_extent_map(em);
22004358d963SJosef Bacik 			btrfs_put_block_group(bg);
22014358d963SJosef Bacik 			break;
22024358d963SJosef Bacik 		}
22034358d963SJosef Bacik 		start = em->start + em->len;
22044358d963SJosef Bacik 		free_extent_map(em);
22054358d963SJosef Bacik 		btrfs_put_block_group(bg);
22064358d963SJosef Bacik 	}
22074358d963SJosef Bacik 	return ret;
22084358d963SJosef Bacik }
22094358d963SJosef Bacik 
2210ffb9e0f0SQu Wenruo static int read_one_block_group(struct btrfs_fs_info *info,
22114afd2fe8SJohannes Thumshirn 				struct btrfs_block_group_item *bgi,
2212d49a2ddbSQu Wenruo 				const struct btrfs_key *key,
2213ffb9e0f0SQu Wenruo 				int need_clear)
2214ffb9e0f0SQu Wenruo {
221532da5386SDavid Sterba 	struct btrfs_block_group *cache;
2216ffb9e0f0SQu Wenruo 	const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
2217ffb9e0f0SQu Wenruo 	int ret;
2218ffb9e0f0SQu Wenruo 
2219d49a2ddbSQu Wenruo 	ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
2220ffb9e0f0SQu Wenruo 
22219afc6649SQu Wenruo 	cache = btrfs_create_block_group_cache(info, key->objectid);
2222ffb9e0f0SQu Wenruo 	if (!cache)
2223ffb9e0f0SQu Wenruo 		return -ENOMEM;
2224ffb9e0f0SQu Wenruo 
22254afd2fe8SJohannes Thumshirn 	cache->length = key->offset;
22264afd2fe8SJohannes Thumshirn 	cache->used = btrfs_stack_block_group_used(bgi);
22277248e0ceSQu Wenruo 	cache->commit_used = cache->used;
22284afd2fe8SJohannes Thumshirn 	cache->flags = btrfs_stack_block_group_flags(bgi);
2229f7238e50SJosef Bacik 	cache->global_root_id = btrfs_stack_block_group_chunk_objectid(bgi);
22309afc6649SQu Wenruo 
2231e3e39c72SMarcos Paulo de Souza 	set_free_space_tree_thresholds(cache);
2232e3e39c72SMarcos Paulo de Souza 
2233ffb9e0f0SQu Wenruo 	if (need_clear) {
2234ffb9e0f0SQu Wenruo 		/*
2235ffb9e0f0SQu Wenruo 		 * When we mount with old space cache, we need to
2236ffb9e0f0SQu Wenruo 		 * set BTRFS_DC_CLEAR and set dirty flag.
2237ffb9e0f0SQu Wenruo 		 *
2238ffb9e0f0SQu Wenruo 		 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
2239ffb9e0f0SQu Wenruo 		 *    truncate the old free space cache inode and
2240ffb9e0f0SQu Wenruo 		 *    setup a new one.
2241ffb9e0f0SQu Wenruo 		 * b) Setting 'dirty flag' makes sure that we flush
2242ffb9e0f0SQu Wenruo 		 *    the new space cache info onto disk.
2243ffb9e0f0SQu Wenruo 		 */
2244ffb9e0f0SQu Wenruo 		if (btrfs_test_opt(info, SPACE_CACHE))
2245ffb9e0f0SQu Wenruo 			cache->disk_cache_state = BTRFS_DC_CLEAR;
2246ffb9e0f0SQu Wenruo 	}
2247ffb9e0f0SQu Wenruo 	if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
2248ffb9e0f0SQu Wenruo 	    (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
2249ffb9e0f0SQu Wenruo 			btrfs_err(info,
2250ffb9e0f0SQu Wenruo "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2251ffb9e0f0SQu Wenruo 				  cache->start);
2252ffb9e0f0SQu Wenruo 			ret = -EINVAL;
2253ffb9e0f0SQu Wenruo 			goto error;
2254ffb9e0f0SQu Wenruo 	}
2255ffb9e0f0SQu Wenruo 
2256a94794d5SNaohiro Aota 	ret = btrfs_load_block_group_zone_info(cache, false);
225708e11a3dSNaohiro Aota 	if (ret) {
225808e11a3dSNaohiro Aota 		btrfs_err(info, "zoned: failed to load zone info of bg %llu",
225908e11a3dSNaohiro Aota 			  cache->start);
226008e11a3dSNaohiro Aota 		goto error;
226108e11a3dSNaohiro Aota 	}
226208e11a3dSNaohiro Aota 
2263ffb9e0f0SQu Wenruo 	/*
2264ffb9e0f0SQu Wenruo 	 * We need to exclude the super stripes now so that the space info has
2265ffb9e0f0SQu Wenruo 	 * super bytes accounted for, otherwise we'll think we have more space
2266ffb9e0f0SQu Wenruo 	 * than we actually do.
2267ffb9e0f0SQu Wenruo 	 */
2268ffb9e0f0SQu Wenruo 	ret = exclude_super_stripes(cache);
2269ffb9e0f0SQu Wenruo 	if (ret) {
2270ffb9e0f0SQu Wenruo 		/* We may have excluded something, so call this just in case. */
2271ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2272ffb9e0f0SQu Wenruo 		goto error;
2273ffb9e0f0SQu Wenruo 	}
2274ffb9e0f0SQu Wenruo 
2275ffb9e0f0SQu Wenruo 	/*
2276169e0da9SNaohiro Aota 	 * For zoned filesystem, space after the allocation offset is the only
2277169e0da9SNaohiro Aota 	 * free space for a block group. So, we don't need any caching work.
2278169e0da9SNaohiro Aota 	 * btrfs_calc_zone_unusable() will set the amount of free space and
2279169e0da9SNaohiro Aota 	 * zone_unusable space.
2280169e0da9SNaohiro Aota 	 *
2281169e0da9SNaohiro Aota 	 * For regular filesystem, check for two cases, either we are full, and
2282169e0da9SNaohiro Aota 	 * therefore don't need to bother with the caching work since we won't
2283169e0da9SNaohiro Aota 	 * find any space, or we are empty, and we can just add all the space
2284169e0da9SNaohiro Aota 	 * in and be done with it.  This saves us _a_lot_ of time, particularly
2285169e0da9SNaohiro Aota 	 * in the full case.
2286ffb9e0f0SQu Wenruo 	 */
2287169e0da9SNaohiro Aota 	if (btrfs_is_zoned(info)) {
2288169e0da9SNaohiro Aota 		btrfs_calc_zone_unusable(cache);
2289c46c4247SNaohiro Aota 		/* Should not have any excluded extents. Just in case, though. */
2290c46c4247SNaohiro Aota 		btrfs_free_excluded_extents(cache);
2291169e0da9SNaohiro Aota 	} else if (cache->length == cache->used) {
2292ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
2293ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2294ffb9e0f0SQu Wenruo 	} else if (cache->used == 0) {
2295ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
22969afc6649SQu Wenruo 		add_new_free_space(cache, cache->start,
22979afc6649SQu Wenruo 				   cache->start + cache->length);
2298ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2299ffb9e0f0SQu Wenruo 	}
2300ffb9e0f0SQu Wenruo 
2301ffb9e0f0SQu Wenruo 	ret = btrfs_add_block_group_cache(info, cache);
2302ffb9e0f0SQu Wenruo 	if (ret) {
2303ffb9e0f0SQu Wenruo 		btrfs_remove_free_space_cache(cache);
2304ffb9e0f0SQu Wenruo 		goto error;
2305ffb9e0f0SQu Wenruo 	}
2306ffb9e0f0SQu Wenruo 	trace_btrfs_add_block_group(info, cache, 0);
2307723de71dSJosef Bacik 	btrfs_add_bg_to_space_info(info, cache);
2308ffb9e0f0SQu Wenruo 
2309ffb9e0f0SQu Wenruo 	set_avail_alloc_bits(info, cache->flags);
2310a09f23c3SAnand Jain 	if (btrfs_chunk_writeable(info, cache->start)) {
2311a09f23c3SAnand Jain 		if (cache->used == 0) {
2312ffb9e0f0SQu Wenruo 			ASSERT(list_empty(&cache->bg_list));
23136e80d4f8SDennis Zhou 			if (btrfs_test_opt(info, DISCARD_ASYNC))
23146e80d4f8SDennis Zhou 				btrfs_discard_queue_work(&info->discard_ctl, cache);
23156e80d4f8SDennis Zhou 			else
2316ffb9e0f0SQu Wenruo 				btrfs_mark_bg_unused(cache);
2317ffb9e0f0SQu Wenruo 		}
2318a09f23c3SAnand Jain 	} else {
2319a09f23c3SAnand Jain 		inc_block_group_ro(cache, 1);
2320a09f23c3SAnand Jain 	}
2321a09f23c3SAnand Jain 
2322ffb9e0f0SQu Wenruo 	return 0;
2323ffb9e0f0SQu Wenruo error:
2324ffb9e0f0SQu Wenruo 	btrfs_put_block_group(cache);
2325ffb9e0f0SQu Wenruo 	return ret;
2326ffb9e0f0SQu Wenruo }
2327ffb9e0f0SQu Wenruo 
232842437a63SJosef Bacik static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
232942437a63SJosef Bacik {
233042437a63SJosef Bacik 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
233142437a63SJosef Bacik 	struct rb_node *node;
233242437a63SJosef Bacik 	int ret = 0;
233342437a63SJosef Bacik 
233442437a63SJosef Bacik 	for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
233542437a63SJosef Bacik 		struct extent_map *em;
233642437a63SJosef Bacik 		struct map_lookup *map;
233742437a63SJosef Bacik 		struct btrfs_block_group *bg;
233842437a63SJosef Bacik 
233942437a63SJosef Bacik 		em = rb_entry(node, struct extent_map, rb_node);
234042437a63SJosef Bacik 		map = em->map_lookup;
234142437a63SJosef Bacik 		bg = btrfs_create_block_group_cache(fs_info, em->start);
234242437a63SJosef Bacik 		if (!bg) {
234342437a63SJosef Bacik 			ret = -ENOMEM;
234442437a63SJosef Bacik 			break;
234542437a63SJosef Bacik 		}
234642437a63SJosef Bacik 
234742437a63SJosef Bacik 		/* Fill dummy cache as FULL */
234842437a63SJosef Bacik 		bg->length = em->len;
234942437a63SJosef Bacik 		bg->flags = map->type;
235042437a63SJosef Bacik 		bg->cached = BTRFS_CACHE_FINISHED;
235142437a63SJosef Bacik 		bg->used = em->len;
235242437a63SJosef Bacik 		bg->flags = map->type;
235342437a63SJosef Bacik 		ret = btrfs_add_block_group_cache(fs_info, bg);
23542b29726cSQu Wenruo 		/*
23552b29726cSQu Wenruo 		 * We may have some valid block group cache added already, in
23562b29726cSQu Wenruo 		 * that case we skip to the next one.
23572b29726cSQu Wenruo 		 */
23582b29726cSQu Wenruo 		if (ret == -EEXIST) {
23592b29726cSQu Wenruo 			ret = 0;
23602b29726cSQu Wenruo 			btrfs_put_block_group(bg);
23612b29726cSQu Wenruo 			continue;
23622b29726cSQu Wenruo 		}
23632b29726cSQu Wenruo 
236442437a63SJosef Bacik 		if (ret) {
236542437a63SJosef Bacik 			btrfs_remove_free_space_cache(bg);
236642437a63SJosef Bacik 			btrfs_put_block_group(bg);
236742437a63SJosef Bacik 			break;
236842437a63SJosef Bacik 		}
23692b29726cSQu Wenruo 
2370723de71dSJosef Bacik 		btrfs_add_bg_to_space_info(fs_info, bg);
237142437a63SJosef Bacik 
237242437a63SJosef Bacik 		set_avail_alloc_bits(fs_info, bg->flags);
237342437a63SJosef Bacik 	}
237442437a63SJosef Bacik 	if (!ret)
237542437a63SJosef Bacik 		btrfs_init_global_block_rsv(fs_info);
237642437a63SJosef Bacik 	return ret;
237742437a63SJosef Bacik }
237842437a63SJosef Bacik 
23794358d963SJosef Bacik int btrfs_read_block_groups(struct btrfs_fs_info *info)
23804358d963SJosef Bacik {
2381dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(info);
23824358d963SJosef Bacik 	struct btrfs_path *path;
23834358d963SJosef Bacik 	int ret;
238432da5386SDavid Sterba 	struct btrfs_block_group *cache;
23854358d963SJosef Bacik 	struct btrfs_space_info *space_info;
23864358d963SJosef Bacik 	struct btrfs_key key;
23874358d963SJosef Bacik 	int need_clear = 0;
23884358d963SJosef Bacik 	u64 cache_gen;
23894358d963SJosef Bacik 
239081d5d614SQu Wenruo 	/*
239181d5d614SQu Wenruo 	 * Either no extent root (with ibadroots rescue option) or we have
239281d5d614SQu Wenruo 	 * unsupported RO options. The fs can never be mounted read-write, so no
239381d5d614SQu Wenruo 	 * need to waste time searching block group items.
239481d5d614SQu Wenruo 	 *
239581d5d614SQu Wenruo 	 * This also allows new extent tree related changes to be RO compat,
239681d5d614SQu Wenruo 	 * no need for a full incompat flag.
239781d5d614SQu Wenruo 	 */
239881d5d614SQu Wenruo 	if (!root || (btrfs_super_compat_ro_flags(info->super_copy) &
239981d5d614SQu Wenruo 		      ~BTRFS_FEATURE_COMPAT_RO_SUPP))
240042437a63SJosef Bacik 		return fill_dummy_bgs(info);
240142437a63SJosef Bacik 
24024358d963SJosef Bacik 	key.objectid = 0;
24034358d963SJosef Bacik 	key.offset = 0;
24044358d963SJosef Bacik 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
24054358d963SJosef Bacik 	path = btrfs_alloc_path();
24064358d963SJosef Bacik 	if (!path)
24074358d963SJosef Bacik 		return -ENOMEM;
24084358d963SJosef Bacik 
24094358d963SJosef Bacik 	cache_gen = btrfs_super_cache_generation(info->super_copy);
24104358d963SJosef Bacik 	if (btrfs_test_opt(info, SPACE_CACHE) &&
24114358d963SJosef Bacik 	    btrfs_super_generation(info->super_copy) != cache_gen)
24124358d963SJosef Bacik 		need_clear = 1;
24134358d963SJosef Bacik 	if (btrfs_test_opt(info, CLEAR_CACHE))
24144358d963SJosef Bacik 		need_clear = 1;
24154358d963SJosef Bacik 
24164358d963SJosef Bacik 	while (1) {
24174afd2fe8SJohannes Thumshirn 		struct btrfs_block_group_item bgi;
24184afd2fe8SJohannes Thumshirn 		struct extent_buffer *leaf;
24194afd2fe8SJohannes Thumshirn 		int slot;
24204afd2fe8SJohannes Thumshirn 
24214358d963SJosef Bacik 		ret = find_first_block_group(info, path, &key);
24224358d963SJosef Bacik 		if (ret > 0)
24234358d963SJosef Bacik 			break;
24244358d963SJosef Bacik 		if (ret != 0)
24254358d963SJosef Bacik 			goto error;
24264358d963SJosef Bacik 
24274afd2fe8SJohannes Thumshirn 		leaf = path->nodes[0];
24284afd2fe8SJohannes Thumshirn 		slot = path->slots[0];
24294afd2fe8SJohannes Thumshirn 
24304afd2fe8SJohannes Thumshirn 		read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
24314afd2fe8SJohannes Thumshirn 				   sizeof(bgi));
24324afd2fe8SJohannes Thumshirn 
24334afd2fe8SJohannes Thumshirn 		btrfs_item_key_to_cpu(leaf, &key, slot);
24344afd2fe8SJohannes Thumshirn 		btrfs_release_path(path);
24354afd2fe8SJohannes Thumshirn 		ret = read_one_block_group(info, &bgi, &key, need_clear);
2436ffb9e0f0SQu Wenruo 		if (ret < 0)
24374358d963SJosef Bacik 			goto error;
2438ffb9e0f0SQu Wenruo 		key.objectid += key.offset;
2439ffb9e0f0SQu Wenruo 		key.offset = 0;
24404358d963SJosef Bacik 	}
24417837fa88SJosef Bacik 	btrfs_release_path(path);
24424358d963SJosef Bacik 
244372804905SJosef Bacik 	list_for_each_entry(space_info, &info->space_info, list) {
244449ea112dSJosef Bacik 		int i;
244549ea112dSJosef Bacik 
244649ea112dSJosef Bacik 		for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
244749ea112dSJosef Bacik 			if (list_empty(&space_info->block_groups[i]))
244849ea112dSJosef Bacik 				continue;
244949ea112dSJosef Bacik 			cache = list_first_entry(&space_info->block_groups[i],
245049ea112dSJosef Bacik 						 struct btrfs_block_group,
245149ea112dSJosef Bacik 						 list);
245249ea112dSJosef Bacik 			btrfs_sysfs_add_block_group_type(cache);
245349ea112dSJosef Bacik 		}
245449ea112dSJosef Bacik 
24554358d963SJosef Bacik 		if (!(btrfs_get_alloc_profile(info, space_info->flags) &
24564358d963SJosef Bacik 		      (BTRFS_BLOCK_GROUP_RAID10 |
24574358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID1_MASK |
24584358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID56_MASK |
24594358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_DUP)))
24604358d963SJosef Bacik 			continue;
24614358d963SJosef Bacik 		/*
24624358d963SJosef Bacik 		 * Avoid allocating from un-mirrored block group if there are
24634358d963SJosef Bacik 		 * mirrored block groups.
24644358d963SJosef Bacik 		 */
24654358d963SJosef Bacik 		list_for_each_entry(cache,
24664358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_RAID0],
24674358d963SJosef Bacik 				list)
2468e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
24694358d963SJosef Bacik 		list_for_each_entry(cache,
24704358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_SINGLE],
24714358d963SJosef Bacik 				list)
2472e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
24734358d963SJosef Bacik 	}
24744358d963SJosef Bacik 
24754358d963SJosef Bacik 	btrfs_init_global_block_rsv(info);
24764358d963SJosef Bacik 	ret = check_chunk_block_group_mappings(info);
24774358d963SJosef Bacik error:
24784358d963SJosef Bacik 	btrfs_free_path(path);
24792b29726cSQu Wenruo 	/*
24802b29726cSQu Wenruo 	 * We've hit some error while reading the extent tree, and have
24812b29726cSQu Wenruo 	 * rescue=ibadroots mount option.
24822b29726cSQu Wenruo 	 * Try to fill the tree using dummy block groups so that the user can
24832b29726cSQu Wenruo 	 * continue to mount and grab their data.
24842b29726cSQu Wenruo 	 */
24852b29726cSQu Wenruo 	if (ret && btrfs_test_opt(info, IGNOREBADROOTS))
24862b29726cSQu Wenruo 		ret = fill_dummy_bgs(info);
24874358d963SJosef Bacik 	return ret;
24884358d963SJosef Bacik }
24894358d963SJosef Bacik 
249079bd3712SFilipe Manana /*
249179bd3712SFilipe Manana  * This function, insert_block_group_item(), belongs to the phase 2 of chunk
249279bd3712SFilipe Manana  * allocation.
249379bd3712SFilipe Manana  *
249479bd3712SFilipe Manana  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
249579bd3712SFilipe Manana  * phases.
249679bd3712SFilipe Manana  */
249797f4728aSQu Wenruo static int insert_block_group_item(struct btrfs_trans_handle *trans,
249897f4728aSQu Wenruo 				   struct btrfs_block_group *block_group)
249997f4728aSQu Wenruo {
250097f4728aSQu Wenruo 	struct btrfs_fs_info *fs_info = trans->fs_info;
250197f4728aSQu Wenruo 	struct btrfs_block_group_item bgi;
2502dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
250397f4728aSQu Wenruo 	struct btrfs_key key;
2504675dfe12SFilipe Manana 	u64 old_commit_used;
2505675dfe12SFilipe Manana 	int ret;
250697f4728aSQu Wenruo 
250797f4728aSQu Wenruo 	spin_lock(&block_group->lock);
250897f4728aSQu Wenruo 	btrfs_set_stack_block_group_used(&bgi, block_group->used);
250997f4728aSQu Wenruo 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
2510f7238e50SJosef Bacik 						   block_group->global_root_id);
251197f4728aSQu Wenruo 	btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2512675dfe12SFilipe Manana 	old_commit_used = block_group->commit_used;
2513675dfe12SFilipe Manana 	block_group->commit_used = block_group->used;
251497f4728aSQu Wenruo 	key.objectid = block_group->start;
251597f4728aSQu Wenruo 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
251697f4728aSQu Wenruo 	key.offset = block_group->length;
251797f4728aSQu Wenruo 	spin_unlock(&block_group->lock);
251897f4728aSQu Wenruo 
2519675dfe12SFilipe Manana 	ret = btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2520675dfe12SFilipe Manana 	if (ret < 0) {
2521675dfe12SFilipe Manana 		spin_lock(&block_group->lock);
2522675dfe12SFilipe Manana 		block_group->commit_used = old_commit_used;
2523675dfe12SFilipe Manana 		spin_unlock(&block_group->lock);
2524675dfe12SFilipe Manana 	}
2525675dfe12SFilipe Manana 
2526675dfe12SFilipe Manana 	return ret;
252797f4728aSQu Wenruo }
252897f4728aSQu Wenruo 
25292eadb9e7SNikolay Borisov static int insert_dev_extent(struct btrfs_trans_handle *trans,
25302eadb9e7SNikolay Borisov 			    struct btrfs_device *device, u64 chunk_offset,
25312eadb9e7SNikolay Borisov 			    u64 start, u64 num_bytes)
25322eadb9e7SNikolay Borisov {
25332eadb9e7SNikolay Borisov 	struct btrfs_fs_info *fs_info = device->fs_info;
25342eadb9e7SNikolay Borisov 	struct btrfs_root *root = fs_info->dev_root;
25352eadb9e7SNikolay Borisov 	struct btrfs_path *path;
25362eadb9e7SNikolay Borisov 	struct btrfs_dev_extent *extent;
25372eadb9e7SNikolay Borisov 	struct extent_buffer *leaf;
25382eadb9e7SNikolay Borisov 	struct btrfs_key key;
25392eadb9e7SNikolay Borisov 	int ret;
25402eadb9e7SNikolay Borisov 
25412eadb9e7SNikolay Borisov 	WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
25422eadb9e7SNikolay Borisov 	WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
25432eadb9e7SNikolay Borisov 	path = btrfs_alloc_path();
25442eadb9e7SNikolay Borisov 	if (!path)
25452eadb9e7SNikolay Borisov 		return -ENOMEM;
25462eadb9e7SNikolay Borisov 
25472eadb9e7SNikolay Borisov 	key.objectid = device->devid;
25482eadb9e7SNikolay Borisov 	key.type = BTRFS_DEV_EXTENT_KEY;
25492eadb9e7SNikolay Borisov 	key.offset = start;
25502eadb9e7SNikolay Borisov 	ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent));
25512eadb9e7SNikolay Borisov 	if (ret)
25522eadb9e7SNikolay Borisov 		goto out;
25532eadb9e7SNikolay Borisov 
25542eadb9e7SNikolay Borisov 	leaf = path->nodes[0];
25552eadb9e7SNikolay Borisov 	extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
25562eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID);
25572eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_objectid(leaf, extent,
25582eadb9e7SNikolay Borisov 					    BTRFS_FIRST_CHUNK_TREE_OBJECTID);
25592eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
25602eadb9e7SNikolay Borisov 
25612eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_length(leaf, extent, num_bytes);
25622eadb9e7SNikolay Borisov 	btrfs_mark_buffer_dirty(leaf);
25632eadb9e7SNikolay Borisov out:
25642eadb9e7SNikolay Borisov 	btrfs_free_path(path);
25652eadb9e7SNikolay Borisov 	return ret;
25662eadb9e7SNikolay Borisov }
25672eadb9e7SNikolay Borisov 
25682eadb9e7SNikolay Borisov /*
25692eadb9e7SNikolay Borisov  * This function belongs to phase 2.
25702eadb9e7SNikolay Borisov  *
25712eadb9e7SNikolay Borisov  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
25722eadb9e7SNikolay Borisov  * phases.
25732eadb9e7SNikolay Borisov  */
25742eadb9e7SNikolay Borisov static int insert_dev_extents(struct btrfs_trans_handle *trans,
25752eadb9e7SNikolay Borisov 				   u64 chunk_offset, u64 chunk_size)
25762eadb9e7SNikolay Borisov {
25772eadb9e7SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
25782eadb9e7SNikolay Borisov 	struct btrfs_device *device;
25792eadb9e7SNikolay Borisov 	struct extent_map *em;
25802eadb9e7SNikolay Borisov 	struct map_lookup *map;
25812eadb9e7SNikolay Borisov 	u64 dev_offset;
25822eadb9e7SNikolay Borisov 	u64 stripe_size;
25832eadb9e7SNikolay Borisov 	int i;
25842eadb9e7SNikolay Borisov 	int ret = 0;
25852eadb9e7SNikolay Borisov 
25862eadb9e7SNikolay Borisov 	em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
25872eadb9e7SNikolay Borisov 	if (IS_ERR(em))
25882eadb9e7SNikolay Borisov 		return PTR_ERR(em);
25892eadb9e7SNikolay Borisov 
25902eadb9e7SNikolay Borisov 	map = em->map_lookup;
25912eadb9e7SNikolay Borisov 	stripe_size = em->orig_block_len;
25922eadb9e7SNikolay Borisov 
25932eadb9e7SNikolay Borisov 	/*
25942eadb9e7SNikolay Borisov 	 * Take the device list mutex to prevent races with the final phase of
25952eadb9e7SNikolay Borisov 	 * a device replace operation that replaces the device object associated
25962eadb9e7SNikolay Borisov 	 * with the map's stripes, because the device object's id can change
25972eadb9e7SNikolay Borisov 	 * at any time during that final phase of the device replace operation
25982eadb9e7SNikolay Borisov 	 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
25992eadb9e7SNikolay Borisov 	 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
26002eadb9e7SNikolay Borisov 	 * resulting in persisting a device extent item with such ID.
26012eadb9e7SNikolay Borisov 	 */
26022eadb9e7SNikolay Borisov 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
26032eadb9e7SNikolay Borisov 	for (i = 0; i < map->num_stripes; i++) {
26042eadb9e7SNikolay Borisov 		device = map->stripes[i].dev;
26052eadb9e7SNikolay Borisov 		dev_offset = map->stripes[i].physical;
26062eadb9e7SNikolay Borisov 
26072eadb9e7SNikolay Borisov 		ret = insert_dev_extent(trans, device, chunk_offset, dev_offset,
26082eadb9e7SNikolay Borisov 				       stripe_size);
26092eadb9e7SNikolay Borisov 		if (ret)
26102eadb9e7SNikolay Borisov 			break;
26112eadb9e7SNikolay Borisov 	}
26122eadb9e7SNikolay Borisov 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
26132eadb9e7SNikolay Borisov 
26142eadb9e7SNikolay Borisov 	free_extent_map(em);
26152eadb9e7SNikolay Borisov 	return ret;
26162eadb9e7SNikolay Borisov }
26172eadb9e7SNikolay Borisov 
261879bd3712SFilipe Manana /*
261979bd3712SFilipe Manana  * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
262079bd3712SFilipe Manana  * chunk allocation.
262179bd3712SFilipe Manana  *
262279bd3712SFilipe Manana  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
262379bd3712SFilipe Manana  * phases.
262479bd3712SFilipe Manana  */
26254358d963SJosef Bacik void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
26264358d963SJosef Bacik {
26274358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
262832da5386SDavid Sterba 	struct btrfs_block_group *block_group;
26294358d963SJosef Bacik 	int ret = 0;
26304358d963SJosef Bacik 
26314358d963SJosef Bacik 	while (!list_empty(&trans->new_bgs)) {
263249ea112dSJosef Bacik 		int index;
263349ea112dSJosef Bacik 
26344358d963SJosef Bacik 		block_group = list_first_entry(&trans->new_bgs,
263532da5386SDavid Sterba 					       struct btrfs_block_group,
26364358d963SJosef Bacik 					       bg_list);
26374358d963SJosef Bacik 		if (ret)
26384358d963SJosef Bacik 			goto next;
26394358d963SJosef Bacik 
264049ea112dSJosef Bacik 		index = btrfs_bg_flags_to_raid_index(block_group->flags);
264149ea112dSJosef Bacik 
264297f4728aSQu Wenruo 		ret = insert_block_group_item(trans, block_group);
26434358d963SJosef Bacik 		if (ret)
26444358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
26453349b57fSJosef Bacik 		if (!test_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED,
26463349b57fSJosef Bacik 			      &block_group->runtime_flags)) {
264779bd3712SFilipe Manana 			mutex_lock(&fs_info->chunk_mutex);
264879bd3712SFilipe Manana 			ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group);
264979bd3712SFilipe Manana 			mutex_unlock(&fs_info->chunk_mutex);
265079bd3712SFilipe Manana 			if (ret)
265179bd3712SFilipe Manana 				btrfs_abort_transaction(trans, ret);
265279bd3712SFilipe Manana 		}
26532eadb9e7SNikolay Borisov 		ret = insert_dev_extents(trans, block_group->start,
265497f4728aSQu Wenruo 					 block_group->length);
26554358d963SJosef Bacik 		if (ret)
26564358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
26574358d963SJosef Bacik 		add_block_group_free_space(trans, block_group);
265849ea112dSJosef Bacik 
265949ea112dSJosef Bacik 		/*
266049ea112dSJosef Bacik 		 * If we restriped during balance, we may have added a new raid
266149ea112dSJosef Bacik 		 * type, so now add the sysfs entries when it is safe to do so.
266249ea112dSJosef Bacik 		 * We don't have to worry about locking here as it's handled in
266349ea112dSJosef Bacik 		 * btrfs_sysfs_add_block_group_type.
266449ea112dSJosef Bacik 		 */
266549ea112dSJosef Bacik 		if (block_group->space_info->block_group_kobjs[index] == NULL)
266649ea112dSJosef Bacik 			btrfs_sysfs_add_block_group_type(block_group);
266749ea112dSJosef Bacik 
26684358d963SJosef Bacik 		/* Already aborted the transaction if it failed. */
26694358d963SJosef Bacik next:
26704358d963SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
26714358d963SJosef Bacik 		list_del_init(&block_group->bg_list);
2672*0657b20cSFilipe Manana 		clear_bit(BLOCK_GROUP_FLAG_NEW, &block_group->runtime_flags);
26734358d963SJosef Bacik 	}
26744358d963SJosef Bacik 	btrfs_trans_release_chunk_metadata(trans);
26754358d963SJosef Bacik }
26764358d963SJosef Bacik 
2677f7238e50SJosef Bacik /*
2678f7238e50SJosef Bacik  * For extent tree v2 we use the block_group_item->chunk_offset to point at our
2679f7238e50SJosef Bacik  * global root id.  For v1 it's always set to BTRFS_FIRST_CHUNK_TREE_OBJECTID.
2680f7238e50SJosef Bacik  */
2681f7238e50SJosef Bacik static u64 calculate_global_root_id(struct btrfs_fs_info *fs_info, u64 offset)
2682f7238e50SJosef Bacik {
2683f7238e50SJosef Bacik 	u64 div = SZ_1G;
2684f7238e50SJosef Bacik 	u64 index;
2685f7238e50SJosef Bacik 
2686f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2687f7238e50SJosef Bacik 		return BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2688f7238e50SJosef Bacik 
2689f7238e50SJosef Bacik 	/* If we have a smaller fs index based on 128MiB. */
2690f7238e50SJosef Bacik 	if (btrfs_super_total_bytes(fs_info->super_copy) <= (SZ_1G * 10ULL))
2691f7238e50SJosef Bacik 		div = SZ_128M;
2692f7238e50SJosef Bacik 
2693f7238e50SJosef Bacik 	offset = div64_u64(offset, div);
2694f7238e50SJosef Bacik 	div64_u64_rem(offset, fs_info->nr_global_roots, &index);
2695f7238e50SJosef Bacik 	return index;
2696f7238e50SJosef Bacik }
2697f7238e50SJosef Bacik 
269879bd3712SFilipe Manana struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
26995758d1bdSFilipe Manana 						 u64 type,
270079bd3712SFilipe Manana 						 u64 chunk_offset, u64 size)
27014358d963SJosef Bacik {
27024358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
270332da5386SDavid Sterba 	struct btrfs_block_group *cache;
27044358d963SJosef Bacik 	int ret;
27054358d963SJosef Bacik 
27064358d963SJosef Bacik 	btrfs_set_log_full_commit(trans);
27074358d963SJosef Bacik 
27089afc6649SQu Wenruo 	cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
27094358d963SJosef Bacik 	if (!cache)
271079bd3712SFilipe Manana 		return ERR_PTR(-ENOMEM);
27114358d963SJosef Bacik 
2712*0657b20cSFilipe Manana 	/*
2713*0657b20cSFilipe Manana 	 * Mark it as new before adding it to the rbtree of block groups or any
2714*0657b20cSFilipe Manana 	 * list, so that no other task finds it and calls btrfs_mark_bg_unused()
2715*0657b20cSFilipe Manana 	 * before the new flag is set.
2716*0657b20cSFilipe Manana 	 */
2717*0657b20cSFilipe Manana 	set_bit(BLOCK_GROUP_FLAG_NEW, &cache->runtime_flags);
2718*0657b20cSFilipe Manana 
27199afc6649SQu Wenruo 	cache->length = size;
2720e3e39c72SMarcos Paulo de Souza 	set_free_space_tree_thresholds(cache);
27214358d963SJosef Bacik 	cache->flags = type;
27224358d963SJosef Bacik 	cache->cached = BTRFS_CACHE_FINISHED;
2723f7238e50SJosef Bacik 	cache->global_root_id = calculate_global_root_id(fs_info, cache->start);
2724f7238e50SJosef Bacik 
2725997e3e2eSBoris Burkov 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
27260d7764ffSDavid Sterba 		set_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE, &cache->runtime_flags);
272708e11a3dSNaohiro Aota 
2728a94794d5SNaohiro Aota 	ret = btrfs_load_block_group_zone_info(cache, true);
272908e11a3dSNaohiro Aota 	if (ret) {
273008e11a3dSNaohiro Aota 		btrfs_put_block_group(cache);
273179bd3712SFilipe Manana 		return ERR_PTR(ret);
273208e11a3dSNaohiro Aota 	}
273308e11a3dSNaohiro Aota 
27344358d963SJosef Bacik 	ret = exclude_super_stripes(cache);
27354358d963SJosef Bacik 	if (ret) {
27364358d963SJosef Bacik 		/* We may have excluded something, so call this just in case */
27374358d963SJosef Bacik 		btrfs_free_excluded_extents(cache);
27384358d963SJosef Bacik 		btrfs_put_block_group(cache);
273979bd3712SFilipe Manana 		return ERR_PTR(ret);
27404358d963SJosef Bacik 	}
27414358d963SJosef Bacik 
27424358d963SJosef Bacik 	add_new_free_space(cache, chunk_offset, chunk_offset + size);
27434358d963SJosef Bacik 
27444358d963SJosef Bacik 	btrfs_free_excluded_extents(cache);
27454358d963SJosef Bacik 
27464358d963SJosef Bacik 	/*
27474358d963SJosef Bacik 	 * Ensure the corresponding space_info object is created and
27484358d963SJosef Bacik 	 * assigned to our block group. We want our bg to be added to the rbtree
27494358d963SJosef Bacik 	 * with its ->space_info set.
27504358d963SJosef Bacik 	 */
27514358d963SJosef Bacik 	cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
27524358d963SJosef Bacik 	ASSERT(cache->space_info);
27534358d963SJosef Bacik 
27544358d963SJosef Bacik 	ret = btrfs_add_block_group_cache(fs_info, cache);
27554358d963SJosef Bacik 	if (ret) {
27564358d963SJosef Bacik 		btrfs_remove_free_space_cache(cache);
27574358d963SJosef Bacik 		btrfs_put_block_group(cache);
275879bd3712SFilipe Manana 		return ERR_PTR(ret);
27594358d963SJosef Bacik 	}
27604358d963SJosef Bacik 
27614358d963SJosef Bacik 	/*
27624358d963SJosef Bacik 	 * Now that our block group has its ->space_info set and is inserted in
27634358d963SJosef Bacik 	 * the rbtree, update the space info's counters.
27644358d963SJosef Bacik 	 */
27654358d963SJosef Bacik 	trace_btrfs_add_block_group(fs_info, cache, 1);
2766723de71dSJosef Bacik 	btrfs_add_bg_to_space_info(fs_info, cache);
27674358d963SJosef Bacik 	btrfs_update_global_block_rsv(fs_info);
27684358d963SJosef Bacik 
27699d4b0a12SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
27709d4b0a12SJosef Bacik 	if (btrfs_should_fragment_free_space(cache)) {
27715758d1bdSFilipe Manana 		cache->space_info->bytes_used += size >> 1;
27729d4b0a12SJosef Bacik 		fragment_free_space(cache);
27739d4b0a12SJosef Bacik 	}
27749d4b0a12SJosef Bacik #endif
27754358d963SJosef Bacik 
27764358d963SJosef Bacik 	list_add_tail(&cache->bg_list, &trans->new_bgs);
27774358d963SJosef Bacik 	trans->delayed_ref_updates++;
27784358d963SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
27794358d963SJosef Bacik 
27804358d963SJosef Bacik 	set_avail_alloc_bits(fs_info, type);
278179bd3712SFilipe Manana 	return cache;
27824358d963SJosef Bacik }
278326ce2095SJosef Bacik 
2784b12de528SQu Wenruo /*
2785b12de528SQu Wenruo  * Mark one block group RO, can be called several times for the same block
2786b12de528SQu Wenruo  * group.
2787b12de528SQu Wenruo  *
2788b12de528SQu Wenruo  * @cache:		the destination block group
2789b12de528SQu Wenruo  * @do_chunk_alloc:	whether need to do chunk pre-allocation, this is to
2790b12de528SQu Wenruo  * 			ensure we still have some free space after marking this
2791b12de528SQu Wenruo  * 			block group RO.
2792b12de528SQu Wenruo  */
2793b12de528SQu Wenruo int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2794b12de528SQu Wenruo 			     bool do_chunk_alloc)
279526ce2095SJosef Bacik {
279626ce2095SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
279726ce2095SJosef Bacik 	struct btrfs_trans_handle *trans;
2798dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
279926ce2095SJosef Bacik 	u64 alloc_flags;
280026ce2095SJosef Bacik 	int ret;
2801b6e9f16cSNikolay Borisov 	bool dirty_bg_running;
280226ce2095SJosef Bacik 
28032d192fc4SQu Wenruo 	/*
28042d192fc4SQu Wenruo 	 * This can only happen when we are doing read-only scrub on read-only
28052d192fc4SQu Wenruo 	 * mount.
28062d192fc4SQu Wenruo 	 * In that case we should not start a new transaction on read-only fs.
28072d192fc4SQu Wenruo 	 * Thus here we skip all chunk allocations.
28082d192fc4SQu Wenruo 	 */
28092d192fc4SQu Wenruo 	if (sb_rdonly(fs_info->sb)) {
28102d192fc4SQu Wenruo 		mutex_lock(&fs_info->ro_block_group_mutex);
28112d192fc4SQu Wenruo 		ret = inc_block_group_ro(cache, 0);
28122d192fc4SQu Wenruo 		mutex_unlock(&fs_info->ro_block_group_mutex);
28132d192fc4SQu Wenruo 		return ret;
28142d192fc4SQu Wenruo 	}
28152d192fc4SQu Wenruo 
2816b6e9f16cSNikolay Borisov 	do {
2817dfe8aec4SJosef Bacik 		trans = btrfs_join_transaction(root);
281826ce2095SJosef Bacik 		if (IS_ERR(trans))
281926ce2095SJosef Bacik 			return PTR_ERR(trans);
282026ce2095SJosef Bacik 
2821b6e9f16cSNikolay Borisov 		dirty_bg_running = false;
2822b6e9f16cSNikolay Borisov 
282326ce2095SJosef Bacik 		/*
2824b6e9f16cSNikolay Borisov 		 * We're not allowed to set block groups readonly after the dirty
2825b6e9f16cSNikolay Borisov 		 * block group cache has started writing.  If it already started,
2826b6e9f16cSNikolay Borisov 		 * back off and let this transaction commit.
282726ce2095SJosef Bacik 		 */
282826ce2095SJosef Bacik 		mutex_lock(&fs_info->ro_block_group_mutex);
282926ce2095SJosef Bacik 		if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
283026ce2095SJosef Bacik 			u64 transid = trans->transid;
283126ce2095SJosef Bacik 
283226ce2095SJosef Bacik 			mutex_unlock(&fs_info->ro_block_group_mutex);
283326ce2095SJosef Bacik 			btrfs_end_transaction(trans);
283426ce2095SJosef Bacik 
283526ce2095SJosef Bacik 			ret = btrfs_wait_for_commit(fs_info, transid);
283626ce2095SJosef Bacik 			if (ret)
283726ce2095SJosef Bacik 				return ret;
2838b6e9f16cSNikolay Borisov 			dirty_bg_running = true;
283926ce2095SJosef Bacik 		}
2840b6e9f16cSNikolay Borisov 	} while (dirty_bg_running);
284126ce2095SJosef Bacik 
2842b12de528SQu Wenruo 	if (do_chunk_alloc) {
284326ce2095SJosef Bacik 		/*
2844b12de528SQu Wenruo 		 * If we are changing raid levels, try to allocate a
2845b12de528SQu Wenruo 		 * corresponding block group with the new raid level.
284626ce2095SJosef Bacik 		 */
2847349e120eSJosef Bacik 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
284826ce2095SJosef Bacik 		if (alloc_flags != cache->flags) {
2849b12de528SQu Wenruo 			ret = btrfs_chunk_alloc(trans, alloc_flags,
2850b12de528SQu Wenruo 						CHUNK_ALLOC_FORCE);
285126ce2095SJosef Bacik 			/*
285226ce2095SJosef Bacik 			 * ENOSPC is allowed here, we may have enough space
2853b12de528SQu Wenruo 			 * already allocated at the new raid level to carry on
285426ce2095SJosef Bacik 			 */
285526ce2095SJosef Bacik 			if (ret == -ENOSPC)
285626ce2095SJosef Bacik 				ret = 0;
285726ce2095SJosef Bacik 			if (ret < 0)
285826ce2095SJosef Bacik 				goto out;
285926ce2095SJosef Bacik 		}
2860b12de528SQu Wenruo 	}
286126ce2095SJosef Bacik 
2862a7a63accSJosef Bacik 	ret = inc_block_group_ro(cache, 0);
286326ce2095SJosef Bacik 	if (!ret)
286426ce2095SJosef Bacik 		goto out;
28657561551eSQu Wenruo 	if (ret == -ETXTBSY)
28667561551eSQu Wenruo 		goto unlock_out;
28677561551eSQu Wenruo 
28687561551eSQu Wenruo 	/*
28697561551eSQu Wenruo 	 * Skip chunk alloction if the bg is SYSTEM, this is to avoid system
28707561551eSQu Wenruo 	 * chunk allocation storm to exhaust the system chunk array.  Otherwise
28717561551eSQu Wenruo 	 * we still want to try our best to mark the block group read-only.
28727561551eSQu Wenruo 	 */
28737561551eSQu Wenruo 	if (!do_chunk_alloc && ret == -ENOSPC &&
28747561551eSQu Wenruo 	    (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM))
28757561551eSQu Wenruo 		goto unlock_out;
28767561551eSQu Wenruo 
287726ce2095SJosef Bacik 	alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
287826ce2095SJosef Bacik 	ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
287926ce2095SJosef Bacik 	if (ret < 0)
288026ce2095SJosef Bacik 		goto out;
2881b6a98021SNaohiro Aota 	/*
2882b6a98021SNaohiro Aota 	 * We have allocated a new chunk. We also need to activate that chunk to
2883b6a98021SNaohiro Aota 	 * grant metadata tickets for zoned filesystem.
2884b6a98021SNaohiro Aota 	 */
2885b6a98021SNaohiro Aota 	ret = btrfs_zoned_activate_one_bg(fs_info, cache->space_info, true);
2886b6a98021SNaohiro Aota 	if (ret < 0)
2887b6a98021SNaohiro Aota 		goto out;
2888b6a98021SNaohiro Aota 
2889e11c0406SJosef Bacik 	ret = inc_block_group_ro(cache, 0);
2890195a49eaSFilipe Manana 	if (ret == -ETXTBSY)
2891195a49eaSFilipe Manana 		goto unlock_out;
289226ce2095SJosef Bacik out:
289326ce2095SJosef Bacik 	if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2894349e120eSJosef Bacik 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
289526ce2095SJosef Bacik 		mutex_lock(&fs_info->chunk_mutex);
289626ce2095SJosef Bacik 		check_system_chunk(trans, alloc_flags);
289726ce2095SJosef Bacik 		mutex_unlock(&fs_info->chunk_mutex);
289826ce2095SJosef Bacik 	}
2899b12de528SQu Wenruo unlock_out:
290026ce2095SJosef Bacik 	mutex_unlock(&fs_info->ro_block_group_mutex);
290126ce2095SJosef Bacik 
290226ce2095SJosef Bacik 	btrfs_end_transaction(trans);
290326ce2095SJosef Bacik 	return ret;
290426ce2095SJosef Bacik }
290526ce2095SJosef Bacik 
290632da5386SDavid Sterba void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
290726ce2095SJosef Bacik {
290826ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
290926ce2095SJosef Bacik 	u64 num_bytes;
291026ce2095SJosef Bacik 
291126ce2095SJosef Bacik 	BUG_ON(!cache->ro);
291226ce2095SJosef Bacik 
291326ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
291426ce2095SJosef Bacik 	spin_lock(&cache->lock);
291526ce2095SJosef Bacik 	if (!--cache->ro) {
2916169e0da9SNaohiro Aota 		if (btrfs_is_zoned(cache->fs_info)) {
2917169e0da9SNaohiro Aota 			/* Migrate zone_unusable bytes back */
291898173255SNaohiro Aota 			cache->zone_unusable =
291998173255SNaohiro Aota 				(cache->alloc_offset - cache->used) +
292098173255SNaohiro Aota 				(cache->length - cache->zone_capacity);
2921169e0da9SNaohiro Aota 			sinfo->bytes_zone_unusable += cache->zone_unusable;
2922169e0da9SNaohiro Aota 			sinfo->bytes_readonly -= cache->zone_unusable;
2923169e0da9SNaohiro Aota 		}
2924f9f28e5bSNaohiro Aota 		num_bytes = cache->length - cache->reserved -
2925f9f28e5bSNaohiro Aota 			    cache->pinned - cache->bytes_super -
2926f9f28e5bSNaohiro Aota 			    cache->zone_unusable - cache->used;
2927f9f28e5bSNaohiro Aota 		sinfo->bytes_readonly -= num_bytes;
292826ce2095SJosef Bacik 		list_del_init(&cache->ro_list);
292926ce2095SJosef Bacik 	}
293026ce2095SJosef Bacik 	spin_unlock(&cache->lock);
293126ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
293226ce2095SJosef Bacik }
293377745c05SJosef Bacik 
29343be4d8efSQu Wenruo static int update_block_group_item(struct btrfs_trans_handle *trans,
293577745c05SJosef Bacik 				   struct btrfs_path *path,
293632da5386SDavid Sterba 				   struct btrfs_block_group *cache)
293777745c05SJosef Bacik {
293877745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
293977745c05SJosef Bacik 	int ret;
2940dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
294177745c05SJosef Bacik 	unsigned long bi;
294277745c05SJosef Bacik 	struct extent_buffer *leaf;
2943bf38be65SDavid Sterba 	struct btrfs_block_group_item bgi;
2944b3470b5dSDavid Sterba 	struct btrfs_key key;
29457248e0ceSQu Wenruo 	u64 old_commit_used;
29467248e0ceSQu Wenruo 	u64 used;
29477248e0ceSQu Wenruo 
29487248e0ceSQu Wenruo 	/*
29497248e0ceSQu Wenruo 	 * Block group items update can be triggered out of commit transaction
29507248e0ceSQu Wenruo 	 * critical section, thus we need a consistent view of used bytes.
29517248e0ceSQu Wenruo 	 * We cannot use cache->used directly outside of the spin lock, as it
29527248e0ceSQu Wenruo 	 * may be changed.
29537248e0ceSQu Wenruo 	 */
29547248e0ceSQu Wenruo 	spin_lock(&cache->lock);
29557248e0ceSQu Wenruo 	old_commit_used = cache->commit_used;
29567248e0ceSQu Wenruo 	used = cache->used;
29577248e0ceSQu Wenruo 	/* No change in used bytes, can safely skip it. */
29587248e0ceSQu Wenruo 	if (cache->commit_used == used) {
29597248e0ceSQu Wenruo 		spin_unlock(&cache->lock);
29607248e0ceSQu Wenruo 		return 0;
29617248e0ceSQu Wenruo 	}
29627248e0ceSQu Wenruo 	cache->commit_used = used;
29637248e0ceSQu Wenruo 	spin_unlock(&cache->lock);
296477745c05SJosef Bacik 
2965b3470b5dSDavid Sterba 	key.objectid = cache->start;
2966b3470b5dSDavid Sterba 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2967b3470b5dSDavid Sterba 	key.offset = cache->length;
2968b3470b5dSDavid Sterba 
29693be4d8efSQu Wenruo 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
297077745c05SJosef Bacik 	if (ret) {
297177745c05SJosef Bacik 		if (ret > 0)
297277745c05SJosef Bacik 			ret = -ENOENT;
297377745c05SJosef Bacik 		goto fail;
297477745c05SJosef Bacik 	}
297577745c05SJosef Bacik 
297677745c05SJosef Bacik 	leaf = path->nodes[0];
297777745c05SJosef Bacik 	bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
29787248e0ceSQu Wenruo 	btrfs_set_stack_block_group_used(&bgi, used);
2979de0dc456SDavid Sterba 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
2980f7238e50SJosef Bacik 						   cache->global_root_id);
2981de0dc456SDavid Sterba 	btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2982bf38be65SDavid Sterba 	write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
298377745c05SJosef Bacik 	btrfs_mark_buffer_dirty(leaf);
298477745c05SJosef Bacik fail:
298577745c05SJosef Bacik 	btrfs_release_path(path);
29867248e0ceSQu Wenruo 	/* We didn't update the block group item, need to revert @commit_used. */
29877248e0ceSQu Wenruo 	if (ret < 0) {
29887248e0ceSQu Wenruo 		spin_lock(&cache->lock);
29897248e0ceSQu Wenruo 		cache->commit_used = old_commit_used;
29907248e0ceSQu Wenruo 		spin_unlock(&cache->lock);
29917248e0ceSQu Wenruo 	}
299277745c05SJosef Bacik 	return ret;
299377745c05SJosef Bacik 
299477745c05SJosef Bacik }
299577745c05SJosef Bacik 
299632da5386SDavid Sterba static int cache_save_setup(struct btrfs_block_group *block_group,
299777745c05SJosef Bacik 			    struct btrfs_trans_handle *trans,
299877745c05SJosef Bacik 			    struct btrfs_path *path)
299977745c05SJosef Bacik {
300077745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
300177745c05SJosef Bacik 	struct btrfs_root *root = fs_info->tree_root;
300277745c05SJosef Bacik 	struct inode *inode = NULL;
300377745c05SJosef Bacik 	struct extent_changeset *data_reserved = NULL;
300477745c05SJosef Bacik 	u64 alloc_hint = 0;
300577745c05SJosef Bacik 	int dcs = BTRFS_DC_ERROR;
30060044ae11SQu Wenruo 	u64 cache_size = 0;
300777745c05SJosef Bacik 	int retries = 0;
300877745c05SJosef Bacik 	int ret = 0;
300977745c05SJosef Bacik 
3010af456a2cSBoris Burkov 	if (!btrfs_test_opt(fs_info, SPACE_CACHE))
3011af456a2cSBoris Burkov 		return 0;
3012af456a2cSBoris Burkov 
301377745c05SJosef Bacik 	/*
301477745c05SJosef Bacik 	 * If this block group is smaller than 100 megs don't bother caching the
301577745c05SJosef Bacik 	 * block group.
301677745c05SJosef Bacik 	 */
3017b3470b5dSDavid Sterba 	if (block_group->length < (100 * SZ_1M)) {
301877745c05SJosef Bacik 		spin_lock(&block_group->lock);
301977745c05SJosef Bacik 		block_group->disk_cache_state = BTRFS_DC_WRITTEN;
302077745c05SJosef Bacik 		spin_unlock(&block_group->lock);
302177745c05SJosef Bacik 		return 0;
302277745c05SJosef Bacik 	}
302377745c05SJosef Bacik 
3024bf31f87fSDavid Sterba 	if (TRANS_ABORTED(trans))
302577745c05SJosef Bacik 		return 0;
302677745c05SJosef Bacik again:
302777745c05SJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
302877745c05SJosef Bacik 	if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
302977745c05SJosef Bacik 		ret = PTR_ERR(inode);
303077745c05SJosef Bacik 		btrfs_release_path(path);
303177745c05SJosef Bacik 		goto out;
303277745c05SJosef Bacik 	}
303377745c05SJosef Bacik 
303477745c05SJosef Bacik 	if (IS_ERR(inode)) {
303577745c05SJosef Bacik 		BUG_ON(retries);
303677745c05SJosef Bacik 		retries++;
303777745c05SJosef Bacik 
303877745c05SJosef Bacik 		if (block_group->ro)
303977745c05SJosef Bacik 			goto out_free;
304077745c05SJosef Bacik 
304177745c05SJosef Bacik 		ret = create_free_space_inode(trans, block_group, path);
304277745c05SJosef Bacik 		if (ret)
304377745c05SJosef Bacik 			goto out_free;
304477745c05SJosef Bacik 		goto again;
304577745c05SJosef Bacik 	}
304677745c05SJosef Bacik 
304777745c05SJosef Bacik 	/*
304877745c05SJosef Bacik 	 * We want to set the generation to 0, that way if anything goes wrong
304977745c05SJosef Bacik 	 * from here on out we know not to trust this cache when we load up next
305077745c05SJosef Bacik 	 * time.
305177745c05SJosef Bacik 	 */
305277745c05SJosef Bacik 	BTRFS_I(inode)->generation = 0;
30539a56fcd1SNikolay Borisov 	ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
305477745c05SJosef Bacik 	if (ret) {
305577745c05SJosef Bacik 		/*
305677745c05SJosef Bacik 		 * So theoretically we could recover from this, simply set the
305777745c05SJosef Bacik 		 * super cache generation to 0 so we know to invalidate the
305877745c05SJosef Bacik 		 * cache, but then we'd have to keep track of the block groups
305977745c05SJosef Bacik 		 * that fail this way so we know we _have_ to reset this cache
306077745c05SJosef Bacik 		 * before the next commit or risk reading stale cache.  So to
306177745c05SJosef Bacik 		 * limit our exposure to horrible edge cases lets just abort the
306277745c05SJosef Bacik 		 * transaction, this only happens in really bad situations
306377745c05SJosef Bacik 		 * anyway.
306477745c05SJosef Bacik 		 */
306577745c05SJosef Bacik 		btrfs_abort_transaction(trans, ret);
306677745c05SJosef Bacik 		goto out_put;
306777745c05SJosef Bacik 	}
306877745c05SJosef Bacik 	WARN_ON(ret);
306977745c05SJosef Bacik 
307077745c05SJosef Bacik 	/* We've already setup this transaction, go ahead and exit */
307177745c05SJosef Bacik 	if (block_group->cache_generation == trans->transid &&
307277745c05SJosef Bacik 	    i_size_read(inode)) {
307377745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
307477745c05SJosef Bacik 		goto out_put;
307577745c05SJosef Bacik 	}
307677745c05SJosef Bacik 
307777745c05SJosef Bacik 	if (i_size_read(inode) > 0) {
307877745c05SJosef Bacik 		ret = btrfs_check_trunc_cache_free_space(fs_info,
307977745c05SJosef Bacik 					&fs_info->global_block_rsv);
308077745c05SJosef Bacik 		if (ret)
308177745c05SJosef Bacik 			goto out_put;
308277745c05SJosef Bacik 
308377745c05SJosef Bacik 		ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
308477745c05SJosef Bacik 		if (ret)
308577745c05SJosef Bacik 			goto out_put;
308677745c05SJosef Bacik 	}
308777745c05SJosef Bacik 
308877745c05SJosef Bacik 	spin_lock(&block_group->lock);
308977745c05SJosef Bacik 	if (block_group->cached != BTRFS_CACHE_FINISHED ||
309077745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE)) {
309177745c05SJosef Bacik 		/*
309277745c05SJosef Bacik 		 * don't bother trying to write stuff out _if_
309377745c05SJosef Bacik 		 * a) we're not cached,
309477745c05SJosef Bacik 		 * b) we're with nospace_cache mount option,
309577745c05SJosef Bacik 		 * c) we're with v2 space_cache (FREE_SPACE_TREE).
309677745c05SJosef Bacik 		 */
309777745c05SJosef Bacik 		dcs = BTRFS_DC_WRITTEN;
309877745c05SJosef Bacik 		spin_unlock(&block_group->lock);
309977745c05SJosef Bacik 		goto out_put;
310077745c05SJosef Bacik 	}
310177745c05SJosef Bacik 	spin_unlock(&block_group->lock);
310277745c05SJosef Bacik 
310377745c05SJosef Bacik 	/*
310477745c05SJosef Bacik 	 * We hit an ENOSPC when setting up the cache in this transaction, just
310577745c05SJosef Bacik 	 * skip doing the setup, we've already cleared the cache so we're safe.
310677745c05SJosef Bacik 	 */
310777745c05SJosef Bacik 	if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
310877745c05SJosef Bacik 		ret = -ENOSPC;
310977745c05SJosef Bacik 		goto out_put;
311077745c05SJosef Bacik 	}
311177745c05SJosef Bacik 
311277745c05SJosef Bacik 	/*
311377745c05SJosef Bacik 	 * Try to preallocate enough space based on how big the block group is.
311477745c05SJosef Bacik 	 * Keep in mind this has to include any pinned space which could end up
311577745c05SJosef Bacik 	 * taking up quite a bit since it's not folded into the other space
311677745c05SJosef Bacik 	 * cache.
311777745c05SJosef Bacik 	 */
31180044ae11SQu Wenruo 	cache_size = div_u64(block_group->length, SZ_256M);
31190044ae11SQu Wenruo 	if (!cache_size)
31200044ae11SQu Wenruo 		cache_size = 1;
312177745c05SJosef Bacik 
31220044ae11SQu Wenruo 	cache_size *= 16;
31230044ae11SQu Wenruo 	cache_size *= fs_info->sectorsize;
312477745c05SJosef Bacik 
312536ea6f3eSNikolay Borisov 	ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
31261daedb1dSJosef Bacik 					  cache_size, false);
312777745c05SJosef Bacik 	if (ret)
312877745c05SJosef Bacik 		goto out_put;
312977745c05SJosef Bacik 
31300044ae11SQu Wenruo 	ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
31310044ae11SQu Wenruo 					      cache_size, cache_size,
313277745c05SJosef Bacik 					      &alloc_hint);
313377745c05SJosef Bacik 	/*
313477745c05SJosef Bacik 	 * Our cache requires contiguous chunks so that we don't modify a bunch
313577745c05SJosef Bacik 	 * of metadata or split extents when writing the cache out, which means
313677745c05SJosef Bacik 	 * we can enospc if we are heavily fragmented in addition to just normal
313777745c05SJosef Bacik 	 * out of space conditions.  So if we hit this just skip setting up any
313877745c05SJosef Bacik 	 * other block groups for this transaction, maybe we'll unpin enough
313977745c05SJosef Bacik 	 * space the next time around.
314077745c05SJosef Bacik 	 */
314177745c05SJosef Bacik 	if (!ret)
314277745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
314377745c05SJosef Bacik 	else if (ret == -ENOSPC)
314477745c05SJosef Bacik 		set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
314577745c05SJosef Bacik 
314677745c05SJosef Bacik out_put:
314777745c05SJosef Bacik 	iput(inode);
314877745c05SJosef Bacik out_free:
314977745c05SJosef Bacik 	btrfs_release_path(path);
315077745c05SJosef Bacik out:
315177745c05SJosef Bacik 	spin_lock(&block_group->lock);
315277745c05SJosef Bacik 	if (!ret && dcs == BTRFS_DC_SETUP)
315377745c05SJosef Bacik 		block_group->cache_generation = trans->transid;
315477745c05SJosef Bacik 	block_group->disk_cache_state = dcs;
315577745c05SJosef Bacik 	spin_unlock(&block_group->lock);
315677745c05SJosef Bacik 
315777745c05SJosef Bacik 	extent_changeset_free(data_reserved);
315877745c05SJosef Bacik 	return ret;
315977745c05SJosef Bacik }
316077745c05SJosef Bacik 
316177745c05SJosef Bacik int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
316277745c05SJosef Bacik {
316377745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
316432da5386SDavid Sterba 	struct btrfs_block_group *cache, *tmp;
316577745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
316677745c05SJosef Bacik 	struct btrfs_path *path;
316777745c05SJosef Bacik 
316877745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs) ||
316977745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE))
317077745c05SJosef Bacik 		return 0;
317177745c05SJosef Bacik 
317277745c05SJosef Bacik 	path = btrfs_alloc_path();
317377745c05SJosef Bacik 	if (!path)
317477745c05SJosef Bacik 		return -ENOMEM;
317577745c05SJosef Bacik 
317677745c05SJosef Bacik 	/* Could add new block groups, use _safe just in case */
317777745c05SJosef Bacik 	list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
317877745c05SJosef Bacik 				 dirty_list) {
317977745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_CLEAR)
318077745c05SJosef Bacik 			cache_save_setup(cache, trans, path);
318177745c05SJosef Bacik 	}
318277745c05SJosef Bacik 
318377745c05SJosef Bacik 	btrfs_free_path(path);
318477745c05SJosef Bacik 	return 0;
318577745c05SJosef Bacik }
318677745c05SJosef Bacik 
318777745c05SJosef Bacik /*
318877745c05SJosef Bacik  * Transaction commit does final block group cache writeback during a critical
318977745c05SJosef Bacik  * section where nothing is allowed to change the FS.  This is required in
319077745c05SJosef Bacik  * order for the cache to actually match the block group, but can introduce a
319177745c05SJosef Bacik  * lot of latency into the commit.
319277745c05SJosef Bacik  *
319377745c05SJosef Bacik  * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
319477745c05SJosef Bacik  * There's a chance we'll have to redo some of it if the block group changes
319577745c05SJosef Bacik  * again during the commit, but it greatly reduces the commit latency by
319677745c05SJosef Bacik  * getting rid of the easy block groups while we're still allowing others to
319777745c05SJosef Bacik  * join the commit.
319877745c05SJosef Bacik  */
319977745c05SJosef Bacik int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
320077745c05SJosef Bacik {
320177745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
320232da5386SDavid Sterba 	struct btrfs_block_group *cache;
320377745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
320477745c05SJosef Bacik 	int ret = 0;
320577745c05SJosef Bacik 	int should_put;
320677745c05SJosef Bacik 	struct btrfs_path *path = NULL;
320777745c05SJosef Bacik 	LIST_HEAD(dirty);
320877745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
320977745c05SJosef Bacik 	int loops = 0;
321077745c05SJosef Bacik 
321177745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
321277745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs)) {
321377745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
321477745c05SJosef Bacik 		return 0;
321577745c05SJosef Bacik 	}
321677745c05SJosef Bacik 	list_splice_init(&cur_trans->dirty_bgs, &dirty);
321777745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
321877745c05SJosef Bacik 
321977745c05SJosef Bacik again:
322077745c05SJosef Bacik 	/* Make sure all the block groups on our dirty list actually exist */
322177745c05SJosef Bacik 	btrfs_create_pending_block_groups(trans);
322277745c05SJosef Bacik 
322377745c05SJosef Bacik 	if (!path) {
322477745c05SJosef Bacik 		path = btrfs_alloc_path();
3225938fcbfbSJosef Bacik 		if (!path) {
3226938fcbfbSJosef Bacik 			ret = -ENOMEM;
3227938fcbfbSJosef Bacik 			goto out;
3228938fcbfbSJosef Bacik 		}
322977745c05SJosef Bacik 	}
323077745c05SJosef Bacik 
323177745c05SJosef Bacik 	/*
323277745c05SJosef Bacik 	 * cache_write_mutex is here only to save us from balance or automatic
323377745c05SJosef Bacik 	 * removal of empty block groups deleting this block group while we are
323477745c05SJosef Bacik 	 * writing out the cache
323577745c05SJosef Bacik 	 */
323677745c05SJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
323777745c05SJosef Bacik 	while (!list_empty(&dirty)) {
323877745c05SJosef Bacik 		bool drop_reserve = true;
323977745c05SJosef Bacik 
324032da5386SDavid Sterba 		cache = list_first_entry(&dirty, struct btrfs_block_group,
324177745c05SJosef Bacik 					 dirty_list);
324277745c05SJosef Bacik 		/*
324377745c05SJosef Bacik 		 * This can happen if something re-dirties a block group that
324477745c05SJosef Bacik 		 * is already under IO.  Just wait for it to finish and then do
324577745c05SJosef Bacik 		 * it all again
324677745c05SJosef Bacik 		 */
324777745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
324877745c05SJosef Bacik 			list_del_init(&cache->io_list);
324977745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
325077745c05SJosef Bacik 			btrfs_put_block_group(cache);
325177745c05SJosef Bacik 		}
325277745c05SJosef Bacik 
325377745c05SJosef Bacik 
325477745c05SJosef Bacik 		/*
325577745c05SJosef Bacik 		 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
325677745c05SJosef Bacik 		 * it should update the cache_state.  Don't delete until after
325777745c05SJosef Bacik 		 * we wait.
325877745c05SJosef Bacik 		 *
325977745c05SJosef Bacik 		 * Since we're not running in the commit critical section
326077745c05SJosef Bacik 		 * we need the dirty_bgs_lock to protect from update_block_group
326177745c05SJosef Bacik 		 */
326277745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
326377745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
326477745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
326577745c05SJosef Bacik 
326677745c05SJosef Bacik 		should_put = 1;
326777745c05SJosef Bacik 
326877745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
326977745c05SJosef Bacik 
327077745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_SETUP) {
327177745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
327277745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
327377745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
327477745c05SJosef Bacik 				should_put = 0;
327577745c05SJosef Bacik 
327677745c05SJosef Bacik 				/*
327777745c05SJosef Bacik 				 * The cache_write_mutex is protecting the
327877745c05SJosef Bacik 				 * io_list, also refer to the definition of
327977745c05SJosef Bacik 				 * btrfs_transaction::io_bgs for more details
328077745c05SJosef Bacik 				 */
328177745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
328277745c05SJosef Bacik 			} else {
328377745c05SJosef Bacik 				/*
328477745c05SJosef Bacik 				 * If we failed to write the cache, the
328577745c05SJosef Bacik 				 * generation will be bad and life goes on
328677745c05SJosef Bacik 				 */
328777745c05SJosef Bacik 				ret = 0;
328877745c05SJosef Bacik 			}
328977745c05SJosef Bacik 		}
329077745c05SJosef Bacik 		if (!ret) {
32913be4d8efSQu Wenruo 			ret = update_block_group_item(trans, path, cache);
329277745c05SJosef Bacik 			/*
329377745c05SJosef Bacik 			 * Our block group might still be attached to the list
329477745c05SJosef Bacik 			 * of new block groups in the transaction handle of some
329577745c05SJosef Bacik 			 * other task (struct btrfs_trans_handle->new_bgs). This
329677745c05SJosef Bacik 			 * means its block group item isn't yet in the extent
329777745c05SJosef Bacik 			 * tree. If this happens ignore the error, as we will
329877745c05SJosef Bacik 			 * try again later in the critical section of the
329977745c05SJosef Bacik 			 * transaction commit.
330077745c05SJosef Bacik 			 */
330177745c05SJosef Bacik 			if (ret == -ENOENT) {
330277745c05SJosef Bacik 				ret = 0;
330377745c05SJosef Bacik 				spin_lock(&cur_trans->dirty_bgs_lock);
330477745c05SJosef Bacik 				if (list_empty(&cache->dirty_list)) {
330577745c05SJosef Bacik 					list_add_tail(&cache->dirty_list,
330677745c05SJosef Bacik 						      &cur_trans->dirty_bgs);
330777745c05SJosef Bacik 					btrfs_get_block_group(cache);
330877745c05SJosef Bacik 					drop_reserve = false;
330977745c05SJosef Bacik 				}
331077745c05SJosef Bacik 				spin_unlock(&cur_trans->dirty_bgs_lock);
331177745c05SJosef Bacik 			} else if (ret) {
331277745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
331377745c05SJosef Bacik 			}
331477745c05SJosef Bacik 		}
331577745c05SJosef Bacik 
331677745c05SJosef Bacik 		/* If it's not on the io list, we need to put the block group */
331777745c05SJosef Bacik 		if (should_put)
331877745c05SJosef Bacik 			btrfs_put_block_group(cache);
331977745c05SJosef Bacik 		if (drop_reserve)
332077745c05SJosef Bacik 			btrfs_delayed_refs_rsv_release(fs_info, 1);
332177745c05SJosef Bacik 		/*
332277745c05SJosef Bacik 		 * Avoid blocking other tasks for too long. It might even save
332377745c05SJosef Bacik 		 * us from writing caches for block groups that are going to be
332477745c05SJosef Bacik 		 * removed.
332577745c05SJosef Bacik 		 */
332677745c05SJosef Bacik 		mutex_unlock(&trans->transaction->cache_write_mutex);
3327938fcbfbSJosef Bacik 		if (ret)
3328938fcbfbSJosef Bacik 			goto out;
332977745c05SJosef Bacik 		mutex_lock(&trans->transaction->cache_write_mutex);
333077745c05SJosef Bacik 	}
333177745c05SJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
333277745c05SJosef Bacik 
333377745c05SJosef Bacik 	/*
333477745c05SJosef Bacik 	 * Go through delayed refs for all the stuff we've just kicked off
333577745c05SJosef Bacik 	 * and then loop back (just once)
333677745c05SJosef Bacik 	 */
333734d1eb0eSJosef Bacik 	if (!ret)
333877745c05SJosef Bacik 		ret = btrfs_run_delayed_refs(trans, 0);
333977745c05SJosef Bacik 	if (!ret && loops == 0) {
334077745c05SJosef Bacik 		loops++;
334177745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
334277745c05SJosef Bacik 		list_splice_init(&cur_trans->dirty_bgs, &dirty);
334377745c05SJosef Bacik 		/*
334477745c05SJosef Bacik 		 * dirty_bgs_lock protects us from concurrent block group
334577745c05SJosef Bacik 		 * deletes too (not just cache_write_mutex).
334677745c05SJosef Bacik 		 */
334777745c05SJosef Bacik 		if (!list_empty(&dirty)) {
334877745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
334977745c05SJosef Bacik 			goto again;
335077745c05SJosef Bacik 		}
335177745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
3352938fcbfbSJosef Bacik 	}
3353938fcbfbSJosef Bacik out:
3354938fcbfbSJosef Bacik 	if (ret < 0) {
3355938fcbfbSJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
3356938fcbfbSJosef Bacik 		list_splice_init(&dirty, &cur_trans->dirty_bgs);
3357938fcbfbSJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
335877745c05SJosef Bacik 		btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
335977745c05SJosef Bacik 	}
336077745c05SJosef Bacik 
336177745c05SJosef Bacik 	btrfs_free_path(path);
336277745c05SJosef Bacik 	return ret;
336377745c05SJosef Bacik }
336477745c05SJosef Bacik 
336577745c05SJosef Bacik int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
336677745c05SJosef Bacik {
336777745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
336832da5386SDavid Sterba 	struct btrfs_block_group *cache;
336977745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
337077745c05SJosef Bacik 	int ret = 0;
337177745c05SJosef Bacik 	int should_put;
337277745c05SJosef Bacik 	struct btrfs_path *path;
337377745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
337477745c05SJosef Bacik 
337577745c05SJosef Bacik 	path = btrfs_alloc_path();
337677745c05SJosef Bacik 	if (!path)
337777745c05SJosef Bacik 		return -ENOMEM;
337877745c05SJosef Bacik 
337977745c05SJosef Bacik 	/*
338077745c05SJosef Bacik 	 * Even though we are in the critical section of the transaction commit,
338177745c05SJosef Bacik 	 * we can still have concurrent tasks adding elements to this
338277745c05SJosef Bacik 	 * transaction's list of dirty block groups. These tasks correspond to
338377745c05SJosef Bacik 	 * endio free space workers started when writeback finishes for a
338477745c05SJosef Bacik 	 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
338577745c05SJosef Bacik 	 * allocate new block groups as a result of COWing nodes of the root
338677745c05SJosef Bacik 	 * tree when updating the free space inode. The writeback for the space
338777745c05SJosef Bacik 	 * caches is triggered by an earlier call to
338877745c05SJosef Bacik 	 * btrfs_start_dirty_block_groups() and iterations of the following
338977745c05SJosef Bacik 	 * loop.
339077745c05SJosef Bacik 	 * Also we want to do the cache_save_setup first and then run the
339177745c05SJosef Bacik 	 * delayed refs to make sure we have the best chance at doing this all
339277745c05SJosef Bacik 	 * in one shot.
339377745c05SJosef Bacik 	 */
339477745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
339577745c05SJosef Bacik 	while (!list_empty(&cur_trans->dirty_bgs)) {
339677745c05SJosef Bacik 		cache = list_first_entry(&cur_trans->dirty_bgs,
339732da5386SDavid Sterba 					 struct btrfs_block_group,
339877745c05SJosef Bacik 					 dirty_list);
339977745c05SJosef Bacik 
340077745c05SJosef Bacik 		/*
340177745c05SJosef Bacik 		 * This can happen if cache_save_setup re-dirties a block group
340277745c05SJosef Bacik 		 * that is already under IO.  Just wait for it to finish and
340377745c05SJosef Bacik 		 * then do it all again
340477745c05SJosef Bacik 		 */
340577745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
340677745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
340777745c05SJosef Bacik 			list_del_init(&cache->io_list);
340877745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
340977745c05SJosef Bacik 			btrfs_put_block_group(cache);
341077745c05SJosef Bacik 			spin_lock(&cur_trans->dirty_bgs_lock);
341177745c05SJosef Bacik 		}
341277745c05SJosef Bacik 
341377745c05SJosef Bacik 		/*
341477745c05SJosef Bacik 		 * Don't remove from the dirty list until after we've waited on
341577745c05SJosef Bacik 		 * any pending IO
341677745c05SJosef Bacik 		 */
341777745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
341877745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
341977745c05SJosef Bacik 		should_put = 1;
342077745c05SJosef Bacik 
342177745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
342277745c05SJosef Bacik 
342377745c05SJosef Bacik 		if (!ret)
342477745c05SJosef Bacik 			ret = btrfs_run_delayed_refs(trans,
342577745c05SJosef Bacik 						     (unsigned long) -1);
342677745c05SJosef Bacik 
342777745c05SJosef Bacik 		if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
342877745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
342977745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
343077745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
343177745c05SJosef Bacik 				should_put = 0;
343277745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
343377745c05SJosef Bacik 			} else {
343477745c05SJosef Bacik 				/*
343577745c05SJosef Bacik 				 * If we failed to write the cache, the
343677745c05SJosef Bacik 				 * generation will be bad and life goes on
343777745c05SJosef Bacik 				 */
343877745c05SJosef Bacik 				ret = 0;
343977745c05SJosef Bacik 			}
344077745c05SJosef Bacik 		}
344177745c05SJosef Bacik 		if (!ret) {
34423be4d8efSQu Wenruo 			ret = update_block_group_item(trans, path, cache);
344377745c05SJosef Bacik 			/*
344477745c05SJosef Bacik 			 * One of the free space endio workers might have
344577745c05SJosef Bacik 			 * created a new block group while updating a free space
344677745c05SJosef Bacik 			 * cache's inode (at inode.c:btrfs_finish_ordered_io())
344777745c05SJosef Bacik 			 * and hasn't released its transaction handle yet, in
344877745c05SJosef Bacik 			 * which case the new block group is still attached to
344977745c05SJosef Bacik 			 * its transaction handle and its creation has not
345077745c05SJosef Bacik 			 * finished yet (no block group item in the extent tree
345177745c05SJosef Bacik 			 * yet, etc). If this is the case, wait for all free
345277745c05SJosef Bacik 			 * space endio workers to finish and retry. This is a
3453260db43cSRandy Dunlap 			 * very rare case so no need for a more efficient and
345477745c05SJosef Bacik 			 * complex approach.
345577745c05SJosef Bacik 			 */
345677745c05SJosef Bacik 			if (ret == -ENOENT) {
345777745c05SJosef Bacik 				wait_event(cur_trans->writer_wait,
345877745c05SJosef Bacik 				   atomic_read(&cur_trans->num_writers) == 1);
34593be4d8efSQu Wenruo 				ret = update_block_group_item(trans, path, cache);
346077745c05SJosef Bacik 			}
346177745c05SJosef Bacik 			if (ret)
346277745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
346377745c05SJosef Bacik 		}
346477745c05SJosef Bacik 
346577745c05SJosef Bacik 		/* If its not on the io list, we need to put the block group */
346677745c05SJosef Bacik 		if (should_put)
346777745c05SJosef Bacik 			btrfs_put_block_group(cache);
346877745c05SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
346977745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
347077745c05SJosef Bacik 	}
347177745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
347277745c05SJosef Bacik 
347377745c05SJosef Bacik 	/*
347477745c05SJosef Bacik 	 * Refer to the definition of io_bgs member for details why it's safe
347577745c05SJosef Bacik 	 * to use it without any locking
347677745c05SJosef Bacik 	 */
347777745c05SJosef Bacik 	while (!list_empty(io)) {
347832da5386SDavid Sterba 		cache = list_first_entry(io, struct btrfs_block_group,
347977745c05SJosef Bacik 					 io_list);
348077745c05SJosef Bacik 		list_del_init(&cache->io_list);
348177745c05SJosef Bacik 		btrfs_wait_cache_io(trans, cache, path);
348277745c05SJosef Bacik 		btrfs_put_block_group(cache);
348377745c05SJosef Bacik 	}
348477745c05SJosef Bacik 
348577745c05SJosef Bacik 	btrfs_free_path(path);
348677745c05SJosef Bacik 	return ret;
348777745c05SJosef Bacik }
3488606d1bf1SJosef Bacik 
3489606d1bf1SJosef Bacik int btrfs_update_block_group(struct btrfs_trans_handle *trans,
349011b66fa6SAnand Jain 			     u64 bytenr, u64 num_bytes, bool alloc)
3491606d1bf1SJosef Bacik {
3492606d1bf1SJosef Bacik 	struct btrfs_fs_info *info = trans->fs_info;
349332da5386SDavid Sterba 	struct btrfs_block_group *cache = NULL;
3494606d1bf1SJosef Bacik 	u64 total = num_bytes;
3495606d1bf1SJosef Bacik 	u64 old_val;
3496606d1bf1SJosef Bacik 	u64 byte_in_group;
3497606d1bf1SJosef Bacik 	int factor;
3498606d1bf1SJosef Bacik 	int ret = 0;
3499606d1bf1SJosef Bacik 
3500606d1bf1SJosef Bacik 	/* Block accounting for super block */
3501606d1bf1SJosef Bacik 	spin_lock(&info->delalloc_root_lock);
3502606d1bf1SJosef Bacik 	old_val = btrfs_super_bytes_used(info->super_copy);
3503606d1bf1SJosef Bacik 	if (alloc)
3504606d1bf1SJosef Bacik 		old_val += num_bytes;
3505606d1bf1SJosef Bacik 	else
3506606d1bf1SJosef Bacik 		old_val -= num_bytes;
3507606d1bf1SJosef Bacik 	btrfs_set_super_bytes_used(info->super_copy, old_val);
3508606d1bf1SJosef Bacik 	spin_unlock(&info->delalloc_root_lock);
3509606d1bf1SJosef Bacik 
3510606d1bf1SJosef Bacik 	while (total) {
3511df384da5SJosef Bacik 		struct btrfs_space_info *space_info;
3512efbf35a1SJosef Bacik 		bool reclaim = false;
3513ac2f1e63SJosef Bacik 
3514606d1bf1SJosef Bacik 		cache = btrfs_lookup_block_group(info, bytenr);
3515606d1bf1SJosef Bacik 		if (!cache) {
3516606d1bf1SJosef Bacik 			ret = -ENOENT;
3517606d1bf1SJosef Bacik 			break;
3518606d1bf1SJosef Bacik 		}
3519df384da5SJosef Bacik 		space_info = cache->space_info;
3520606d1bf1SJosef Bacik 		factor = btrfs_bg_type_to_factor(cache->flags);
3521606d1bf1SJosef Bacik 
3522606d1bf1SJosef Bacik 		/*
3523606d1bf1SJosef Bacik 		 * If this block group has free space cache written out, we
3524606d1bf1SJosef Bacik 		 * need to make sure to load it if we are removing space.  This
3525606d1bf1SJosef Bacik 		 * is because we need the unpinning stage to actually add the
3526606d1bf1SJosef Bacik 		 * space back to the block group, otherwise we will leak space.
3527606d1bf1SJosef Bacik 		 */
352832da5386SDavid Sterba 		if (!alloc && !btrfs_block_group_done(cache))
3529ced8ecf0SOmar Sandoval 			btrfs_cache_block_group(cache, true);
3530606d1bf1SJosef Bacik 
3531b3470b5dSDavid Sterba 		byte_in_group = bytenr - cache->start;
3532b3470b5dSDavid Sterba 		WARN_ON(byte_in_group > cache->length);
3533606d1bf1SJosef Bacik 
3534df384da5SJosef Bacik 		spin_lock(&space_info->lock);
3535606d1bf1SJosef Bacik 		spin_lock(&cache->lock);
3536606d1bf1SJosef Bacik 
3537606d1bf1SJosef Bacik 		if (btrfs_test_opt(info, SPACE_CACHE) &&
3538606d1bf1SJosef Bacik 		    cache->disk_cache_state < BTRFS_DC_CLEAR)
3539606d1bf1SJosef Bacik 			cache->disk_cache_state = BTRFS_DC_CLEAR;
3540606d1bf1SJosef Bacik 
3541bf38be65SDavid Sterba 		old_val = cache->used;
3542b3470b5dSDavid Sterba 		num_bytes = min(total, cache->length - byte_in_group);
3543606d1bf1SJosef Bacik 		if (alloc) {
3544606d1bf1SJosef Bacik 			old_val += num_bytes;
3545bf38be65SDavid Sterba 			cache->used = old_val;
3546606d1bf1SJosef Bacik 			cache->reserved -= num_bytes;
3547df384da5SJosef Bacik 			space_info->bytes_reserved -= num_bytes;
3548df384da5SJosef Bacik 			space_info->bytes_used += num_bytes;
3549df384da5SJosef Bacik 			space_info->disk_used += num_bytes * factor;
3550606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
3551df384da5SJosef Bacik 			spin_unlock(&space_info->lock);
3552606d1bf1SJosef Bacik 		} else {
3553606d1bf1SJosef Bacik 			old_val -= num_bytes;
3554bf38be65SDavid Sterba 			cache->used = old_val;
3555606d1bf1SJosef Bacik 			cache->pinned += num_bytes;
3556df384da5SJosef Bacik 			btrfs_space_info_update_bytes_pinned(info, space_info,
3557df384da5SJosef Bacik 							     num_bytes);
3558df384da5SJosef Bacik 			space_info->bytes_used -= num_bytes;
3559df384da5SJosef Bacik 			space_info->disk_used -= num_bytes * factor;
3560ac2f1e63SJosef Bacik 
3561ac2f1e63SJosef Bacik 			reclaim = should_reclaim_block_group(cache, num_bytes);
356252bb7a21SBoris Burkov 
3563606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
3564df384da5SJosef Bacik 			spin_unlock(&space_info->lock);
3565606d1bf1SJosef Bacik 
3566fe1a598cSDavid Sterba 			set_extent_bit(&trans->transaction->pinned_extents,
3567606d1bf1SJosef Bacik 				       bytenr, bytenr + num_bytes - 1,
35681d126800SDavid Sterba 				       EXTENT_DIRTY, NULL);
3569606d1bf1SJosef Bacik 		}
3570606d1bf1SJosef Bacik 
3571606d1bf1SJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
3572606d1bf1SJosef Bacik 		if (list_empty(&cache->dirty_list)) {
3573606d1bf1SJosef Bacik 			list_add_tail(&cache->dirty_list,
3574606d1bf1SJosef Bacik 				      &trans->transaction->dirty_bgs);
3575606d1bf1SJosef Bacik 			trans->delayed_ref_updates++;
3576606d1bf1SJosef Bacik 			btrfs_get_block_group(cache);
3577606d1bf1SJosef Bacik 		}
3578606d1bf1SJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
3579606d1bf1SJosef Bacik 
3580606d1bf1SJosef Bacik 		/*
3581606d1bf1SJosef Bacik 		 * No longer have used bytes in this block group, queue it for
3582606d1bf1SJosef Bacik 		 * deletion. We do this after adding the block group to the
3583606d1bf1SJosef Bacik 		 * dirty list to avoid races between cleaner kthread and space
3584606d1bf1SJosef Bacik 		 * cache writeout.
3585606d1bf1SJosef Bacik 		 */
35866e80d4f8SDennis Zhou 		if (!alloc && old_val == 0) {
35876e80d4f8SDennis Zhou 			if (!btrfs_test_opt(info, DISCARD_ASYNC))
3588606d1bf1SJosef Bacik 				btrfs_mark_bg_unused(cache);
3589ac2f1e63SJosef Bacik 		} else if (!alloc && reclaim) {
3590ac2f1e63SJosef Bacik 			btrfs_mark_bg_to_reclaim(cache);
35916e80d4f8SDennis Zhou 		}
3592606d1bf1SJosef Bacik 
3593606d1bf1SJosef Bacik 		btrfs_put_block_group(cache);
3594606d1bf1SJosef Bacik 		total -= num_bytes;
3595606d1bf1SJosef Bacik 		bytenr += num_bytes;
3596606d1bf1SJosef Bacik 	}
3597606d1bf1SJosef Bacik 
3598606d1bf1SJosef Bacik 	/* Modified block groups are accounted for in the delayed_refs_rsv. */
3599606d1bf1SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
3600606d1bf1SJosef Bacik 	return ret;
3601606d1bf1SJosef Bacik }
3602606d1bf1SJosef Bacik 
360343dd529aSDavid Sterba /*
360443dd529aSDavid Sterba  * Update the block_group and space info counters.
360543dd529aSDavid Sterba  *
3606606d1bf1SJosef Bacik  * @cache:	The cache we are manipulating
3607606d1bf1SJosef Bacik  * @ram_bytes:  The number of bytes of file content, and will be same to
3608606d1bf1SJosef Bacik  *              @num_bytes except for the compress path.
3609606d1bf1SJosef Bacik  * @num_bytes:	The number of bytes in question
3610606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
3611606d1bf1SJosef Bacik  *
3612606d1bf1SJosef Bacik  * This is called by the allocator when it reserves space. If this is a
3613606d1bf1SJosef Bacik  * reservation and the block group has become read only we cannot make the
3614606d1bf1SJosef Bacik  * reservation and return -EAGAIN, otherwise this function always succeeds.
3615606d1bf1SJosef Bacik  */
361632da5386SDavid Sterba int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
361752bb7a21SBoris Burkov 			     u64 ram_bytes, u64 num_bytes, int delalloc,
361852bb7a21SBoris Burkov 			     bool force_wrong_size_class)
3619606d1bf1SJosef Bacik {
3620606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
362152bb7a21SBoris Burkov 	enum btrfs_block_group_size_class size_class;
3622606d1bf1SJosef Bacik 	int ret = 0;
3623606d1bf1SJosef Bacik 
3624606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
3625606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
3626606d1bf1SJosef Bacik 	if (cache->ro) {
3627606d1bf1SJosef Bacik 		ret = -EAGAIN;
362852bb7a21SBoris Burkov 		goto out;
362952bb7a21SBoris Burkov 	}
363052bb7a21SBoris Burkov 
3631cb0922f2SBoris Burkov 	if (btrfs_block_group_should_use_size_class(cache)) {
363252bb7a21SBoris Burkov 		size_class = btrfs_calc_block_group_size_class(num_bytes);
363352bb7a21SBoris Burkov 		ret = btrfs_use_block_group_size_class(cache, size_class, force_wrong_size_class);
363452bb7a21SBoris Burkov 		if (ret)
363552bb7a21SBoris Burkov 			goto out;
363652bb7a21SBoris Burkov 	}
3637606d1bf1SJosef Bacik 	cache->reserved += num_bytes;
3638606d1bf1SJosef Bacik 	space_info->bytes_reserved += num_bytes;
3639a43c3835SJosef Bacik 	trace_btrfs_space_reservation(cache->fs_info, "space_info",
3640a43c3835SJosef Bacik 				      space_info->flags, num_bytes, 1);
3641606d1bf1SJosef Bacik 	btrfs_space_info_update_bytes_may_use(cache->fs_info,
3642606d1bf1SJosef Bacik 					      space_info, -ram_bytes);
3643606d1bf1SJosef Bacik 	if (delalloc)
3644606d1bf1SJosef Bacik 		cache->delalloc_bytes += num_bytes;
364599ffb43eSJosef Bacik 
364699ffb43eSJosef Bacik 	/*
364752bb7a21SBoris Burkov 	 * Compression can use less space than we reserved, so wake tickets if
364852bb7a21SBoris Burkov 	 * that happens.
364999ffb43eSJosef Bacik 	 */
365099ffb43eSJosef Bacik 	if (num_bytes < ram_bytes)
365199ffb43eSJosef Bacik 		btrfs_try_granting_tickets(cache->fs_info, space_info);
365252bb7a21SBoris Burkov out:
3653606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
3654606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
3655606d1bf1SJosef Bacik 	return ret;
3656606d1bf1SJosef Bacik }
3657606d1bf1SJosef Bacik 
365843dd529aSDavid Sterba /*
365943dd529aSDavid Sterba  * Update the block_group and space info counters.
366043dd529aSDavid Sterba  *
3661606d1bf1SJosef Bacik  * @cache:      The cache we are manipulating
3662606d1bf1SJosef Bacik  * @num_bytes:  The number of bytes in question
3663606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
3664606d1bf1SJosef Bacik  *
3665606d1bf1SJosef Bacik  * This is called by somebody who is freeing space that was never actually used
3666606d1bf1SJosef Bacik  * on disk.  For example if you reserve some space for a new leaf in transaction
3667606d1bf1SJosef Bacik  * A and before transaction A commits you free that leaf, you call this with
3668606d1bf1SJosef Bacik  * reserve set to 0 in order to clear the reservation.
3669606d1bf1SJosef Bacik  */
367032da5386SDavid Sterba void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3671606d1bf1SJosef Bacik 			       u64 num_bytes, int delalloc)
3672606d1bf1SJosef Bacik {
3673606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
3674606d1bf1SJosef Bacik 
3675606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
3676606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
3677606d1bf1SJosef Bacik 	if (cache->ro)
3678606d1bf1SJosef Bacik 		space_info->bytes_readonly += num_bytes;
3679606d1bf1SJosef Bacik 	cache->reserved -= num_bytes;
3680606d1bf1SJosef Bacik 	space_info->bytes_reserved -= num_bytes;
3681606d1bf1SJosef Bacik 	space_info->max_extent_size = 0;
3682606d1bf1SJosef Bacik 
3683606d1bf1SJosef Bacik 	if (delalloc)
3684606d1bf1SJosef Bacik 		cache->delalloc_bytes -= num_bytes;
3685606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
36863308234aSJosef Bacik 
36873308234aSJosef Bacik 	btrfs_try_granting_tickets(cache->fs_info, space_info);
3688606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
3689606d1bf1SJosef Bacik }
369007730d87SJosef Bacik 
369107730d87SJosef Bacik static void force_metadata_allocation(struct btrfs_fs_info *info)
369207730d87SJosef Bacik {
369307730d87SJosef Bacik 	struct list_head *head = &info->space_info;
369407730d87SJosef Bacik 	struct btrfs_space_info *found;
369507730d87SJosef Bacik 
369672804905SJosef Bacik 	list_for_each_entry(found, head, list) {
369707730d87SJosef Bacik 		if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
369807730d87SJosef Bacik 			found->force_alloc = CHUNK_ALLOC_FORCE;
369907730d87SJosef Bacik 	}
370007730d87SJosef Bacik }
370107730d87SJosef Bacik 
370207730d87SJosef Bacik static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
370307730d87SJosef Bacik 			      struct btrfs_space_info *sinfo, int force)
370407730d87SJosef Bacik {
370507730d87SJosef Bacik 	u64 bytes_used = btrfs_space_info_used(sinfo, false);
370607730d87SJosef Bacik 	u64 thresh;
370707730d87SJosef Bacik 
370807730d87SJosef Bacik 	if (force == CHUNK_ALLOC_FORCE)
370907730d87SJosef Bacik 		return 1;
371007730d87SJosef Bacik 
371107730d87SJosef Bacik 	/*
371207730d87SJosef Bacik 	 * in limited mode, we want to have some free space up to
371307730d87SJosef Bacik 	 * about 1% of the FS size.
371407730d87SJosef Bacik 	 */
371507730d87SJosef Bacik 	if (force == CHUNK_ALLOC_LIMITED) {
371607730d87SJosef Bacik 		thresh = btrfs_super_total_bytes(fs_info->super_copy);
3717428c8e03SDavid Sterba 		thresh = max_t(u64, SZ_64M, mult_perc(thresh, 1));
371807730d87SJosef Bacik 
371907730d87SJosef Bacik 		if (sinfo->total_bytes - bytes_used < thresh)
372007730d87SJosef Bacik 			return 1;
372107730d87SJosef Bacik 	}
372207730d87SJosef Bacik 
3723428c8e03SDavid Sterba 	if (bytes_used + SZ_2M < mult_perc(sinfo->total_bytes, 80))
372407730d87SJosef Bacik 		return 0;
372507730d87SJosef Bacik 	return 1;
372607730d87SJosef Bacik }
372707730d87SJosef Bacik 
372807730d87SJosef Bacik int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
372907730d87SJosef Bacik {
373007730d87SJosef Bacik 	u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
373107730d87SJosef Bacik 
373207730d87SJosef Bacik 	return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
373307730d87SJosef Bacik }
373407730d87SJosef Bacik 
3735820c363bSNaohiro Aota static struct btrfs_block_group *do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags)
373679bd3712SFilipe Manana {
373779bd3712SFilipe Manana 	struct btrfs_block_group *bg;
373879bd3712SFilipe Manana 	int ret;
373979bd3712SFilipe Manana 
374007730d87SJosef Bacik 	/*
374179bd3712SFilipe Manana 	 * Check if we have enough space in the system space info because we
374279bd3712SFilipe Manana 	 * will need to update device items in the chunk btree and insert a new
374379bd3712SFilipe Manana 	 * chunk item in the chunk btree as well. This will allocate a new
374479bd3712SFilipe Manana 	 * system block group if needed.
374579bd3712SFilipe Manana 	 */
374679bd3712SFilipe Manana 	check_system_chunk(trans, flags);
374779bd3712SFilipe Manana 
3748f6f39f7aSNikolay Borisov 	bg = btrfs_create_chunk(trans, flags);
374979bd3712SFilipe Manana 	if (IS_ERR(bg)) {
375079bd3712SFilipe Manana 		ret = PTR_ERR(bg);
375179bd3712SFilipe Manana 		goto out;
375279bd3712SFilipe Manana 	}
375379bd3712SFilipe Manana 
375479bd3712SFilipe Manana 	ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
375579bd3712SFilipe Manana 	/*
375679bd3712SFilipe Manana 	 * Normally we are not expected to fail with -ENOSPC here, since we have
375779bd3712SFilipe Manana 	 * previously reserved space in the system space_info and allocated one
3758ecd84d54SFilipe Manana 	 * new system chunk if necessary. However there are three exceptions:
375979bd3712SFilipe Manana 	 *
376079bd3712SFilipe Manana 	 * 1) We may have enough free space in the system space_info but all the
376179bd3712SFilipe Manana 	 *    existing system block groups have a profile which can not be used
376279bd3712SFilipe Manana 	 *    for extent allocation.
376379bd3712SFilipe Manana 	 *
376479bd3712SFilipe Manana 	 *    This happens when mounting in degraded mode. For example we have a
376579bd3712SFilipe Manana 	 *    RAID1 filesystem with 2 devices, lose one device and mount the fs
376679bd3712SFilipe Manana 	 *    using the other device in degraded mode. If we then allocate a chunk,
376779bd3712SFilipe Manana 	 *    we may have enough free space in the existing system space_info, but
376879bd3712SFilipe Manana 	 *    none of the block groups can be used for extent allocation since they
376979bd3712SFilipe Manana 	 *    have a RAID1 profile, and because we are in degraded mode with a
377079bd3712SFilipe Manana 	 *    single device, we are forced to allocate a new system chunk with a
377179bd3712SFilipe Manana 	 *    SINGLE profile. Making check_system_chunk() iterate over all system
377279bd3712SFilipe Manana 	 *    block groups and check if they have a usable profile and enough space
377379bd3712SFilipe Manana 	 *    can be slow on very large filesystems, so we tolerate the -ENOSPC and
377479bd3712SFilipe Manana 	 *    try again after forcing allocation of a new system chunk. Like this
377579bd3712SFilipe Manana 	 *    we avoid paying the cost of that search in normal circumstances, when
377679bd3712SFilipe Manana 	 *    we were not mounted in degraded mode;
377779bd3712SFilipe Manana 	 *
377879bd3712SFilipe Manana 	 * 2) We had enough free space info the system space_info, and one suitable
377979bd3712SFilipe Manana 	 *    block group to allocate from when we called check_system_chunk()
378079bd3712SFilipe Manana 	 *    above. However right after we called it, the only system block group
378179bd3712SFilipe Manana 	 *    with enough free space got turned into RO mode by a running scrub,
378279bd3712SFilipe Manana 	 *    and in this case we have to allocate a new one and retry. We only
378379bd3712SFilipe Manana 	 *    need do this allocate and retry once, since we have a transaction
3784ecd84d54SFilipe Manana 	 *    handle and scrub uses the commit root to search for block groups;
3785ecd84d54SFilipe Manana 	 *
3786ecd84d54SFilipe Manana 	 * 3) We had one system block group with enough free space when we called
3787ecd84d54SFilipe Manana 	 *    check_system_chunk(), but after that, right before we tried to
3788ecd84d54SFilipe Manana 	 *    allocate the last extent buffer we needed, a discard operation came
3789ecd84d54SFilipe Manana 	 *    in and it temporarily removed the last free space entry from the
3790ecd84d54SFilipe Manana 	 *    block group (discard removes a free space entry, discards it, and
3791ecd84d54SFilipe Manana 	 *    then adds back the entry to the block group cache).
379279bd3712SFilipe Manana 	 */
379379bd3712SFilipe Manana 	if (ret == -ENOSPC) {
379479bd3712SFilipe Manana 		const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info);
379579bd3712SFilipe Manana 		struct btrfs_block_group *sys_bg;
379679bd3712SFilipe Manana 
3797f6f39f7aSNikolay Borisov 		sys_bg = btrfs_create_chunk(trans, sys_flags);
379879bd3712SFilipe Manana 		if (IS_ERR(sys_bg)) {
379979bd3712SFilipe Manana 			ret = PTR_ERR(sys_bg);
380079bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
380179bd3712SFilipe Manana 			goto out;
380279bd3712SFilipe Manana 		}
380379bd3712SFilipe Manana 
380479bd3712SFilipe Manana 		ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
380579bd3712SFilipe Manana 		if (ret) {
380679bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
380779bd3712SFilipe Manana 			goto out;
380879bd3712SFilipe Manana 		}
380979bd3712SFilipe Manana 
381079bd3712SFilipe Manana 		ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
381179bd3712SFilipe Manana 		if (ret) {
381279bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
381379bd3712SFilipe Manana 			goto out;
381479bd3712SFilipe Manana 		}
381579bd3712SFilipe Manana 	} else if (ret) {
381679bd3712SFilipe Manana 		btrfs_abort_transaction(trans, ret);
381779bd3712SFilipe Manana 		goto out;
381879bd3712SFilipe Manana 	}
381979bd3712SFilipe Manana out:
382079bd3712SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
382179bd3712SFilipe Manana 
3822820c363bSNaohiro Aota 	if (ret)
3823820c363bSNaohiro Aota 		return ERR_PTR(ret);
3824820c363bSNaohiro Aota 
3825820c363bSNaohiro Aota 	btrfs_get_block_group(bg);
3826820c363bSNaohiro Aota 	return bg;
382779bd3712SFilipe Manana }
382879bd3712SFilipe Manana 
382979bd3712SFilipe Manana /*
383079bd3712SFilipe Manana  * Chunk allocation is done in 2 phases:
383179bd3712SFilipe Manana  *
383279bd3712SFilipe Manana  * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
383379bd3712SFilipe Manana  *    the chunk, the chunk mapping, create its block group and add the items
383479bd3712SFilipe Manana  *    that belong in the chunk btree to it - more specifically, we need to
383579bd3712SFilipe Manana  *    update device items in the chunk btree and add a new chunk item to it.
383679bd3712SFilipe Manana  *
383779bd3712SFilipe Manana  * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
383879bd3712SFilipe Manana  *    group item to the extent btree and the device extent items to the devices
383979bd3712SFilipe Manana  *    btree.
384079bd3712SFilipe Manana  *
384179bd3712SFilipe Manana  * This is done to prevent deadlocks. For example when COWing a node from the
384279bd3712SFilipe Manana  * extent btree we are holding a write lock on the node's parent and if we
384379bd3712SFilipe Manana  * trigger chunk allocation and attempted to insert the new block group item
384479bd3712SFilipe Manana  * in the extent btree right way, we could deadlock because the path for the
384579bd3712SFilipe Manana  * insertion can include that parent node. At first glance it seems impossible
384679bd3712SFilipe Manana  * to trigger chunk allocation after starting a transaction since tasks should
384779bd3712SFilipe Manana  * reserve enough transaction units (metadata space), however while that is true
384879bd3712SFilipe Manana  * most of the time, chunk allocation may still be triggered for several reasons:
384979bd3712SFilipe Manana  *
385079bd3712SFilipe Manana  * 1) When reserving metadata, we check if there is enough free space in the
385179bd3712SFilipe Manana  *    metadata space_info and therefore don't trigger allocation of a new chunk.
385279bd3712SFilipe Manana  *    However later when the task actually tries to COW an extent buffer from
385379bd3712SFilipe Manana  *    the extent btree or from the device btree for example, it is forced to
385479bd3712SFilipe Manana  *    allocate a new block group (chunk) because the only one that had enough
385579bd3712SFilipe Manana  *    free space was just turned to RO mode by a running scrub for example (or
385679bd3712SFilipe Manana  *    device replace, block group reclaim thread, etc), so we can not use it
385779bd3712SFilipe Manana  *    for allocating an extent and end up being forced to allocate a new one;
385879bd3712SFilipe Manana  *
385979bd3712SFilipe Manana  * 2) Because we only check that the metadata space_info has enough free bytes,
386079bd3712SFilipe Manana  *    we end up not allocating a new metadata chunk in that case. However if
386179bd3712SFilipe Manana  *    the filesystem was mounted in degraded mode, none of the existing block
386279bd3712SFilipe Manana  *    groups might be suitable for extent allocation due to their incompatible
386379bd3712SFilipe Manana  *    profile (for e.g. mounting a 2 devices filesystem, where all block groups
386479bd3712SFilipe Manana  *    use a RAID1 profile, in degraded mode using a single device). In this case
386579bd3712SFilipe Manana  *    when the task attempts to COW some extent buffer of the extent btree for
386679bd3712SFilipe Manana  *    example, it will trigger allocation of a new metadata block group with a
386779bd3712SFilipe Manana  *    suitable profile (SINGLE profile in the example of the degraded mount of
386879bd3712SFilipe Manana  *    the RAID1 filesystem);
386979bd3712SFilipe Manana  *
387079bd3712SFilipe Manana  * 3) The task has reserved enough transaction units / metadata space, but when
387179bd3712SFilipe Manana  *    it attempts to COW an extent buffer from the extent or device btree for
387279bd3712SFilipe Manana  *    example, it does not find any free extent in any metadata block group,
387379bd3712SFilipe Manana  *    therefore forced to try to allocate a new metadata block group.
387479bd3712SFilipe Manana  *    This is because some other task allocated all available extents in the
387579bd3712SFilipe Manana  *    meanwhile - this typically happens with tasks that don't reserve space
387679bd3712SFilipe Manana  *    properly, either intentionally or as a bug. One example where this is
387779bd3712SFilipe Manana  *    done intentionally is fsync, as it does not reserve any transaction units
387879bd3712SFilipe Manana  *    and ends up allocating a variable number of metadata extents for log
3879ecd84d54SFilipe Manana  *    tree extent buffers;
3880ecd84d54SFilipe Manana  *
3881ecd84d54SFilipe Manana  * 4) The task has reserved enough transaction units / metadata space, but right
3882ecd84d54SFilipe Manana  *    before it tries to allocate the last extent buffer it needs, a discard
3883ecd84d54SFilipe Manana  *    operation comes in and, temporarily, removes the last free space entry from
3884ecd84d54SFilipe Manana  *    the only metadata block group that had free space (discard starts by
3885ecd84d54SFilipe Manana  *    removing a free space entry from a block group, then does the discard
3886ecd84d54SFilipe Manana  *    operation and, once it's done, it adds back the free space entry to the
3887ecd84d54SFilipe Manana  *    block group).
388879bd3712SFilipe Manana  *
388979bd3712SFilipe Manana  * We also need this 2 phases setup when adding a device to a filesystem with
389079bd3712SFilipe Manana  * a seed device - we must create new metadata and system chunks without adding
389179bd3712SFilipe Manana  * any of the block group items to the chunk, extent and device btrees. If we
389279bd3712SFilipe Manana  * did not do it this way, we would get ENOSPC when attempting to update those
389379bd3712SFilipe Manana  * btrees, since all the chunks from the seed device are read-only.
389479bd3712SFilipe Manana  *
389579bd3712SFilipe Manana  * Phase 1 does the updates and insertions to the chunk btree because if we had
389679bd3712SFilipe Manana  * it done in phase 2 and have a thundering herd of tasks allocating chunks in
389779bd3712SFilipe Manana  * parallel, we risk having too many system chunks allocated by many tasks if
389879bd3712SFilipe Manana  * many tasks reach phase 1 without the previous ones completing phase 2. In the
389979bd3712SFilipe Manana  * extreme case this leads to exhaustion of the system chunk array in the
390079bd3712SFilipe Manana  * superblock. This is easier to trigger if using a btree node/leaf size of 64K
390179bd3712SFilipe Manana  * and with RAID filesystems (so we have more device items in the chunk btree).
390279bd3712SFilipe Manana  * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
390379bd3712SFilipe Manana  * the system chunk array due to concurrent allocations") provides more details.
390479bd3712SFilipe Manana  *
39052bb2e00eSFilipe Manana  * Allocation of system chunks does not happen through this function. A task that
39062bb2e00eSFilipe Manana  * needs to update the chunk btree (the only btree that uses system chunks), must
39072bb2e00eSFilipe Manana  * preallocate chunk space by calling either check_system_chunk() or
39082bb2e00eSFilipe Manana  * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or
39092bb2e00eSFilipe Manana  * metadata chunk or when removing a chunk, while the later is used before doing
39102bb2e00eSFilipe Manana  * a modification to the chunk btree - use cases for the later are adding,
39112bb2e00eSFilipe Manana  * removing and resizing a device as well as relocation of a system chunk.
39122bb2e00eSFilipe Manana  * See the comment below for more details.
391379bd3712SFilipe Manana  *
391479bd3712SFilipe Manana  * The reservation of system space, done through check_system_chunk(), as well
391579bd3712SFilipe Manana  * as all the updates and insertions into the chunk btree must be done while
391679bd3712SFilipe Manana  * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
391779bd3712SFilipe Manana  * an extent buffer from the chunks btree we never trigger allocation of a new
391879bd3712SFilipe Manana  * system chunk, which would result in a deadlock (trying to lock twice an
391979bd3712SFilipe Manana  * extent buffer of the chunk btree, first time before triggering the chunk
392079bd3712SFilipe Manana  * allocation and the second time during chunk allocation while attempting to
392179bd3712SFilipe Manana  * update the chunks btree). The system chunk array is also updated while holding
392279bd3712SFilipe Manana  * that mutex. The same logic applies to removing chunks - we must reserve system
392379bd3712SFilipe Manana  * space, update the chunk btree and the system chunk array in the superblock
392479bd3712SFilipe Manana  * while holding fs_info->chunk_mutex.
392579bd3712SFilipe Manana  *
392679bd3712SFilipe Manana  * This function, btrfs_chunk_alloc(), belongs to phase 1.
392779bd3712SFilipe Manana  *
392879bd3712SFilipe Manana  * If @force is CHUNK_ALLOC_FORCE:
392907730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
393007730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
393179bd3712SFilipe Manana  * If @force is NOT CHUNK_ALLOC_FORCE:
393207730d87SJosef Bacik  *    - return 0 if it doesn't need to allocate a new chunk,
393307730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
393407730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
393507730d87SJosef Bacik  */
393607730d87SJosef Bacik int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
393707730d87SJosef Bacik 		      enum btrfs_chunk_alloc_enum force)
393807730d87SJosef Bacik {
393907730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
394007730d87SJosef Bacik 	struct btrfs_space_info *space_info;
3941820c363bSNaohiro Aota 	struct btrfs_block_group *ret_bg;
394207730d87SJosef Bacik 	bool wait_for_alloc = false;
394307730d87SJosef Bacik 	bool should_alloc = false;
3944760e69c4SNaohiro Aota 	bool from_extent_allocation = false;
394507730d87SJosef Bacik 	int ret = 0;
394607730d87SJosef Bacik 
3947760e69c4SNaohiro Aota 	if (force == CHUNK_ALLOC_FORCE_FOR_EXTENT) {
3948760e69c4SNaohiro Aota 		from_extent_allocation = true;
3949760e69c4SNaohiro Aota 		force = CHUNK_ALLOC_FORCE;
3950760e69c4SNaohiro Aota 	}
3951760e69c4SNaohiro Aota 
395207730d87SJosef Bacik 	/* Don't re-enter if we're already allocating a chunk */
395307730d87SJosef Bacik 	if (trans->allocating_chunk)
395407730d87SJosef Bacik 		return -ENOSPC;
395579bd3712SFilipe Manana 	/*
39562bb2e00eSFilipe Manana 	 * Allocation of system chunks can not happen through this path, as we
39572bb2e00eSFilipe Manana 	 * could end up in a deadlock if we are allocating a data or metadata
39582bb2e00eSFilipe Manana 	 * chunk and there is another task modifying the chunk btree.
39592bb2e00eSFilipe Manana 	 *
39602bb2e00eSFilipe Manana 	 * This is because while we are holding the chunk mutex, we will attempt
39612bb2e00eSFilipe Manana 	 * to add the new chunk item to the chunk btree or update an existing
39622bb2e00eSFilipe Manana 	 * device item in the chunk btree, while the other task that is modifying
39632bb2e00eSFilipe Manana 	 * the chunk btree is attempting to COW an extent buffer while holding a
39642bb2e00eSFilipe Manana 	 * lock on it and on its parent - if the COW operation triggers a system
39652bb2e00eSFilipe Manana 	 * chunk allocation, then we can deadlock because we are holding the
39662bb2e00eSFilipe Manana 	 * chunk mutex and we may need to access that extent buffer or its parent
39672bb2e00eSFilipe Manana 	 * in order to add the chunk item or update a device item.
39682bb2e00eSFilipe Manana 	 *
39692bb2e00eSFilipe Manana 	 * Tasks that want to modify the chunk tree should reserve system space
39702bb2e00eSFilipe Manana 	 * before updating the chunk btree, by calling either
39712bb2e00eSFilipe Manana 	 * btrfs_reserve_chunk_metadata() or check_system_chunk().
39722bb2e00eSFilipe Manana 	 * It's possible that after a task reserves the space, it still ends up
39732bb2e00eSFilipe Manana 	 * here - this happens in the cases described above at do_chunk_alloc().
39742bb2e00eSFilipe Manana 	 * The task will have to either retry or fail.
397579bd3712SFilipe Manana 	 */
39762bb2e00eSFilipe Manana 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
397779bd3712SFilipe Manana 		return -ENOSPC;
397807730d87SJosef Bacik 
397907730d87SJosef Bacik 	space_info = btrfs_find_space_info(fs_info, flags);
398007730d87SJosef Bacik 	ASSERT(space_info);
398107730d87SJosef Bacik 
398207730d87SJosef Bacik 	do {
398307730d87SJosef Bacik 		spin_lock(&space_info->lock);
398407730d87SJosef Bacik 		if (force < space_info->force_alloc)
398507730d87SJosef Bacik 			force = space_info->force_alloc;
398607730d87SJosef Bacik 		should_alloc = should_alloc_chunk(fs_info, space_info, force);
398707730d87SJosef Bacik 		if (space_info->full) {
398807730d87SJosef Bacik 			/* No more free physical space */
398907730d87SJosef Bacik 			if (should_alloc)
399007730d87SJosef Bacik 				ret = -ENOSPC;
399107730d87SJosef Bacik 			else
399207730d87SJosef Bacik 				ret = 0;
399307730d87SJosef Bacik 			spin_unlock(&space_info->lock);
399407730d87SJosef Bacik 			return ret;
399507730d87SJosef Bacik 		} else if (!should_alloc) {
399607730d87SJosef Bacik 			spin_unlock(&space_info->lock);
399707730d87SJosef Bacik 			return 0;
399807730d87SJosef Bacik 		} else if (space_info->chunk_alloc) {
399907730d87SJosef Bacik 			/*
400007730d87SJosef Bacik 			 * Someone is already allocating, so we need to block
400107730d87SJosef Bacik 			 * until this someone is finished and then loop to
400207730d87SJosef Bacik 			 * recheck if we should continue with our allocation
400307730d87SJosef Bacik 			 * attempt.
400407730d87SJosef Bacik 			 */
400507730d87SJosef Bacik 			wait_for_alloc = true;
40061314ca78SJosef Bacik 			force = CHUNK_ALLOC_NO_FORCE;
400707730d87SJosef Bacik 			spin_unlock(&space_info->lock);
400807730d87SJosef Bacik 			mutex_lock(&fs_info->chunk_mutex);
400907730d87SJosef Bacik 			mutex_unlock(&fs_info->chunk_mutex);
401007730d87SJosef Bacik 		} else {
401107730d87SJosef Bacik 			/* Proceed with allocation */
401207730d87SJosef Bacik 			space_info->chunk_alloc = 1;
401307730d87SJosef Bacik 			wait_for_alloc = false;
401407730d87SJosef Bacik 			spin_unlock(&space_info->lock);
401507730d87SJosef Bacik 		}
401607730d87SJosef Bacik 
401707730d87SJosef Bacik 		cond_resched();
401807730d87SJosef Bacik 	} while (wait_for_alloc);
401907730d87SJosef Bacik 
402007730d87SJosef Bacik 	mutex_lock(&fs_info->chunk_mutex);
402107730d87SJosef Bacik 	trans->allocating_chunk = true;
402207730d87SJosef Bacik 
402307730d87SJosef Bacik 	/*
402407730d87SJosef Bacik 	 * If we have mixed data/metadata chunks we want to make sure we keep
402507730d87SJosef Bacik 	 * allocating mixed chunks instead of individual chunks.
402607730d87SJosef Bacik 	 */
402707730d87SJosef Bacik 	if (btrfs_mixed_space_info(space_info))
402807730d87SJosef Bacik 		flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
402907730d87SJosef Bacik 
403007730d87SJosef Bacik 	/*
403107730d87SJosef Bacik 	 * if we're doing a data chunk, go ahead and make sure that
403207730d87SJosef Bacik 	 * we keep a reasonable number of metadata chunks allocated in the
403307730d87SJosef Bacik 	 * FS as well.
403407730d87SJosef Bacik 	 */
403507730d87SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
403607730d87SJosef Bacik 		fs_info->data_chunk_allocations++;
403707730d87SJosef Bacik 		if (!(fs_info->data_chunk_allocations %
403807730d87SJosef Bacik 		      fs_info->metadata_ratio))
403907730d87SJosef Bacik 			force_metadata_allocation(fs_info);
404007730d87SJosef Bacik 	}
404107730d87SJosef Bacik 
4042820c363bSNaohiro Aota 	ret_bg = do_chunk_alloc(trans, flags);
404307730d87SJosef Bacik 	trans->allocating_chunk = false;
404407730d87SJosef Bacik 
4045760e69c4SNaohiro Aota 	if (IS_ERR(ret_bg)) {
4046820c363bSNaohiro Aota 		ret = PTR_ERR(ret_bg);
4047760e69c4SNaohiro Aota 	} else if (from_extent_allocation) {
4048760e69c4SNaohiro Aota 		/*
4049760e69c4SNaohiro Aota 		 * New block group is likely to be used soon. Try to activate
4050760e69c4SNaohiro Aota 		 * it now. Failure is OK for now.
4051760e69c4SNaohiro Aota 		 */
4052760e69c4SNaohiro Aota 		btrfs_zone_activate(ret_bg);
4053760e69c4SNaohiro Aota 	}
4054760e69c4SNaohiro Aota 
4055760e69c4SNaohiro Aota 	if (!ret)
4056820c363bSNaohiro Aota 		btrfs_put_block_group(ret_bg);
4057820c363bSNaohiro Aota 
405807730d87SJosef Bacik 	spin_lock(&space_info->lock);
405907730d87SJosef Bacik 	if (ret < 0) {
406007730d87SJosef Bacik 		if (ret == -ENOSPC)
406107730d87SJosef Bacik 			space_info->full = 1;
406207730d87SJosef Bacik 		else
406307730d87SJosef Bacik 			goto out;
406407730d87SJosef Bacik 	} else {
406507730d87SJosef Bacik 		ret = 1;
406607730d87SJosef Bacik 		space_info->max_extent_size = 0;
406707730d87SJosef Bacik 	}
406807730d87SJosef Bacik 
406907730d87SJosef Bacik 	space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
407007730d87SJosef Bacik out:
407107730d87SJosef Bacik 	space_info->chunk_alloc = 0;
407207730d87SJosef Bacik 	spin_unlock(&space_info->lock);
407307730d87SJosef Bacik 	mutex_unlock(&fs_info->chunk_mutex);
407407730d87SJosef Bacik 
407507730d87SJosef Bacik 	return ret;
407607730d87SJosef Bacik }
407707730d87SJosef Bacik 
407807730d87SJosef Bacik static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
407907730d87SJosef Bacik {
408007730d87SJosef Bacik 	u64 num_dev;
408107730d87SJosef Bacik 
408207730d87SJosef Bacik 	num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
408307730d87SJosef Bacik 	if (!num_dev)
408407730d87SJosef Bacik 		num_dev = fs_info->fs_devices->rw_devices;
408507730d87SJosef Bacik 
408607730d87SJosef Bacik 	return num_dev;
408707730d87SJosef Bacik }
408807730d87SJosef Bacik 
40892bb2e00eSFilipe Manana static void reserve_chunk_space(struct btrfs_trans_handle *trans,
40902bb2e00eSFilipe Manana 				u64 bytes,
40912bb2e00eSFilipe Manana 				u64 type)
409207730d87SJosef Bacik {
409307730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
409407730d87SJosef Bacik 	struct btrfs_space_info *info;
409507730d87SJosef Bacik 	u64 left;
409607730d87SJosef Bacik 	int ret = 0;
409707730d87SJosef Bacik 
409807730d87SJosef Bacik 	/*
409907730d87SJosef Bacik 	 * Needed because we can end up allocating a system chunk and for an
410007730d87SJosef Bacik 	 * atomic and race free space reservation in the chunk block reserve.
410107730d87SJosef Bacik 	 */
410207730d87SJosef Bacik 	lockdep_assert_held(&fs_info->chunk_mutex);
410307730d87SJosef Bacik 
410407730d87SJosef Bacik 	info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
410507730d87SJosef Bacik 	spin_lock(&info->lock);
410607730d87SJosef Bacik 	left = info->total_bytes - btrfs_space_info_used(info, true);
410707730d87SJosef Bacik 	spin_unlock(&info->lock);
410807730d87SJosef Bacik 
41092bb2e00eSFilipe Manana 	if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
411007730d87SJosef Bacik 		btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
41112bb2e00eSFilipe Manana 			   left, bytes, type);
411207730d87SJosef Bacik 		btrfs_dump_space_info(fs_info, info, 0, 0);
411307730d87SJosef Bacik 	}
411407730d87SJosef Bacik 
41152bb2e00eSFilipe Manana 	if (left < bytes) {
411607730d87SJosef Bacik 		u64 flags = btrfs_system_alloc_profile(fs_info);
411779bd3712SFilipe Manana 		struct btrfs_block_group *bg;
411807730d87SJosef Bacik 
411907730d87SJosef Bacik 		/*
412007730d87SJosef Bacik 		 * Ignore failure to create system chunk. We might end up not
412107730d87SJosef Bacik 		 * needing it, as we might not need to COW all nodes/leafs from
412207730d87SJosef Bacik 		 * the paths we visit in the chunk tree (they were already COWed
412307730d87SJosef Bacik 		 * or created in the current transaction for example).
412407730d87SJosef Bacik 		 */
4125f6f39f7aSNikolay Borisov 		bg = btrfs_create_chunk(trans, flags);
412679bd3712SFilipe Manana 		if (IS_ERR(bg)) {
412779bd3712SFilipe Manana 			ret = PTR_ERR(bg);
41282bb2e00eSFilipe Manana 		} else {
412979bd3712SFilipe Manana 			/*
4130b6a98021SNaohiro Aota 			 * We have a new chunk. We also need to activate it for
4131b6a98021SNaohiro Aota 			 * zoned filesystem.
4132b6a98021SNaohiro Aota 			 */
4133b6a98021SNaohiro Aota 			ret = btrfs_zoned_activate_one_bg(fs_info, info, true);
4134b6a98021SNaohiro Aota 			if (ret < 0)
4135b6a98021SNaohiro Aota 				return;
4136b6a98021SNaohiro Aota 
4137b6a98021SNaohiro Aota 			/*
413879bd3712SFilipe Manana 			 * If we fail to add the chunk item here, we end up
413979bd3712SFilipe Manana 			 * trying again at phase 2 of chunk allocation, at
414079bd3712SFilipe Manana 			 * btrfs_create_pending_block_groups(). So ignore
41412bb2e00eSFilipe Manana 			 * any error here. An ENOSPC here could happen, due to
41422bb2e00eSFilipe Manana 			 * the cases described at do_chunk_alloc() - the system
41432bb2e00eSFilipe Manana 			 * block group we just created was just turned into RO
41442bb2e00eSFilipe Manana 			 * mode by a scrub for example, or a running discard
41452bb2e00eSFilipe Manana 			 * temporarily removed its free space entries, etc.
414679bd3712SFilipe Manana 			 */
414779bd3712SFilipe Manana 			btrfs_chunk_alloc_add_chunk_item(trans, bg);
414879bd3712SFilipe Manana 		}
414907730d87SJosef Bacik 	}
415007730d87SJosef Bacik 
415107730d87SJosef Bacik 	if (!ret) {
41529270501cSJosef Bacik 		ret = btrfs_block_rsv_add(fs_info,
415307730d87SJosef Bacik 					  &fs_info->chunk_block_rsv,
41542bb2e00eSFilipe Manana 					  bytes, BTRFS_RESERVE_NO_FLUSH);
41551cb3db1cSFilipe Manana 		if (!ret)
41562bb2e00eSFilipe Manana 			trans->chunk_bytes_reserved += bytes;
415707730d87SJosef Bacik 	}
415807730d87SJosef Bacik }
415907730d87SJosef Bacik 
41602bb2e00eSFilipe Manana /*
41612bb2e00eSFilipe Manana  * Reserve space in the system space for allocating or removing a chunk.
41622bb2e00eSFilipe Manana  * The caller must be holding fs_info->chunk_mutex.
41632bb2e00eSFilipe Manana  */
41642bb2e00eSFilipe Manana void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
41652bb2e00eSFilipe Manana {
41662bb2e00eSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
41672bb2e00eSFilipe Manana 	const u64 num_devs = get_profile_num_devs(fs_info, type);
41682bb2e00eSFilipe Manana 	u64 bytes;
41692bb2e00eSFilipe Manana 
41702bb2e00eSFilipe Manana 	/* num_devs device items to update and 1 chunk item to add or remove. */
41712bb2e00eSFilipe Manana 	bytes = btrfs_calc_metadata_size(fs_info, num_devs) +
41722bb2e00eSFilipe Manana 		btrfs_calc_insert_metadata_size(fs_info, 1);
41732bb2e00eSFilipe Manana 
41742bb2e00eSFilipe Manana 	reserve_chunk_space(trans, bytes, type);
41752bb2e00eSFilipe Manana }
41762bb2e00eSFilipe Manana 
41772bb2e00eSFilipe Manana /*
41782bb2e00eSFilipe Manana  * Reserve space in the system space, if needed, for doing a modification to the
41792bb2e00eSFilipe Manana  * chunk btree.
41802bb2e00eSFilipe Manana  *
41812bb2e00eSFilipe Manana  * @trans:		A transaction handle.
41822bb2e00eSFilipe Manana  * @is_item_insertion:	Indicate if the modification is for inserting a new item
41832bb2e00eSFilipe Manana  *			in the chunk btree or if it's for the deletion or update
41842bb2e00eSFilipe Manana  *			of an existing item.
41852bb2e00eSFilipe Manana  *
41862bb2e00eSFilipe Manana  * This is used in a context where we need to update the chunk btree outside
41872bb2e00eSFilipe Manana  * block group allocation and removal, to avoid a deadlock with a concurrent
41882bb2e00eSFilipe Manana  * task that is allocating a metadata or data block group and therefore needs to
41892bb2e00eSFilipe Manana  * update the chunk btree while holding the chunk mutex. After the update to the
41902bb2e00eSFilipe Manana  * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called.
41912bb2e00eSFilipe Manana  *
41922bb2e00eSFilipe Manana  */
41932bb2e00eSFilipe Manana void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans,
41942bb2e00eSFilipe Manana 				  bool is_item_insertion)
41952bb2e00eSFilipe Manana {
41962bb2e00eSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
41972bb2e00eSFilipe Manana 	u64 bytes;
41982bb2e00eSFilipe Manana 
41992bb2e00eSFilipe Manana 	if (is_item_insertion)
42002bb2e00eSFilipe Manana 		bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
42012bb2e00eSFilipe Manana 	else
42022bb2e00eSFilipe Manana 		bytes = btrfs_calc_metadata_size(fs_info, 1);
42032bb2e00eSFilipe Manana 
42042bb2e00eSFilipe Manana 	mutex_lock(&fs_info->chunk_mutex);
42052bb2e00eSFilipe Manana 	reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM);
42062bb2e00eSFilipe Manana 	mutex_unlock(&fs_info->chunk_mutex);
42072bb2e00eSFilipe Manana }
42082bb2e00eSFilipe Manana 
42093e43c279SJosef Bacik void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
42103e43c279SJosef Bacik {
421132da5386SDavid Sterba 	struct btrfs_block_group *block_group;
42123e43c279SJosef Bacik 
421350c31eaaSJosef Bacik 	block_group = btrfs_lookup_first_block_group(info, 0);
42143e43c279SJosef Bacik 	while (block_group) {
42153e43c279SJosef Bacik 		btrfs_wait_block_group_cache_done(block_group);
42163e43c279SJosef Bacik 		spin_lock(&block_group->lock);
421750c31eaaSJosef Bacik 		if (test_and_clear_bit(BLOCK_GROUP_FLAG_IREF,
421850c31eaaSJosef Bacik 				       &block_group->runtime_flags)) {
421950c31eaaSJosef Bacik 			struct inode *inode = block_group->inode;
42203e43c279SJosef Bacik 
42213e43c279SJosef Bacik 			block_group->inode = NULL;
42223e43c279SJosef Bacik 			spin_unlock(&block_group->lock);
422350c31eaaSJosef Bacik 
42243e43c279SJosef Bacik 			ASSERT(block_group->io_ctl.inode == NULL);
42253e43c279SJosef Bacik 			iput(inode);
422650c31eaaSJosef Bacik 		} else {
422750c31eaaSJosef Bacik 			spin_unlock(&block_group->lock);
422850c31eaaSJosef Bacik 		}
422950c31eaaSJosef Bacik 		block_group = btrfs_next_block_group(block_group);
42303e43c279SJosef Bacik 	}
42313e43c279SJosef Bacik }
42323e43c279SJosef Bacik 
42333e43c279SJosef Bacik /*
42343e43c279SJosef Bacik  * Must be called only after stopping all workers, since we could have block
42353e43c279SJosef Bacik  * group caching kthreads running, and therefore they could race with us if we
42363e43c279SJosef Bacik  * freed the block groups before stopping them.
42373e43c279SJosef Bacik  */
42383e43c279SJosef Bacik int btrfs_free_block_groups(struct btrfs_fs_info *info)
42393e43c279SJosef Bacik {
424032da5386SDavid Sterba 	struct btrfs_block_group *block_group;
42413e43c279SJosef Bacik 	struct btrfs_space_info *space_info;
42423e43c279SJosef Bacik 	struct btrfs_caching_control *caching_ctl;
42433e43c279SJosef Bacik 	struct rb_node *n;
42443e43c279SJosef Bacik 
424516b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
42463e43c279SJosef Bacik 	while (!list_empty(&info->caching_block_groups)) {
42473e43c279SJosef Bacik 		caching_ctl = list_entry(info->caching_block_groups.next,
42483e43c279SJosef Bacik 					 struct btrfs_caching_control, list);
42493e43c279SJosef Bacik 		list_del(&caching_ctl->list);
42503e43c279SJosef Bacik 		btrfs_put_caching_control(caching_ctl);
42513e43c279SJosef Bacik 	}
425216b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
42533e43c279SJosef Bacik 
42543e43c279SJosef Bacik 	spin_lock(&info->unused_bgs_lock);
42553e43c279SJosef Bacik 	while (!list_empty(&info->unused_bgs)) {
42563e43c279SJosef Bacik 		block_group = list_first_entry(&info->unused_bgs,
425732da5386SDavid Sterba 					       struct btrfs_block_group,
42583e43c279SJosef Bacik 					       bg_list);
42593e43c279SJosef Bacik 		list_del_init(&block_group->bg_list);
42603e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
42613e43c279SJosef Bacik 	}
42623e43c279SJosef Bacik 
426318bb8bbfSJohannes Thumshirn 	while (!list_empty(&info->reclaim_bgs)) {
426418bb8bbfSJohannes Thumshirn 		block_group = list_first_entry(&info->reclaim_bgs,
426518bb8bbfSJohannes Thumshirn 					       struct btrfs_block_group,
426618bb8bbfSJohannes Thumshirn 					       bg_list);
426718bb8bbfSJohannes Thumshirn 		list_del_init(&block_group->bg_list);
426818bb8bbfSJohannes Thumshirn 		btrfs_put_block_group(block_group);
426918bb8bbfSJohannes Thumshirn 	}
427018bb8bbfSJohannes Thumshirn 	spin_unlock(&info->unused_bgs_lock);
427118bb8bbfSJohannes Thumshirn 
4272afba2bc0SNaohiro Aota 	spin_lock(&info->zone_active_bgs_lock);
4273afba2bc0SNaohiro Aota 	while (!list_empty(&info->zone_active_bgs)) {
4274afba2bc0SNaohiro Aota 		block_group = list_first_entry(&info->zone_active_bgs,
4275afba2bc0SNaohiro Aota 					       struct btrfs_block_group,
4276afba2bc0SNaohiro Aota 					       active_bg_list);
4277afba2bc0SNaohiro Aota 		list_del_init(&block_group->active_bg_list);
4278afba2bc0SNaohiro Aota 		btrfs_put_block_group(block_group);
4279afba2bc0SNaohiro Aota 	}
4280afba2bc0SNaohiro Aota 	spin_unlock(&info->zone_active_bgs_lock);
4281afba2bc0SNaohiro Aota 
428216b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
428308dddb29SFilipe Manana 	while ((n = rb_last(&info->block_group_cache_tree.rb_root)) != NULL) {
428432da5386SDavid Sterba 		block_group = rb_entry(n, struct btrfs_block_group,
42853e43c279SJosef Bacik 				       cache_node);
428608dddb29SFilipe Manana 		rb_erase_cached(&block_group->cache_node,
42873e43c279SJosef Bacik 				&info->block_group_cache_tree);
42883e43c279SJosef Bacik 		RB_CLEAR_NODE(&block_group->cache_node);
428916b0c258SFilipe Manana 		write_unlock(&info->block_group_cache_lock);
42903e43c279SJosef Bacik 
42913e43c279SJosef Bacik 		down_write(&block_group->space_info->groups_sem);
42923e43c279SJosef Bacik 		list_del(&block_group->list);
42933e43c279SJosef Bacik 		up_write(&block_group->space_info->groups_sem);
42943e43c279SJosef Bacik 
42953e43c279SJosef Bacik 		/*
42963e43c279SJosef Bacik 		 * We haven't cached this block group, which means we could
42973e43c279SJosef Bacik 		 * possibly have excluded extents on this block group.
42983e43c279SJosef Bacik 		 */
42993e43c279SJosef Bacik 		if (block_group->cached == BTRFS_CACHE_NO ||
43003e43c279SJosef Bacik 		    block_group->cached == BTRFS_CACHE_ERROR)
43013e43c279SJosef Bacik 			btrfs_free_excluded_extents(block_group);
43023e43c279SJosef Bacik 
43033e43c279SJosef Bacik 		btrfs_remove_free_space_cache(block_group);
43043e43c279SJosef Bacik 		ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
43053e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->dirty_list));
43063e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->io_list));
43073e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->bg_list));
430848aaeebeSJosef Bacik 		ASSERT(refcount_read(&block_group->refs) == 1);
4309195a49eaSFilipe Manana 		ASSERT(block_group->swap_extents == 0);
43103e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
43113e43c279SJosef Bacik 
431216b0c258SFilipe Manana 		write_lock(&info->block_group_cache_lock);
43133e43c279SJosef Bacik 	}
431416b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
43153e43c279SJosef Bacik 
43163e43c279SJosef Bacik 	btrfs_release_global_block_rsv(info);
43173e43c279SJosef Bacik 
43183e43c279SJosef Bacik 	while (!list_empty(&info->space_info)) {
43193e43c279SJosef Bacik 		space_info = list_entry(info->space_info.next,
43203e43c279SJosef Bacik 					struct btrfs_space_info,
43213e43c279SJosef Bacik 					list);
43223e43c279SJosef Bacik 
43233e43c279SJosef Bacik 		/*
43243e43c279SJosef Bacik 		 * Do not hide this behind enospc_debug, this is actually
43253e43c279SJosef Bacik 		 * important and indicates a real bug if this happens.
43263e43c279SJosef Bacik 		 */
43273e43c279SJosef Bacik 		if (WARN_ON(space_info->bytes_pinned > 0 ||
43283e43c279SJosef Bacik 			    space_info->bytes_may_use > 0))
43293e43c279SJosef Bacik 			btrfs_dump_space_info(info, space_info, 0, 0);
433040cdc509SFilipe Manana 
433140cdc509SFilipe Manana 		/*
433240cdc509SFilipe Manana 		 * If there was a failure to cleanup a log tree, very likely due
433340cdc509SFilipe Manana 		 * to an IO failure on a writeback attempt of one or more of its
433440cdc509SFilipe Manana 		 * extent buffers, we could not do proper (and cheap) unaccounting
433540cdc509SFilipe Manana 		 * of their reserved space, so don't warn on bytes_reserved > 0 in
433640cdc509SFilipe Manana 		 * that case.
433740cdc509SFilipe Manana 		 */
433840cdc509SFilipe Manana 		if (!(space_info->flags & BTRFS_BLOCK_GROUP_METADATA) ||
433940cdc509SFilipe Manana 		    !BTRFS_FS_LOG_CLEANUP_ERROR(info)) {
434040cdc509SFilipe Manana 			if (WARN_ON(space_info->bytes_reserved > 0))
434140cdc509SFilipe Manana 				btrfs_dump_space_info(info, space_info, 0, 0);
434240cdc509SFilipe Manana 		}
434340cdc509SFilipe Manana 
4344d611add4SFilipe Manana 		WARN_ON(space_info->reclaim_size > 0);
43453e43c279SJosef Bacik 		list_del(&space_info->list);
43463e43c279SJosef Bacik 		btrfs_sysfs_remove_space_info(space_info);
43473e43c279SJosef Bacik 	}
43483e43c279SJosef Bacik 	return 0;
43493e43c279SJosef Bacik }
4350684b752bSFilipe Manana 
4351684b752bSFilipe Manana void btrfs_freeze_block_group(struct btrfs_block_group *cache)
4352684b752bSFilipe Manana {
4353684b752bSFilipe Manana 	atomic_inc(&cache->frozen);
4354684b752bSFilipe Manana }
4355684b752bSFilipe Manana 
4356684b752bSFilipe Manana void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
4357684b752bSFilipe Manana {
4358684b752bSFilipe Manana 	struct btrfs_fs_info *fs_info = block_group->fs_info;
4359684b752bSFilipe Manana 	struct extent_map_tree *em_tree;
4360684b752bSFilipe Manana 	struct extent_map *em;
4361684b752bSFilipe Manana 	bool cleanup;
4362684b752bSFilipe Manana 
4363684b752bSFilipe Manana 	spin_lock(&block_group->lock);
4364684b752bSFilipe Manana 	cleanup = (atomic_dec_and_test(&block_group->frozen) &&
43653349b57fSJosef Bacik 		   test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags));
4366684b752bSFilipe Manana 	spin_unlock(&block_group->lock);
4367684b752bSFilipe Manana 
4368684b752bSFilipe Manana 	if (cleanup) {
4369684b752bSFilipe Manana 		em_tree = &fs_info->mapping_tree;
4370684b752bSFilipe Manana 		write_lock(&em_tree->lock);
4371684b752bSFilipe Manana 		em = lookup_extent_mapping(em_tree, block_group->start,
4372684b752bSFilipe Manana 					   1);
4373684b752bSFilipe Manana 		BUG_ON(!em); /* logic error, can't happen */
4374684b752bSFilipe Manana 		remove_extent_mapping(em_tree, em);
4375684b752bSFilipe Manana 		write_unlock(&em_tree->lock);
4376684b752bSFilipe Manana 
4377684b752bSFilipe Manana 		/* once for us and once for the tree */
4378684b752bSFilipe Manana 		free_extent_map(em);
4379684b752bSFilipe Manana 		free_extent_map(em);
4380684b752bSFilipe Manana 
4381684b752bSFilipe Manana 		/*
4382684b752bSFilipe Manana 		 * We may have left one free space entry and other possible
4383684b752bSFilipe Manana 		 * tasks trimming this block group have left 1 entry each one.
4384684b752bSFilipe Manana 		 * Free them if any.
4385684b752bSFilipe Manana 		 */
4386fc80f7acSJosef Bacik 		btrfs_remove_free_space_cache(block_group);
4387684b752bSFilipe Manana 	}
4388684b752bSFilipe Manana }
4389195a49eaSFilipe Manana 
4390195a49eaSFilipe Manana bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
4391195a49eaSFilipe Manana {
4392195a49eaSFilipe Manana 	bool ret = true;
4393195a49eaSFilipe Manana 
4394195a49eaSFilipe Manana 	spin_lock(&bg->lock);
4395195a49eaSFilipe Manana 	if (bg->ro)
4396195a49eaSFilipe Manana 		ret = false;
4397195a49eaSFilipe Manana 	else
4398195a49eaSFilipe Manana 		bg->swap_extents++;
4399195a49eaSFilipe Manana 	spin_unlock(&bg->lock);
4400195a49eaSFilipe Manana 
4401195a49eaSFilipe Manana 	return ret;
4402195a49eaSFilipe Manana }
4403195a49eaSFilipe Manana 
4404195a49eaSFilipe Manana void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
4405195a49eaSFilipe Manana {
4406195a49eaSFilipe Manana 	spin_lock(&bg->lock);
4407195a49eaSFilipe Manana 	ASSERT(!bg->ro);
4408195a49eaSFilipe Manana 	ASSERT(bg->swap_extents >= amount);
4409195a49eaSFilipe Manana 	bg->swap_extents -= amount;
4410195a49eaSFilipe Manana 	spin_unlock(&bg->lock);
4411195a49eaSFilipe Manana }
441252bb7a21SBoris Burkov 
441352bb7a21SBoris Burkov enum btrfs_block_group_size_class btrfs_calc_block_group_size_class(u64 size)
441452bb7a21SBoris Burkov {
441552bb7a21SBoris Burkov 	if (size <= SZ_128K)
441652bb7a21SBoris Burkov 		return BTRFS_BG_SZ_SMALL;
441752bb7a21SBoris Burkov 	if (size <= SZ_8M)
441852bb7a21SBoris Burkov 		return BTRFS_BG_SZ_MEDIUM;
441952bb7a21SBoris Burkov 	return BTRFS_BG_SZ_LARGE;
442052bb7a21SBoris Burkov }
442152bb7a21SBoris Burkov 
442252bb7a21SBoris Burkov /*
442352bb7a21SBoris Burkov  * Handle a block group allocating an extent in a size class
442452bb7a21SBoris Burkov  *
442552bb7a21SBoris Burkov  * @bg:				The block group we allocated in.
442652bb7a21SBoris Burkov  * @size_class:			The size class of the allocation.
442752bb7a21SBoris Burkov  * @force_wrong_size_class:	Whether we are desperate enough to allow
442852bb7a21SBoris Burkov  *				mismatched size classes.
442952bb7a21SBoris Burkov  *
443052bb7a21SBoris Burkov  * Returns: 0 if the size class was valid for this block_group, -EAGAIN in the
443152bb7a21SBoris Burkov  * case of a race that leads to the wrong size class without
443252bb7a21SBoris Burkov  * force_wrong_size_class set.
443352bb7a21SBoris Burkov  *
443452bb7a21SBoris Burkov  * find_free_extent will skip block groups with a mismatched size class until
443552bb7a21SBoris Burkov  * it really needs to avoid ENOSPC. In that case it will set
443652bb7a21SBoris Burkov  * force_wrong_size_class. However, if a block group is newly allocated and
443752bb7a21SBoris Burkov  * doesn't yet have a size class, then it is possible for two allocations of
443852bb7a21SBoris Burkov  * different sizes to race and both try to use it. The loser is caught here and
443952bb7a21SBoris Burkov  * has to retry.
444052bb7a21SBoris Burkov  */
444152bb7a21SBoris Burkov int btrfs_use_block_group_size_class(struct btrfs_block_group *bg,
444252bb7a21SBoris Burkov 				     enum btrfs_block_group_size_class size_class,
444352bb7a21SBoris Burkov 				     bool force_wrong_size_class)
444452bb7a21SBoris Burkov {
444552bb7a21SBoris Burkov 	ASSERT(size_class != BTRFS_BG_SZ_NONE);
444652bb7a21SBoris Burkov 
444752bb7a21SBoris Burkov 	/* The new allocation is in the right size class, do nothing */
444852bb7a21SBoris Burkov 	if (bg->size_class == size_class)
444952bb7a21SBoris Burkov 		return 0;
445052bb7a21SBoris Burkov 	/*
445152bb7a21SBoris Burkov 	 * The new allocation is in a mismatched size class.
445252bb7a21SBoris Burkov 	 * This means one of two things:
445352bb7a21SBoris Burkov 	 *
445452bb7a21SBoris Burkov 	 * 1. Two tasks in find_free_extent for different size_classes raced
445552bb7a21SBoris Burkov 	 *    and hit the same empty block_group. Make the loser try again.
445652bb7a21SBoris Burkov 	 * 2. A call to find_free_extent got desperate enough to set
445752bb7a21SBoris Burkov 	 *    'force_wrong_slab'. Don't change the size_class, but allow the
445852bb7a21SBoris Burkov 	 *    allocation.
445952bb7a21SBoris Burkov 	 */
446052bb7a21SBoris Burkov 	if (bg->size_class != BTRFS_BG_SZ_NONE) {
446152bb7a21SBoris Burkov 		if (force_wrong_size_class)
446252bb7a21SBoris Burkov 			return 0;
446352bb7a21SBoris Burkov 		return -EAGAIN;
446452bb7a21SBoris Burkov 	}
446552bb7a21SBoris Burkov 	/*
446652bb7a21SBoris Burkov 	 * The happy new block group case: the new allocation is the first
446752bb7a21SBoris Burkov 	 * one in the block_group so we set size_class.
446852bb7a21SBoris Burkov 	 */
446952bb7a21SBoris Burkov 	bg->size_class = size_class;
447052bb7a21SBoris Burkov 
447152bb7a21SBoris Burkov 	return 0;
447252bb7a21SBoris Burkov }
4473cb0922f2SBoris Burkov 
4474cb0922f2SBoris Burkov bool btrfs_block_group_should_use_size_class(struct btrfs_block_group *bg)
4475cb0922f2SBoris Burkov {
4476cb0922f2SBoris Burkov 	if (btrfs_is_zoned(bg->fs_info))
4477cb0922f2SBoris Burkov 		return false;
4478cb0922f2SBoris Burkov 	if (!btrfs_is_block_group_data_only(bg))
4479cb0922f2SBoris Burkov 		return false;
4480cb0922f2SBoris Burkov 	return true;
4481cb0922f2SBoris Burkov }
4482