xref: /openbmc/linux/fs/btrfs/block-group.c (revision e50e86dbcabda570fc8a1435fe2fca97e9ab7312)
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
btrfs_should_fragment_free_space(struct btrfs_block_group * block_group)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  */
get_restripe_target(struct btrfs_fs_info * fs_info,u64 flags)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  */
btrfs_reduce_alloc_profile(struct btrfs_fs_info * fs_info,u64 flags)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 
btrfs_get_alloc_profile(struct btrfs_fs_info * fs_info,u64 orig_flags)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 
btrfs_get_block_group(struct btrfs_block_group * cache)14132da5386SDavid Sterba void btrfs_get_block_group(struct btrfs_block_group *cache)
1423cad1284SJosef Bacik {
14348aaeebeSJosef Bacik 	refcount_inc(&cache->refs);
1443cad1284SJosef Bacik }
1453cad1284SJosef Bacik 
btrfs_put_block_group(struct btrfs_block_group * cache)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  */
btrfs_add_block_group_cache(struct btrfs_fs_info * info,struct btrfs_block_group * block_group)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  */
block_group_cache_tree_search(struct btrfs_fs_info * info,u64 bytenr,int contains)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  */
btrfs_lookup_first_block_group(struct btrfs_fs_info * info,u64 bytenr)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  */
btrfs_lookup_block_group(struct btrfs_fs_info * info,u64 bytenr)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 
btrfs_next_block_group(struct btrfs_block_group * cache)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  */
btrfs_inc_nocow_writers(struct btrfs_fs_info * fs_info,u64 bytenr)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  */
btrfs_dec_nocow_writers(struct btrfs_block_group * bg)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 
btrfs_wait_nocow_writers(struct btrfs_block_group * bg)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 
btrfs_dec_block_group_reservations(struct btrfs_fs_info * fs_info,const u64 start)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 
btrfs_wait_block_group_reservations(struct btrfs_block_group * bg)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 
btrfs_get_caching_control(struct btrfs_block_group * cache)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 
btrfs_put_caching_control(struct btrfs_caching_control * ctl)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  */
btrfs_wait_block_group_cache_progress(struct btrfs_block_group * cache,u64 num_bytes)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;
444fc1f91b9SJosef Bacik 	int progress;
4459f21246dSJosef Bacik 
4469f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4479f21246dSJosef Bacik 	if (!caching_ctl)
4489f21246dSJosef Bacik 		return;
4499f21246dSJosef Bacik 
450fc1f91b9SJosef Bacik 	/*
451fc1f91b9SJosef Bacik 	 * We've already failed to allocate from this block group, so even if
452fc1f91b9SJosef Bacik 	 * there's enough space in the block group it isn't contiguous enough to
453fc1f91b9SJosef Bacik 	 * allow for an allocation, so wait for at least the next wakeup tick,
454fc1f91b9SJosef Bacik 	 * or for the thing to be done.
455fc1f91b9SJosef Bacik 	 */
456fc1f91b9SJosef Bacik 	progress = atomic_read(&caching_ctl->progress);
457fc1f91b9SJosef Bacik 
45832da5386SDavid Sterba 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
459fc1f91b9SJosef Bacik 		   (progress != atomic_read(&caching_ctl->progress) &&
460fc1f91b9SJosef Bacik 		    (cache->free_space_ctl->free_space >= num_bytes)));
4619f21246dSJosef Bacik 
4629f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4639f21246dSJosef Bacik }
4649f21246dSJosef Bacik 
btrfs_caching_ctl_wait_done(struct btrfs_block_group * cache,struct btrfs_caching_control * caching_ctl)465ced8ecf0SOmar Sandoval static int btrfs_caching_ctl_wait_done(struct btrfs_block_group *cache,
466ced8ecf0SOmar Sandoval 				       struct btrfs_caching_control *caching_ctl)
467ced8ecf0SOmar Sandoval {
468ced8ecf0SOmar Sandoval 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
469ced8ecf0SOmar Sandoval 	return cache->cached == BTRFS_CACHE_ERROR ? -EIO : 0;
470ced8ecf0SOmar Sandoval }
471ced8ecf0SOmar Sandoval 
btrfs_wait_block_group_cache_done(struct btrfs_block_group * cache)472ced8ecf0SOmar Sandoval static int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
4739f21246dSJosef Bacik {
4749f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
475ced8ecf0SOmar Sandoval 	int ret;
4769f21246dSJosef Bacik 
4779f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4789f21246dSJosef Bacik 	if (!caching_ctl)
4799f21246dSJosef Bacik 		return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
480ced8ecf0SOmar Sandoval 	ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
4819f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4829f21246dSJosef Bacik 	return ret;
4839f21246dSJosef Bacik }
4849f21246dSJosef Bacik 
4859f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
fragment_free_space(struct btrfs_block_group * block_group)48632da5386SDavid Sterba static void fragment_free_space(struct btrfs_block_group *block_group)
4879f21246dSJosef Bacik {
4889f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
489b3470b5dSDavid Sterba 	u64 start = block_group->start;
490b3470b5dSDavid Sterba 	u64 len = block_group->length;
4919f21246dSJosef Bacik 	u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
4929f21246dSJosef Bacik 		fs_info->nodesize : fs_info->sectorsize;
4939f21246dSJosef Bacik 	u64 step = chunk << 1;
4949f21246dSJosef Bacik 
4959f21246dSJosef Bacik 	while (len > chunk) {
4969f21246dSJosef Bacik 		btrfs_remove_free_space(block_group, start, chunk);
4979f21246dSJosef Bacik 		start += step;
4989f21246dSJosef Bacik 		if (len < step)
4999f21246dSJosef Bacik 			len = 0;
5009f21246dSJosef Bacik 		else
5019f21246dSJosef Bacik 			len -= step;
5029f21246dSJosef Bacik 	}
5039f21246dSJosef Bacik }
5049f21246dSJosef Bacik #endif
5059f21246dSJosef Bacik 
5069f21246dSJosef Bacik /*
50728f60894SFilipe Manana  * Add a free space range to the in memory free space cache of a block group.
50828f60894SFilipe Manana  * This checks if the range contains super block locations and any such
50928f60894SFilipe Manana  * locations are not added to the free space cache.
51028f60894SFilipe Manana  *
51128f60894SFilipe Manana  * @block_group:      The target block group.
51228f60894SFilipe Manana  * @start:            Start offset of the range.
51328f60894SFilipe Manana  * @end:              End offset of the range (exclusive).
51428f60894SFilipe Manana  * @total_added_ret:  Optional pointer to return the total amount of space
51528f60894SFilipe Manana  *                    added to the block group's free space cache.
51628f60894SFilipe Manana  *
51728f60894SFilipe Manana  * Returns 0 on success or < 0 on error.
5189f21246dSJosef Bacik  */
btrfs_add_new_free_space(struct btrfs_block_group * block_group,u64 start,u64 end,u64 * total_added_ret)5193b9f0995SFilipe Manana int btrfs_add_new_free_space(struct btrfs_block_group *block_group, u64 start,
5203b9f0995SFilipe Manana 			     u64 end, u64 *total_added_ret)
5219f21246dSJosef Bacik {
5229f21246dSJosef Bacik 	struct btrfs_fs_info *info = block_group->fs_info;
523d8ccbd21SFilipe Manana 	u64 extent_start, extent_end, size;
5249f21246dSJosef Bacik 	int ret;
5259f21246dSJosef Bacik 
526d8ccbd21SFilipe Manana 	if (total_added_ret)
527d8ccbd21SFilipe Manana 		*total_added_ret = 0;
528d8ccbd21SFilipe Manana 
5299f21246dSJosef Bacik 	while (start < end) {
530e5860f82SFilipe Manana 		if (!find_first_extent_bit(&info->excluded_extents, start,
5319f21246dSJosef Bacik 					   &extent_start, &extent_end,
5329f21246dSJosef Bacik 					   EXTENT_DIRTY | EXTENT_UPTODATE,
533e5860f82SFilipe Manana 					   NULL))
5349f21246dSJosef Bacik 			break;
5359f21246dSJosef Bacik 
5369f21246dSJosef Bacik 		if (extent_start <= start) {
5379f21246dSJosef Bacik 			start = extent_end + 1;
5389f21246dSJosef Bacik 		} else if (extent_start > start && extent_start < end) {
5399f21246dSJosef Bacik 			size = extent_start - start;
540b0643e59SDennis Zhou 			ret = btrfs_add_free_space_async_trimmed(block_group,
541b0643e59SDennis Zhou 								 start, size);
542d8ccbd21SFilipe Manana 			if (ret)
543d8ccbd21SFilipe Manana 				return ret;
544d8ccbd21SFilipe Manana 			if (total_added_ret)
545d8ccbd21SFilipe Manana 				*total_added_ret += size;
5469f21246dSJosef Bacik 			start = extent_end + 1;
5479f21246dSJosef Bacik 		} else {
5489f21246dSJosef Bacik 			break;
5499f21246dSJosef Bacik 		}
5509f21246dSJosef Bacik 	}
5519f21246dSJosef Bacik 
5529f21246dSJosef Bacik 	if (start < end) {
5539f21246dSJosef Bacik 		size = end - start;
554b0643e59SDennis Zhou 		ret = btrfs_add_free_space_async_trimmed(block_group, start,
555b0643e59SDennis Zhou 							 size);
556d8ccbd21SFilipe Manana 		if (ret)
557d8ccbd21SFilipe Manana 			return ret;
558d8ccbd21SFilipe Manana 		if (total_added_ret)
559d8ccbd21SFilipe Manana 			*total_added_ret += size;
5609f21246dSJosef Bacik 	}
5619f21246dSJosef Bacik 
562d8ccbd21SFilipe Manana 	return 0;
5639f21246dSJosef Bacik }
5649f21246dSJosef Bacik 
565c7eec3d9SBoris Burkov /*
566c7eec3d9SBoris Burkov  * Get an arbitrary extent item index / max_index through the block group
567c7eec3d9SBoris Burkov  *
568c7eec3d9SBoris Burkov  * @block_group   the block group to sample from
569c7eec3d9SBoris Burkov  * @index:        the integral step through the block group to grab from
570c7eec3d9SBoris Burkov  * @max_index:    the granularity of the sampling
571c7eec3d9SBoris Burkov  * @key:          return value parameter for the item we find
572c7eec3d9SBoris Burkov  *
573c7eec3d9SBoris Burkov  * Pre-conditions on indices:
574c7eec3d9SBoris Burkov  * 0 <= index <= max_index
575c7eec3d9SBoris Burkov  * 0 < max_index
576c7eec3d9SBoris Burkov  *
577c7eec3d9SBoris Burkov  * Returns: 0 on success, 1 if the search didn't yield a useful item, negative
578c7eec3d9SBoris Burkov  * error code on error.
579c7eec3d9SBoris Burkov  */
sample_block_group_extent_item(struct btrfs_caching_control * caching_ctl,struct btrfs_block_group * block_group,int index,int max_index,struct btrfs_key * found_key)580c7eec3d9SBoris Burkov static int sample_block_group_extent_item(struct btrfs_caching_control *caching_ctl,
581c7eec3d9SBoris Burkov 					  struct btrfs_block_group *block_group,
582c7eec3d9SBoris Burkov 					  int index, int max_index,
58312148367SBoris Burkov 					  struct btrfs_key *found_key)
584c7eec3d9SBoris Burkov {
585c7eec3d9SBoris Burkov 	struct btrfs_fs_info *fs_info = block_group->fs_info;
586c7eec3d9SBoris Burkov 	struct btrfs_root *extent_root;
587c7eec3d9SBoris Burkov 	u64 search_offset;
588c7eec3d9SBoris Burkov 	u64 search_end = block_group->start + block_group->length;
589c7eec3d9SBoris Burkov 	struct btrfs_path *path;
59012148367SBoris Burkov 	struct btrfs_key search_key;
59112148367SBoris Burkov 	int ret = 0;
592c7eec3d9SBoris Burkov 
593c7eec3d9SBoris Burkov 	ASSERT(index >= 0);
594c7eec3d9SBoris Burkov 	ASSERT(index <= max_index);
595c7eec3d9SBoris Burkov 	ASSERT(max_index > 0);
596c7eec3d9SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
597c7eec3d9SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
598c7eec3d9SBoris Burkov 
599c7eec3d9SBoris Burkov 	path = btrfs_alloc_path();
600c7eec3d9SBoris Burkov 	if (!path)
601c7eec3d9SBoris Burkov 		return -ENOMEM;
602c7eec3d9SBoris Burkov 
603c7eec3d9SBoris Burkov 	extent_root = btrfs_extent_root(fs_info, max_t(u64, block_group->start,
604c7eec3d9SBoris Burkov 						       BTRFS_SUPER_INFO_OFFSET));
605c7eec3d9SBoris Burkov 
606c7eec3d9SBoris Burkov 	path->skip_locking = 1;
607c7eec3d9SBoris Burkov 	path->search_commit_root = 1;
608c7eec3d9SBoris Burkov 	path->reada = READA_FORWARD;
609c7eec3d9SBoris Burkov 
610c7eec3d9SBoris Burkov 	search_offset = index * div_u64(block_group->length, max_index);
61112148367SBoris Burkov 	search_key.objectid = block_group->start + search_offset;
61212148367SBoris Burkov 	search_key.type = BTRFS_EXTENT_ITEM_KEY;
61312148367SBoris Burkov 	search_key.offset = 0;
614c7eec3d9SBoris Burkov 
61512148367SBoris Burkov 	btrfs_for_each_slot(extent_root, &search_key, found_key, path, ret) {
616c7eec3d9SBoris Burkov 		/* Success; sampled an extent item in the block group */
61712148367SBoris Burkov 		if (found_key->type == BTRFS_EXTENT_ITEM_KEY &&
61812148367SBoris Burkov 		    found_key->objectid >= block_group->start &&
61912148367SBoris Burkov 		    found_key->objectid + found_key->offset <= search_end)
62012148367SBoris Burkov 			break;
621c7eec3d9SBoris Burkov 
622c7eec3d9SBoris Burkov 		/* We can't possibly find a valid extent item anymore */
62312148367SBoris Burkov 		if (found_key->objectid >= search_end) {
624c7eec3d9SBoris Burkov 			ret = 1;
625c7eec3d9SBoris Burkov 			break;
626c7eec3d9SBoris Burkov 		}
627c7eec3d9SBoris Burkov 	}
62812148367SBoris Burkov 
629c7eec3d9SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
630c7eec3d9SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
631c7eec3d9SBoris Burkov 	btrfs_free_path(path);
632c7eec3d9SBoris Burkov 	return ret;
633c7eec3d9SBoris Burkov }
634c7eec3d9SBoris Burkov 
635c7eec3d9SBoris Burkov /*
636c7eec3d9SBoris Burkov  * Best effort attempt to compute a block group's size class while caching it.
637c7eec3d9SBoris Burkov  *
638c7eec3d9SBoris Burkov  * @block_group: the block group we are caching
639c7eec3d9SBoris Burkov  *
640c7eec3d9SBoris Burkov  * We cannot infer the size class while adding free space extents, because that
641c7eec3d9SBoris Burkov  * logic doesn't care about contiguous file extents (it doesn't differentiate
642c7eec3d9SBoris Burkov  * between a 100M extent and 100 contiguous 1M extents). So we need to read the
643c7eec3d9SBoris Burkov  * file extent items. Reading all of them is quite wasteful, because usually
644c7eec3d9SBoris Burkov  * only a handful are enough to give a good answer. Therefore, we just grab 5 of
645c7eec3d9SBoris Burkov  * them at even steps through the block group and pick the smallest size class
646c7eec3d9SBoris Burkov  * we see. Since size class is best effort, and not guaranteed in general,
647c7eec3d9SBoris Burkov  * inaccuracy is acceptable.
648c7eec3d9SBoris Burkov  *
649c7eec3d9SBoris Burkov  * To be more explicit about why this algorithm makes sense:
650c7eec3d9SBoris Burkov  *
651c7eec3d9SBoris Burkov  * If we are caching in a block group from disk, then there are three major cases
652c7eec3d9SBoris Burkov  * to consider:
653c7eec3d9SBoris Burkov  * 1. the block group is well behaved and all extents in it are the same size
654c7eec3d9SBoris Burkov  *    class.
655c7eec3d9SBoris Burkov  * 2. the block group is mostly one size class with rare exceptions for last
656c7eec3d9SBoris Burkov  *    ditch allocations
657c7eec3d9SBoris Burkov  * 3. the block group was populated before size classes and can have a totally
658c7eec3d9SBoris Burkov  *    arbitrary mix of size classes.
659c7eec3d9SBoris Burkov  *
660c7eec3d9SBoris Burkov  * In case 1, looking at any extent in the block group will yield the correct
661c7eec3d9SBoris Burkov  * result. For the mixed cases, taking the minimum size class seems like a good
662c7eec3d9SBoris Burkov  * approximation, since gaps from frees will be usable to the size class. For
663c7eec3d9SBoris Burkov  * 2., a small handful of file extents is likely to yield the right answer. For
664c7eec3d9SBoris Burkov  * 3, we can either read every file extent, or admit that this is best effort
665c7eec3d9SBoris Burkov  * anyway and try to stay fast.
666c7eec3d9SBoris Burkov  *
667c7eec3d9SBoris Burkov  * Returns: 0 on success, negative error code on error.
668c7eec3d9SBoris Burkov  */
load_block_group_size_class(struct btrfs_caching_control * caching_ctl,struct btrfs_block_group * block_group)669c7eec3d9SBoris Burkov static int load_block_group_size_class(struct btrfs_caching_control *caching_ctl,
670c7eec3d9SBoris Burkov 				       struct btrfs_block_group *block_group)
671c7eec3d9SBoris Burkov {
67212148367SBoris Burkov 	struct btrfs_fs_info *fs_info = block_group->fs_info;
673c7eec3d9SBoris Burkov 	struct btrfs_key key;
674c7eec3d9SBoris Burkov 	int i;
675c7eec3d9SBoris Burkov 	u64 min_size = block_group->length;
676c7eec3d9SBoris Burkov 	enum btrfs_block_group_size_class size_class = BTRFS_BG_SZ_NONE;
677c7eec3d9SBoris Burkov 	int ret;
678c7eec3d9SBoris Burkov 
679cb0922f2SBoris Burkov 	if (!btrfs_block_group_should_use_size_class(block_group))
680c7eec3d9SBoris Burkov 		return 0;
681c7eec3d9SBoris Burkov 
68212148367SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
68312148367SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
684c7eec3d9SBoris Burkov 	for (i = 0; i < 5; ++i) {
685c7eec3d9SBoris Burkov 		ret = sample_block_group_extent_item(caching_ctl, block_group, i, 5, &key);
686c7eec3d9SBoris Burkov 		if (ret < 0)
687c7eec3d9SBoris Burkov 			goto out;
688c7eec3d9SBoris Burkov 		if (ret > 0)
689c7eec3d9SBoris Burkov 			continue;
690c7eec3d9SBoris Burkov 		min_size = min_t(u64, min_size, key.offset);
691c7eec3d9SBoris Burkov 		size_class = btrfs_calc_block_group_size_class(min_size);
692c7eec3d9SBoris Burkov 	}
693c7eec3d9SBoris Burkov 	if (size_class != BTRFS_BG_SZ_NONE) {
694c7eec3d9SBoris Burkov 		spin_lock(&block_group->lock);
695c7eec3d9SBoris Burkov 		block_group->size_class = size_class;
696c7eec3d9SBoris Burkov 		spin_unlock(&block_group->lock);
697c7eec3d9SBoris Burkov 	}
698c7eec3d9SBoris Burkov out:
699c7eec3d9SBoris Burkov 	return ret;
700c7eec3d9SBoris Burkov }
701c7eec3d9SBoris Burkov 
load_extent_tree_free(struct btrfs_caching_control * caching_ctl)7029f21246dSJosef Bacik static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
7039f21246dSJosef Bacik {
70432da5386SDavid Sterba 	struct btrfs_block_group *block_group = caching_ctl->block_group;
7059f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
70629cbcf40SJosef Bacik 	struct btrfs_root *extent_root;
7079f21246dSJosef Bacik 	struct btrfs_path *path;
7089f21246dSJosef Bacik 	struct extent_buffer *leaf;
7099f21246dSJosef Bacik 	struct btrfs_key key;
7109f21246dSJosef Bacik 	u64 total_found = 0;
7119f21246dSJosef Bacik 	u64 last = 0;
7129f21246dSJosef Bacik 	u32 nritems;
7139f21246dSJosef Bacik 	int ret;
7149f21246dSJosef Bacik 	bool wakeup = true;
7159f21246dSJosef Bacik 
7169f21246dSJosef Bacik 	path = btrfs_alloc_path();
7179f21246dSJosef Bacik 	if (!path)
7189f21246dSJosef Bacik 		return -ENOMEM;
7199f21246dSJosef Bacik 
720b3470b5dSDavid Sterba 	last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
72129cbcf40SJosef Bacik 	extent_root = btrfs_extent_root(fs_info, last);
7229f21246dSJosef Bacik 
7239f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
7249f21246dSJosef Bacik 	/*
7259f21246dSJosef Bacik 	 * If we're fragmenting we don't want to make anybody think we can
7269f21246dSJosef Bacik 	 * allocate from this block group until we've had a chance to fragment
7279f21246dSJosef Bacik 	 * the free space.
7289f21246dSJosef Bacik 	 */
7299f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group))
7309f21246dSJosef Bacik 		wakeup = false;
7319f21246dSJosef Bacik #endif
7329f21246dSJosef Bacik 	/*
7339f21246dSJosef Bacik 	 * We don't want to deadlock with somebody trying to allocate a new
7349f21246dSJosef Bacik 	 * extent for the extent root while also trying to search the extent
7359f21246dSJosef Bacik 	 * root to add free space.  So we skip locking and search the commit
7369f21246dSJosef Bacik 	 * root, since its read-only
7379f21246dSJosef Bacik 	 */
7389f21246dSJosef Bacik 	path->skip_locking = 1;
7399f21246dSJosef Bacik 	path->search_commit_root = 1;
7409f21246dSJosef Bacik 	path->reada = READA_FORWARD;
7419f21246dSJosef Bacik 
7429f21246dSJosef Bacik 	key.objectid = last;
7439f21246dSJosef Bacik 	key.offset = 0;
7449f21246dSJosef Bacik 	key.type = BTRFS_EXTENT_ITEM_KEY;
7459f21246dSJosef Bacik 
7469f21246dSJosef Bacik next:
7479f21246dSJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
7489f21246dSJosef Bacik 	if (ret < 0)
7499f21246dSJosef Bacik 		goto out;
7509f21246dSJosef Bacik 
7519f21246dSJosef Bacik 	leaf = path->nodes[0];
7529f21246dSJosef Bacik 	nritems = btrfs_header_nritems(leaf);
7539f21246dSJosef Bacik 
7549f21246dSJosef Bacik 	while (1) {
7559f21246dSJosef Bacik 		if (btrfs_fs_closing(fs_info) > 1) {
7569f21246dSJosef Bacik 			last = (u64)-1;
7579f21246dSJosef Bacik 			break;
7589f21246dSJosef Bacik 		}
7599f21246dSJosef Bacik 
7609f21246dSJosef Bacik 		if (path->slots[0] < nritems) {
7619f21246dSJosef Bacik 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7629f21246dSJosef Bacik 		} else {
7639f21246dSJosef Bacik 			ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
7649f21246dSJosef Bacik 			if (ret)
7659f21246dSJosef Bacik 				break;
7669f21246dSJosef Bacik 
7679f21246dSJosef Bacik 			if (need_resched() ||
7689f21246dSJosef Bacik 			    rwsem_is_contended(&fs_info->commit_root_sem)) {
7699f21246dSJosef Bacik 				btrfs_release_path(path);
7709f21246dSJosef Bacik 				up_read(&fs_info->commit_root_sem);
7719f21246dSJosef Bacik 				mutex_unlock(&caching_ctl->mutex);
7729f21246dSJosef Bacik 				cond_resched();
7739f21246dSJosef Bacik 				mutex_lock(&caching_ctl->mutex);
7749f21246dSJosef Bacik 				down_read(&fs_info->commit_root_sem);
7759f21246dSJosef Bacik 				goto next;
7769f21246dSJosef Bacik 			}
7779f21246dSJosef Bacik 
7789f21246dSJosef Bacik 			ret = btrfs_next_leaf(extent_root, path);
7799f21246dSJosef Bacik 			if (ret < 0)
7809f21246dSJosef Bacik 				goto out;
7819f21246dSJosef Bacik 			if (ret)
7829f21246dSJosef Bacik 				break;
7839f21246dSJosef Bacik 			leaf = path->nodes[0];
7849f21246dSJosef Bacik 			nritems = btrfs_header_nritems(leaf);
7859f21246dSJosef Bacik 			continue;
7869f21246dSJosef Bacik 		}
7879f21246dSJosef Bacik 
7889f21246dSJosef Bacik 		if (key.objectid < last) {
7899f21246dSJosef Bacik 			key.objectid = last;
7909f21246dSJosef Bacik 			key.offset = 0;
7919f21246dSJosef Bacik 			key.type = BTRFS_EXTENT_ITEM_KEY;
7929f21246dSJosef Bacik 			btrfs_release_path(path);
7939f21246dSJosef Bacik 			goto next;
7949f21246dSJosef Bacik 		}
7959f21246dSJosef Bacik 
796b3470b5dSDavid Sterba 		if (key.objectid < block_group->start) {
7979f21246dSJosef Bacik 			path->slots[0]++;
7989f21246dSJosef Bacik 			continue;
7999f21246dSJosef Bacik 		}
8009f21246dSJosef Bacik 
801b3470b5dSDavid Sterba 		if (key.objectid >= block_group->start + block_group->length)
8029f21246dSJosef Bacik 			break;
8039f21246dSJosef Bacik 
8049f21246dSJosef Bacik 		if (key.type == BTRFS_EXTENT_ITEM_KEY ||
8059f21246dSJosef Bacik 		    key.type == BTRFS_METADATA_ITEM_KEY) {
806d8ccbd21SFilipe Manana 			u64 space_added;
807d8ccbd21SFilipe Manana 
8083b9f0995SFilipe Manana 			ret = btrfs_add_new_free_space(block_group, last,
8093b9f0995SFilipe Manana 						       key.objectid, &space_added);
810d8ccbd21SFilipe Manana 			if (ret)
811d8ccbd21SFilipe Manana 				goto out;
812d8ccbd21SFilipe Manana 			total_found += space_added;
8139f21246dSJosef Bacik 			if (key.type == BTRFS_METADATA_ITEM_KEY)
8149f21246dSJosef Bacik 				last = key.objectid +
8159f21246dSJosef Bacik 					fs_info->nodesize;
8169f21246dSJosef Bacik 			else
8179f21246dSJosef Bacik 				last = key.objectid + key.offset;
8189f21246dSJosef Bacik 
8199f21246dSJosef Bacik 			if (total_found > CACHING_CTL_WAKE_UP) {
8209f21246dSJosef Bacik 				total_found = 0;
821fc1f91b9SJosef Bacik 				if (wakeup) {
822fc1f91b9SJosef Bacik 					atomic_inc(&caching_ctl->progress);
8239f21246dSJosef Bacik 					wake_up(&caching_ctl->wait);
8249f21246dSJosef Bacik 				}
8259f21246dSJosef Bacik 			}
826fc1f91b9SJosef Bacik 		}
8279f21246dSJosef Bacik 		path->slots[0]++;
8289f21246dSJosef Bacik 	}
8299f21246dSJosef Bacik 
8303b9f0995SFilipe Manana 	ret = btrfs_add_new_free_space(block_group, last,
831d8ccbd21SFilipe Manana 				       block_group->start + block_group->length,
832d8ccbd21SFilipe Manana 				       NULL);
8339f21246dSJosef Bacik out:
8349f21246dSJosef Bacik 	btrfs_free_path(path);
8359f21246dSJosef Bacik 	return ret;
8369f21246dSJosef Bacik }
8379f21246dSJosef Bacik 
btrfs_free_excluded_extents(const struct btrfs_block_group * bg)83898b5a8fdSFilipe Manana static inline void btrfs_free_excluded_extents(const struct btrfs_block_group *bg)
83998b5a8fdSFilipe Manana {
84098b5a8fdSFilipe Manana 	clear_extent_bits(&bg->fs_info->excluded_extents, bg->start,
84198b5a8fdSFilipe Manana 			  bg->start + bg->length - 1, EXTENT_UPTODATE);
84298b5a8fdSFilipe Manana }
84398b5a8fdSFilipe Manana 
caching_thread(struct btrfs_work * work)8449f21246dSJosef Bacik static noinline void caching_thread(struct btrfs_work *work)
8459f21246dSJosef Bacik {
84632da5386SDavid Sterba 	struct btrfs_block_group *block_group;
8479f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info;
8489f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
8499f21246dSJosef Bacik 	int ret;
8509f21246dSJosef Bacik 
8519f21246dSJosef Bacik 	caching_ctl = container_of(work, struct btrfs_caching_control, work);
8529f21246dSJosef Bacik 	block_group = caching_ctl->block_group;
8539f21246dSJosef Bacik 	fs_info = block_group->fs_info;
8549f21246dSJosef Bacik 
8559f21246dSJosef Bacik 	mutex_lock(&caching_ctl->mutex);
8569f21246dSJosef Bacik 	down_read(&fs_info->commit_root_sem);
8579f21246dSJosef Bacik 
858c7eec3d9SBoris Burkov 	load_block_group_size_class(caching_ctl, block_group);
859e747853cSJosef Bacik 	if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
860e747853cSJosef Bacik 		ret = load_free_space_cache(block_group);
861e747853cSJosef Bacik 		if (ret == 1) {
862e747853cSJosef Bacik 			ret = 0;
863e747853cSJosef Bacik 			goto done;
864e747853cSJosef Bacik 		}
865e747853cSJosef Bacik 
866e747853cSJosef Bacik 		/*
867e747853cSJosef Bacik 		 * We failed to load the space cache, set ourselves to
868e747853cSJosef Bacik 		 * CACHE_STARTED and carry on.
869e747853cSJosef Bacik 		 */
870e747853cSJosef Bacik 		spin_lock(&block_group->lock);
871e747853cSJosef Bacik 		block_group->cached = BTRFS_CACHE_STARTED;
872e747853cSJosef Bacik 		spin_unlock(&block_group->lock);
873e747853cSJosef Bacik 		wake_up(&caching_ctl->wait);
874e747853cSJosef Bacik 	}
875e747853cSJosef Bacik 
8762f96e402SJosef Bacik 	/*
8772f96e402SJosef Bacik 	 * If we are in the transaction that populated the free space tree we
8782f96e402SJosef Bacik 	 * can't actually cache from the free space tree as our commit root and
8792f96e402SJosef Bacik 	 * real root are the same, so we could change the contents of the blocks
8802f96e402SJosef Bacik 	 * while caching.  Instead do the slow caching in this case, and after
8812f96e402SJosef Bacik 	 * the transaction has committed we will be safe.
8822f96e402SJosef Bacik 	 */
8832f96e402SJosef Bacik 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
8842f96e402SJosef Bacik 	    !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
8859f21246dSJosef Bacik 		ret = load_free_space_tree(caching_ctl);
8869f21246dSJosef Bacik 	else
8879f21246dSJosef Bacik 		ret = load_extent_tree_free(caching_ctl);
888e747853cSJosef Bacik done:
8899f21246dSJosef Bacik 	spin_lock(&block_group->lock);
8909f21246dSJosef Bacik 	block_group->caching_ctl = NULL;
8919f21246dSJosef Bacik 	block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
8929f21246dSJosef Bacik 	spin_unlock(&block_group->lock);
8939f21246dSJosef Bacik 
8949f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
8959f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group)) {
8969f21246dSJosef Bacik 		u64 bytes_used;
8979f21246dSJosef Bacik 
8989f21246dSJosef Bacik 		spin_lock(&block_group->space_info->lock);
8999f21246dSJosef Bacik 		spin_lock(&block_group->lock);
900b3470b5dSDavid Sterba 		bytes_used = block_group->length - block_group->used;
9019f21246dSJosef Bacik 		block_group->space_info->bytes_used += bytes_used >> 1;
9029f21246dSJosef Bacik 		spin_unlock(&block_group->lock);
9039f21246dSJosef Bacik 		spin_unlock(&block_group->space_info->lock);
904e11c0406SJosef Bacik 		fragment_free_space(block_group);
9059f21246dSJosef Bacik 	}
9069f21246dSJosef Bacik #endif
9079f21246dSJosef Bacik 
9089f21246dSJosef Bacik 	up_read(&fs_info->commit_root_sem);
9099f21246dSJosef Bacik 	btrfs_free_excluded_extents(block_group);
9109f21246dSJosef Bacik 	mutex_unlock(&caching_ctl->mutex);
9119f21246dSJosef Bacik 
9129f21246dSJosef Bacik 	wake_up(&caching_ctl->wait);
9139f21246dSJosef Bacik 
9149f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
9159f21246dSJosef Bacik 	btrfs_put_block_group(block_group);
9169f21246dSJosef Bacik }
9179f21246dSJosef Bacik 
btrfs_cache_block_group(struct btrfs_block_group * cache,bool wait)918ced8ecf0SOmar Sandoval int btrfs_cache_block_group(struct btrfs_block_group *cache, bool wait)
9199f21246dSJosef Bacik {
9209f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
921e747853cSJosef Bacik 	struct btrfs_caching_control *caching_ctl = NULL;
9229f21246dSJosef Bacik 	int ret = 0;
9239f21246dSJosef Bacik 
9242eda5708SNaohiro Aota 	/* Allocator for zoned filesystems does not use the cache at all */
9252eda5708SNaohiro Aota 	if (btrfs_is_zoned(fs_info))
9262eda5708SNaohiro Aota 		return 0;
9272eda5708SNaohiro Aota 
9289f21246dSJosef Bacik 	caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
9299f21246dSJosef Bacik 	if (!caching_ctl)
9309f21246dSJosef Bacik 		return -ENOMEM;
9319f21246dSJosef Bacik 
9329f21246dSJosef Bacik 	INIT_LIST_HEAD(&caching_ctl->list);
9339f21246dSJosef Bacik 	mutex_init(&caching_ctl->mutex);
9349f21246dSJosef Bacik 	init_waitqueue_head(&caching_ctl->wait);
9359f21246dSJosef Bacik 	caching_ctl->block_group = cache;
936e747853cSJosef Bacik 	refcount_set(&caching_ctl->count, 2);
937fc1f91b9SJosef Bacik 	atomic_set(&caching_ctl->progress, 0);
938a0cac0ecSOmar Sandoval 	btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
9399f21246dSJosef Bacik 
9409f21246dSJosef Bacik 	spin_lock(&cache->lock);
9419f21246dSJosef Bacik 	if (cache->cached != BTRFS_CACHE_NO) {
9429f21246dSJosef Bacik 		kfree(caching_ctl);
943e747853cSJosef Bacik 
944e747853cSJosef Bacik 		caching_ctl = cache->caching_ctl;
945e747853cSJosef Bacik 		if (caching_ctl)
946e747853cSJosef Bacik 			refcount_inc(&caching_ctl->count);
947e747853cSJosef Bacik 		spin_unlock(&cache->lock);
948e747853cSJosef Bacik 		goto out;
9499f21246dSJosef Bacik 	}
9509f21246dSJosef Bacik 	WARN_ON(cache->caching_ctl);
9519f21246dSJosef Bacik 	cache->caching_ctl = caching_ctl;
9529f21246dSJosef Bacik 	cache->cached = BTRFS_CACHE_STARTED;
9539f21246dSJosef Bacik 	spin_unlock(&cache->lock);
9549f21246dSJosef Bacik 
95516b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
9569f21246dSJosef Bacik 	refcount_inc(&caching_ctl->count);
9579f21246dSJosef Bacik 	list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
95816b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
9599f21246dSJosef Bacik 
9609f21246dSJosef Bacik 	btrfs_get_block_group(cache);
9619f21246dSJosef Bacik 
9629f21246dSJosef Bacik 	btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
963e747853cSJosef Bacik out:
964ced8ecf0SOmar Sandoval 	if (wait && caching_ctl)
965ced8ecf0SOmar Sandoval 		ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
966e747853cSJosef Bacik 	if (caching_ctl)
967e747853cSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
9689f21246dSJosef Bacik 
9699f21246dSJosef Bacik 	return ret;
9709f21246dSJosef Bacik }
971e3e0520bSJosef Bacik 
clear_avail_alloc_bits(struct btrfs_fs_info * fs_info,u64 flags)972e3e0520bSJosef Bacik static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
973e3e0520bSJosef Bacik {
974e3e0520bSJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
975e3e0520bSJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
976e3e0520bSJosef Bacik 
977e3e0520bSJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
978e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
979e3e0520bSJosef Bacik 		fs_info->avail_data_alloc_bits &= ~extra_flags;
980e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
981e3e0520bSJosef Bacik 		fs_info->avail_metadata_alloc_bits &= ~extra_flags;
982e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
983e3e0520bSJosef Bacik 		fs_info->avail_system_alloc_bits &= ~extra_flags;
984e3e0520bSJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
985e3e0520bSJosef Bacik }
986e3e0520bSJosef Bacik 
987e3e0520bSJosef Bacik /*
988e3e0520bSJosef Bacik  * Clear incompat bits for the following feature(s):
989e3e0520bSJosef Bacik  *
990e3e0520bSJosef Bacik  * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
991e3e0520bSJosef Bacik  *            in the whole filesystem
9929c907446SDavid Sterba  *
9939c907446SDavid Sterba  * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
994e3e0520bSJosef Bacik  */
clear_incompat_bg_bits(struct btrfs_fs_info * fs_info,u64 flags)995e3e0520bSJosef Bacik static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
996e3e0520bSJosef Bacik {
9979c907446SDavid Sterba 	bool found_raid56 = false;
9989c907446SDavid Sterba 	bool found_raid1c34 = false;
9999c907446SDavid Sterba 
10009c907446SDavid Sterba 	if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
10019c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
10029c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
1003e3e0520bSJosef Bacik 		struct list_head *head = &fs_info->space_info;
1004e3e0520bSJosef Bacik 		struct btrfs_space_info *sinfo;
1005e3e0520bSJosef Bacik 
1006e3e0520bSJosef Bacik 		list_for_each_entry_rcu(sinfo, head, list) {
1007e3e0520bSJosef Bacik 			down_read(&sinfo->groups_sem);
1008e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
10099c907446SDavid Sterba 				found_raid56 = true;
1010e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
10119c907446SDavid Sterba 				found_raid56 = true;
10129c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
10139c907446SDavid Sterba 				found_raid1c34 = true;
10149c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
10159c907446SDavid Sterba 				found_raid1c34 = true;
1016e3e0520bSJosef Bacik 			up_read(&sinfo->groups_sem);
1017e3e0520bSJosef Bacik 		}
1018d8e6fd5cSFilipe Manana 		if (!found_raid56)
1019e3e0520bSJosef Bacik 			btrfs_clear_fs_incompat(fs_info, RAID56);
1020d8e6fd5cSFilipe Manana 		if (!found_raid1c34)
10219c907446SDavid Sterba 			btrfs_clear_fs_incompat(fs_info, RAID1C34);
1022e3e0520bSJosef Bacik 	}
1023e3e0520bSJosef Bacik }
1024e3e0520bSJosef Bacik 
remove_block_group_item(struct btrfs_trans_handle * trans,struct btrfs_path * path,struct btrfs_block_group * block_group)10257357623aSQu Wenruo static int remove_block_group_item(struct btrfs_trans_handle *trans,
10267357623aSQu Wenruo 				   struct btrfs_path *path,
10277357623aSQu Wenruo 				   struct btrfs_block_group *block_group)
10287357623aSQu Wenruo {
10297357623aSQu Wenruo 	struct btrfs_fs_info *fs_info = trans->fs_info;
10307357623aSQu Wenruo 	struct btrfs_root *root;
10317357623aSQu Wenruo 	struct btrfs_key key;
10327357623aSQu Wenruo 	int ret;
10337357623aSQu Wenruo 
1034dfe8aec4SJosef Bacik 	root = btrfs_block_group_root(fs_info);
10357357623aSQu Wenruo 	key.objectid = block_group->start;
10367357623aSQu Wenruo 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
10377357623aSQu Wenruo 	key.offset = block_group->length;
10387357623aSQu Wenruo 
10397357623aSQu Wenruo 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10407357623aSQu Wenruo 	if (ret > 0)
10417357623aSQu Wenruo 		ret = -ENOENT;
10427357623aSQu Wenruo 	if (ret < 0)
10437357623aSQu Wenruo 		return ret;
10447357623aSQu Wenruo 
10457357623aSQu Wenruo 	ret = btrfs_del_item(trans, root, path);
10467357623aSQu Wenruo 	return ret;
10477357623aSQu Wenruo }
10487357623aSQu Wenruo 
btrfs_remove_block_group(struct btrfs_trans_handle * trans,u64 group_start,struct extent_map * em)1049e3e0520bSJosef Bacik int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
1050e3e0520bSJosef Bacik 			     u64 group_start, struct extent_map *em)
1051e3e0520bSJosef Bacik {
1052e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
1053e3e0520bSJosef Bacik 	struct btrfs_path *path;
105432da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1055e3e0520bSJosef Bacik 	struct btrfs_free_cluster *cluster;
1056e3e0520bSJosef Bacik 	struct inode *inode;
1057e3e0520bSJosef Bacik 	struct kobject *kobj = NULL;
1058e3e0520bSJosef Bacik 	int ret;
1059e3e0520bSJosef Bacik 	int index;
1060e3e0520bSJosef Bacik 	int factor;
1061e3e0520bSJosef Bacik 	struct btrfs_caching_control *caching_ctl = NULL;
1062e3e0520bSJosef Bacik 	bool remove_em;
1063e3e0520bSJosef Bacik 	bool remove_rsv = false;
1064e3e0520bSJosef Bacik 
1065e3e0520bSJosef Bacik 	block_group = btrfs_lookup_block_group(fs_info, group_start);
1066e3e0520bSJosef Bacik 	BUG_ON(!block_group);
1067e3e0520bSJosef Bacik 	BUG_ON(!block_group->ro);
1068e3e0520bSJosef Bacik 
1069e3e0520bSJosef Bacik 	trace_btrfs_remove_block_group(block_group);
1070e3e0520bSJosef Bacik 	/*
1071e3e0520bSJosef Bacik 	 * Free the reserved super bytes from this block group before
1072e3e0520bSJosef Bacik 	 * remove it.
1073e3e0520bSJosef Bacik 	 */
1074e3e0520bSJosef Bacik 	btrfs_free_excluded_extents(block_group);
1075b3470b5dSDavid Sterba 	btrfs_free_ref_tree_range(fs_info, block_group->start,
1076b3470b5dSDavid Sterba 				  block_group->length);
1077e3e0520bSJosef Bacik 
1078e3e0520bSJosef Bacik 	index = btrfs_bg_flags_to_raid_index(block_group->flags);
1079e3e0520bSJosef Bacik 	factor = btrfs_bg_type_to_factor(block_group->flags);
1080e3e0520bSJosef Bacik 
1081e3e0520bSJosef Bacik 	/* make sure this block group isn't part of an allocation cluster */
1082e3e0520bSJosef Bacik 	cluster = &fs_info->data_alloc_cluster;
1083e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
1084e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
1085e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
1086e3e0520bSJosef Bacik 
1087e3e0520bSJosef Bacik 	/*
1088e3e0520bSJosef Bacik 	 * make sure this block group isn't part of a metadata
1089e3e0520bSJosef Bacik 	 * allocation cluster
1090e3e0520bSJosef Bacik 	 */
1091e3e0520bSJosef Bacik 	cluster = &fs_info->meta_alloc_cluster;
1092e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
1093e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
1094e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
1095e3e0520bSJosef Bacik 
109640ab3be1SNaohiro Aota 	btrfs_clear_treelog_bg(block_group);
1097c2707a25SJohannes Thumshirn 	btrfs_clear_data_reloc_bg(block_group);
109840ab3be1SNaohiro Aota 
1099e3e0520bSJosef Bacik 	path = btrfs_alloc_path();
1100e3e0520bSJosef Bacik 	if (!path) {
1101e3e0520bSJosef Bacik 		ret = -ENOMEM;
11029fecd132SFilipe Manana 		goto out;
1103e3e0520bSJosef Bacik 	}
1104e3e0520bSJosef Bacik 
1105e3e0520bSJosef Bacik 	/*
1106e3e0520bSJosef Bacik 	 * get the inode first so any iput calls done for the io_list
1107e3e0520bSJosef Bacik 	 * aren't the final iput (no unlinks allowed now)
1108e3e0520bSJosef Bacik 	 */
1109e3e0520bSJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
1110e3e0520bSJosef Bacik 
1111e3e0520bSJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
1112e3e0520bSJosef Bacik 	/*
1113e3e0520bSJosef Bacik 	 * Make sure our free space cache IO is done before removing the
1114e3e0520bSJosef Bacik 	 * free space inode
1115e3e0520bSJosef Bacik 	 */
1116e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
1117e3e0520bSJosef Bacik 	if (!list_empty(&block_group->io_list)) {
1118e3e0520bSJosef Bacik 		list_del_init(&block_group->io_list);
1119e3e0520bSJosef Bacik 
1120e3e0520bSJosef Bacik 		WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
1121e3e0520bSJosef Bacik 
1122e3e0520bSJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
1123e3e0520bSJosef Bacik 		btrfs_wait_cache_io(trans, block_group, path);
1124e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1125e3e0520bSJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
1126e3e0520bSJosef Bacik 	}
1127e3e0520bSJosef Bacik 
1128e3e0520bSJosef Bacik 	if (!list_empty(&block_group->dirty_list)) {
1129e3e0520bSJosef Bacik 		list_del_init(&block_group->dirty_list);
1130e3e0520bSJosef Bacik 		remove_rsv = true;
1131e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1132e3e0520bSJosef Bacik 	}
1133e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1134e3e0520bSJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
1135e3e0520bSJosef Bacik 
113636b216c8SBoris Burkov 	ret = btrfs_remove_free_space_inode(trans, inode, block_group);
1137e3e0520bSJosef Bacik 	if (ret)
11389fecd132SFilipe Manana 		goto out;
1139e3e0520bSJosef Bacik 
114016b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
114108dddb29SFilipe Manana 	rb_erase_cached(&block_group->cache_node,
1142e3e0520bSJosef Bacik 			&fs_info->block_group_cache_tree);
1143e3e0520bSJosef Bacik 	RB_CLEAR_NODE(&block_group->cache_node);
1144e3e0520bSJosef Bacik 
11459fecd132SFilipe Manana 	/* Once for the block groups rbtree */
11469fecd132SFilipe Manana 	btrfs_put_block_group(block_group);
11479fecd132SFilipe Manana 
114816b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
1149e3e0520bSJosef Bacik 
1150e3e0520bSJosef Bacik 	down_write(&block_group->space_info->groups_sem);
1151e3e0520bSJosef Bacik 	/*
1152e3e0520bSJosef Bacik 	 * we must use list_del_init so people can check to see if they
1153e3e0520bSJosef Bacik 	 * are still on the list after taking the semaphore
1154e3e0520bSJosef Bacik 	 */
1155e3e0520bSJosef Bacik 	list_del_init(&block_group->list);
1156e3e0520bSJosef Bacik 	if (list_empty(&block_group->space_info->block_groups[index])) {
1157e3e0520bSJosef Bacik 		kobj = block_group->space_info->block_group_kobjs[index];
1158e3e0520bSJosef Bacik 		block_group->space_info->block_group_kobjs[index] = NULL;
1159e3e0520bSJosef Bacik 		clear_avail_alloc_bits(fs_info, block_group->flags);
1160e3e0520bSJosef Bacik 	}
1161e3e0520bSJosef Bacik 	up_write(&block_group->space_info->groups_sem);
1162e3e0520bSJosef Bacik 	clear_incompat_bg_bits(fs_info, block_group->flags);
1163e3e0520bSJosef Bacik 	if (kobj) {
1164e3e0520bSJosef Bacik 		kobject_del(kobj);
1165e3e0520bSJosef Bacik 		kobject_put(kobj);
1166e3e0520bSJosef Bacik 	}
1167e3e0520bSJosef Bacik 
1168e3e0520bSJosef Bacik 	if (block_group->cached == BTRFS_CACHE_STARTED)
1169e3e0520bSJosef Bacik 		btrfs_wait_block_group_cache_done(block_group);
11707b9c293bSJosef Bacik 
117116b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
11727b9c293bSJosef Bacik 	caching_ctl = btrfs_get_caching_control(block_group);
1173e3e0520bSJosef Bacik 	if (!caching_ctl) {
1174e3e0520bSJosef Bacik 		struct btrfs_caching_control *ctl;
1175e3e0520bSJosef Bacik 
11767b9c293bSJosef Bacik 		list_for_each_entry(ctl, &fs_info->caching_block_groups, list) {
1177e3e0520bSJosef Bacik 			if (ctl->block_group == block_group) {
1178e3e0520bSJosef Bacik 				caching_ctl = ctl;
1179e3e0520bSJosef Bacik 				refcount_inc(&caching_ctl->count);
1180e3e0520bSJosef Bacik 				break;
1181e3e0520bSJosef Bacik 			}
1182e3e0520bSJosef Bacik 		}
11837b9c293bSJosef Bacik 	}
1184e3e0520bSJosef Bacik 	if (caching_ctl)
1185e3e0520bSJosef Bacik 		list_del_init(&caching_ctl->list);
118616b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
11877b9c293bSJosef Bacik 
1188e3e0520bSJosef Bacik 	if (caching_ctl) {
1189e3e0520bSJosef Bacik 		/* Once for the caching bgs list and once for us. */
1190e3e0520bSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
1191e3e0520bSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
1192e3e0520bSJosef Bacik 	}
1193e3e0520bSJosef Bacik 
1194e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
1195e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->dirty_list));
1196e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->io_list));
1197e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1198e3e0520bSJosef Bacik 
1199e3e0520bSJosef Bacik 	btrfs_remove_free_space_cache(block_group);
1200e3e0520bSJosef Bacik 
1201e3e0520bSJosef Bacik 	spin_lock(&block_group->space_info->lock);
1202e3e0520bSJosef Bacik 	list_del_init(&block_group->ro_list);
1203e3e0520bSJosef Bacik 
1204e3e0520bSJosef Bacik 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1205e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->total_bytes
1206b3470b5dSDavid Sterba 			< block_group->length);
1207e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->bytes_readonly
1208169e0da9SNaohiro Aota 			< block_group->length - block_group->zone_unusable);
1209169e0da9SNaohiro Aota 		WARN_ON(block_group->space_info->bytes_zone_unusable
1210169e0da9SNaohiro Aota 			< block_group->zone_unusable);
1211e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->disk_total
1212b3470b5dSDavid Sterba 			< block_group->length * factor);
1213e3e0520bSJosef Bacik 	}
1214b3470b5dSDavid Sterba 	block_group->space_info->total_bytes -= block_group->length;
1215169e0da9SNaohiro Aota 	block_group->space_info->bytes_readonly -=
1216169e0da9SNaohiro Aota 		(block_group->length - block_group->zone_unusable);
1217ae29e6f7SNaohiro Aota 	btrfs_space_info_update_bytes_zone_unusable(fs_info, block_group->space_info,
1218ae29e6f7SNaohiro Aota 						    -block_group->zone_unusable);
1219b3470b5dSDavid Sterba 	block_group->space_info->disk_total -= block_group->length * factor;
1220e3e0520bSJosef Bacik 
1221e3e0520bSJosef Bacik 	spin_unlock(&block_group->space_info->lock);
1222e3e0520bSJosef Bacik 
1223ffcb9d44SFilipe Manana 	/*
1224ffcb9d44SFilipe Manana 	 * Remove the free space for the block group from the free space tree
1225ffcb9d44SFilipe Manana 	 * and the block group's item from the extent tree before marking the
1226ffcb9d44SFilipe Manana 	 * block group as removed. This is to prevent races with tasks that
1227ffcb9d44SFilipe Manana 	 * freeze and unfreeze a block group, this task and another task
1228ffcb9d44SFilipe Manana 	 * allocating a new block group - the unfreeze task ends up removing
1229ffcb9d44SFilipe Manana 	 * the block group's extent map before the task calling this function
1230ffcb9d44SFilipe Manana 	 * deletes the block group item from the extent tree, allowing for
1231ffcb9d44SFilipe Manana 	 * another task to attempt to create another block group with the same
1232ffcb9d44SFilipe Manana 	 * item key (and failing with -EEXIST and a transaction abort).
1233ffcb9d44SFilipe Manana 	 */
1234ffcb9d44SFilipe Manana 	ret = remove_block_group_free_space(trans, block_group);
1235ffcb9d44SFilipe Manana 	if (ret)
1236ffcb9d44SFilipe Manana 		goto out;
1237ffcb9d44SFilipe Manana 
1238ffcb9d44SFilipe Manana 	ret = remove_block_group_item(trans, path, block_group);
1239ffcb9d44SFilipe Manana 	if (ret < 0)
1240ffcb9d44SFilipe Manana 		goto out;
1241ffcb9d44SFilipe Manana 
1242e3e0520bSJosef Bacik 	spin_lock(&block_group->lock);
12433349b57fSJosef Bacik 	set_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags);
12443349b57fSJosef Bacik 
1245e3e0520bSJosef Bacik 	/*
12466b7304afSFilipe Manana 	 * At this point trimming or scrub can't start on this block group,
12476b7304afSFilipe Manana 	 * because we removed the block group from the rbtree
12486b7304afSFilipe Manana 	 * fs_info->block_group_cache_tree so no one can't find it anymore and
12496b7304afSFilipe Manana 	 * even if someone already got this block group before we removed it
12506b7304afSFilipe Manana 	 * from the rbtree, they have already incremented block_group->frozen -
12516b7304afSFilipe Manana 	 * if they didn't, for the trimming case they won't find any free space
12526b7304afSFilipe Manana 	 * entries because we already removed them all when we called
12536b7304afSFilipe Manana 	 * btrfs_remove_free_space_cache().
1254e3e0520bSJosef Bacik 	 *
1255e3e0520bSJosef Bacik 	 * And we must not remove the extent map from the fs_info->mapping_tree
1256e3e0520bSJosef Bacik 	 * to prevent the same logical address range and physical device space
12576b7304afSFilipe Manana 	 * ranges from being reused for a new block group. This is needed to
12586b7304afSFilipe Manana 	 * avoid races with trimming and scrub.
12596b7304afSFilipe Manana 	 *
12606b7304afSFilipe Manana 	 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1261e3e0520bSJosef Bacik 	 * completely transactionless, so while it is trimming a range the
1262e3e0520bSJosef Bacik 	 * currently running transaction might finish and a new one start,
1263e3e0520bSJosef Bacik 	 * allowing for new block groups to be created that can reuse the same
1264e3e0520bSJosef Bacik 	 * physical device locations unless we take this special care.
1265e3e0520bSJosef Bacik 	 *
1266e3e0520bSJosef Bacik 	 * There may also be an implicit trim operation if the file system
1267e3e0520bSJosef Bacik 	 * is mounted with -odiscard. The same protections must remain
1268e3e0520bSJosef Bacik 	 * in place until the extents have been discarded completely when
1269e3e0520bSJosef Bacik 	 * the transaction commit has completed.
1270e3e0520bSJosef Bacik 	 */
12716b7304afSFilipe Manana 	remove_em = (atomic_read(&block_group->frozen) == 0);
1272e3e0520bSJosef Bacik 	spin_unlock(&block_group->lock);
1273e3e0520bSJosef Bacik 
1274e3e0520bSJosef Bacik 	if (remove_em) {
1275e3e0520bSJosef Bacik 		struct extent_map_tree *em_tree;
1276e3e0520bSJosef Bacik 
1277e3e0520bSJosef Bacik 		em_tree = &fs_info->mapping_tree;
1278e3e0520bSJosef Bacik 		write_lock(&em_tree->lock);
1279e3e0520bSJosef Bacik 		remove_extent_mapping(em_tree, em);
1280e3e0520bSJosef Bacik 		write_unlock(&em_tree->lock);
1281e3e0520bSJosef Bacik 		/* once for the tree */
1282e3e0520bSJosef Bacik 		free_extent_map(em);
1283e3e0520bSJosef Bacik 	}
1284f6033c5eSXiyu Yang 
12859fecd132SFilipe Manana out:
1286f6033c5eSXiyu Yang 	/* Once for the lookup reference */
1287f6033c5eSXiyu Yang 	btrfs_put_block_group(block_group);
1288e3e0520bSJosef Bacik 	if (remove_rsv)
1289e3e0520bSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
1290e3e0520bSJosef Bacik 	btrfs_free_path(path);
1291e3e0520bSJosef Bacik 	return ret;
1292e3e0520bSJosef Bacik }
1293e3e0520bSJosef Bacik 
btrfs_start_trans_remove_block_group(struct btrfs_fs_info * fs_info,const u64 chunk_offset)1294e3e0520bSJosef Bacik struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1295e3e0520bSJosef Bacik 		struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1296e3e0520bSJosef Bacik {
1297dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
1298e3e0520bSJosef Bacik 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1299e3e0520bSJosef Bacik 	struct extent_map *em;
1300e3e0520bSJosef Bacik 	struct map_lookup *map;
1301e3e0520bSJosef Bacik 	unsigned int num_items;
1302e3e0520bSJosef Bacik 
1303e3e0520bSJosef Bacik 	read_lock(&em_tree->lock);
1304e3e0520bSJosef Bacik 	em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1305e3e0520bSJosef Bacik 	read_unlock(&em_tree->lock);
1306e3e0520bSJosef Bacik 	ASSERT(em && em->start == chunk_offset);
1307e3e0520bSJosef Bacik 
1308e3e0520bSJosef Bacik 	/*
1309e3e0520bSJosef Bacik 	 * We need to reserve 3 + N units from the metadata space info in order
1310e3e0520bSJosef Bacik 	 * to remove a block group (done at btrfs_remove_chunk() and at
1311e3e0520bSJosef Bacik 	 * btrfs_remove_block_group()), which are used for:
1312e3e0520bSJosef Bacik 	 *
1313e3e0520bSJosef Bacik 	 * 1 unit for adding the free space inode's orphan (located in the tree
1314e3e0520bSJosef Bacik 	 * of tree roots).
1315e3e0520bSJosef Bacik 	 * 1 unit for deleting the block group item (located in the extent
1316e3e0520bSJosef Bacik 	 * tree).
1317e3e0520bSJosef Bacik 	 * 1 unit for deleting the free space item (located in tree of tree
1318e3e0520bSJosef Bacik 	 * roots).
1319e3e0520bSJosef Bacik 	 * N units for deleting N device extent items corresponding to each
1320e3e0520bSJosef Bacik 	 * stripe (located in the device tree).
1321e3e0520bSJosef Bacik 	 *
1322e3e0520bSJosef Bacik 	 * In order to remove a block group we also need to reserve units in the
1323e3e0520bSJosef Bacik 	 * system space info in order to update the chunk tree (update one or
1324e3e0520bSJosef Bacik 	 * more device items and remove one chunk item), but this is done at
1325e3e0520bSJosef Bacik 	 * btrfs_remove_chunk() through a call to check_system_chunk().
1326e3e0520bSJosef Bacik 	 */
1327e3e0520bSJosef Bacik 	map = em->map_lookup;
1328e3e0520bSJosef Bacik 	num_items = 3 + map->num_stripes;
1329e3e0520bSJosef Bacik 	free_extent_map(em);
1330e3e0520bSJosef Bacik 
1331dfe8aec4SJosef Bacik 	return btrfs_start_transaction_fallback_global_rsv(root, num_items);
1332e3e0520bSJosef Bacik }
1333e3e0520bSJosef Bacik 
1334e3e0520bSJosef Bacik /*
133526ce2095SJosef Bacik  * Mark block group @cache read-only, so later write won't happen to block
133626ce2095SJosef Bacik  * group @cache.
133726ce2095SJosef Bacik  *
133826ce2095SJosef Bacik  * If @force is not set, this function will only mark the block group readonly
133926ce2095SJosef Bacik  * if we have enough free space (1M) in other metadata/system block groups.
134026ce2095SJosef Bacik  * If @force is not set, this function will mark the block group readonly
134126ce2095SJosef Bacik  * without checking free space.
134226ce2095SJosef Bacik  *
134326ce2095SJosef Bacik  * NOTE: This function doesn't care if other block groups can contain all the
134426ce2095SJosef Bacik  * data in this block group. That check should be done by relocation routine,
134526ce2095SJosef Bacik  * not this function.
134626ce2095SJosef Bacik  */
inc_block_group_ro(struct btrfs_block_group * cache,int force)134732da5386SDavid Sterba static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
134826ce2095SJosef Bacik {
134926ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
135026ce2095SJosef Bacik 	u64 num_bytes;
135126ce2095SJosef Bacik 	int ret = -ENOSPC;
135226ce2095SJosef Bacik 
135326ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
135426ce2095SJosef Bacik 	spin_lock(&cache->lock);
135526ce2095SJosef Bacik 
1356195a49eaSFilipe Manana 	if (cache->swap_extents) {
1357195a49eaSFilipe Manana 		ret = -ETXTBSY;
1358195a49eaSFilipe Manana 		goto out;
1359195a49eaSFilipe Manana 	}
1360195a49eaSFilipe Manana 
136126ce2095SJosef Bacik 	if (cache->ro) {
136226ce2095SJosef Bacik 		cache->ro++;
136326ce2095SJosef Bacik 		ret = 0;
136426ce2095SJosef Bacik 		goto out;
136526ce2095SJosef Bacik 	}
136626ce2095SJosef Bacik 
1367b3470b5dSDavid Sterba 	num_bytes = cache->length - cache->reserved - cache->pinned -
1368169e0da9SNaohiro Aota 		    cache->bytes_super - cache->zone_unusable - cache->used;
136926ce2095SJosef Bacik 
137026ce2095SJosef Bacik 	/*
1371a30a3d20SJosef Bacik 	 * Data never overcommits, even in mixed mode, so do just the straight
1372a30a3d20SJosef Bacik 	 * check of left over space in how much we have allocated.
1373a30a3d20SJosef Bacik 	 */
1374a30a3d20SJosef Bacik 	if (force) {
1375a30a3d20SJosef Bacik 		ret = 0;
1376a30a3d20SJosef Bacik 	} else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1377a30a3d20SJosef Bacik 		u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1378a30a3d20SJosef Bacik 
1379a30a3d20SJosef Bacik 		/*
138026ce2095SJosef Bacik 		 * Here we make sure if we mark this bg RO, we still have enough
1381f8935566SJosef Bacik 		 * free space as buffer.
138226ce2095SJosef Bacik 		 */
1383a30a3d20SJosef Bacik 		if (sinfo_used + num_bytes <= sinfo->total_bytes)
1384a30a3d20SJosef Bacik 			ret = 0;
1385a30a3d20SJosef Bacik 	} else {
1386a30a3d20SJosef Bacik 		/*
1387a30a3d20SJosef Bacik 		 * We overcommit metadata, so we need to do the
1388a30a3d20SJosef Bacik 		 * btrfs_can_overcommit check here, and we need to pass in
1389a30a3d20SJosef Bacik 		 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1390a30a3d20SJosef Bacik 		 * leeway to allow us to mark this block group as read only.
1391a30a3d20SJosef Bacik 		 */
1392a30a3d20SJosef Bacik 		if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1393a30a3d20SJosef Bacik 					 BTRFS_RESERVE_NO_FLUSH))
1394a30a3d20SJosef Bacik 			ret = 0;
1395a30a3d20SJosef Bacik 	}
1396a30a3d20SJosef Bacik 
1397a30a3d20SJosef Bacik 	if (!ret) {
139826ce2095SJosef Bacik 		sinfo->bytes_readonly += num_bytes;
1399169e0da9SNaohiro Aota 		if (btrfs_is_zoned(cache->fs_info)) {
1400169e0da9SNaohiro Aota 			/* Migrate zone_unusable bytes to readonly */
1401169e0da9SNaohiro Aota 			sinfo->bytes_readonly += cache->zone_unusable;
1402ae29e6f7SNaohiro Aota 			btrfs_space_info_update_bytes_zone_unusable(cache->fs_info, sinfo,
1403ae29e6f7SNaohiro Aota 								    -cache->zone_unusable);
1404169e0da9SNaohiro Aota 			cache->zone_unusable = 0;
1405169e0da9SNaohiro Aota 		}
140626ce2095SJosef Bacik 		cache->ro++;
140726ce2095SJosef Bacik 		list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
140826ce2095SJosef Bacik 	}
140926ce2095SJosef Bacik out:
141026ce2095SJosef Bacik 	spin_unlock(&cache->lock);
141126ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
141226ce2095SJosef Bacik 	if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
141326ce2095SJosef Bacik 		btrfs_info(cache->fs_info,
1414b3470b5dSDavid Sterba 			"unable to make block group %llu ro", cache->start);
141526ce2095SJosef Bacik 		btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
141626ce2095SJosef Bacik 	}
141726ce2095SJosef Bacik 	return ret;
141826ce2095SJosef Bacik }
141926ce2095SJosef Bacik 
clean_pinned_extents(struct btrfs_trans_handle * trans,struct btrfs_block_group * bg)1420fe119a6eSNikolay Borisov static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1421fe119a6eSNikolay Borisov 				 struct btrfs_block_group *bg)
142245bb5d6aSNikolay Borisov {
142345bb5d6aSNikolay Borisov 	struct btrfs_fs_info *fs_info = bg->fs_info;
1424fe119a6eSNikolay Borisov 	struct btrfs_transaction *prev_trans = NULL;
142545bb5d6aSNikolay Borisov 	const u64 start = bg->start;
142645bb5d6aSNikolay Borisov 	const u64 end = start + bg->length - 1;
142745bb5d6aSNikolay Borisov 	int ret;
142845bb5d6aSNikolay Borisov 
1429fe119a6eSNikolay Borisov 	spin_lock(&fs_info->trans_lock);
1430fe119a6eSNikolay Borisov 	if (trans->transaction->list.prev != &fs_info->trans_list) {
1431fe119a6eSNikolay Borisov 		prev_trans = list_last_entry(&trans->transaction->list,
1432fe119a6eSNikolay Borisov 					     struct btrfs_transaction, list);
1433fe119a6eSNikolay Borisov 		refcount_inc(&prev_trans->use_count);
1434fe119a6eSNikolay Borisov 	}
1435fe119a6eSNikolay Borisov 	spin_unlock(&fs_info->trans_lock);
1436fe119a6eSNikolay Borisov 
143745bb5d6aSNikolay Borisov 	/*
143845bb5d6aSNikolay Borisov 	 * Hold the unused_bg_unpin_mutex lock to avoid racing with
143945bb5d6aSNikolay Borisov 	 * btrfs_finish_extent_commit(). If we are at transaction N, another
144045bb5d6aSNikolay Borisov 	 * task might be running finish_extent_commit() for the previous
144145bb5d6aSNikolay Borisov 	 * transaction N - 1, and have seen a range belonging to the block
1442fe119a6eSNikolay Borisov 	 * group in pinned_extents before we were able to clear the whole block
1443fe119a6eSNikolay Borisov 	 * group range from pinned_extents. This means that task can lookup for
1444fe119a6eSNikolay Borisov 	 * the block group after we unpinned it from pinned_extents and removed
1445fe119a6eSNikolay Borisov 	 * it, leading to a BUG_ON() at unpin_extent_range().
144645bb5d6aSNikolay Borisov 	 */
144745bb5d6aSNikolay Borisov 	mutex_lock(&fs_info->unused_bg_unpin_mutex);
1448fe119a6eSNikolay Borisov 	if (prev_trans) {
1449fe119a6eSNikolay Borisov 		ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
145045bb5d6aSNikolay Borisov 					EXTENT_DIRTY);
145145bb5d6aSNikolay Borisov 		if (ret)
1452534cf531SFilipe Manana 			goto out;
1453fe119a6eSNikolay Borisov 	}
145445bb5d6aSNikolay Borisov 
1455fe119a6eSNikolay Borisov 	ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
145645bb5d6aSNikolay Borisov 				EXTENT_DIRTY);
1457534cf531SFilipe Manana out:
145845bb5d6aSNikolay Borisov 	mutex_unlock(&fs_info->unused_bg_unpin_mutex);
14595150bf19SFilipe Manana 	if (prev_trans)
14605150bf19SFilipe Manana 		btrfs_put_transaction(prev_trans);
146145bb5d6aSNikolay Borisov 
1462534cf531SFilipe Manana 	return ret == 0;
146345bb5d6aSNikolay Borisov }
146445bb5d6aSNikolay Borisov 
146526ce2095SJosef Bacik /*
1466e3e0520bSJosef Bacik  * Process the unused_bgs list and remove any that don't have any allocated
1467e3e0520bSJosef Bacik  * space inside of them.
1468e3e0520bSJosef Bacik  */
btrfs_delete_unused_bgs(struct btrfs_fs_info * fs_info)1469e3e0520bSJosef Bacik void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1470e3e0520bSJosef Bacik {
1471505a948dSFilipe Manana 	LIST_HEAD(retry_list);
147232da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1473e3e0520bSJosef Bacik 	struct btrfs_space_info *space_info;
1474e3e0520bSJosef Bacik 	struct btrfs_trans_handle *trans;
14756e80d4f8SDennis Zhou 	const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1476e3e0520bSJosef Bacik 	int ret = 0;
1477e3e0520bSJosef Bacik 
1478e3e0520bSJosef Bacik 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1479e3e0520bSJosef Bacik 		return;
1480e3e0520bSJosef Bacik 
14812f12741fSJosef Bacik 	if (btrfs_fs_closing(fs_info))
14822f12741fSJosef Bacik 		return;
14832f12741fSJosef Bacik 
1484ddfd08cbSJosef Bacik 	/*
1485ddfd08cbSJosef Bacik 	 * Long running balances can keep us blocked here for eternity, so
1486ddfd08cbSJosef Bacik 	 * simply skip deletion if we're unable to get the mutex.
1487ddfd08cbSJosef Bacik 	 */
1488f3372065SJohannes Thumshirn 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
1489ddfd08cbSJosef Bacik 		return;
1490ddfd08cbSJosef Bacik 
1491e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1492e3e0520bSJosef Bacik 	while (!list_empty(&fs_info->unused_bgs)) {
1493505a948dSFilipe Manana 		u64 used;
1494e3e0520bSJosef Bacik 		int trimming;
1495e3e0520bSJosef Bacik 
1496e3e0520bSJosef Bacik 		block_group = list_first_entry(&fs_info->unused_bgs,
149732da5386SDavid Sterba 					       struct btrfs_block_group,
1498e3e0520bSJosef Bacik 					       bg_list);
1499e3e0520bSJosef Bacik 		list_del_init(&block_group->bg_list);
1500e3e0520bSJosef Bacik 
1501e3e0520bSJosef Bacik 		space_info = block_group->space_info;
1502e3e0520bSJosef Bacik 
1503e3e0520bSJosef Bacik 		if (ret || btrfs_mixed_space_info(space_info)) {
1504e3e0520bSJosef Bacik 			btrfs_put_block_group(block_group);
1505e3e0520bSJosef Bacik 			continue;
1506e3e0520bSJosef Bacik 		}
1507e3e0520bSJosef Bacik 		spin_unlock(&fs_info->unused_bgs_lock);
1508e3e0520bSJosef Bacik 
1509b0643e59SDennis Zhou 		btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1510b0643e59SDennis Zhou 
1511e3e0520bSJosef Bacik 		/* Don't want to race with allocators so take the groups_sem */
1512e3e0520bSJosef Bacik 		down_write(&space_info->groups_sem);
15136e80d4f8SDennis Zhou 
15146e80d4f8SDennis Zhou 		/*
15156e80d4f8SDennis Zhou 		 * Async discard moves the final block group discard to be prior
15166e80d4f8SDennis Zhou 		 * to the unused_bgs code path.  Therefore, if it's not fully
15176e80d4f8SDennis Zhou 		 * trimmed, punt it back to the async discard lists.
15186e80d4f8SDennis Zhou 		 */
15196e80d4f8SDennis Zhou 		if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
15206e80d4f8SDennis Zhou 		    !btrfs_is_free_space_trimmed(block_group)) {
15216e80d4f8SDennis Zhou 			trace_btrfs_skip_unused_block_group(block_group);
15226e80d4f8SDennis Zhou 			up_write(&space_info->groups_sem);
15236e80d4f8SDennis Zhou 			/* Requeue if we failed because of async discard */
15246e80d4f8SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
15256e80d4f8SDennis Zhou 						 block_group);
15266e80d4f8SDennis Zhou 			goto next;
15276e80d4f8SDennis Zhou 		}
15286e80d4f8SDennis Zhou 
1529505a948dSFilipe Manana 		spin_lock(&space_info->lock);
1530e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1531e97ebc2aSFilipe Manana 		if (btrfs_is_block_group_used(block_group) || block_group->ro ||
1532e3e0520bSJosef Bacik 		    list_is_singular(&block_group->list)) {
1533e3e0520bSJosef Bacik 			/*
1534e3e0520bSJosef Bacik 			 * We want to bail if we made new allocations or have
1535e3e0520bSJosef Bacik 			 * outstanding allocations in this block group.  We do
1536e3e0520bSJosef Bacik 			 * the ro check in case balance is currently acting on
1537e3e0520bSJosef Bacik 			 * this block group.
1538e3e0520bSJosef Bacik 			 */
1539e3e0520bSJosef Bacik 			trace_btrfs_skip_unused_block_group(block_group);
1540e3e0520bSJosef Bacik 			spin_unlock(&block_group->lock);
1541505a948dSFilipe Manana 			spin_unlock(&space_info->lock);
1542e3e0520bSJosef Bacik 			up_write(&space_info->groups_sem);
1543e3e0520bSJosef Bacik 			goto next;
1544e3e0520bSJosef Bacik 		}
1545505a948dSFilipe Manana 
1546505a948dSFilipe Manana 		/*
1547505a948dSFilipe Manana 		 * The block group may be unused but there may be space reserved
1548505a948dSFilipe Manana 		 * accounting with the existence of that block group, that is,
1549505a948dSFilipe Manana 		 * space_info->bytes_may_use was incremented by a task but no
1550505a948dSFilipe Manana 		 * space was yet allocated from the block group by the task.
1551505a948dSFilipe Manana 		 * That space may or may not be allocated, as we are generally
1552505a948dSFilipe Manana 		 * pessimistic about space reservation for metadata as well as
1553505a948dSFilipe Manana 		 * for data when using compression (as we reserve space based on
1554505a948dSFilipe Manana 		 * the worst case, when data can't be compressed, and before
1555505a948dSFilipe Manana 		 * actually attempting compression, before starting writeback).
1556505a948dSFilipe Manana 		 *
1557505a948dSFilipe Manana 		 * So check if the total space of the space_info minus the size
1558505a948dSFilipe Manana 		 * of this block group is less than the used space of the
1559505a948dSFilipe Manana 		 * space_info - if that's the case, then it means we have tasks
1560505a948dSFilipe Manana 		 * that might be relying on the block group in order to allocate
1561505a948dSFilipe Manana 		 * extents, and add back the block group to the unused list when
1562505a948dSFilipe Manana 		 * we finish, so that we retry later in case no tasks ended up
1563505a948dSFilipe Manana 		 * needing to allocate extents from the block group.
1564505a948dSFilipe Manana 		 */
1565505a948dSFilipe Manana 		used = btrfs_space_info_used(space_info, true);
15667b5029e3SJohannes Thumshirn 		if (space_info->total_bytes - block_group->length < used &&
15677b5029e3SJohannes Thumshirn 		    block_group->zone_unusable < block_group->length) {
1568505a948dSFilipe Manana 			/*
1569505a948dSFilipe Manana 			 * Add a reference for the list, compensate for the ref
1570505a948dSFilipe Manana 			 * drop under the "next" label for the
1571505a948dSFilipe Manana 			 * fs_info->unused_bgs list.
1572505a948dSFilipe Manana 			 */
1573505a948dSFilipe Manana 			btrfs_get_block_group(block_group);
1574505a948dSFilipe Manana 			list_add_tail(&block_group->bg_list, &retry_list);
1575505a948dSFilipe Manana 
1576505a948dSFilipe Manana 			trace_btrfs_skip_unused_block_group(block_group);
1577e3e0520bSJosef Bacik 			spin_unlock(&block_group->lock);
1578505a948dSFilipe Manana 			spin_unlock(&space_info->lock);
1579505a948dSFilipe Manana 			up_write(&space_info->groups_sem);
1580505a948dSFilipe Manana 			goto next;
1581505a948dSFilipe Manana 		}
1582505a948dSFilipe Manana 
1583505a948dSFilipe Manana 		spin_unlock(&block_group->lock);
1584505a948dSFilipe Manana 		spin_unlock(&space_info->lock);
1585e3e0520bSJosef Bacik 
1586e3e0520bSJosef Bacik 		/* We don't want to force the issue, only flip if it's ok. */
1587e11c0406SJosef Bacik 		ret = inc_block_group_ro(block_group, 0);
1588e3e0520bSJosef Bacik 		up_write(&space_info->groups_sem);
1589e3e0520bSJosef Bacik 		if (ret < 0) {
1590e3e0520bSJosef Bacik 			ret = 0;
1591e3e0520bSJosef Bacik 			goto next;
1592e3e0520bSJosef Bacik 		}
1593e3e0520bSJosef Bacik 
159474e91b12SNaohiro Aota 		ret = btrfs_zone_finish(block_group);
159574e91b12SNaohiro Aota 		if (ret < 0) {
159674e91b12SNaohiro Aota 			btrfs_dec_block_group_ro(block_group);
159774e91b12SNaohiro Aota 			if (ret == -EAGAIN)
159874e91b12SNaohiro Aota 				ret = 0;
159974e91b12SNaohiro Aota 			goto next;
160074e91b12SNaohiro Aota 		}
160174e91b12SNaohiro Aota 
1602e3e0520bSJosef Bacik 		/*
1603e3e0520bSJosef Bacik 		 * Want to do this before we do anything else so we can recover
1604e3e0520bSJosef Bacik 		 * properly if we fail to join the transaction.
1605e3e0520bSJosef Bacik 		 */
1606e3e0520bSJosef Bacik 		trans = btrfs_start_trans_remove_block_group(fs_info,
1607b3470b5dSDavid Sterba 						     block_group->start);
1608e3e0520bSJosef Bacik 		if (IS_ERR(trans)) {
1609e3e0520bSJosef Bacik 			btrfs_dec_block_group_ro(block_group);
1610e3e0520bSJosef Bacik 			ret = PTR_ERR(trans);
1611e3e0520bSJosef Bacik 			goto next;
1612e3e0520bSJosef Bacik 		}
1613e3e0520bSJosef Bacik 
1614e3e0520bSJosef Bacik 		/*
1615e3e0520bSJosef Bacik 		 * We could have pending pinned extents for this block group,
1616e3e0520bSJosef Bacik 		 * just delete them, we don't care about them anymore.
1617e3e0520bSJosef Bacik 		 */
1618534cf531SFilipe Manana 		if (!clean_pinned_extents(trans, block_group)) {
1619534cf531SFilipe Manana 			btrfs_dec_block_group_ro(block_group);
1620e3e0520bSJosef Bacik 			goto end_trans;
1621534cf531SFilipe Manana 		}
1622e3e0520bSJosef Bacik 
1623b0643e59SDennis Zhou 		/*
1624b0643e59SDennis Zhou 		 * At this point, the block_group is read only and should fail
1625b0643e59SDennis Zhou 		 * new allocations.  However, btrfs_finish_extent_commit() can
1626b0643e59SDennis Zhou 		 * cause this block_group to be placed back on the discard
1627b0643e59SDennis Zhou 		 * lists because now the block_group isn't fully discarded.
1628b0643e59SDennis Zhou 		 * Bail here and try again later after discarding everything.
1629b0643e59SDennis Zhou 		 */
1630b0643e59SDennis Zhou 		spin_lock(&fs_info->discard_ctl.lock);
1631b0643e59SDennis Zhou 		if (!list_empty(&block_group->discard_list)) {
1632b0643e59SDennis Zhou 			spin_unlock(&fs_info->discard_ctl.lock);
1633b0643e59SDennis Zhou 			btrfs_dec_block_group_ro(block_group);
1634b0643e59SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
1635b0643e59SDennis Zhou 						 block_group);
1636b0643e59SDennis Zhou 			goto end_trans;
1637b0643e59SDennis Zhou 		}
1638b0643e59SDennis Zhou 		spin_unlock(&fs_info->discard_ctl.lock);
1639b0643e59SDennis Zhou 
1640e3e0520bSJosef Bacik 		/* Reset pinned so btrfs_put_block_group doesn't complain */
1641e3e0520bSJosef Bacik 		spin_lock(&space_info->lock);
1642e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1643e3e0520bSJosef Bacik 
1644e3e0520bSJosef Bacik 		btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1645e3e0520bSJosef Bacik 						     -block_group->pinned);
1646e3e0520bSJosef Bacik 		space_info->bytes_readonly += block_group->pinned;
1647e3e0520bSJosef Bacik 		block_group->pinned = 0;
1648e3e0520bSJosef Bacik 
1649e3e0520bSJosef Bacik 		spin_unlock(&block_group->lock);
1650e3e0520bSJosef Bacik 		spin_unlock(&space_info->lock);
1651e3e0520bSJosef Bacik 
16526e80d4f8SDennis Zhou 		/*
16536e80d4f8SDennis Zhou 		 * The normal path here is an unused block group is passed here,
16546e80d4f8SDennis Zhou 		 * then trimming is handled in the transaction commit path.
16556e80d4f8SDennis Zhou 		 * Async discard interposes before this to do the trimming
16566e80d4f8SDennis Zhou 		 * before coming down the unused block group path as trimming
16576e80d4f8SDennis Zhou 		 * will no longer be done later in the transaction commit path.
16586e80d4f8SDennis Zhou 		 */
16596e80d4f8SDennis Zhou 		if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
16606e80d4f8SDennis Zhou 			goto flip_async;
16616e80d4f8SDennis Zhou 
1662dcba6e48SNaohiro Aota 		/*
1663dcba6e48SNaohiro Aota 		 * DISCARD can flip during remount. On zoned filesystems, we
1664dcba6e48SNaohiro Aota 		 * need to reset sequential-required zones.
1665dcba6e48SNaohiro Aota 		 */
1666dcba6e48SNaohiro Aota 		trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) ||
1667dcba6e48SNaohiro Aota 				btrfs_is_zoned(fs_info);
1668e3e0520bSJosef Bacik 
1669e3e0520bSJosef Bacik 		/* Implicit trim during transaction commit. */
1670e3e0520bSJosef Bacik 		if (trimming)
16716b7304afSFilipe Manana 			btrfs_freeze_block_group(block_group);
1672e3e0520bSJosef Bacik 
1673e3e0520bSJosef Bacik 		/*
1674e3e0520bSJosef Bacik 		 * Btrfs_remove_chunk will abort the transaction if things go
1675e3e0520bSJosef Bacik 		 * horribly wrong.
1676e3e0520bSJosef Bacik 		 */
1677b3470b5dSDavid Sterba 		ret = btrfs_remove_chunk(trans, block_group->start);
1678e3e0520bSJosef Bacik 
1679e3e0520bSJosef Bacik 		if (ret) {
1680e3e0520bSJosef Bacik 			if (trimming)
16816b7304afSFilipe Manana 				btrfs_unfreeze_block_group(block_group);
1682e3e0520bSJosef Bacik 			goto end_trans;
1683e3e0520bSJosef Bacik 		}
1684e3e0520bSJosef Bacik 
1685e3e0520bSJosef Bacik 		/*
1686e3e0520bSJosef Bacik 		 * If we're not mounted with -odiscard, we can just forget
1687e3e0520bSJosef Bacik 		 * about this block group. Otherwise we'll need to wait
1688e3e0520bSJosef Bacik 		 * until transaction commit to do the actual discard.
1689e3e0520bSJosef Bacik 		 */
1690e3e0520bSJosef Bacik 		if (trimming) {
1691e3e0520bSJosef Bacik 			spin_lock(&fs_info->unused_bgs_lock);
1692e3e0520bSJosef Bacik 			/*
1693e3e0520bSJosef Bacik 			 * A concurrent scrub might have added us to the list
1694e3e0520bSJosef Bacik 			 * fs_info->unused_bgs, so use a list_move operation
1695e3e0520bSJosef Bacik 			 * to add the block group to the deleted_bgs list.
1696e3e0520bSJosef Bacik 			 */
1697e3e0520bSJosef Bacik 			list_move(&block_group->bg_list,
1698e3e0520bSJosef Bacik 				  &trans->transaction->deleted_bgs);
1699e3e0520bSJosef Bacik 			spin_unlock(&fs_info->unused_bgs_lock);
1700e3e0520bSJosef Bacik 			btrfs_get_block_group(block_group);
1701e3e0520bSJosef Bacik 		}
1702e3e0520bSJosef Bacik end_trans:
1703e3e0520bSJosef Bacik 		btrfs_end_transaction(trans);
1704e3e0520bSJosef Bacik next:
1705e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1706e3e0520bSJosef Bacik 		spin_lock(&fs_info->unused_bgs_lock);
1707e3e0520bSJosef Bacik 	}
1708505a948dSFilipe Manana 	list_splice_tail(&retry_list, &fs_info->unused_bgs);
1709e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
1710f3372065SJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
17116e80d4f8SDennis Zhou 	return;
17126e80d4f8SDennis Zhou 
17136e80d4f8SDennis Zhou flip_async:
17146e80d4f8SDennis Zhou 	btrfs_end_transaction(trans);
1715505a948dSFilipe Manana 	spin_lock(&fs_info->unused_bgs_lock);
1716505a948dSFilipe Manana 	list_splice_tail(&retry_list, &fs_info->unused_bgs);
1717505a948dSFilipe Manana 	spin_unlock(&fs_info->unused_bgs_lock);
1718f3372065SJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
17196e80d4f8SDennis Zhou 	btrfs_put_block_group(block_group);
17206e80d4f8SDennis Zhou 	btrfs_discard_punt_unused_bgs_list(fs_info);
1721e3e0520bSJosef Bacik }
1722e3e0520bSJosef Bacik 
btrfs_mark_bg_unused(struct btrfs_block_group * bg)172332da5386SDavid Sterba void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1724e3e0520bSJosef Bacik {
1725e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = bg->fs_info;
1726e3e0520bSJosef Bacik 
1727e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1728e3e0520bSJosef Bacik 	if (list_empty(&bg->bg_list)) {
1729e3e0520bSJosef Bacik 		btrfs_get_block_group(bg);
17300657b20cSFilipe Manana 		trace_btrfs_add_unused_block_group(bg);
1731e3e0520bSJosef Bacik 		list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
17320657b20cSFilipe Manana 	} else if (!test_bit(BLOCK_GROUP_FLAG_NEW, &bg->runtime_flags)) {
1733a9f18971SNaohiro Aota 		/* Pull out the block group from the reclaim_bgs list. */
17340657b20cSFilipe Manana 		trace_btrfs_add_unused_block_group(bg);
1735a9f18971SNaohiro Aota 		list_move_tail(&bg->bg_list, &fs_info->unused_bgs);
1736e3e0520bSJosef Bacik 	}
1737e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
1738e3e0520bSJosef Bacik }
17394358d963SJosef Bacik 
17402ca0ec77SJohannes Thumshirn /*
17412ca0ec77SJohannes Thumshirn  * We want block groups with a low number of used bytes to be in the beginning
17422ca0ec77SJohannes Thumshirn  * of the list, so they will get reclaimed first.
17432ca0ec77SJohannes Thumshirn  */
reclaim_bgs_cmp(void * unused,const struct list_head * a,const struct list_head * b)17442ca0ec77SJohannes Thumshirn static int reclaim_bgs_cmp(void *unused, const struct list_head *a,
17452ca0ec77SJohannes Thumshirn 			   const struct list_head *b)
17462ca0ec77SJohannes Thumshirn {
17472ca0ec77SJohannes Thumshirn 	const struct btrfs_block_group *bg1, *bg2;
17482ca0ec77SJohannes Thumshirn 
17492ca0ec77SJohannes Thumshirn 	bg1 = list_entry(a, struct btrfs_block_group, bg_list);
17502ca0ec77SJohannes Thumshirn 	bg2 = list_entry(b, struct btrfs_block_group, bg_list);
17512ca0ec77SJohannes Thumshirn 
17522ca0ec77SJohannes Thumshirn 	return bg1->used > bg2->used;
17532ca0ec77SJohannes Thumshirn }
17542ca0ec77SJohannes Thumshirn 
btrfs_should_reclaim(struct btrfs_fs_info * fs_info)17553687fcb0SJohannes Thumshirn static inline bool btrfs_should_reclaim(struct btrfs_fs_info *fs_info)
17563687fcb0SJohannes Thumshirn {
17573687fcb0SJohannes Thumshirn 	if (btrfs_is_zoned(fs_info))
17583687fcb0SJohannes Thumshirn 		return btrfs_zoned_should_reclaim(fs_info);
17593687fcb0SJohannes Thumshirn 	return true;
17603687fcb0SJohannes Thumshirn }
17613687fcb0SJohannes Thumshirn 
should_reclaim_block_group(struct btrfs_block_group * bg,u64 bytes_freed)176281531225SBoris Burkov static bool should_reclaim_block_group(struct btrfs_block_group *bg, u64 bytes_freed)
176381531225SBoris Burkov {
176481531225SBoris Burkov 	const struct btrfs_space_info *space_info = bg->space_info;
176581531225SBoris Burkov 	const int reclaim_thresh = READ_ONCE(space_info->bg_reclaim_threshold);
176681531225SBoris Burkov 	const u64 new_val = bg->used;
176781531225SBoris Burkov 	const u64 old_val = new_val + bytes_freed;
176881531225SBoris Burkov 	u64 thresh;
176981531225SBoris Burkov 
177081531225SBoris Burkov 	if (reclaim_thresh == 0)
177181531225SBoris Burkov 		return false;
177281531225SBoris Burkov 
1773428c8e03SDavid Sterba 	thresh = mult_perc(bg->length, reclaim_thresh);
177481531225SBoris Burkov 
177581531225SBoris Burkov 	/*
177681531225SBoris Burkov 	 * If we were below the threshold before don't reclaim, we are likely a
177781531225SBoris Burkov 	 * brand new block group and we don't want to relocate new block groups.
177881531225SBoris Burkov 	 */
177981531225SBoris Burkov 	if (old_val < thresh)
178081531225SBoris Burkov 		return false;
178181531225SBoris Burkov 	if (new_val >= thresh)
178281531225SBoris Burkov 		return false;
178381531225SBoris Burkov 	return true;
178481531225SBoris Burkov }
178581531225SBoris Burkov 
btrfs_reclaim_bgs_work(struct work_struct * work)178618bb8bbfSJohannes Thumshirn void btrfs_reclaim_bgs_work(struct work_struct *work)
178718bb8bbfSJohannes Thumshirn {
178818bb8bbfSJohannes Thumshirn 	struct btrfs_fs_info *fs_info =
178918bb8bbfSJohannes Thumshirn 		container_of(work, struct btrfs_fs_info, reclaim_bgs_work);
179018bb8bbfSJohannes Thumshirn 	struct btrfs_block_group *bg;
179118bb8bbfSJohannes Thumshirn 	struct btrfs_space_info *space_info;
1792bf1e8c21SBoris Burkov 	LIST_HEAD(retry_list);
179318bb8bbfSJohannes Thumshirn 
179418bb8bbfSJohannes Thumshirn 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
179518bb8bbfSJohannes Thumshirn 		return;
179618bb8bbfSJohannes Thumshirn 
17972f12741fSJosef Bacik 	if (btrfs_fs_closing(fs_info))
17982f12741fSJosef Bacik 		return;
17992f12741fSJosef Bacik 
18003687fcb0SJohannes Thumshirn 	if (!btrfs_should_reclaim(fs_info))
18013687fcb0SJohannes Thumshirn 		return;
18023687fcb0SJohannes Thumshirn 
1803ca5e4ea0SNaohiro Aota 	sb_start_write(fs_info->sb);
1804ca5e4ea0SNaohiro Aota 
1805ca5e4ea0SNaohiro Aota 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
1806ca5e4ea0SNaohiro Aota 		sb_end_write(fs_info->sb);
180718bb8bbfSJohannes Thumshirn 		return;
1808ca5e4ea0SNaohiro Aota 	}
180918bb8bbfSJohannes Thumshirn 
18109cc0b837SJohannes Thumshirn 	/*
18119cc0b837SJohannes Thumshirn 	 * Long running balances can keep us blocked here for eternity, so
18129cc0b837SJohannes Thumshirn 	 * simply skip reclaim if we're unable to get the mutex.
18139cc0b837SJohannes Thumshirn 	 */
18149cc0b837SJohannes Thumshirn 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) {
18159cc0b837SJohannes Thumshirn 		btrfs_exclop_finish(fs_info);
1816ca5e4ea0SNaohiro Aota 		sb_end_write(fs_info->sb);
18179cc0b837SJohannes Thumshirn 		return;
18189cc0b837SJohannes Thumshirn 	}
18199cc0b837SJohannes Thumshirn 
182018bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
18212ca0ec77SJohannes Thumshirn 	/*
18222ca0ec77SJohannes Thumshirn 	 * Sort happens under lock because we can't simply splice it and sort.
18232ca0ec77SJohannes Thumshirn 	 * The block groups might still be in use and reachable via bg_list,
18242ca0ec77SJohannes Thumshirn 	 * and their presence in the reclaim_bgs list must be preserved.
18252ca0ec77SJohannes Thumshirn 	 */
18262ca0ec77SJohannes Thumshirn 	list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp);
182718bb8bbfSJohannes Thumshirn 	while (!list_empty(&fs_info->reclaim_bgs)) {
18285f93e776SJohannes Thumshirn 		u64 zone_unusable;
18291cea5cf0SFilipe Manana 		int ret = 0;
18301cea5cf0SFilipe Manana 
183118bb8bbfSJohannes Thumshirn 		bg = list_first_entry(&fs_info->reclaim_bgs,
183218bb8bbfSJohannes Thumshirn 				      struct btrfs_block_group,
183318bb8bbfSJohannes Thumshirn 				      bg_list);
183418bb8bbfSJohannes Thumshirn 		list_del_init(&bg->bg_list);
183518bb8bbfSJohannes Thumshirn 
183618bb8bbfSJohannes Thumshirn 		space_info = bg->space_info;
183718bb8bbfSJohannes Thumshirn 		spin_unlock(&fs_info->unused_bgs_lock);
183818bb8bbfSJohannes Thumshirn 
183918bb8bbfSJohannes Thumshirn 		/* Don't race with allocators so take the groups_sem */
184018bb8bbfSJohannes Thumshirn 		down_write(&space_info->groups_sem);
184118bb8bbfSJohannes Thumshirn 
184218bb8bbfSJohannes Thumshirn 		spin_lock(&bg->lock);
184318bb8bbfSJohannes Thumshirn 		if (bg->reserved || bg->pinned || bg->ro) {
184418bb8bbfSJohannes Thumshirn 			/*
184518bb8bbfSJohannes Thumshirn 			 * We want to bail if we made new allocations or have
184618bb8bbfSJohannes Thumshirn 			 * outstanding allocations in this block group.  We do
184718bb8bbfSJohannes Thumshirn 			 * the ro check in case balance is currently acting on
184818bb8bbfSJohannes Thumshirn 			 * this block group.
184918bb8bbfSJohannes Thumshirn 			 */
185018bb8bbfSJohannes Thumshirn 			spin_unlock(&bg->lock);
185118bb8bbfSJohannes Thumshirn 			up_write(&space_info->groups_sem);
185218bb8bbfSJohannes Thumshirn 			goto next;
185318bb8bbfSJohannes Thumshirn 		}
1854cc4804bfSBoris Burkov 		if (bg->used == 0) {
1855cc4804bfSBoris Burkov 			/*
1856cc4804bfSBoris Burkov 			 * It is possible that we trigger relocation on a block
1857cc4804bfSBoris Burkov 			 * group as its extents are deleted and it first goes
1858cc4804bfSBoris Burkov 			 * below the threshold, then shortly after goes empty.
1859cc4804bfSBoris Burkov 			 *
1860cc4804bfSBoris Burkov 			 * In this case, relocating it does delete it, but has
1861cc4804bfSBoris Burkov 			 * some overhead in relocation specific metadata, looking
1862cc4804bfSBoris Burkov 			 * for the non-existent extents and running some extra
1863cc4804bfSBoris Burkov 			 * transactions, which we can avoid by using one of the
1864cc4804bfSBoris Burkov 			 * other mechanisms for dealing with empty block groups.
1865cc4804bfSBoris Burkov 			 */
1866cc4804bfSBoris Burkov 			if (!btrfs_test_opt(fs_info, DISCARD_ASYNC))
1867cc4804bfSBoris Burkov 				btrfs_mark_bg_unused(bg);
1868cc4804bfSBoris Burkov 			spin_unlock(&bg->lock);
1869cc4804bfSBoris Burkov 			up_write(&space_info->groups_sem);
1870cc4804bfSBoris Burkov 			goto next;
187181531225SBoris Burkov 
187281531225SBoris Burkov 		}
187381531225SBoris Burkov 		/*
187481531225SBoris Burkov 		 * The block group might no longer meet the reclaim condition by
187581531225SBoris Burkov 		 * the time we get around to reclaiming it, so to avoid
187681531225SBoris Burkov 		 * reclaiming overly full block_groups, skip reclaiming them.
187781531225SBoris Burkov 		 *
187881531225SBoris Burkov 		 * Since the decision making process also depends on the amount
187981531225SBoris Burkov 		 * being freed, pass in a fake giant value to skip that extra
188081531225SBoris Burkov 		 * check, which is more meaningful when adding to the list in
188181531225SBoris Burkov 		 * the first place.
188281531225SBoris Burkov 		 */
188381531225SBoris Burkov 		if (!should_reclaim_block_group(bg, bg->length)) {
188481531225SBoris Burkov 			spin_unlock(&bg->lock);
188581531225SBoris Burkov 			up_write(&space_info->groups_sem);
188681531225SBoris Burkov 			goto next;
1887cc4804bfSBoris Burkov 		}
188818bb8bbfSJohannes Thumshirn 		spin_unlock(&bg->lock);
188918bb8bbfSJohannes Thumshirn 
189093463ff7SNaohiro Aota 		/*
189193463ff7SNaohiro Aota 		 * Get out fast, in case we're read-only or unmounting the
189293463ff7SNaohiro Aota 		 * filesystem. It is OK to drop block groups from the list even
189393463ff7SNaohiro Aota 		 * for the read-only case. As we did sb_start_write(),
189493463ff7SNaohiro Aota 		 * "mount -o remount,ro" won't happen and read-only filesystem
189593463ff7SNaohiro Aota 		 * means it is forced read-only due to a fatal error. So, it
189693463ff7SNaohiro Aota 		 * never gets back to read-write to let us reclaim again.
189793463ff7SNaohiro Aota 		 */
189893463ff7SNaohiro Aota 		if (btrfs_need_cleaner_sleep(fs_info)) {
189918bb8bbfSJohannes Thumshirn 			up_write(&space_info->groups_sem);
190018bb8bbfSJohannes Thumshirn 			goto next;
190118bb8bbfSJohannes Thumshirn 		}
190218bb8bbfSJohannes Thumshirn 
19035f93e776SJohannes Thumshirn 		/*
19045f93e776SJohannes Thumshirn 		 * Cache the zone_unusable value before turning the block group
19055f93e776SJohannes Thumshirn 		 * to read only. As soon as the blog group is read only it's
19065f93e776SJohannes Thumshirn 		 * zone_unusable value gets moved to the block group's read-only
19075f93e776SJohannes Thumshirn 		 * bytes and isn't available for calculations anymore.
19085f93e776SJohannes Thumshirn 		 */
19095f93e776SJohannes Thumshirn 		zone_unusable = bg->zone_unusable;
191018bb8bbfSJohannes Thumshirn 		ret = inc_block_group_ro(bg, 0);
191118bb8bbfSJohannes Thumshirn 		up_write(&space_info->groups_sem);
191218bb8bbfSJohannes Thumshirn 		if (ret < 0)
191318bb8bbfSJohannes Thumshirn 			goto next;
191418bb8bbfSJohannes Thumshirn 
19155f93e776SJohannes Thumshirn 		btrfs_info(fs_info,
19165f93e776SJohannes Thumshirn 			"reclaiming chunk %llu with %llu%% used %llu%% unusable",
191795cd356cSJohannes Thumshirn 				bg->start,
191895cd356cSJohannes Thumshirn 				div64_u64(bg->used * 100, bg->length),
19195f93e776SJohannes Thumshirn 				div64_u64(zone_unusable * 100, bg->length));
192018bb8bbfSJohannes Thumshirn 		trace_btrfs_reclaim_block_group(bg);
192118bb8bbfSJohannes Thumshirn 		ret = btrfs_relocate_chunk(fs_info, bg->start);
192274944c87SJosef Bacik 		if (ret) {
192374944c87SJosef Bacik 			btrfs_dec_block_group_ro(bg);
192418bb8bbfSJohannes Thumshirn 			btrfs_err(fs_info, "error relocating chunk %llu",
192518bb8bbfSJohannes Thumshirn 				  bg->start);
192674944c87SJosef Bacik 		}
192718bb8bbfSJohannes Thumshirn 
192818bb8bbfSJohannes Thumshirn next:
1929bf1e8c21SBoris Burkov 		if (ret) {
1930bf1e8c21SBoris Burkov 			/* Refcount held by the reclaim_bgs list after splice. */
1931f8e960beSNaohiro Aota 			spin_lock(&fs_info->unused_bgs_lock);
1932f8e960beSNaohiro Aota 			/*
1933f8e960beSNaohiro Aota 			 * This block group might be added to the unused list
1934f8e960beSNaohiro Aota 			 * during the above process. Move it back to the
1935f8e960beSNaohiro Aota 			 * reclaim list otherwise.
1936f8e960beSNaohiro Aota 			 */
1937f8e960beSNaohiro Aota 			if (list_empty(&bg->bg_list)) {
1938bf1e8c21SBoris Burkov 				btrfs_get_block_group(bg);
1939bf1e8c21SBoris Burkov 				list_add_tail(&bg->bg_list, &retry_list);
1940bf1e8c21SBoris Burkov 			}
1941f8e960beSNaohiro Aota 			spin_unlock(&fs_info->unused_bgs_lock);
1942f8e960beSNaohiro Aota 		}
19431cea5cf0SFilipe Manana 		btrfs_put_block_group(bg);
19443ed01616SNaohiro Aota 
19453ed01616SNaohiro Aota 		mutex_unlock(&fs_info->reclaim_bgs_lock);
19463ed01616SNaohiro Aota 		/*
19473ed01616SNaohiro Aota 		 * Reclaiming all the block groups in the list can take really
19483ed01616SNaohiro Aota 		 * long.  Prioritize cleaning up unused block groups.
19493ed01616SNaohiro Aota 		 */
19503ed01616SNaohiro Aota 		btrfs_delete_unused_bgs(fs_info);
19513ed01616SNaohiro Aota 		/*
19523ed01616SNaohiro Aota 		 * If we are interrupted by a balance, we can just bail out. The
19533ed01616SNaohiro Aota 		 * cleaner thread restart again if necessary.
19543ed01616SNaohiro Aota 		 */
19553ed01616SNaohiro Aota 		if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
19563ed01616SNaohiro Aota 			goto end;
1957d96b3424SFilipe Manana 		spin_lock(&fs_info->unused_bgs_lock);
195818bb8bbfSJohannes Thumshirn 	}
195918bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
196018bb8bbfSJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
19613ed01616SNaohiro Aota end:
1962bf1e8c21SBoris Burkov 	spin_lock(&fs_info->unused_bgs_lock);
1963bf1e8c21SBoris Burkov 	list_splice_tail(&retry_list, &fs_info->reclaim_bgs);
1964bf1e8c21SBoris Burkov 	spin_unlock(&fs_info->unused_bgs_lock);
196518bb8bbfSJohannes Thumshirn 	btrfs_exclop_finish(fs_info);
1966ca5e4ea0SNaohiro Aota 	sb_end_write(fs_info->sb);
196718bb8bbfSJohannes Thumshirn }
196818bb8bbfSJohannes Thumshirn 
btrfs_reclaim_bgs(struct btrfs_fs_info * fs_info)196918bb8bbfSJohannes Thumshirn void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
197018bb8bbfSJohannes Thumshirn {
197118bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
197218bb8bbfSJohannes Thumshirn 	if (!list_empty(&fs_info->reclaim_bgs))
197318bb8bbfSJohannes Thumshirn 		queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
197418bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
197518bb8bbfSJohannes Thumshirn }
197618bb8bbfSJohannes Thumshirn 
btrfs_mark_bg_to_reclaim(struct btrfs_block_group * bg)197718bb8bbfSJohannes Thumshirn void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
197818bb8bbfSJohannes Thumshirn {
197918bb8bbfSJohannes Thumshirn 	struct btrfs_fs_info *fs_info = bg->fs_info;
198018bb8bbfSJohannes Thumshirn 
198118bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
198218bb8bbfSJohannes Thumshirn 	if (list_empty(&bg->bg_list)) {
198318bb8bbfSJohannes Thumshirn 		btrfs_get_block_group(bg);
198418bb8bbfSJohannes Thumshirn 		trace_btrfs_add_reclaim_block_group(bg);
198518bb8bbfSJohannes Thumshirn 		list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
198618bb8bbfSJohannes Thumshirn 	}
198718bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
198818bb8bbfSJohannes Thumshirn }
198918bb8bbfSJohannes Thumshirn 
read_bg_from_eb(struct btrfs_fs_info * fs_info,struct btrfs_key * key,struct btrfs_path * path)1990e3ba67a1SJohannes Thumshirn static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1991e3ba67a1SJohannes Thumshirn 			   struct btrfs_path *path)
1992e3ba67a1SJohannes Thumshirn {
1993e3ba67a1SJohannes Thumshirn 	struct extent_map_tree *em_tree;
1994e3ba67a1SJohannes Thumshirn 	struct extent_map *em;
1995e3ba67a1SJohannes Thumshirn 	struct btrfs_block_group_item bg;
1996e3ba67a1SJohannes Thumshirn 	struct extent_buffer *leaf;
1997e3ba67a1SJohannes Thumshirn 	int slot;
1998e3ba67a1SJohannes Thumshirn 	u64 flags;
1999e3ba67a1SJohannes Thumshirn 	int ret = 0;
2000e3ba67a1SJohannes Thumshirn 
2001e3ba67a1SJohannes Thumshirn 	slot = path->slots[0];
2002e3ba67a1SJohannes Thumshirn 	leaf = path->nodes[0];
2003e3ba67a1SJohannes Thumshirn 
2004e3ba67a1SJohannes Thumshirn 	em_tree = &fs_info->mapping_tree;
2005e3ba67a1SJohannes Thumshirn 	read_lock(&em_tree->lock);
2006e3ba67a1SJohannes Thumshirn 	em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
2007e3ba67a1SJohannes Thumshirn 	read_unlock(&em_tree->lock);
2008e3ba67a1SJohannes Thumshirn 	if (!em) {
2009e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
2010e3ba67a1SJohannes Thumshirn 			  "logical %llu len %llu found bg but no related chunk",
2011e3ba67a1SJohannes Thumshirn 			  key->objectid, key->offset);
2012e3ba67a1SJohannes Thumshirn 		return -ENOENT;
2013e3ba67a1SJohannes Thumshirn 	}
2014e3ba67a1SJohannes Thumshirn 
2015e3ba67a1SJohannes Thumshirn 	if (em->start != key->objectid || em->len != key->offset) {
2016e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
2017e3ba67a1SJohannes Thumshirn 			"block group %llu len %llu mismatch with chunk %llu len %llu",
2018e3ba67a1SJohannes Thumshirn 			key->objectid, key->offset, em->start, em->len);
2019e3ba67a1SJohannes Thumshirn 		ret = -EUCLEAN;
2020e3ba67a1SJohannes Thumshirn 		goto out_free_em;
2021e3ba67a1SJohannes Thumshirn 	}
2022e3ba67a1SJohannes Thumshirn 
2023e3ba67a1SJohannes Thumshirn 	read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
2024e3ba67a1SJohannes Thumshirn 			   sizeof(bg));
2025e3ba67a1SJohannes Thumshirn 	flags = btrfs_stack_block_group_flags(&bg) &
2026e3ba67a1SJohannes Thumshirn 		BTRFS_BLOCK_GROUP_TYPE_MASK;
2027e3ba67a1SJohannes Thumshirn 
2028e3ba67a1SJohannes Thumshirn 	if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
2029e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
2030e3ba67a1SJohannes Thumshirn "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
2031e3ba67a1SJohannes Thumshirn 			  key->objectid, key->offset, flags,
2032e3ba67a1SJohannes Thumshirn 			  (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
2033e3ba67a1SJohannes Thumshirn 		ret = -EUCLEAN;
2034e3ba67a1SJohannes Thumshirn 	}
2035e3ba67a1SJohannes Thumshirn 
2036e3ba67a1SJohannes Thumshirn out_free_em:
2037e3ba67a1SJohannes Thumshirn 	free_extent_map(em);
2038e3ba67a1SJohannes Thumshirn 	return ret;
2039e3ba67a1SJohannes Thumshirn }
2040e3ba67a1SJohannes Thumshirn 
find_first_block_group(struct btrfs_fs_info * fs_info,struct btrfs_path * path,struct btrfs_key * key)20414358d963SJosef Bacik static int find_first_block_group(struct btrfs_fs_info *fs_info,
20424358d963SJosef Bacik 				  struct btrfs_path *path,
20434358d963SJosef Bacik 				  struct btrfs_key *key)
20444358d963SJosef Bacik {
2045dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
2046e3ba67a1SJohannes Thumshirn 	int ret;
20474358d963SJosef Bacik 	struct btrfs_key found_key;
20484358d963SJosef Bacik 
204936dfbbe2SGabriel Niebler 	btrfs_for_each_slot(root, key, &found_key, path, ret) {
20504358d963SJosef Bacik 		if (found_key.objectid >= key->objectid &&
20514358d963SJosef Bacik 		    found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
205236dfbbe2SGabriel Niebler 			return read_bg_from_eb(fs_info, &found_key, path);
2053e3ba67a1SJohannes Thumshirn 		}
20544358d963SJosef Bacik 	}
20554358d963SJosef Bacik 	return ret;
20564358d963SJosef Bacik }
20574358d963SJosef Bacik 
set_avail_alloc_bits(struct btrfs_fs_info * fs_info,u64 flags)20584358d963SJosef Bacik static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
20594358d963SJosef Bacik {
20604358d963SJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
20614358d963SJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
20624358d963SJosef Bacik 
20634358d963SJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
20644358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
20654358d963SJosef Bacik 		fs_info->avail_data_alloc_bits |= extra_flags;
20664358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
20674358d963SJosef Bacik 		fs_info->avail_metadata_alloc_bits |= extra_flags;
20684358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
20694358d963SJosef Bacik 		fs_info->avail_system_alloc_bits |= extra_flags;
20704358d963SJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
20714358d963SJosef Bacik }
20724358d963SJosef Bacik 
207343dd529aSDavid Sterba /*
207443dd529aSDavid Sterba  * Map a physical disk address to a list of logical addresses.
20759ee9b979SNikolay Borisov  *
20769ee9b979SNikolay Borisov  * @fs_info:       the filesystem
207796a14336SNikolay Borisov  * @chunk_start:   logical address of block group
207896a14336SNikolay Borisov  * @physical:	   physical address to map to logical addresses
207996a14336SNikolay Borisov  * @logical:	   return array of logical addresses which map to @physical
208096a14336SNikolay Borisov  * @naddrs:	   length of @logical
208196a14336SNikolay Borisov  * @stripe_len:    size of IO stripe for the given block group
208296a14336SNikolay Borisov  *
208396a14336SNikolay Borisov  * Maps a particular @physical disk address to a list of @logical addresses.
208496a14336SNikolay Borisov  * Used primarily to exclude those portions of a block group that contain super
208596a14336SNikolay Borisov  * block copies.
208696a14336SNikolay Borisov  */
btrfs_rmap_block(struct btrfs_fs_info * fs_info,u64 chunk_start,u64 physical,u64 ** logical,int * naddrs,int * stripe_len)208796a14336SNikolay Borisov int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
20881eb82ef8SChristoph Hellwig 		     u64 physical, u64 **logical, int *naddrs, int *stripe_len)
208996a14336SNikolay Borisov {
209096a14336SNikolay Borisov 	struct extent_map *em;
209196a14336SNikolay Borisov 	struct map_lookup *map;
209296a14336SNikolay Borisov 	u64 *buf;
209396a14336SNikolay Borisov 	u64 bytenr;
20941776ad17SNikolay Borisov 	u64 data_stripe_length;
20951776ad17SNikolay Borisov 	u64 io_stripe_size;
20961776ad17SNikolay Borisov 	int i, nr = 0;
20971776ad17SNikolay Borisov 	int ret = 0;
209896a14336SNikolay Borisov 
209996a14336SNikolay Borisov 	em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
210096a14336SNikolay Borisov 	if (IS_ERR(em))
210196a14336SNikolay Borisov 		return -EIO;
210296a14336SNikolay Borisov 
210396a14336SNikolay Borisov 	map = em->map_lookup;
21049e22b925SNikolay Borisov 	data_stripe_length = em->orig_block_len;
2105a97699d1SQu Wenruo 	io_stripe_size = BTRFS_STRIPE_LEN;
2106138082f3SNaohiro Aota 	chunk_start = em->start;
210796a14336SNikolay Borisov 
21089e22b925SNikolay Borisov 	/* For RAID5/6 adjust to a full IO stripe length */
21099e22b925SNikolay Borisov 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
2110cb091225SQu Wenruo 		io_stripe_size = btrfs_stripe_nr_to_offset(nr_data_stripes(map));
211196a14336SNikolay Borisov 
211296a14336SNikolay Borisov 	buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
21131776ad17SNikolay Borisov 	if (!buf) {
21141776ad17SNikolay Borisov 		ret = -ENOMEM;
21151776ad17SNikolay Borisov 		goto out;
21161776ad17SNikolay Borisov 	}
211796a14336SNikolay Borisov 
211896a14336SNikolay Borisov 	for (i = 0; i < map->num_stripes; i++) {
21191776ad17SNikolay Borisov 		bool already_inserted = false;
21206ded22c1SQu Wenruo 		u32 stripe_nr;
21216ded22c1SQu Wenruo 		u32 offset;
21221776ad17SNikolay Borisov 		int j;
21231776ad17SNikolay Borisov 
21241776ad17SNikolay Borisov 		if (!in_range(physical, map->stripes[i].physical,
21251776ad17SNikolay Borisov 			      data_stripe_length))
212696a14336SNikolay Borisov 			continue;
212796a14336SNikolay Borisov 
2128a97699d1SQu Wenruo 		stripe_nr = (physical - map->stripes[i].physical) >>
2129a97699d1SQu Wenruo 			    BTRFS_STRIPE_LEN_SHIFT;
2130a97699d1SQu Wenruo 		offset = (physical - map->stripes[i].physical) &
2131a97699d1SQu Wenruo 			 BTRFS_STRIPE_LEN_MASK;
213296a14336SNikolay Borisov 
2133ac067734SDavid Sterba 		if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
21346ded22c1SQu Wenruo 				 BTRFS_BLOCK_GROUP_RAID10))
21356ded22c1SQu Wenruo 			stripe_nr = div_u64(stripe_nr * map->num_stripes + i,
21366ded22c1SQu Wenruo 					    map->sub_stripes);
213796a14336SNikolay Borisov 		/*
213896a14336SNikolay Borisov 		 * The remaining case would be for RAID56, multiply by
213996a14336SNikolay Borisov 		 * nr_data_stripes().  Alternatively, just use rmap_len below
214096a14336SNikolay Borisov 		 * instead of map->stripe_len
214196a14336SNikolay Borisov 		 */
2142138082f3SNaohiro Aota 		bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
21431776ad17SNikolay Borisov 
21441776ad17SNikolay Borisov 		/* Ensure we don't add duplicate addresses */
214596a14336SNikolay Borisov 		for (j = 0; j < nr; j++) {
21461776ad17SNikolay Borisov 			if (buf[j] == bytenr) {
21471776ad17SNikolay Borisov 				already_inserted = true;
214896a14336SNikolay Borisov 				break;
214996a14336SNikolay Borisov 			}
215096a14336SNikolay Borisov 		}
21511776ad17SNikolay Borisov 
21521776ad17SNikolay Borisov 		if (!already_inserted)
21531776ad17SNikolay Borisov 			buf[nr++] = bytenr;
215496a14336SNikolay Borisov 	}
215596a14336SNikolay Borisov 
215696a14336SNikolay Borisov 	*logical = buf;
215796a14336SNikolay Borisov 	*naddrs = nr;
21581776ad17SNikolay Borisov 	*stripe_len = io_stripe_size;
21591776ad17SNikolay Borisov out:
216096a14336SNikolay Borisov 	free_extent_map(em);
21611776ad17SNikolay Borisov 	return ret;
216296a14336SNikolay Borisov }
216396a14336SNikolay Borisov 
exclude_super_stripes(struct btrfs_block_group * cache)216432da5386SDavid Sterba static int exclude_super_stripes(struct btrfs_block_group *cache)
21654358d963SJosef Bacik {
21664358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
216712659251SNaohiro Aota 	const bool zoned = btrfs_is_zoned(fs_info);
21684358d963SJosef Bacik 	u64 bytenr;
21694358d963SJosef Bacik 	u64 *logical;
21704358d963SJosef Bacik 	int stripe_len;
21714358d963SJosef Bacik 	int i, nr, ret;
21724358d963SJosef Bacik 
2173b3470b5dSDavid Sterba 	if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
2174b3470b5dSDavid Sterba 		stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
21754358d963SJosef Bacik 		cache->bytes_super += stripe_len;
2176b1c8f527SFilipe Manana 		ret = set_extent_bit(&fs_info->excluded_extents, cache->start,
2177b1c8f527SFilipe Manana 				     cache->start + stripe_len - 1,
2178b1c8f527SFilipe Manana 				     EXTENT_UPTODATE, NULL);
21794358d963SJosef Bacik 		if (ret)
21804358d963SJosef Bacik 			return ret;
21814358d963SJosef Bacik 	}
21824358d963SJosef Bacik 
21834358d963SJosef Bacik 	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
21844358d963SJosef Bacik 		bytenr = btrfs_sb_offset(i);
21851eb82ef8SChristoph Hellwig 		ret = btrfs_rmap_block(fs_info, cache->start,
21864358d963SJosef Bacik 				       bytenr, &logical, &nr, &stripe_len);
21874358d963SJosef Bacik 		if (ret)
21884358d963SJosef Bacik 			return ret;
21894358d963SJosef Bacik 
219012659251SNaohiro Aota 		/* Shouldn't have super stripes in sequential zones */
219112659251SNaohiro Aota 		if (zoned && nr) {
2192f1a07c2bSFilipe Manana 			kfree(logical);
219312659251SNaohiro Aota 			btrfs_err(fs_info,
219412659251SNaohiro Aota 			"zoned: block group %llu must not contain super block",
219512659251SNaohiro Aota 				  cache->start);
219612659251SNaohiro Aota 			return -EUCLEAN;
219712659251SNaohiro Aota 		}
219812659251SNaohiro Aota 
21994358d963SJosef Bacik 		while (nr--) {
220096f9b0f2SNikolay Borisov 			u64 len = min_t(u64, stripe_len,
220196f9b0f2SNikolay Borisov 				cache->start + cache->length - logical[nr]);
22024358d963SJosef Bacik 
22034358d963SJosef Bacik 			cache->bytes_super += len;
2204b1c8f527SFilipe Manana 			ret = set_extent_bit(&fs_info->excluded_extents, logical[nr],
2205b1c8f527SFilipe Manana 					     logical[nr] + len - 1,
2206b1c8f527SFilipe Manana 					     EXTENT_UPTODATE, NULL);
22074358d963SJosef Bacik 			if (ret) {
22084358d963SJosef Bacik 				kfree(logical);
22094358d963SJosef Bacik 				return ret;
22104358d963SJosef Bacik 			}
22114358d963SJosef Bacik 		}
22124358d963SJosef Bacik 
22134358d963SJosef Bacik 		kfree(logical);
22144358d963SJosef Bacik 	}
22154358d963SJosef Bacik 	return 0;
22164358d963SJosef Bacik }
22174358d963SJosef Bacik 
btrfs_create_block_group_cache(struct btrfs_fs_info * fs_info,u64 start)221832da5386SDavid Sterba static struct btrfs_block_group *btrfs_create_block_group_cache(
22199afc6649SQu Wenruo 		struct btrfs_fs_info *fs_info, u64 start)
22204358d963SJosef Bacik {
222132da5386SDavid Sterba 	struct btrfs_block_group *cache;
22224358d963SJosef Bacik 
22234358d963SJosef Bacik 	cache = kzalloc(sizeof(*cache), GFP_NOFS);
22244358d963SJosef Bacik 	if (!cache)
22254358d963SJosef Bacik 		return NULL;
22264358d963SJosef Bacik 
22274358d963SJosef Bacik 	cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
22284358d963SJosef Bacik 					GFP_NOFS);
22294358d963SJosef Bacik 	if (!cache->free_space_ctl) {
22304358d963SJosef Bacik 		kfree(cache);
22314358d963SJosef Bacik 		return NULL;
22324358d963SJosef Bacik 	}
22334358d963SJosef Bacik 
2234b3470b5dSDavid Sterba 	cache->start = start;
22354358d963SJosef Bacik 
22364358d963SJosef Bacik 	cache->fs_info = fs_info;
22374358d963SJosef Bacik 	cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
22384358d963SJosef Bacik 
22396e80d4f8SDennis Zhou 	cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
22406e80d4f8SDennis Zhou 
224148aaeebeSJosef Bacik 	refcount_set(&cache->refs, 1);
22424358d963SJosef Bacik 	spin_lock_init(&cache->lock);
22434358d963SJosef Bacik 	init_rwsem(&cache->data_rwsem);
22444358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->list);
22454358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->cluster_list);
22464358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->bg_list);
22474358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->ro_list);
2248b0643e59SDennis Zhou 	INIT_LIST_HEAD(&cache->discard_list);
22494358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->dirty_list);
22504358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->io_list);
2251afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&cache->active_bg_list);
2252cd79909bSJosef Bacik 	btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
22536b7304afSFilipe Manana 	atomic_set(&cache->frozen, 0);
22544358d963SJosef Bacik 	mutex_init(&cache->free_space_lock);
22554358d963SJosef Bacik 
22564358d963SJosef Bacik 	return cache;
22574358d963SJosef Bacik }
22584358d963SJosef Bacik 
22594358d963SJosef Bacik /*
22604358d963SJosef Bacik  * Iterate all chunks and verify that each of them has the corresponding block
22614358d963SJosef Bacik  * group
22624358d963SJosef Bacik  */
check_chunk_block_group_mappings(struct btrfs_fs_info * fs_info)22634358d963SJosef Bacik static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
22644358d963SJosef Bacik {
22654358d963SJosef Bacik 	struct extent_map_tree *map_tree = &fs_info->mapping_tree;
22664358d963SJosef Bacik 	struct extent_map *em;
226732da5386SDavid Sterba 	struct btrfs_block_group *bg;
22684358d963SJosef Bacik 	u64 start = 0;
22694358d963SJosef Bacik 	int ret = 0;
22704358d963SJosef Bacik 
22714358d963SJosef Bacik 	while (1) {
22724358d963SJosef Bacik 		read_lock(&map_tree->lock);
22734358d963SJosef Bacik 		/*
22744358d963SJosef Bacik 		 * lookup_extent_mapping will return the first extent map
22754358d963SJosef Bacik 		 * intersecting the range, so setting @len to 1 is enough to
22764358d963SJosef Bacik 		 * get the first chunk.
22774358d963SJosef Bacik 		 */
22784358d963SJosef Bacik 		em = lookup_extent_mapping(map_tree, start, 1);
22794358d963SJosef Bacik 		read_unlock(&map_tree->lock);
22804358d963SJosef Bacik 		if (!em)
22814358d963SJosef Bacik 			break;
22824358d963SJosef Bacik 
22834358d963SJosef Bacik 		bg = btrfs_lookup_block_group(fs_info, em->start);
22844358d963SJosef Bacik 		if (!bg) {
22854358d963SJosef Bacik 			btrfs_err(fs_info,
22864358d963SJosef Bacik 	"chunk start=%llu len=%llu doesn't have corresponding block group",
22874358d963SJosef Bacik 				     em->start, em->len);
22884358d963SJosef Bacik 			ret = -EUCLEAN;
22894358d963SJosef Bacik 			free_extent_map(em);
22904358d963SJosef Bacik 			break;
22914358d963SJosef Bacik 		}
2292b3470b5dSDavid Sterba 		if (bg->start != em->start || bg->length != em->len ||
22934358d963SJosef Bacik 		    (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
22944358d963SJosef Bacik 		    (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
22954358d963SJosef Bacik 			btrfs_err(fs_info,
22964358d963SJosef Bacik "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
22974358d963SJosef Bacik 				em->start, em->len,
22984358d963SJosef Bacik 				em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
2299b3470b5dSDavid Sterba 				bg->start, bg->length,
23004358d963SJosef Bacik 				bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
23014358d963SJosef Bacik 			ret = -EUCLEAN;
23024358d963SJosef Bacik 			free_extent_map(em);
23034358d963SJosef Bacik 			btrfs_put_block_group(bg);
23044358d963SJosef Bacik 			break;
23054358d963SJosef Bacik 		}
23064358d963SJosef Bacik 		start = em->start + em->len;
23074358d963SJosef Bacik 		free_extent_map(em);
23084358d963SJosef Bacik 		btrfs_put_block_group(bg);
23094358d963SJosef Bacik 	}
23104358d963SJosef Bacik 	return ret;
23114358d963SJosef Bacik }
23124358d963SJosef Bacik 
read_one_block_group(struct btrfs_fs_info * info,struct btrfs_block_group_item * bgi,const struct btrfs_key * key,int need_clear)2313ffb9e0f0SQu Wenruo static int read_one_block_group(struct btrfs_fs_info *info,
23144afd2fe8SJohannes Thumshirn 				struct btrfs_block_group_item *bgi,
2315d49a2ddbSQu Wenruo 				const struct btrfs_key *key,
2316ffb9e0f0SQu Wenruo 				int need_clear)
2317ffb9e0f0SQu Wenruo {
231832da5386SDavid Sterba 	struct btrfs_block_group *cache;
2319ffb9e0f0SQu Wenruo 	const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
2320ffb9e0f0SQu Wenruo 	int ret;
2321ffb9e0f0SQu Wenruo 
2322d49a2ddbSQu Wenruo 	ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
2323ffb9e0f0SQu Wenruo 
23249afc6649SQu Wenruo 	cache = btrfs_create_block_group_cache(info, key->objectid);
2325ffb9e0f0SQu Wenruo 	if (!cache)
2326ffb9e0f0SQu Wenruo 		return -ENOMEM;
2327ffb9e0f0SQu Wenruo 
23284afd2fe8SJohannes Thumshirn 	cache->length = key->offset;
23294afd2fe8SJohannes Thumshirn 	cache->used = btrfs_stack_block_group_used(bgi);
23307248e0ceSQu Wenruo 	cache->commit_used = cache->used;
23314afd2fe8SJohannes Thumshirn 	cache->flags = btrfs_stack_block_group_flags(bgi);
2332f7238e50SJosef Bacik 	cache->global_root_id = btrfs_stack_block_group_chunk_objectid(bgi);
23339afc6649SQu Wenruo 
2334e3e39c72SMarcos Paulo de Souza 	set_free_space_tree_thresholds(cache);
2335e3e39c72SMarcos Paulo de Souza 
2336ffb9e0f0SQu Wenruo 	if (need_clear) {
2337ffb9e0f0SQu Wenruo 		/*
2338ffb9e0f0SQu Wenruo 		 * When we mount with old space cache, we need to
2339ffb9e0f0SQu Wenruo 		 * set BTRFS_DC_CLEAR and set dirty flag.
2340ffb9e0f0SQu Wenruo 		 *
2341ffb9e0f0SQu Wenruo 		 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
2342ffb9e0f0SQu Wenruo 		 *    truncate the old free space cache inode and
2343ffb9e0f0SQu Wenruo 		 *    setup a new one.
2344ffb9e0f0SQu Wenruo 		 * b) Setting 'dirty flag' makes sure that we flush
2345ffb9e0f0SQu Wenruo 		 *    the new space cache info onto disk.
2346ffb9e0f0SQu Wenruo 		 */
2347ffb9e0f0SQu Wenruo 		if (btrfs_test_opt(info, SPACE_CACHE))
2348ffb9e0f0SQu Wenruo 			cache->disk_cache_state = BTRFS_DC_CLEAR;
2349ffb9e0f0SQu Wenruo 	}
2350ffb9e0f0SQu Wenruo 	if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
2351ffb9e0f0SQu Wenruo 	    (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
2352ffb9e0f0SQu Wenruo 			btrfs_err(info,
2353ffb9e0f0SQu Wenruo "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2354ffb9e0f0SQu Wenruo 				  cache->start);
2355ffb9e0f0SQu Wenruo 			ret = -EINVAL;
2356ffb9e0f0SQu Wenruo 			goto error;
2357ffb9e0f0SQu Wenruo 	}
2358ffb9e0f0SQu Wenruo 
2359a94794d5SNaohiro Aota 	ret = btrfs_load_block_group_zone_info(cache, false);
236008e11a3dSNaohiro Aota 	if (ret) {
236108e11a3dSNaohiro Aota 		btrfs_err(info, "zoned: failed to load zone info of bg %llu",
236208e11a3dSNaohiro Aota 			  cache->start);
236308e11a3dSNaohiro Aota 		goto error;
236408e11a3dSNaohiro Aota 	}
236508e11a3dSNaohiro Aota 
2366ffb9e0f0SQu Wenruo 	/*
2367ffb9e0f0SQu Wenruo 	 * We need to exclude the super stripes now so that the space info has
2368ffb9e0f0SQu Wenruo 	 * super bytes accounted for, otherwise we'll think we have more space
2369ffb9e0f0SQu Wenruo 	 * than we actually do.
2370ffb9e0f0SQu Wenruo 	 */
2371ffb9e0f0SQu Wenruo 	ret = exclude_super_stripes(cache);
2372ffb9e0f0SQu Wenruo 	if (ret) {
2373ffb9e0f0SQu Wenruo 		/* We may have excluded something, so call this just in case. */
2374ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2375ffb9e0f0SQu Wenruo 		goto error;
2376ffb9e0f0SQu Wenruo 	}
2377ffb9e0f0SQu Wenruo 
2378ffb9e0f0SQu Wenruo 	/*
2379169e0da9SNaohiro Aota 	 * For zoned filesystem, space after the allocation offset is the only
2380169e0da9SNaohiro Aota 	 * free space for a block group. So, we don't need any caching work.
2381169e0da9SNaohiro Aota 	 * btrfs_calc_zone_unusable() will set the amount of free space and
2382169e0da9SNaohiro Aota 	 * zone_unusable space.
2383169e0da9SNaohiro Aota 	 *
2384169e0da9SNaohiro Aota 	 * For regular filesystem, check for two cases, either we are full, and
2385169e0da9SNaohiro Aota 	 * therefore don't need to bother with the caching work since we won't
2386169e0da9SNaohiro Aota 	 * find any space, or we are empty, and we can just add all the space
2387169e0da9SNaohiro Aota 	 * in and be done with it.  This saves us _a_lot_ of time, particularly
2388169e0da9SNaohiro Aota 	 * in the full case.
2389ffb9e0f0SQu Wenruo 	 */
2390169e0da9SNaohiro Aota 	if (btrfs_is_zoned(info)) {
2391169e0da9SNaohiro Aota 		btrfs_calc_zone_unusable(cache);
2392c46c4247SNaohiro Aota 		/* Should not have any excluded extents. Just in case, though. */
2393c46c4247SNaohiro Aota 		btrfs_free_excluded_extents(cache);
2394169e0da9SNaohiro Aota 	} else if (cache->length == cache->used) {
2395ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
2396ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2397ffb9e0f0SQu Wenruo 	} else if (cache->used == 0) {
2398ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
23993b9f0995SFilipe Manana 		ret = btrfs_add_new_free_space(cache, cache->start,
2400d8ccbd21SFilipe Manana 					       cache->start + cache->length, NULL);
2401ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2402d8ccbd21SFilipe Manana 		if (ret)
2403d8ccbd21SFilipe Manana 			goto error;
2404ffb9e0f0SQu Wenruo 	}
2405ffb9e0f0SQu Wenruo 
2406ffb9e0f0SQu Wenruo 	ret = btrfs_add_block_group_cache(info, cache);
2407ffb9e0f0SQu Wenruo 	if (ret) {
2408ffb9e0f0SQu Wenruo 		btrfs_remove_free_space_cache(cache);
2409ffb9e0f0SQu Wenruo 		goto error;
2410ffb9e0f0SQu Wenruo 	}
2411ffb9e0f0SQu Wenruo 	trace_btrfs_add_block_group(info, cache, 0);
2412723de71dSJosef Bacik 	btrfs_add_bg_to_space_info(info, cache);
2413ffb9e0f0SQu Wenruo 
2414ffb9e0f0SQu Wenruo 	set_avail_alloc_bits(info, cache->flags);
2415a09f23c3SAnand Jain 	if (btrfs_chunk_writeable(info, cache->start)) {
2416a09f23c3SAnand Jain 		if (cache->used == 0) {
2417ffb9e0f0SQu Wenruo 			ASSERT(list_empty(&cache->bg_list));
24186e80d4f8SDennis Zhou 			if (btrfs_test_opt(info, DISCARD_ASYNC))
24196e80d4f8SDennis Zhou 				btrfs_discard_queue_work(&info->discard_ctl, cache);
24206e80d4f8SDennis Zhou 			else
2421ffb9e0f0SQu Wenruo 				btrfs_mark_bg_unused(cache);
2422ffb9e0f0SQu Wenruo 		}
2423a09f23c3SAnand Jain 	} else {
2424a09f23c3SAnand Jain 		inc_block_group_ro(cache, 1);
2425a09f23c3SAnand Jain 	}
2426a09f23c3SAnand Jain 
2427ffb9e0f0SQu Wenruo 	return 0;
2428ffb9e0f0SQu Wenruo error:
2429ffb9e0f0SQu Wenruo 	btrfs_put_block_group(cache);
2430ffb9e0f0SQu Wenruo 	return ret;
2431ffb9e0f0SQu Wenruo }
2432ffb9e0f0SQu Wenruo 
fill_dummy_bgs(struct btrfs_fs_info * fs_info)243342437a63SJosef Bacik static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
243442437a63SJosef Bacik {
243542437a63SJosef Bacik 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
243642437a63SJosef Bacik 	struct rb_node *node;
243742437a63SJosef Bacik 	int ret = 0;
243842437a63SJosef Bacik 
243942437a63SJosef Bacik 	for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
244042437a63SJosef Bacik 		struct extent_map *em;
244142437a63SJosef Bacik 		struct map_lookup *map;
244242437a63SJosef Bacik 		struct btrfs_block_group *bg;
244342437a63SJosef Bacik 
244442437a63SJosef Bacik 		em = rb_entry(node, struct extent_map, rb_node);
244542437a63SJosef Bacik 		map = em->map_lookup;
244642437a63SJosef Bacik 		bg = btrfs_create_block_group_cache(fs_info, em->start);
244742437a63SJosef Bacik 		if (!bg) {
244842437a63SJosef Bacik 			ret = -ENOMEM;
244942437a63SJosef Bacik 			break;
245042437a63SJosef Bacik 		}
245142437a63SJosef Bacik 
245242437a63SJosef Bacik 		/* Fill dummy cache as FULL */
245342437a63SJosef Bacik 		bg->length = em->len;
245442437a63SJosef Bacik 		bg->flags = map->type;
245542437a63SJosef Bacik 		bg->cached = BTRFS_CACHE_FINISHED;
245642437a63SJosef Bacik 		bg->used = em->len;
245742437a63SJosef Bacik 		bg->flags = map->type;
245842437a63SJosef Bacik 		ret = btrfs_add_block_group_cache(fs_info, bg);
24592b29726cSQu Wenruo 		/*
24602b29726cSQu Wenruo 		 * We may have some valid block group cache added already, in
24612b29726cSQu Wenruo 		 * that case we skip to the next one.
24622b29726cSQu Wenruo 		 */
24632b29726cSQu Wenruo 		if (ret == -EEXIST) {
24642b29726cSQu Wenruo 			ret = 0;
24652b29726cSQu Wenruo 			btrfs_put_block_group(bg);
24662b29726cSQu Wenruo 			continue;
24672b29726cSQu Wenruo 		}
24682b29726cSQu Wenruo 
246942437a63SJosef Bacik 		if (ret) {
247042437a63SJosef Bacik 			btrfs_remove_free_space_cache(bg);
247142437a63SJosef Bacik 			btrfs_put_block_group(bg);
247242437a63SJosef Bacik 			break;
247342437a63SJosef Bacik 		}
24742b29726cSQu Wenruo 
2475723de71dSJosef Bacik 		btrfs_add_bg_to_space_info(fs_info, bg);
247642437a63SJosef Bacik 
247742437a63SJosef Bacik 		set_avail_alloc_bits(fs_info, bg->flags);
247842437a63SJosef Bacik 	}
247942437a63SJosef Bacik 	if (!ret)
248042437a63SJosef Bacik 		btrfs_init_global_block_rsv(fs_info);
248142437a63SJosef Bacik 	return ret;
248242437a63SJosef Bacik }
248342437a63SJosef Bacik 
btrfs_read_block_groups(struct btrfs_fs_info * info)24844358d963SJosef Bacik int btrfs_read_block_groups(struct btrfs_fs_info *info)
24854358d963SJosef Bacik {
2486dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(info);
24874358d963SJosef Bacik 	struct btrfs_path *path;
24884358d963SJosef Bacik 	int ret;
248932da5386SDavid Sterba 	struct btrfs_block_group *cache;
24904358d963SJosef Bacik 	struct btrfs_space_info *space_info;
24914358d963SJosef Bacik 	struct btrfs_key key;
24924358d963SJosef Bacik 	int need_clear = 0;
24934358d963SJosef Bacik 	u64 cache_gen;
24944358d963SJosef Bacik 
249581d5d614SQu Wenruo 	/*
249681d5d614SQu Wenruo 	 * Either no extent root (with ibadroots rescue option) or we have
249781d5d614SQu Wenruo 	 * unsupported RO options. The fs can never be mounted read-write, so no
249881d5d614SQu Wenruo 	 * need to waste time searching block group items.
249981d5d614SQu Wenruo 	 *
250081d5d614SQu Wenruo 	 * This also allows new extent tree related changes to be RO compat,
250181d5d614SQu Wenruo 	 * no need for a full incompat flag.
250281d5d614SQu Wenruo 	 */
250381d5d614SQu Wenruo 	if (!root || (btrfs_super_compat_ro_flags(info->super_copy) &
250481d5d614SQu Wenruo 		      ~BTRFS_FEATURE_COMPAT_RO_SUPP))
250542437a63SJosef Bacik 		return fill_dummy_bgs(info);
250642437a63SJosef Bacik 
25074358d963SJosef Bacik 	key.objectid = 0;
25084358d963SJosef Bacik 	key.offset = 0;
25094358d963SJosef Bacik 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
25104358d963SJosef Bacik 	path = btrfs_alloc_path();
25114358d963SJosef Bacik 	if (!path)
25124358d963SJosef Bacik 		return -ENOMEM;
25134358d963SJosef Bacik 
25144358d963SJosef Bacik 	cache_gen = btrfs_super_cache_generation(info->super_copy);
25154358d963SJosef Bacik 	if (btrfs_test_opt(info, SPACE_CACHE) &&
25164358d963SJosef Bacik 	    btrfs_super_generation(info->super_copy) != cache_gen)
25174358d963SJosef Bacik 		need_clear = 1;
25184358d963SJosef Bacik 	if (btrfs_test_opt(info, CLEAR_CACHE))
25194358d963SJosef Bacik 		need_clear = 1;
25204358d963SJosef Bacik 
25214358d963SJosef Bacik 	while (1) {
25224afd2fe8SJohannes Thumshirn 		struct btrfs_block_group_item bgi;
25234afd2fe8SJohannes Thumshirn 		struct extent_buffer *leaf;
25244afd2fe8SJohannes Thumshirn 		int slot;
25254afd2fe8SJohannes Thumshirn 
25264358d963SJosef Bacik 		ret = find_first_block_group(info, path, &key);
25274358d963SJosef Bacik 		if (ret > 0)
25284358d963SJosef Bacik 			break;
25294358d963SJosef Bacik 		if (ret != 0)
25304358d963SJosef Bacik 			goto error;
25314358d963SJosef Bacik 
25324afd2fe8SJohannes Thumshirn 		leaf = path->nodes[0];
25334afd2fe8SJohannes Thumshirn 		slot = path->slots[0];
25344afd2fe8SJohannes Thumshirn 
25354afd2fe8SJohannes Thumshirn 		read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
25364afd2fe8SJohannes Thumshirn 				   sizeof(bgi));
25374afd2fe8SJohannes Thumshirn 
25384afd2fe8SJohannes Thumshirn 		btrfs_item_key_to_cpu(leaf, &key, slot);
25394afd2fe8SJohannes Thumshirn 		btrfs_release_path(path);
25404afd2fe8SJohannes Thumshirn 		ret = read_one_block_group(info, &bgi, &key, need_clear);
2541ffb9e0f0SQu Wenruo 		if (ret < 0)
25424358d963SJosef Bacik 			goto error;
2543ffb9e0f0SQu Wenruo 		key.objectid += key.offset;
2544ffb9e0f0SQu Wenruo 		key.offset = 0;
25454358d963SJosef Bacik 	}
25467837fa88SJosef Bacik 	btrfs_release_path(path);
25474358d963SJosef Bacik 
254872804905SJosef Bacik 	list_for_each_entry(space_info, &info->space_info, list) {
254949ea112dSJosef Bacik 		int i;
255049ea112dSJosef Bacik 
255149ea112dSJosef Bacik 		for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
255249ea112dSJosef Bacik 			if (list_empty(&space_info->block_groups[i]))
255349ea112dSJosef Bacik 				continue;
255449ea112dSJosef Bacik 			cache = list_first_entry(&space_info->block_groups[i],
255549ea112dSJosef Bacik 						 struct btrfs_block_group,
255649ea112dSJosef Bacik 						 list);
255749ea112dSJosef Bacik 			btrfs_sysfs_add_block_group_type(cache);
255849ea112dSJosef Bacik 		}
255949ea112dSJosef Bacik 
25604358d963SJosef Bacik 		if (!(btrfs_get_alloc_profile(info, space_info->flags) &
25614358d963SJosef Bacik 		      (BTRFS_BLOCK_GROUP_RAID10 |
25624358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID1_MASK |
25634358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID56_MASK |
25644358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_DUP)))
25654358d963SJosef Bacik 			continue;
25664358d963SJosef Bacik 		/*
25674358d963SJosef Bacik 		 * Avoid allocating from un-mirrored block group if there are
25684358d963SJosef Bacik 		 * mirrored block groups.
25694358d963SJosef Bacik 		 */
25704358d963SJosef Bacik 		list_for_each_entry(cache,
25714358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_RAID0],
25724358d963SJosef Bacik 				list)
2573e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
25744358d963SJosef Bacik 		list_for_each_entry(cache,
25754358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_SINGLE],
25764358d963SJosef Bacik 				list)
2577e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
25784358d963SJosef Bacik 	}
25794358d963SJosef Bacik 
25804358d963SJosef Bacik 	btrfs_init_global_block_rsv(info);
25814358d963SJosef Bacik 	ret = check_chunk_block_group_mappings(info);
25824358d963SJosef Bacik error:
25834358d963SJosef Bacik 	btrfs_free_path(path);
25842b29726cSQu Wenruo 	/*
25852b29726cSQu Wenruo 	 * We've hit some error while reading the extent tree, and have
25862b29726cSQu Wenruo 	 * rescue=ibadroots mount option.
25872b29726cSQu Wenruo 	 * Try to fill the tree using dummy block groups so that the user can
25882b29726cSQu Wenruo 	 * continue to mount and grab their data.
25892b29726cSQu Wenruo 	 */
25902b29726cSQu Wenruo 	if (ret && btrfs_test_opt(info, IGNOREBADROOTS))
25912b29726cSQu Wenruo 		ret = fill_dummy_bgs(info);
25924358d963SJosef Bacik 	return ret;
25934358d963SJosef Bacik }
25944358d963SJosef Bacik 
259579bd3712SFilipe Manana /*
259679bd3712SFilipe Manana  * This function, insert_block_group_item(), belongs to the phase 2 of chunk
259779bd3712SFilipe Manana  * allocation.
259879bd3712SFilipe Manana  *
259979bd3712SFilipe Manana  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
260079bd3712SFilipe Manana  * phases.
260179bd3712SFilipe Manana  */
insert_block_group_item(struct btrfs_trans_handle * trans,struct btrfs_block_group * block_group)260297f4728aSQu Wenruo static int insert_block_group_item(struct btrfs_trans_handle *trans,
260397f4728aSQu Wenruo 				   struct btrfs_block_group *block_group)
260497f4728aSQu Wenruo {
260597f4728aSQu Wenruo 	struct btrfs_fs_info *fs_info = trans->fs_info;
260697f4728aSQu Wenruo 	struct btrfs_block_group_item bgi;
2607dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
260897f4728aSQu Wenruo 	struct btrfs_key key;
2609675dfe12SFilipe Manana 	u64 old_commit_used;
2610675dfe12SFilipe Manana 	int ret;
261197f4728aSQu Wenruo 
261297f4728aSQu Wenruo 	spin_lock(&block_group->lock);
261397f4728aSQu Wenruo 	btrfs_set_stack_block_group_used(&bgi, block_group->used);
261497f4728aSQu Wenruo 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
2615f7238e50SJosef Bacik 						   block_group->global_root_id);
261697f4728aSQu Wenruo 	btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2617675dfe12SFilipe Manana 	old_commit_used = block_group->commit_used;
2618675dfe12SFilipe Manana 	block_group->commit_used = block_group->used;
261997f4728aSQu Wenruo 	key.objectid = block_group->start;
262097f4728aSQu Wenruo 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
262197f4728aSQu Wenruo 	key.offset = block_group->length;
262297f4728aSQu Wenruo 	spin_unlock(&block_group->lock);
262397f4728aSQu Wenruo 
2624675dfe12SFilipe Manana 	ret = btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2625675dfe12SFilipe Manana 	if (ret < 0) {
2626675dfe12SFilipe Manana 		spin_lock(&block_group->lock);
2627675dfe12SFilipe Manana 		block_group->commit_used = old_commit_used;
2628675dfe12SFilipe Manana 		spin_unlock(&block_group->lock);
2629675dfe12SFilipe Manana 	}
2630675dfe12SFilipe Manana 
2631675dfe12SFilipe Manana 	return ret;
263297f4728aSQu Wenruo }
263397f4728aSQu Wenruo 
insert_dev_extent(struct btrfs_trans_handle * trans,struct btrfs_device * device,u64 chunk_offset,u64 start,u64 num_bytes)26342eadb9e7SNikolay Borisov static int insert_dev_extent(struct btrfs_trans_handle *trans,
26352eadb9e7SNikolay Borisov 			    struct btrfs_device *device, u64 chunk_offset,
26362eadb9e7SNikolay Borisov 			    u64 start, u64 num_bytes)
26372eadb9e7SNikolay Borisov {
26382eadb9e7SNikolay Borisov 	struct btrfs_fs_info *fs_info = device->fs_info;
26392eadb9e7SNikolay Borisov 	struct btrfs_root *root = fs_info->dev_root;
26402eadb9e7SNikolay Borisov 	struct btrfs_path *path;
26412eadb9e7SNikolay Borisov 	struct btrfs_dev_extent *extent;
26422eadb9e7SNikolay Borisov 	struct extent_buffer *leaf;
26432eadb9e7SNikolay Borisov 	struct btrfs_key key;
26442eadb9e7SNikolay Borisov 	int ret;
26452eadb9e7SNikolay Borisov 
26462eadb9e7SNikolay Borisov 	WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
26472eadb9e7SNikolay Borisov 	WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
26482eadb9e7SNikolay Borisov 	path = btrfs_alloc_path();
26492eadb9e7SNikolay Borisov 	if (!path)
26502eadb9e7SNikolay Borisov 		return -ENOMEM;
26512eadb9e7SNikolay Borisov 
26522eadb9e7SNikolay Borisov 	key.objectid = device->devid;
26532eadb9e7SNikolay Borisov 	key.type = BTRFS_DEV_EXTENT_KEY;
26542eadb9e7SNikolay Borisov 	key.offset = start;
26552eadb9e7SNikolay Borisov 	ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent));
26562eadb9e7SNikolay Borisov 	if (ret)
26572eadb9e7SNikolay Borisov 		goto out;
26582eadb9e7SNikolay Borisov 
26592eadb9e7SNikolay Borisov 	leaf = path->nodes[0];
26602eadb9e7SNikolay Borisov 	extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
26612eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID);
26622eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_objectid(leaf, extent,
26632eadb9e7SNikolay Borisov 					    BTRFS_FIRST_CHUNK_TREE_OBJECTID);
26642eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
26652eadb9e7SNikolay Borisov 
26662eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_length(leaf, extent, num_bytes);
2667d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, leaf);
26682eadb9e7SNikolay Borisov out:
26692eadb9e7SNikolay Borisov 	btrfs_free_path(path);
26702eadb9e7SNikolay Borisov 	return ret;
26712eadb9e7SNikolay Borisov }
26722eadb9e7SNikolay Borisov 
26732eadb9e7SNikolay Borisov /*
26742eadb9e7SNikolay Borisov  * This function belongs to phase 2.
26752eadb9e7SNikolay Borisov  *
26762eadb9e7SNikolay Borisov  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
26772eadb9e7SNikolay Borisov  * phases.
26782eadb9e7SNikolay Borisov  */
insert_dev_extents(struct btrfs_trans_handle * trans,u64 chunk_offset,u64 chunk_size)26792eadb9e7SNikolay Borisov static int insert_dev_extents(struct btrfs_trans_handle *trans,
26802eadb9e7SNikolay Borisov 				   u64 chunk_offset, u64 chunk_size)
26812eadb9e7SNikolay Borisov {
26822eadb9e7SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
26832eadb9e7SNikolay Borisov 	struct btrfs_device *device;
26842eadb9e7SNikolay Borisov 	struct extent_map *em;
26852eadb9e7SNikolay Borisov 	struct map_lookup *map;
26862eadb9e7SNikolay Borisov 	u64 dev_offset;
26872eadb9e7SNikolay Borisov 	u64 stripe_size;
26882eadb9e7SNikolay Borisov 	int i;
26892eadb9e7SNikolay Borisov 	int ret = 0;
26902eadb9e7SNikolay Borisov 
26912eadb9e7SNikolay Borisov 	em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
26922eadb9e7SNikolay Borisov 	if (IS_ERR(em))
26932eadb9e7SNikolay Borisov 		return PTR_ERR(em);
26942eadb9e7SNikolay Borisov 
26952eadb9e7SNikolay Borisov 	map = em->map_lookup;
26962eadb9e7SNikolay Borisov 	stripe_size = em->orig_block_len;
26972eadb9e7SNikolay Borisov 
26982eadb9e7SNikolay Borisov 	/*
26992eadb9e7SNikolay Borisov 	 * Take the device list mutex to prevent races with the final phase of
27002eadb9e7SNikolay Borisov 	 * a device replace operation that replaces the device object associated
27012eadb9e7SNikolay Borisov 	 * with the map's stripes, because the device object's id can change
27022eadb9e7SNikolay Borisov 	 * at any time during that final phase of the device replace operation
27032eadb9e7SNikolay Borisov 	 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
27042eadb9e7SNikolay Borisov 	 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
27052eadb9e7SNikolay Borisov 	 * resulting in persisting a device extent item with such ID.
27062eadb9e7SNikolay Borisov 	 */
27072eadb9e7SNikolay Borisov 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
27082eadb9e7SNikolay Borisov 	for (i = 0; i < map->num_stripes; i++) {
27092eadb9e7SNikolay Borisov 		device = map->stripes[i].dev;
27102eadb9e7SNikolay Borisov 		dev_offset = map->stripes[i].physical;
27112eadb9e7SNikolay Borisov 
27122eadb9e7SNikolay Borisov 		ret = insert_dev_extent(trans, device, chunk_offset, dev_offset,
27132eadb9e7SNikolay Borisov 				       stripe_size);
27142eadb9e7SNikolay Borisov 		if (ret)
27152eadb9e7SNikolay Borisov 			break;
27162eadb9e7SNikolay Borisov 	}
27172eadb9e7SNikolay Borisov 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
27182eadb9e7SNikolay Borisov 
27192eadb9e7SNikolay Borisov 	free_extent_map(em);
27202eadb9e7SNikolay Borisov 	return ret;
27212eadb9e7SNikolay Borisov }
27222eadb9e7SNikolay Borisov 
272379bd3712SFilipe Manana /*
272479bd3712SFilipe Manana  * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
272579bd3712SFilipe Manana  * chunk allocation.
272679bd3712SFilipe Manana  *
272779bd3712SFilipe Manana  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
272879bd3712SFilipe Manana  * phases.
272979bd3712SFilipe Manana  */
btrfs_create_pending_block_groups(struct btrfs_trans_handle * trans)27304358d963SJosef Bacik void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
27314358d963SJosef Bacik {
27324358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
273332da5386SDavid Sterba 	struct btrfs_block_group *block_group;
27344358d963SJosef Bacik 	int ret = 0;
27354358d963SJosef Bacik 
27364358d963SJosef Bacik 	while (!list_empty(&trans->new_bgs)) {
273749ea112dSJosef Bacik 		int index;
273849ea112dSJosef Bacik 
27394358d963SJosef Bacik 		block_group = list_first_entry(&trans->new_bgs,
274032da5386SDavid Sterba 					       struct btrfs_block_group,
27414358d963SJosef Bacik 					       bg_list);
27424358d963SJosef Bacik 		if (ret)
27434358d963SJosef Bacik 			goto next;
27444358d963SJosef Bacik 
274549ea112dSJosef Bacik 		index = btrfs_bg_flags_to_raid_index(block_group->flags);
274649ea112dSJosef Bacik 
274797f4728aSQu Wenruo 		ret = insert_block_group_item(trans, block_group);
27484358d963SJosef Bacik 		if (ret)
27494358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
27503349b57fSJosef Bacik 		if (!test_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED,
27513349b57fSJosef Bacik 			      &block_group->runtime_flags)) {
275279bd3712SFilipe Manana 			mutex_lock(&fs_info->chunk_mutex);
275379bd3712SFilipe Manana 			ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group);
275479bd3712SFilipe Manana 			mutex_unlock(&fs_info->chunk_mutex);
275579bd3712SFilipe Manana 			if (ret)
275679bd3712SFilipe Manana 				btrfs_abort_transaction(trans, ret);
275779bd3712SFilipe Manana 		}
27582eadb9e7SNikolay Borisov 		ret = insert_dev_extents(trans, block_group->start,
275997f4728aSQu Wenruo 					 block_group->length);
27604358d963SJosef Bacik 		if (ret)
27614358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
27624358d963SJosef Bacik 		add_block_group_free_space(trans, block_group);
276349ea112dSJosef Bacik 
276449ea112dSJosef Bacik 		/*
276549ea112dSJosef Bacik 		 * If we restriped during balance, we may have added a new raid
276649ea112dSJosef Bacik 		 * type, so now add the sysfs entries when it is safe to do so.
276749ea112dSJosef Bacik 		 * We don't have to worry about locking here as it's handled in
276849ea112dSJosef Bacik 		 * btrfs_sysfs_add_block_group_type.
276949ea112dSJosef Bacik 		 */
277049ea112dSJosef Bacik 		if (block_group->space_info->block_group_kobjs[index] == NULL)
277149ea112dSJosef Bacik 			btrfs_sysfs_add_block_group_type(block_group);
277249ea112dSJosef Bacik 
27734358d963SJosef Bacik 		/* Already aborted the transaction if it failed. */
27744358d963SJosef Bacik next:
27754358d963SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
27764358d963SJosef Bacik 		list_del_init(&block_group->bg_list);
27770657b20cSFilipe Manana 		clear_bit(BLOCK_GROUP_FLAG_NEW, &block_group->runtime_flags);
27784358d963SJosef Bacik 	}
27794358d963SJosef Bacik 	btrfs_trans_release_chunk_metadata(trans);
27804358d963SJosef Bacik }
27814358d963SJosef Bacik 
2782f7238e50SJosef Bacik /*
2783f7238e50SJosef Bacik  * For extent tree v2 we use the block_group_item->chunk_offset to point at our
2784f7238e50SJosef Bacik  * global root id.  For v1 it's always set to BTRFS_FIRST_CHUNK_TREE_OBJECTID.
2785f7238e50SJosef Bacik  */
calculate_global_root_id(struct btrfs_fs_info * fs_info,u64 offset)2786f7238e50SJosef Bacik static u64 calculate_global_root_id(struct btrfs_fs_info *fs_info, u64 offset)
2787f7238e50SJosef Bacik {
2788f7238e50SJosef Bacik 	u64 div = SZ_1G;
2789f7238e50SJosef Bacik 	u64 index;
2790f7238e50SJosef Bacik 
2791f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2792f7238e50SJosef Bacik 		return BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2793f7238e50SJosef Bacik 
2794f7238e50SJosef Bacik 	/* If we have a smaller fs index based on 128MiB. */
2795f7238e50SJosef Bacik 	if (btrfs_super_total_bytes(fs_info->super_copy) <= (SZ_1G * 10ULL))
2796f7238e50SJosef Bacik 		div = SZ_128M;
2797f7238e50SJosef Bacik 
2798f7238e50SJosef Bacik 	offset = div64_u64(offset, div);
2799f7238e50SJosef Bacik 	div64_u64_rem(offset, fs_info->nr_global_roots, &index);
2800f7238e50SJosef Bacik 	return index;
2801f7238e50SJosef Bacik }
2802f7238e50SJosef Bacik 
btrfs_make_block_group(struct btrfs_trans_handle * trans,u64 type,u64 chunk_offset,u64 size)280379bd3712SFilipe Manana struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
28045758d1bdSFilipe Manana 						 u64 type,
280579bd3712SFilipe Manana 						 u64 chunk_offset, u64 size)
28064358d963SJosef Bacik {
28074358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
280832da5386SDavid Sterba 	struct btrfs_block_group *cache;
28094358d963SJosef Bacik 	int ret;
28104358d963SJosef Bacik 
28114358d963SJosef Bacik 	btrfs_set_log_full_commit(trans);
28124358d963SJosef Bacik 
28139afc6649SQu Wenruo 	cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
28144358d963SJosef Bacik 	if (!cache)
281579bd3712SFilipe Manana 		return ERR_PTR(-ENOMEM);
28164358d963SJosef Bacik 
28170657b20cSFilipe Manana 	/*
28180657b20cSFilipe Manana 	 * Mark it as new before adding it to the rbtree of block groups or any
28190657b20cSFilipe Manana 	 * list, so that no other task finds it and calls btrfs_mark_bg_unused()
28200657b20cSFilipe Manana 	 * before the new flag is set.
28210657b20cSFilipe Manana 	 */
28220657b20cSFilipe Manana 	set_bit(BLOCK_GROUP_FLAG_NEW, &cache->runtime_flags);
28230657b20cSFilipe Manana 
28249afc6649SQu Wenruo 	cache->length = size;
2825e3e39c72SMarcos Paulo de Souza 	set_free_space_tree_thresholds(cache);
28264358d963SJosef Bacik 	cache->flags = type;
28274358d963SJosef Bacik 	cache->cached = BTRFS_CACHE_FINISHED;
2828f7238e50SJosef Bacik 	cache->global_root_id = calculate_global_root_id(fs_info, cache->start);
2829f7238e50SJosef Bacik 
2830997e3e2eSBoris Burkov 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
28310d7764ffSDavid Sterba 		set_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE, &cache->runtime_flags);
283208e11a3dSNaohiro Aota 
2833a94794d5SNaohiro Aota 	ret = btrfs_load_block_group_zone_info(cache, true);
283408e11a3dSNaohiro Aota 	if (ret) {
283508e11a3dSNaohiro Aota 		btrfs_put_block_group(cache);
283679bd3712SFilipe Manana 		return ERR_PTR(ret);
283708e11a3dSNaohiro Aota 	}
283808e11a3dSNaohiro Aota 
28394358d963SJosef Bacik 	ret = exclude_super_stripes(cache);
28404358d963SJosef Bacik 	if (ret) {
28414358d963SJosef Bacik 		/* We may have excluded something, so call this just in case */
28424358d963SJosef Bacik 		btrfs_free_excluded_extents(cache);
28434358d963SJosef Bacik 		btrfs_put_block_group(cache);
284479bd3712SFilipe Manana 		return ERR_PTR(ret);
28454358d963SJosef Bacik 	}
28464358d963SJosef Bacik 
28473b9f0995SFilipe Manana 	ret = btrfs_add_new_free_space(cache, chunk_offset, chunk_offset + size, NULL);
28484358d963SJosef Bacik 	btrfs_free_excluded_extents(cache);
2849d8ccbd21SFilipe Manana 	if (ret) {
2850d8ccbd21SFilipe Manana 		btrfs_put_block_group(cache);
2851d8ccbd21SFilipe Manana 		return ERR_PTR(ret);
2852d8ccbd21SFilipe Manana 	}
28534358d963SJosef Bacik 
28544358d963SJosef Bacik 	/*
28554358d963SJosef Bacik 	 * Ensure the corresponding space_info object is created and
28564358d963SJosef Bacik 	 * assigned to our block group. We want our bg to be added to the rbtree
28574358d963SJosef Bacik 	 * with its ->space_info set.
28584358d963SJosef Bacik 	 */
28594358d963SJosef Bacik 	cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
28604358d963SJosef Bacik 	ASSERT(cache->space_info);
28614358d963SJosef Bacik 
28624358d963SJosef Bacik 	ret = btrfs_add_block_group_cache(fs_info, cache);
28634358d963SJosef Bacik 	if (ret) {
28644358d963SJosef Bacik 		btrfs_remove_free_space_cache(cache);
28654358d963SJosef Bacik 		btrfs_put_block_group(cache);
286679bd3712SFilipe Manana 		return ERR_PTR(ret);
28674358d963SJosef Bacik 	}
28684358d963SJosef Bacik 
28694358d963SJosef Bacik 	/*
28704358d963SJosef Bacik 	 * Now that our block group has its ->space_info set and is inserted in
28714358d963SJosef Bacik 	 * the rbtree, update the space info's counters.
28724358d963SJosef Bacik 	 */
28734358d963SJosef Bacik 	trace_btrfs_add_block_group(fs_info, cache, 1);
2874723de71dSJosef Bacik 	btrfs_add_bg_to_space_info(fs_info, cache);
28754358d963SJosef Bacik 	btrfs_update_global_block_rsv(fs_info);
28764358d963SJosef Bacik 
28779d4b0a12SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
28789d4b0a12SJosef Bacik 	if (btrfs_should_fragment_free_space(cache)) {
28795758d1bdSFilipe Manana 		cache->space_info->bytes_used += size >> 1;
28809d4b0a12SJosef Bacik 		fragment_free_space(cache);
28819d4b0a12SJosef Bacik 	}
28829d4b0a12SJosef Bacik #endif
28834358d963SJosef Bacik 
28844358d963SJosef Bacik 	list_add_tail(&cache->bg_list, &trans->new_bgs);
28854358d963SJosef Bacik 	trans->delayed_ref_updates++;
28864358d963SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
28874358d963SJosef Bacik 
28884358d963SJosef Bacik 	set_avail_alloc_bits(fs_info, type);
288979bd3712SFilipe Manana 	return cache;
28904358d963SJosef Bacik }
289126ce2095SJosef Bacik 
2892b12de528SQu Wenruo /*
2893b12de528SQu Wenruo  * Mark one block group RO, can be called several times for the same block
2894b12de528SQu Wenruo  * group.
2895b12de528SQu Wenruo  *
2896b12de528SQu Wenruo  * @cache:		the destination block group
2897b12de528SQu Wenruo  * @do_chunk_alloc:	whether need to do chunk pre-allocation, this is to
2898b12de528SQu Wenruo  * 			ensure we still have some free space after marking this
2899b12de528SQu Wenruo  * 			block group RO.
2900b12de528SQu Wenruo  */
btrfs_inc_block_group_ro(struct btrfs_block_group * cache,bool do_chunk_alloc)2901b12de528SQu Wenruo int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2902b12de528SQu Wenruo 			     bool do_chunk_alloc)
290326ce2095SJosef Bacik {
290426ce2095SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
290526ce2095SJosef Bacik 	struct btrfs_trans_handle *trans;
2906dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
290726ce2095SJosef Bacik 	u64 alloc_flags;
290826ce2095SJosef Bacik 	int ret;
2909b6e9f16cSNikolay Borisov 	bool dirty_bg_running;
291026ce2095SJosef Bacik 
29112d192fc4SQu Wenruo 	/*
29122d192fc4SQu Wenruo 	 * This can only happen when we are doing read-only scrub on read-only
29132d192fc4SQu Wenruo 	 * mount.
29142d192fc4SQu Wenruo 	 * In that case we should not start a new transaction on read-only fs.
29152d192fc4SQu Wenruo 	 * Thus here we skip all chunk allocations.
29162d192fc4SQu Wenruo 	 */
29172d192fc4SQu Wenruo 	if (sb_rdonly(fs_info->sb)) {
29182d192fc4SQu Wenruo 		mutex_lock(&fs_info->ro_block_group_mutex);
29192d192fc4SQu Wenruo 		ret = inc_block_group_ro(cache, 0);
29202d192fc4SQu Wenruo 		mutex_unlock(&fs_info->ro_block_group_mutex);
29212d192fc4SQu Wenruo 		return ret;
29222d192fc4SQu Wenruo 	}
29232d192fc4SQu Wenruo 
2924b6e9f16cSNikolay Borisov 	do {
2925dfe8aec4SJosef Bacik 		trans = btrfs_join_transaction(root);
292626ce2095SJosef Bacik 		if (IS_ERR(trans))
292726ce2095SJosef Bacik 			return PTR_ERR(trans);
292826ce2095SJosef Bacik 
2929b6e9f16cSNikolay Borisov 		dirty_bg_running = false;
2930b6e9f16cSNikolay Borisov 
293126ce2095SJosef Bacik 		/*
2932b6e9f16cSNikolay Borisov 		 * We're not allowed to set block groups readonly after the dirty
2933b6e9f16cSNikolay Borisov 		 * block group cache has started writing.  If it already started,
2934b6e9f16cSNikolay Borisov 		 * back off and let this transaction commit.
293526ce2095SJosef Bacik 		 */
293626ce2095SJosef Bacik 		mutex_lock(&fs_info->ro_block_group_mutex);
293726ce2095SJosef Bacik 		if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
293826ce2095SJosef Bacik 			u64 transid = trans->transid;
293926ce2095SJosef Bacik 
294026ce2095SJosef Bacik 			mutex_unlock(&fs_info->ro_block_group_mutex);
294126ce2095SJosef Bacik 			btrfs_end_transaction(trans);
294226ce2095SJosef Bacik 
294326ce2095SJosef Bacik 			ret = btrfs_wait_for_commit(fs_info, transid);
294426ce2095SJosef Bacik 			if (ret)
294526ce2095SJosef Bacik 				return ret;
2946b6e9f16cSNikolay Borisov 			dirty_bg_running = true;
294726ce2095SJosef Bacik 		}
2948b6e9f16cSNikolay Borisov 	} while (dirty_bg_running);
294926ce2095SJosef Bacik 
2950b12de528SQu Wenruo 	if (do_chunk_alloc) {
295126ce2095SJosef Bacik 		/*
2952b12de528SQu Wenruo 		 * If we are changing raid levels, try to allocate a
2953b12de528SQu Wenruo 		 * corresponding block group with the new raid level.
295426ce2095SJosef Bacik 		 */
2955349e120eSJosef Bacik 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
295626ce2095SJosef Bacik 		if (alloc_flags != cache->flags) {
2957b12de528SQu Wenruo 			ret = btrfs_chunk_alloc(trans, alloc_flags,
2958b12de528SQu Wenruo 						CHUNK_ALLOC_FORCE);
295926ce2095SJosef Bacik 			/*
296026ce2095SJosef Bacik 			 * ENOSPC is allowed here, we may have enough space
2961b12de528SQu Wenruo 			 * already allocated at the new raid level to carry on
296226ce2095SJosef Bacik 			 */
296326ce2095SJosef Bacik 			if (ret == -ENOSPC)
296426ce2095SJosef Bacik 				ret = 0;
296526ce2095SJosef Bacik 			if (ret < 0)
296626ce2095SJosef Bacik 				goto out;
296726ce2095SJosef Bacik 		}
2968b12de528SQu Wenruo 	}
296926ce2095SJosef Bacik 
2970a7a63accSJosef Bacik 	ret = inc_block_group_ro(cache, 0);
297126ce2095SJosef Bacik 	if (!ret)
297226ce2095SJosef Bacik 		goto out;
29737561551eSQu Wenruo 	if (ret == -ETXTBSY)
29747561551eSQu Wenruo 		goto unlock_out;
29757561551eSQu Wenruo 
29767561551eSQu Wenruo 	/*
29777561551eSQu Wenruo 	 * Skip chunk alloction if the bg is SYSTEM, this is to avoid system
29787561551eSQu Wenruo 	 * chunk allocation storm to exhaust the system chunk array.  Otherwise
29797561551eSQu Wenruo 	 * we still want to try our best to mark the block group read-only.
29807561551eSQu Wenruo 	 */
29817561551eSQu Wenruo 	if (!do_chunk_alloc && ret == -ENOSPC &&
29827561551eSQu Wenruo 	    (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM))
29837561551eSQu Wenruo 		goto unlock_out;
29847561551eSQu Wenruo 
298526ce2095SJosef Bacik 	alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
298626ce2095SJosef Bacik 	ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
298726ce2095SJosef Bacik 	if (ret < 0)
298826ce2095SJosef Bacik 		goto out;
2989b6a98021SNaohiro Aota 	/*
2990b6a98021SNaohiro Aota 	 * We have allocated a new chunk. We also need to activate that chunk to
2991b6a98021SNaohiro Aota 	 * grant metadata tickets for zoned filesystem.
2992b6a98021SNaohiro Aota 	 */
2993b6a98021SNaohiro Aota 	ret = btrfs_zoned_activate_one_bg(fs_info, cache->space_info, true);
2994b6a98021SNaohiro Aota 	if (ret < 0)
2995b6a98021SNaohiro Aota 		goto out;
2996b6a98021SNaohiro Aota 
2997e11c0406SJosef Bacik 	ret = inc_block_group_ro(cache, 0);
2998195a49eaSFilipe Manana 	if (ret == -ETXTBSY)
2999195a49eaSFilipe Manana 		goto unlock_out;
300026ce2095SJosef Bacik out:
300126ce2095SJosef Bacik 	if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
3002349e120eSJosef Bacik 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
300326ce2095SJosef Bacik 		mutex_lock(&fs_info->chunk_mutex);
300426ce2095SJosef Bacik 		check_system_chunk(trans, alloc_flags);
300526ce2095SJosef Bacik 		mutex_unlock(&fs_info->chunk_mutex);
300626ce2095SJosef Bacik 	}
3007b12de528SQu Wenruo unlock_out:
300826ce2095SJosef Bacik 	mutex_unlock(&fs_info->ro_block_group_mutex);
300926ce2095SJosef Bacik 
301026ce2095SJosef Bacik 	btrfs_end_transaction(trans);
301126ce2095SJosef Bacik 	return ret;
301226ce2095SJosef Bacik }
301326ce2095SJosef Bacik 
btrfs_dec_block_group_ro(struct btrfs_block_group * cache)301432da5386SDavid Sterba void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
301526ce2095SJosef Bacik {
301626ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
301726ce2095SJosef Bacik 	u64 num_bytes;
301826ce2095SJosef Bacik 
301926ce2095SJosef Bacik 	BUG_ON(!cache->ro);
302026ce2095SJosef Bacik 
302126ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
302226ce2095SJosef Bacik 	spin_lock(&cache->lock);
302326ce2095SJosef Bacik 	if (!--cache->ro) {
3024169e0da9SNaohiro Aota 		if (btrfs_is_zoned(cache->fs_info)) {
3025169e0da9SNaohiro Aota 			/* Migrate zone_unusable bytes back */
302698173255SNaohiro Aota 			cache->zone_unusable =
3027ae29e6f7SNaohiro Aota 				(cache->alloc_offset - cache->used - cache->pinned -
3028ae29e6f7SNaohiro Aota 				 cache->reserved) +
302998173255SNaohiro Aota 				(cache->length - cache->zone_capacity);
3030ae29e6f7SNaohiro Aota 			btrfs_space_info_update_bytes_zone_unusable(cache->fs_info, sinfo,
3031ae29e6f7SNaohiro Aota 								    cache->zone_unusable);
3032169e0da9SNaohiro Aota 			sinfo->bytes_readonly -= cache->zone_unusable;
3033169e0da9SNaohiro Aota 		}
3034f9f28e5bSNaohiro Aota 		num_bytes = cache->length - cache->reserved -
3035f9f28e5bSNaohiro Aota 			    cache->pinned - cache->bytes_super -
3036f9f28e5bSNaohiro Aota 			    cache->zone_unusable - cache->used;
3037f9f28e5bSNaohiro Aota 		sinfo->bytes_readonly -= num_bytes;
303826ce2095SJosef Bacik 		list_del_init(&cache->ro_list);
303926ce2095SJosef Bacik 	}
304026ce2095SJosef Bacik 	spin_unlock(&cache->lock);
304126ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
304226ce2095SJosef Bacik }
304377745c05SJosef Bacik 
update_block_group_item(struct btrfs_trans_handle * trans,struct btrfs_path * path,struct btrfs_block_group * cache)30443be4d8efSQu Wenruo static int update_block_group_item(struct btrfs_trans_handle *trans,
304577745c05SJosef Bacik 				   struct btrfs_path *path,
304632da5386SDavid Sterba 				   struct btrfs_block_group *cache)
304777745c05SJosef Bacik {
304877745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
304977745c05SJosef Bacik 	int ret;
3050dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
305177745c05SJosef Bacik 	unsigned long bi;
305277745c05SJosef Bacik 	struct extent_buffer *leaf;
3053bf38be65SDavid Sterba 	struct btrfs_block_group_item bgi;
3054b3470b5dSDavid Sterba 	struct btrfs_key key;
30557248e0ceSQu Wenruo 	u64 old_commit_used;
30567248e0ceSQu Wenruo 	u64 used;
30577248e0ceSQu Wenruo 
30587248e0ceSQu Wenruo 	/*
30597248e0ceSQu Wenruo 	 * Block group items update can be triggered out of commit transaction
30607248e0ceSQu Wenruo 	 * critical section, thus we need a consistent view of used bytes.
30617248e0ceSQu Wenruo 	 * We cannot use cache->used directly outside of the spin lock, as it
30627248e0ceSQu Wenruo 	 * may be changed.
30637248e0ceSQu Wenruo 	 */
30647248e0ceSQu Wenruo 	spin_lock(&cache->lock);
30657248e0ceSQu Wenruo 	old_commit_used = cache->commit_used;
30667248e0ceSQu Wenruo 	used = cache->used;
30677248e0ceSQu Wenruo 	/* No change in used bytes, can safely skip it. */
30687248e0ceSQu Wenruo 	if (cache->commit_used == used) {
30697248e0ceSQu Wenruo 		spin_unlock(&cache->lock);
30707248e0ceSQu Wenruo 		return 0;
30717248e0ceSQu Wenruo 	}
30727248e0ceSQu Wenruo 	cache->commit_used = used;
30737248e0ceSQu Wenruo 	spin_unlock(&cache->lock);
307477745c05SJosef Bacik 
3075b3470b5dSDavid Sterba 	key.objectid = cache->start;
3076b3470b5dSDavid Sterba 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
3077b3470b5dSDavid Sterba 	key.offset = cache->length;
3078b3470b5dSDavid Sterba 
30793be4d8efSQu Wenruo 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
308077745c05SJosef Bacik 	if (ret) {
308177745c05SJosef Bacik 		if (ret > 0)
308277745c05SJosef Bacik 			ret = -ENOENT;
308377745c05SJosef Bacik 		goto fail;
308477745c05SJosef Bacik 	}
308577745c05SJosef Bacik 
308677745c05SJosef Bacik 	leaf = path->nodes[0];
308777745c05SJosef Bacik 	bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
30887248e0ceSQu Wenruo 	btrfs_set_stack_block_group_used(&bgi, used);
3089de0dc456SDavid Sterba 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
3090f7238e50SJosef Bacik 						   cache->global_root_id);
3091de0dc456SDavid Sterba 	btrfs_set_stack_block_group_flags(&bgi, cache->flags);
3092bf38be65SDavid Sterba 	write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
3093d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, leaf);
309477745c05SJosef Bacik fail:
309577745c05SJosef Bacik 	btrfs_release_path(path);
30962d6cd791SFilipe Manana 	/*
30972d6cd791SFilipe Manana 	 * We didn't update the block group item, need to revert commit_used
30982d6cd791SFilipe Manana 	 * unless the block group item didn't exist yet - this is to prevent a
30992d6cd791SFilipe Manana 	 * race with a concurrent insertion of the block group item, with
31002d6cd791SFilipe Manana 	 * insert_block_group_item(), that happened just after we attempted to
31012d6cd791SFilipe Manana 	 * update. In that case we would reset commit_used to 0 just after the
31022d6cd791SFilipe Manana 	 * insertion set it to a value greater than 0 - if the block group later
31032d6cd791SFilipe Manana 	 * becomes with 0 used bytes, we would incorrectly skip its update.
31042d6cd791SFilipe Manana 	 */
31052d6cd791SFilipe Manana 	if (ret < 0 && ret != -ENOENT) {
31067248e0ceSQu Wenruo 		spin_lock(&cache->lock);
31077248e0ceSQu Wenruo 		cache->commit_used = old_commit_used;
31087248e0ceSQu Wenruo 		spin_unlock(&cache->lock);
31097248e0ceSQu Wenruo 	}
311077745c05SJosef Bacik 	return ret;
311177745c05SJosef Bacik 
311277745c05SJosef Bacik }
311377745c05SJosef Bacik 
cache_save_setup(struct btrfs_block_group * block_group,struct btrfs_trans_handle * trans,struct btrfs_path * path)311432da5386SDavid Sterba static int cache_save_setup(struct btrfs_block_group *block_group,
311577745c05SJosef Bacik 			    struct btrfs_trans_handle *trans,
311677745c05SJosef Bacik 			    struct btrfs_path *path)
311777745c05SJosef Bacik {
311877745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
311977745c05SJosef Bacik 	struct btrfs_root *root = fs_info->tree_root;
312077745c05SJosef Bacik 	struct inode *inode = NULL;
312177745c05SJosef Bacik 	struct extent_changeset *data_reserved = NULL;
312277745c05SJosef Bacik 	u64 alloc_hint = 0;
312377745c05SJosef Bacik 	int dcs = BTRFS_DC_ERROR;
31240044ae11SQu Wenruo 	u64 cache_size = 0;
312577745c05SJosef Bacik 	int retries = 0;
312677745c05SJosef Bacik 	int ret = 0;
312777745c05SJosef Bacik 
3128af456a2cSBoris Burkov 	if (!btrfs_test_opt(fs_info, SPACE_CACHE))
3129af456a2cSBoris Burkov 		return 0;
3130af456a2cSBoris Burkov 
313177745c05SJosef Bacik 	/*
313277745c05SJosef Bacik 	 * If this block group is smaller than 100 megs don't bother caching the
313377745c05SJosef Bacik 	 * block group.
313477745c05SJosef Bacik 	 */
3135b3470b5dSDavid Sterba 	if (block_group->length < (100 * SZ_1M)) {
313677745c05SJosef Bacik 		spin_lock(&block_group->lock);
313777745c05SJosef Bacik 		block_group->disk_cache_state = BTRFS_DC_WRITTEN;
313877745c05SJosef Bacik 		spin_unlock(&block_group->lock);
313977745c05SJosef Bacik 		return 0;
314077745c05SJosef Bacik 	}
314177745c05SJosef Bacik 
3142bf31f87fSDavid Sterba 	if (TRANS_ABORTED(trans))
314377745c05SJosef Bacik 		return 0;
314477745c05SJosef Bacik again:
314577745c05SJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
314677745c05SJosef Bacik 	if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
314777745c05SJosef Bacik 		ret = PTR_ERR(inode);
314877745c05SJosef Bacik 		btrfs_release_path(path);
314977745c05SJosef Bacik 		goto out;
315077745c05SJosef Bacik 	}
315177745c05SJosef Bacik 
315277745c05SJosef Bacik 	if (IS_ERR(inode)) {
315377745c05SJosef Bacik 		BUG_ON(retries);
315477745c05SJosef Bacik 		retries++;
315577745c05SJosef Bacik 
315677745c05SJosef Bacik 		if (block_group->ro)
315777745c05SJosef Bacik 			goto out_free;
315877745c05SJosef Bacik 
315977745c05SJosef Bacik 		ret = create_free_space_inode(trans, block_group, path);
316077745c05SJosef Bacik 		if (ret)
316177745c05SJosef Bacik 			goto out_free;
316277745c05SJosef Bacik 		goto again;
316377745c05SJosef Bacik 	}
316477745c05SJosef Bacik 
316577745c05SJosef Bacik 	/*
316677745c05SJosef Bacik 	 * We want to set the generation to 0, that way if anything goes wrong
316777745c05SJosef Bacik 	 * from here on out we know not to trust this cache when we load up next
316877745c05SJosef Bacik 	 * time.
316977745c05SJosef Bacik 	 */
317077745c05SJosef Bacik 	BTRFS_I(inode)->generation = 0;
31719a56fcd1SNikolay Borisov 	ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
317277745c05SJosef Bacik 	if (ret) {
317377745c05SJosef Bacik 		/*
317477745c05SJosef Bacik 		 * So theoretically we could recover from this, simply set the
317577745c05SJosef Bacik 		 * super cache generation to 0 so we know to invalidate the
317677745c05SJosef Bacik 		 * cache, but then we'd have to keep track of the block groups
317777745c05SJosef Bacik 		 * that fail this way so we know we _have_ to reset this cache
317877745c05SJosef Bacik 		 * before the next commit or risk reading stale cache.  So to
317977745c05SJosef Bacik 		 * limit our exposure to horrible edge cases lets just abort the
318077745c05SJosef Bacik 		 * transaction, this only happens in really bad situations
318177745c05SJosef Bacik 		 * anyway.
318277745c05SJosef Bacik 		 */
318377745c05SJosef Bacik 		btrfs_abort_transaction(trans, ret);
318477745c05SJosef Bacik 		goto out_put;
318577745c05SJosef Bacik 	}
318677745c05SJosef Bacik 	WARN_ON(ret);
318777745c05SJosef Bacik 
318877745c05SJosef Bacik 	/* We've already setup this transaction, go ahead and exit */
318977745c05SJosef Bacik 	if (block_group->cache_generation == trans->transid &&
319077745c05SJosef Bacik 	    i_size_read(inode)) {
319177745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
319277745c05SJosef Bacik 		goto out_put;
319377745c05SJosef Bacik 	}
319477745c05SJosef Bacik 
319577745c05SJosef Bacik 	if (i_size_read(inode) > 0) {
319677745c05SJosef Bacik 		ret = btrfs_check_trunc_cache_free_space(fs_info,
319777745c05SJosef Bacik 					&fs_info->global_block_rsv);
319877745c05SJosef Bacik 		if (ret)
319977745c05SJosef Bacik 			goto out_put;
320077745c05SJosef Bacik 
320177745c05SJosef Bacik 		ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
320277745c05SJosef Bacik 		if (ret)
320377745c05SJosef Bacik 			goto out_put;
320477745c05SJosef Bacik 	}
320577745c05SJosef Bacik 
320677745c05SJosef Bacik 	spin_lock(&block_group->lock);
320777745c05SJosef Bacik 	if (block_group->cached != BTRFS_CACHE_FINISHED ||
320877745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE)) {
320977745c05SJosef Bacik 		/*
321077745c05SJosef Bacik 		 * don't bother trying to write stuff out _if_
321177745c05SJosef Bacik 		 * a) we're not cached,
321277745c05SJosef Bacik 		 * b) we're with nospace_cache mount option,
321377745c05SJosef Bacik 		 * c) we're with v2 space_cache (FREE_SPACE_TREE).
321477745c05SJosef Bacik 		 */
321577745c05SJosef Bacik 		dcs = BTRFS_DC_WRITTEN;
321677745c05SJosef Bacik 		spin_unlock(&block_group->lock);
321777745c05SJosef Bacik 		goto out_put;
321877745c05SJosef Bacik 	}
321977745c05SJosef Bacik 	spin_unlock(&block_group->lock);
322077745c05SJosef Bacik 
322177745c05SJosef Bacik 	/*
322277745c05SJosef Bacik 	 * We hit an ENOSPC when setting up the cache in this transaction, just
322377745c05SJosef Bacik 	 * skip doing the setup, we've already cleared the cache so we're safe.
322477745c05SJosef Bacik 	 */
322577745c05SJosef Bacik 	if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
322677745c05SJosef Bacik 		ret = -ENOSPC;
322777745c05SJosef Bacik 		goto out_put;
322877745c05SJosef Bacik 	}
322977745c05SJosef Bacik 
323077745c05SJosef Bacik 	/*
323177745c05SJosef Bacik 	 * Try to preallocate enough space based on how big the block group is.
323277745c05SJosef Bacik 	 * Keep in mind this has to include any pinned space which could end up
323377745c05SJosef Bacik 	 * taking up quite a bit since it's not folded into the other space
323477745c05SJosef Bacik 	 * cache.
323577745c05SJosef Bacik 	 */
32360044ae11SQu Wenruo 	cache_size = div_u64(block_group->length, SZ_256M);
32370044ae11SQu Wenruo 	if (!cache_size)
32380044ae11SQu Wenruo 		cache_size = 1;
323977745c05SJosef Bacik 
32400044ae11SQu Wenruo 	cache_size *= 16;
32410044ae11SQu Wenruo 	cache_size *= fs_info->sectorsize;
324277745c05SJosef Bacik 
324336ea6f3eSNikolay Borisov 	ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
32441daedb1dSJosef Bacik 					  cache_size, false);
324577745c05SJosef Bacik 	if (ret)
324677745c05SJosef Bacik 		goto out_put;
324777745c05SJosef Bacik 
32480044ae11SQu Wenruo 	ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
32490044ae11SQu Wenruo 					      cache_size, cache_size,
325077745c05SJosef Bacik 					      &alloc_hint);
325177745c05SJosef Bacik 	/*
325277745c05SJosef Bacik 	 * Our cache requires contiguous chunks so that we don't modify a bunch
325377745c05SJosef Bacik 	 * of metadata or split extents when writing the cache out, which means
325477745c05SJosef Bacik 	 * we can enospc if we are heavily fragmented in addition to just normal
325577745c05SJosef Bacik 	 * out of space conditions.  So if we hit this just skip setting up any
325677745c05SJosef Bacik 	 * other block groups for this transaction, maybe we'll unpin enough
325777745c05SJosef Bacik 	 * space the next time around.
325877745c05SJosef Bacik 	 */
325977745c05SJosef Bacik 	if (!ret)
326077745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
326177745c05SJosef Bacik 	else if (ret == -ENOSPC)
326277745c05SJosef Bacik 		set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
326377745c05SJosef Bacik 
326477745c05SJosef Bacik out_put:
326577745c05SJosef Bacik 	iput(inode);
326677745c05SJosef Bacik out_free:
326777745c05SJosef Bacik 	btrfs_release_path(path);
326877745c05SJosef Bacik out:
326977745c05SJosef Bacik 	spin_lock(&block_group->lock);
327077745c05SJosef Bacik 	if (!ret && dcs == BTRFS_DC_SETUP)
327177745c05SJosef Bacik 		block_group->cache_generation = trans->transid;
327277745c05SJosef Bacik 	block_group->disk_cache_state = dcs;
327377745c05SJosef Bacik 	spin_unlock(&block_group->lock);
327477745c05SJosef Bacik 
327577745c05SJosef Bacik 	extent_changeset_free(data_reserved);
327677745c05SJosef Bacik 	return ret;
327777745c05SJosef Bacik }
327877745c05SJosef Bacik 
btrfs_setup_space_cache(struct btrfs_trans_handle * trans)327977745c05SJosef Bacik int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
328077745c05SJosef Bacik {
328177745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
328232da5386SDavid Sterba 	struct btrfs_block_group *cache, *tmp;
328377745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
328477745c05SJosef Bacik 	struct btrfs_path *path;
328577745c05SJosef Bacik 
328677745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs) ||
328777745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE))
328877745c05SJosef Bacik 		return 0;
328977745c05SJosef Bacik 
329077745c05SJosef Bacik 	path = btrfs_alloc_path();
329177745c05SJosef Bacik 	if (!path)
329277745c05SJosef Bacik 		return -ENOMEM;
329377745c05SJosef Bacik 
329477745c05SJosef Bacik 	/* Could add new block groups, use _safe just in case */
329577745c05SJosef Bacik 	list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
329677745c05SJosef Bacik 				 dirty_list) {
329777745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_CLEAR)
329877745c05SJosef Bacik 			cache_save_setup(cache, trans, path);
329977745c05SJosef Bacik 	}
330077745c05SJosef Bacik 
330177745c05SJosef Bacik 	btrfs_free_path(path);
330277745c05SJosef Bacik 	return 0;
330377745c05SJosef Bacik }
330477745c05SJosef Bacik 
330577745c05SJosef Bacik /*
330677745c05SJosef Bacik  * Transaction commit does final block group cache writeback during a critical
330777745c05SJosef Bacik  * section where nothing is allowed to change the FS.  This is required in
330877745c05SJosef Bacik  * order for the cache to actually match the block group, but can introduce a
330977745c05SJosef Bacik  * lot of latency into the commit.
331077745c05SJosef Bacik  *
331177745c05SJosef Bacik  * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
331277745c05SJosef Bacik  * There's a chance we'll have to redo some of it if the block group changes
331377745c05SJosef Bacik  * again during the commit, but it greatly reduces the commit latency by
331477745c05SJosef Bacik  * getting rid of the easy block groups while we're still allowing others to
331577745c05SJosef Bacik  * join the commit.
331677745c05SJosef Bacik  */
btrfs_start_dirty_block_groups(struct btrfs_trans_handle * trans)331777745c05SJosef Bacik int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
331877745c05SJosef Bacik {
331977745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
332032da5386SDavid Sterba 	struct btrfs_block_group *cache;
332177745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
332277745c05SJosef Bacik 	int ret = 0;
332377745c05SJosef Bacik 	int should_put;
332477745c05SJosef Bacik 	struct btrfs_path *path = NULL;
332577745c05SJosef Bacik 	LIST_HEAD(dirty);
332677745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
332777745c05SJosef Bacik 	int loops = 0;
332877745c05SJosef Bacik 
332977745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
333077745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs)) {
333177745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
333277745c05SJosef Bacik 		return 0;
333377745c05SJosef Bacik 	}
333477745c05SJosef Bacik 	list_splice_init(&cur_trans->dirty_bgs, &dirty);
333577745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
333677745c05SJosef Bacik 
333777745c05SJosef Bacik again:
333877745c05SJosef Bacik 	/* Make sure all the block groups on our dirty list actually exist */
333977745c05SJosef Bacik 	btrfs_create_pending_block_groups(trans);
334077745c05SJosef Bacik 
334177745c05SJosef Bacik 	if (!path) {
334277745c05SJosef Bacik 		path = btrfs_alloc_path();
3343938fcbfbSJosef Bacik 		if (!path) {
3344938fcbfbSJosef Bacik 			ret = -ENOMEM;
3345938fcbfbSJosef Bacik 			goto out;
3346938fcbfbSJosef Bacik 		}
334777745c05SJosef Bacik 	}
334877745c05SJosef Bacik 
334977745c05SJosef Bacik 	/*
335077745c05SJosef Bacik 	 * cache_write_mutex is here only to save us from balance or automatic
335177745c05SJosef Bacik 	 * removal of empty block groups deleting this block group while we are
335277745c05SJosef Bacik 	 * writing out the cache
335377745c05SJosef Bacik 	 */
335477745c05SJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
335577745c05SJosef Bacik 	while (!list_empty(&dirty)) {
335677745c05SJosef Bacik 		bool drop_reserve = true;
335777745c05SJosef Bacik 
335832da5386SDavid Sterba 		cache = list_first_entry(&dirty, struct btrfs_block_group,
335977745c05SJosef Bacik 					 dirty_list);
336077745c05SJosef Bacik 		/*
336177745c05SJosef Bacik 		 * This can happen if something re-dirties a block group that
336277745c05SJosef Bacik 		 * is already under IO.  Just wait for it to finish and then do
336377745c05SJosef Bacik 		 * it all again
336477745c05SJosef Bacik 		 */
336577745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
336677745c05SJosef Bacik 			list_del_init(&cache->io_list);
336777745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
336877745c05SJosef Bacik 			btrfs_put_block_group(cache);
336977745c05SJosef Bacik 		}
337077745c05SJosef Bacik 
337177745c05SJosef Bacik 
337277745c05SJosef Bacik 		/*
337377745c05SJosef Bacik 		 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
337477745c05SJosef Bacik 		 * it should update the cache_state.  Don't delete until after
337577745c05SJosef Bacik 		 * we wait.
337677745c05SJosef Bacik 		 *
337777745c05SJosef Bacik 		 * Since we're not running in the commit critical section
337877745c05SJosef Bacik 		 * we need the dirty_bgs_lock to protect from update_block_group
337977745c05SJosef Bacik 		 */
338077745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
338177745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
338277745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
338377745c05SJosef Bacik 
338477745c05SJosef Bacik 		should_put = 1;
338577745c05SJosef Bacik 
338677745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
338777745c05SJosef Bacik 
338877745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_SETUP) {
338977745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
339077745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
339177745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
339277745c05SJosef Bacik 				should_put = 0;
339377745c05SJosef Bacik 
339477745c05SJosef Bacik 				/*
339577745c05SJosef Bacik 				 * The cache_write_mutex is protecting the
339677745c05SJosef Bacik 				 * io_list, also refer to the definition of
339777745c05SJosef Bacik 				 * btrfs_transaction::io_bgs for more details
339877745c05SJosef Bacik 				 */
339977745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
340077745c05SJosef Bacik 			} else {
340177745c05SJosef Bacik 				/*
340277745c05SJosef Bacik 				 * If we failed to write the cache, the
340377745c05SJosef Bacik 				 * generation will be bad and life goes on
340477745c05SJosef Bacik 				 */
340577745c05SJosef Bacik 				ret = 0;
340677745c05SJosef Bacik 			}
340777745c05SJosef Bacik 		}
340877745c05SJosef Bacik 		if (!ret) {
34093be4d8efSQu Wenruo 			ret = update_block_group_item(trans, path, cache);
341077745c05SJosef Bacik 			/*
341177745c05SJosef Bacik 			 * Our block group might still be attached to the list
341277745c05SJosef Bacik 			 * of new block groups in the transaction handle of some
341377745c05SJosef Bacik 			 * other task (struct btrfs_trans_handle->new_bgs). This
341477745c05SJosef Bacik 			 * means its block group item isn't yet in the extent
341577745c05SJosef Bacik 			 * tree. If this happens ignore the error, as we will
341677745c05SJosef Bacik 			 * try again later in the critical section of the
341777745c05SJosef Bacik 			 * transaction commit.
341877745c05SJosef Bacik 			 */
341977745c05SJosef Bacik 			if (ret == -ENOENT) {
342077745c05SJosef Bacik 				ret = 0;
342177745c05SJosef Bacik 				spin_lock(&cur_trans->dirty_bgs_lock);
342277745c05SJosef Bacik 				if (list_empty(&cache->dirty_list)) {
342377745c05SJosef Bacik 					list_add_tail(&cache->dirty_list,
342477745c05SJosef Bacik 						      &cur_trans->dirty_bgs);
342577745c05SJosef Bacik 					btrfs_get_block_group(cache);
342677745c05SJosef Bacik 					drop_reserve = false;
342777745c05SJosef Bacik 				}
342877745c05SJosef Bacik 				spin_unlock(&cur_trans->dirty_bgs_lock);
342977745c05SJosef Bacik 			} else if (ret) {
343077745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
343177745c05SJosef Bacik 			}
343277745c05SJosef Bacik 		}
343377745c05SJosef Bacik 
343477745c05SJosef Bacik 		/* If it's not on the io list, we need to put the block group */
343577745c05SJosef Bacik 		if (should_put)
343677745c05SJosef Bacik 			btrfs_put_block_group(cache);
343777745c05SJosef Bacik 		if (drop_reserve)
343877745c05SJosef Bacik 			btrfs_delayed_refs_rsv_release(fs_info, 1);
343977745c05SJosef Bacik 		/*
344077745c05SJosef Bacik 		 * Avoid blocking other tasks for too long. It might even save
344177745c05SJosef Bacik 		 * us from writing caches for block groups that are going to be
344277745c05SJosef Bacik 		 * removed.
344377745c05SJosef Bacik 		 */
344477745c05SJosef Bacik 		mutex_unlock(&trans->transaction->cache_write_mutex);
3445938fcbfbSJosef Bacik 		if (ret)
3446938fcbfbSJosef Bacik 			goto out;
344777745c05SJosef Bacik 		mutex_lock(&trans->transaction->cache_write_mutex);
344877745c05SJosef Bacik 	}
344977745c05SJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
345077745c05SJosef Bacik 
345177745c05SJosef Bacik 	/*
345277745c05SJosef Bacik 	 * Go through delayed refs for all the stuff we've just kicked off
345377745c05SJosef Bacik 	 * and then loop back (just once)
345477745c05SJosef Bacik 	 */
345534d1eb0eSJosef Bacik 	if (!ret)
345677745c05SJosef Bacik 		ret = btrfs_run_delayed_refs(trans, 0);
345777745c05SJosef Bacik 	if (!ret && loops == 0) {
345877745c05SJosef Bacik 		loops++;
345977745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
346077745c05SJosef Bacik 		list_splice_init(&cur_trans->dirty_bgs, &dirty);
346177745c05SJosef Bacik 		/*
346277745c05SJosef Bacik 		 * dirty_bgs_lock protects us from concurrent block group
346377745c05SJosef Bacik 		 * deletes too (not just cache_write_mutex).
346477745c05SJosef Bacik 		 */
346577745c05SJosef Bacik 		if (!list_empty(&dirty)) {
346677745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
346777745c05SJosef Bacik 			goto again;
346877745c05SJosef Bacik 		}
346977745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
3470938fcbfbSJosef Bacik 	}
3471938fcbfbSJosef Bacik out:
3472938fcbfbSJosef Bacik 	if (ret < 0) {
3473938fcbfbSJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
3474938fcbfbSJosef Bacik 		list_splice_init(&dirty, &cur_trans->dirty_bgs);
3475938fcbfbSJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
347677745c05SJosef Bacik 		btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
347777745c05SJosef Bacik 	}
347877745c05SJosef Bacik 
347977745c05SJosef Bacik 	btrfs_free_path(path);
348077745c05SJosef Bacik 	return ret;
348177745c05SJosef Bacik }
348277745c05SJosef Bacik 
btrfs_write_dirty_block_groups(struct btrfs_trans_handle * trans)348377745c05SJosef Bacik int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
348477745c05SJosef Bacik {
348577745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
348632da5386SDavid Sterba 	struct btrfs_block_group *cache;
348777745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
348877745c05SJosef Bacik 	int ret = 0;
348977745c05SJosef Bacik 	int should_put;
349077745c05SJosef Bacik 	struct btrfs_path *path;
349177745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
349277745c05SJosef Bacik 
349377745c05SJosef Bacik 	path = btrfs_alloc_path();
349477745c05SJosef Bacik 	if (!path)
349577745c05SJosef Bacik 		return -ENOMEM;
349677745c05SJosef Bacik 
349777745c05SJosef Bacik 	/*
349877745c05SJosef Bacik 	 * Even though we are in the critical section of the transaction commit,
349977745c05SJosef Bacik 	 * we can still have concurrent tasks adding elements to this
350077745c05SJosef Bacik 	 * transaction's list of dirty block groups. These tasks correspond to
350177745c05SJosef Bacik 	 * endio free space workers started when writeback finishes for a
350277745c05SJosef Bacik 	 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
350377745c05SJosef Bacik 	 * allocate new block groups as a result of COWing nodes of the root
350477745c05SJosef Bacik 	 * tree when updating the free space inode. The writeback for the space
350577745c05SJosef Bacik 	 * caches is triggered by an earlier call to
350677745c05SJosef Bacik 	 * btrfs_start_dirty_block_groups() and iterations of the following
350777745c05SJosef Bacik 	 * loop.
350877745c05SJosef Bacik 	 * Also we want to do the cache_save_setup first and then run the
350977745c05SJosef Bacik 	 * delayed refs to make sure we have the best chance at doing this all
351077745c05SJosef Bacik 	 * in one shot.
351177745c05SJosef Bacik 	 */
351277745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
351377745c05SJosef Bacik 	while (!list_empty(&cur_trans->dirty_bgs)) {
351477745c05SJosef Bacik 		cache = list_first_entry(&cur_trans->dirty_bgs,
351532da5386SDavid Sterba 					 struct btrfs_block_group,
351677745c05SJosef Bacik 					 dirty_list);
351777745c05SJosef Bacik 
351877745c05SJosef Bacik 		/*
351977745c05SJosef Bacik 		 * This can happen if cache_save_setup re-dirties a block group
352077745c05SJosef Bacik 		 * that is already under IO.  Just wait for it to finish and
352177745c05SJosef Bacik 		 * then do it all again
352277745c05SJosef Bacik 		 */
352377745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
352477745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
352577745c05SJosef Bacik 			list_del_init(&cache->io_list);
352677745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
352777745c05SJosef Bacik 			btrfs_put_block_group(cache);
352877745c05SJosef Bacik 			spin_lock(&cur_trans->dirty_bgs_lock);
352977745c05SJosef Bacik 		}
353077745c05SJosef Bacik 
353177745c05SJosef Bacik 		/*
353277745c05SJosef Bacik 		 * Don't remove from the dirty list until after we've waited on
353377745c05SJosef Bacik 		 * any pending IO
353477745c05SJosef Bacik 		 */
353577745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
353677745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
353777745c05SJosef Bacik 		should_put = 1;
353877745c05SJosef Bacik 
353977745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
354077745c05SJosef Bacik 
354177745c05SJosef Bacik 		if (!ret)
354277745c05SJosef Bacik 			ret = btrfs_run_delayed_refs(trans,
354377745c05SJosef Bacik 						     (unsigned long) -1);
354477745c05SJosef Bacik 
354577745c05SJosef Bacik 		if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
354677745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
354777745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
354877745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
354977745c05SJosef Bacik 				should_put = 0;
355077745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
355177745c05SJosef Bacik 			} else {
355277745c05SJosef Bacik 				/*
355377745c05SJosef Bacik 				 * If we failed to write the cache, the
355477745c05SJosef Bacik 				 * generation will be bad and life goes on
355577745c05SJosef Bacik 				 */
355677745c05SJosef Bacik 				ret = 0;
355777745c05SJosef Bacik 			}
355877745c05SJosef Bacik 		}
355977745c05SJosef Bacik 		if (!ret) {
35603be4d8efSQu Wenruo 			ret = update_block_group_item(trans, path, cache);
356177745c05SJosef Bacik 			/*
356277745c05SJosef Bacik 			 * One of the free space endio workers might have
356377745c05SJosef Bacik 			 * created a new block group while updating a free space
356477745c05SJosef Bacik 			 * cache's inode (at inode.c:btrfs_finish_ordered_io())
356577745c05SJosef Bacik 			 * and hasn't released its transaction handle yet, in
356677745c05SJosef Bacik 			 * which case the new block group is still attached to
356777745c05SJosef Bacik 			 * its transaction handle and its creation has not
356877745c05SJosef Bacik 			 * finished yet (no block group item in the extent tree
356977745c05SJosef Bacik 			 * yet, etc). If this is the case, wait for all free
357077745c05SJosef Bacik 			 * space endio workers to finish and retry. This is a
3571260db43cSRandy Dunlap 			 * very rare case so no need for a more efficient and
357277745c05SJosef Bacik 			 * complex approach.
357377745c05SJosef Bacik 			 */
357477745c05SJosef Bacik 			if (ret == -ENOENT) {
357577745c05SJosef Bacik 				wait_event(cur_trans->writer_wait,
357677745c05SJosef Bacik 				   atomic_read(&cur_trans->num_writers) == 1);
35773be4d8efSQu Wenruo 				ret = update_block_group_item(trans, path, cache);
357877745c05SJosef Bacik 			}
357977745c05SJosef Bacik 			if (ret)
358077745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
358177745c05SJosef Bacik 		}
358277745c05SJosef Bacik 
358377745c05SJosef Bacik 		/* If its not on the io list, we need to put the block group */
358477745c05SJosef Bacik 		if (should_put)
358577745c05SJosef Bacik 			btrfs_put_block_group(cache);
358677745c05SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
358777745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
358877745c05SJosef Bacik 	}
358977745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
359077745c05SJosef Bacik 
359177745c05SJosef Bacik 	/*
359277745c05SJosef Bacik 	 * Refer to the definition of io_bgs member for details why it's safe
359377745c05SJosef Bacik 	 * to use it without any locking
359477745c05SJosef Bacik 	 */
359577745c05SJosef Bacik 	while (!list_empty(io)) {
359632da5386SDavid Sterba 		cache = list_first_entry(io, struct btrfs_block_group,
359777745c05SJosef Bacik 					 io_list);
359877745c05SJosef Bacik 		list_del_init(&cache->io_list);
359977745c05SJosef Bacik 		btrfs_wait_cache_io(trans, cache, path);
360077745c05SJosef Bacik 		btrfs_put_block_group(cache);
360177745c05SJosef Bacik 	}
360277745c05SJosef Bacik 
360377745c05SJosef Bacik 	btrfs_free_path(path);
360477745c05SJosef Bacik 	return ret;
360577745c05SJosef Bacik }
3606606d1bf1SJosef Bacik 
btrfs_update_block_group(struct btrfs_trans_handle * trans,u64 bytenr,u64 num_bytes,bool alloc)3607606d1bf1SJosef Bacik int btrfs_update_block_group(struct btrfs_trans_handle *trans,
360811b66fa6SAnand Jain 			     u64 bytenr, u64 num_bytes, bool alloc)
3609606d1bf1SJosef Bacik {
3610606d1bf1SJosef Bacik 	struct btrfs_fs_info *info = trans->fs_info;
361132da5386SDavid Sterba 	struct btrfs_block_group *cache = NULL;
3612606d1bf1SJosef Bacik 	u64 total = num_bytes;
3613606d1bf1SJosef Bacik 	u64 old_val;
3614606d1bf1SJosef Bacik 	u64 byte_in_group;
3615606d1bf1SJosef Bacik 	int factor;
3616606d1bf1SJosef Bacik 	int ret = 0;
3617606d1bf1SJosef Bacik 
3618606d1bf1SJosef Bacik 	/* Block accounting for super block */
3619606d1bf1SJosef Bacik 	spin_lock(&info->delalloc_root_lock);
3620606d1bf1SJosef Bacik 	old_val = btrfs_super_bytes_used(info->super_copy);
3621606d1bf1SJosef Bacik 	if (alloc)
3622606d1bf1SJosef Bacik 		old_val += num_bytes;
3623606d1bf1SJosef Bacik 	else
3624606d1bf1SJosef Bacik 		old_val -= num_bytes;
3625606d1bf1SJosef Bacik 	btrfs_set_super_bytes_used(info->super_copy, old_val);
3626606d1bf1SJosef Bacik 	spin_unlock(&info->delalloc_root_lock);
3627606d1bf1SJosef Bacik 
3628606d1bf1SJosef Bacik 	while (total) {
3629df384da5SJosef Bacik 		struct btrfs_space_info *space_info;
3630efbf35a1SJosef Bacik 		bool reclaim = false;
3631ac2f1e63SJosef Bacik 
3632606d1bf1SJosef Bacik 		cache = btrfs_lookup_block_group(info, bytenr);
3633606d1bf1SJosef Bacik 		if (!cache) {
3634606d1bf1SJosef Bacik 			ret = -ENOENT;
3635606d1bf1SJosef Bacik 			break;
3636606d1bf1SJosef Bacik 		}
3637df384da5SJosef Bacik 		space_info = cache->space_info;
3638606d1bf1SJosef Bacik 		factor = btrfs_bg_type_to_factor(cache->flags);
3639606d1bf1SJosef Bacik 
3640606d1bf1SJosef Bacik 		/*
3641606d1bf1SJosef Bacik 		 * If this block group has free space cache written out, we
3642606d1bf1SJosef Bacik 		 * need to make sure to load it if we are removing space.  This
3643606d1bf1SJosef Bacik 		 * is because we need the unpinning stage to actually add the
3644606d1bf1SJosef Bacik 		 * space back to the block group, otherwise we will leak space.
3645606d1bf1SJosef Bacik 		 */
364632da5386SDavid Sterba 		if (!alloc && !btrfs_block_group_done(cache))
3647ced8ecf0SOmar Sandoval 			btrfs_cache_block_group(cache, true);
3648606d1bf1SJosef Bacik 
3649b3470b5dSDavid Sterba 		byte_in_group = bytenr - cache->start;
3650b3470b5dSDavid Sterba 		WARN_ON(byte_in_group > cache->length);
3651606d1bf1SJosef Bacik 
3652df384da5SJosef Bacik 		spin_lock(&space_info->lock);
3653606d1bf1SJosef Bacik 		spin_lock(&cache->lock);
3654606d1bf1SJosef Bacik 
3655606d1bf1SJosef Bacik 		if (btrfs_test_opt(info, SPACE_CACHE) &&
3656606d1bf1SJosef Bacik 		    cache->disk_cache_state < BTRFS_DC_CLEAR)
3657606d1bf1SJosef Bacik 			cache->disk_cache_state = BTRFS_DC_CLEAR;
3658606d1bf1SJosef Bacik 
3659bf38be65SDavid Sterba 		old_val = cache->used;
3660b3470b5dSDavid Sterba 		num_bytes = min(total, cache->length - byte_in_group);
3661606d1bf1SJosef Bacik 		if (alloc) {
3662606d1bf1SJosef Bacik 			old_val += num_bytes;
3663bf38be65SDavid Sterba 			cache->used = old_val;
3664606d1bf1SJosef Bacik 			cache->reserved -= num_bytes;
3665df384da5SJosef Bacik 			space_info->bytes_reserved -= num_bytes;
3666df384da5SJosef Bacik 			space_info->bytes_used += num_bytes;
3667df384da5SJosef Bacik 			space_info->disk_used += num_bytes * factor;
3668606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
3669df384da5SJosef Bacik 			spin_unlock(&space_info->lock);
3670606d1bf1SJosef Bacik 		} else {
3671606d1bf1SJosef Bacik 			old_val -= num_bytes;
3672bf38be65SDavid Sterba 			cache->used = old_val;
3673606d1bf1SJosef Bacik 			cache->pinned += num_bytes;
3674df384da5SJosef Bacik 			btrfs_space_info_update_bytes_pinned(info, space_info,
3675df384da5SJosef Bacik 							     num_bytes);
3676df384da5SJosef Bacik 			space_info->bytes_used -= num_bytes;
3677df384da5SJosef Bacik 			space_info->disk_used -= num_bytes * factor;
3678ac2f1e63SJosef Bacik 
3679ac2f1e63SJosef Bacik 			reclaim = should_reclaim_block_group(cache, num_bytes);
368052bb7a21SBoris Burkov 
3681606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
3682df384da5SJosef Bacik 			spin_unlock(&space_info->lock);
3683606d1bf1SJosef Bacik 
3684fe1a598cSDavid Sterba 			set_extent_bit(&trans->transaction->pinned_extents,
3685606d1bf1SJosef Bacik 				       bytenr, bytenr + num_bytes - 1,
36861d126800SDavid Sterba 				       EXTENT_DIRTY, NULL);
3687606d1bf1SJosef Bacik 		}
3688606d1bf1SJosef Bacik 
3689606d1bf1SJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
3690606d1bf1SJosef Bacik 		if (list_empty(&cache->dirty_list)) {
3691606d1bf1SJosef Bacik 			list_add_tail(&cache->dirty_list,
3692606d1bf1SJosef Bacik 				      &trans->transaction->dirty_bgs);
3693606d1bf1SJosef Bacik 			trans->delayed_ref_updates++;
3694606d1bf1SJosef Bacik 			btrfs_get_block_group(cache);
3695606d1bf1SJosef Bacik 		}
3696606d1bf1SJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
3697606d1bf1SJosef Bacik 
3698606d1bf1SJosef Bacik 		/*
3699606d1bf1SJosef Bacik 		 * No longer have used bytes in this block group, queue it for
3700606d1bf1SJosef Bacik 		 * deletion. We do this after adding the block group to the
3701606d1bf1SJosef Bacik 		 * dirty list to avoid races between cleaner kthread and space
3702606d1bf1SJosef Bacik 		 * cache writeout.
3703606d1bf1SJosef Bacik 		 */
37046e80d4f8SDennis Zhou 		if (!alloc && old_val == 0) {
37056e80d4f8SDennis Zhou 			if (!btrfs_test_opt(info, DISCARD_ASYNC))
3706606d1bf1SJosef Bacik 				btrfs_mark_bg_unused(cache);
3707ac2f1e63SJosef Bacik 		} else if (!alloc && reclaim) {
3708ac2f1e63SJosef Bacik 			btrfs_mark_bg_to_reclaim(cache);
37096e80d4f8SDennis Zhou 		}
3710606d1bf1SJosef Bacik 
3711606d1bf1SJosef Bacik 		btrfs_put_block_group(cache);
3712606d1bf1SJosef Bacik 		total -= num_bytes;
3713606d1bf1SJosef Bacik 		bytenr += num_bytes;
3714606d1bf1SJosef Bacik 	}
3715606d1bf1SJosef Bacik 
3716606d1bf1SJosef Bacik 	/* Modified block groups are accounted for in the delayed_refs_rsv. */
3717606d1bf1SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
3718606d1bf1SJosef Bacik 	return ret;
3719606d1bf1SJosef Bacik }
3720606d1bf1SJosef Bacik 
372143dd529aSDavid Sterba /*
372243dd529aSDavid Sterba  * Update the block_group and space info counters.
372343dd529aSDavid Sterba  *
3724606d1bf1SJosef Bacik  * @cache:	The cache we are manipulating
3725606d1bf1SJosef Bacik  * @ram_bytes:  The number of bytes of file content, and will be same to
3726606d1bf1SJosef Bacik  *              @num_bytes except for the compress path.
3727606d1bf1SJosef Bacik  * @num_bytes:	The number of bytes in question
3728606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
3729606d1bf1SJosef Bacik  *
3730606d1bf1SJosef Bacik  * This is called by the allocator when it reserves space. If this is a
3731606d1bf1SJosef Bacik  * reservation and the block group has become read only we cannot make the
3732606d1bf1SJosef Bacik  * reservation and return -EAGAIN, otherwise this function always succeeds.
3733606d1bf1SJosef Bacik  */
btrfs_add_reserved_bytes(struct btrfs_block_group * cache,u64 ram_bytes,u64 num_bytes,int delalloc,bool force_wrong_size_class)373432da5386SDavid Sterba int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
373552bb7a21SBoris Burkov 			     u64 ram_bytes, u64 num_bytes, int delalloc,
373652bb7a21SBoris Burkov 			     bool force_wrong_size_class)
3737606d1bf1SJosef Bacik {
3738606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
373952bb7a21SBoris Burkov 	enum btrfs_block_group_size_class size_class;
3740606d1bf1SJosef Bacik 	int ret = 0;
3741606d1bf1SJosef Bacik 
3742606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
3743606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
3744606d1bf1SJosef Bacik 	if (cache->ro) {
3745606d1bf1SJosef Bacik 		ret = -EAGAIN;
374652bb7a21SBoris Burkov 		goto out;
374752bb7a21SBoris Burkov 	}
374852bb7a21SBoris Burkov 
3749cb0922f2SBoris Burkov 	if (btrfs_block_group_should_use_size_class(cache)) {
375052bb7a21SBoris Burkov 		size_class = btrfs_calc_block_group_size_class(num_bytes);
375152bb7a21SBoris Burkov 		ret = btrfs_use_block_group_size_class(cache, size_class, force_wrong_size_class);
375252bb7a21SBoris Burkov 		if (ret)
375352bb7a21SBoris Burkov 			goto out;
375452bb7a21SBoris Burkov 	}
3755606d1bf1SJosef Bacik 	cache->reserved += num_bytes;
3756606d1bf1SJosef Bacik 	space_info->bytes_reserved += num_bytes;
3757a43c3835SJosef Bacik 	trace_btrfs_space_reservation(cache->fs_info, "space_info",
3758a43c3835SJosef Bacik 				      space_info->flags, num_bytes, 1);
3759606d1bf1SJosef Bacik 	btrfs_space_info_update_bytes_may_use(cache->fs_info,
3760606d1bf1SJosef Bacik 					      space_info, -ram_bytes);
3761606d1bf1SJosef Bacik 	if (delalloc)
3762606d1bf1SJosef Bacik 		cache->delalloc_bytes += num_bytes;
376399ffb43eSJosef Bacik 
376499ffb43eSJosef Bacik 	/*
376552bb7a21SBoris Burkov 	 * Compression can use less space than we reserved, so wake tickets if
376652bb7a21SBoris Burkov 	 * that happens.
376799ffb43eSJosef Bacik 	 */
376899ffb43eSJosef Bacik 	if (num_bytes < ram_bytes)
376999ffb43eSJosef Bacik 		btrfs_try_granting_tickets(cache->fs_info, space_info);
377052bb7a21SBoris Burkov out:
3771606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
3772606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
3773606d1bf1SJosef Bacik 	return ret;
3774606d1bf1SJosef Bacik }
3775606d1bf1SJosef Bacik 
377643dd529aSDavid Sterba /*
377743dd529aSDavid Sterba  * Update the block_group and space info counters.
377843dd529aSDavid Sterba  *
3779606d1bf1SJosef Bacik  * @cache:      The cache we are manipulating
3780606d1bf1SJosef Bacik  * @num_bytes:  The number of bytes in question
3781606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
3782606d1bf1SJosef Bacik  *
3783606d1bf1SJosef Bacik  * This is called by somebody who is freeing space that was never actually used
3784606d1bf1SJosef Bacik  * on disk.  For example if you reserve some space for a new leaf in transaction
3785606d1bf1SJosef Bacik  * A and before transaction A commits you free that leaf, you call this with
3786606d1bf1SJosef Bacik  * reserve set to 0 in order to clear the reservation.
3787606d1bf1SJosef Bacik  */
btrfs_free_reserved_bytes(struct btrfs_block_group * cache,u64 num_bytes,int delalloc)378832da5386SDavid Sterba void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3789606d1bf1SJosef Bacik 			       u64 num_bytes, int delalloc)
3790606d1bf1SJosef Bacik {
3791606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
3792606d1bf1SJosef Bacik 
3793606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
3794606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
3795606d1bf1SJosef Bacik 	if (cache->ro)
3796606d1bf1SJosef Bacik 		space_info->bytes_readonly += num_bytes;
3797*004ad1a2SNaohiro Aota 	else if (btrfs_is_zoned(cache->fs_info))
3798*004ad1a2SNaohiro Aota 		space_info->bytes_zone_unusable += num_bytes;
3799606d1bf1SJosef Bacik 	cache->reserved -= num_bytes;
3800606d1bf1SJosef Bacik 	space_info->bytes_reserved -= num_bytes;
3801606d1bf1SJosef Bacik 	space_info->max_extent_size = 0;
3802606d1bf1SJosef Bacik 
3803606d1bf1SJosef Bacik 	if (delalloc)
3804606d1bf1SJosef Bacik 		cache->delalloc_bytes -= num_bytes;
3805606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
38063308234aSJosef Bacik 
38073308234aSJosef Bacik 	btrfs_try_granting_tickets(cache->fs_info, space_info);
3808606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
3809606d1bf1SJosef Bacik }
381007730d87SJosef Bacik 
force_metadata_allocation(struct btrfs_fs_info * info)381107730d87SJosef Bacik static void force_metadata_allocation(struct btrfs_fs_info *info)
381207730d87SJosef Bacik {
381307730d87SJosef Bacik 	struct list_head *head = &info->space_info;
381407730d87SJosef Bacik 	struct btrfs_space_info *found;
381507730d87SJosef Bacik 
381672804905SJosef Bacik 	list_for_each_entry(found, head, list) {
381707730d87SJosef Bacik 		if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
381807730d87SJosef Bacik 			found->force_alloc = CHUNK_ALLOC_FORCE;
381907730d87SJosef Bacik 	}
382007730d87SJosef Bacik }
382107730d87SJosef Bacik 
should_alloc_chunk(struct btrfs_fs_info * fs_info,struct btrfs_space_info * sinfo,int force)382207730d87SJosef Bacik static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
382307730d87SJosef Bacik 			      struct btrfs_space_info *sinfo, int force)
382407730d87SJosef Bacik {
382507730d87SJosef Bacik 	u64 bytes_used = btrfs_space_info_used(sinfo, false);
382607730d87SJosef Bacik 	u64 thresh;
382707730d87SJosef Bacik 
382807730d87SJosef Bacik 	if (force == CHUNK_ALLOC_FORCE)
382907730d87SJosef Bacik 		return 1;
383007730d87SJosef Bacik 
383107730d87SJosef Bacik 	/*
383207730d87SJosef Bacik 	 * in limited mode, we want to have some free space up to
383307730d87SJosef Bacik 	 * about 1% of the FS size.
383407730d87SJosef Bacik 	 */
383507730d87SJosef Bacik 	if (force == CHUNK_ALLOC_LIMITED) {
383607730d87SJosef Bacik 		thresh = btrfs_super_total_bytes(fs_info->super_copy);
3837428c8e03SDavid Sterba 		thresh = max_t(u64, SZ_64M, mult_perc(thresh, 1));
383807730d87SJosef Bacik 
383907730d87SJosef Bacik 		if (sinfo->total_bytes - bytes_used < thresh)
384007730d87SJosef Bacik 			return 1;
384107730d87SJosef Bacik 	}
384207730d87SJosef Bacik 
3843428c8e03SDavid Sterba 	if (bytes_used + SZ_2M < mult_perc(sinfo->total_bytes, 80))
384407730d87SJosef Bacik 		return 0;
384507730d87SJosef Bacik 	return 1;
384607730d87SJosef Bacik }
384707730d87SJosef Bacik 
btrfs_force_chunk_alloc(struct btrfs_trans_handle * trans,u64 type)384807730d87SJosef Bacik int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
384907730d87SJosef Bacik {
385007730d87SJosef Bacik 	u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
385107730d87SJosef Bacik 
385207730d87SJosef Bacik 	return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
385307730d87SJosef Bacik }
385407730d87SJosef Bacik 
do_chunk_alloc(struct btrfs_trans_handle * trans,u64 flags)3855820c363bSNaohiro Aota static struct btrfs_block_group *do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags)
385679bd3712SFilipe Manana {
385779bd3712SFilipe Manana 	struct btrfs_block_group *bg;
385879bd3712SFilipe Manana 	int ret;
385979bd3712SFilipe Manana 
386007730d87SJosef Bacik 	/*
386179bd3712SFilipe Manana 	 * Check if we have enough space in the system space info because we
386279bd3712SFilipe Manana 	 * will need to update device items in the chunk btree and insert a new
386379bd3712SFilipe Manana 	 * chunk item in the chunk btree as well. This will allocate a new
386479bd3712SFilipe Manana 	 * system block group if needed.
386579bd3712SFilipe Manana 	 */
386679bd3712SFilipe Manana 	check_system_chunk(trans, flags);
386779bd3712SFilipe Manana 
3868f6f39f7aSNikolay Borisov 	bg = btrfs_create_chunk(trans, flags);
386979bd3712SFilipe Manana 	if (IS_ERR(bg)) {
387079bd3712SFilipe Manana 		ret = PTR_ERR(bg);
387179bd3712SFilipe Manana 		goto out;
387279bd3712SFilipe Manana 	}
387379bd3712SFilipe Manana 
387479bd3712SFilipe Manana 	ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
387579bd3712SFilipe Manana 	/*
387679bd3712SFilipe Manana 	 * Normally we are not expected to fail with -ENOSPC here, since we have
387779bd3712SFilipe Manana 	 * previously reserved space in the system space_info and allocated one
3878ecd84d54SFilipe Manana 	 * new system chunk if necessary. However there are three exceptions:
387979bd3712SFilipe Manana 	 *
388079bd3712SFilipe Manana 	 * 1) We may have enough free space in the system space_info but all the
388179bd3712SFilipe Manana 	 *    existing system block groups have a profile which can not be used
388279bd3712SFilipe Manana 	 *    for extent allocation.
388379bd3712SFilipe Manana 	 *
388479bd3712SFilipe Manana 	 *    This happens when mounting in degraded mode. For example we have a
388579bd3712SFilipe Manana 	 *    RAID1 filesystem with 2 devices, lose one device and mount the fs
388679bd3712SFilipe Manana 	 *    using the other device in degraded mode. If we then allocate a chunk,
388779bd3712SFilipe Manana 	 *    we may have enough free space in the existing system space_info, but
388879bd3712SFilipe Manana 	 *    none of the block groups can be used for extent allocation since they
388979bd3712SFilipe Manana 	 *    have a RAID1 profile, and because we are in degraded mode with a
389079bd3712SFilipe Manana 	 *    single device, we are forced to allocate a new system chunk with a
389179bd3712SFilipe Manana 	 *    SINGLE profile. Making check_system_chunk() iterate over all system
389279bd3712SFilipe Manana 	 *    block groups and check if they have a usable profile and enough space
389379bd3712SFilipe Manana 	 *    can be slow on very large filesystems, so we tolerate the -ENOSPC and
389479bd3712SFilipe Manana 	 *    try again after forcing allocation of a new system chunk. Like this
389579bd3712SFilipe Manana 	 *    we avoid paying the cost of that search in normal circumstances, when
389679bd3712SFilipe Manana 	 *    we were not mounted in degraded mode;
389779bd3712SFilipe Manana 	 *
389879bd3712SFilipe Manana 	 * 2) We had enough free space info the system space_info, and one suitable
389979bd3712SFilipe Manana 	 *    block group to allocate from when we called check_system_chunk()
390079bd3712SFilipe Manana 	 *    above. However right after we called it, the only system block group
390179bd3712SFilipe Manana 	 *    with enough free space got turned into RO mode by a running scrub,
390279bd3712SFilipe Manana 	 *    and in this case we have to allocate a new one and retry. We only
390379bd3712SFilipe Manana 	 *    need do this allocate and retry once, since we have a transaction
3904ecd84d54SFilipe Manana 	 *    handle and scrub uses the commit root to search for block groups;
3905ecd84d54SFilipe Manana 	 *
3906ecd84d54SFilipe Manana 	 * 3) We had one system block group with enough free space when we called
3907ecd84d54SFilipe Manana 	 *    check_system_chunk(), but after that, right before we tried to
3908ecd84d54SFilipe Manana 	 *    allocate the last extent buffer we needed, a discard operation came
3909ecd84d54SFilipe Manana 	 *    in and it temporarily removed the last free space entry from the
3910ecd84d54SFilipe Manana 	 *    block group (discard removes a free space entry, discards it, and
3911ecd84d54SFilipe Manana 	 *    then adds back the entry to the block group cache).
391279bd3712SFilipe Manana 	 */
391379bd3712SFilipe Manana 	if (ret == -ENOSPC) {
391479bd3712SFilipe Manana 		const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info);
391579bd3712SFilipe Manana 		struct btrfs_block_group *sys_bg;
391679bd3712SFilipe Manana 
3917f6f39f7aSNikolay Borisov 		sys_bg = btrfs_create_chunk(trans, sys_flags);
391879bd3712SFilipe Manana 		if (IS_ERR(sys_bg)) {
391979bd3712SFilipe Manana 			ret = PTR_ERR(sys_bg);
392079bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
392179bd3712SFilipe Manana 			goto out;
392279bd3712SFilipe Manana 		}
392379bd3712SFilipe Manana 
392479bd3712SFilipe Manana 		ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
392579bd3712SFilipe Manana 		if (ret) {
392679bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
392779bd3712SFilipe Manana 			goto out;
392879bd3712SFilipe Manana 		}
392979bd3712SFilipe Manana 
393079bd3712SFilipe Manana 		ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
393179bd3712SFilipe Manana 		if (ret) {
393279bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
393379bd3712SFilipe Manana 			goto out;
393479bd3712SFilipe Manana 		}
393579bd3712SFilipe Manana 	} else if (ret) {
393679bd3712SFilipe Manana 		btrfs_abort_transaction(trans, ret);
393779bd3712SFilipe Manana 		goto out;
393879bd3712SFilipe Manana 	}
393979bd3712SFilipe Manana out:
394079bd3712SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
394179bd3712SFilipe Manana 
3942820c363bSNaohiro Aota 	if (ret)
3943820c363bSNaohiro Aota 		return ERR_PTR(ret);
3944820c363bSNaohiro Aota 
3945820c363bSNaohiro Aota 	btrfs_get_block_group(bg);
3946820c363bSNaohiro Aota 	return bg;
394779bd3712SFilipe Manana }
394879bd3712SFilipe Manana 
394979bd3712SFilipe Manana /*
395079bd3712SFilipe Manana  * Chunk allocation is done in 2 phases:
395179bd3712SFilipe Manana  *
395279bd3712SFilipe Manana  * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
395379bd3712SFilipe Manana  *    the chunk, the chunk mapping, create its block group and add the items
395479bd3712SFilipe Manana  *    that belong in the chunk btree to it - more specifically, we need to
395579bd3712SFilipe Manana  *    update device items in the chunk btree and add a new chunk item to it.
395679bd3712SFilipe Manana  *
395779bd3712SFilipe Manana  * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
395879bd3712SFilipe Manana  *    group item to the extent btree and the device extent items to the devices
395979bd3712SFilipe Manana  *    btree.
396079bd3712SFilipe Manana  *
396179bd3712SFilipe Manana  * This is done to prevent deadlocks. For example when COWing a node from the
396279bd3712SFilipe Manana  * extent btree we are holding a write lock on the node's parent and if we
396379bd3712SFilipe Manana  * trigger chunk allocation and attempted to insert the new block group item
396479bd3712SFilipe Manana  * in the extent btree right way, we could deadlock because the path for the
396579bd3712SFilipe Manana  * insertion can include that parent node. At first glance it seems impossible
396679bd3712SFilipe Manana  * to trigger chunk allocation after starting a transaction since tasks should
396779bd3712SFilipe Manana  * reserve enough transaction units (metadata space), however while that is true
396879bd3712SFilipe Manana  * most of the time, chunk allocation may still be triggered for several reasons:
396979bd3712SFilipe Manana  *
397079bd3712SFilipe Manana  * 1) When reserving metadata, we check if there is enough free space in the
397179bd3712SFilipe Manana  *    metadata space_info and therefore don't trigger allocation of a new chunk.
397279bd3712SFilipe Manana  *    However later when the task actually tries to COW an extent buffer from
397379bd3712SFilipe Manana  *    the extent btree or from the device btree for example, it is forced to
397479bd3712SFilipe Manana  *    allocate a new block group (chunk) because the only one that had enough
397579bd3712SFilipe Manana  *    free space was just turned to RO mode by a running scrub for example (or
397679bd3712SFilipe Manana  *    device replace, block group reclaim thread, etc), so we can not use it
397779bd3712SFilipe Manana  *    for allocating an extent and end up being forced to allocate a new one;
397879bd3712SFilipe Manana  *
397979bd3712SFilipe Manana  * 2) Because we only check that the metadata space_info has enough free bytes,
398079bd3712SFilipe Manana  *    we end up not allocating a new metadata chunk in that case. However if
398179bd3712SFilipe Manana  *    the filesystem was mounted in degraded mode, none of the existing block
398279bd3712SFilipe Manana  *    groups might be suitable for extent allocation due to their incompatible
398379bd3712SFilipe Manana  *    profile (for e.g. mounting a 2 devices filesystem, where all block groups
398479bd3712SFilipe Manana  *    use a RAID1 profile, in degraded mode using a single device). In this case
398579bd3712SFilipe Manana  *    when the task attempts to COW some extent buffer of the extent btree for
398679bd3712SFilipe Manana  *    example, it will trigger allocation of a new metadata block group with a
398779bd3712SFilipe Manana  *    suitable profile (SINGLE profile in the example of the degraded mount of
398879bd3712SFilipe Manana  *    the RAID1 filesystem);
398979bd3712SFilipe Manana  *
399079bd3712SFilipe Manana  * 3) The task has reserved enough transaction units / metadata space, but when
399179bd3712SFilipe Manana  *    it attempts to COW an extent buffer from the extent or device btree for
399279bd3712SFilipe Manana  *    example, it does not find any free extent in any metadata block group,
399379bd3712SFilipe Manana  *    therefore forced to try to allocate a new metadata block group.
399479bd3712SFilipe Manana  *    This is because some other task allocated all available extents in the
399579bd3712SFilipe Manana  *    meanwhile - this typically happens with tasks that don't reserve space
399679bd3712SFilipe Manana  *    properly, either intentionally or as a bug. One example where this is
399779bd3712SFilipe Manana  *    done intentionally is fsync, as it does not reserve any transaction units
399879bd3712SFilipe Manana  *    and ends up allocating a variable number of metadata extents for log
3999ecd84d54SFilipe Manana  *    tree extent buffers;
4000ecd84d54SFilipe Manana  *
4001ecd84d54SFilipe Manana  * 4) The task has reserved enough transaction units / metadata space, but right
4002ecd84d54SFilipe Manana  *    before it tries to allocate the last extent buffer it needs, a discard
4003ecd84d54SFilipe Manana  *    operation comes in and, temporarily, removes the last free space entry from
4004ecd84d54SFilipe Manana  *    the only metadata block group that had free space (discard starts by
4005ecd84d54SFilipe Manana  *    removing a free space entry from a block group, then does the discard
4006ecd84d54SFilipe Manana  *    operation and, once it's done, it adds back the free space entry to the
4007ecd84d54SFilipe Manana  *    block group).
400879bd3712SFilipe Manana  *
400979bd3712SFilipe Manana  * We also need this 2 phases setup when adding a device to a filesystem with
401079bd3712SFilipe Manana  * a seed device - we must create new metadata and system chunks without adding
401179bd3712SFilipe Manana  * any of the block group items to the chunk, extent and device btrees. If we
401279bd3712SFilipe Manana  * did not do it this way, we would get ENOSPC when attempting to update those
401379bd3712SFilipe Manana  * btrees, since all the chunks from the seed device are read-only.
401479bd3712SFilipe Manana  *
401579bd3712SFilipe Manana  * Phase 1 does the updates and insertions to the chunk btree because if we had
401679bd3712SFilipe Manana  * it done in phase 2 and have a thundering herd of tasks allocating chunks in
401779bd3712SFilipe Manana  * parallel, we risk having too many system chunks allocated by many tasks if
401879bd3712SFilipe Manana  * many tasks reach phase 1 without the previous ones completing phase 2. In the
401979bd3712SFilipe Manana  * extreme case this leads to exhaustion of the system chunk array in the
402079bd3712SFilipe Manana  * superblock. This is easier to trigger if using a btree node/leaf size of 64K
402179bd3712SFilipe Manana  * and with RAID filesystems (so we have more device items in the chunk btree).
402279bd3712SFilipe Manana  * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
402379bd3712SFilipe Manana  * the system chunk array due to concurrent allocations") provides more details.
402479bd3712SFilipe Manana  *
40252bb2e00eSFilipe Manana  * Allocation of system chunks does not happen through this function. A task that
40262bb2e00eSFilipe Manana  * needs to update the chunk btree (the only btree that uses system chunks), must
40272bb2e00eSFilipe Manana  * preallocate chunk space by calling either check_system_chunk() or
40282bb2e00eSFilipe Manana  * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or
40292bb2e00eSFilipe Manana  * metadata chunk or when removing a chunk, while the later is used before doing
40302bb2e00eSFilipe Manana  * a modification to the chunk btree - use cases for the later are adding,
40312bb2e00eSFilipe Manana  * removing and resizing a device as well as relocation of a system chunk.
40322bb2e00eSFilipe Manana  * See the comment below for more details.
403379bd3712SFilipe Manana  *
403479bd3712SFilipe Manana  * The reservation of system space, done through check_system_chunk(), as well
403579bd3712SFilipe Manana  * as all the updates and insertions into the chunk btree must be done while
403679bd3712SFilipe Manana  * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
403779bd3712SFilipe Manana  * an extent buffer from the chunks btree we never trigger allocation of a new
403879bd3712SFilipe Manana  * system chunk, which would result in a deadlock (trying to lock twice an
403979bd3712SFilipe Manana  * extent buffer of the chunk btree, first time before triggering the chunk
404079bd3712SFilipe Manana  * allocation and the second time during chunk allocation while attempting to
404179bd3712SFilipe Manana  * update the chunks btree). The system chunk array is also updated while holding
404279bd3712SFilipe Manana  * that mutex. The same logic applies to removing chunks - we must reserve system
404379bd3712SFilipe Manana  * space, update the chunk btree and the system chunk array in the superblock
404479bd3712SFilipe Manana  * while holding fs_info->chunk_mutex.
404579bd3712SFilipe Manana  *
404679bd3712SFilipe Manana  * This function, btrfs_chunk_alloc(), belongs to phase 1.
404779bd3712SFilipe Manana  *
404879bd3712SFilipe Manana  * If @force is CHUNK_ALLOC_FORCE:
404907730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
405007730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
405179bd3712SFilipe Manana  * If @force is NOT CHUNK_ALLOC_FORCE:
405207730d87SJosef Bacik  *    - return 0 if it doesn't need to allocate a new chunk,
405307730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
405407730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
405507730d87SJosef Bacik  */
btrfs_chunk_alloc(struct btrfs_trans_handle * trans,u64 flags,enum btrfs_chunk_alloc_enum force)405607730d87SJosef Bacik int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
405707730d87SJosef Bacik 		      enum btrfs_chunk_alloc_enum force)
405807730d87SJosef Bacik {
405907730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
406007730d87SJosef Bacik 	struct btrfs_space_info *space_info;
4061820c363bSNaohiro Aota 	struct btrfs_block_group *ret_bg;
406207730d87SJosef Bacik 	bool wait_for_alloc = false;
406307730d87SJosef Bacik 	bool should_alloc = false;
4064760e69c4SNaohiro Aota 	bool from_extent_allocation = false;
406507730d87SJosef Bacik 	int ret = 0;
406607730d87SJosef Bacik 
4067760e69c4SNaohiro Aota 	if (force == CHUNK_ALLOC_FORCE_FOR_EXTENT) {
4068760e69c4SNaohiro Aota 		from_extent_allocation = true;
4069760e69c4SNaohiro Aota 		force = CHUNK_ALLOC_FORCE;
4070760e69c4SNaohiro Aota 	}
4071760e69c4SNaohiro Aota 
407207730d87SJosef Bacik 	/* Don't re-enter if we're already allocating a chunk */
407307730d87SJosef Bacik 	if (trans->allocating_chunk)
407407730d87SJosef Bacik 		return -ENOSPC;
407579bd3712SFilipe Manana 	/*
40762bb2e00eSFilipe Manana 	 * Allocation of system chunks can not happen through this path, as we
40772bb2e00eSFilipe Manana 	 * could end up in a deadlock if we are allocating a data or metadata
40782bb2e00eSFilipe Manana 	 * chunk and there is another task modifying the chunk btree.
40792bb2e00eSFilipe Manana 	 *
40802bb2e00eSFilipe Manana 	 * This is because while we are holding the chunk mutex, we will attempt
40812bb2e00eSFilipe Manana 	 * to add the new chunk item to the chunk btree or update an existing
40822bb2e00eSFilipe Manana 	 * device item in the chunk btree, while the other task that is modifying
40832bb2e00eSFilipe Manana 	 * the chunk btree is attempting to COW an extent buffer while holding a
40842bb2e00eSFilipe Manana 	 * lock on it and on its parent - if the COW operation triggers a system
40852bb2e00eSFilipe Manana 	 * chunk allocation, then we can deadlock because we are holding the
40862bb2e00eSFilipe Manana 	 * chunk mutex and we may need to access that extent buffer or its parent
40872bb2e00eSFilipe Manana 	 * in order to add the chunk item or update a device item.
40882bb2e00eSFilipe Manana 	 *
40892bb2e00eSFilipe Manana 	 * Tasks that want to modify the chunk tree should reserve system space
40902bb2e00eSFilipe Manana 	 * before updating the chunk btree, by calling either
40912bb2e00eSFilipe Manana 	 * btrfs_reserve_chunk_metadata() or check_system_chunk().
40922bb2e00eSFilipe Manana 	 * It's possible that after a task reserves the space, it still ends up
40932bb2e00eSFilipe Manana 	 * here - this happens in the cases described above at do_chunk_alloc().
40942bb2e00eSFilipe Manana 	 * The task will have to either retry or fail.
409579bd3712SFilipe Manana 	 */
40962bb2e00eSFilipe Manana 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
409779bd3712SFilipe Manana 		return -ENOSPC;
409807730d87SJosef Bacik 
409907730d87SJosef Bacik 	space_info = btrfs_find_space_info(fs_info, flags);
410007730d87SJosef Bacik 	ASSERT(space_info);
410107730d87SJosef Bacik 
410207730d87SJosef Bacik 	do {
410307730d87SJosef Bacik 		spin_lock(&space_info->lock);
410407730d87SJosef Bacik 		if (force < space_info->force_alloc)
410507730d87SJosef Bacik 			force = space_info->force_alloc;
410607730d87SJosef Bacik 		should_alloc = should_alloc_chunk(fs_info, space_info, force);
410707730d87SJosef Bacik 		if (space_info->full) {
410807730d87SJosef Bacik 			/* No more free physical space */
410907730d87SJosef Bacik 			if (should_alloc)
411007730d87SJosef Bacik 				ret = -ENOSPC;
411107730d87SJosef Bacik 			else
411207730d87SJosef Bacik 				ret = 0;
411307730d87SJosef Bacik 			spin_unlock(&space_info->lock);
411407730d87SJosef Bacik 			return ret;
411507730d87SJosef Bacik 		} else if (!should_alloc) {
411607730d87SJosef Bacik 			spin_unlock(&space_info->lock);
411707730d87SJosef Bacik 			return 0;
411807730d87SJosef Bacik 		} else if (space_info->chunk_alloc) {
411907730d87SJosef Bacik 			/*
412007730d87SJosef Bacik 			 * Someone is already allocating, so we need to block
412107730d87SJosef Bacik 			 * until this someone is finished and then loop to
412207730d87SJosef Bacik 			 * recheck if we should continue with our allocation
412307730d87SJosef Bacik 			 * attempt.
412407730d87SJosef Bacik 			 */
412507730d87SJosef Bacik 			wait_for_alloc = true;
41261314ca78SJosef Bacik 			force = CHUNK_ALLOC_NO_FORCE;
412707730d87SJosef Bacik 			spin_unlock(&space_info->lock);
412807730d87SJosef Bacik 			mutex_lock(&fs_info->chunk_mutex);
412907730d87SJosef Bacik 			mutex_unlock(&fs_info->chunk_mutex);
413007730d87SJosef Bacik 		} else {
413107730d87SJosef Bacik 			/* Proceed with allocation */
413207730d87SJosef Bacik 			space_info->chunk_alloc = 1;
413307730d87SJosef Bacik 			wait_for_alloc = false;
413407730d87SJosef Bacik 			spin_unlock(&space_info->lock);
413507730d87SJosef Bacik 		}
413607730d87SJosef Bacik 
413707730d87SJosef Bacik 		cond_resched();
413807730d87SJosef Bacik 	} while (wait_for_alloc);
413907730d87SJosef Bacik 
414007730d87SJosef Bacik 	mutex_lock(&fs_info->chunk_mutex);
414107730d87SJosef Bacik 	trans->allocating_chunk = true;
414207730d87SJosef Bacik 
414307730d87SJosef Bacik 	/*
414407730d87SJosef Bacik 	 * If we have mixed data/metadata chunks we want to make sure we keep
414507730d87SJosef Bacik 	 * allocating mixed chunks instead of individual chunks.
414607730d87SJosef Bacik 	 */
414707730d87SJosef Bacik 	if (btrfs_mixed_space_info(space_info))
414807730d87SJosef Bacik 		flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
414907730d87SJosef Bacik 
415007730d87SJosef Bacik 	/*
415107730d87SJosef Bacik 	 * if we're doing a data chunk, go ahead and make sure that
415207730d87SJosef Bacik 	 * we keep a reasonable number of metadata chunks allocated in the
415307730d87SJosef Bacik 	 * FS as well.
415407730d87SJosef Bacik 	 */
415507730d87SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
415607730d87SJosef Bacik 		fs_info->data_chunk_allocations++;
415707730d87SJosef Bacik 		if (!(fs_info->data_chunk_allocations %
415807730d87SJosef Bacik 		      fs_info->metadata_ratio))
415907730d87SJosef Bacik 			force_metadata_allocation(fs_info);
416007730d87SJosef Bacik 	}
416107730d87SJosef Bacik 
4162820c363bSNaohiro Aota 	ret_bg = do_chunk_alloc(trans, flags);
416307730d87SJosef Bacik 	trans->allocating_chunk = false;
416407730d87SJosef Bacik 
4165760e69c4SNaohiro Aota 	if (IS_ERR(ret_bg)) {
4166820c363bSNaohiro Aota 		ret = PTR_ERR(ret_bg);
41675a7d107eSNaohiro Aota 	} else if (from_extent_allocation && (flags & BTRFS_BLOCK_GROUP_DATA)) {
4168760e69c4SNaohiro Aota 		/*
4169760e69c4SNaohiro Aota 		 * New block group is likely to be used soon. Try to activate
4170760e69c4SNaohiro Aota 		 * it now. Failure is OK for now.
4171760e69c4SNaohiro Aota 		 */
4172760e69c4SNaohiro Aota 		btrfs_zone_activate(ret_bg);
4173760e69c4SNaohiro Aota 	}
4174760e69c4SNaohiro Aota 
4175760e69c4SNaohiro Aota 	if (!ret)
4176820c363bSNaohiro Aota 		btrfs_put_block_group(ret_bg);
4177820c363bSNaohiro Aota 
417807730d87SJosef Bacik 	spin_lock(&space_info->lock);
417907730d87SJosef Bacik 	if (ret < 0) {
418007730d87SJosef Bacik 		if (ret == -ENOSPC)
418107730d87SJosef Bacik 			space_info->full = 1;
418207730d87SJosef Bacik 		else
418307730d87SJosef Bacik 			goto out;
418407730d87SJosef Bacik 	} else {
418507730d87SJosef Bacik 		ret = 1;
418607730d87SJosef Bacik 		space_info->max_extent_size = 0;
418707730d87SJosef Bacik 	}
418807730d87SJosef Bacik 
418907730d87SJosef Bacik 	space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
419007730d87SJosef Bacik out:
419107730d87SJosef Bacik 	space_info->chunk_alloc = 0;
419207730d87SJosef Bacik 	spin_unlock(&space_info->lock);
419307730d87SJosef Bacik 	mutex_unlock(&fs_info->chunk_mutex);
419407730d87SJosef Bacik 
419507730d87SJosef Bacik 	return ret;
419607730d87SJosef Bacik }
419707730d87SJosef Bacik 
get_profile_num_devs(struct btrfs_fs_info * fs_info,u64 type)419807730d87SJosef Bacik static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
419907730d87SJosef Bacik {
420007730d87SJosef Bacik 	u64 num_dev;
420107730d87SJosef Bacik 
420207730d87SJosef Bacik 	num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
420307730d87SJosef Bacik 	if (!num_dev)
420407730d87SJosef Bacik 		num_dev = fs_info->fs_devices->rw_devices;
420507730d87SJosef Bacik 
420607730d87SJosef Bacik 	return num_dev;
420707730d87SJosef Bacik }
420807730d87SJosef Bacik 
reserve_chunk_space(struct btrfs_trans_handle * trans,u64 bytes,u64 type)42092bb2e00eSFilipe Manana static void reserve_chunk_space(struct btrfs_trans_handle *trans,
42102bb2e00eSFilipe Manana 				u64 bytes,
42112bb2e00eSFilipe Manana 				u64 type)
421207730d87SJosef Bacik {
421307730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
421407730d87SJosef Bacik 	struct btrfs_space_info *info;
421507730d87SJosef Bacik 	u64 left;
421607730d87SJosef Bacik 	int ret = 0;
421707730d87SJosef Bacik 
421807730d87SJosef Bacik 	/*
421907730d87SJosef Bacik 	 * Needed because we can end up allocating a system chunk and for an
422007730d87SJosef Bacik 	 * atomic and race free space reservation in the chunk block reserve.
422107730d87SJosef Bacik 	 */
422207730d87SJosef Bacik 	lockdep_assert_held(&fs_info->chunk_mutex);
422307730d87SJosef Bacik 
422407730d87SJosef Bacik 	info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
422507730d87SJosef Bacik 	spin_lock(&info->lock);
422607730d87SJosef Bacik 	left = info->total_bytes - btrfs_space_info_used(info, true);
422707730d87SJosef Bacik 	spin_unlock(&info->lock);
422807730d87SJosef Bacik 
42292bb2e00eSFilipe Manana 	if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
423007730d87SJosef Bacik 		btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
42312bb2e00eSFilipe Manana 			   left, bytes, type);
423207730d87SJosef Bacik 		btrfs_dump_space_info(fs_info, info, 0, 0);
423307730d87SJosef Bacik 	}
423407730d87SJosef Bacik 
42352bb2e00eSFilipe Manana 	if (left < bytes) {
423607730d87SJosef Bacik 		u64 flags = btrfs_system_alloc_profile(fs_info);
423779bd3712SFilipe Manana 		struct btrfs_block_group *bg;
423807730d87SJosef Bacik 
423907730d87SJosef Bacik 		/*
424007730d87SJosef Bacik 		 * Ignore failure to create system chunk. We might end up not
424107730d87SJosef Bacik 		 * needing it, as we might not need to COW all nodes/leafs from
424207730d87SJosef Bacik 		 * the paths we visit in the chunk tree (they were already COWed
424307730d87SJosef Bacik 		 * or created in the current transaction for example).
424407730d87SJosef Bacik 		 */
4245f6f39f7aSNikolay Borisov 		bg = btrfs_create_chunk(trans, flags);
424679bd3712SFilipe Manana 		if (IS_ERR(bg)) {
424779bd3712SFilipe Manana 			ret = PTR_ERR(bg);
42482bb2e00eSFilipe Manana 		} else {
424979bd3712SFilipe Manana 			/*
4250b6a98021SNaohiro Aota 			 * We have a new chunk. We also need to activate it for
4251b6a98021SNaohiro Aota 			 * zoned filesystem.
4252b6a98021SNaohiro Aota 			 */
4253b6a98021SNaohiro Aota 			ret = btrfs_zoned_activate_one_bg(fs_info, info, true);
4254b6a98021SNaohiro Aota 			if (ret < 0)
4255b6a98021SNaohiro Aota 				return;
4256b6a98021SNaohiro Aota 
4257b6a98021SNaohiro Aota 			/*
425879bd3712SFilipe Manana 			 * If we fail to add the chunk item here, we end up
425979bd3712SFilipe Manana 			 * trying again at phase 2 of chunk allocation, at
426079bd3712SFilipe Manana 			 * btrfs_create_pending_block_groups(). So ignore
42612bb2e00eSFilipe Manana 			 * any error here. An ENOSPC here could happen, due to
42622bb2e00eSFilipe Manana 			 * the cases described at do_chunk_alloc() - the system
42632bb2e00eSFilipe Manana 			 * block group we just created was just turned into RO
42642bb2e00eSFilipe Manana 			 * mode by a scrub for example, or a running discard
42652bb2e00eSFilipe Manana 			 * temporarily removed its free space entries, etc.
426679bd3712SFilipe Manana 			 */
426779bd3712SFilipe Manana 			btrfs_chunk_alloc_add_chunk_item(trans, bg);
426879bd3712SFilipe Manana 		}
426907730d87SJosef Bacik 	}
427007730d87SJosef Bacik 
427107730d87SJosef Bacik 	if (!ret) {
42729270501cSJosef Bacik 		ret = btrfs_block_rsv_add(fs_info,
427307730d87SJosef Bacik 					  &fs_info->chunk_block_rsv,
42742bb2e00eSFilipe Manana 					  bytes, BTRFS_RESERVE_NO_FLUSH);
42751cb3db1cSFilipe Manana 		if (!ret)
42762bb2e00eSFilipe Manana 			trans->chunk_bytes_reserved += bytes;
427707730d87SJosef Bacik 	}
427807730d87SJosef Bacik }
427907730d87SJosef Bacik 
42802bb2e00eSFilipe Manana /*
42812bb2e00eSFilipe Manana  * Reserve space in the system space for allocating or removing a chunk.
42822bb2e00eSFilipe Manana  * The caller must be holding fs_info->chunk_mutex.
42832bb2e00eSFilipe Manana  */
check_system_chunk(struct btrfs_trans_handle * trans,u64 type)42842bb2e00eSFilipe Manana void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
42852bb2e00eSFilipe Manana {
42862bb2e00eSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
42872bb2e00eSFilipe Manana 	const u64 num_devs = get_profile_num_devs(fs_info, type);
42882bb2e00eSFilipe Manana 	u64 bytes;
42892bb2e00eSFilipe Manana 
42902bb2e00eSFilipe Manana 	/* num_devs device items to update and 1 chunk item to add or remove. */
42912bb2e00eSFilipe Manana 	bytes = btrfs_calc_metadata_size(fs_info, num_devs) +
42922bb2e00eSFilipe Manana 		btrfs_calc_insert_metadata_size(fs_info, 1);
42932bb2e00eSFilipe Manana 
42942bb2e00eSFilipe Manana 	reserve_chunk_space(trans, bytes, type);
42952bb2e00eSFilipe Manana }
42962bb2e00eSFilipe Manana 
42972bb2e00eSFilipe Manana /*
42982bb2e00eSFilipe Manana  * Reserve space in the system space, if needed, for doing a modification to the
42992bb2e00eSFilipe Manana  * chunk btree.
43002bb2e00eSFilipe Manana  *
43012bb2e00eSFilipe Manana  * @trans:		A transaction handle.
43022bb2e00eSFilipe Manana  * @is_item_insertion:	Indicate if the modification is for inserting a new item
43032bb2e00eSFilipe Manana  *			in the chunk btree or if it's for the deletion or update
43042bb2e00eSFilipe Manana  *			of an existing item.
43052bb2e00eSFilipe Manana  *
43062bb2e00eSFilipe Manana  * This is used in a context where we need to update the chunk btree outside
43072bb2e00eSFilipe Manana  * block group allocation and removal, to avoid a deadlock with a concurrent
43082bb2e00eSFilipe Manana  * task that is allocating a metadata or data block group and therefore needs to
43092bb2e00eSFilipe Manana  * update the chunk btree while holding the chunk mutex. After the update to the
43102bb2e00eSFilipe Manana  * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called.
43112bb2e00eSFilipe Manana  *
43122bb2e00eSFilipe Manana  */
btrfs_reserve_chunk_metadata(struct btrfs_trans_handle * trans,bool is_item_insertion)43132bb2e00eSFilipe Manana void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans,
43142bb2e00eSFilipe Manana 				  bool is_item_insertion)
43152bb2e00eSFilipe Manana {
43162bb2e00eSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
43172bb2e00eSFilipe Manana 	u64 bytes;
43182bb2e00eSFilipe Manana 
43192bb2e00eSFilipe Manana 	if (is_item_insertion)
43202bb2e00eSFilipe Manana 		bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
43212bb2e00eSFilipe Manana 	else
43222bb2e00eSFilipe Manana 		bytes = btrfs_calc_metadata_size(fs_info, 1);
43232bb2e00eSFilipe Manana 
43242bb2e00eSFilipe Manana 	mutex_lock(&fs_info->chunk_mutex);
43252bb2e00eSFilipe Manana 	reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM);
43262bb2e00eSFilipe Manana 	mutex_unlock(&fs_info->chunk_mutex);
43272bb2e00eSFilipe Manana }
43282bb2e00eSFilipe Manana 
btrfs_put_block_group_cache(struct btrfs_fs_info * info)43293e43c279SJosef Bacik void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
43303e43c279SJosef Bacik {
433132da5386SDavid Sterba 	struct btrfs_block_group *block_group;
43323e43c279SJosef Bacik 
433350c31eaaSJosef Bacik 	block_group = btrfs_lookup_first_block_group(info, 0);
43343e43c279SJosef Bacik 	while (block_group) {
43353e43c279SJosef Bacik 		btrfs_wait_block_group_cache_done(block_group);
43363e43c279SJosef Bacik 		spin_lock(&block_group->lock);
433750c31eaaSJosef Bacik 		if (test_and_clear_bit(BLOCK_GROUP_FLAG_IREF,
433850c31eaaSJosef Bacik 				       &block_group->runtime_flags)) {
433950c31eaaSJosef Bacik 			struct inode *inode = block_group->inode;
43403e43c279SJosef Bacik 
43413e43c279SJosef Bacik 			block_group->inode = NULL;
43423e43c279SJosef Bacik 			spin_unlock(&block_group->lock);
434350c31eaaSJosef Bacik 
43443e43c279SJosef Bacik 			ASSERT(block_group->io_ctl.inode == NULL);
43453e43c279SJosef Bacik 			iput(inode);
434650c31eaaSJosef Bacik 		} else {
434750c31eaaSJosef Bacik 			spin_unlock(&block_group->lock);
434850c31eaaSJosef Bacik 		}
434950c31eaaSJosef Bacik 		block_group = btrfs_next_block_group(block_group);
43503e43c279SJosef Bacik 	}
43513e43c279SJosef Bacik }
43523e43c279SJosef Bacik 
43533e43c279SJosef Bacik /*
43543e43c279SJosef Bacik  * Must be called only after stopping all workers, since we could have block
43553e43c279SJosef Bacik  * group caching kthreads running, and therefore they could race with us if we
43563e43c279SJosef Bacik  * freed the block groups before stopping them.
43573e43c279SJosef Bacik  */
btrfs_free_block_groups(struct btrfs_fs_info * info)43583e43c279SJosef Bacik int btrfs_free_block_groups(struct btrfs_fs_info *info)
43593e43c279SJosef Bacik {
436032da5386SDavid Sterba 	struct btrfs_block_group *block_group;
43613e43c279SJosef Bacik 	struct btrfs_space_info *space_info;
43623e43c279SJosef Bacik 	struct btrfs_caching_control *caching_ctl;
43633e43c279SJosef Bacik 	struct rb_node *n;
43643e43c279SJosef Bacik 
436513bb483dSNaohiro Aota 	if (btrfs_is_zoned(info)) {
436613bb483dSNaohiro Aota 		if (info->active_meta_bg) {
436713bb483dSNaohiro Aota 			btrfs_put_block_group(info->active_meta_bg);
436813bb483dSNaohiro Aota 			info->active_meta_bg = NULL;
436913bb483dSNaohiro Aota 		}
437013bb483dSNaohiro Aota 		if (info->active_system_bg) {
437113bb483dSNaohiro Aota 			btrfs_put_block_group(info->active_system_bg);
437213bb483dSNaohiro Aota 			info->active_system_bg = NULL;
437313bb483dSNaohiro Aota 		}
437413bb483dSNaohiro Aota 	}
437513bb483dSNaohiro Aota 
437616b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
43773e43c279SJosef Bacik 	while (!list_empty(&info->caching_block_groups)) {
43783e43c279SJosef Bacik 		caching_ctl = list_entry(info->caching_block_groups.next,
43793e43c279SJosef Bacik 					 struct btrfs_caching_control, list);
43803e43c279SJosef Bacik 		list_del(&caching_ctl->list);
43813e43c279SJosef Bacik 		btrfs_put_caching_control(caching_ctl);
43823e43c279SJosef Bacik 	}
438316b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
43843e43c279SJosef Bacik 
43853e43c279SJosef Bacik 	spin_lock(&info->unused_bgs_lock);
43863e43c279SJosef Bacik 	while (!list_empty(&info->unused_bgs)) {
43873e43c279SJosef Bacik 		block_group = list_first_entry(&info->unused_bgs,
438832da5386SDavid Sterba 					       struct btrfs_block_group,
43893e43c279SJosef Bacik 					       bg_list);
43903e43c279SJosef Bacik 		list_del_init(&block_group->bg_list);
43913e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
43923e43c279SJosef Bacik 	}
43933e43c279SJosef Bacik 
439418bb8bbfSJohannes Thumshirn 	while (!list_empty(&info->reclaim_bgs)) {
439518bb8bbfSJohannes Thumshirn 		block_group = list_first_entry(&info->reclaim_bgs,
439618bb8bbfSJohannes Thumshirn 					       struct btrfs_block_group,
439718bb8bbfSJohannes Thumshirn 					       bg_list);
439818bb8bbfSJohannes Thumshirn 		list_del_init(&block_group->bg_list);
439918bb8bbfSJohannes Thumshirn 		btrfs_put_block_group(block_group);
440018bb8bbfSJohannes Thumshirn 	}
440118bb8bbfSJohannes Thumshirn 	spin_unlock(&info->unused_bgs_lock);
440218bb8bbfSJohannes Thumshirn 
4403afba2bc0SNaohiro Aota 	spin_lock(&info->zone_active_bgs_lock);
4404afba2bc0SNaohiro Aota 	while (!list_empty(&info->zone_active_bgs)) {
4405afba2bc0SNaohiro Aota 		block_group = list_first_entry(&info->zone_active_bgs,
4406afba2bc0SNaohiro Aota 					       struct btrfs_block_group,
4407afba2bc0SNaohiro Aota 					       active_bg_list);
4408afba2bc0SNaohiro Aota 		list_del_init(&block_group->active_bg_list);
4409afba2bc0SNaohiro Aota 		btrfs_put_block_group(block_group);
4410afba2bc0SNaohiro Aota 	}
4411afba2bc0SNaohiro Aota 	spin_unlock(&info->zone_active_bgs_lock);
4412afba2bc0SNaohiro Aota 
441316b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
441408dddb29SFilipe Manana 	while ((n = rb_last(&info->block_group_cache_tree.rb_root)) != NULL) {
441532da5386SDavid Sterba 		block_group = rb_entry(n, struct btrfs_block_group,
44163e43c279SJosef Bacik 				       cache_node);
441708dddb29SFilipe Manana 		rb_erase_cached(&block_group->cache_node,
44183e43c279SJosef Bacik 				&info->block_group_cache_tree);
44193e43c279SJosef Bacik 		RB_CLEAR_NODE(&block_group->cache_node);
442016b0c258SFilipe Manana 		write_unlock(&info->block_group_cache_lock);
44213e43c279SJosef Bacik 
44223e43c279SJosef Bacik 		down_write(&block_group->space_info->groups_sem);
44233e43c279SJosef Bacik 		list_del(&block_group->list);
44243e43c279SJosef Bacik 		up_write(&block_group->space_info->groups_sem);
44253e43c279SJosef Bacik 
44263e43c279SJosef Bacik 		/*
44273e43c279SJosef Bacik 		 * We haven't cached this block group, which means we could
44283e43c279SJosef Bacik 		 * possibly have excluded extents on this block group.
44293e43c279SJosef Bacik 		 */
44303e43c279SJosef Bacik 		if (block_group->cached == BTRFS_CACHE_NO ||
44313e43c279SJosef Bacik 		    block_group->cached == BTRFS_CACHE_ERROR)
44323e43c279SJosef Bacik 			btrfs_free_excluded_extents(block_group);
44333e43c279SJosef Bacik 
44343e43c279SJosef Bacik 		btrfs_remove_free_space_cache(block_group);
44353e43c279SJosef Bacik 		ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
44363e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->dirty_list));
44373e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->io_list));
44383e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->bg_list));
443948aaeebeSJosef Bacik 		ASSERT(refcount_read(&block_group->refs) == 1);
4440195a49eaSFilipe Manana 		ASSERT(block_group->swap_extents == 0);
44413e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
44423e43c279SJosef Bacik 
444316b0c258SFilipe Manana 		write_lock(&info->block_group_cache_lock);
44443e43c279SJosef Bacik 	}
444516b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
44463e43c279SJosef Bacik 
44473e43c279SJosef Bacik 	btrfs_release_global_block_rsv(info);
44483e43c279SJosef Bacik 
44493e43c279SJosef Bacik 	while (!list_empty(&info->space_info)) {
44503e43c279SJosef Bacik 		space_info = list_entry(info->space_info.next,
44513e43c279SJosef Bacik 					struct btrfs_space_info,
44523e43c279SJosef Bacik 					list);
44533e43c279SJosef Bacik 
44543e43c279SJosef Bacik 		/*
44553e43c279SJosef Bacik 		 * Do not hide this behind enospc_debug, this is actually
44563e43c279SJosef Bacik 		 * important and indicates a real bug if this happens.
44573e43c279SJosef Bacik 		 */
44583e43c279SJosef Bacik 		if (WARN_ON(space_info->bytes_pinned > 0 ||
44593e43c279SJosef Bacik 			    space_info->bytes_may_use > 0))
44603e43c279SJosef Bacik 			btrfs_dump_space_info(info, space_info, 0, 0);
446140cdc509SFilipe Manana 
446240cdc509SFilipe Manana 		/*
446340cdc509SFilipe Manana 		 * If there was a failure to cleanup a log tree, very likely due
446440cdc509SFilipe Manana 		 * to an IO failure on a writeback attempt of one or more of its
446540cdc509SFilipe Manana 		 * extent buffers, we could not do proper (and cheap) unaccounting
446640cdc509SFilipe Manana 		 * of their reserved space, so don't warn on bytes_reserved > 0 in
446740cdc509SFilipe Manana 		 * that case.
446840cdc509SFilipe Manana 		 */
446940cdc509SFilipe Manana 		if (!(space_info->flags & BTRFS_BLOCK_GROUP_METADATA) ||
447040cdc509SFilipe Manana 		    !BTRFS_FS_LOG_CLEANUP_ERROR(info)) {
447140cdc509SFilipe Manana 			if (WARN_ON(space_info->bytes_reserved > 0))
447240cdc509SFilipe Manana 				btrfs_dump_space_info(info, space_info, 0, 0);
447340cdc509SFilipe Manana 		}
447440cdc509SFilipe Manana 
4475d611add4SFilipe Manana 		WARN_ON(space_info->reclaim_size > 0);
44763e43c279SJosef Bacik 		list_del(&space_info->list);
44773e43c279SJosef Bacik 		btrfs_sysfs_remove_space_info(space_info);
44783e43c279SJosef Bacik 	}
44793e43c279SJosef Bacik 	return 0;
44803e43c279SJosef Bacik }
4481684b752bSFilipe Manana 
btrfs_freeze_block_group(struct btrfs_block_group * cache)4482684b752bSFilipe Manana void btrfs_freeze_block_group(struct btrfs_block_group *cache)
4483684b752bSFilipe Manana {
4484684b752bSFilipe Manana 	atomic_inc(&cache->frozen);
4485684b752bSFilipe Manana }
4486684b752bSFilipe Manana 
btrfs_unfreeze_block_group(struct btrfs_block_group * block_group)4487684b752bSFilipe Manana void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
4488684b752bSFilipe Manana {
4489684b752bSFilipe Manana 	struct btrfs_fs_info *fs_info = block_group->fs_info;
4490684b752bSFilipe Manana 	struct extent_map_tree *em_tree;
4491684b752bSFilipe Manana 	struct extent_map *em;
4492684b752bSFilipe Manana 	bool cleanup;
4493684b752bSFilipe Manana 
4494684b752bSFilipe Manana 	spin_lock(&block_group->lock);
4495684b752bSFilipe Manana 	cleanup = (atomic_dec_and_test(&block_group->frozen) &&
44963349b57fSJosef Bacik 		   test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags));
4497684b752bSFilipe Manana 	spin_unlock(&block_group->lock);
4498684b752bSFilipe Manana 
4499684b752bSFilipe Manana 	if (cleanup) {
4500684b752bSFilipe Manana 		em_tree = &fs_info->mapping_tree;
4501684b752bSFilipe Manana 		write_lock(&em_tree->lock);
4502684b752bSFilipe Manana 		em = lookup_extent_mapping(em_tree, block_group->start,
4503684b752bSFilipe Manana 					   1);
4504684b752bSFilipe Manana 		BUG_ON(!em); /* logic error, can't happen */
4505684b752bSFilipe Manana 		remove_extent_mapping(em_tree, em);
4506684b752bSFilipe Manana 		write_unlock(&em_tree->lock);
4507684b752bSFilipe Manana 
4508684b752bSFilipe Manana 		/* once for us and once for the tree */
4509684b752bSFilipe Manana 		free_extent_map(em);
4510684b752bSFilipe Manana 		free_extent_map(em);
4511684b752bSFilipe Manana 
4512684b752bSFilipe Manana 		/*
4513684b752bSFilipe Manana 		 * We may have left one free space entry and other possible
4514684b752bSFilipe Manana 		 * tasks trimming this block group have left 1 entry each one.
4515684b752bSFilipe Manana 		 * Free them if any.
4516684b752bSFilipe Manana 		 */
4517fc80f7acSJosef Bacik 		btrfs_remove_free_space_cache(block_group);
4518684b752bSFilipe Manana 	}
4519684b752bSFilipe Manana }
4520195a49eaSFilipe Manana 
btrfs_inc_block_group_swap_extents(struct btrfs_block_group * bg)4521195a49eaSFilipe Manana bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
4522195a49eaSFilipe Manana {
4523195a49eaSFilipe Manana 	bool ret = true;
4524195a49eaSFilipe Manana 
4525195a49eaSFilipe Manana 	spin_lock(&bg->lock);
4526195a49eaSFilipe Manana 	if (bg->ro)
4527195a49eaSFilipe Manana 		ret = false;
4528195a49eaSFilipe Manana 	else
4529195a49eaSFilipe Manana 		bg->swap_extents++;
4530195a49eaSFilipe Manana 	spin_unlock(&bg->lock);
4531195a49eaSFilipe Manana 
4532195a49eaSFilipe Manana 	return ret;
4533195a49eaSFilipe Manana }
4534195a49eaSFilipe Manana 
btrfs_dec_block_group_swap_extents(struct btrfs_block_group * bg,int amount)4535195a49eaSFilipe Manana void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
4536195a49eaSFilipe Manana {
4537195a49eaSFilipe Manana 	spin_lock(&bg->lock);
4538195a49eaSFilipe Manana 	ASSERT(!bg->ro);
4539195a49eaSFilipe Manana 	ASSERT(bg->swap_extents >= amount);
4540195a49eaSFilipe Manana 	bg->swap_extents -= amount;
4541195a49eaSFilipe Manana 	spin_unlock(&bg->lock);
4542195a49eaSFilipe Manana }
454352bb7a21SBoris Burkov 
btrfs_calc_block_group_size_class(u64 size)454452bb7a21SBoris Burkov enum btrfs_block_group_size_class btrfs_calc_block_group_size_class(u64 size)
454552bb7a21SBoris Burkov {
454652bb7a21SBoris Burkov 	if (size <= SZ_128K)
454752bb7a21SBoris Burkov 		return BTRFS_BG_SZ_SMALL;
454852bb7a21SBoris Burkov 	if (size <= SZ_8M)
454952bb7a21SBoris Burkov 		return BTRFS_BG_SZ_MEDIUM;
455052bb7a21SBoris Burkov 	return BTRFS_BG_SZ_LARGE;
455152bb7a21SBoris Burkov }
455252bb7a21SBoris Burkov 
455352bb7a21SBoris Burkov /*
455452bb7a21SBoris Burkov  * Handle a block group allocating an extent in a size class
455552bb7a21SBoris Burkov  *
455652bb7a21SBoris Burkov  * @bg:				The block group we allocated in.
455752bb7a21SBoris Burkov  * @size_class:			The size class of the allocation.
455852bb7a21SBoris Burkov  * @force_wrong_size_class:	Whether we are desperate enough to allow
455952bb7a21SBoris Burkov  *				mismatched size classes.
456052bb7a21SBoris Burkov  *
456152bb7a21SBoris Burkov  * Returns: 0 if the size class was valid for this block_group, -EAGAIN in the
456252bb7a21SBoris Burkov  * case of a race that leads to the wrong size class without
456352bb7a21SBoris Burkov  * force_wrong_size_class set.
456452bb7a21SBoris Burkov  *
456552bb7a21SBoris Burkov  * find_free_extent will skip block groups with a mismatched size class until
456652bb7a21SBoris Burkov  * it really needs to avoid ENOSPC. In that case it will set
456752bb7a21SBoris Burkov  * force_wrong_size_class. However, if a block group is newly allocated and
456852bb7a21SBoris Burkov  * doesn't yet have a size class, then it is possible for two allocations of
456952bb7a21SBoris Burkov  * different sizes to race and both try to use it. The loser is caught here and
457052bb7a21SBoris Burkov  * has to retry.
457152bb7a21SBoris Burkov  */
btrfs_use_block_group_size_class(struct btrfs_block_group * bg,enum btrfs_block_group_size_class size_class,bool force_wrong_size_class)457252bb7a21SBoris Burkov int btrfs_use_block_group_size_class(struct btrfs_block_group *bg,
457352bb7a21SBoris Burkov 				     enum btrfs_block_group_size_class size_class,
457452bb7a21SBoris Burkov 				     bool force_wrong_size_class)
457552bb7a21SBoris Burkov {
457652bb7a21SBoris Burkov 	ASSERT(size_class != BTRFS_BG_SZ_NONE);
457752bb7a21SBoris Burkov 
457852bb7a21SBoris Burkov 	/* The new allocation is in the right size class, do nothing */
457952bb7a21SBoris Burkov 	if (bg->size_class == size_class)
458052bb7a21SBoris Burkov 		return 0;
458152bb7a21SBoris Burkov 	/*
458252bb7a21SBoris Burkov 	 * The new allocation is in a mismatched size class.
458352bb7a21SBoris Burkov 	 * This means one of two things:
458452bb7a21SBoris Burkov 	 *
458552bb7a21SBoris Burkov 	 * 1. Two tasks in find_free_extent for different size_classes raced
458652bb7a21SBoris Burkov 	 *    and hit the same empty block_group. Make the loser try again.
458752bb7a21SBoris Burkov 	 * 2. A call to find_free_extent got desperate enough to set
458852bb7a21SBoris Burkov 	 *    'force_wrong_slab'. Don't change the size_class, but allow the
458952bb7a21SBoris Burkov 	 *    allocation.
459052bb7a21SBoris Burkov 	 */
459152bb7a21SBoris Burkov 	if (bg->size_class != BTRFS_BG_SZ_NONE) {
459252bb7a21SBoris Burkov 		if (force_wrong_size_class)
459352bb7a21SBoris Burkov 			return 0;
459452bb7a21SBoris Burkov 		return -EAGAIN;
459552bb7a21SBoris Burkov 	}
459652bb7a21SBoris Burkov 	/*
459752bb7a21SBoris Burkov 	 * The happy new block group case: the new allocation is the first
459852bb7a21SBoris Burkov 	 * one in the block_group so we set size_class.
459952bb7a21SBoris Burkov 	 */
460052bb7a21SBoris Burkov 	bg->size_class = size_class;
460152bb7a21SBoris Burkov 
460252bb7a21SBoris Burkov 	return 0;
460352bb7a21SBoris Burkov }
4604cb0922f2SBoris Burkov 
btrfs_block_group_should_use_size_class(struct btrfs_block_group * bg)4605cb0922f2SBoris Burkov bool btrfs_block_group_should_use_size_class(struct btrfs_block_group *bg)
4606cb0922f2SBoris Burkov {
4607cb0922f2SBoris Burkov 	if (btrfs_is_zoned(bg->fs_info))
4608cb0922f2SBoris Burkov 		return false;
4609cb0922f2SBoris Burkov 	if (!btrfs_is_block_group_data_only(bg))
4610cb0922f2SBoris Burkov 		return false;
4611cb0922f2SBoris Burkov 	return true;
4612cb0922f2SBoris Burkov }
4613