xref: /linux/fs/btrfs/block-group.c (revision c7eec3d9aa955cbd00470f874f34bdba946bd101)
12e405ad8SJosef Bacik // SPDX-License-Identifier: GPL-2.0
22e405ad8SJosef Bacik 
352bb7a21SBoris Burkov #include <linux/sizes.h>
42ca0ec77SJohannes Thumshirn #include <linux/list_sort.h>
5784352feSDavid Sterba #include "misc.h"
62e405ad8SJosef Bacik #include "ctree.h"
72e405ad8SJosef Bacik #include "block-group.h"
83eeb3226SJosef Bacik #include "space-info.h"
99f21246dSJosef Bacik #include "disk-io.h"
109f21246dSJosef Bacik #include "free-space-cache.h"
119f21246dSJosef Bacik #include "free-space-tree.h"
12e3e0520bSJosef Bacik #include "volumes.h"
13e3e0520bSJosef Bacik #include "transaction.h"
14e3e0520bSJosef Bacik #include "ref-verify.h"
154358d963SJosef Bacik #include "sysfs.h"
164358d963SJosef Bacik #include "tree-log.h"
1777745c05SJosef Bacik #include "delalloc-space.h"
18b0643e59SDennis Zhou #include "discard.h"
1996a14336SNikolay Borisov #include "raid56.h"
2008e11a3dSNaohiro Aota #include "zoned.h"
21c7f13d42SJosef Bacik #include "fs.h"
2207e81dc9SJosef Bacik #include "accessors.h"
23a0231804SJosef Bacik #include "extent-tree.h"
242e405ad8SJosef Bacik 
2506d61cb1SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2606d61cb1SJosef Bacik int btrfs_should_fragment_free_space(struct btrfs_block_group *block_group)
2706d61cb1SJosef Bacik {
2806d61cb1SJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
2906d61cb1SJosef Bacik 
3006d61cb1SJosef Bacik 	return (btrfs_test_opt(fs_info, FRAGMENT_METADATA) &&
3106d61cb1SJosef Bacik 		block_group->flags & BTRFS_BLOCK_GROUP_METADATA) ||
3206d61cb1SJosef Bacik 	       (btrfs_test_opt(fs_info, FRAGMENT_DATA) &&
3306d61cb1SJosef Bacik 		block_group->flags &  BTRFS_BLOCK_GROUP_DATA);
3406d61cb1SJosef Bacik }
3506d61cb1SJosef Bacik #endif
3606d61cb1SJosef Bacik 
37878d7b67SJosef Bacik /*
38878d7b67SJosef Bacik  * Return target flags in extended format or 0 if restripe for this chunk_type
39878d7b67SJosef Bacik  * is not in progress
40878d7b67SJosef Bacik  *
41878d7b67SJosef Bacik  * Should be called with balance_lock held
42878d7b67SJosef Bacik  */
43e11c0406SJosef Bacik static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
44878d7b67SJosef Bacik {
45878d7b67SJosef Bacik 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
46878d7b67SJosef Bacik 	u64 target = 0;
47878d7b67SJosef Bacik 
48878d7b67SJosef Bacik 	if (!bctl)
49878d7b67SJosef Bacik 		return 0;
50878d7b67SJosef Bacik 
51878d7b67SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA &&
52878d7b67SJosef Bacik 	    bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
53878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
54878d7b67SJosef Bacik 	} else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
55878d7b67SJosef Bacik 		   bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
56878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
57878d7b67SJosef Bacik 	} else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
58878d7b67SJosef Bacik 		   bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
59878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
60878d7b67SJosef Bacik 	}
61878d7b67SJosef Bacik 
62878d7b67SJosef Bacik 	return target;
63878d7b67SJosef Bacik }
64878d7b67SJosef Bacik 
65878d7b67SJosef Bacik /*
66878d7b67SJosef Bacik  * @flags: available profiles in extended format (see ctree.h)
67878d7b67SJosef Bacik  *
68878d7b67SJosef Bacik  * Return reduced profile in chunk format.  If profile changing is in progress
69878d7b67SJosef Bacik  * (either running or paused) picks the target profile (if it's already
70878d7b67SJosef Bacik  * available), otherwise falls back to plain reducing.
71878d7b67SJosef Bacik  */
72878d7b67SJosef Bacik static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
73878d7b67SJosef Bacik {
74878d7b67SJosef Bacik 	u64 num_devices = fs_info->fs_devices->rw_devices;
75878d7b67SJosef Bacik 	u64 target;
76878d7b67SJosef Bacik 	u64 raid_type;
77878d7b67SJosef Bacik 	u64 allowed = 0;
78878d7b67SJosef Bacik 
79878d7b67SJosef Bacik 	/*
80878d7b67SJosef Bacik 	 * See if restripe for this chunk_type is in progress, if so try to
81878d7b67SJosef Bacik 	 * reduce to the target profile
82878d7b67SJosef Bacik 	 */
83878d7b67SJosef Bacik 	spin_lock(&fs_info->balance_lock);
84e11c0406SJosef Bacik 	target = get_restripe_target(fs_info, flags);
85878d7b67SJosef Bacik 	if (target) {
86878d7b67SJosef Bacik 		spin_unlock(&fs_info->balance_lock);
87878d7b67SJosef Bacik 		return extended_to_chunk(target);
88878d7b67SJosef Bacik 	}
89878d7b67SJosef Bacik 	spin_unlock(&fs_info->balance_lock);
90878d7b67SJosef Bacik 
91878d7b67SJosef Bacik 	/* First, mask out the RAID levels which aren't possible */
92878d7b67SJosef Bacik 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
93878d7b67SJosef Bacik 		if (num_devices >= btrfs_raid_array[raid_type].devs_min)
94878d7b67SJosef Bacik 			allowed |= btrfs_raid_array[raid_type].bg_flag;
95878d7b67SJosef Bacik 	}
96878d7b67SJosef Bacik 	allowed &= flags;
97878d7b67SJosef Bacik 
98878d7b67SJosef Bacik 	if (allowed & BTRFS_BLOCK_GROUP_RAID6)
99878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID6;
100878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
101878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID5;
102878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
103878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID10;
104878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
105878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID1;
106878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
107878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID0;
108878d7b67SJosef Bacik 
109878d7b67SJosef Bacik 	flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
110878d7b67SJosef Bacik 
111878d7b67SJosef Bacik 	return extended_to_chunk(flags | allowed);
112878d7b67SJosef Bacik }
113878d7b67SJosef Bacik 
114ef0a82daSJohannes Thumshirn u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
115878d7b67SJosef Bacik {
116878d7b67SJosef Bacik 	unsigned seq;
117878d7b67SJosef Bacik 	u64 flags;
118878d7b67SJosef Bacik 
119878d7b67SJosef Bacik 	do {
120878d7b67SJosef Bacik 		flags = orig_flags;
121878d7b67SJosef Bacik 		seq = read_seqbegin(&fs_info->profiles_lock);
122878d7b67SJosef Bacik 
123878d7b67SJosef Bacik 		if (flags & BTRFS_BLOCK_GROUP_DATA)
124878d7b67SJosef Bacik 			flags |= fs_info->avail_data_alloc_bits;
125878d7b67SJosef Bacik 		else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
126878d7b67SJosef Bacik 			flags |= fs_info->avail_system_alloc_bits;
127878d7b67SJosef Bacik 		else if (flags & BTRFS_BLOCK_GROUP_METADATA)
128878d7b67SJosef Bacik 			flags |= fs_info->avail_metadata_alloc_bits;
129878d7b67SJosef Bacik 	} while (read_seqretry(&fs_info->profiles_lock, seq));
130878d7b67SJosef Bacik 
131878d7b67SJosef Bacik 	return btrfs_reduce_alloc_profile(fs_info, flags);
132878d7b67SJosef Bacik }
133878d7b67SJosef Bacik 
13432da5386SDavid Sterba void btrfs_get_block_group(struct btrfs_block_group *cache)
1353cad1284SJosef Bacik {
13648aaeebeSJosef Bacik 	refcount_inc(&cache->refs);
1373cad1284SJosef Bacik }
1383cad1284SJosef Bacik 
13932da5386SDavid Sterba void btrfs_put_block_group(struct btrfs_block_group *cache)
1403cad1284SJosef Bacik {
14148aaeebeSJosef Bacik 	if (refcount_dec_and_test(&cache->refs)) {
1423cad1284SJosef Bacik 		WARN_ON(cache->pinned > 0);
14340cdc509SFilipe Manana 		/*
14440cdc509SFilipe Manana 		 * If there was a failure to cleanup a log tree, very likely due
14540cdc509SFilipe Manana 		 * to an IO failure on a writeback attempt of one or more of its
14640cdc509SFilipe Manana 		 * extent buffers, we could not do proper (and cheap) unaccounting
14740cdc509SFilipe Manana 		 * of their reserved space, so don't warn on reserved > 0 in that
14840cdc509SFilipe Manana 		 * case.
14940cdc509SFilipe Manana 		 */
15040cdc509SFilipe Manana 		if (!(cache->flags & BTRFS_BLOCK_GROUP_METADATA) ||
15140cdc509SFilipe Manana 		    !BTRFS_FS_LOG_CLEANUP_ERROR(cache->fs_info))
1523cad1284SJosef Bacik 			WARN_ON(cache->reserved > 0);
1533cad1284SJosef Bacik 
1543cad1284SJosef Bacik 		/*
155b0643e59SDennis Zhou 		 * A block_group shouldn't be on the discard_list anymore.
156b0643e59SDennis Zhou 		 * Remove the block_group from the discard_list to prevent us
157b0643e59SDennis Zhou 		 * from causing a panic due to NULL pointer dereference.
158b0643e59SDennis Zhou 		 */
159b0643e59SDennis Zhou 		if (WARN_ON(!list_empty(&cache->discard_list)))
160b0643e59SDennis Zhou 			btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
161b0643e59SDennis Zhou 						  cache);
162b0643e59SDennis Zhou 
163b0643e59SDennis Zhou 		/*
1643cad1284SJosef Bacik 		 * If not empty, someone is still holding mutex of
1653cad1284SJosef Bacik 		 * full_stripe_lock, which can only be released by caller.
1663cad1284SJosef Bacik 		 * And it will definitely cause use-after-free when caller
1673cad1284SJosef Bacik 		 * tries to release full stripe lock.
1683cad1284SJosef Bacik 		 *
1693cad1284SJosef Bacik 		 * No better way to resolve, but only to warn.
1703cad1284SJosef Bacik 		 */
1713cad1284SJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
1723cad1284SJosef Bacik 		kfree(cache->free_space_ctl);
173dafc340dSNaohiro Aota 		kfree(cache->physical_map);
1743cad1284SJosef Bacik 		kfree(cache);
1753cad1284SJosef Bacik 	}
1763cad1284SJosef Bacik }
1773cad1284SJosef Bacik 
1782e405ad8SJosef Bacik /*
1794358d963SJosef Bacik  * This adds the block group to the fs_info rb tree for the block group cache
1804358d963SJosef Bacik  */
1814358d963SJosef Bacik static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
18232da5386SDavid Sterba 				       struct btrfs_block_group *block_group)
1834358d963SJosef Bacik {
1844358d963SJosef Bacik 	struct rb_node **p;
1854358d963SJosef Bacik 	struct rb_node *parent = NULL;
18632da5386SDavid Sterba 	struct btrfs_block_group *cache;
18708dddb29SFilipe Manana 	bool leftmost = true;
1884358d963SJosef Bacik 
1899afc6649SQu Wenruo 	ASSERT(block_group->length != 0);
1909afc6649SQu Wenruo 
19116b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
19208dddb29SFilipe Manana 	p = &info->block_group_cache_tree.rb_root.rb_node;
1934358d963SJosef Bacik 
1944358d963SJosef Bacik 	while (*p) {
1954358d963SJosef Bacik 		parent = *p;
19632da5386SDavid Sterba 		cache = rb_entry(parent, struct btrfs_block_group, cache_node);
197b3470b5dSDavid Sterba 		if (block_group->start < cache->start) {
1984358d963SJosef Bacik 			p = &(*p)->rb_left;
199b3470b5dSDavid Sterba 		} else if (block_group->start > cache->start) {
2004358d963SJosef Bacik 			p = &(*p)->rb_right;
20108dddb29SFilipe Manana 			leftmost = false;
2024358d963SJosef Bacik 		} else {
20316b0c258SFilipe Manana 			write_unlock(&info->block_group_cache_lock);
2044358d963SJosef Bacik 			return -EEXIST;
2054358d963SJosef Bacik 		}
2064358d963SJosef Bacik 	}
2074358d963SJosef Bacik 
2084358d963SJosef Bacik 	rb_link_node(&block_group->cache_node, parent, p);
20908dddb29SFilipe Manana 	rb_insert_color_cached(&block_group->cache_node,
21008dddb29SFilipe Manana 			       &info->block_group_cache_tree, leftmost);
2114358d963SJosef Bacik 
21216b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
2134358d963SJosef Bacik 
2144358d963SJosef Bacik 	return 0;
2154358d963SJosef Bacik }
2164358d963SJosef Bacik 
2174358d963SJosef Bacik /*
2182e405ad8SJosef Bacik  * This will return the block group at or after bytenr if contains is 0, else
2192e405ad8SJosef Bacik  * it will return the block group that contains the bytenr
2202e405ad8SJosef Bacik  */
22132da5386SDavid Sterba static struct btrfs_block_group *block_group_cache_tree_search(
2222e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr, int contains)
2232e405ad8SJosef Bacik {
22432da5386SDavid Sterba 	struct btrfs_block_group *cache, *ret = NULL;
2252e405ad8SJosef Bacik 	struct rb_node *n;
2262e405ad8SJosef Bacik 	u64 end, start;
2272e405ad8SJosef Bacik 
22816b0c258SFilipe Manana 	read_lock(&info->block_group_cache_lock);
22908dddb29SFilipe Manana 	n = info->block_group_cache_tree.rb_root.rb_node;
2302e405ad8SJosef Bacik 
2312e405ad8SJosef Bacik 	while (n) {
23232da5386SDavid Sterba 		cache = rb_entry(n, struct btrfs_block_group, cache_node);
233b3470b5dSDavid Sterba 		end = cache->start + cache->length - 1;
234b3470b5dSDavid Sterba 		start = cache->start;
2352e405ad8SJosef Bacik 
2362e405ad8SJosef Bacik 		if (bytenr < start) {
237b3470b5dSDavid Sterba 			if (!contains && (!ret || start < ret->start))
2382e405ad8SJosef Bacik 				ret = cache;
2392e405ad8SJosef Bacik 			n = n->rb_left;
2402e405ad8SJosef Bacik 		} else if (bytenr > start) {
2412e405ad8SJosef Bacik 			if (contains && bytenr <= end) {
2422e405ad8SJosef Bacik 				ret = cache;
2432e405ad8SJosef Bacik 				break;
2442e405ad8SJosef Bacik 			}
2452e405ad8SJosef Bacik 			n = n->rb_right;
2462e405ad8SJosef Bacik 		} else {
2472e405ad8SJosef Bacik 			ret = cache;
2482e405ad8SJosef Bacik 			break;
2492e405ad8SJosef Bacik 		}
2502e405ad8SJosef Bacik 	}
25108dddb29SFilipe Manana 	if (ret)
2522e405ad8SJosef Bacik 		btrfs_get_block_group(ret);
25316b0c258SFilipe Manana 	read_unlock(&info->block_group_cache_lock);
2542e405ad8SJosef Bacik 
2552e405ad8SJosef Bacik 	return ret;
2562e405ad8SJosef Bacik }
2572e405ad8SJosef Bacik 
2582e405ad8SJosef Bacik /*
2592e405ad8SJosef Bacik  * Return the block group that starts at or after bytenr
2602e405ad8SJosef Bacik  */
26132da5386SDavid Sterba struct btrfs_block_group *btrfs_lookup_first_block_group(
2622e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr)
2632e405ad8SJosef Bacik {
2642e405ad8SJosef Bacik 	return block_group_cache_tree_search(info, bytenr, 0);
2652e405ad8SJosef Bacik }
2662e405ad8SJosef Bacik 
2672e405ad8SJosef Bacik /*
2682e405ad8SJosef Bacik  * Return the block group that contains the given bytenr
2692e405ad8SJosef Bacik  */
27032da5386SDavid Sterba struct btrfs_block_group *btrfs_lookup_block_group(
2712e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr)
2722e405ad8SJosef Bacik {
2732e405ad8SJosef Bacik 	return block_group_cache_tree_search(info, bytenr, 1);
2742e405ad8SJosef Bacik }
2752e405ad8SJosef Bacik 
27632da5386SDavid Sterba struct btrfs_block_group *btrfs_next_block_group(
27732da5386SDavid Sterba 		struct btrfs_block_group *cache)
2782e405ad8SJosef Bacik {
2792e405ad8SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
2802e405ad8SJosef Bacik 	struct rb_node *node;
2812e405ad8SJosef Bacik 
28216b0c258SFilipe Manana 	read_lock(&fs_info->block_group_cache_lock);
2832e405ad8SJosef Bacik 
2842e405ad8SJosef Bacik 	/* If our block group was removed, we need a full search. */
2852e405ad8SJosef Bacik 	if (RB_EMPTY_NODE(&cache->cache_node)) {
286b3470b5dSDavid Sterba 		const u64 next_bytenr = cache->start + cache->length;
2872e405ad8SJosef Bacik 
28816b0c258SFilipe Manana 		read_unlock(&fs_info->block_group_cache_lock);
2892e405ad8SJosef Bacik 		btrfs_put_block_group(cache);
2908b01f931SFilipe Manana 		return btrfs_lookup_first_block_group(fs_info, next_bytenr);
2912e405ad8SJosef Bacik 	}
2922e405ad8SJosef Bacik 	node = rb_next(&cache->cache_node);
2932e405ad8SJosef Bacik 	btrfs_put_block_group(cache);
2942e405ad8SJosef Bacik 	if (node) {
29532da5386SDavid Sterba 		cache = rb_entry(node, struct btrfs_block_group, cache_node);
2962e405ad8SJosef Bacik 		btrfs_get_block_group(cache);
2972e405ad8SJosef Bacik 	} else
2982e405ad8SJosef Bacik 		cache = NULL;
29916b0c258SFilipe Manana 	read_unlock(&fs_info->block_group_cache_lock);
3002e405ad8SJosef Bacik 	return cache;
3012e405ad8SJosef Bacik }
3023eeb3226SJosef Bacik 
30343dd529aSDavid Sterba /*
3042306e83eSFilipe Manana  * Check if we can do a NOCOW write for a given extent.
3052306e83eSFilipe Manana  *
3062306e83eSFilipe Manana  * @fs_info:       The filesystem information object.
3072306e83eSFilipe Manana  * @bytenr:        Logical start address of the extent.
3082306e83eSFilipe Manana  *
3092306e83eSFilipe Manana  * Check if we can do a NOCOW write for the given extent, and increments the
3102306e83eSFilipe Manana  * number of NOCOW writers in the block group that contains the extent, as long
3112306e83eSFilipe Manana  * as the block group exists and it's currently not in read-only mode.
3122306e83eSFilipe Manana  *
3132306e83eSFilipe Manana  * Returns: A non-NULL block group pointer if we can do a NOCOW write, the caller
3142306e83eSFilipe Manana  *          is responsible for calling btrfs_dec_nocow_writers() later.
3152306e83eSFilipe Manana  *
3162306e83eSFilipe Manana  *          Or NULL if we can not do a NOCOW write
3172306e83eSFilipe Manana  */
3182306e83eSFilipe Manana struct btrfs_block_group *btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info,
3192306e83eSFilipe Manana 						  u64 bytenr)
3203eeb3226SJosef Bacik {
32132da5386SDavid Sterba 	struct btrfs_block_group *bg;
3222306e83eSFilipe Manana 	bool can_nocow = true;
3233eeb3226SJosef Bacik 
3243eeb3226SJosef Bacik 	bg = btrfs_lookup_block_group(fs_info, bytenr);
3253eeb3226SJosef Bacik 	if (!bg)
3262306e83eSFilipe Manana 		return NULL;
3273eeb3226SJosef Bacik 
3283eeb3226SJosef Bacik 	spin_lock(&bg->lock);
3293eeb3226SJosef Bacik 	if (bg->ro)
3302306e83eSFilipe Manana 		can_nocow = false;
3313eeb3226SJosef Bacik 	else
3323eeb3226SJosef Bacik 		atomic_inc(&bg->nocow_writers);
3333eeb3226SJosef Bacik 	spin_unlock(&bg->lock);
3343eeb3226SJosef Bacik 
3352306e83eSFilipe Manana 	if (!can_nocow) {
3363eeb3226SJosef Bacik 		btrfs_put_block_group(bg);
3372306e83eSFilipe Manana 		return NULL;
3383eeb3226SJosef Bacik 	}
3393eeb3226SJosef Bacik 
3402306e83eSFilipe Manana 	/* No put on block group, done by btrfs_dec_nocow_writers(). */
3412306e83eSFilipe Manana 	return bg;
3422306e83eSFilipe Manana }
3433eeb3226SJosef Bacik 
34443dd529aSDavid Sterba /*
3452306e83eSFilipe Manana  * Decrement the number of NOCOW writers in a block group.
3462306e83eSFilipe Manana  *
3472306e83eSFilipe Manana  * This is meant to be called after a previous call to btrfs_inc_nocow_writers(),
3482306e83eSFilipe Manana  * and on the block group returned by that call. Typically this is called after
3492306e83eSFilipe Manana  * creating an ordered extent for a NOCOW write, to prevent races with scrub and
3502306e83eSFilipe Manana  * relocation.
3512306e83eSFilipe Manana  *
3522306e83eSFilipe Manana  * After this call, the caller should not use the block group anymore. It it wants
3532306e83eSFilipe Manana  * to use it, then it should get a reference on it before calling this function.
3542306e83eSFilipe Manana  */
3552306e83eSFilipe Manana void btrfs_dec_nocow_writers(struct btrfs_block_group *bg)
3562306e83eSFilipe Manana {
3573eeb3226SJosef Bacik 	if (atomic_dec_and_test(&bg->nocow_writers))
3583eeb3226SJosef Bacik 		wake_up_var(&bg->nocow_writers);
3592306e83eSFilipe Manana 
3602306e83eSFilipe Manana 	/* For the lookup done by a previous call to btrfs_inc_nocow_writers(). */
3613eeb3226SJosef Bacik 	btrfs_put_block_group(bg);
3623eeb3226SJosef Bacik }
3633eeb3226SJosef Bacik 
36432da5386SDavid Sterba void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
3653eeb3226SJosef Bacik {
3663eeb3226SJosef Bacik 	wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
3673eeb3226SJosef Bacik }
3683eeb3226SJosef Bacik 
3693eeb3226SJosef Bacik void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
3703eeb3226SJosef Bacik 					const u64 start)
3713eeb3226SJosef Bacik {
37232da5386SDavid Sterba 	struct btrfs_block_group *bg;
3733eeb3226SJosef Bacik 
3743eeb3226SJosef Bacik 	bg = btrfs_lookup_block_group(fs_info, start);
3753eeb3226SJosef Bacik 	ASSERT(bg);
3763eeb3226SJosef Bacik 	if (atomic_dec_and_test(&bg->reservations))
3773eeb3226SJosef Bacik 		wake_up_var(&bg->reservations);
3783eeb3226SJosef Bacik 	btrfs_put_block_group(bg);
3793eeb3226SJosef Bacik }
3803eeb3226SJosef Bacik 
38132da5386SDavid Sterba void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
3823eeb3226SJosef Bacik {
3833eeb3226SJosef Bacik 	struct btrfs_space_info *space_info = bg->space_info;
3843eeb3226SJosef Bacik 
3853eeb3226SJosef Bacik 	ASSERT(bg->ro);
3863eeb3226SJosef Bacik 
3873eeb3226SJosef Bacik 	if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
3883eeb3226SJosef Bacik 		return;
3893eeb3226SJosef Bacik 
3903eeb3226SJosef Bacik 	/*
3913eeb3226SJosef Bacik 	 * Our block group is read only but before we set it to read only,
3923eeb3226SJosef Bacik 	 * some task might have had allocated an extent from it already, but it
3933eeb3226SJosef Bacik 	 * has not yet created a respective ordered extent (and added it to a
3943eeb3226SJosef Bacik 	 * root's list of ordered extents).
3953eeb3226SJosef Bacik 	 * Therefore wait for any task currently allocating extents, since the
3963eeb3226SJosef Bacik 	 * block group's reservations counter is incremented while a read lock
3973eeb3226SJosef Bacik 	 * on the groups' semaphore is held and decremented after releasing
3983eeb3226SJosef Bacik 	 * the read access on that semaphore and creating the ordered extent.
3993eeb3226SJosef Bacik 	 */
4003eeb3226SJosef Bacik 	down_write(&space_info->groups_sem);
4013eeb3226SJosef Bacik 	up_write(&space_info->groups_sem);
4023eeb3226SJosef Bacik 
4033eeb3226SJosef Bacik 	wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
4043eeb3226SJosef Bacik }
4059f21246dSJosef Bacik 
4069f21246dSJosef Bacik struct btrfs_caching_control *btrfs_get_caching_control(
40732da5386SDavid Sterba 		struct btrfs_block_group *cache)
4089f21246dSJosef Bacik {
4099f21246dSJosef Bacik 	struct btrfs_caching_control *ctl;
4109f21246dSJosef Bacik 
4119f21246dSJosef Bacik 	spin_lock(&cache->lock);
4129f21246dSJosef Bacik 	if (!cache->caching_ctl) {
4139f21246dSJosef Bacik 		spin_unlock(&cache->lock);
4149f21246dSJosef Bacik 		return NULL;
4159f21246dSJosef Bacik 	}
4169f21246dSJosef Bacik 
4179f21246dSJosef Bacik 	ctl = cache->caching_ctl;
4189f21246dSJosef Bacik 	refcount_inc(&ctl->count);
4199f21246dSJosef Bacik 	spin_unlock(&cache->lock);
4209f21246dSJosef Bacik 	return ctl;
4219f21246dSJosef Bacik }
4229f21246dSJosef Bacik 
4239f21246dSJosef Bacik void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
4249f21246dSJosef Bacik {
4259f21246dSJosef Bacik 	if (refcount_dec_and_test(&ctl->count))
4269f21246dSJosef Bacik 		kfree(ctl);
4279f21246dSJosef Bacik }
4289f21246dSJosef Bacik 
4299f21246dSJosef Bacik /*
4309f21246dSJosef Bacik  * When we wait for progress in the block group caching, its because our
4319f21246dSJosef Bacik  * allocation attempt failed at least once.  So, we must sleep and let some
4329f21246dSJosef Bacik  * progress happen before we try again.
4339f21246dSJosef Bacik  *
4349f21246dSJosef Bacik  * This function will sleep at least once waiting for new free space to show
4359f21246dSJosef Bacik  * up, and then it will check the block group free space numbers for our min
4369f21246dSJosef Bacik  * num_bytes.  Another option is to have it go ahead and look in the rbtree for
4379f21246dSJosef Bacik  * a free extent of a given size, but this is a good start.
4389f21246dSJosef Bacik  *
4399f21246dSJosef Bacik  * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
4409f21246dSJosef Bacik  * any of the information in this block group.
4419f21246dSJosef Bacik  */
44232da5386SDavid Sterba void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
4439f21246dSJosef Bacik 					   u64 num_bytes)
4449f21246dSJosef Bacik {
4459f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
4469f21246dSJosef Bacik 
4479f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4489f21246dSJosef Bacik 	if (!caching_ctl)
4499f21246dSJosef Bacik 		return;
4509f21246dSJosef Bacik 
45132da5386SDavid Sterba 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
4529f21246dSJosef Bacik 		   (cache->free_space_ctl->free_space >= num_bytes));
4539f21246dSJosef Bacik 
4549f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4559f21246dSJosef Bacik }
4569f21246dSJosef Bacik 
457ced8ecf0SOmar Sandoval static int btrfs_caching_ctl_wait_done(struct btrfs_block_group *cache,
458ced8ecf0SOmar Sandoval 				       struct btrfs_caching_control *caching_ctl)
459ced8ecf0SOmar Sandoval {
460ced8ecf0SOmar Sandoval 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
461ced8ecf0SOmar Sandoval 	return cache->cached == BTRFS_CACHE_ERROR ? -EIO : 0;
462ced8ecf0SOmar Sandoval }
463ced8ecf0SOmar Sandoval 
464ced8ecf0SOmar Sandoval static int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
4659f21246dSJosef Bacik {
4669f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
467ced8ecf0SOmar Sandoval 	int ret;
4689f21246dSJosef Bacik 
4699f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4709f21246dSJosef Bacik 	if (!caching_ctl)
4719f21246dSJosef Bacik 		return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
472ced8ecf0SOmar Sandoval 	ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
4739f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4749f21246dSJosef Bacik 	return ret;
4759f21246dSJosef Bacik }
4769f21246dSJosef Bacik 
4779f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
47832da5386SDavid Sterba static void fragment_free_space(struct btrfs_block_group *block_group)
4799f21246dSJosef Bacik {
4809f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
481b3470b5dSDavid Sterba 	u64 start = block_group->start;
482b3470b5dSDavid Sterba 	u64 len = block_group->length;
4839f21246dSJosef Bacik 	u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
4849f21246dSJosef Bacik 		fs_info->nodesize : fs_info->sectorsize;
4859f21246dSJosef Bacik 	u64 step = chunk << 1;
4869f21246dSJosef Bacik 
4879f21246dSJosef Bacik 	while (len > chunk) {
4889f21246dSJosef Bacik 		btrfs_remove_free_space(block_group, start, chunk);
4899f21246dSJosef Bacik 		start += step;
4909f21246dSJosef Bacik 		if (len < step)
4919f21246dSJosef Bacik 			len = 0;
4929f21246dSJosef Bacik 		else
4939f21246dSJosef Bacik 			len -= step;
4949f21246dSJosef Bacik 	}
4959f21246dSJosef Bacik }
4969f21246dSJosef Bacik #endif
4979f21246dSJosef Bacik 
4989f21246dSJosef Bacik /*
4999f21246dSJosef Bacik  * This is only called by btrfs_cache_block_group, since we could have freed
5009f21246dSJosef Bacik  * extents we need to check the pinned_extents for any extents that can't be
5019f21246dSJosef Bacik  * used yet since their free space will be released as soon as the transaction
5029f21246dSJosef Bacik  * commits.
5039f21246dSJosef Bacik  */
50432da5386SDavid Sterba u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
5059f21246dSJosef Bacik {
5069f21246dSJosef Bacik 	struct btrfs_fs_info *info = block_group->fs_info;
5079f21246dSJosef Bacik 	u64 extent_start, extent_end, size, total_added = 0;
5089f21246dSJosef Bacik 	int ret;
5099f21246dSJosef Bacik 
5109f21246dSJosef Bacik 	while (start < end) {
511fe119a6eSNikolay Borisov 		ret = find_first_extent_bit(&info->excluded_extents, start,
5129f21246dSJosef Bacik 					    &extent_start, &extent_end,
5139f21246dSJosef Bacik 					    EXTENT_DIRTY | EXTENT_UPTODATE,
5149f21246dSJosef Bacik 					    NULL);
5159f21246dSJosef Bacik 		if (ret)
5169f21246dSJosef Bacik 			break;
5179f21246dSJosef Bacik 
5189f21246dSJosef Bacik 		if (extent_start <= start) {
5199f21246dSJosef Bacik 			start = extent_end + 1;
5209f21246dSJosef Bacik 		} else if (extent_start > start && extent_start < end) {
5219f21246dSJosef Bacik 			size = extent_start - start;
5229f21246dSJosef Bacik 			total_added += size;
523b0643e59SDennis Zhou 			ret = btrfs_add_free_space_async_trimmed(block_group,
524b0643e59SDennis Zhou 								 start, size);
5259f21246dSJosef Bacik 			BUG_ON(ret); /* -ENOMEM or logic error */
5269f21246dSJosef Bacik 			start = extent_end + 1;
5279f21246dSJosef Bacik 		} else {
5289f21246dSJosef Bacik 			break;
5299f21246dSJosef Bacik 		}
5309f21246dSJosef Bacik 	}
5319f21246dSJosef Bacik 
5329f21246dSJosef Bacik 	if (start < end) {
5339f21246dSJosef Bacik 		size = end - start;
5349f21246dSJosef Bacik 		total_added += size;
535b0643e59SDennis Zhou 		ret = btrfs_add_free_space_async_trimmed(block_group, start,
536b0643e59SDennis Zhou 							 size);
5379f21246dSJosef Bacik 		BUG_ON(ret); /* -ENOMEM or logic error */
5389f21246dSJosef Bacik 	}
5399f21246dSJosef Bacik 
5409f21246dSJosef Bacik 	return total_added;
5419f21246dSJosef Bacik }
5429f21246dSJosef Bacik 
543*c7eec3d9SBoris Burkov /*
544*c7eec3d9SBoris Burkov  * Get an arbitrary extent item index / max_index through the block group
545*c7eec3d9SBoris Burkov  *
546*c7eec3d9SBoris Burkov  * @block_group   the block group to sample from
547*c7eec3d9SBoris Burkov  * @index:        the integral step through the block group to grab from
548*c7eec3d9SBoris Burkov  * @max_index:    the granularity of the sampling
549*c7eec3d9SBoris Burkov  * @key:          return value parameter for the item we find
550*c7eec3d9SBoris Burkov  *
551*c7eec3d9SBoris Burkov  * Pre-conditions on indices:
552*c7eec3d9SBoris Burkov  * 0 <= index <= max_index
553*c7eec3d9SBoris Burkov  * 0 < max_index
554*c7eec3d9SBoris Burkov  *
555*c7eec3d9SBoris Burkov  * Returns: 0 on success, 1 if the search didn't yield a useful item, negative
556*c7eec3d9SBoris Burkov  * error code on error.
557*c7eec3d9SBoris Burkov  */
558*c7eec3d9SBoris Burkov static int sample_block_group_extent_item(struct btrfs_caching_control *caching_ctl,
559*c7eec3d9SBoris Burkov 					  struct btrfs_block_group *block_group,
560*c7eec3d9SBoris Burkov 					  int index, int max_index,
561*c7eec3d9SBoris Burkov 					  struct btrfs_key *key)
562*c7eec3d9SBoris Burkov {
563*c7eec3d9SBoris Burkov 	struct btrfs_fs_info *fs_info = block_group->fs_info;
564*c7eec3d9SBoris Burkov 	struct btrfs_root *extent_root;
565*c7eec3d9SBoris Burkov 	int ret = 0;
566*c7eec3d9SBoris Burkov 	u64 search_offset;
567*c7eec3d9SBoris Burkov 	u64 search_end = block_group->start + block_group->length;
568*c7eec3d9SBoris Burkov 	struct btrfs_path *path;
569*c7eec3d9SBoris Burkov 
570*c7eec3d9SBoris Burkov 	ASSERT(index >= 0);
571*c7eec3d9SBoris Burkov 	ASSERT(index <= max_index);
572*c7eec3d9SBoris Burkov 	ASSERT(max_index > 0);
573*c7eec3d9SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
574*c7eec3d9SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
575*c7eec3d9SBoris Burkov 
576*c7eec3d9SBoris Burkov 	path = btrfs_alloc_path();
577*c7eec3d9SBoris Burkov 	if (!path)
578*c7eec3d9SBoris Burkov 		return -ENOMEM;
579*c7eec3d9SBoris Burkov 
580*c7eec3d9SBoris Burkov 	extent_root = btrfs_extent_root(fs_info, max_t(u64, block_group->start,
581*c7eec3d9SBoris Burkov 						       BTRFS_SUPER_INFO_OFFSET));
582*c7eec3d9SBoris Burkov 
583*c7eec3d9SBoris Burkov 	path->skip_locking = 1;
584*c7eec3d9SBoris Burkov 	path->search_commit_root = 1;
585*c7eec3d9SBoris Burkov 	path->reada = READA_FORWARD;
586*c7eec3d9SBoris Burkov 
587*c7eec3d9SBoris Burkov 	search_offset = index * div_u64(block_group->length, max_index);
588*c7eec3d9SBoris Burkov 	key->objectid = block_group->start + search_offset;
589*c7eec3d9SBoris Burkov 	key->type = BTRFS_EXTENT_ITEM_KEY;
590*c7eec3d9SBoris Burkov 	key->offset = 0;
591*c7eec3d9SBoris Burkov 
592*c7eec3d9SBoris Burkov 	while (1) {
593*c7eec3d9SBoris Burkov 		ret = btrfs_search_forward(extent_root, key, path, 0);
594*c7eec3d9SBoris Burkov 		if (ret != 0)
595*c7eec3d9SBoris Burkov 			goto out;
596*c7eec3d9SBoris Burkov 		/* Success; sampled an extent item in the block group */
597*c7eec3d9SBoris Burkov 		if (key->type == BTRFS_EXTENT_ITEM_KEY &&
598*c7eec3d9SBoris Burkov 		    key->objectid >= block_group->start &&
599*c7eec3d9SBoris Burkov 		    key->objectid + key->offset <= search_end)
600*c7eec3d9SBoris Burkov 			goto out;
601*c7eec3d9SBoris Burkov 
602*c7eec3d9SBoris Burkov 		/* We can't possibly find a valid extent item anymore */
603*c7eec3d9SBoris Burkov 		if (key->objectid >= search_end) {
604*c7eec3d9SBoris Burkov 			ret = 1;
605*c7eec3d9SBoris Burkov 			break;
606*c7eec3d9SBoris Burkov 		}
607*c7eec3d9SBoris Burkov 		if (key->type < BTRFS_EXTENT_ITEM_KEY)
608*c7eec3d9SBoris Burkov 			key->type = BTRFS_EXTENT_ITEM_KEY;
609*c7eec3d9SBoris Burkov 		else
610*c7eec3d9SBoris Burkov 			key->objectid++;
611*c7eec3d9SBoris Burkov 		btrfs_release_path(path);
612*c7eec3d9SBoris Burkov 		up_read(&fs_info->commit_root_sem);
613*c7eec3d9SBoris Burkov 		mutex_unlock(&caching_ctl->mutex);
614*c7eec3d9SBoris Burkov 		cond_resched();
615*c7eec3d9SBoris Burkov 		mutex_lock(&caching_ctl->mutex);
616*c7eec3d9SBoris Burkov 		down_read(&fs_info->commit_root_sem);
617*c7eec3d9SBoris Burkov 	}
618*c7eec3d9SBoris Burkov out:
619*c7eec3d9SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
620*c7eec3d9SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
621*c7eec3d9SBoris Burkov 	btrfs_free_path(path);
622*c7eec3d9SBoris Burkov 	return ret;
623*c7eec3d9SBoris Burkov }
624*c7eec3d9SBoris Burkov 
625*c7eec3d9SBoris Burkov /*
626*c7eec3d9SBoris Burkov  * Best effort attempt to compute a block group's size class while caching it.
627*c7eec3d9SBoris Burkov  *
628*c7eec3d9SBoris Burkov  * @block_group: the block group we are caching
629*c7eec3d9SBoris Burkov  *
630*c7eec3d9SBoris Burkov  * We cannot infer the size class while adding free space extents, because that
631*c7eec3d9SBoris Burkov  * logic doesn't care about contiguous file extents (it doesn't differentiate
632*c7eec3d9SBoris Burkov  * between a 100M extent and 100 contiguous 1M extents). So we need to read the
633*c7eec3d9SBoris Burkov  * file extent items. Reading all of them is quite wasteful, because usually
634*c7eec3d9SBoris Burkov  * only a handful are enough to give a good answer. Therefore, we just grab 5 of
635*c7eec3d9SBoris Burkov  * them at even steps through the block group and pick the smallest size class
636*c7eec3d9SBoris Burkov  * we see. Since size class is best effort, and not guaranteed in general,
637*c7eec3d9SBoris Burkov  * inaccuracy is acceptable.
638*c7eec3d9SBoris Burkov  *
639*c7eec3d9SBoris Burkov  * To be more explicit about why this algorithm makes sense:
640*c7eec3d9SBoris Burkov  *
641*c7eec3d9SBoris Burkov  * If we are caching in a block group from disk, then there are three major cases
642*c7eec3d9SBoris Burkov  * to consider:
643*c7eec3d9SBoris Burkov  * 1. the block group is well behaved and all extents in it are the same size
644*c7eec3d9SBoris Burkov  *    class.
645*c7eec3d9SBoris Burkov  * 2. the block group is mostly one size class with rare exceptions for last
646*c7eec3d9SBoris Burkov  *    ditch allocations
647*c7eec3d9SBoris Burkov  * 3. the block group was populated before size classes and can have a totally
648*c7eec3d9SBoris Burkov  *    arbitrary mix of size classes.
649*c7eec3d9SBoris Burkov  *
650*c7eec3d9SBoris Burkov  * In case 1, looking at any extent in the block group will yield the correct
651*c7eec3d9SBoris Burkov  * result. For the mixed cases, taking the minimum size class seems like a good
652*c7eec3d9SBoris Burkov  * approximation, since gaps from frees will be usable to the size class. For
653*c7eec3d9SBoris Burkov  * 2., a small handful of file extents is likely to yield the right answer. For
654*c7eec3d9SBoris Burkov  * 3, we can either read every file extent, or admit that this is best effort
655*c7eec3d9SBoris Burkov  * anyway and try to stay fast.
656*c7eec3d9SBoris Burkov  *
657*c7eec3d9SBoris Burkov  * Returns: 0 on success, negative error code on error.
658*c7eec3d9SBoris Burkov  */
659*c7eec3d9SBoris Burkov static int load_block_group_size_class(struct btrfs_caching_control *caching_ctl,
660*c7eec3d9SBoris Burkov 				       struct btrfs_block_group *block_group)
661*c7eec3d9SBoris Burkov {
662*c7eec3d9SBoris Burkov 	struct btrfs_key key;
663*c7eec3d9SBoris Burkov 	int i;
664*c7eec3d9SBoris Burkov 	u64 min_size = block_group->length;
665*c7eec3d9SBoris Burkov 	enum btrfs_block_group_size_class size_class = BTRFS_BG_SZ_NONE;
666*c7eec3d9SBoris Burkov 	int ret;
667*c7eec3d9SBoris Burkov 
668*c7eec3d9SBoris Burkov 	if (!btrfs_is_block_group_data_only(block_group))
669*c7eec3d9SBoris Burkov 		return 0;
670*c7eec3d9SBoris Burkov 
671*c7eec3d9SBoris Burkov 	for (i = 0; i < 5; ++i) {
672*c7eec3d9SBoris Burkov 		ret = sample_block_group_extent_item(caching_ctl, block_group, i, 5, &key);
673*c7eec3d9SBoris Burkov 		if (ret < 0)
674*c7eec3d9SBoris Burkov 			goto out;
675*c7eec3d9SBoris Burkov 		if (ret > 0)
676*c7eec3d9SBoris Burkov 			continue;
677*c7eec3d9SBoris Burkov 		min_size = min_t(u64, min_size, key.offset);
678*c7eec3d9SBoris Burkov 		size_class = btrfs_calc_block_group_size_class(min_size);
679*c7eec3d9SBoris Burkov 	}
680*c7eec3d9SBoris Burkov 	if (size_class != BTRFS_BG_SZ_NONE) {
681*c7eec3d9SBoris Burkov 		spin_lock(&block_group->lock);
682*c7eec3d9SBoris Burkov 		block_group->size_class = size_class;
683*c7eec3d9SBoris Burkov 		spin_unlock(&block_group->lock);
684*c7eec3d9SBoris Burkov 	}
685*c7eec3d9SBoris Burkov 
686*c7eec3d9SBoris Burkov out:
687*c7eec3d9SBoris Burkov 	return ret;
688*c7eec3d9SBoris Burkov }
689*c7eec3d9SBoris Burkov 
6909f21246dSJosef Bacik static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
6919f21246dSJosef Bacik {
69232da5386SDavid Sterba 	struct btrfs_block_group *block_group = caching_ctl->block_group;
6939f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
69429cbcf40SJosef Bacik 	struct btrfs_root *extent_root;
6959f21246dSJosef Bacik 	struct btrfs_path *path;
6969f21246dSJosef Bacik 	struct extent_buffer *leaf;
6979f21246dSJosef Bacik 	struct btrfs_key key;
6989f21246dSJosef Bacik 	u64 total_found = 0;
6999f21246dSJosef Bacik 	u64 last = 0;
7009f21246dSJosef Bacik 	u32 nritems;
7019f21246dSJosef Bacik 	int ret;
7029f21246dSJosef Bacik 	bool wakeup = true;
7039f21246dSJosef Bacik 
7049f21246dSJosef Bacik 	path = btrfs_alloc_path();
7059f21246dSJosef Bacik 	if (!path)
7069f21246dSJosef Bacik 		return -ENOMEM;
7079f21246dSJosef Bacik 
708b3470b5dSDavid Sterba 	last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
70929cbcf40SJosef Bacik 	extent_root = btrfs_extent_root(fs_info, last);
7109f21246dSJosef Bacik 
7119f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
7129f21246dSJosef Bacik 	/*
7139f21246dSJosef Bacik 	 * If we're fragmenting we don't want to make anybody think we can
7149f21246dSJosef Bacik 	 * allocate from this block group until we've had a chance to fragment
7159f21246dSJosef Bacik 	 * the free space.
7169f21246dSJosef Bacik 	 */
7179f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group))
7189f21246dSJosef Bacik 		wakeup = false;
7199f21246dSJosef Bacik #endif
7209f21246dSJosef Bacik 	/*
7219f21246dSJosef Bacik 	 * We don't want to deadlock with somebody trying to allocate a new
7229f21246dSJosef Bacik 	 * extent for the extent root while also trying to search the extent
7239f21246dSJosef Bacik 	 * root to add free space.  So we skip locking and search the commit
7249f21246dSJosef Bacik 	 * root, since its read-only
7259f21246dSJosef Bacik 	 */
7269f21246dSJosef Bacik 	path->skip_locking = 1;
7279f21246dSJosef Bacik 	path->search_commit_root = 1;
7289f21246dSJosef Bacik 	path->reada = READA_FORWARD;
7299f21246dSJosef Bacik 
7309f21246dSJosef Bacik 	key.objectid = last;
7319f21246dSJosef Bacik 	key.offset = 0;
7329f21246dSJosef Bacik 	key.type = BTRFS_EXTENT_ITEM_KEY;
7339f21246dSJosef Bacik 
7349f21246dSJosef Bacik next:
7359f21246dSJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
7369f21246dSJosef Bacik 	if (ret < 0)
7379f21246dSJosef Bacik 		goto out;
7389f21246dSJosef Bacik 
7399f21246dSJosef Bacik 	leaf = path->nodes[0];
7409f21246dSJosef Bacik 	nritems = btrfs_header_nritems(leaf);
7419f21246dSJosef Bacik 
7429f21246dSJosef Bacik 	while (1) {
7439f21246dSJosef Bacik 		if (btrfs_fs_closing(fs_info) > 1) {
7449f21246dSJosef Bacik 			last = (u64)-1;
7459f21246dSJosef Bacik 			break;
7469f21246dSJosef Bacik 		}
7479f21246dSJosef Bacik 
7489f21246dSJosef Bacik 		if (path->slots[0] < nritems) {
7499f21246dSJosef Bacik 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7509f21246dSJosef Bacik 		} else {
7519f21246dSJosef Bacik 			ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
7529f21246dSJosef Bacik 			if (ret)
7539f21246dSJosef Bacik 				break;
7549f21246dSJosef Bacik 
7559f21246dSJosef Bacik 			if (need_resched() ||
7569f21246dSJosef Bacik 			    rwsem_is_contended(&fs_info->commit_root_sem)) {
7579f21246dSJosef Bacik 				btrfs_release_path(path);
7589f21246dSJosef Bacik 				up_read(&fs_info->commit_root_sem);
7599f21246dSJosef Bacik 				mutex_unlock(&caching_ctl->mutex);
7609f21246dSJosef Bacik 				cond_resched();
7619f21246dSJosef Bacik 				mutex_lock(&caching_ctl->mutex);
7629f21246dSJosef Bacik 				down_read(&fs_info->commit_root_sem);
7639f21246dSJosef Bacik 				goto next;
7649f21246dSJosef Bacik 			}
7659f21246dSJosef Bacik 
7669f21246dSJosef Bacik 			ret = btrfs_next_leaf(extent_root, path);
7679f21246dSJosef Bacik 			if (ret < 0)
7689f21246dSJosef Bacik 				goto out;
7699f21246dSJosef Bacik 			if (ret)
7709f21246dSJosef Bacik 				break;
7719f21246dSJosef Bacik 			leaf = path->nodes[0];
7729f21246dSJosef Bacik 			nritems = btrfs_header_nritems(leaf);
7739f21246dSJosef Bacik 			continue;
7749f21246dSJosef Bacik 		}
7759f21246dSJosef Bacik 
7769f21246dSJosef Bacik 		if (key.objectid < last) {
7779f21246dSJosef Bacik 			key.objectid = last;
7789f21246dSJosef Bacik 			key.offset = 0;
7799f21246dSJosef Bacik 			key.type = BTRFS_EXTENT_ITEM_KEY;
7809f21246dSJosef Bacik 			btrfs_release_path(path);
7819f21246dSJosef Bacik 			goto next;
7829f21246dSJosef Bacik 		}
7839f21246dSJosef Bacik 
784b3470b5dSDavid Sterba 		if (key.objectid < block_group->start) {
7859f21246dSJosef Bacik 			path->slots[0]++;
7869f21246dSJosef Bacik 			continue;
7879f21246dSJosef Bacik 		}
7889f21246dSJosef Bacik 
789b3470b5dSDavid Sterba 		if (key.objectid >= block_group->start + block_group->length)
7909f21246dSJosef Bacik 			break;
7919f21246dSJosef Bacik 
7929f21246dSJosef Bacik 		if (key.type == BTRFS_EXTENT_ITEM_KEY ||
7939f21246dSJosef Bacik 		    key.type == BTRFS_METADATA_ITEM_KEY) {
7949f21246dSJosef Bacik 			total_found += add_new_free_space(block_group, last,
7959f21246dSJosef Bacik 							  key.objectid);
7969f21246dSJosef Bacik 			if (key.type == BTRFS_METADATA_ITEM_KEY)
7979f21246dSJosef Bacik 				last = key.objectid +
7989f21246dSJosef Bacik 					fs_info->nodesize;
7999f21246dSJosef Bacik 			else
8009f21246dSJosef Bacik 				last = key.objectid + key.offset;
8019f21246dSJosef Bacik 
8029f21246dSJosef Bacik 			if (total_found > CACHING_CTL_WAKE_UP) {
8039f21246dSJosef Bacik 				total_found = 0;
8049f21246dSJosef Bacik 				if (wakeup)
8059f21246dSJosef Bacik 					wake_up(&caching_ctl->wait);
8069f21246dSJosef Bacik 			}
8079f21246dSJosef Bacik 		}
8089f21246dSJosef Bacik 		path->slots[0]++;
8099f21246dSJosef Bacik 	}
8109f21246dSJosef Bacik 	ret = 0;
8119f21246dSJosef Bacik 
8129f21246dSJosef Bacik 	total_found += add_new_free_space(block_group, last,
813b3470b5dSDavid Sterba 				block_group->start + block_group->length);
8149f21246dSJosef Bacik 
8159f21246dSJosef Bacik out:
8169f21246dSJosef Bacik 	btrfs_free_path(path);
8179f21246dSJosef Bacik 	return ret;
8189f21246dSJosef Bacik }
8199f21246dSJosef Bacik 
8209f21246dSJosef Bacik static noinline void caching_thread(struct btrfs_work *work)
8219f21246dSJosef Bacik {
82232da5386SDavid Sterba 	struct btrfs_block_group *block_group;
8239f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info;
8249f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
8259f21246dSJosef Bacik 	int ret;
8269f21246dSJosef Bacik 
8279f21246dSJosef Bacik 	caching_ctl = container_of(work, struct btrfs_caching_control, work);
8289f21246dSJosef Bacik 	block_group = caching_ctl->block_group;
8299f21246dSJosef Bacik 	fs_info = block_group->fs_info;
8309f21246dSJosef Bacik 
8319f21246dSJosef Bacik 	mutex_lock(&caching_ctl->mutex);
8329f21246dSJosef Bacik 	down_read(&fs_info->commit_root_sem);
8339f21246dSJosef Bacik 
834*c7eec3d9SBoris Burkov 	load_block_group_size_class(caching_ctl, block_group);
835e747853cSJosef Bacik 	if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
836e747853cSJosef Bacik 		ret = load_free_space_cache(block_group);
837e747853cSJosef Bacik 		if (ret == 1) {
838e747853cSJosef Bacik 			ret = 0;
839e747853cSJosef Bacik 			goto done;
840e747853cSJosef Bacik 		}
841e747853cSJosef Bacik 
842e747853cSJosef Bacik 		/*
843e747853cSJosef Bacik 		 * We failed to load the space cache, set ourselves to
844e747853cSJosef Bacik 		 * CACHE_STARTED and carry on.
845e747853cSJosef Bacik 		 */
846e747853cSJosef Bacik 		spin_lock(&block_group->lock);
847e747853cSJosef Bacik 		block_group->cached = BTRFS_CACHE_STARTED;
848e747853cSJosef Bacik 		spin_unlock(&block_group->lock);
849e747853cSJosef Bacik 		wake_up(&caching_ctl->wait);
850e747853cSJosef Bacik 	}
851e747853cSJosef Bacik 
8522f96e402SJosef Bacik 	/*
8532f96e402SJosef Bacik 	 * If we are in the transaction that populated the free space tree we
8542f96e402SJosef Bacik 	 * can't actually cache from the free space tree as our commit root and
8552f96e402SJosef Bacik 	 * real root are the same, so we could change the contents of the blocks
8562f96e402SJosef Bacik 	 * while caching.  Instead do the slow caching in this case, and after
8572f96e402SJosef Bacik 	 * the transaction has committed we will be safe.
8582f96e402SJosef Bacik 	 */
8592f96e402SJosef Bacik 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
8602f96e402SJosef Bacik 	    !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
8619f21246dSJosef Bacik 		ret = load_free_space_tree(caching_ctl);
8629f21246dSJosef Bacik 	else
8639f21246dSJosef Bacik 		ret = load_extent_tree_free(caching_ctl);
864e747853cSJosef Bacik done:
8659f21246dSJosef Bacik 	spin_lock(&block_group->lock);
8669f21246dSJosef Bacik 	block_group->caching_ctl = NULL;
8679f21246dSJosef Bacik 	block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
8689f21246dSJosef Bacik 	spin_unlock(&block_group->lock);
8699f21246dSJosef Bacik 
8709f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
8719f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group)) {
8729f21246dSJosef Bacik 		u64 bytes_used;
8739f21246dSJosef Bacik 
8749f21246dSJosef Bacik 		spin_lock(&block_group->space_info->lock);
8759f21246dSJosef Bacik 		spin_lock(&block_group->lock);
876b3470b5dSDavid Sterba 		bytes_used = block_group->length - block_group->used;
8779f21246dSJosef Bacik 		block_group->space_info->bytes_used += bytes_used >> 1;
8789f21246dSJosef Bacik 		spin_unlock(&block_group->lock);
8799f21246dSJosef Bacik 		spin_unlock(&block_group->space_info->lock);
880e11c0406SJosef Bacik 		fragment_free_space(block_group);
8819f21246dSJosef Bacik 	}
8829f21246dSJosef Bacik #endif
8839f21246dSJosef Bacik 
8849f21246dSJosef Bacik 	up_read(&fs_info->commit_root_sem);
8859f21246dSJosef Bacik 	btrfs_free_excluded_extents(block_group);
8869f21246dSJosef Bacik 	mutex_unlock(&caching_ctl->mutex);
8879f21246dSJosef Bacik 
8889f21246dSJosef Bacik 	wake_up(&caching_ctl->wait);
8899f21246dSJosef Bacik 
8909f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
8919f21246dSJosef Bacik 	btrfs_put_block_group(block_group);
8929f21246dSJosef Bacik }
8939f21246dSJosef Bacik 
894ced8ecf0SOmar Sandoval int btrfs_cache_block_group(struct btrfs_block_group *cache, bool wait)
8959f21246dSJosef Bacik {
8969f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
897e747853cSJosef Bacik 	struct btrfs_caching_control *caching_ctl = NULL;
8989f21246dSJosef Bacik 	int ret = 0;
8999f21246dSJosef Bacik 
9002eda5708SNaohiro Aota 	/* Allocator for zoned filesystems does not use the cache at all */
9012eda5708SNaohiro Aota 	if (btrfs_is_zoned(fs_info))
9022eda5708SNaohiro Aota 		return 0;
9032eda5708SNaohiro Aota 
9049f21246dSJosef Bacik 	caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
9059f21246dSJosef Bacik 	if (!caching_ctl)
9069f21246dSJosef Bacik 		return -ENOMEM;
9079f21246dSJosef Bacik 
9089f21246dSJosef Bacik 	INIT_LIST_HEAD(&caching_ctl->list);
9099f21246dSJosef Bacik 	mutex_init(&caching_ctl->mutex);
9109f21246dSJosef Bacik 	init_waitqueue_head(&caching_ctl->wait);
9119f21246dSJosef Bacik 	caching_ctl->block_group = cache;
912e747853cSJosef Bacik 	refcount_set(&caching_ctl->count, 2);
913a0cac0ecSOmar Sandoval 	btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
9149f21246dSJosef Bacik 
9159f21246dSJosef Bacik 	spin_lock(&cache->lock);
9169f21246dSJosef Bacik 	if (cache->cached != BTRFS_CACHE_NO) {
9179f21246dSJosef Bacik 		kfree(caching_ctl);
918e747853cSJosef Bacik 
919e747853cSJosef Bacik 		caching_ctl = cache->caching_ctl;
920e747853cSJosef Bacik 		if (caching_ctl)
921e747853cSJosef Bacik 			refcount_inc(&caching_ctl->count);
922e747853cSJosef Bacik 		spin_unlock(&cache->lock);
923e747853cSJosef Bacik 		goto out;
9249f21246dSJosef Bacik 	}
9259f21246dSJosef Bacik 	WARN_ON(cache->caching_ctl);
9269f21246dSJosef Bacik 	cache->caching_ctl = caching_ctl;
9279f21246dSJosef Bacik 	cache->cached = BTRFS_CACHE_STARTED;
9289f21246dSJosef Bacik 	spin_unlock(&cache->lock);
9299f21246dSJosef Bacik 
93016b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
9319f21246dSJosef Bacik 	refcount_inc(&caching_ctl->count);
9329f21246dSJosef Bacik 	list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
93316b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
9349f21246dSJosef Bacik 
9359f21246dSJosef Bacik 	btrfs_get_block_group(cache);
9369f21246dSJosef Bacik 
9379f21246dSJosef Bacik 	btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
938e747853cSJosef Bacik out:
939ced8ecf0SOmar Sandoval 	if (wait && caching_ctl)
940ced8ecf0SOmar Sandoval 		ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
941e747853cSJosef Bacik 	if (caching_ctl)
942e747853cSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
9439f21246dSJosef Bacik 
9449f21246dSJosef Bacik 	return ret;
9459f21246dSJosef Bacik }
946e3e0520bSJosef Bacik 
947e3e0520bSJosef Bacik static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
948e3e0520bSJosef Bacik {
949e3e0520bSJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
950e3e0520bSJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
951e3e0520bSJosef Bacik 
952e3e0520bSJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
953e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
954e3e0520bSJosef Bacik 		fs_info->avail_data_alloc_bits &= ~extra_flags;
955e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
956e3e0520bSJosef Bacik 		fs_info->avail_metadata_alloc_bits &= ~extra_flags;
957e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
958e3e0520bSJosef Bacik 		fs_info->avail_system_alloc_bits &= ~extra_flags;
959e3e0520bSJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
960e3e0520bSJosef Bacik }
961e3e0520bSJosef Bacik 
962e3e0520bSJosef Bacik /*
963e3e0520bSJosef Bacik  * Clear incompat bits for the following feature(s):
964e3e0520bSJosef Bacik  *
965e3e0520bSJosef Bacik  * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
966e3e0520bSJosef Bacik  *            in the whole filesystem
9679c907446SDavid Sterba  *
9689c907446SDavid Sterba  * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
969e3e0520bSJosef Bacik  */
970e3e0520bSJosef Bacik static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
971e3e0520bSJosef Bacik {
9729c907446SDavid Sterba 	bool found_raid56 = false;
9739c907446SDavid Sterba 	bool found_raid1c34 = false;
9749c907446SDavid Sterba 
9759c907446SDavid Sterba 	if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
9769c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
9779c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
978e3e0520bSJosef Bacik 		struct list_head *head = &fs_info->space_info;
979e3e0520bSJosef Bacik 		struct btrfs_space_info *sinfo;
980e3e0520bSJosef Bacik 
981e3e0520bSJosef Bacik 		list_for_each_entry_rcu(sinfo, head, list) {
982e3e0520bSJosef Bacik 			down_read(&sinfo->groups_sem);
983e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
9849c907446SDavid Sterba 				found_raid56 = true;
985e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
9869c907446SDavid Sterba 				found_raid56 = true;
9879c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
9889c907446SDavid Sterba 				found_raid1c34 = true;
9899c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
9909c907446SDavid Sterba 				found_raid1c34 = true;
991e3e0520bSJosef Bacik 			up_read(&sinfo->groups_sem);
992e3e0520bSJosef Bacik 		}
993d8e6fd5cSFilipe Manana 		if (!found_raid56)
994e3e0520bSJosef Bacik 			btrfs_clear_fs_incompat(fs_info, RAID56);
995d8e6fd5cSFilipe Manana 		if (!found_raid1c34)
9969c907446SDavid Sterba 			btrfs_clear_fs_incompat(fs_info, RAID1C34);
997e3e0520bSJosef Bacik 	}
998e3e0520bSJosef Bacik }
999e3e0520bSJosef Bacik 
10007357623aSQu Wenruo static int remove_block_group_item(struct btrfs_trans_handle *trans,
10017357623aSQu Wenruo 				   struct btrfs_path *path,
10027357623aSQu Wenruo 				   struct btrfs_block_group *block_group)
10037357623aSQu Wenruo {
10047357623aSQu Wenruo 	struct btrfs_fs_info *fs_info = trans->fs_info;
10057357623aSQu Wenruo 	struct btrfs_root *root;
10067357623aSQu Wenruo 	struct btrfs_key key;
10077357623aSQu Wenruo 	int ret;
10087357623aSQu Wenruo 
1009dfe8aec4SJosef Bacik 	root = btrfs_block_group_root(fs_info);
10107357623aSQu Wenruo 	key.objectid = block_group->start;
10117357623aSQu Wenruo 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
10127357623aSQu Wenruo 	key.offset = block_group->length;
10137357623aSQu Wenruo 
10147357623aSQu Wenruo 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10157357623aSQu Wenruo 	if (ret > 0)
10167357623aSQu Wenruo 		ret = -ENOENT;
10177357623aSQu Wenruo 	if (ret < 0)
10187357623aSQu Wenruo 		return ret;
10197357623aSQu Wenruo 
10207357623aSQu Wenruo 	ret = btrfs_del_item(trans, root, path);
10217357623aSQu Wenruo 	return ret;
10227357623aSQu Wenruo }
10237357623aSQu Wenruo 
1024e3e0520bSJosef Bacik int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
1025e3e0520bSJosef Bacik 			     u64 group_start, struct extent_map *em)
1026e3e0520bSJosef Bacik {
1027e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
1028e3e0520bSJosef Bacik 	struct btrfs_path *path;
102932da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1030e3e0520bSJosef Bacik 	struct btrfs_free_cluster *cluster;
1031e3e0520bSJosef Bacik 	struct inode *inode;
1032e3e0520bSJosef Bacik 	struct kobject *kobj = NULL;
1033e3e0520bSJosef Bacik 	int ret;
1034e3e0520bSJosef Bacik 	int index;
1035e3e0520bSJosef Bacik 	int factor;
1036e3e0520bSJosef Bacik 	struct btrfs_caching_control *caching_ctl = NULL;
1037e3e0520bSJosef Bacik 	bool remove_em;
1038e3e0520bSJosef Bacik 	bool remove_rsv = false;
1039e3e0520bSJosef Bacik 
1040e3e0520bSJosef Bacik 	block_group = btrfs_lookup_block_group(fs_info, group_start);
1041e3e0520bSJosef Bacik 	BUG_ON(!block_group);
1042e3e0520bSJosef Bacik 	BUG_ON(!block_group->ro);
1043e3e0520bSJosef Bacik 
1044e3e0520bSJosef Bacik 	trace_btrfs_remove_block_group(block_group);
1045e3e0520bSJosef Bacik 	/*
1046e3e0520bSJosef Bacik 	 * Free the reserved super bytes from this block group before
1047e3e0520bSJosef Bacik 	 * remove it.
1048e3e0520bSJosef Bacik 	 */
1049e3e0520bSJosef Bacik 	btrfs_free_excluded_extents(block_group);
1050b3470b5dSDavid Sterba 	btrfs_free_ref_tree_range(fs_info, block_group->start,
1051b3470b5dSDavid Sterba 				  block_group->length);
1052e3e0520bSJosef Bacik 
1053e3e0520bSJosef Bacik 	index = btrfs_bg_flags_to_raid_index(block_group->flags);
1054e3e0520bSJosef Bacik 	factor = btrfs_bg_type_to_factor(block_group->flags);
1055e3e0520bSJosef Bacik 
1056e3e0520bSJosef Bacik 	/* make sure this block group isn't part of an allocation cluster */
1057e3e0520bSJosef Bacik 	cluster = &fs_info->data_alloc_cluster;
1058e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
1059e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
1060e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
1061e3e0520bSJosef Bacik 
1062e3e0520bSJosef Bacik 	/*
1063e3e0520bSJosef Bacik 	 * make sure this block group isn't part of a metadata
1064e3e0520bSJosef Bacik 	 * allocation cluster
1065e3e0520bSJosef Bacik 	 */
1066e3e0520bSJosef Bacik 	cluster = &fs_info->meta_alloc_cluster;
1067e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
1068e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
1069e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
1070e3e0520bSJosef Bacik 
107140ab3be1SNaohiro Aota 	btrfs_clear_treelog_bg(block_group);
1072c2707a25SJohannes Thumshirn 	btrfs_clear_data_reloc_bg(block_group);
107340ab3be1SNaohiro Aota 
1074e3e0520bSJosef Bacik 	path = btrfs_alloc_path();
1075e3e0520bSJosef Bacik 	if (!path) {
1076e3e0520bSJosef Bacik 		ret = -ENOMEM;
10779fecd132SFilipe Manana 		goto out;
1078e3e0520bSJosef Bacik 	}
1079e3e0520bSJosef Bacik 
1080e3e0520bSJosef Bacik 	/*
1081e3e0520bSJosef Bacik 	 * get the inode first so any iput calls done for the io_list
1082e3e0520bSJosef Bacik 	 * aren't the final iput (no unlinks allowed now)
1083e3e0520bSJosef Bacik 	 */
1084e3e0520bSJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
1085e3e0520bSJosef Bacik 
1086e3e0520bSJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
1087e3e0520bSJosef Bacik 	/*
1088e3e0520bSJosef Bacik 	 * Make sure our free space cache IO is done before removing the
1089e3e0520bSJosef Bacik 	 * free space inode
1090e3e0520bSJosef Bacik 	 */
1091e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
1092e3e0520bSJosef Bacik 	if (!list_empty(&block_group->io_list)) {
1093e3e0520bSJosef Bacik 		list_del_init(&block_group->io_list);
1094e3e0520bSJosef Bacik 
1095e3e0520bSJosef Bacik 		WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
1096e3e0520bSJosef Bacik 
1097e3e0520bSJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
1098e3e0520bSJosef Bacik 		btrfs_wait_cache_io(trans, block_group, path);
1099e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1100e3e0520bSJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
1101e3e0520bSJosef Bacik 	}
1102e3e0520bSJosef Bacik 
1103e3e0520bSJosef Bacik 	if (!list_empty(&block_group->dirty_list)) {
1104e3e0520bSJosef Bacik 		list_del_init(&block_group->dirty_list);
1105e3e0520bSJosef Bacik 		remove_rsv = true;
1106e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1107e3e0520bSJosef Bacik 	}
1108e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1109e3e0520bSJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
1110e3e0520bSJosef Bacik 
111136b216c8SBoris Burkov 	ret = btrfs_remove_free_space_inode(trans, inode, block_group);
1112e3e0520bSJosef Bacik 	if (ret)
11139fecd132SFilipe Manana 		goto out;
1114e3e0520bSJosef Bacik 
111516b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
111608dddb29SFilipe Manana 	rb_erase_cached(&block_group->cache_node,
1117e3e0520bSJosef Bacik 			&fs_info->block_group_cache_tree);
1118e3e0520bSJosef Bacik 	RB_CLEAR_NODE(&block_group->cache_node);
1119e3e0520bSJosef Bacik 
11209fecd132SFilipe Manana 	/* Once for the block groups rbtree */
11219fecd132SFilipe Manana 	btrfs_put_block_group(block_group);
11229fecd132SFilipe Manana 
112316b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
1124e3e0520bSJosef Bacik 
1125e3e0520bSJosef Bacik 	down_write(&block_group->space_info->groups_sem);
1126e3e0520bSJosef Bacik 	/*
1127e3e0520bSJosef Bacik 	 * we must use list_del_init so people can check to see if they
1128e3e0520bSJosef Bacik 	 * are still on the list after taking the semaphore
1129e3e0520bSJosef Bacik 	 */
1130e3e0520bSJosef Bacik 	list_del_init(&block_group->list);
1131e3e0520bSJosef Bacik 	if (list_empty(&block_group->space_info->block_groups[index])) {
1132e3e0520bSJosef Bacik 		kobj = block_group->space_info->block_group_kobjs[index];
1133e3e0520bSJosef Bacik 		block_group->space_info->block_group_kobjs[index] = NULL;
1134e3e0520bSJosef Bacik 		clear_avail_alloc_bits(fs_info, block_group->flags);
1135e3e0520bSJosef Bacik 	}
1136e3e0520bSJosef Bacik 	up_write(&block_group->space_info->groups_sem);
1137e3e0520bSJosef Bacik 	clear_incompat_bg_bits(fs_info, block_group->flags);
1138e3e0520bSJosef Bacik 	if (kobj) {
1139e3e0520bSJosef Bacik 		kobject_del(kobj);
1140e3e0520bSJosef Bacik 		kobject_put(kobj);
1141e3e0520bSJosef Bacik 	}
1142e3e0520bSJosef Bacik 
1143e3e0520bSJosef Bacik 	if (block_group->cached == BTRFS_CACHE_STARTED)
1144e3e0520bSJosef Bacik 		btrfs_wait_block_group_cache_done(block_group);
11457b9c293bSJosef Bacik 
114616b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
11477b9c293bSJosef Bacik 	caching_ctl = btrfs_get_caching_control(block_group);
1148e3e0520bSJosef Bacik 	if (!caching_ctl) {
1149e3e0520bSJosef Bacik 		struct btrfs_caching_control *ctl;
1150e3e0520bSJosef Bacik 
11517b9c293bSJosef Bacik 		list_for_each_entry(ctl, &fs_info->caching_block_groups, list) {
1152e3e0520bSJosef Bacik 			if (ctl->block_group == block_group) {
1153e3e0520bSJosef Bacik 				caching_ctl = ctl;
1154e3e0520bSJosef Bacik 				refcount_inc(&caching_ctl->count);
1155e3e0520bSJosef Bacik 				break;
1156e3e0520bSJosef Bacik 			}
1157e3e0520bSJosef Bacik 		}
11587b9c293bSJosef Bacik 	}
1159e3e0520bSJosef Bacik 	if (caching_ctl)
1160e3e0520bSJosef Bacik 		list_del_init(&caching_ctl->list);
116116b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
11627b9c293bSJosef Bacik 
1163e3e0520bSJosef Bacik 	if (caching_ctl) {
1164e3e0520bSJosef Bacik 		/* Once for the caching bgs list and once for us. */
1165e3e0520bSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
1166e3e0520bSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
1167e3e0520bSJosef Bacik 	}
1168e3e0520bSJosef Bacik 
1169e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
1170e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->dirty_list));
1171e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->io_list));
1172e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1173e3e0520bSJosef Bacik 
1174e3e0520bSJosef Bacik 	btrfs_remove_free_space_cache(block_group);
1175e3e0520bSJosef Bacik 
1176e3e0520bSJosef Bacik 	spin_lock(&block_group->space_info->lock);
1177e3e0520bSJosef Bacik 	list_del_init(&block_group->ro_list);
1178e3e0520bSJosef Bacik 
1179e3e0520bSJosef Bacik 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1180e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->total_bytes
1181b3470b5dSDavid Sterba 			< block_group->length);
1182e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->bytes_readonly
1183169e0da9SNaohiro Aota 			< block_group->length - block_group->zone_unusable);
1184169e0da9SNaohiro Aota 		WARN_ON(block_group->space_info->bytes_zone_unusable
1185169e0da9SNaohiro Aota 			< block_group->zone_unusable);
1186e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->disk_total
1187b3470b5dSDavid Sterba 			< block_group->length * factor);
11883349b57fSJosef Bacik 		WARN_ON(test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE,
11893349b57fSJosef Bacik 				 &block_group->runtime_flags) &&
11906a921de5SNaohiro Aota 			block_group->space_info->active_total_bytes
11916a921de5SNaohiro Aota 			< block_group->length);
1192e3e0520bSJosef Bacik 	}
1193b3470b5dSDavid Sterba 	block_group->space_info->total_bytes -= block_group->length;
11943349b57fSJosef Bacik 	if (test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags))
11956a921de5SNaohiro Aota 		block_group->space_info->active_total_bytes -= block_group->length;
1196169e0da9SNaohiro Aota 	block_group->space_info->bytes_readonly -=
1197169e0da9SNaohiro Aota 		(block_group->length - block_group->zone_unusable);
1198169e0da9SNaohiro Aota 	block_group->space_info->bytes_zone_unusable -=
1199169e0da9SNaohiro Aota 		block_group->zone_unusable;
1200b3470b5dSDavid Sterba 	block_group->space_info->disk_total -= block_group->length * factor;
1201e3e0520bSJosef Bacik 
1202e3e0520bSJosef Bacik 	spin_unlock(&block_group->space_info->lock);
1203e3e0520bSJosef Bacik 
1204ffcb9d44SFilipe Manana 	/*
1205ffcb9d44SFilipe Manana 	 * Remove the free space for the block group from the free space tree
1206ffcb9d44SFilipe Manana 	 * and the block group's item from the extent tree before marking the
1207ffcb9d44SFilipe Manana 	 * block group as removed. This is to prevent races with tasks that
1208ffcb9d44SFilipe Manana 	 * freeze and unfreeze a block group, this task and another task
1209ffcb9d44SFilipe Manana 	 * allocating a new block group - the unfreeze task ends up removing
1210ffcb9d44SFilipe Manana 	 * the block group's extent map before the task calling this function
1211ffcb9d44SFilipe Manana 	 * deletes the block group item from the extent tree, allowing for
1212ffcb9d44SFilipe Manana 	 * another task to attempt to create another block group with the same
1213ffcb9d44SFilipe Manana 	 * item key (and failing with -EEXIST and a transaction abort).
1214ffcb9d44SFilipe Manana 	 */
1215ffcb9d44SFilipe Manana 	ret = remove_block_group_free_space(trans, block_group);
1216ffcb9d44SFilipe Manana 	if (ret)
1217ffcb9d44SFilipe Manana 		goto out;
1218ffcb9d44SFilipe Manana 
1219ffcb9d44SFilipe Manana 	ret = remove_block_group_item(trans, path, block_group);
1220ffcb9d44SFilipe Manana 	if (ret < 0)
1221ffcb9d44SFilipe Manana 		goto out;
1222ffcb9d44SFilipe Manana 
1223e3e0520bSJosef Bacik 	spin_lock(&block_group->lock);
12243349b57fSJosef Bacik 	set_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags);
12253349b57fSJosef Bacik 
1226e3e0520bSJosef Bacik 	/*
12276b7304afSFilipe Manana 	 * At this point trimming or scrub can't start on this block group,
12286b7304afSFilipe Manana 	 * because we removed the block group from the rbtree
12296b7304afSFilipe Manana 	 * fs_info->block_group_cache_tree so no one can't find it anymore and
12306b7304afSFilipe Manana 	 * even if someone already got this block group before we removed it
12316b7304afSFilipe Manana 	 * from the rbtree, they have already incremented block_group->frozen -
12326b7304afSFilipe Manana 	 * if they didn't, for the trimming case they won't find any free space
12336b7304afSFilipe Manana 	 * entries because we already removed them all when we called
12346b7304afSFilipe Manana 	 * btrfs_remove_free_space_cache().
1235e3e0520bSJosef Bacik 	 *
1236e3e0520bSJosef Bacik 	 * And we must not remove the extent map from the fs_info->mapping_tree
1237e3e0520bSJosef Bacik 	 * to prevent the same logical address range and physical device space
12386b7304afSFilipe Manana 	 * ranges from being reused for a new block group. This is needed to
12396b7304afSFilipe Manana 	 * avoid races with trimming and scrub.
12406b7304afSFilipe Manana 	 *
12416b7304afSFilipe Manana 	 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1242e3e0520bSJosef Bacik 	 * completely transactionless, so while it is trimming a range the
1243e3e0520bSJosef Bacik 	 * currently running transaction might finish and a new one start,
1244e3e0520bSJosef Bacik 	 * allowing for new block groups to be created that can reuse the same
1245e3e0520bSJosef Bacik 	 * physical device locations unless we take this special care.
1246e3e0520bSJosef Bacik 	 *
1247e3e0520bSJosef Bacik 	 * There may also be an implicit trim operation if the file system
1248e3e0520bSJosef Bacik 	 * is mounted with -odiscard. The same protections must remain
1249e3e0520bSJosef Bacik 	 * in place until the extents have been discarded completely when
1250e3e0520bSJosef Bacik 	 * the transaction commit has completed.
1251e3e0520bSJosef Bacik 	 */
12526b7304afSFilipe Manana 	remove_em = (atomic_read(&block_group->frozen) == 0);
1253e3e0520bSJosef Bacik 	spin_unlock(&block_group->lock);
1254e3e0520bSJosef Bacik 
1255e3e0520bSJosef Bacik 	if (remove_em) {
1256e3e0520bSJosef Bacik 		struct extent_map_tree *em_tree;
1257e3e0520bSJosef Bacik 
1258e3e0520bSJosef Bacik 		em_tree = &fs_info->mapping_tree;
1259e3e0520bSJosef Bacik 		write_lock(&em_tree->lock);
1260e3e0520bSJosef Bacik 		remove_extent_mapping(em_tree, em);
1261e3e0520bSJosef Bacik 		write_unlock(&em_tree->lock);
1262e3e0520bSJosef Bacik 		/* once for the tree */
1263e3e0520bSJosef Bacik 		free_extent_map(em);
1264e3e0520bSJosef Bacik 	}
1265f6033c5eSXiyu Yang 
12669fecd132SFilipe Manana out:
1267f6033c5eSXiyu Yang 	/* Once for the lookup reference */
1268f6033c5eSXiyu Yang 	btrfs_put_block_group(block_group);
1269e3e0520bSJosef Bacik 	if (remove_rsv)
1270e3e0520bSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
1271e3e0520bSJosef Bacik 	btrfs_free_path(path);
1272e3e0520bSJosef Bacik 	return ret;
1273e3e0520bSJosef Bacik }
1274e3e0520bSJosef Bacik 
1275e3e0520bSJosef Bacik struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1276e3e0520bSJosef Bacik 		struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1277e3e0520bSJosef Bacik {
1278dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
1279e3e0520bSJosef Bacik 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1280e3e0520bSJosef Bacik 	struct extent_map *em;
1281e3e0520bSJosef Bacik 	struct map_lookup *map;
1282e3e0520bSJosef Bacik 	unsigned int num_items;
1283e3e0520bSJosef Bacik 
1284e3e0520bSJosef Bacik 	read_lock(&em_tree->lock);
1285e3e0520bSJosef Bacik 	em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1286e3e0520bSJosef Bacik 	read_unlock(&em_tree->lock);
1287e3e0520bSJosef Bacik 	ASSERT(em && em->start == chunk_offset);
1288e3e0520bSJosef Bacik 
1289e3e0520bSJosef Bacik 	/*
1290e3e0520bSJosef Bacik 	 * We need to reserve 3 + N units from the metadata space info in order
1291e3e0520bSJosef Bacik 	 * to remove a block group (done at btrfs_remove_chunk() and at
1292e3e0520bSJosef Bacik 	 * btrfs_remove_block_group()), which are used for:
1293e3e0520bSJosef Bacik 	 *
1294e3e0520bSJosef Bacik 	 * 1 unit for adding the free space inode's orphan (located in the tree
1295e3e0520bSJosef Bacik 	 * of tree roots).
1296e3e0520bSJosef Bacik 	 * 1 unit for deleting the block group item (located in the extent
1297e3e0520bSJosef Bacik 	 * tree).
1298e3e0520bSJosef Bacik 	 * 1 unit for deleting the free space item (located in tree of tree
1299e3e0520bSJosef Bacik 	 * roots).
1300e3e0520bSJosef Bacik 	 * N units for deleting N device extent items corresponding to each
1301e3e0520bSJosef Bacik 	 * stripe (located in the device tree).
1302e3e0520bSJosef Bacik 	 *
1303e3e0520bSJosef Bacik 	 * In order to remove a block group we also need to reserve units in the
1304e3e0520bSJosef Bacik 	 * system space info in order to update the chunk tree (update one or
1305e3e0520bSJosef Bacik 	 * more device items and remove one chunk item), but this is done at
1306e3e0520bSJosef Bacik 	 * btrfs_remove_chunk() through a call to check_system_chunk().
1307e3e0520bSJosef Bacik 	 */
1308e3e0520bSJosef Bacik 	map = em->map_lookup;
1309e3e0520bSJosef Bacik 	num_items = 3 + map->num_stripes;
1310e3e0520bSJosef Bacik 	free_extent_map(em);
1311e3e0520bSJosef Bacik 
1312dfe8aec4SJosef Bacik 	return btrfs_start_transaction_fallback_global_rsv(root, num_items);
1313e3e0520bSJosef Bacik }
1314e3e0520bSJosef Bacik 
1315e3e0520bSJosef Bacik /*
131626ce2095SJosef Bacik  * Mark block group @cache read-only, so later write won't happen to block
131726ce2095SJosef Bacik  * group @cache.
131826ce2095SJosef Bacik  *
131926ce2095SJosef Bacik  * If @force is not set, this function will only mark the block group readonly
132026ce2095SJosef Bacik  * if we have enough free space (1M) in other metadata/system block groups.
132126ce2095SJosef Bacik  * If @force is not set, this function will mark the block group readonly
132226ce2095SJosef Bacik  * without checking free space.
132326ce2095SJosef Bacik  *
132426ce2095SJosef Bacik  * NOTE: This function doesn't care if other block groups can contain all the
132526ce2095SJosef Bacik  * data in this block group. That check should be done by relocation routine,
132626ce2095SJosef Bacik  * not this function.
132726ce2095SJosef Bacik  */
132832da5386SDavid Sterba static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
132926ce2095SJosef Bacik {
133026ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
133126ce2095SJosef Bacik 	u64 num_bytes;
133226ce2095SJosef Bacik 	int ret = -ENOSPC;
133326ce2095SJosef Bacik 
133426ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
133526ce2095SJosef Bacik 	spin_lock(&cache->lock);
133626ce2095SJosef Bacik 
1337195a49eaSFilipe Manana 	if (cache->swap_extents) {
1338195a49eaSFilipe Manana 		ret = -ETXTBSY;
1339195a49eaSFilipe Manana 		goto out;
1340195a49eaSFilipe Manana 	}
1341195a49eaSFilipe Manana 
134226ce2095SJosef Bacik 	if (cache->ro) {
134326ce2095SJosef Bacik 		cache->ro++;
134426ce2095SJosef Bacik 		ret = 0;
134526ce2095SJosef Bacik 		goto out;
134626ce2095SJosef Bacik 	}
134726ce2095SJosef Bacik 
1348b3470b5dSDavid Sterba 	num_bytes = cache->length - cache->reserved - cache->pinned -
1349169e0da9SNaohiro Aota 		    cache->bytes_super - cache->zone_unusable - cache->used;
135026ce2095SJosef Bacik 
135126ce2095SJosef Bacik 	/*
1352a30a3d20SJosef Bacik 	 * Data never overcommits, even in mixed mode, so do just the straight
1353a30a3d20SJosef Bacik 	 * check of left over space in how much we have allocated.
1354a30a3d20SJosef Bacik 	 */
1355a30a3d20SJosef Bacik 	if (force) {
1356a30a3d20SJosef Bacik 		ret = 0;
1357a30a3d20SJosef Bacik 	} else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1358a30a3d20SJosef Bacik 		u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1359a30a3d20SJosef Bacik 
1360a30a3d20SJosef Bacik 		/*
136126ce2095SJosef Bacik 		 * Here we make sure if we mark this bg RO, we still have enough
1362f8935566SJosef Bacik 		 * free space as buffer.
136326ce2095SJosef Bacik 		 */
1364a30a3d20SJosef Bacik 		if (sinfo_used + num_bytes <= sinfo->total_bytes)
1365a30a3d20SJosef Bacik 			ret = 0;
1366a30a3d20SJosef Bacik 	} else {
1367a30a3d20SJosef Bacik 		/*
1368a30a3d20SJosef Bacik 		 * We overcommit metadata, so we need to do the
1369a30a3d20SJosef Bacik 		 * btrfs_can_overcommit check here, and we need to pass in
1370a30a3d20SJosef Bacik 		 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1371a30a3d20SJosef Bacik 		 * leeway to allow us to mark this block group as read only.
1372a30a3d20SJosef Bacik 		 */
1373a30a3d20SJosef Bacik 		if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1374a30a3d20SJosef Bacik 					 BTRFS_RESERVE_NO_FLUSH))
1375a30a3d20SJosef Bacik 			ret = 0;
1376a30a3d20SJosef Bacik 	}
1377a30a3d20SJosef Bacik 
1378a30a3d20SJosef Bacik 	if (!ret) {
137926ce2095SJosef Bacik 		sinfo->bytes_readonly += num_bytes;
1380169e0da9SNaohiro Aota 		if (btrfs_is_zoned(cache->fs_info)) {
1381169e0da9SNaohiro Aota 			/* Migrate zone_unusable bytes to readonly */
1382169e0da9SNaohiro Aota 			sinfo->bytes_readonly += cache->zone_unusable;
1383169e0da9SNaohiro Aota 			sinfo->bytes_zone_unusable -= cache->zone_unusable;
1384169e0da9SNaohiro Aota 			cache->zone_unusable = 0;
1385169e0da9SNaohiro Aota 		}
138626ce2095SJosef Bacik 		cache->ro++;
138726ce2095SJosef Bacik 		list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
138826ce2095SJosef Bacik 	}
138926ce2095SJosef Bacik out:
139026ce2095SJosef Bacik 	spin_unlock(&cache->lock);
139126ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
139226ce2095SJosef Bacik 	if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
139326ce2095SJosef Bacik 		btrfs_info(cache->fs_info,
1394b3470b5dSDavid Sterba 			"unable to make block group %llu ro", cache->start);
139526ce2095SJosef Bacik 		btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
139626ce2095SJosef Bacik 	}
139726ce2095SJosef Bacik 	return ret;
139826ce2095SJosef Bacik }
139926ce2095SJosef Bacik 
1400fe119a6eSNikolay Borisov static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1401fe119a6eSNikolay Borisov 				 struct btrfs_block_group *bg)
140245bb5d6aSNikolay Borisov {
140345bb5d6aSNikolay Borisov 	struct btrfs_fs_info *fs_info = bg->fs_info;
1404fe119a6eSNikolay Borisov 	struct btrfs_transaction *prev_trans = NULL;
140545bb5d6aSNikolay Borisov 	const u64 start = bg->start;
140645bb5d6aSNikolay Borisov 	const u64 end = start + bg->length - 1;
140745bb5d6aSNikolay Borisov 	int ret;
140845bb5d6aSNikolay Borisov 
1409fe119a6eSNikolay Borisov 	spin_lock(&fs_info->trans_lock);
1410fe119a6eSNikolay Borisov 	if (trans->transaction->list.prev != &fs_info->trans_list) {
1411fe119a6eSNikolay Borisov 		prev_trans = list_last_entry(&trans->transaction->list,
1412fe119a6eSNikolay Borisov 					     struct btrfs_transaction, list);
1413fe119a6eSNikolay Borisov 		refcount_inc(&prev_trans->use_count);
1414fe119a6eSNikolay Borisov 	}
1415fe119a6eSNikolay Borisov 	spin_unlock(&fs_info->trans_lock);
1416fe119a6eSNikolay Borisov 
141745bb5d6aSNikolay Borisov 	/*
141845bb5d6aSNikolay Borisov 	 * Hold the unused_bg_unpin_mutex lock to avoid racing with
141945bb5d6aSNikolay Borisov 	 * btrfs_finish_extent_commit(). If we are at transaction N, another
142045bb5d6aSNikolay Borisov 	 * task might be running finish_extent_commit() for the previous
142145bb5d6aSNikolay Borisov 	 * transaction N - 1, and have seen a range belonging to the block
1422fe119a6eSNikolay Borisov 	 * group in pinned_extents before we were able to clear the whole block
1423fe119a6eSNikolay Borisov 	 * group range from pinned_extents. This means that task can lookup for
1424fe119a6eSNikolay Borisov 	 * the block group after we unpinned it from pinned_extents and removed
1425fe119a6eSNikolay Borisov 	 * it, leading to a BUG_ON() at unpin_extent_range().
142645bb5d6aSNikolay Borisov 	 */
142745bb5d6aSNikolay Borisov 	mutex_lock(&fs_info->unused_bg_unpin_mutex);
1428fe119a6eSNikolay Borisov 	if (prev_trans) {
1429fe119a6eSNikolay Borisov 		ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
143045bb5d6aSNikolay Borisov 					EXTENT_DIRTY);
143145bb5d6aSNikolay Borisov 		if (ret)
1432534cf531SFilipe Manana 			goto out;
1433fe119a6eSNikolay Borisov 	}
143445bb5d6aSNikolay Borisov 
1435fe119a6eSNikolay Borisov 	ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
143645bb5d6aSNikolay Borisov 				EXTENT_DIRTY);
1437534cf531SFilipe Manana out:
143845bb5d6aSNikolay Borisov 	mutex_unlock(&fs_info->unused_bg_unpin_mutex);
14395150bf19SFilipe Manana 	if (prev_trans)
14405150bf19SFilipe Manana 		btrfs_put_transaction(prev_trans);
144145bb5d6aSNikolay Borisov 
1442534cf531SFilipe Manana 	return ret == 0;
144345bb5d6aSNikolay Borisov }
144445bb5d6aSNikolay Borisov 
144526ce2095SJosef Bacik /*
1446e3e0520bSJosef Bacik  * Process the unused_bgs list and remove any that don't have any allocated
1447e3e0520bSJosef Bacik  * space inside of them.
1448e3e0520bSJosef Bacik  */
1449e3e0520bSJosef Bacik void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1450e3e0520bSJosef Bacik {
145132da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1452e3e0520bSJosef Bacik 	struct btrfs_space_info *space_info;
1453e3e0520bSJosef Bacik 	struct btrfs_trans_handle *trans;
14546e80d4f8SDennis Zhou 	const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1455e3e0520bSJosef Bacik 	int ret = 0;
1456e3e0520bSJosef Bacik 
1457e3e0520bSJosef Bacik 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1458e3e0520bSJosef Bacik 		return;
1459e3e0520bSJosef Bacik 
14602f12741fSJosef Bacik 	if (btrfs_fs_closing(fs_info))
14612f12741fSJosef Bacik 		return;
14622f12741fSJosef Bacik 
1463ddfd08cbSJosef Bacik 	/*
1464ddfd08cbSJosef Bacik 	 * Long running balances can keep us blocked here for eternity, so
1465ddfd08cbSJosef Bacik 	 * simply skip deletion if we're unable to get the mutex.
1466ddfd08cbSJosef Bacik 	 */
1467f3372065SJohannes Thumshirn 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
1468ddfd08cbSJosef Bacik 		return;
1469ddfd08cbSJosef Bacik 
1470e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1471e3e0520bSJosef Bacik 	while (!list_empty(&fs_info->unused_bgs)) {
1472e3e0520bSJosef Bacik 		int trimming;
1473e3e0520bSJosef Bacik 
1474e3e0520bSJosef Bacik 		block_group = list_first_entry(&fs_info->unused_bgs,
147532da5386SDavid Sterba 					       struct btrfs_block_group,
1476e3e0520bSJosef Bacik 					       bg_list);
1477e3e0520bSJosef Bacik 		list_del_init(&block_group->bg_list);
1478e3e0520bSJosef Bacik 
1479e3e0520bSJosef Bacik 		space_info = block_group->space_info;
1480e3e0520bSJosef Bacik 
1481e3e0520bSJosef Bacik 		if (ret || btrfs_mixed_space_info(space_info)) {
1482e3e0520bSJosef Bacik 			btrfs_put_block_group(block_group);
1483e3e0520bSJosef Bacik 			continue;
1484e3e0520bSJosef Bacik 		}
1485e3e0520bSJosef Bacik 		spin_unlock(&fs_info->unused_bgs_lock);
1486e3e0520bSJosef Bacik 
1487b0643e59SDennis Zhou 		btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1488b0643e59SDennis Zhou 
1489e3e0520bSJosef Bacik 		/* Don't want to race with allocators so take the groups_sem */
1490e3e0520bSJosef Bacik 		down_write(&space_info->groups_sem);
14916e80d4f8SDennis Zhou 
14926e80d4f8SDennis Zhou 		/*
14936e80d4f8SDennis Zhou 		 * Async discard moves the final block group discard to be prior
14946e80d4f8SDennis Zhou 		 * to the unused_bgs code path.  Therefore, if it's not fully
14956e80d4f8SDennis Zhou 		 * trimmed, punt it back to the async discard lists.
14966e80d4f8SDennis Zhou 		 */
14976e80d4f8SDennis Zhou 		if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
14986e80d4f8SDennis Zhou 		    !btrfs_is_free_space_trimmed(block_group)) {
14996e80d4f8SDennis Zhou 			trace_btrfs_skip_unused_block_group(block_group);
15006e80d4f8SDennis Zhou 			up_write(&space_info->groups_sem);
15016e80d4f8SDennis Zhou 			/* Requeue if we failed because of async discard */
15026e80d4f8SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
15036e80d4f8SDennis Zhou 						 block_group);
15046e80d4f8SDennis Zhou 			goto next;
15056e80d4f8SDennis Zhou 		}
15066e80d4f8SDennis Zhou 
1507e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1508e3e0520bSJosef Bacik 		if (block_group->reserved || block_group->pinned ||
1509bf38be65SDavid Sterba 		    block_group->used || block_group->ro ||
1510e3e0520bSJosef Bacik 		    list_is_singular(&block_group->list)) {
1511e3e0520bSJosef Bacik 			/*
1512e3e0520bSJosef Bacik 			 * We want to bail if we made new allocations or have
1513e3e0520bSJosef Bacik 			 * outstanding allocations in this block group.  We do
1514e3e0520bSJosef Bacik 			 * the ro check in case balance is currently acting on
1515e3e0520bSJosef Bacik 			 * this block group.
1516e3e0520bSJosef Bacik 			 */
1517e3e0520bSJosef Bacik 			trace_btrfs_skip_unused_block_group(block_group);
1518e3e0520bSJosef Bacik 			spin_unlock(&block_group->lock);
1519e3e0520bSJosef Bacik 			up_write(&space_info->groups_sem);
1520e3e0520bSJosef Bacik 			goto next;
1521e3e0520bSJosef Bacik 		}
1522e3e0520bSJosef Bacik 		spin_unlock(&block_group->lock);
1523e3e0520bSJosef Bacik 
1524e3e0520bSJosef Bacik 		/* We don't want to force the issue, only flip if it's ok. */
1525e11c0406SJosef Bacik 		ret = inc_block_group_ro(block_group, 0);
1526e3e0520bSJosef Bacik 		up_write(&space_info->groups_sem);
1527e3e0520bSJosef Bacik 		if (ret < 0) {
1528e3e0520bSJosef Bacik 			ret = 0;
1529e3e0520bSJosef Bacik 			goto next;
1530e3e0520bSJosef Bacik 		}
1531e3e0520bSJosef Bacik 
153274e91b12SNaohiro Aota 		ret = btrfs_zone_finish(block_group);
153374e91b12SNaohiro Aota 		if (ret < 0) {
153474e91b12SNaohiro Aota 			btrfs_dec_block_group_ro(block_group);
153574e91b12SNaohiro Aota 			if (ret == -EAGAIN)
153674e91b12SNaohiro Aota 				ret = 0;
153774e91b12SNaohiro Aota 			goto next;
153874e91b12SNaohiro Aota 		}
153974e91b12SNaohiro Aota 
1540e3e0520bSJosef Bacik 		/*
1541e3e0520bSJosef Bacik 		 * Want to do this before we do anything else so we can recover
1542e3e0520bSJosef Bacik 		 * properly if we fail to join the transaction.
1543e3e0520bSJosef Bacik 		 */
1544e3e0520bSJosef Bacik 		trans = btrfs_start_trans_remove_block_group(fs_info,
1545b3470b5dSDavid Sterba 						     block_group->start);
1546e3e0520bSJosef Bacik 		if (IS_ERR(trans)) {
1547e3e0520bSJosef Bacik 			btrfs_dec_block_group_ro(block_group);
1548e3e0520bSJosef Bacik 			ret = PTR_ERR(trans);
1549e3e0520bSJosef Bacik 			goto next;
1550e3e0520bSJosef Bacik 		}
1551e3e0520bSJosef Bacik 
1552e3e0520bSJosef Bacik 		/*
1553e3e0520bSJosef Bacik 		 * We could have pending pinned extents for this block group,
1554e3e0520bSJosef Bacik 		 * just delete them, we don't care about them anymore.
1555e3e0520bSJosef Bacik 		 */
1556534cf531SFilipe Manana 		if (!clean_pinned_extents(trans, block_group)) {
1557534cf531SFilipe Manana 			btrfs_dec_block_group_ro(block_group);
1558e3e0520bSJosef Bacik 			goto end_trans;
1559534cf531SFilipe Manana 		}
1560e3e0520bSJosef Bacik 
1561b0643e59SDennis Zhou 		/*
1562b0643e59SDennis Zhou 		 * At this point, the block_group is read only and should fail
1563b0643e59SDennis Zhou 		 * new allocations.  However, btrfs_finish_extent_commit() can
1564b0643e59SDennis Zhou 		 * cause this block_group to be placed back on the discard
1565b0643e59SDennis Zhou 		 * lists because now the block_group isn't fully discarded.
1566b0643e59SDennis Zhou 		 * Bail here and try again later after discarding everything.
1567b0643e59SDennis Zhou 		 */
1568b0643e59SDennis Zhou 		spin_lock(&fs_info->discard_ctl.lock);
1569b0643e59SDennis Zhou 		if (!list_empty(&block_group->discard_list)) {
1570b0643e59SDennis Zhou 			spin_unlock(&fs_info->discard_ctl.lock);
1571b0643e59SDennis Zhou 			btrfs_dec_block_group_ro(block_group);
1572b0643e59SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
1573b0643e59SDennis Zhou 						 block_group);
1574b0643e59SDennis Zhou 			goto end_trans;
1575b0643e59SDennis Zhou 		}
1576b0643e59SDennis Zhou 		spin_unlock(&fs_info->discard_ctl.lock);
1577b0643e59SDennis Zhou 
1578e3e0520bSJosef Bacik 		/* Reset pinned so btrfs_put_block_group doesn't complain */
1579e3e0520bSJosef Bacik 		spin_lock(&space_info->lock);
1580e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1581e3e0520bSJosef Bacik 
1582e3e0520bSJosef Bacik 		btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1583e3e0520bSJosef Bacik 						     -block_group->pinned);
1584e3e0520bSJosef Bacik 		space_info->bytes_readonly += block_group->pinned;
1585e3e0520bSJosef Bacik 		block_group->pinned = 0;
1586e3e0520bSJosef Bacik 
1587e3e0520bSJosef Bacik 		spin_unlock(&block_group->lock);
1588e3e0520bSJosef Bacik 		spin_unlock(&space_info->lock);
1589e3e0520bSJosef Bacik 
15906e80d4f8SDennis Zhou 		/*
15916e80d4f8SDennis Zhou 		 * The normal path here is an unused block group is passed here,
15926e80d4f8SDennis Zhou 		 * then trimming is handled in the transaction commit path.
15936e80d4f8SDennis Zhou 		 * Async discard interposes before this to do the trimming
15946e80d4f8SDennis Zhou 		 * before coming down the unused block group path as trimming
15956e80d4f8SDennis Zhou 		 * will no longer be done later in the transaction commit path.
15966e80d4f8SDennis Zhou 		 */
15976e80d4f8SDennis Zhou 		if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
15986e80d4f8SDennis Zhou 			goto flip_async;
15996e80d4f8SDennis Zhou 
1600dcba6e48SNaohiro Aota 		/*
1601dcba6e48SNaohiro Aota 		 * DISCARD can flip during remount. On zoned filesystems, we
1602dcba6e48SNaohiro Aota 		 * need to reset sequential-required zones.
1603dcba6e48SNaohiro Aota 		 */
1604dcba6e48SNaohiro Aota 		trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) ||
1605dcba6e48SNaohiro Aota 				btrfs_is_zoned(fs_info);
1606e3e0520bSJosef Bacik 
1607e3e0520bSJosef Bacik 		/* Implicit trim during transaction commit. */
1608e3e0520bSJosef Bacik 		if (trimming)
16096b7304afSFilipe Manana 			btrfs_freeze_block_group(block_group);
1610e3e0520bSJosef Bacik 
1611e3e0520bSJosef Bacik 		/*
1612e3e0520bSJosef Bacik 		 * Btrfs_remove_chunk will abort the transaction if things go
1613e3e0520bSJosef Bacik 		 * horribly wrong.
1614e3e0520bSJosef Bacik 		 */
1615b3470b5dSDavid Sterba 		ret = btrfs_remove_chunk(trans, block_group->start);
1616e3e0520bSJosef Bacik 
1617e3e0520bSJosef Bacik 		if (ret) {
1618e3e0520bSJosef Bacik 			if (trimming)
16196b7304afSFilipe Manana 				btrfs_unfreeze_block_group(block_group);
1620e3e0520bSJosef Bacik 			goto end_trans;
1621e3e0520bSJosef Bacik 		}
1622e3e0520bSJosef Bacik 
1623e3e0520bSJosef Bacik 		/*
1624e3e0520bSJosef Bacik 		 * If we're not mounted with -odiscard, we can just forget
1625e3e0520bSJosef Bacik 		 * about this block group. Otherwise we'll need to wait
1626e3e0520bSJosef Bacik 		 * until transaction commit to do the actual discard.
1627e3e0520bSJosef Bacik 		 */
1628e3e0520bSJosef Bacik 		if (trimming) {
1629e3e0520bSJosef Bacik 			spin_lock(&fs_info->unused_bgs_lock);
1630e3e0520bSJosef Bacik 			/*
1631e3e0520bSJosef Bacik 			 * A concurrent scrub might have added us to the list
1632e3e0520bSJosef Bacik 			 * fs_info->unused_bgs, so use a list_move operation
1633e3e0520bSJosef Bacik 			 * to add the block group to the deleted_bgs list.
1634e3e0520bSJosef Bacik 			 */
1635e3e0520bSJosef Bacik 			list_move(&block_group->bg_list,
1636e3e0520bSJosef Bacik 				  &trans->transaction->deleted_bgs);
1637e3e0520bSJosef Bacik 			spin_unlock(&fs_info->unused_bgs_lock);
1638e3e0520bSJosef Bacik 			btrfs_get_block_group(block_group);
1639e3e0520bSJosef Bacik 		}
1640e3e0520bSJosef Bacik end_trans:
1641e3e0520bSJosef Bacik 		btrfs_end_transaction(trans);
1642e3e0520bSJosef Bacik next:
1643e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1644e3e0520bSJosef Bacik 		spin_lock(&fs_info->unused_bgs_lock);
1645e3e0520bSJosef Bacik 	}
1646e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
1647f3372065SJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
16486e80d4f8SDennis Zhou 	return;
16496e80d4f8SDennis Zhou 
16506e80d4f8SDennis Zhou flip_async:
16516e80d4f8SDennis Zhou 	btrfs_end_transaction(trans);
1652f3372065SJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
16536e80d4f8SDennis Zhou 	btrfs_put_block_group(block_group);
16546e80d4f8SDennis Zhou 	btrfs_discard_punt_unused_bgs_list(fs_info);
1655e3e0520bSJosef Bacik }
1656e3e0520bSJosef Bacik 
165732da5386SDavid Sterba void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1658e3e0520bSJosef Bacik {
1659e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = bg->fs_info;
1660e3e0520bSJosef Bacik 
1661e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1662e3e0520bSJosef Bacik 	if (list_empty(&bg->bg_list)) {
1663e3e0520bSJosef Bacik 		btrfs_get_block_group(bg);
1664e3e0520bSJosef Bacik 		trace_btrfs_add_unused_block_group(bg);
1665e3e0520bSJosef Bacik 		list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1666e3e0520bSJosef Bacik 	}
1667e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
1668e3e0520bSJosef Bacik }
16694358d963SJosef Bacik 
16702ca0ec77SJohannes Thumshirn /*
16712ca0ec77SJohannes Thumshirn  * We want block groups with a low number of used bytes to be in the beginning
16722ca0ec77SJohannes Thumshirn  * of the list, so they will get reclaimed first.
16732ca0ec77SJohannes Thumshirn  */
16742ca0ec77SJohannes Thumshirn static int reclaim_bgs_cmp(void *unused, const struct list_head *a,
16752ca0ec77SJohannes Thumshirn 			   const struct list_head *b)
16762ca0ec77SJohannes Thumshirn {
16772ca0ec77SJohannes Thumshirn 	const struct btrfs_block_group *bg1, *bg2;
16782ca0ec77SJohannes Thumshirn 
16792ca0ec77SJohannes Thumshirn 	bg1 = list_entry(a, struct btrfs_block_group, bg_list);
16802ca0ec77SJohannes Thumshirn 	bg2 = list_entry(b, struct btrfs_block_group, bg_list);
16812ca0ec77SJohannes Thumshirn 
16822ca0ec77SJohannes Thumshirn 	return bg1->used > bg2->used;
16832ca0ec77SJohannes Thumshirn }
16842ca0ec77SJohannes Thumshirn 
16853687fcb0SJohannes Thumshirn static inline bool btrfs_should_reclaim(struct btrfs_fs_info *fs_info)
16863687fcb0SJohannes Thumshirn {
16873687fcb0SJohannes Thumshirn 	if (btrfs_is_zoned(fs_info))
16883687fcb0SJohannes Thumshirn 		return btrfs_zoned_should_reclaim(fs_info);
16893687fcb0SJohannes Thumshirn 	return true;
16903687fcb0SJohannes Thumshirn }
16913687fcb0SJohannes Thumshirn 
169281531225SBoris Burkov static bool should_reclaim_block_group(struct btrfs_block_group *bg, u64 bytes_freed)
169381531225SBoris Burkov {
169481531225SBoris Burkov 	const struct btrfs_space_info *space_info = bg->space_info;
169581531225SBoris Burkov 	const int reclaim_thresh = READ_ONCE(space_info->bg_reclaim_threshold);
169681531225SBoris Burkov 	const u64 new_val = bg->used;
169781531225SBoris Burkov 	const u64 old_val = new_val + bytes_freed;
169881531225SBoris Burkov 	u64 thresh;
169981531225SBoris Burkov 
170081531225SBoris Burkov 	if (reclaim_thresh == 0)
170181531225SBoris Burkov 		return false;
170281531225SBoris Burkov 
1703428c8e03SDavid Sterba 	thresh = mult_perc(bg->length, reclaim_thresh);
170481531225SBoris Burkov 
170581531225SBoris Burkov 	/*
170681531225SBoris Burkov 	 * If we were below the threshold before don't reclaim, we are likely a
170781531225SBoris Burkov 	 * brand new block group and we don't want to relocate new block groups.
170881531225SBoris Burkov 	 */
170981531225SBoris Burkov 	if (old_val < thresh)
171081531225SBoris Burkov 		return false;
171181531225SBoris Burkov 	if (new_val >= thresh)
171281531225SBoris Burkov 		return false;
171381531225SBoris Burkov 	return true;
171481531225SBoris Burkov }
171581531225SBoris Burkov 
171618bb8bbfSJohannes Thumshirn void btrfs_reclaim_bgs_work(struct work_struct *work)
171718bb8bbfSJohannes Thumshirn {
171818bb8bbfSJohannes Thumshirn 	struct btrfs_fs_info *fs_info =
171918bb8bbfSJohannes Thumshirn 		container_of(work, struct btrfs_fs_info, reclaim_bgs_work);
172018bb8bbfSJohannes Thumshirn 	struct btrfs_block_group *bg;
172118bb8bbfSJohannes Thumshirn 	struct btrfs_space_info *space_info;
172218bb8bbfSJohannes Thumshirn 
172318bb8bbfSJohannes Thumshirn 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
172418bb8bbfSJohannes Thumshirn 		return;
172518bb8bbfSJohannes Thumshirn 
17262f12741fSJosef Bacik 	if (btrfs_fs_closing(fs_info))
17272f12741fSJosef Bacik 		return;
17282f12741fSJosef Bacik 
17293687fcb0SJohannes Thumshirn 	if (!btrfs_should_reclaim(fs_info))
17303687fcb0SJohannes Thumshirn 		return;
17313687fcb0SJohannes Thumshirn 
1732ca5e4ea0SNaohiro Aota 	sb_start_write(fs_info->sb);
1733ca5e4ea0SNaohiro Aota 
1734ca5e4ea0SNaohiro Aota 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
1735ca5e4ea0SNaohiro Aota 		sb_end_write(fs_info->sb);
173618bb8bbfSJohannes Thumshirn 		return;
1737ca5e4ea0SNaohiro Aota 	}
173818bb8bbfSJohannes Thumshirn 
17399cc0b837SJohannes Thumshirn 	/*
17409cc0b837SJohannes Thumshirn 	 * Long running balances can keep us blocked here for eternity, so
17419cc0b837SJohannes Thumshirn 	 * simply skip reclaim if we're unable to get the mutex.
17429cc0b837SJohannes Thumshirn 	 */
17439cc0b837SJohannes Thumshirn 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) {
17449cc0b837SJohannes Thumshirn 		btrfs_exclop_finish(fs_info);
1745ca5e4ea0SNaohiro Aota 		sb_end_write(fs_info->sb);
17469cc0b837SJohannes Thumshirn 		return;
17479cc0b837SJohannes Thumshirn 	}
17489cc0b837SJohannes Thumshirn 
174918bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
17502ca0ec77SJohannes Thumshirn 	/*
17512ca0ec77SJohannes Thumshirn 	 * Sort happens under lock because we can't simply splice it and sort.
17522ca0ec77SJohannes Thumshirn 	 * The block groups might still be in use and reachable via bg_list,
17532ca0ec77SJohannes Thumshirn 	 * and their presence in the reclaim_bgs list must be preserved.
17542ca0ec77SJohannes Thumshirn 	 */
17552ca0ec77SJohannes Thumshirn 	list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp);
175618bb8bbfSJohannes Thumshirn 	while (!list_empty(&fs_info->reclaim_bgs)) {
17575f93e776SJohannes Thumshirn 		u64 zone_unusable;
17581cea5cf0SFilipe Manana 		int ret = 0;
17591cea5cf0SFilipe Manana 
176018bb8bbfSJohannes Thumshirn 		bg = list_first_entry(&fs_info->reclaim_bgs,
176118bb8bbfSJohannes Thumshirn 				      struct btrfs_block_group,
176218bb8bbfSJohannes Thumshirn 				      bg_list);
176318bb8bbfSJohannes Thumshirn 		list_del_init(&bg->bg_list);
176418bb8bbfSJohannes Thumshirn 
176518bb8bbfSJohannes Thumshirn 		space_info = bg->space_info;
176618bb8bbfSJohannes Thumshirn 		spin_unlock(&fs_info->unused_bgs_lock);
176718bb8bbfSJohannes Thumshirn 
176818bb8bbfSJohannes Thumshirn 		/* Don't race with allocators so take the groups_sem */
176918bb8bbfSJohannes Thumshirn 		down_write(&space_info->groups_sem);
177018bb8bbfSJohannes Thumshirn 
177118bb8bbfSJohannes Thumshirn 		spin_lock(&bg->lock);
177218bb8bbfSJohannes Thumshirn 		if (bg->reserved || bg->pinned || bg->ro) {
177318bb8bbfSJohannes Thumshirn 			/*
177418bb8bbfSJohannes Thumshirn 			 * We want to bail if we made new allocations or have
177518bb8bbfSJohannes Thumshirn 			 * outstanding allocations in this block group.  We do
177618bb8bbfSJohannes Thumshirn 			 * the ro check in case balance is currently acting on
177718bb8bbfSJohannes Thumshirn 			 * this block group.
177818bb8bbfSJohannes Thumshirn 			 */
177918bb8bbfSJohannes Thumshirn 			spin_unlock(&bg->lock);
178018bb8bbfSJohannes Thumshirn 			up_write(&space_info->groups_sem);
178118bb8bbfSJohannes Thumshirn 			goto next;
178218bb8bbfSJohannes Thumshirn 		}
1783cc4804bfSBoris Burkov 		if (bg->used == 0) {
1784cc4804bfSBoris Burkov 			/*
1785cc4804bfSBoris Burkov 			 * It is possible that we trigger relocation on a block
1786cc4804bfSBoris Burkov 			 * group as its extents are deleted and it first goes
1787cc4804bfSBoris Burkov 			 * below the threshold, then shortly after goes empty.
1788cc4804bfSBoris Burkov 			 *
1789cc4804bfSBoris Burkov 			 * In this case, relocating it does delete it, but has
1790cc4804bfSBoris Burkov 			 * some overhead in relocation specific metadata, looking
1791cc4804bfSBoris Burkov 			 * for the non-existent extents and running some extra
1792cc4804bfSBoris Burkov 			 * transactions, which we can avoid by using one of the
1793cc4804bfSBoris Burkov 			 * other mechanisms for dealing with empty block groups.
1794cc4804bfSBoris Burkov 			 */
1795cc4804bfSBoris Burkov 			if (!btrfs_test_opt(fs_info, DISCARD_ASYNC))
1796cc4804bfSBoris Burkov 				btrfs_mark_bg_unused(bg);
1797cc4804bfSBoris Burkov 			spin_unlock(&bg->lock);
1798cc4804bfSBoris Burkov 			up_write(&space_info->groups_sem);
1799cc4804bfSBoris Burkov 			goto next;
180081531225SBoris Burkov 
180181531225SBoris Burkov 		}
180281531225SBoris Burkov 		/*
180381531225SBoris Burkov 		 * The block group might no longer meet the reclaim condition by
180481531225SBoris Burkov 		 * the time we get around to reclaiming it, so to avoid
180581531225SBoris Burkov 		 * reclaiming overly full block_groups, skip reclaiming them.
180681531225SBoris Burkov 		 *
180781531225SBoris Burkov 		 * Since the decision making process also depends on the amount
180881531225SBoris Burkov 		 * being freed, pass in a fake giant value to skip that extra
180981531225SBoris Burkov 		 * check, which is more meaningful when adding to the list in
181081531225SBoris Burkov 		 * the first place.
181181531225SBoris Burkov 		 */
181281531225SBoris Burkov 		if (!should_reclaim_block_group(bg, bg->length)) {
181381531225SBoris Burkov 			spin_unlock(&bg->lock);
181481531225SBoris Burkov 			up_write(&space_info->groups_sem);
181581531225SBoris Burkov 			goto next;
1816cc4804bfSBoris Burkov 		}
181718bb8bbfSJohannes Thumshirn 		spin_unlock(&bg->lock);
181818bb8bbfSJohannes Thumshirn 
181918bb8bbfSJohannes Thumshirn 		/* Get out fast, in case we're unmounting the filesystem */
182018bb8bbfSJohannes Thumshirn 		if (btrfs_fs_closing(fs_info)) {
182118bb8bbfSJohannes Thumshirn 			up_write(&space_info->groups_sem);
182218bb8bbfSJohannes Thumshirn 			goto next;
182318bb8bbfSJohannes Thumshirn 		}
182418bb8bbfSJohannes Thumshirn 
18255f93e776SJohannes Thumshirn 		/*
18265f93e776SJohannes Thumshirn 		 * Cache the zone_unusable value before turning the block group
18275f93e776SJohannes Thumshirn 		 * to read only. As soon as the blog group is read only it's
18285f93e776SJohannes Thumshirn 		 * zone_unusable value gets moved to the block group's read-only
18295f93e776SJohannes Thumshirn 		 * bytes and isn't available for calculations anymore.
18305f93e776SJohannes Thumshirn 		 */
18315f93e776SJohannes Thumshirn 		zone_unusable = bg->zone_unusable;
183218bb8bbfSJohannes Thumshirn 		ret = inc_block_group_ro(bg, 0);
183318bb8bbfSJohannes Thumshirn 		up_write(&space_info->groups_sem);
183418bb8bbfSJohannes Thumshirn 		if (ret < 0)
183518bb8bbfSJohannes Thumshirn 			goto next;
183618bb8bbfSJohannes Thumshirn 
18375f93e776SJohannes Thumshirn 		btrfs_info(fs_info,
18385f93e776SJohannes Thumshirn 			"reclaiming chunk %llu with %llu%% used %llu%% unusable",
18395f93e776SJohannes Thumshirn 				bg->start, div_u64(bg->used * 100, bg->length),
18405f93e776SJohannes Thumshirn 				div64_u64(zone_unusable * 100, bg->length));
184118bb8bbfSJohannes Thumshirn 		trace_btrfs_reclaim_block_group(bg);
184218bb8bbfSJohannes Thumshirn 		ret = btrfs_relocate_chunk(fs_info, bg->start);
184374944c87SJosef Bacik 		if (ret) {
184474944c87SJosef Bacik 			btrfs_dec_block_group_ro(bg);
184518bb8bbfSJohannes Thumshirn 			btrfs_err(fs_info, "error relocating chunk %llu",
184618bb8bbfSJohannes Thumshirn 				  bg->start);
184774944c87SJosef Bacik 		}
184818bb8bbfSJohannes Thumshirn 
184918bb8bbfSJohannes Thumshirn next:
18501cea5cf0SFilipe Manana 		btrfs_put_block_group(bg);
1851d96b3424SFilipe Manana 		spin_lock(&fs_info->unused_bgs_lock);
185218bb8bbfSJohannes Thumshirn 	}
185318bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
185418bb8bbfSJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
185518bb8bbfSJohannes Thumshirn 	btrfs_exclop_finish(fs_info);
1856ca5e4ea0SNaohiro Aota 	sb_end_write(fs_info->sb);
185718bb8bbfSJohannes Thumshirn }
185818bb8bbfSJohannes Thumshirn 
185918bb8bbfSJohannes Thumshirn void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
186018bb8bbfSJohannes Thumshirn {
186118bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
186218bb8bbfSJohannes Thumshirn 	if (!list_empty(&fs_info->reclaim_bgs))
186318bb8bbfSJohannes Thumshirn 		queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
186418bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
186518bb8bbfSJohannes Thumshirn }
186618bb8bbfSJohannes Thumshirn 
186718bb8bbfSJohannes Thumshirn void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
186818bb8bbfSJohannes Thumshirn {
186918bb8bbfSJohannes Thumshirn 	struct btrfs_fs_info *fs_info = bg->fs_info;
187018bb8bbfSJohannes Thumshirn 
187118bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
187218bb8bbfSJohannes Thumshirn 	if (list_empty(&bg->bg_list)) {
187318bb8bbfSJohannes Thumshirn 		btrfs_get_block_group(bg);
187418bb8bbfSJohannes Thumshirn 		trace_btrfs_add_reclaim_block_group(bg);
187518bb8bbfSJohannes Thumshirn 		list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
187618bb8bbfSJohannes Thumshirn 	}
187718bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
187818bb8bbfSJohannes Thumshirn }
187918bb8bbfSJohannes Thumshirn 
1880e3ba67a1SJohannes Thumshirn static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1881e3ba67a1SJohannes Thumshirn 			   struct btrfs_path *path)
1882e3ba67a1SJohannes Thumshirn {
1883e3ba67a1SJohannes Thumshirn 	struct extent_map_tree *em_tree;
1884e3ba67a1SJohannes Thumshirn 	struct extent_map *em;
1885e3ba67a1SJohannes Thumshirn 	struct btrfs_block_group_item bg;
1886e3ba67a1SJohannes Thumshirn 	struct extent_buffer *leaf;
1887e3ba67a1SJohannes Thumshirn 	int slot;
1888e3ba67a1SJohannes Thumshirn 	u64 flags;
1889e3ba67a1SJohannes Thumshirn 	int ret = 0;
1890e3ba67a1SJohannes Thumshirn 
1891e3ba67a1SJohannes Thumshirn 	slot = path->slots[0];
1892e3ba67a1SJohannes Thumshirn 	leaf = path->nodes[0];
1893e3ba67a1SJohannes Thumshirn 
1894e3ba67a1SJohannes Thumshirn 	em_tree = &fs_info->mapping_tree;
1895e3ba67a1SJohannes Thumshirn 	read_lock(&em_tree->lock);
1896e3ba67a1SJohannes Thumshirn 	em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1897e3ba67a1SJohannes Thumshirn 	read_unlock(&em_tree->lock);
1898e3ba67a1SJohannes Thumshirn 	if (!em) {
1899e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1900e3ba67a1SJohannes Thumshirn 			  "logical %llu len %llu found bg but no related chunk",
1901e3ba67a1SJohannes Thumshirn 			  key->objectid, key->offset);
1902e3ba67a1SJohannes Thumshirn 		return -ENOENT;
1903e3ba67a1SJohannes Thumshirn 	}
1904e3ba67a1SJohannes Thumshirn 
1905e3ba67a1SJohannes Thumshirn 	if (em->start != key->objectid || em->len != key->offset) {
1906e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1907e3ba67a1SJohannes Thumshirn 			"block group %llu len %llu mismatch with chunk %llu len %llu",
1908e3ba67a1SJohannes Thumshirn 			key->objectid, key->offset, em->start, em->len);
1909e3ba67a1SJohannes Thumshirn 		ret = -EUCLEAN;
1910e3ba67a1SJohannes Thumshirn 		goto out_free_em;
1911e3ba67a1SJohannes Thumshirn 	}
1912e3ba67a1SJohannes Thumshirn 
1913e3ba67a1SJohannes Thumshirn 	read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1914e3ba67a1SJohannes Thumshirn 			   sizeof(bg));
1915e3ba67a1SJohannes Thumshirn 	flags = btrfs_stack_block_group_flags(&bg) &
1916e3ba67a1SJohannes Thumshirn 		BTRFS_BLOCK_GROUP_TYPE_MASK;
1917e3ba67a1SJohannes Thumshirn 
1918e3ba67a1SJohannes Thumshirn 	if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1919e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1920e3ba67a1SJohannes Thumshirn "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1921e3ba67a1SJohannes Thumshirn 			  key->objectid, key->offset, flags,
1922e3ba67a1SJohannes Thumshirn 			  (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1923e3ba67a1SJohannes Thumshirn 		ret = -EUCLEAN;
1924e3ba67a1SJohannes Thumshirn 	}
1925e3ba67a1SJohannes Thumshirn 
1926e3ba67a1SJohannes Thumshirn out_free_em:
1927e3ba67a1SJohannes Thumshirn 	free_extent_map(em);
1928e3ba67a1SJohannes Thumshirn 	return ret;
1929e3ba67a1SJohannes Thumshirn }
1930e3ba67a1SJohannes Thumshirn 
19314358d963SJosef Bacik static int find_first_block_group(struct btrfs_fs_info *fs_info,
19324358d963SJosef Bacik 				  struct btrfs_path *path,
19334358d963SJosef Bacik 				  struct btrfs_key *key)
19344358d963SJosef Bacik {
1935dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
1936e3ba67a1SJohannes Thumshirn 	int ret;
19374358d963SJosef Bacik 	struct btrfs_key found_key;
19384358d963SJosef Bacik 
193936dfbbe2SGabriel Niebler 	btrfs_for_each_slot(root, key, &found_key, path, ret) {
19404358d963SJosef Bacik 		if (found_key.objectid >= key->objectid &&
19414358d963SJosef Bacik 		    found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
194236dfbbe2SGabriel Niebler 			return read_bg_from_eb(fs_info, &found_key, path);
1943e3ba67a1SJohannes Thumshirn 		}
19444358d963SJosef Bacik 	}
19454358d963SJosef Bacik 	return ret;
19464358d963SJosef Bacik }
19474358d963SJosef Bacik 
19484358d963SJosef Bacik static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
19494358d963SJosef Bacik {
19504358d963SJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
19514358d963SJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
19524358d963SJosef Bacik 
19534358d963SJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
19544358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
19554358d963SJosef Bacik 		fs_info->avail_data_alloc_bits |= extra_flags;
19564358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
19574358d963SJosef Bacik 		fs_info->avail_metadata_alloc_bits |= extra_flags;
19584358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
19594358d963SJosef Bacik 		fs_info->avail_system_alloc_bits |= extra_flags;
19604358d963SJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
19614358d963SJosef Bacik }
19624358d963SJosef Bacik 
196343dd529aSDavid Sterba /*
196443dd529aSDavid Sterba  * Map a physical disk address to a list of logical addresses.
19659ee9b979SNikolay Borisov  *
19669ee9b979SNikolay Borisov  * @fs_info:       the filesystem
196796a14336SNikolay Borisov  * @chunk_start:   logical address of block group
1968138082f3SNaohiro Aota  * @bdev:	   physical device to resolve, can be NULL to indicate any device
196996a14336SNikolay Borisov  * @physical:	   physical address to map to logical addresses
197096a14336SNikolay Borisov  * @logical:	   return array of logical addresses which map to @physical
197196a14336SNikolay Borisov  * @naddrs:	   length of @logical
197296a14336SNikolay Borisov  * @stripe_len:    size of IO stripe for the given block group
197396a14336SNikolay Borisov  *
197496a14336SNikolay Borisov  * Maps a particular @physical disk address to a list of @logical addresses.
197596a14336SNikolay Borisov  * Used primarily to exclude those portions of a block group that contain super
197696a14336SNikolay Borisov  * block copies.
197796a14336SNikolay Borisov  */
197896a14336SNikolay Borisov int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1979138082f3SNaohiro Aota 		     struct block_device *bdev, u64 physical, u64 **logical,
1980138082f3SNaohiro Aota 		     int *naddrs, int *stripe_len)
198196a14336SNikolay Borisov {
198296a14336SNikolay Borisov 	struct extent_map *em;
198396a14336SNikolay Borisov 	struct map_lookup *map;
198496a14336SNikolay Borisov 	u64 *buf;
198596a14336SNikolay Borisov 	u64 bytenr;
19861776ad17SNikolay Borisov 	u64 data_stripe_length;
19871776ad17SNikolay Borisov 	u64 io_stripe_size;
19881776ad17SNikolay Borisov 	int i, nr = 0;
19891776ad17SNikolay Borisov 	int ret = 0;
199096a14336SNikolay Borisov 
199196a14336SNikolay Borisov 	em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
199296a14336SNikolay Borisov 	if (IS_ERR(em))
199396a14336SNikolay Borisov 		return -EIO;
199496a14336SNikolay Borisov 
199596a14336SNikolay Borisov 	map = em->map_lookup;
19969e22b925SNikolay Borisov 	data_stripe_length = em->orig_block_len;
19971776ad17SNikolay Borisov 	io_stripe_size = map->stripe_len;
1998138082f3SNaohiro Aota 	chunk_start = em->start;
199996a14336SNikolay Borisov 
20009e22b925SNikolay Borisov 	/* For RAID5/6 adjust to a full IO stripe length */
20019e22b925SNikolay Borisov 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
20021776ad17SNikolay Borisov 		io_stripe_size = map->stripe_len * nr_data_stripes(map);
200396a14336SNikolay Borisov 
200496a14336SNikolay Borisov 	buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
20051776ad17SNikolay Borisov 	if (!buf) {
20061776ad17SNikolay Borisov 		ret = -ENOMEM;
20071776ad17SNikolay Borisov 		goto out;
20081776ad17SNikolay Borisov 	}
200996a14336SNikolay Borisov 
201096a14336SNikolay Borisov 	for (i = 0; i < map->num_stripes; i++) {
20111776ad17SNikolay Borisov 		bool already_inserted = false;
20121776ad17SNikolay Borisov 		u64 stripe_nr;
2013138082f3SNaohiro Aota 		u64 offset;
20141776ad17SNikolay Borisov 		int j;
20151776ad17SNikolay Borisov 
20161776ad17SNikolay Borisov 		if (!in_range(physical, map->stripes[i].physical,
20171776ad17SNikolay Borisov 			      data_stripe_length))
201896a14336SNikolay Borisov 			continue;
201996a14336SNikolay Borisov 
2020138082f3SNaohiro Aota 		if (bdev && map->stripes[i].dev->bdev != bdev)
2021138082f3SNaohiro Aota 			continue;
2022138082f3SNaohiro Aota 
202396a14336SNikolay Borisov 		stripe_nr = physical - map->stripes[i].physical;
2024138082f3SNaohiro Aota 		stripe_nr = div64_u64_rem(stripe_nr, map->stripe_len, &offset);
202596a14336SNikolay Borisov 
2026ac067734SDavid Sterba 		if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
2027ac067734SDavid Sterba 				 BTRFS_BLOCK_GROUP_RAID10)) {
202896a14336SNikolay Borisov 			stripe_nr = stripe_nr * map->num_stripes + i;
202996a14336SNikolay Borisov 			stripe_nr = div_u64(stripe_nr, map->sub_stripes);
203096a14336SNikolay Borisov 		}
203196a14336SNikolay Borisov 		/*
203296a14336SNikolay Borisov 		 * The remaining case would be for RAID56, multiply by
203396a14336SNikolay Borisov 		 * nr_data_stripes().  Alternatively, just use rmap_len below
203496a14336SNikolay Borisov 		 * instead of map->stripe_len
203596a14336SNikolay Borisov 		 */
203696a14336SNikolay Borisov 
2037138082f3SNaohiro Aota 		bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
20381776ad17SNikolay Borisov 
20391776ad17SNikolay Borisov 		/* Ensure we don't add duplicate addresses */
204096a14336SNikolay Borisov 		for (j = 0; j < nr; j++) {
20411776ad17SNikolay Borisov 			if (buf[j] == bytenr) {
20421776ad17SNikolay Borisov 				already_inserted = true;
204396a14336SNikolay Borisov 				break;
204496a14336SNikolay Borisov 			}
204596a14336SNikolay Borisov 		}
20461776ad17SNikolay Borisov 
20471776ad17SNikolay Borisov 		if (!already_inserted)
20481776ad17SNikolay Borisov 			buf[nr++] = bytenr;
204996a14336SNikolay Borisov 	}
205096a14336SNikolay Borisov 
205196a14336SNikolay Borisov 	*logical = buf;
205296a14336SNikolay Borisov 	*naddrs = nr;
20531776ad17SNikolay Borisov 	*stripe_len = io_stripe_size;
20541776ad17SNikolay Borisov out:
205596a14336SNikolay Borisov 	free_extent_map(em);
20561776ad17SNikolay Borisov 	return ret;
205796a14336SNikolay Borisov }
205896a14336SNikolay Borisov 
205932da5386SDavid Sterba static int exclude_super_stripes(struct btrfs_block_group *cache)
20604358d963SJosef Bacik {
20614358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
206212659251SNaohiro Aota 	const bool zoned = btrfs_is_zoned(fs_info);
20634358d963SJosef Bacik 	u64 bytenr;
20644358d963SJosef Bacik 	u64 *logical;
20654358d963SJosef Bacik 	int stripe_len;
20664358d963SJosef Bacik 	int i, nr, ret;
20674358d963SJosef Bacik 
2068b3470b5dSDavid Sterba 	if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
2069b3470b5dSDavid Sterba 		stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
20704358d963SJosef Bacik 		cache->bytes_super += stripe_len;
2071b3470b5dSDavid Sterba 		ret = btrfs_add_excluded_extent(fs_info, cache->start,
20724358d963SJosef Bacik 						stripe_len);
20734358d963SJosef Bacik 		if (ret)
20744358d963SJosef Bacik 			return ret;
20754358d963SJosef Bacik 	}
20764358d963SJosef Bacik 
20774358d963SJosef Bacik 	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
20784358d963SJosef Bacik 		bytenr = btrfs_sb_offset(i);
2079138082f3SNaohiro Aota 		ret = btrfs_rmap_block(fs_info, cache->start, NULL,
20804358d963SJosef Bacik 				       bytenr, &logical, &nr, &stripe_len);
20814358d963SJosef Bacik 		if (ret)
20824358d963SJosef Bacik 			return ret;
20834358d963SJosef Bacik 
208412659251SNaohiro Aota 		/* Shouldn't have super stripes in sequential zones */
208512659251SNaohiro Aota 		if (zoned && nr) {
208612659251SNaohiro Aota 			btrfs_err(fs_info,
208712659251SNaohiro Aota 			"zoned: block group %llu must not contain super block",
208812659251SNaohiro Aota 				  cache->start);
208912659251SNaohiro Aota 			return -EUCLEAN;
209012659251SNaohiro Aota 		}
209112659251SNaohiro Aota 
20924358d963SJosef Bacik 		while (nr--) {
209396f9b0f2SNikolay Borisov 			u64 len = min_t(u64, stripe_len,
209496f9b0f2SNikolay Borisov 				cache->start + cache->length - logical[nr]);
20954358d963SJosef Bacik 
20964358d963SJosef Bacik 			cache->bytes_super += len;
209796f9b0f2SNikolay Borisov 			ret = btrfs_add_excluded_extent(fs_info, logical[nr],
209896f9b0f2SNikolay Borisov 							len);
20994358d963SJosef Bacik 			if (ret) {
21004358d963SJosef Bacik 				kfree(logical);
21014358d963SJosef Bacik 				return ret;
21024358d963SJosef Bacik 			}
21034358d963SJosef Bacik 		}
21044358d963SJosef Bacik 
21054358d963SJosef Bacik 		kfree(logical);
21064358d963SJosef Bacik 	}
21074358d963SJosef Bacik 	return 0;
21084358d963SJosef Bacik }
21094358d963SJosef Bacik 
211032da5386SDavid Sterba static struct btrfs_block_group *btrfs_create_block_group_cache(
21119afc6649SQu Wenruo 		struct btrfs_fs_info *fs_info, u64 start)
21124358d963SJosef Bacik {
211332da5386SDavid Sterba 	struct btrfs_block_group *cache;
21144358d963SJosef Bacik 
21154358d963SJosef Bacik 	cache = kzalloc(sizeof(*cache), GFP_NOFS);
21164358d963SJosef Bacik 	if (!cache)
21174358d963SJosef Bacik 		return NULL;
21184358d963SJosef Bacik 
21194358d963SJosef Bacik 	cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
21204358d963SJosef Bacik 					GFP_NOFS);
21214358d963SJosef Bacik 	if (!cache->free_space_ctl) {
21224358d963SJosef Bacik 		kfree(cache);
21234358d963SJosef Bacik 		return NULL;
21244358d963SJosef Bacik 	}
21254358d963SJosef Bacik 
2126b3470b5dSDavid Sterba 	cache->start = start;
21274358d963SJosef Bacik 
21284358d963SJosef Bacik 	cache->fs_info = fs_info;
21294358d963SJosef Bacik 	cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
21304358d963SJosef Bacik 
21316e80d4f8SDennis Zhou 	cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
21326e80d4f8SDennis Zhou 
213348aaeebeSJosef Bacik 	refcount_set(&cache->refs, 1);
21344358d963SJosef Bacik 	spin_lock_init(&cache->lock);
21354358d963SJosef Bacik 	init_rwsem(&cache->data_rwsem);
21364358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->list);
21374358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->cluster_list);
21384358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->bg_list);
21394358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->ro_list);
2140b0643e59SDennis Zhou 	INIT_LIST_HEAD(&cache->discard_list);
21414358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->dirty_list);
21424358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->io_list);
2143afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&cache->active_bg_list);
2144cd79909bSJosef Bacik 	btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
21456b7304afSFilipe Manana 	atomic_set(&cache->frozen, 0);
21464358d963SJosef Bacik 	mutex_init(&cache->free_space_lock);
2147c29abab4SJosef Bacik 	cache->full_stripe_locks_root.root = RB_ROOT;
2148c29abab4SJosef Bacik 	mutex_init(&cache->full_stripe_locks_root.lock);
21494358d963SJosef Bacik 
21504358d963SJosef Bacik 	return cache;
21514358d963SJosef Bacik }
21524358d963SJosef Bacik 
21534358d963SJosef Bacik /*
21544358d963SJosef Bacik  * Iterate all chunks and verify that each of them has the corresponding block
21554358d963SJosef Bacik  * group
21564358d963SJosef Bacik  */
21574358d963SJosef Bacik static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
21584358d963SJosef Bacik {
21594358d963SJosef Bacik 	struct extent_map_tree *map_tree = &fs_info->mapping_tree;
21604358d963SJosef Bacik 	struct extent_map *em;
216132da5386SDavid Sterba 	struct btrfs_block_group *bg;
21624358d963SJosef Bacik 	u64 start = 0;
21634358d963SJosef Bacik 	int ret = 0;
21644358d963SJosef Bacik 
21654358d963SJosef Bacik 	while (1) {
21664358d963SJosef Bacik 		read_lock(&map_tree->lock);
21674358d963SJosef Bacik 		/*
21684358d963SJosef Bacik 		 * lookup_extent_mapping will return the first extent map
21694358d963SJosef Bacik 		 * intersecting the range, so setting @len to 1 is enough to
21704358d963SJosef Bacik 		 * get the first chunk.
21714358d963SJosef Bacik 		 */
21724358d963SJosef Bacik 		em = lookup_extent_mapping(map_tree, start, 1);
21734358d963SJosef Bacik 		read_unlock(&map_tree->lock);
21744358d963SJosef Bacik 		if (!em)
21754358d963SJosef Bacik 			break;
21764358d963SJosef Bacik 
21774358d963SJosef Bacik 		bg = btrfs_lookup_block_group(fs_info, em->start);
21784358d963SJosef Bacik 		if (!bg) {
21794358d963SJosef Bacik 			btrfs_err(fs_info,
21804358d963SJosef Bacik 	"chunk start=%llu len=%llu doesn't have corresponding block group",
21814358d963SJosef Bacik 				     em->start, em->len);
21824358d963SJosef Bacik 			ret = -EUCLEAN;
21834358d963SJosef Bacik 			free_extent_map(em);
21844358d963SJosef Bacik 			break;
21854358d963SJosef Bacik 		}
2186b3470b5dSDavid Sterba 		if (bg->start != em->start || bg->length != em->len ||
21874358d963SJosef Bacik 		    (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
21884358d963SJosef Bacik 		    (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
21894358d963SJosef Bacik 			btrfs_err(fs_info,
21904358d963SJosef Bacik "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
21914358d963SJosef Bacik 				em->start, em->len,
21924358d963SJosef Bacik 				em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
2193b3470b5dSDavid Sterba 				bg->start, bg->length,
21944358d963SJosef Bacik 				bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
21954358d963SJosef Bacik 			ret = -EUCLEAN;
21964358d963SJosef Bacik 			free_extent_map(em);
21974358d963SJosef Bacik 			btrfs_put_block_group(bg);
21984358d963SJosef Bacik 			break;
21994358d963SJosef Bacik 		}
22004358d963SJosef Bacik 		start = em->start + em->len;
22014358d963SJosef Bacik 		free_extent_map(em);
22024358d963SJosef Bacik 		btrfs_put_block_group(bg);
22034358d963SJosef Bacik 	}
22044358d963SJosef Bacik 	return ret;
22054358d963SJosef Bacik }
22064358d963SJosef Bacik 
2207ffb9e0f0SQu Wenruo static int read_one_block_group(struct btrfs_fs_info *info,
22084afd2fe8SJohannes Thumshirn 				struct btrfs_block_group_item *bgi,
2209d49a2ddbSQu Wenruo 				const struct btrfs_key *key,
2210ffb9e0f0SQu Wenruo 				int need_clear)
2211ffb9e0f0SQu Wenruo {
221232da5386SDavid Sterba 	struct btrfs_block_group *cache;
2213ffb9e0f0SQu Wenruo 	const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
2214ffb9e0f0SQu Wenruo 	int ret;
2215ffb9e0f0SQu Wenruo 
2216d49a2ddbSQu Wenruo 	ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
2217ffb9e0f0SQu Wenruo 
22189afc6649SQu Wenruo 	cache = btrfs_create_block_group_cache(info, key->objectid);
2219ffb9e0f0SQu Wenruo 	if (!cache)
2220ffb9e0f0SQu Wenruo 		return -ENOMEM;
2221ffb9e0f0SQu Wenruo 
22224afd2fe8SJohannes Thumshirn 	cache->length = key->offset;
22234afd2fe8SJohannes Thumshirn 	cache->used = btrfs_stack_block_group_used(bgi);
22247248e0ceSQu Wenruo 	cache->commit_used = cache->used;
22254afd2fe8SJohannes Thumshirn 	cache->flags = btrfs_stack_block_group_flags(bgi);
2226f7238e50SJosef Bacik 	cache->global_root_id = btrfs_stack_block_group_chunk_objectid(bgi);
22279afc6649SQu Wenruo 
2228e3e39c72SMarcos Paulo de Souza 	set_free_space_tree_thresholds(cache);
2229e3e39c72SMarcos Paulo de Souza 
2230ffb9e0f0SQu Wenruo 	if (need_clear) {
2231ffb9e0f0SQu Wenruo 		/*
2232ffb9e0f0SQu Wenruo 		 * When we mount with old space cache, we need to
2233ffb9e0f0SQu Wenruo 		 * set BTRFS_DC_CLEAR and set dirty flag.
2234ffb9e0f0SQu Wenruo 		 *
2235ffb9e0f0SQu Wenruo 		 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
2236ffb9e0f0SQu Wenruo 		 *    truncate the old free space cache inode and
2237ffb9e0f0SQu Wenruo 		 *    setup a new one.
2238ffb9e0f0SQu Wenruo 		 * b) Setting 'dirty flag' makes sure that we flush
2239ffb9e0f0SQu Wenruo 		 *    the new space cache info onto disk.
2240ffb9e0f0SQu Wenruo 		 */
2241ffb9e0f0SQu Wenruo 		if (btrfs_test_opt(info, SPACE_CACHE))
2242ffb9e0f0SQu Wenruo 			cache->disk_cache_state = BTRFS_DC_CLEAR;
2243ffb9e0f0SQu Wenruo 	}
2244ffb9e0f0SQu Wenruo 	if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
2245ffb9e0f0SQu Wenruo 	    (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
2246ffb9e0f0SQu Wenruo 			btrfs_err(info,
2247ffb9e0f0SQu Wenruo "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2248ffb9e0f0SQu Wenruo 				  cache->start);
2249ffb9e0f0SQu Wenruo 			ret = -EINVAL;
2250ffb9e0f0SQu Wenruo 			goto error;
2251ffb9e0f0SQu Wenruo 	}
2252ffb9e0f0SQu Wenruo 
2253a94794d5SNaohiro Aota 	ret = btrfs_load_block_group_zone_info(cache, false);
225408e11a3dSNaohiro Aota 	if (ret) {
225508e11a3dSNaohiro Aota 		btrfs_err(info, "zoned: failed to load zone info of bg %llu",
225608e11a3dSNaohiro Aota 			  cache->start);
225708e11a3dSNaohiro Aota 		goto error;
225808e11a3dSNaohiro Aota 	}
225908e11a3dSNaohiro Aota 
2260ffb9e0f0SQu Wenruo 	/*
2261ffb9e0f0SQu Wenruo 	 * We need to exclude the super stripes now so that the space info has
2262ffb9e0f0SQu Wenruo 	 * super bytes accounted for, otherwise we'll think we have more space
2263ffb9e0f0SQu Wenruo 	 * than we actually do.
2264ffb9e0f0SQu Wenruo 	 */
2265ffb9e0f0SQu Wenruo 	ret = exclude_super_stripes(cache);
2266ffb9e0f0SQu Wenruo 	if (ret) {
2267ffb9e0f0SQu Wenruo 		/* We may have excluded something, so call this just in case. */
2268ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2269ffb9e0f0SQu Wenruo 		goto error;
2270ffb9e0f0SQu Wenruo 	}
2271ffb9e0f0SQu Wenruo 
2272ffb9e0f0SQu Wenruo 	/*
2273169e0da9SNaohiro Aota 	 * For zoned filesystem, space after the allocation offset is the only
2274169e0da9SNaohiro Aota 	 * free space for a block group. So, we don't need any caching work.
2275169e0da9SNaohiro Aota 	 * btrfs_calc_zone_unusable() will set the amount of free space and
2276169e0da9SNaohiro Aota 	 * zone_unusable space.
2277169e0da9SNaohiro Aota 	 *
2278169e0da9SNaohiro Aota 	 * For regular filesystem, check for two cases, either we are full, and
2279169e0da9SNaohiro Aota 	 * therefore don't need to bother with the caching work since we won't
2280169e0da9SNaohiro Aota 	 * find any space, or we are empty, and we can just add all the space
2281169e0da9SNaohiro Aota 	 * in and be done with it.  This saves us _a_lot_ of time, particularly
2282169e0da9SNaohiro Aota 	 * in the full case.
2283ffb9e0f0SQu Wenruo 	 */
2284169e0da9SNaohiro Aota 	if (btrfs_is_zoned(info)) {
2285169e0da9SNaohiro Aota 		btrfs_calc_zone_unusable(cache);
2286c46c4247SNaohiro Aota 		/* Should not have any excluded extents. Just in case, though. */
2287c46c4247SNaohiro Aota 		btrfs_free_excluded_extents(cache);
2288169e0da9SNaohiro Aota 	} else if (cache->length == cache->used) {
2289ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
2290ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2291ffb9e0f0SQu Wenruo 	} else if (cache->used == 0) {
2292ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
22939afc6649SQu Wenruo 		add_new_free_space(cache, cache->start,
22949afc6649SQu Wenruo 				   cache->start + cache->length);
2295ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2296ffb9e0f0SQu Wenruo 	}
2297ffb9e0f0SQu Wenruo 
2298ffb9e0f0SQu Wenruo 	ret = btrfs_add_block_group_cache(info, cache);
2299ffb9e0f0SQu Wenruo 	if (ret) {
2300ffb9e0f0SQu Wenruo 		btrfs_remove_free_space_cache(cache);
2301ffb9e0f0SQu Wenruo 		goto error;
2302ffb9e0f0SQu Wenruo 	}
2303ffb9e0f0SQu Wenruo 	trace_btrfs_add_block_group(info, cache, 0);
2304723de71dSJosef Bacik 	btrfs_add_bg_to_space_info(info, cache);
2305ffb9e0f0SQu Wenruo 
2306ffb9e0f0SQu Wenruo 	set_avail_alloc_bits(info, cache->flags);
2307a09f23c3SAnand Jain 	if (btrfs_chunk_writeable(info, cache->start)) {
2308a09f23c3SAnand Jain 		if (cache->used == 0) {
2309ffb9e0f0SQu Wenruo 			ASSERT(list_empty(&cache->bg_list));
23106e80d4f8SDennis Zhou 			if (btrfs_test_opt(info, DISCARD_ASYNC))
23116e80d4f8SDennis Zhou 				btrfs_discard_queue_work(&info->discard_ctl, cache);
23126e80d4f8SDennis Zhou 			else
2313ffb9e0f0SQu Wenruo 				btrfs_mark_bg_unused(cache);
2314ffb9e0f0SQu Wenruo 		}
2315a09f23c3SAnand Jain 	} else {
2316a09f23c3SAnand Jain 		inc_block_group_ro(cache, 1);
2317a09f23c3SAnand Jain 	}
2318a09f23c3SAnand Jain 
2319ffb9e0f0SQu Wenruo 	return 0;
2320ffb9e0f0SQu Wenruo error:
2321ffb9e0f0SQu Wenruo 	btrfs_put_block_group(cache);
2322ffb9e0f0SQu Wenruo 	return ret;
2323ffb9e0f0SQu Wenruo }
2324ffb9e0f0SQu Wenruo 
232542437a63SJosef Bacik static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
232642437a63SJosef Bacik {
232742437a63SJosef Bacik 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
232842437a63SJosef Bacik 	struct rb_node *node;
232942437a63SJosef Bacik 	int ret = 0;
233042437a63SJosef Bacik 
233142437a63SJosef Bacik 	for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
233242437a63SJosef Bacik 		struct extent_map *em;
233342437a63SJosef Bacik 		struct map_lookup *map;
233442437a63SJosef Bacik 		struct btrfs_block_group *bg;
233542437a63SJosef Bacik 
233642437a63SJosef Bacik 		em = rb_entry(node, struct extent_map, rb_node);
233742437a63SJosef Bacik 		map = em->map_lookup;
233842437a63SJosef Bacik 		bg = btrfs_create_block_group_cache(fs_info, em->start);
233942437a63SJosef Bacik 		if (!bg) {
234042437a63SJosef Bacik 			ret = -ENOMEM;
234142437a63SJosef Bacik 			break;
234242437a63SJosef Bacik 		}
234342437a63SJosef Bacik 
234442437a63SJosef Bacik 		/* Fill dummy cache as FULL */
234542437a63SJosef Bacik 		bg->length = em->len;
234642437a63SJosef Bacik 		bg->flags = map->type;
234742437a63SJosef Bacik 		bg->cached = BTRFS_CACHE_FINISHED;
234842437a63SJosef Bacik 		bg->used = em->len;
234942437a63SJosef Bacik 		bg->flags = map->type;
235042437a63SJosef Bacik 		ret = btrfs_add_block_group_cache(fs_info, bg);
23512b29726cSQu Wenruo 		/*
23522b29726cSQu Wenruo 		 * We may have some valid block group cache added already, in
23532b29726cSQu Wenruo 		 * that case we skip to the next one.
23542b29726cSQu Wenruo 		 */
23552b29726cSQu Wenruo 		if (ret == -EEXIST) {
23562b29726cSQu Wenruo 			ret = 0;
23572b29726cSQu Wenruo 			btrfs_put_block_group(bg);
23582b29726cSQu Wenruo 			continue;
23592b29726cSQu Wenruo 		}
23602b29726cSQu Wenruo 
236142437a63SJosef Bacik 		if (ret) {
236242437a63SJosef Bacik 			btrfs_remove_free_space_cache(bg);
236342437a63SJosef Bacik 			btrfs_put_block_group(bg);
236442437a63SJosef Bacik 			break;
236542437a63SJosef Bacik 		}
23662b29726cSQu Wenruo 
2367723de71dSJosef Bacik 		btrfs_add_bg_to_space_info(fs_info, bg);
236842437a63SJosef Bacik 
236942437a63SJosef Bacik 		set_avail_alloc_bits(fs_info, bg->flags);
237042437a63SJosef Bacik 	}
237142437a63SJosef Bacik 	if (!ret)
237242437a63SJosef Bacik 		btrfs_init_global_block_rsv(fs_info);
237342437a63SJosef Bacik 	return ret;
237442437a63SJosef Bacik }
237542437a63SJosef Bacik 
23764358d963SJosef Bacik int btrfs_read_block_groups(struct btrfs_fs_info *info)
23774358d963SJosef Bacik {
2378dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(info);
23794358d963SJosef Bacik 	struct btrfs_path *path;
23804358d963SJosef Bacik 	int ret;
238132da5386SDavid Sterba 	struct btrfs_block_group *cache;
23824358d963SJosef Bacik 	struct btrfs_space_info *space_info;
23834358d963SJosef Bacik 	struct btrfs_key key;
23844358d963SJosef Bacik 	int need_clear = 0;
23854358d963SJosef Bacik 	u64 cache_gen;
23864358d963SJosef Bacik 
238781d5d614SQu Wenruo 	/*
238881d5d614SQu Wenruo 	 * Either no extent root (with ibadroots rescue option) or we have
238981d5d614SQu Wenruo 	 * unsupported RO options. The fs can never be mounted read-write, so no
239081d5d614SQu Wenruo 	 * need to waste time searching block group items.
239181d5d614SQu Wenruo 	 *
239281d5d614SQu Wenruo 	 * This also allows new extent tree related changes to be RO compat,
239381d5d614SQu Wenruo 	 * no need for a full incompat flag.
239481d5d614SQu Wenruo 	 */
239581d5d614SQu Wenruo 	if (!root || (btrfs_super_compat_ro_flags(info->super_copy) &
239681d5d614SQu Wenruo 		      ~BTRFS_FEATURE_COMPAT_RO_SUPP))
239742437a63SJosef Bacik 		return fill_dummy_bgs(info);
239842437a63SJosef Bacik 
23994358d963SJosef Bacik 	key.objectid = 0;
24004358d963SJosef Bacik 	key.offset = 0;
24014358d963SJosef Bacik 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
24024358d963SJosef Bacik 	path = btrfs_alloc_path();
24034358d963SJosef Bacik 	if (!path)
24044358d963SJosef Bacik 		return -ENOMEM;
24054358d963SJosef Bacik 
24064358d963SJosef Bacik 	cache_gen = btrfs_super_cache_generation(info->super_copy);
24074358d963SJosef Bacik 	if (btrfs_test_opt(info, SPACE_CACHE) &&
24084358d963SJosef Bacik 	    btrfs_super_generation(info->super_copy) != cache_gen)
24094358d963SJosef Bacik 		need_clear = 1;
24104358d963SJosef Bacik 	if (btrfs_test_opt(info, CLEAR_CACHE))
24114358d963SJosef Bacik 		need_clear = 1;
24124358d963SJosef Bacik 
24134358d963SJosef Bacik 	while (1) {
24144afd2fe8SJohannes Thumshirn 		struct btrfs_block_group_item bgi;
24154afd2fe8SJohannes Thumshirn 		struct extent_buffer *leaf;
24164afd2fe8SJohannes Thumshirn 		int slot;
24174afd2fe8SJohannes Thumshirn 
24184358d963SJosef Bacik 		ret = find_first_block_group(info, path, &key);
24194358d963SJosef Bacik 		if (ret > 0)
24204358d963SJosef Bacik 			break;
24214358d963SJosef Bacik 		if (ret != 0)
24224358d963SJosef Bacik 			goto error;
24234358d963SJosef Bacik 
24244afd2fe8SJohannes Thumshirn 		leaf = path->nodes[0];
24254afd2fe8SJohannes Thumshirn 		slot = path->slots[0];
24264afd2fe8SJohannes Thumshirn 
24274afd2fe8SJohannes Thumshirn 		read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
24284afd2fe8SJohannes Thumshirn 				   sizeof(bgi));
24294afd2fe8SJohannes Thumshirn 
24304afd2fe8SJohannes Thumshirn 		btrfs_item_key_to_cpu(leaf, &key, slot);
24314afd2fe8SJohannes Thumshirn 		btrfs_release_path(path);
24324afd2fe8SJohannes Thumshirn 		ret = read_one_block_group(info, &bgi, &key, need_clear);
2433ffb9e0f0SQu Wenruo 		if (ret < 0)
24344358d963SJosef Bacik 			goto error;
2435ffb9e0f0SQu Wenruo 		key.objectid += key.offset;
2436ffb9e0f0SQu Wenruo 		key.offset = 0;
24374358d963SJosef Bacik 	}
24387837fa88SJosef Bacik 	btrfs_release_path(path);
24394358d963SJosef Bacik 
244072804905SJosef Bacik 	list_for_each_entry(space_info, &info->space_info, list) {
244149ea112dSJosef Bacik 		int i;
244249ea112dSJosef Bacik 
244349ea112dSJosef Bacik 		for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
244449ea112dSJosef Bacik 			if (list_empty(&space_info->block_groups[i]))
244549ea112dSJosef Bacik 				continue;
244649ea112dSJosef Bacik 			cache = list_first_entry(&space_info->block_groups[i],
244749ea112dSJosef Bacik 						 struct btrfs_block_group,
244849ea112dSJosef Bacik 						 list);
244949ea112dSJosef Bacik 			btrfs_sysfs_add_block_group_type(cache);
245049ea112dSJosef Bacik 		}
245149ea112dSJosef Bacik 
24524358d963SJosef Bacik 		if (!(btrfs_get_alloc_profile(info, space_info->flags) &
24534358d963SJosef Bacik 		      (BTRFS_BLOCK_GROUP_RAID10 |
24544358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID1_MASK |
24554358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID56_MASK |
24564358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_DUP)))
24574358d963SJosef Bacik 			continue;
24584358d963SJosef Bacik 		/*
24594358d963SJosef Bacik 		 * Avoid allocating from un-mirrored block group if there are
24604358d963SJosef Bacik 		 * mirrored block groups.
24614358d963SJosef Bacik 		 */
24624358d963SJosef Bacik 		list_for_each_entry(cache,
24634358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_RAID0],
24644358d963SJosef Bacik 				list)
2465e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
24664358d963SJosef Bacik 		list_for_each_entry(cache,
24674358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_SINGLE],
24684358d963SJosef Bacik 				list)
2469e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
24704358d963SJosef Bacik 	}
24714358d963SJosef Bacik 
24724358d963SJosef Bacik 	btrfs_init_global_block_rsv(info);
24734358d963SJosef Bacik 	ret = check_chunk_block_group_mappings(info);
24744358d963SJosef Bacik error:
24754358d963SJosef Bacik 	btrfs_free_path(path);
24762b29726cSQu Wenruo 	/*
24772b29726cSQu Wenruo 	 * We've hit some error while reading the extent tree, and have
24782b29726cSQu Wenruo 	 * rescue=ibadroots mount option.
24792b29726cSQu Wenruo 	 * Try to fill the tree using dummy block groups so that the user can
24802b29726cSQu Wenruo 	 * continue to mount and grab their data.
24812b29726cSQu Wenruo 	 */
24822b29726cSQu Wenruo 	if (ret && btrfs_test_opt(info, IGNOREBADROOTS))
24832b29726cSQu Wenruo 		ret = fill_dummy_bgs(info);
24844358d963SJosef Bacik 	return ret;
24854358d963SJosef Bacik }
24864358d963SJosef Bacik 
248779bd3712SFilipe Manana /*
248879bd3712SFilipe Manana  * This function, insert_block_group_item(), belongs to the phase 2 of chunk
248979bd3712SFilipe Manana  * allocation.
249079bd3712SFilipe Manana  *
249179bd3712SFilipe Manana  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
249279bd3712SFilipe Manana  * phases.
249379bd3712SFilipe Manana  */
249497f4728aSQu Wenruo static int insert_block_group_item(struct btrfs_trans_handle *trans,
249597f4728aSQu Wenruo 				   struct btrfs_block_group *block_group)
249697f4728aSQu Wenruo {
249797f4728aSQu Wenruo 	struct btrfs_fs_info *fs_info = trans->fs_info;
249897f4728aSQu Wenruo 	struct btrfs_block_group_item bgi;
2499dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
250097f4728aSQu Wenruo 	struct btrfs_key key;
250197f4728aSQu Wenruo 
250297f4728aSQu Wenruo 	spin_lock(&block_group->lock);
250397f4728aSQu Wenruo 	btrfs_set_stack_block_group_used(&bgi, block_group->used);
250497f4728aSQu Wenruo 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
2505f7238e50SJosef Bacik 						   block_group->global_root_id);
250697f4728aSQu Wenruo 	btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
250797f4728aSQu Wenruo 	key.objectid = block_group->start;
250897f4728aSQu Wenruo 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
250997f4728aSQu Wenruo 	key.offset = block_group->length;
251097f4728aSQu Wenruo 	spin_unlock(&block_group->lock);
251197f4728aSQu Wenruo 
251297f4728aSQu Wenruo 	return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
251397f4728aSQu Wenruo }
251497f4728aSQu Wenruo 
25152eadb9e7SNikolay Borisov static int insert_dev_extent(struct btrfs_trans_handle *trans,
25162eadb9e7SNikolay Borisov 			    struct btrfs_device *device, u64 chunk_offset,
25172eadb9e7SNikolay Borisov 			    u64 start, u64 num_bytes)
25182eadb9e7SNikolay Borisov {
25192eadb9e7SNikolay Borisov 	struct btrfs_fs_info *fs_info = device->fs_info;
25202eadb9e7SNikolay Borisov 	struct btrfs_root *root = fs_info->dev_root;
25212eadb9e7SNikolay Borisov 	struct btrfs_path *path;
25222eadb9e7SNikolay Borisov 	struct btrfs_dev_extent *extent;
25232eadb9e7SNikolay Borisov 	struct extent_buffer *leaf;
25242eadb9e7SNikolay Borisov 	struct btrfs_key key;
25252eadb9e7SNikolay Borisov 	int ret;
25262eadb9e7SNikolay Borisov 
25272eadb9e7SNikolay Borisov 	WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
25282eadb9e7SNikolay Borisov 	WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
25292eadb9e7SNikolay Borisov 	path = btrfs_alloc_path();
25302eadb9e7SNikolay Borisov 	if (!path)
25312eadb9e7SNikolay Borisov 		return -ENOMEM;
25322eadb9e7SNikolay Borisov 
25332eadb9e7SNikolay Borisov 	key.objectid = device->devid;
25342eadb9e7SNikolay Borisov 	key.type = BTRFS_DEV_EXTENT_KEY;
25352eadb9e7SNikolay Borisov 	key.offset = start;
25362eadb9e7SNikolay Borisov 	ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent));
25372eadb9e7SNikolay Borisov 	if (ret)
25382eadb9e7SNikolay Borisov 		goto out;
25392eadb9e7SNikolay Borisov 
25402eadb9e7SNikolay Borisov 	leaf = path->nodes[0];
25412eadb9e7SNikolay Borisov 	extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
25422eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID);
25432eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_objectid(leaf, extent,
25442eadb9e7SNikolay Borisov 					    BTRFS_FIRST_CHUNK_TREE_OBJECTID);
25452eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
25462eadb9e7SNikolay Borisov 
25472eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_length(leaf, extent, num_bytes);
25482eadb9e7SNikolay Borisov 	btrfs_mark_buffer_dirty(leaf);
25492eadb9e7SNikolay Borisov out:
25502eadb9e7SNikolay Borisov 	btrfs_free_path(path);
25512eadb9e7SNikolay Borisov 	return ret;
25522eadb9e7SNikolay Borisov }
25532eadb9e7SNikolay Borisov 
25542eadb9e7SNikolay Borisov /*
25552eadb9e7SNikolay Borisov  * This function belongs to phase 2.
25562eadb9e7SNikolay Borisov  *
25572eadb9e7SNikolay Borisov  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
25582eadb9e7SNikolay Borisov  * phases.
25592eadb9e7SNikolay Borisov  */
25602eadb9e7SNikolay Borisov static int insert_dev_extents(struct btrfs_trans_handle *trans,
25612eadb9e7SNikolay Borisov 				   u64 chunk_offset, u64 chunk_size)
25622eadb9e7SNikolay Borisov {
25632eadb9e7SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
25642eadb9e7SNikolay Borisov 	struct btrfs_device *device;
25652eadb9e7SNikolay Borisov 	struct extent_map *em;
25662eadb9e7SNikolay Borisov 	struct map_lookup *map;
25672eadb9e7SNikolay Borisov 	u64 dev_offset;
25682eadb9e7SNikolay Borisov 	u64 stripe_size;
25692eadb9e7SNikolay Borisov 	int i;
25702eadb9e7SNikolay Borisov 	int ret = 0;
25712eadb9e7SNikolay Borisov 
25722eadb9e7SNikolay Borisov 	em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
25732eadb9e7SNikolay Borisov 	if (IS_ERR(em))
25742eadb9e7SNikolay Borisov 		return PTR_ERR(em);
25752eadb9e7SNikolay Borisov 
25762eadb9e7SNikolay Borisov 	map = em->map_lookup;
25772eadb9e7SNikolay Borisov 	stripe_size = em->orig_block_len;
25782eadb9e7SNikolay Borisov 
25792eadb9e7SNikolay Borisov 	/*
25802eadb9e7SNikolay Borisov 	 * Take the device list mutex to prevent races with the final phase of
25812eadb9e7SNikolay Borisov 	 * a device replace operation that replaces the device object associated
25822eadb9e7SNikolay Borisov 	 * with the map's stripes, because the device object's id can change
25832eadb9e7SNikolay Borisov 	 * at any time during that final phase of the device replace operation
25842eadb9e7SNikolay Borisov 	 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
25852eadb9e7SNikolay Borisov 	 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
25862eadb9e7SNikolay Borisov 	 * resulting in persisting a device extent item with such ID.
25872eadb9e7SNikolay Borisov 	 */
25882eadb9e7SNikolay Borisov 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
25892eadb9e7SNikolay Borisov 	for (i = 0; i < map->num_stripes; i++) {
25902eadb9e7SNikolay Borisov 		device = map->stripes[i].dev;
25912eadb9e7SNikolay Borisov 		dev_offset = map->stripes[i].physical;
25922eadb9e7SNikolay Borisov 
25932eadb9e7SNikolay Borisov 		ret = insert_dev_extent(trans, device, chunk_offset, dev_offset,
25942eadb9e7SNikolay Borisov 				       stripe_size);
25952eadb9e7SNikolay Borisov 		if (ret)
25962eadb9e7SNikolay Borisov 			break;
25972eadb9e7SNikolay Borisov 	}
25982eadb9e7SNikolay Borisov 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
25992eadb9e7SNikolay Borisov 
26002eadb9e7SNikolay Borisov 	free_extent_map(em);
26012eadb9e7SNikolay Borisov 	return ret;
26022eadb9e7SNikolay Borisov }
26032eadb9e7SNikolay Borisov 
260479bd3712SFilipe Manana /*
260579bd3712SFilipe Manana  * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
260679bd3712SFilipe Manana  * chunk allocation.
260779bd3712SFilipe Manana  *
260879bd3712SFilipe Manana  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
260979bd3712SFilipe Manana  * phases.
261079bd3712SFilipe Manana  */
26114358d963SJosef Bacik void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
26124358d963SJosef Bacik {
26134358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
261432da5386SDavid Sterba 	struct btrfs_block_group *block_group;
26154358d963SJosef Bacik 	int ret = 0;
26164358d963SJosef Bacik 
26174358d963SJosef Bacik 	while (!list_empty(&trans->new_bgs)) {
261849ea112dSJosef Bacik 		int index;
261949ea112dSJosef Bacik 
26204358d963SJosef Bacik 		block_group = list_first_entry(&trans->new_bgs,
262132da5386SDavid Sterba 					       struct btrfs_block_group,
26224358d963SJosef Bacik 					       bg_list);
26234358d963SJosef Bacik 		if (ret)
26244358d963SJosef Bacik 			goto next;
26254358d963SJosef Bacik 
262649ea112dSJosef Bacik 		index = btrfs_bg_flags_to_raid_index(block_group->flags);
262749ea112dSJosef Bacik 
262897f4728aSQu Wenruo 		ret = insert_block_group_item(trans, block_group);
26294358d963SJosef Bacik 		if (ret)
26304358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
26313349b57fSJosef Bacik 		if (!test_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED,
26323349b57fSJosef Bacik 			      &block_group->runtime_flags)) {
263379bd3712SFilipe Manana 			mutex_lock(&fs_info->chunk_mutex);
263479bd3712SFilipe Manana 			ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group);
263579bd3712SFilipe Manana 			mutex_unlock(&fs_info->chunk_mutex);
263679bd3712SFilipe Manana 			if (ret)
263779bd3712SFilipe Manana 				btrfs_abort_transaction(trans, ret);
263879bd3712SFilipe Manana 		}
26392eadb9e7SNikolay Borisov 		ret = insert_dev_extents(trans, block_group->start,
264097f4728aSQu Wenruo 					 block_group->length);
26414358d963SJosef Bacik 		if (ret)
26424358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
26434358d963SJosef Bacik 		add_block_group_free_space(trans, block_group);
264449ea112dSJosef Bacik 
264549ea112dSJosef Bacik 		/*
264649ea112dSJosef Bacik 		 * If we restriped during balance, we may have added a new raid
264749ea112dSJosef Bacik 		 * type, so now add the sysfs entries when it is safe to do so.
264849ea112dSJosef Bacik 		 * We don't have to worry about locking here as it's handled in
264949ea112dSJosef Bacik 		 * btrfs_sysfs_add_block_group_type.
265049ea112dSJosef Bacik 		 */
265149ea112dSJosef Bacik 		if (block_group->space_info->block_group_kobjs[index] == NULL)
265249ea112dSJosef Bacik 			btrfs_sysfs_add_block_group_type(block_group);
265349ea112dSJosef Bacik 
26544358d963SJosef Bacik 		/* Already aborted the transaction if it failed. */
26554358d963SJosef Bacik next:
26564358d963SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
26574358d963SJosef Bacik 		list_del_init(&block_group->bg_list);
26584358d963SJosef Bacik 	}
26594358d963SJosef Bacik 	btrfs_trans_release_chunk_metadata(trans);
26604358d963SJosef Bacik }
26614358d963SJosef Bacik 
2662f7238e50SJosef Bacik /*
2663f7238e50SJosef Bacik  * For extent tree v2 we use the block_group_item->chunk_offset to point at our
2664f7238e50SJosef Bacik  * global root id.  For v1 it's always set to BTRFS_FIRST_CHUNK_TREE_OBJECTID.
2665f7238e50SJosef Bacik  */
2666f7238e50SJosef Bacik static u64 calculate_global_root_id(struct btrfs_fs_info *fs_info, u64 offset)
2667f7238e50SJosef Bacik {
2668f7238e50SJosef Bacik 	u64 div = SZ_1G;
2669f7238e50SJosef Bacik 	u64 index;
2670f7238e50SJosef Bacik 
2671f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2672f7238e50SJosef Bacik 		return BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2673f7238e50SJosef Bacik 
2674f7238e50SJosef Bacik 	/* If we have a smaller fs index based on 128MiB. */
2675f7238e50SJosef Bacik 	if (btrfs_super_total_bytes(fs_info->super_copy) <= (SZ_1G * 10ULL))
2676f7238e50SJosef Bacik 		div = SZ_128M;
2677f7238e50SJosef Bacik 
2678f7238e50SJosef Bacik 	offset = div64_u64(offset, div);
2679f7238e50SJosef Bacik 	div64_u64_rem(offset, fs_info->nr_global_roots, &index);
2680f7238e50SJosef Bacik 	return index;
2681f7238e50SJosef Bacik }
2682f7238e50SJosef Bacik 
268379bd3712SFilipe Manana struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
268479bd3712SFilipe Manana 						 u64 bytes_used, u64 type,
268579bd3712SFilipe Manana 						 u64 chunk_offset, u64 size)
26864358d963SJosef Bacik {
26874358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
268832da5386SDavid Sterba 	struct btrfs_block_group *cache;
26894358d963SJosef Bacik 	int ret;
26904358d963SJosef Bacik 
26914358d963SJosef Bacik 	btrfs_set_log_full_commit(trans);
26924358d963SJosef Bacik 
26939afc6649SQu Wenruo 	cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
26944358d963SJosef Bacik 	if (!cache)
269579bd3712SFilipe Manana 		return ERR_PTR(-ENOMEM);
26964358d963SJosef Bacik 
26979afc6649SQu Wenruo 	cache->length = size;
2698e3e39c72SMarcos Paulo de Souza 	set_free_space_tree_thresholds(cache);
2699bf38be65SDavid Sterba 	cache->used = bytes_used;
27004358d963SJosef Bacik 	cache->flags = type;
27014358d963SJosef Bacik 	cache->cached = BTRFS_CACHE_FINISHED;
2702f7238e50SJosef Bacik 	cache->global_root_id = calculate_global_root_id(fs_info, cache->start);
2703f7238e50SJosef Bacik 
2704997e3e2eSBoris Burkov 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
27050d7764ffSDavid Sterba 		set_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE, &cache->runtime_flags);
270608e11a3dSNaohiro Aota 
2707a94794d5SNaohiro Aota 	ret = btrfs_load_block_group_zone_info(cache, true);
270808e11a3dSNaohiro Aota 	if (ret) {
270908e11a3dSNaohiro Aota 		btrfs_put_block_group(cache);
271079bd3712SFilipe Manana 		return ERR_PTR(ret);
271108e11a3dSNaohiro Aota 	}
271208e11a3dSNaohiro Aota 
27134358d963SJosef Bacik 	ret = exclude_super_stripes(cache);
27144358d963SJosef Bacik 	if (ret) {
27154358d963SJosef Bacik 		/* We may have excluded something, so call this just in case */
27164358d963SJosef Bacik 		btrfs_free_excluded_extents(cache);
27174358d963SJosef Bacik 		btrfs_put_block_group(cache);
271879bd3712SFilipe Manana 		return ERR_PTR(ret);
27194358d963SJosef Bacik 	}
27204358d963SJosef Bacik 
27214358d963SJosef Bacik 	add_new_free_space(cache, chunk_offset, chunk_offset + size);
27224358d963SJosef Bacik 
27234358d963SJosef Bacik 	btrfs_free_excluded_extents(cache);
27244358d963SJosef Bacik 
27254358d963SJosef Bacik 	/*
27264358d963SJosef Bacik 	 * Ensure the corresponding space_info object is created and
27274358d963SJosef Bacik 	 * assigned to our block group. We want our bg to be added to the rbtree
27284358d963SJosef Bacik 	 * with its ->space_info set.
27294358d963SJosef Bacik 	 */
27304358d963SJosef Bacik 	cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
27314358d963SJosef Bacik 	ASSERT(cache->space_info);
27324358d963SJosef Bacik 
27334358d963SJosef Bacik 	ret = btrfs_add_block_group_cache(fs_info, cache);
27344358d963SJosef Bacik 	if (ret) {
27354358d963SJosef Bacik 		btrfs_remove_free_space_cache(cache);
27364358d963SJosef Bacik 		btrfs_put_block_group(cache);
273779bd3712SFilipe Manana 		return ERR_PTR(ret);
27384358d963SJosef Bacik 	}
27394358d963SJosef Bacik 
27404358d963SJosef Bacik 	/*
27414358d963SJosef Bacik 	 * Now that our block group has its ->space_info set and is inserted in
27424358d963SJosef Bacik 	 * the rbtree, update the space info's counters.
27434358d963SJosef Bacik 	 */
27444358d963SJosef Bacik 	trace_btrfs_add_block_group(fs_info, cache, 1);
2745723de71dSJosef Bacik 	btrfs_add_bg_to_space_info(fs_info, cache);
27464358d963SJosef Bacik 	btrfs_update_global_block_rsv(fs_info);
27474358d963SJosef Bacik 
27489d4b0a12SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
27499d4b0a12SJosef Bacik 	if (btrfs_should_fragment_free_space(cache)) {
27509d4b0a12SJosef Bacik 		u64 new_bytes_used = size - bytes_used;
27519d4b0a12SJosef Bacik 
27529d4b0a12SJosef Bacik 		cache->space_info->bytes_used += new_bytes_used >> 1;
27539d4b0a12SJosef Bacik 		fragment_free_space(cache);
27549d4b0a12SJosef Bacik 	}
27559d4b0a12SJosef Bacik #endif
27564358d963SJosef Bacik 
27574358d963SJosef Bacik 	list_add_tail(&cache->bg_list, &trans->new_bgs);
27584358d963SJosef Bacik 	trans->delayed_ref_updates++;
27594358d963SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
27604358d963SJosef Bacik 
27614358d963SJosef Bacik 	set_avail_alloc_bits(fs_info, type);
276279bd3712SFilipe Manana 	return cache;
27634358d963SJosef Bacik }
276426ce2095SJosef Bacik 
2765b12de528SQu Wenruo /*
2766b12de528SQu Wenruo  * Mark one block group RO, can be called several times for the same block
2767b12de528SQu Wenruo  * group.
2768b12de528SQu Wenruo  *
2769b12de528SQu Wenruo  * @cache:		the destination block group
2770b12de528SQu Wenruo  * @do_chunk_alloc:	whether need to do chunk pre-allocation, this is to
2771b12de528SQu Wenruo  * 			ensure we still have some free space after marking this
2772b12de528SQu Wenruo  * 			block group RO.
2773b12de528SQu Wenruo  */
2774b12de528SQu Wenruo int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2775b12de528SQu Wenruo 			     bool do_chunk_alloc)
277626ce2095SJosef Bacik {
277726ce2095SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
277826ce2095SJosef Bacik 	struct btrfs_trans_handle *trans;
2779dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
278026ce2095SJosef Bacik 	u64 alloc_flags;
278126ce2095SJosef Bacik 	int ret;
2782b6e9f16cSNikolay Borisov 	bool dirty_bg_running;
278326ce2095SJosef Bacik 
27842d192fc4SQu Wenruo 	/*
27852d192fc4SQu Wenruo 	 * This can only happen when we are doing read-only scrub on read-only
27862d192fc4SQu Wenruo 	 * mount.
27872d192fc4SQu Wenruo 	 * In that case we should not start a new transaction on read-only fs.
27882d192fc4SQu Wenruo 	 * Thus here we skip all chunk allocations.
27892d192fc4SQu Wenruo 	 */
27902d192fc4SQu Wenruo 	if (sb_rdonly(fs_info->sb)) {
27912d192fc4SQu Wenruo 		mutex_lock(&fs_info->ro_block_group_mutex);
27922d192fc4SQu Wenruo 		ret = inc_block_group_ro(cache, 0);
27932d192fc4SQu Wenruo 		mutex_unlock(&fs_info->ro_block_group_mutex);
27942d192fc4SQu Wenruo 		return ret;
27952d192fc4SQu Wenruo 	}
27962d192fc4SQu Wenruo 
2797b6e9f16cSNikolay Borisov 	do {
2798dfe8aec4SJosef Bacik 		trans = btrfs_join_transaction(root);
279926ce2095SJosef Bacik 		if (IS_ERR(trans))
280026ce2095SJosef Bacik 			return PTR_ERR(trans);
280126ce2095SJosef Bacik 
2802b6e9f16cSNikolay Borisov 		dirty_bg_running = false;
2803b6e9f16cSNikolay Borisov 
280426ce2095SJosef Bacik 		/*
2805b6e9f16cSNikolay Borisov 		 * We're not allowed to set block groups readonly after the dirty
2806b6e9f16cSNikolay Borisov 		 * block group cache has started writing.  If it already started,
2807b6e9f16cSNikolay Borisov 		 * back off and let this transaction commit.
280826ce2095SJosef Bacik 		 */
280926ce2095SJosef Bacik 		mutex_lock(&fs_info->ro_block_group_mutex);
281026ce2095SJosef Bacik 		if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
281126ce2095SJosef Bacik 			u64 transid = trans->transid;
281226ce2095SJosef Bacik 
281326ce2095SJosef Bacik 			mutex_unlock(&fs_info->ro_block_group_mutex);
281426ce2095SJosef Bacik 			btrfs_end_transaction(trans);
281526ce2095SJosef Bacik 
281626ce2095SJosef Bacik 			ret = btrfs_wait_for_commit(fs_info, transid);
281726ce2095SJosef Bacik 			if (ret)
281826ce2095SJosef Bacik 				return ret;
2819b6e9f16cSNikolay Borisov 			dirty_bg_running = true;
282026ce2095SJosef Bacik 		}
2821b6e9f16cSNikolay Borisov 	} while (dirty_bg_running);
282226ce2095SJosef Bacik 
2823b12de528SQu Wenruo 	if (do_chunk_alloc) {
282426ce2095SJosef Bacik 		/*
2825b12de528SQu Wenruo 		 * If we are changing raid levels, try to allocate a
2826b12de528SQu Wenruo 		 * corresponding block group with the new raid level.
282726ce2095SJosef Bacik 		 */
2828349e120eSJosef Bacik 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
282926ce2095SJosef Bacik 		if (alloc_flags != cache->flags) {
2830b12de528SQu Wenruo 			ret = btrfs_chunk_alloc(trans, alloc_flags,
2831b12de528SQu Wenruo 						CHUNK_ALLOC_FORCE);
283226ce2095SJosef Bacik 			/*
283326ce2095SJosef Bacik 			 * ENOSPC is allowed here, we may have enough space
2834b12de528SQu Wenruo 			 * already allocated at the new raid level to carry on
283526ce2095SJosef Bacik 			 */
283626ce2095SJosef Bacik 			if (ret == -ENOSPC)
283726ce2095SJosef Bacik 				ret = 0;
283826ce2095SJosef Bacik 			if (ret < 0)
283926ce2095SJosef Bacik 				goto out;
284026ce2095SJosef Bacik 		}
2841b12de528SQu Wenruo 	}
284226ce2095SJosef Bacik 
2843a7a63accSJosef Bacik 	ret = inc_block_group_ro(cache, 0);
2844195a49eaSFilipe Manana 	if (!do_chunk_alloc || ret == -ETXTBSY)
2845b12de528SQu Wenruo 		goto unlock_out;
284626ce2095SJosef Bacik 	if (!ret)
284726ce2095SJosef Bacik 		goto out;
284826ce2095SJosef Bacik 	alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
284926ce2095SJosef Bacik 	ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
285026ce2095SJosef Bacik 	if (ret < 0)
285126ce2095SJosef Bacik 		goto out;
2852b6a98021SNaohiro Aota 	/*
2853b6a98021SNaohiro Aota 	 * We have allocated a new chunk. We also need to activate that chunk to
2854b6a98021SNaohiro Aota 	 * grant metadata tickets for zoned filesystem.
2855b6a98021SNaohiro Aota 	 */
2856b6a98021SNaohiro Aota 	ret = btrfs_zoned_activate_one_bg(fs_info, cache->space_info, true);
2857b6a98021SNaohiro Aota 	if (ret < 0)
2858b6a98021SNaohiro Aota 		goto out;
2859b6a98021SNaohiro Aota 
2860e11c0406SJosef Bacik 	ret = inc_block_group_ro(cache, 0);
2861195a49eaSFilipe Manana 	if (ret == -ETXTBSY)
2862195a49eaSFilipe Manana 		goto unlock_out;
286326ce2095SJosef Bacik out:
286426ce2095SJosef Bacik 	if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2865349e120eSJosef Bacik 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
286626ce2095SJosef Bacik 		mutex_lock(&fs_info->chunk_mutex);
286726ce2095SJosef Bacik 		check_system_chunk(trans, alloc_flags);
286826ce2095SJosef Bacik 		mutex_unlock(&fs_info->chunk_mutex);
286926ce2095SJosef Bacik 	}
2870b12de528SQu Wenruo unlock_out:
287126ce2095SJosef Bacik 	mutex_unlock(&fs_info->ro_block_group_mutex);
287226ce2095SJosef Bacik 
287326ce2095SJosef Bacik 	btrfs_end_transaction(trans);
287426ce2095SJosef Bacik 	return ret;
287526ce2095SJosef Bacik }
287626ce2095SJosef Bacik 
287732da5386SDavid Sterba void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
287826ce2095SJosef Bacik {
287926ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
288026ce2095SJosef Bacik 	u64 num_bytes;
288126ce2095SJosef Bacik 
288226ce2095SJosef Bacik 	BUG_ON(!cache->ro);
288326ce2095SJosef Bacik 
288426ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
288526ce2095SJosef Bacik 	spin_lock(&cache->lock);
288626ce2095SJosef Bacik 	if (!--cache->ro) {
2887169e0da9SNaohiro Aota 		if (btrfs_is_zoned(cache->fs_info)) {
2888169e0da9SNaohiro Aota 			/* Migrate zone_unusable bytes back */
288998173255SNaohiro Aota 			cache->zone_unusable =
289098173255SNaohiro Aota 				(cache->alloc_offset - cache->used) +
289198173255SNaohiro Aota 				(cache->length - cache->zone_capacity);
2892169e0da9SNaohiro Aota 			sinfo->bytes_zone_unusable += cache->zone_unusable;
2893169e0da9SNaohiro Aota 			sinfo->bytes_readonly -= cache->zone_unusable;
2894169e0da9SNaohiro Aota 		}
2895f9f28e5bSNaohiro Aota 		num_bytes = cache->length - cache->reserved -
2896f9f28e5bSNaohiro Aota 			    cache->pinned - cache->bytes_super -
2897f9f28e5bSNaohiro Aota 			    cache->zone_unusable - cache->used;
2898f9f28e5bSNaohiro Aota 		sinfo->bytes_readonly -= num_bytes;
289926ce2095SJosef Bacik 		list_del_init(&cache->ro_list);
290026ce2095SJosef Bacik 	}
290126ce2095SJosef Bacik 	spin_unlock(&cache->lock);
290226ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
290326ce2095SJosef Bacik }
290477745c05SJosef Bacik 
29053be4d8efSQu Wenruo static int update_block_group_item(struct btrfs_trans_handle *trans,
290677745c05SJosef Bacik 				   struct btrfs_path *path,
290732da5386SDavid Sterba 				   struct btrfs_block_group *cache)
290877745c05SJosef Bacik {
290977745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
291077745c05SJosef Bacik 	int ret;
2911dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
291277745c05SJosef Bacik 	unsigned long bi;
291377745c05SJosef Bacik 	struct extent_buffer *leaf;
2914bf38be65SDavid Sterba 	struct btrfs_block_group_item bgi;
2915b3470b5dSDavid Sterba 	struct btrfs_key key;
29167248e0ceSQu Wenruo 	u64 old_commit_used;
29177248e0ceSQu Wenruo 	u64 used;
29187248e0ceSQu Wenruo 
29197248e0ceSQu Wenruo 	/*
29207248e0ceSQu Wenruo 	 * Block group items update can be triggered out of commit transaction
29217248e0ceSQu Wenruo 	 * critical section, thus we need a consistent view of used bytes.
29227248e0ceSQu Wenruo 	 * We cannot use cache->used directly outside of the spin lock, as it
29237248e0ceSQu Wenruo 	 * may be changed.
29247248e0ceSQu Wenruo 	 */
29257248e0ceSQu Wenruo 	spin_lock(&cache->lock);
29267248e0ceSQu Wenruo 	old_commit_used = cache->commit_used;
29277248e0ceSQu Wenruo 	used = cache->used;
29287248e0ceSQu Wenruo 	/* No change in used bytes, can safely skip it. */
29297248e0ceSQu Wenruo 	if (cache->commit_used == used) {
29307248e0ceSQu Wenruo 		spin_unlock(&cache->lock);
29317248e0ceSQu Wenruo 		return 0;
29327248e0ceSQu Wenruo 	}
29337248e0ceSQu Wenruo 	cache->commit_used = used;
29347248e0ceSQu Wenruo 	spin_unlock(&cache->lock);
293577745c05SJosef Bacik 
2936b3470b5dSDavid Sterba 	key.objectid = cache->start;
2937b3470b5dSDavid Sterba 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2938b3470b5dSDavid Sterba 	key.offset = cache->length;
2939b3470b5dSDavid Sterba 
29403be4d8efSQu Wenruo 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
294177745c05SJosef Bacik 	if (ret) {
294277745c05SJosef Bacik 		if (ret > 0)
294377745c05SJosef Bacik 			ret = -ENOENT;
294477745c05SJosef Bacik 		goto fail;
294577745c05SJosef Bacik 	}
294677745c05SJosef Bacik 
294777745c05SJosef Bacik 	leaf = path->nodes[0];
294877745c05SJosef Bacik 	bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
29497248e0ceSQu Wenruo 	btrfs_set_stack_block_group_used(&bgi, used);
2950de0dc456SDavid Sterba 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
2951f7238e50SJosef Bacik 						   cache->global_root_id);
2952de0dc456SDavid Sterba 	btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2953bf38be65SDavid Sterba 	write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
295477745c05SJosef Bacik 	btrfs_mark_buffer_dirty(leaf);
295577745c05SJosef Bacik fail:
295677745c05SJosef Bacik 	btrfs_release_path(path);
29577248e0ceSQu Wenruo 	/* We didn't update the block group item, need to revert @commit_used. */
29587248e0ceSQu Wenruo 	if (ret < 0) {
29597248e0ceSQu Wenruo 		spin_lock(&cache->lock);
29607248e0ceSQu Wenruo 		cache->commit_used = old_commit_used;
29617248e0ceSQu Wenruo 		spin_unlock(&cache->lock);
29627248e0ceSQu Wenruo 	}
296377745c05SJosef Bacik 	return ret;
296477745c05SJosef Bacik 
296577745c05SJosef Bacik }
296677745c05SJosef Bacik 
296732da5386SDavid Sterba static int cache_save_setup(struct btrfs_block_group *block_group,
296877745c05SJosef Bacik 			    struct btrfs_trans_handle *trans,
296977745c05SJosef Bacik 			    struct btrfs_path *path)
297077745c05SJosef Bacik {
297177745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
297277745c05SJosef Bacik 	struct btrfs_root *root = fs_info->tree_root;
297377745c05SJosef Bacik 	struct inode *inode = NULL;
297477745c05SJosef Bacik 	struct extent_changeset *data_reserved = NULL;
297577745c05SJosef Bacik 	u64 alloc_hint = 0;
297677745c05SJosef Bacik 	int dcs = BTRFS_DC_ERROR;
29770044ae11SQu Wenruo 	u64 cache_size = 0;
297877745c05SJosef Bacik 	int retries = 0;
297977745c05SJosef Bacik 	int ret = 0;
298077745c05SJosef Bacik 
2981af456a2cSBoris Burkov 	if (!btrfs_test_opt(fs_info, SPACE_CACHE))
2982af456a2cSBoris Burkov 		return 0;
2983af456a2cSBoris Burkov 
298477745c05SJosef Bacik 	/*
298577745c05SJosef Bacik 	 * If this block group is smaller than 100 megs don't bother caching the
298677745c05SJosef Bacik 	 * block group.
298777745c05SJosef Bacik 	 */
2988b3470b5dSDavid Sterba 	if (block_group->length < (100 * SZ_1M)) {
298977745c05SJosef Bacik 		spin_lock(&block_group->lock);
299077745c05SJosef Bacik 		block_group->disk_cache_state = BTRFS_DC_WRITTEN;
299177745c05SJosef Bacik 		spin_unlock(&block_group->lock);
299277745c05SJosef Bacik 		return 0;
299377745c05SJosef Bacik 	}
299477745c05SJosef Bacik 
2995bf31f87fSDavid Sterba 	if (TRANS_ABORTED(trans))
299677745c05SJosef Bacik 		return 0;
299777745c05SJosef Bacik again:
299877745c05SJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
299977745c05SJosef Bacik 	if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
300077745c05SJosef Bacik 		ret = PTR_ERR(inode);
300177745c05SJosef Bacik 		btrfs_release_path(path);
300277745c05SJosef Bacik 		goto out;
300377745c05SJosef Bacik 	}
300477745c05SJosef Bacik 
300577745c05SJosef Bacik 	if (IS_ERR(inode)) {
300677745c05SJosef Bacik 		BUG_ON(retries);
300777745c05SJosef Bacik 		retries++;
300877745c05SJosef Bacik 
300977745c05SJosef Bacik 		if (block_group->ro)
301077745c05SJosef Bacik 			goto out_free;
301177745c05SJosef Bacik 
301277745c05SJosef Bacik 		ret = create_free_space_inode(trans, block_group, path);
301377745c05SJosef Bacik 		if (ret)
301477745c05SJosef Bacik 			goto out_free;
301577745c05SJosef Bacik 		goto again;
301677745c05SJosef Bacik 	}
301777745c05SJosef Bacik 
301877745c05SJosef Bacik 	/*
301977745c05SJosef Bacik 	 * We want to set the generation to 0, that way if anything goes wrong
302077745c05SJosef Bacik 	 * from here on out we know not to trust this cache when we load up next
302177745c05SJosef Bacik 	 * time.
302277745c05SJosef Bacik 	 */
302377745c05SJosef Bacik 	BTRFS_I(inode)->generation = 0;
30249a56fcd1SNikolay Borisov 	ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
302577745c05SJosef Bacik 	if (ret) {
302677745c05SJosef Bacik 		/*
302777745c05SJosef Bacik 		 * So theoretically we could recover from this, simply set the
302877745c05SJosef Bacik 		 * super cache generation to 0 so we know to invalidate the
302977745c05SJosef Bacik 		 * cache, but then we'd have to keep track of the block groups
303077745c05SJosef Bacik 		 * that fail this way so we know we _have_ to reset this cache
303177745c05SJosef Bacik 		 * before the next commit or risk reading stale cache.  So to
303277745c05SJosef Bacik 		 * limit our exposure to horrible edge cases lets just abort the
303377745c05SJosef Bacik 		 * transaction, this only happens in really bad situations
303477745c05SJosef Bacik 		 * anyway.
303577745c05SJosef Bacik 		 */
303677745c05SJosef Bacik 		btrfs_abort_transaction(trans, ret);
303777745c05SJosef Bacik 		goto out_put;
303877745c05SJosef Bacik 	}
303977745c05SJosef Bacik 	WARN_ON(ret);
304077745c05SJosef Bacik 
304177745c05SJosef Bacik 	/* We've already setup this transaction, go ahead and exit */
304277745c05SJosef Bacik 	if (block_group->cache_generation == trans->transid &&
304377745c05SJosef Bacik 	    i_size_read(inode)) {
304477745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
304577745c05SJosef Bacik 		goto out_put;
304677745c05SJosef Bacik 	}
304777745c05SJosef Bacik 
304877745c05SJosef Bacik 	if (i_size_read(inode) > 0) {
304977745c05SJosef Bacik 		ret = btrfs_check_trunc_cache_free_space(fs_info,
305077745c05SJosef Bacik 					&fs_info->global_block_rsv);
305177745c05SJosef Bacik 		if (ret)
305277745c05SJosef Bacik 			goto out_put;
305377745c05SJosef Bacik 
305477745c05SJosef Bacik 		ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
305577745c05SJosef Bacik 		if (ret)
305677745c05SJosef Bacik 			goto out_put;
305777745c05SJosef Bacik 	}
305877745c05SJosef Bacik 
305977745c05SJosef Bacik 	spin_lock(&block_group->lock);
306077745c05SJosef Bacik 	if (block_group->cached != BTRFS_CACHE_FINISHED ||
306177745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE)) {
306277745c05SJosef Bacik 		/*
306377745c05SJosef Bacik 		 * don't bother trying to write stuff out _if_
306477745c05SJosef Bacik 		 * a) we're not cached,
306577745c05SJosef Bacik 		 * b) we're with nospace_cache mount option,
306677745c05SJosef Bacik 		 * c) we're with v2 space_cache (FREE_SPACE_TREE).
306777745c05SJosef Bacik 		 */
306877745c05SJosef Bacik 		dcs = BTRFS_DC_WRITTEN;
306977745c05SJosef Bacik 		spin_unlock(&block_group->lock);
307077745c05SJosef Bacik 		goto out_put;
307177745c05SJosef Bacik 	}
307277745c05SJosef Bacik 	spin_unlock(&block_group->lock);
307377745c05SJosef Bacik 
307477745c05SJosef Bacik 	/*
307577745c05SJosef Bacik 	 * We hit an ENOSPC when setting up the cache in this transaction, just
307677745c05SJosef Bacik 	 * skip doing the setup, we've already cleared the cache so we're safe.
307777745c05SJosef Bacik 	 */
307877745c05SJosef Bacik 	if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
307977745c05SJosef Bacik 		ret = -ENOSPC;
308077745c05SJosef Bacik 		goto out_put;
308177745c05SJosef Bacik 	}
308277745c05SJosef Bacik 
308377745c05SJosef Bacik 	/*
308477745c05SJosef Bacik 	 * Try to preallocate enough space based on how big the block group is.
308577745c05SJosef Bacik 	 * Keep in mind this has to include any pinned space which could end up
308677745c05SJosef Bacik 	 * taking up quite a bit since it's not folded into the other space
308777745c05SJosef Bacik 	 * cache.
308877745c05SJosef Bacik 	 */
30890044ae11SQu Wenruo 	cache_size = div_u64(block_group->length, SZ_256M);
30900044ae11SQu Wenruo 	if (!cache_size)
30910044ae11SQu Wenruo 		cache_size = 1;
309277745c05SJosef Bacik 
30930044ae11SQu Wenruo 	cache_size *= 16;
30940044ae11SQu Wenruo 	cache_size *= fs_info->sectorsize;
309577745c05SJosef Bacik 
309636ea6f3eSNikolay Borisov 	ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
30971daedb1dSJosef Bacik 					  cache_size, false);
309877745c05SJosef Bacik 	if (ret)
309977745c05SJosef Bacik 		goto out_put;
310077745c05SJosef Bacik 
31010044ae11SQu Wenruo 	ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
31020044ae11SQu Wenruo 					      cache_size, cache_size,
310377745c05SJosef Bacik 					      &alloc_hint);
310477745c05SJosef Bacik 	/*
310577745c05SJosef Bacik 	 * Our cache requires contiguous chunks so that we don't modify a bunch
310677745c05SJosef Bacik 	 * of metadata or split extents when writing the cache out, which means
310777745c05SJosef Bacik 	 * we can enospc if we are heavily fragmented in addition to just normal
310877745c05SJosef Bacik 	 * out of space conditions.  So if we hit this just skip setting up any
310977745c05SJosef Bacik 	 * other block groups for this transaction, maybe we'll unpin enough
311077745c05SJosef Bacik 	 * space the next time around.
311177745c05SJosef Bacik 	 */
311277745c05SJosef Bacik 	if (!ret)
311377745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
311477745c05SJosef Bacik 	else if (ret == -ENOSPC)
311577745c05SJosef Bacik 		set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
311677745c05SJosef Bacik 
311777745c05SJosef Bacik out_put:
311877745c05SJosef Bacik 	iput(inode);
311977745c05SJosef Bacik out_free:
312077745c05SJosef Bacik 	btrfs_release_path(path);
312177745c05SJosef Bacik out:
312277745c05SJosef Bacik 	spin_lock(&block_group->lock);
312377745c05SJosef Bacik 	if (!ret && dcs == BTRFS_DC_SETUP)
312477745c05SJosef Bacik 		block_group->cache_generation = trans->transid;
312577745c05SJosef Bacik 	block_group->disk_cache_state = dcs;
312677745c05SJosef Bacik 	spin_unlock(&block_group->lock);
312777745c05SJosef Bacik 
312877745c05SJosef Bacik 	extent_changeset_free(data_reserved);
312977745c05SJosef Bacik 	return ret;
313077745c05SJosef Bacik }
313177745c05SJosef Bacik 
313277745c05SJosef Bacik int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
313377745c05SJosef Bacik {
313477745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
313532da5386SDavid Sterba 	struct btrfs_block_group *cache, *tmp;
313677745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
313777745c05SJosef Bacik 	struct btrfs_path *path;
313877745c05SJosef Bacik 
313977745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs) ||
314077745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE))
314177745c05SJosef Bacik 		return 0;
314277745c05SJosef Bacik 
314377745c05SJosef Bacik 	path = btrfs_alloc_path();
314477745c05SJosef Bacik 	if (!path)
314577745c05SJosef Bacik 		return -ENOMEM;
314677745c05SJosef Bacik 
314777745c05SJosef Bacik 	/* Could add new block groups, use _safe just in case */
314877745c05SJosef Bacik 	list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
314977745c05SJosef Bacik 				 dirty_list) {
315077745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_CLEAR)
315177745c05SJosef Bacik 			cache_save_setup(cache, trans, path);
315277745c05SJosef Bacik 	}
315377745c05SJosef Bacik 
315477745c05SJosef Bacik 	btrfs_free_path(path);
315577745c05SJosef Bacik 	return 0;
315677745c05SJosef Bacik }
315777745c05SJosef Bacik 
315877745c05SJosef Bacik /*
315977745c05SJosef Bacik  * Transaction commit does final block group cache writeback during a critical
316077745c05SJosef Bacik  * section where nothing is allowed to change the FS.  This is required in
316177745c05SJosef Bacik  * order for the cache to actually match the block group, but can introduce a
316277745c05SJosef Bacik  * lot of latency into the commit.
316377745c05SJosef Bacik  *
316477745c05SJosef Bacik  * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
316577745c05SJosef Bacik  * There's a chance we'll have to redo some of it if the block group changes
316677745c05SJosef Bacik  * again during the commit, but it greatly reduces the commit latency by
316777745c05SJosef Bacik  * getting rid of the easy block groups while we're still allowing others to
316877745c05SJosef Bacik  * join the commit.
316977745c05SJosef Bacik  */
317077745c05SJosef Bacik int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
317177745c05SJosef Bacik {
317277745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
317332da5386SDavid Sterba 	struct btrfs_block_group *cache;
317477745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
317577745c05SJosef Bacik 	int ret = 0;
317677745c05SJosef Bacik 	int should_put;
317777745c05SJosef Bacik 	struct btrfs_path *path = NULL;
317877745c05SJosef Bacik 	LIST_HEAD(dirty);
317977745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
318077745c05SJosef Bacik 	int loops = 0;
318177745c05SJosef Bacik 
318277745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
318377745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs)) {
318477745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
318577745c05SJosef Bacik 		return 0;
318677745c05SJosef Bacik 	}
318777745c05SJosef Bacik 	list_splice_init(&cur_trans->dirty_bgs, &dirty);
318877745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
318977745c05SJosef Bacik 
319077745c05SJosef Bacik again:
319177745c05SJosef Bacik 	/* Make sure all the block groups on our dirty list actually exist */
319277745c05SJosef Bacik 	btrfs_create_pending_block_groups(trans);
319377745c05SJosef Bacik 
319477745c05SJosef Bacik 	if (!path) {
319577745c05SJosef Bacik 		path = btrfs_alloc_path();
3196938fcbfbSJosef Bacik 		if (!path) {
3197938fcbfbSJosef Bacik 			ret = -ENOMEM;
3198938fcbfbSJosef Bacik 			goto out;
3199938fcbfbSJosef Bacik 		}
320077745c05SJosef Bacik 	}
320177745c05SJosef Bacik 
320277745c05SJosef Bacik 	/*
320377745c05SJosef Bacik 	 * cache_write_mutex is here only to save us from balance or automatic
320477745c05SJosef Bacik 	 * removal of empty block groups deleting this block group while we are
320577745c05SJosef Bacik 	 * writing out the cache
320677745c05SJosef Bacik 	 */
320777745c05SJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
320877745c05SJosef Bacik 	while (!list_empty(&dirty)) {
320977745c05SJosef Bacik 		bool drop_reserve = true;
321077745c05SJosef Bacik 
321132da5386SDavid Sterba 		cache = list_first_entry(&dirty, struct btrfs_block_group,
321277745c05SJosef Bacik 					 dirty_list);
321377745c05SJosef Bacik 		/*
321477745c05SJosef Bacik 		 * This can happen if something re-dirties a block group that
321577745c05SJosef Bacik 		 * is already under IO.  Just wait for it to finish and then do
321677745c05SJosef Bacik 		 * it all again
321777745c05SJosef Bacik 		 */
321877745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
321977745c05SJosef Bacik 			list_del_init(&cache->io_list);
322077745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
322177745c05SJosef Bacik 			btrfs_put_block_group(cache);
322277745c05SJosef Bacik 		}
322377745c05SJosef Bacik 
322477745c05SJosef Bacik 
322577745c05SJosef Bacik 		/*
322677745c05SJosef Bacik 		 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
322777745c05SJosef Bacik 		 * it should update the cache_state.  Don't delete until after
322877745c05SJosef Bacik 		 * we wait.
322977745c05SJosef Bacik 		 *
323077745c05SJosef Bacik 		 * Since we're not running in the commit critical section
323177745c05SJosef Bacik 		 * we need the dirty_bgs_lock to protect from update_block_group
323277745c05SJosef Bacik 		 */
323377745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
323477745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
323577745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
323677745c05SJosef Bacik 
323777745c05SJosef Bacik 		should_put = 1;
323877745c05SJosef Bacik 
323977745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
324077745c05SJosef Bacik 
324177745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_SETUP) {
324277745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
324377745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
324477745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
324577745c05SJosef Bacik 				should_put = 0;
324677745c05SJosef Bacik 
324777745c05SJosef Bacik 				/*
324877745c05SJosef Bacik 				 * The cache_write_mutex is protecting the
324977745c05SJosef Bacik 				 * io_list, also refer to the definition of
325077745c05SJosef Bacik 				 * btrfs_transaction::io_bgs for more details
325177745c05SJosef Bacik 				 */
325277745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
325377745c05SJosef Bacik 			} else {
325477745c05SJosef Bacik 				/*
325577745c05SJosef Bacik 				 * If we failed to write the cache, the
325677745c05SJosef Bacik 				 * generation will be bad and life goes on
325777745c05SJosef Bacik 				 */
325877745c05SJosef Bacik 				ret = 0;
325977745c05SJosef Bacik 			}
326077745c05SJosef Bacik 		}
326177745c05SJosef Bacik 		if (!ret) {
32623be4d8efSQu Wenruo 			ret = update_block_group_item(trans, path, cache);
326377745c05SJosef Bacik 			/*
326477745c05SJosef Bacik 			 * Our block group might still be attached to the list
326577745c05SJosef Bacik 			 * of new block groups in the transaction handle of some
326677745c05SJosef Bacik 			 * other task (struct btrfs_trans_handle->new_bgs). This
326777745c05SJosef Bacik 			 * means its block group item isn't yet in the extent
326877745c05SJosef Bacik 			 * tree. If this happens ignore the error, as we will
326977745c05SJosef Bacik 			 * try again later in the critical section of the
327077745c05SJosef Bacik 			 * transaction commit.
327177745c05SJosef Bacik 			 */
327277745c05SJosef Bacik 			if (ret == -ENOENT) {
327377745c05SJosef Bacik 				ret = 0;
327477745c05SJosef Bacik 				spin_lock(&cur_trans->dirty_bgs_lock);
327577745c05SJosef Bacik 				if (list_empty(&cache->dirty_list)) {
327677745c05SJosef Bacik 					list_add_tail(&cache->dirty_list,
327777745c05SJosef Bacik 						      &cur_trans->dirty_bgs);
327877745c05SJosef Bacik 					btrfs_get_block_group(cache);
327977745c05SJosef Bacik 					drop_reserve = false;
328077745c05SJosef Bacik 				}
328177745c05SJosef Bacik 				spin_unlock(&cur_trans->dirty_bgs_lock);
328277745c05SJosef Bacik 			} else if (ret) {
328377745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
328477745c05SJosef Bacik 			}
328577745c05SJosef Bacik 		}
328677745c05SJosef Bacik 
328777745c05SJosef Bacik 		/* If it's not on the io list, we need to put the block group */
328877745c05SJosef Bacik 		if (should_put)
328977745c05SJosef Bacik 			btrfs_put_block_group(cache);
329077745c05SJosef Bacik 		if (drop_reserve)
329177745c05SJosef Bacik 			btrfs_delayed_refs_rsv_release(fs_info, 1);
329277745c05SJosef Bacik 		/*
329377745c05SJosef Bacik 		 * Avoid blocking other tasks for too long. It might even save
329477745c05SJosef Bacik 		 * us from writing caches for block groups that are going to be
329577745c05SJosef Bacik 		 * removed.
329677745c05SJosef Bacik 		 */
329777745c05SJosef Bacik 		mutex_unlock(&trans->transaction->cache_write_mutex);
3298938fcbfbSJosef Bacik 		if (ret)
3299938fcbfbSJosef Bacik 			goto out;
330077745c05SJosef Bacik 		mutex_lock(&trans->transaction->cache_write_mutex);
330177745c05SJosef Bacik 	}
330277745c05SJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
330377745c05SJosef Bacik 
330477745c05SJosef Bacik 	/*
330577745c05SJosef Bacik 	 * Go through delayed refs for all the stuff we've just kicked off
330677745c05SJosef Bacik 	 * and then loop back (just once)
330777745c05SJosef Bacik 	 */
330834d1eb0eSJosef Bacik 	if (!ret)
330977745c05SJosef Bacik 		ret = btrfs_run_delayed_refs(trans, 0);
331077745c05SJosef Bacik 	if (!ret && loops == 0) {
331177745c05SJosef Bacik 		loops++;
331277745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
331377745c05SJosef Bacik 		list_splice_init(&cur_trans->dirty_bgs, &dirty);
331477745c05SJosef Bacik 		/*
331577745c05SJosef Bacik 		 * dirty_bgs_lock protects us from concurrent block group
331677745c05SJosef Bacik 		 * deletes too (not just cache_write_mutex).
331777745c05SJosef Bacik 		 */
331877745c05SJosef Bacik 		if (!list_empty(&dirty)) {
331977745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
332077745c05SJosef Bacik 			goto again;
332177745c05SJosef Bacik 		}
332277745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
3323938fcbfbSJosef Bacik 	}
3324938fcbfbSJosef Bacik out:
3325938fcbfbSJosef Bacik 	if (ret < 0) {
3326938fcbfbSJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
3327938fcbfbSJosef Bacik 		list_splice_init(&dirty, &cur_trans->dirty_bgs);
3328938fcbfbSJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
332977745c05SJosef Bacik 		btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
333077745c05SJosef Bacik 	}
333177745c05SJosef Bacik 
333277745c05SJosef Bacik 	btrfs_free_path(path);
333377745c05SJosef Bacik 	return ret;
333477745c05SJosef Bacik }
333577745c05SJosef Bacik 
333677745c05SJosef Bacik int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
333777745c05SJosef Bacik {
333877745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
333932da5386SDavid Sterba 	struct btrfs_block_group *cache;
334077745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
334177745c05SJosef Bacik 	int ret = 0;
334277745c05SJosef Bacik 	int should_put;
334377745c05SJosef Bacik 	struct btrfs_path *path;
334477745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
334577745c05SJosef Bacik 
334677745c05SJosef Bacik 	path = btrfs_alloc_path();
334777745c05SJosef Bacik 	if (!path)
334877745c05SJosef Bacik 		return -ENOMEM;
334977745c05SJosef Bacik 
335077745c05SJosef Bacik 	/*
335177745c05SJosef Bacik 	 * Even though we are in the critical section of the transaction commit,
335277745c05SJosef Bacik 	 * we can still have concurrent tasks adding elements to this
335377745c05SJosef Bacik 	 * transaction's list of dirty block groups. These tasks correspond to
335477745c05SJosef Bacik 	 * endio free space workers started when writeback finishes for a
335577745c05SJosef Bacik 	 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
335677745c05SJosef Bacik 	 * allocate new block groups as a result of COWing nodes of the root
335777745c05SJosef Bacik 	 * tree when updating the free space inode. The writeback for the space
335877745c05SJosef Bacik 	 * caches is triggered by an earlier call to
335977745c05SJosef Bacik 	 * btrfs_start_dirty_block_groups() and iterations of the following
336077745c05SJosef Bacik 	 * loop.
336177745c05SJosef Bacik 	 * Also we want to do the cache_save_setup first and then run the
336277745c05SJosef Bacik 	 * delayed refs to make sure we have the best chance at doing this all
336377745c05SJosef Bacik 	 * in one shot.
336477745c05SJosef Bacik 	 */
336577745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
336677745c05SJosef Bacik 	while (!list_empty(&cur_trans->dirty_bgs)) {
336777745c05SJosef Bacik 		cache = list_first_entry(&cur_trans->dirty_bgs,
336832da5386SDavid Sterba 					 struct btrfs_block_group,
336977745c05SJosef Bacik 					 dirty_list);
337077745c05SJosef Bacik 
337177745c05SJosef Bacik 		/*
337277745c05SJosef Bacik 		 * This can happen if cache_save_setup re-dirties a block group
337377745c05SJosef Bacik 		 * that is already under IO.  Just wait for it to finish and
337477745c05SJosef Bacik 		 * then do it all again
337577745c05SJosef Bacik 		 */
337677745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
337777745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
337877745c05SJosef Bacik 			list_del_init(&cache->io_list);
337977745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
338077745c05SJosef Bacik 			btrfs_put_block_group(cache);
338177745c05SJosef Bacik 			spin_lock(&cur_trans->dirty_bgs_lock);
338277745c05SJosef Bacik 		}
338377745c05SJosef Bacik 
338477745c05SJosef Bacik 		/*
338577745c05SJosef Bacik 		 * Don't remove from the dirty list until after we've waited on
338677745c05SJosef Bacik 		 * any pending IO
338777745c05SJosef Bacik 		 */
338877745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
338977745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
339077745c05SJosef Bacik 		should_put = 1;
339177745c05SJosef Bacik 
339277745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
339377745c05SJosef Bacik 
339477745c05SJosef Bacik 		if (!ret)
339577745c05SJosef Bacik 			ret = btrfs_run_delayed_refs(trans,
339677745c05SJosef Bacik 						     (unsigned long) -1);
339777745c05SJosef Bacik 
339877745c05SJosef Bacik 		if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
339977745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
340077745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
340177745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
340277745c05SJosef Bacik 				should_put = 0;
340377745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
340477745c05SJosef Bacik 			} else {
340577745c05SJosef Bacik 				/*
340677745c05SJosef Bacik 				 * If we failed to write the cache, the
340777745c05SJosef Bacik 				 * generation will be bad and life goes on
340877745c05SJosef Bacik 				 */
340977745c05SJosef Bacik 				ret = 0;
341077745c05SJosef Bacik 			}
341177745c05SJosef Bacik 		}
341277745c05SJosef Bacik 		if (!ret) {
34133be4d8efSQu Wenruo 			ret = update_block_group_item(trans, path, cache);
341477745c05SJosef Bacik 			/*
341577745c05SJosef Bacik 			 * One of the free space endio workers might have
341677745c05SJosef Bacik 			 * created a new block group while updating a free space
341777745c05SJosef Bacik 			 * cache's inode (at inode.c:btrfs_finish_ordered_io())
341877745c05SJosef Bacik 			 * and hasn't released its transaction handle yet, in
341977745c05SJosef Bacik 			 * which case the new block group is still attached to
342077745c05SJosef Bacik 			 * its transaction handle and its creation has not
342177745c05SJosef Bacik 			 * finished yet (no block group item in the extent tree
342277745c05SJosef Bacik 			 * yet, etc). If this is the case, wait for all free
342377745c05SJosef Bacik 			 * space endio workers to finish and retry. This is a
3424260db43cSRandy Dunlap 			 * very rare case so no need for a more efficient and
342577745c05SJosef Bacik 			 * complex approach.
342677745c05SJosef Bacik 			 */
342777745c05SJosef Bacik 			if (ret == -ENOENT) {
342877745c05SJosef Bacik 				wait_event(cur_trans->writer_wait,
342977745c05SJosef Bacik 				   atomic_read(&cur_trans->num_writers) == 1);
34303be4d8efSQu Wenruo 				ret = update_block_group_item(trans, path, cache);
343177745c05SJosef Bacik 			}
343277745c05SJosef Bacik 			if (ret)
343377745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
343477745c05SJosef Bacik 		}
343577745c05SJosef Bacik 
343677745c05SJosef Bacik 		/* If its not on the io list, we need to put the block group */
343777745c05SJosef Bacik 		if (should_put)
343877745c05SJosef Bacik 			btrfs_put_block_group(cache);
343977745c05SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
344077745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
344177745c05SJosef Bacik 	}
344277745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
344377745c05SJosef Bacik 
344477745c05SJosef Bacik 	/*
344577745c05SJosef Bacik 	 * Refer to the definition of io_bgs member for details why it's safe
344677745c05SJosef Bacik 	 * to use it without any locking
344777745c05SJosef Bacik 	 */
344877745c05SJosef Bacik 	while (!list_empty(io)) {
344932da5386SDavid Sterba 		cache = list_first_entry(io, struct btrfs_block_group,
345077745c05SJosef Bacik 					 io_list);
345177745c05SJosef Bacik 		list_del_init(&cache->io_list);
345277745c05SJosef Bacik 		btrfs_wait_cache_io(trans, cache, path);
345377745c05SJosef Bacik 		btrfs_put_block_group(cache);
345477745c05SJosef Bacik 	}
345577745c05SJosef Bacik 
345677745c05SJosef Bacik 	btrfs_free_path(path);
345777745c05SJosef Bacik 	return ret;
345877745c05SJosef Bacik }
3459606d1bf1SJosef Bacik 
3460606d1bf1SJosef Bacik int btrfs_update_block_group(struct btrfs_trans_handle *trans,
346111b66fa6SAnand Jain 			     u64 bytenr, u64 num_bytes, bool alloc)
3462606d1bf1SJosef Bacik {
3463606d1bf1SJosef Bacik 	struct btrfs_fs_info *info = trans->fs_info;
346432da5386SDavid Sterba 	struct btrfs_block_group *cache = NULL;
3465606d1bf1SJosef Bacik 	u64 total = num_bytes;
3466606d1bf1SJosef Bacik 	u64 old_val;
3467606d1bf1SJosef Bacik 	u64 byte_in_group;
3468606d1bf1SJosef Bacik 	int factor;
3469606d1bf1SJosef Bacik 	int ret = 0;
3470606d1bf1SJosef Bacik 
3471606d1bf1SJosef Bacik 	/* Block accounting for super block */
3472606d1bf1SJosef Bacik 	spin_lock(&info->delalloc_root_lock);
3473606d1bf1SJosef Bacik 	old_val = btrfs_super_bytes_used(info->super_copy);
3474606d1bf1SJosef Bacik 	if (alloc)
3475606d1bf1SJosef Bacik 		old_val += num_bytes;
3476606d1bf1SJosef Bacik 	else
3477606d1bf1SJosef Bacik 		old_val -= num_bytes;
3478606d1bf1SJosef Bacik 	btrfs_set_super_bytes_used(info->super_copy, old_val);
3479606d1bf1SJosef Bacik 	spin_unlock(&info->delalloc_root_lock);
3480606d1bf1SJosef Bacik 
3481606d1bf1SJosef Bacik 	while (total) {
3482efbf35a1SJosef Bacik 		bool reclaim = false;
3483ac2f1e63SJosef Bacik 
3484606d1bf1SJosef Bacik 		cache = btrfs_lookup_block_group(info, bytenr);
3485606d1bf1SJosef Bacik 		if (!cache) {
3486606d1bf1SJosef Bacik 			ret = -ENOENT;
3487606d1bf1SJosef Bacik 			break;
3488606d1bf1SJosef Bacik 		}
3489606d1bf1SJosef Bacik 		factor = btrfs_bg_type_to_factor(cache->flags);
3490606d1bf1SJosef Bacik 
3491606d1bf1SJosef Bacik 		/*
3492606d1bf1SJosef Bacik 		 * If this block group has free space cache written out, we
3493606d1bf1SJosef Bacik 		 * need to make sure to load it if we are removing space.  This
3494606d1bf1SJosef Bacik 		 * is because we need the unpinning stage to actually add the
3495606d1bf1SJosef Bacik 		 * space back to the block group, otherwise we will leak space.
3496606d1bf1SJosef Bacik 		 */
349732da5386SDavid Sterba 		if (!alloc && !btrfs_block_group_done(cache))
3498ced8ecf0SOmar Sandoval 			btrfs_cache_block_group(cache, true);
3499606d1bf1SJosef Bacik 
3500b3470b5dSDavid Sterba 		byte_in_group = bytenr - cache->start;
3501b3470b5dSDavid Sterba 		WARN_ON(byte_in_group > cache->length);
3502606d1bf1SJosef Bacik 
3503606d1bf1SJosef Bacik 		spin_lock(&cache->space_info->lock);
3504606d1bf1SJosef Bacik 		spin_lock(&cache->lock);
3505606d1bf1SJosef Bacik 
3506606d1bf1SJosef Bacik 		if (btrfs_test_opt(info, SPACE_CACHE) &&
3507606d1bf1SJosef Bacik 		    cache->disk_cache_state < BTRFS_DC_CLEAR)
3508606d1bf1SJosef Bacik 			cache->disk_cache_state = BTRFS_DC_CLEAR;
3509606d1bf1SJosef Bacik 
3510bf38be65SDavid Sterba 		old_val = cache->used;
3511b3470b5dSDavid Sterba 		num_bytes = min(total, cache->length - byte_in_group);
3512606d1bf1SJosef Bacik 		if (alloc) {
3513606d1bf1SJosef Bacik 			old_val += num_bytes;
3514bf38be65SDavid Sterba 			cache->used = old_val;
3515606d1bf1SJosef Bacik 			cache->reserved -= num_bytes;
3516606d1bf1SJosef Bacik 			cache->space_info->bytes_reserved -= num_bytes;
3517606d1bf1SJosef Bacik 			cache->space_info->bytes_used += num_bytes;
3518606d1bf1SJosef Bacik 			cache->space_info->disk_used += num_bytes * factor;
3519606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
3520606d1bf1SJosef Bacik 			spin_unlock(&cache->space_info->lock);
3521606d1bf1SJosef Bacik 		} else {
3522606d1bf1SJosef Bacik 			old_val -= num_bytes;
3523bf38be65SDavid Sterba 			cache->used = old_val;
3524606d1bf1SJosef Bacik 			cache->pinned += num_bytes;
3525606d1bf1SJosef Bacik 			btrfs_space_info_update_bytes_pinned(info,
3526606d1bf1SJosef Bacik 					cache->space_info, num_bytes);
3527606d1bf1SJosef Bacik 			cache->space_info->bytes_used -= num_bytes;
3528606d1bf1SJosef Bacik 			cache->space_info->disk_used -= num_bytes * factor;
3529ac2f1e63SJosef Bacik 
3530ac2f1e63SJosef Bacik 			reclaim = should_reclaim_block_group(cache, num_bytes);
353152bb7a21SBoris Burkov 
3532606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
3533606d1bf1SJosef Bacik 			spin_unlock(&cache->space_info->lock);
3534606d1bf1SJosef Bacik 
3535fe119a6eSNikolay Borisov 			set_extent_dirty(&trans->transaction->pinned_extents,
3536606d1bf1SJosef Bacik 					 bytenr, bytenr + num_bytes - 1,
3537606d1bf1SJosef Bacik 					 GFP_NOFS | __GFP_NOFAIL);
3538606d1bf1SJosef Bacik 		}
3539606d1bf1SJosef Bacik 
3540606d1bf1SJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
3541606d1bf1SJosef Bacik 		if (list_empty(&cache->dirty_list)) {
3542606d1bf1SJosef Bacik 			list_add_tail(&cache->dirty_list,
3543606d1bf1SJosef Bacik 				      &trans->transaction->dirty_bgs);
3544606d1bf1SJosef Bacik 			trans->delayed_ref_updates++;
3545606d1bf1SJosef Bacik 			btrfs_get_block_group(cache);
3546606d1bf1SJosef Bacik 		}
3547606d1bf1SJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
3548606d1bf1SJosef Bacik 
3549606d1bf1SJosef Bacik 		/*
3550606d1bf1SJosef Bacik 		 * No longer have used bytes in this block group, queue it for
3551606d1bf1SJosef Bacik 		 * deletion. We do this after adding the block group to the
3552606d1bf1SJosef Bacik 		 * dirty list to avoid races between cleaner kthread and space
3553606d1bf1SJosef Bacik 		 * cache writeout.
3554606d1bf1SJosef Bacik 		 */
35556e80d4f8SDennis Zhou 		if (!alloc && old_val == 0) {
35566e80d4f8SDennis Zhou 			if (!btrfs_test_opt(info, DISCARD_ASYNC))
3557606d1bf1SJosef Bacik 				btrfs_mark_bg_unused(cache);
3558ac2f1e63SJosef Bacik 		} else if (!alloc && reclaim) {
3559ac2f1e63SJosef Bacik 			btrfs_mark_bg_to_reclaim(cache);
35606e80d4f8SDennis Zhou 		}
3561606d1bf1SJosef Bacik 
3562606d1bf1SJosef Bacik 		btrfs_put_block_group(cache);
3563606d1bf1SJosef Bacik 		total -= num_bytes;
3564606d1bf1SJosef Bacik 		bytenr += num_bytes;
3565606d1bf1SJosef Bacik 	}
3566606d1bf1SJosef Bacik 
3567606d1bf1SJosef Bacik 	/* Modified block groups are accounted for in the delayed_refs_rsv. */
3568606d1bf1SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
3569606d1bf1SJosef Bacik 	return ret;
3570606d1bf1SJosef Bacik }
3571606d1bf1SJosef Bacik 
357243dd529aSDavid Sterba /*
357343dd529aSDavid Sterba  * Update the block_group and space info counters.
357443dd529aSDavid Sterba  *
3575606d1bf1SJosef Bacik  * @cache:	The cache we are manipulating
3576606d1bf1SJosef Bacik  * @ram_bytes:  The number of bytes of file content, and will be same to
3577606d1bf1SJosef Bacik  *              @num_bytes except for the compress path.
3578606d1bf1SJosef Bacik  * @num_bytes:	The number of bytes in question
3579606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
3580606d1bf1SJosef Bacik  *
3581606d1bf1SJosef Bacik  * This is called by the allocator when it reserves space. If this is a
3582606d1bf1SJosef Bacik  * reservation and the block group has become read only we cannot make the
3583606d1bf1SJosef Bacik  * reservation and return -EAGAIN, otherwise this function always succeeds.
3584606d1bf1SJosef Bacik  */
358532da5386SDavid Sterba int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
358652bb7a21SBoris Burkov 			     u64 ram_bytes, u64 num_bytes, int delalloc,
358752bb7a21SBoris Burkov 			     bool force_wrong_size_class)
3588606d1bf1SJosef Bacik {
3589606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
359052bb7a21SBoris Burkov 	enum btrfs_block_group_size_class size_class;
3591606d1bf1SJosef Bacik 	int ret = 0;
3592606d1bf1SJosef Bacik 
3593606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
3594606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
3595606d1bf1SJosef Bacik 	if (cache->ro) {
3596606d1bf1SJosef Bacik 		ret = -EAGAIN;
359752bb7a21SBoris Burkov 		goto out;
359852bb7a21SBoris Burkov 	}
359952bb7a21SBoris Burkov 
360052bb7a21SBoris Burkov 	if (btrfs_is_block_group_data_only(cache)) {
360152bb7a21SBoris Burkov 		size_class = btrfs_calc_block_group_size_class(num_bytes);
360252bb7a21SBoris Burkov 		ret = btrfs_use_block_group_size_class(cache, size_class, force_wrong_size_class);
360352bb7a21SBoris Burkov 		if (ret)
360452bb7a21SBoris Burkov 			goto out;
360552bb7a21SBoris Burkov 	}
3606606d1bf1SJosef Bacik 	cache->reserved += num_bytes;
3607606d1bf1SJosef Bacik 	space_info->bytes_reserved += num_bytes;
3608a43c3835SJosef Bacik 	trace_btrfs_space_reservation(cache->fs_info, "space_info",
3609a43c3835SJosef Bacik 				      space_info->flags, num_bytes, 1);
3610606d1bf1SJosef Bacik 	btrfs_space_info_update_bytes_may_use(cache->fs_info,
3611606d1bf1SJosef Bacik 					      space_info, -ram_bytes);
3612606d1bf1SJosef Bacik 	if (delalloc)
3613606d1bf1SJosef Bacik 		cache->delalloc_bytes += num_bytes;
361499ffb43eSJosef Bacik 
361599ffb43eSJosef Bacik 	/*
361652bb7a21SBoris Burkov 	 * Compression can use less space than we reserved, so wake tickets if
361752bb7a21SBoris Burkov 	 * that happens.
361899ffb43eSJosef Bacik 	 */
361999ffb43eSJosef Bacik 	if (num_bytes < ram_bytes)
362099ffb43eSJosef Bacik 		btrfs_try_granting_tickets(cache->fs_info, space_info);
362152bb7a21SBoris Burkov out:
3622606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
3623606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
3624606d1bf1SJosef Bacik 	return ret;
3625606d1bf1SJosef Bacik }
3626606d1bf1SJosef Bacik 
362743dd529aSDavid Sterba /*
362843dd529aSDavid Sterba  * Update the block_group and space info counters.
362943dd529aSDavid Sterba  *
3630606d1bf1SJosef Bacik  * @cache:      The cache we are manipulating
3631606d1bf1SJosef Bacik  * @num_bytes:  The number of bytes in question
3632606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
3633606d1bf1SJosef Bacik  *
3634606d1bf1SJosef Bacik  * This is called by somebody who is freeing space that was never actually used
3635606d1bf1SJosef Bacik  * on disk.  For example if you reserve some space for a new leaf in transaction
3636606d1bf1SJosef Bacik  * A and before transaction A commits you free that leaf, you call this with
3637606d1bf1SJosef Bacik  * reserve set to 0 in order to clear the reservation.
3638606d1bf1SJosef Bacik  */
363932da5386SDavid Sterba void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3640606d1bf1SJosef Bacik 			       u64 num_bytes, int delalloc)
3641606d1bf1SJosef Bacik {
3642606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
3643606d1bf1SJosef Bacik 
3644606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
3645606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
3646606d1bf1SJosef Bacik 	if (cache->ro)
3647606d1bf1SJosef Bacik 		space_info->bytes_readonly += num_bytes;
3648606d1bf1SJosef Bacik 	cache->reserved -= num_bytes;
3649606d1bf1SJosef Bacik 	space_info->bytes_reserved -= num_bytes;
3650606d1bf1SJosef Bacik 	space_info->max_extent_size = 0;
3651606d1bf1SJosef Bacik 
3652606d1bf1SJosef Bacik 	if (delalloc)
3653606d1bf1SJosef Bacik 		cache->delalloc_bytes -= num_bytes;
3654606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
36553308234aSJosef Bacik 
36563308234aSJosef Bacik 	btrfs_try_granting_tickets(cache->fs_info, space_info);
3657606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
3658606d1bf1SJosef Bacik }
365907730d87SJosef Bacik 
366007730d87SJosef Bacik static void force_metadata_allocation(struct btrfs_fs_info *info)
366107730d87SJosef Bacik {
366207730d87SJosef Bacik 	struct list_head *head = &info->space_info;
366307730d87SJosef Bacik 	struct btrfs_space_info *found;
366407730d87SJosef Bacik 
366572804905SJosef Bacik 	list_for_each_entry(found, head, list) {
366607730d87SJosef Bacik 		if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
366707730d87SJosef Bacik 			found->force_alloc = CHUNK_ALLOC_FORCE;
366807730d87SJosef Bacik 	}
366907730d87SJosef Bacik }
367007730d87SJosef Bacik 
367107730d87SJosef Bacik static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
367207730d87SJosef Bacik 			      struct btrfs_space_info *sinfo, int force)
367307730d87SJosef Bacik {
367407730d87SJosef Bacik 	u64 bytes_used = btrfs_space_info_used(sinfo, false);
367507730d87SJosef Bacik 	u64 thresh;
367607730d87SJosef Bacik 
367707730d87SJosef Bacik 	if (force == CHUNK_ALLOC_FORCE)
367807730d87SJosef Bacik 		return 1;
367907730d87SJosef Bacik 
368007730d87SJosef Bacik 	/*
368107730d87SJosef Bacik 	 * in limited mode, we want to have some free space up to
368207730d87SJosef Bacik 	 * about 1% of the FS size.
368307730d87SJosef Bacik 	 */
368407730d87SJosef Bacik 	if (force == CHUNK_ALLOC_LIMITED) {
368507730d87SJosef Bacik 		thresh = btrfs_super_total_bytes(fs_info->super_copy);
3686428c8e03SDavid Sterba 		thresh = max_t(u64, SZ_64M, mult_perc(thresh, 1));
368707730d87SJosef Bacik 
368807730d87SJosef Bacik 		if (sinfo->total_bytes - bytes_used < thresh)
368907730d87SJosef Bacik 			return 1;
369007730d87SJosef Bacik 	}
369107730d87SJosef Bacik 
3692428c8e03SDavid Sterba 	if (bytes_used + SZ_2M < mult_perc(sinfo->total_bytes, 80))
369307730d87SJosef Bacik 		return 0;
369407730d87SJosef Bacik 	return 1;
369507730d87SJosef Bacik }
369607730d87SJosef Bacik 
369707730d87SJosef Bacik int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
369807730d87SJosef Bacik {
369907730d87SJosef Bacik 	u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
370007730d87SJosef Bacik 
370107730d87SJosef Bacik 	return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
370207730d87SJosef Bacik }
370307730d87SJosef Bacik 
3704820c363bSNaohiro Aota static struct btrfs_block_group *do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags)
370579bd3712SFilipe Manana {
370679bd3712SFilipe Manana 	struct btrfs_block_group *bg;
370779bd3712SFilipe Manana 	int ret;
370879bd3712SFilipe Manana 
370907730d87SJosef Bacik 	/*
371079bd3712SFilipe Manana 	 * Check if we have enough space in the system space info because we
371179bd3712SFilipe Manana 	 * will need to update device items in the chunk btree and insert a new
371279bd3712SFilipe Manana 	 * chunk item in the chunk btree as well. This will allocate a new
371379bd3712SFilipe Manana 	 * system block group if needed.
371479bd3712SFilipe Manana 	 */
371579bd3712SFilipe Manana 	check_system_chunk(trans, flags);
371679bd3712SFilipe Manana 
3717f6f39f7aSNikolay Borisov 	bg = btrfs_create_chunk(trans, flags);
371879bd3712SFilipe Manana 	if (IS_ERR(bg)) {
371979bd3712SFilipe Manana 		ret = PTR_ERR(bg);
372079bd3712SFilipe Manana 		goto out;
372179bd3712SFilipe Manana 	}
372279bd3712SFilipe Manana 
372379bd3712SFilipe Manana 	ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
372479bd3712SFilipe Manana 	/*
372579bd3712SFilipe Manana 	 * Normally we are not expected to fail with -ENOSPC here, since we have
372679bd3712SFilipe Manana 	 * previously reserved space in the system space_info and allocated one
3727ecd84d54SFilipe Manana 	 * new system chunk if necessary. However there are three exceptions:
372879bd3712SFilipe Manana 	 *
372979bd3712SFilipe Manana 	 * 1) We may have enough free space in the system space_info but all the
373079bd3712SFilipe Manana 	 *    existing system block groups have a profile which can not be used
373179bd3712SFilipe Manana 	 *    for extent allocation.
373279bd3712SFilipe Manana 	 *
373379bd3712SFilipe Manana 	 *    This happens when mounting in degraded mode. For example we have a
373479bd3712SFilipe Manana 	 *    RAID1 filesystem with 2 devices, lose one device and mount the fs
373579bd3712SFilipe Manana 	 *    using the other device in degraded mode. If we then allocate a chunk,
373679bd3712SFilipe Manana 	 *    we may have enough free space in the existing system space_info, but
373779bd3712SFilipe Manana 	 *    none of the block groups can be used for extent allocation since they
373879bd3712SFilipe Manana 	 *    have a RAID1 profile, and because we are in degraded mode with a
373979bd3712SFilipe Manana 	 *    single device, we are forced to allocate a new system chunk with a
374079bd3712SFilipe Manana 	 *    SINGLE profile. Making check_system_chunk() iterate over all system
374179bd3712SFilipe Manana 	 *    block groups and check if they have a usable profile and enough space
374279bd3712SFilipe Manana 	 *    can be slow on very large filesystems, so we tolerate the -ENOSPC and
374379bd3712SFilipe Manana 	 *    try again after forcing allocation of a new system chunk. Like this
374479bd3712SFilipe Manana 	 *    we avoid paying the cost of that search in normal circumstances, when
374579bd3712SFilipe Manana 	 *    we were not mounted in degraded mode;
374679bd3712SFilipe Manana 	 *
374779bd3712SFilipe Manana 	 * 2) We had enough free space info the system space_info, and one suitable
374879bd3712SFilipe Manana 	 *    block group to allocate from when we called check_system_chunk()
374979bd3712SFilipe Manana 	 *    above. However right after we called it, the only system block group
375079bd3712SFilipe Manana 	 *    with enough free space got turned into RO mode by a running scrub,
375179bd3712SFilipe Manana 	 *    and in this case we have to allocate a new one and retry. We only
375279bd3712SFilipe Manana 	 *    need do this allocate and retry once, since we have a transaction
3753ecd84d54SFilipe Manana 	 *    handle and scrub uses the commit root to search for block groups;
3754ecd84d54SFilipe Manana 	 *
3755ecd84d54SFilipe Manana 	 * 3) We had one system block group with enough free space when we called
3756ecd84d54SFilipe Manana 	 *    check_system_chunk(), but after that, right before we tried to
3757ecd84d54SFilipe Manana 	 *    allocate the last extent buffer we needed, a discard operation came
3758ecd84d54SFilipe Manana 	 *    in and it temporarily removed the last free space entry from the
3759ecd84d54SFilipe Manana 	 *    block group (discard removes a free space entry, discards it, and
3760ecd84d54SFilipe Manana 	 *    then adds back the entry to the block group cache).
376179bd3712SFilipe Manana 	 */
376279bd3712SFilipe Manana 	if (ret == -ENOSPC) {
376379bd3712SFilipe Manana 		const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info);
376479bd3712SFilipe Manana 		struct btrfs_block_group *sys_bg;
376579bd3712SFilipe Manana 
3766f6f39f7aSNikolay Borisov 		sys_bg = btrfs_create_chunk(trans, sys_flags);
376779bd3712SFilipe Manana 		if (IS_ERR(sys_bg)) {
376879bd3712SFilipe Manana 			ret = PTR_ERR(sys_bg);
376979bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
377079bd3712SFilipe Manana 			goto out;
377179bd3712SFilipe Manana 		}
377279bd3712SFilipe Manana 
377379bd3712SFilipe Manana 		ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
377479bd3712SFilipe Manana 		if (ret) {
377579bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
377679bd3712SFilipe Manana 			goto out;
377779bd3712SFilipe Manana 		}
377879bd3712SFilipe Manana 
377979bd3712SFilipe Manana 		ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
378079bd3712SFilipe Manana 		if (ret) {
378179bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
378279bd3712SFilipe Manana 			goto out;
378379bd3712SFilipe Manana 		}
378479bd3712SFilipe Manana 	} else if (ret) {
378579bd3712SFilipe Manana 		btrfs_abort_transaction(trans, ret);
378679bd3712SFilipe Manana 		goto out;
378779bd3712SFilipe Manana 	}
378879bd3712SFilipe Manana out:
378979bd3712SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
379079bd3712SFilipe Manana 
3791820c363bSNaohiro Aota 	if (ret)
3792820c363bSNaohiro Aota 		return ERR_PTR(ret);
3793820c363bSNaohiro Aota 
3794820c363bSNaohiro Aota 	btrfs_get_block_group(bg);
3795820c363bSNaohiro Aota 	return bg;
379679bd3712SFilipe Manana }
379779bd3712SFilipe Manana 
379879bd3712SFilipe Manana /*
379979bd3712SFilipe Manana  * Chunk allocation is done in 2 phases:
380079bd3712SFilipe Manana  *
380179bd3712SFilipe Manana  * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
380279bd3712SFilipe Manana  *    the chunk, the chunk mapping, create its block group and add the items
380379bd3712SFilipe Manana  *    that belong in the chunk btree to it - more specifically, we need to
380479bd3712SFilipe Manana  *    update device items in the chunk btree and add a new chunk item to it.
380579bd3712SFilipe Manana  *
380679bd3712SFilipe Manana  * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
380779bd3712SFilipe Manana  *    group item to the extent btree and the device extent items to the devices
380879bd3712SFilipe Manana  *    btree.
380979bd3712SFilipe Manana  *
381079bd3712SFilipe Manana  * This is done to prevent deadlocks. For example when COWing a node from the
381179bd3712SFilipe Manana  * extent btree we are holding a write lock on the node's parent and if we
381279bd3712SFilipe Manana  * trigger chunk allocation and attempted to insert the new block group item
381379bd3712SFilipe Manana  * in the extent btree right way, we could deadlock because the path for the
381479bd3712SFilipe Manana  * insertion can include that parent node. At first glance it seems impossible
381579bd3712SFilipe Manana  * to trigger chunk allocation after starting a transaction since tasks should
381679bd3712SFilipe Manana  * reserve enough transaction units (metadata space), however while that is true
381779bd3712SFilipe Manana  * most of the time, chunk allocation may still be triggered for several reasons:
381879bd3712SFilipe Manana  *
381979bd3712SFilipe Manana  * 1) When reserving metadata, we check if there is enough free space in the
382079bd3712SFilipe Manana  *    metadata space_info and therefore don't trigger allocation of a new chunk.
382179bd3712SFilipe Manana  *    However later when the task actually tries to COW an extent buffer from
382279bd3712SFilipe Manana  *    the extent btree or from the device btree for example, it is forced to
382379bd3712SFilipe Manana  *    allocate a new block group (chunk) because the only one that had enough
382479bd3712SFilipe Manana  *    free space was just turned to RO mode by a running scrub for example (or
382579bd3712SFilipe Manana  *    device replace, block group reclaim thread, etc), so we can not use it
382679bd3712SFilipe Manana  *    for allocating an extent and end up being forced to allocate a new one;
382779bd3712SFilipe Manana  *
382879bd3712SFilipe Manana  * 2) Because we only check that the metadata space_info has enough free bytes,
382979bd3712SFilipe Manana  *    we end up not allocating a new metadata chunk in that case. However if
383079bd3712SFilipe Manana  *    the filesystem was mounted in degraded mode, none of the existing block
383179bd3712SFilipe Manana  *    groups might be suitable for extent allocation due to their incompatible
383279bd3712SFilipe Manana  *    profile (for e.g. mounting a 2 devices filesystem, where all block groups
383379bd3712SFilipe Manana  *    use a RAID1 profile, in degraded mode using a single device). In this case
383479bd3712SFilipe Manana  *    when the task attempts to COW some extent buffer of the extent btree for
383579bd3712SFilipe Manana  *    example, it will trigger allocation of a new metadata block group with a
383679bd3712SFilipe Manana  *    suitable profile (SINGLE profile in the example of the degraded mount of
383779bd3712SFilipe Manana  *    the RAID1 filesystem);
383879bd3712SFilipe Manana  *
383979bd3712SFilipe Manana  * 3) The task has reserved enough transaction units / metadata space, but when
384079bd3712SFilipe Manana  *    it attempts to COW an extent buffer from the extent or device btree for
384179bd3712SFilipe Manana  *    example, it does not find any free extent in any metadata block group,
384279bd3712SFilipe Manana  *    therefore forced to try to allocate a new metadata block group.
384379bd3712SFilipe Manana  *    This is because some other task allocated all available extents in the
384479bd3712SFilipe Manana  *    meanwhile - this typically happens with tasks that don't reserve space
384579bd3712SFilipe Manana  *    properly, either intentionally or as a bug. One example where this is
384679bd3712SFilipe Manana  *    done intentionally is fsync, as it does not reserve any transaction units
384779bd3712SFilipe Manana  *    and ends up allocating a variable number of metadata extents for log
3848ecd84d54SFilipe Manana  *    tree extent buffers;
3849ecd84d54SFilipe Manana  *
3850ecd84d54SFilipe Manana  * 4) The task has reserved enough transaction units / metadata space, but right
3851ecd84d54SFilipe Manana  *    before it tries to allocate the last extent buffer it needs, a discard
3852ecd84d54SFilipe Manana  *    operation comes in and, temporarily, removes the last free space entry from
3853ecd84d54SFilipe Manana  *    the only metadata block group that had free space (discard starts by
3854ecd84d54SFilipe Manana  *    removing a free space entry from a block group, then does the discard
3855ecd84d54SFilipe Manana  *    operation and, once it's done, it adds back the free space entry to the
3856ecd84d54SFilipe Manana  *    block group).
385779bd3712SFilipe Manana  *
385879bd3712SFilipe Manana  * We also need this 2 phases setup when adding a device to a filesystem with
385979bd3712SFilipe Manana  * a seed device - we must create new metadata and system chunks without adding
386079bd3712SFilipe Manana  * any of the block group items to the chunk, extent and device btrees. If we
386179bd3712SFilipe Manana  * did not do it this way, we would get ENOSPC when attempting to update those
386279bd3712SFilipe Manana  * btrees, since all the chunks from the seed device are read-only.
386379bd3712SFilipe Manana  *
386479bd3712SFilipe Manana  * Phase 1 does the updates and insertions to the chunk btree because if we had
386579bd3712SFilipe Manana  * it done in phase 2 and have a thundering herd of tasks allocating chunks in
386679bd3712SFilipe Manana  * parallel, we risk having too many system chunks allocated by many tasks if
386779bd3712SFilipe Manana  * many tasks reach phase 1 without the previous ones completing phase 2. In the
386879bd3712SFilipe Manana  * extreme case this leads to exhaustion of the system chunk array in the
386979bd3712SFilipe Manana  * superblock. This is easier to trigger if using a btree node/leaf size of 64K
387079bd3712SFilipe Manana  * and with RAID filesystems (so we have more device items in the chunk btree).
387179bd3712SFilipe Manana  * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
387279bd3712SFilipe Manana  * the system chunk array due to concurrent allocations") provides more details.
387379bd3712SFilipe Manana  *
38742bb2e00eSFilipe Manana  * Allocation of system chunks does not happen through this function. A task that
38752bb2e00eSFilipe Manana  * needs to update the chunk btree (the only btree that uses system chunks), must
38762bb2e00eSFilipe Manana  * preallocate chunk space by calling either check_system_chunk() or
38772bb2e00eSFilipe Manana  * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or
38782bb2e00eSFilipe Manana  * metadata chunk or when removing a chunk, while the later is used before doing
38792bb2e00eSFilipe Manana  * a modification to the chunk btree - use cases for the later are adding,
38802bb2e00eSFilipe Manana  * removing and resizing a device as well as relocation of a system chunk.
38812bb2e00eSFilipe Manana  * See the comment below for more details.
388279bd3712SFilipe Manana  *
388379bd3712SFilipe Manana  * The reservation of system space, done through check_system_chunk(), as well
388479bd3712SFilipe Manana  * as all the updates and insertions into the chunk btree must be done while
388579bd3712SFilipe Manana  * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
388679bd3712SFilipe Manana  * an extent buffer from the chunks btree we never trigger allocation of a new
388779bd3712SFilipe Manana  * system chunk, which would result in a deadlock (trying to lock twice an
388879bd3712SFilipe Manana  * extent buffer of the chunk btree, first time before triggering the chunk
388979bd3712SFilipe Manana  * allocation and the second time during chunk allocation while attempting to
389079bd3712SFilipe Manana  * update the chunks btree). The system chunk array is also updated while holding
389179bd3712SFilipe Manana  * that mutex. The same logic applies to removing chunks - we must reserve system
389279bd3712SFilipe Manana  * space, update the chunk btree and the system chunk array in the superblock
389379bd3712SFilipe Manana  * while holding fs_info->chunk_mutex.
389479bd3712SFilipe Manana  *
389579bd3712SFilipe Manana  * This function, btrfs_chunk_alloc(), belongs to phase 1.
389679bd3712SFilipe Manana  *
389779bd3712SFilipe Manana  * If @force is CHUNK_ALLOC_FORCE:
389807730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
389907730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
390079bd3712SFilipe Manana  * If @force is NOT CHUNK_ALLOC_FORCE:
390107730d87SJosef Bacik  *    - return 0 if it doesn't need to allocate a new chunk,
390207730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
390307730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
390407730d87SJosef Bacik  */
390507730d87SJosef Bacik int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
390607730d87SJosef Bacik 		      enum btrfs_chunk_alloc_enum force)
390707730d87SJosef Bacik {
390807730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
390907730d87SJosef Bacik 	struct btrfs_space_info *space_info;
3910820c363bSNaohiro Aota 	struct btrfs_block_group *ret_bg;
391107730d87SJosef Bacik 	bool wait_for_alloc = false;
391207730d87SJosef Bacik 	bool should_alloc = false;
3913760e69c4SNaohiro Aota 	bool from_extent_allocation = false;
391407730d87SJosef Bacik 	int ret = 0;
391507730d87SJosef Bacik 
3916760e69c4SNaohiro Aota 	if (force == CHUNK_ALLOC_FORCE_FOR_EXTENT) {
3917760e69c4SNaohiro Aota 		from_extent_allocation = true;
3918760e69c4SNaohiro Aota 		force = CHUNK_ALLOC_FORCE;
3919760e69c4SNaohiro Aota 	}
3920760e69c4SNaohiro Aota 
392107730d87SJosef Bacik 	/* Don't re-enter if we're already allocating a chunk */
392207730d87SJosef Bacik 	if (trans->allocating_chunk)
392307730d87SJosef Bacik 		return -ENOSPC;
392479bd3712SFilipe Manana 	/*
39252bb2e00eSFilipe Manana 	 * Allocation of system chunks can not happen through this path, as we
39262bb2e00eSFilipe Manana 	 * could end up in a deadlock if we are allocating a data or metadata
39272bb2e00eSFilipe Manana 	 * chunk and there is another task modifying the chunk btree.
39282bb2e00eSFilipe Manana 	 *
39292bb2e00eSFilipe Manana 	 * This is because while we are holding the chunk mutex, we will attempt
39302bb2e00eSFilipe Manana 	 * to add the new chunk item to the chunk btree or update an existing
39312bb2e00eSFilipe Manana 	 * device item in the chunk btree, while the other task that is modifying
39322bb2e00eSFilipe Manana 	 * the chunk btree is attempting to COW an extent buffer while holding a
39332bb2e00eSFilipe Manana 	 * lock on it and on its parent - if the COW operation triggers a system
39342bb2e00eSFilipe Manana 	 * chunk allocation, then we can deadlock because we are holding the
39352bb2e00eSFilipe Manana 	 * chunk mutex and we may need to access that extent buffer or its parent
39362bb2e00eSFilipe Manana 	 * in order to add the chunk item or update a device item.
39372bb2e00eSFilipe Manana 	 *
39382bb2e00eSFilipe Manana 	 * Tasks that want to modify the chunk tree should reserve system space
39392bb2e00eSFilipe Manana 	 * before updating the chunk btree, by calling either
39402bb2e00eSFilipe Manana 	 * btrfs_reserve_chunk_metadata() or check_system_chunk().
39412bb2e00eSFilipe Manana 	 * It's possible that after a task reserves the space, it still ends up
39422bb2e00eSFilipe Manana 	 * here - this happens in the cases described above at do_chunk_alloc().
39432bb2e00eSFilipe Manana 	 * The task will have to either retry or fail.
394479bd3712SFilipe Manana 	 */
39452bb2e00eSFilipe Manana 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
394679bd3712SFilipe Manana 		return -ENOSPC;
394707730d87SJosef Bacik 
394807730d87SJosef Bacik 	space_info = btrfs_find_space_info(fs_info, flags);
394907730d87SJosef Bacik 	ASSERT(space_info);
395007730d87SJosef Bacik 
395107730d87SJosef Bacik 	do {
395207730d87SJosef Bacik 		spin_lock(&space_info->lock);
395307730d87SJosef Bacik 		if (force < space_info->force_alloc)
395407730d87SJosef Bacik 			force = space_info->force_alloc;
395507730d87SJosef Bacik 		should_alloc = should_alloc_chunk(fs_info, space_info, force);
395607730d87SJosef Bacik 		if (space_info->full) {
395707730d87SJosef Bacik 			/* No more free physical space */
395807730d87SJosef Bacik 			if (should_alloc)
395907730d87SJosef Bacik 				ret = -ENOSPC;
396007730d87SJosef Bacik 			else
396107730d87SJosef Bacik 				ret = 0;
396207730d87SJosef Bacik 			spin_unlock(&space_info->lock);
396307730d87SJosef Bacik 			return ret;
396407730d87SJosef Bacik 		} else if (!should_alloc) {
396507730d87SJosef Bacik 			spin_unlock(&space_info->lock);
396607730d87SJosef Bacik 			return 0;
396707730d87SJosef Bacik 		} else if (space_info->chunk_alloc) {
396807730d87SJosef Bacik 			/*
396907730d87SJosef Bacik 			 * Someone is already allocating, so we need to block
397007730d87SJosef Bacik 			 * until this someone is finished and then loop to
397107730d87SJosef Bacik 			 * recheck if we should continue with our allocation
397207730d87SJosef Bacik 			 * attempt.
397307730d87SJosef Bacik 			 */
397407730d87SJosef Bacik 			wait_for_alloc = true;
39751314ca78SJosef Bacik 			force = CHUNK_ALLOC_NO_FORCE;
397607730d87SJosef Bacik 			spin_unlock(&space_info->lock);
397707730d87SJosef Bacik 			mutex_lock(&fs_info->chunk_mutex);
397807730d87SJosef Bacik 			mutex_unlock(&fs_info->chunk_mutex);
397907730d87SJosef Bacik 		} else {
398007730d87SJosef Bacik 			/* Proceed with allocation */
398107730d87SJosef Bacik 			space_info->chunk_alloc = 1;
398207730d87SJosef Bacik 			wait_for_alloc = false;
398307730d87SJosef Bacik 			spin_unlock(&space_info->lock);
398407730d87SJosef Bacik 		}
398507730d87SJosef Bacik 
398607730d87SJosef Bacik 		cond_resched();
398707730d87SJosef Bacik 	} while (wait_for_alloc);
398807730d87SJosef Bacik 
398907730d87SJosef Bacik 	mutex_lock(&fs_info->chunk_mutex);
399007730d87SJosef Bacik 	trans->allocating_chunk = true;
399107730d87SJosef Bacik 
399207730d87SJosef Bacik 	/*
399307730d87SJosef Bacik 	 * If we have mixed data/metadata chunks we want to make sure we keep
399407730d87SJosef Bacik 	 * allocating mixed chunks instead of individual chunks.
399507730d87SJosef Bacik 	 */
399607730d87SJosef Bacik 	if (btrfs_mixed_space_info(space_info))
399707730d87SJosef Bacik 		flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
399807730d87SJosef Bacik 
399907730d87SJosef Bacik 	/*
400007730d87SJosef Bacik 	 * if we're doing a data chunk, go ahead and make sure that
400107730d87SJosef Bacik 	 * we keep a reasonable number of metadata chunks allocated in the
400207730d87SJosef Bacik 	 * FS as well.
400307730d87SJosef Bacik 	 */
400407730d87SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
400507730d87SJosef Bacik 		fs_info->data_chunk_allocations++;
400607730d87SJosef Bacik 		if (!(fs_info->data_chunk_allocations %
400707730d87SJosef Bacik 		      fs_info->metadata_ratio))
400807730d87SJosef Bacik 			force_metadata_allocation(fs_info);
400907730d87SJosef Bacik 	}
401007730d87SJosef Bacik 
4011820c363bSNaohiro Aota 	ret_bg = do_chunk_alloc(trans, flags);
401207730d87SJosef Bacik 	trans->allocating_chunk = false;
401307730d87SJosef Bacik 
4014760e69c4SNaohiro Aota 	if (IS_ERR(ret_bg)) {
4015820c363bSNaohiro Aota 		ret = PTR_ERR(ret_bg);
4016760e69c4SNaohiro Aota 	} else if (from_extent_allocation) {
4017760e69c4SNaohiro Aota 		/*
4018760e69c4SNaohiro Aota 		 * New block group is likely to be used soon. Try to activate
4019760e69c4SNaohiro Aota 		 * it now. Failure is OK for now.
4020760e69c4SNaohiro Aota 		 */
4021760e69c4SNaohiro Aota 		btrfs_zone_activate(ret_bg);
4022760e69c4SNaohiro Aota 	}
4023760e69c4SNaohiro Aota 
4024760e69c4SNaohiro Aota 	if (!ret)
4025820c363bSNaohiro Aota 		btrfs_put_block_group(ret_bg);
4026820c363bSNaohiro Aota 
402707730d87SJosef Bacik 	spin_lock(&space_info->lock);
402807730d87SJosef Bacik 	if (ret < 0) {
402907730d87SJosef Bacik 		if (ret == -ENOSPC)
403007730d87SJosef Bacik 			space_info->full = 1;
403107730d87SJosef Bacik 		else
403207730d87SJosef Bacik 			goto out;
403307730d87SJosef Bacik 	} else {
403407730d87SJosef Bacik 		ret = 1;
403507730d87SJosef Bacik 		space_info->max_extent_size = 0;
403607730d87SJosef Bacik 	}
403707730d87SJosef Bacik 
403807730d87SJosef Bacik 	space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
403907730d87SJosef Bacik out:
404007730d87SJosef Bacik 	space_info->chunk_alloc = 0;
404107730d87SJosef Bacik 	spin_unlock(&space_info->lock);
404207730d87SJosef Bacik 	mutex_unlock(&fs_info->chunk_mutex);
404307730d87SJosef Bacik 
404407730d87SJosef Bacik 	return ret;
404507730d87SJosef Bacik }
404607730d87SJosef Bacik 
404707730d87SJosef Bacik static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
404807730d87SJosef Bacik {
404907730d87SJosef Bacik 	u64 num_dev;
405007730d87SJosef Bacik 
405107730d87SJosef Bacik 	num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
405207730d87SJosef Bacik 	if (!num_dev)
405307730d87SJosef Bacik 		num_dev = fs_info->fs_devices->rw_devices;
405407730d87SJosef Bacik 
405507730d87SJosef Bacik 	return num_dev;
405607730d87SJosef Bacik }
405707730d87SJosef Bacik 
40582bb2e00eSFilipe Manana static void reserve_chunk_space(struct btrfs_trans_handle *trans,
40592bb2e00eSFilipe Manana 				u64 bytes,
40602bb2e00eSFilipe Manana 				u64 type)
406107730d87SJosef Bacik {
406207730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
406307730d87SJosef Bacik 	struct btrfs_space_info *info;
406407730d87SJosef Bacik 	u64 left;
406507730d87SJosef Bacik 	int ret = 0;
406607730d87SJosef Bacik 
406707730d87SJosef Bacik 	/*
406807730d87SJosef Bacik 	 * Needed because we can end up allocating a system chunk and for an
406907730d87SJosef Bacik 	 * atomic and race free space reservation in the chunk block reserve.
407007730d87SJosef Bacik 	 */
407107730d87SJosef Bacik 	lockdep_assert_held(&fs_info->chunk_mutex);
407207730d87SJosef Bacik 
407307730d87SJosef Bacik 	info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
407407730d87SJosef Bacik 	spin_lock(&info->lock);
407507730d87SJosef Bacik 	left = info->total_bytes - btrfs_space_info_used(info, true);
407607730d87SJosef Bacik 	spin_unlock(&info->lock);
407707730d87SJosef Bacik 
40782bb2e00eSFilipe Manana 	if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
407907730d87SJosef Bacik 		btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
40802bb2e00eSFilipe Manana 			   left, bytes, type);
408107730d87SJosef Bacik 		btrfs_dump_space_info(fs_info, info, 0, 0);
408207730d87SJosef Bacik 	}
408307730d87SJosef Bacik 
40842bb2e00eSFilipe Manana 	if (left < bytes) {
408507730d87SJosef Bacik 		u64 flags = btrfs_system_alloc_profile(fs_info);
408679bd3712SFilipe Manana 		struct btrfs_block_group *bg;
408707730d87SJosef Bacik 
408807730d87SJosef Bacik 		/*
408907730d87SJosef Bacik 		 * Ignore failure to create system chunk. We might end up not
409007730d87SJosef Bacik 		 * needing it, as we might not need to COW all nodes/leafs from
409107730d87SJosef Bacik 		 * the paths we visit in the chunk tree (they were already COWed
409207730d87SJosef Bacik 		 * or created in the current transaction for example).
409307730d87SJosef Bacik 		 */
4094f6f39f7aSNikolay Borisov 		bg = btrfs_create_chunk(trans, flags);
409579bd3712SFilipe Manana 		if (IS_ERR(bg)) {
409679bd3712SFilipe Manana 			ret = PTR_ERR(bg);
40972bb2e00eSFilipe Manana 		} else {
409879bd3712SFilipe Manana 			/*
4099b6a98021SNaohiro Aota 			 * We have a new chunk. We also need to activate it for
4100b6a98021SNaohiro Aota 			 * zoned filesystem.
4101b6a98021SNaohiro Aota 			 */
4102b6a98021SNaohiro Aota 			ret = btrfs_zoned_activate_one_bg(fs_info, info, true);
4103b6a98021SNaohiro Aota 			if (ret < 0)
4104b6a98021SNaohiro Aota 				return;
4105b6a98021SNaohiro Aota 
4106b6a98021SNaohiro Aota 			/*
410779bd3712SFilipe Manana 			 * If we fail to add the chunk item here, we end up
410879bd3712SFilipe Manana 			 * trying again at phase 2 of chunk allocation, at
410979bd3712SFilipe Manana 			 * btrfs_create_pending_block_groups(). So ignore
41102bb2e00eSFilipe Manana 			 * any error here. An ENOSPC here could happen, due to
41112bb2e00eSFilipe Manana 			 * the cases described at do_chunk_alloc() - the system
41122bb2e00eSFilipe Manana 			 * block group we just created was just turned into RO
41132bb2e00eSFilipe Manana 			 * mode by a scrub for example, or a running discard
41142bb2e00eSFilipe Manana 			 * temporarily removed its free space entries, etc.
411579bd3712SFilipe Manana 			 */
411679bd3712SFilipe Manana 			btrfs_chunk_alloc_add_chunk_item(trans, bg);
411779bd3712SFilipe Manana 		}
411807730d87SJosef Bacik 	}
411907730d87SJosef Bacik 
412007730d87SJosef Bacik 	if (!ret) {
41219270501cSJosef Bacik 		ret = btrfs_block_rsv_add(fs_info,
412207730d87SJosef Bacik 					  &fs_info->chunk_block_rsv,
41232bb2e00eSFilipe Manana 					  bytes, BTRFS_RESERVE_NO_FLUSH);
41241cb3db1cSFilipe Manana 		if (!ret)
41252bb2e00eSFilipe Manana 			trans->chunk_bytes_reserved += bytes;
412607730d87SJosef Bacik 	}
412707730d87SJosef Bacik }
412807730d87SJosef Bacik 
41292bb2e00eSFilipe Manana /*
41302bb2e00eSFilipe Manana  * Reserve space in the system space for allocating or removing a chunk.
41312bb2e00eSFilipe Manana  * The caller must be holding fs_info->chunk_mutex.
41322bb2e00eSFilipe Manana  */
41332bb2e00eSFilipe Manana void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
41342bb2e00eSFilipe Manana {
41352bb2e00eSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
41362bb2e00eSFilipe Manana 	const u64 num_devs = get_profile_num_devs(fs_info, type);
41372bb2e00eSFilipe Manana 	u64 bytes;
41382bb2e00eSFilipe Manana 
41392bb2e00eSFilipe Manana 	/* num_devs device items to update and 1 chunk item to add or remove. */
41402bb2e00eSFilipe Manana 	bytes = btrfs_calc_metadata_size(fs_info, num_devs) +
41412bb2e00eSFilipe Manana 		btrfs_calc_insert_metadata_size(fs_info, 1);
41422bb2e00eSFilipe Manana 
41432bb2e00eSFilipe Manana 	reserve_chunk_space(trans, bytes, type);
41442bb2e00eSFilipe Manana }
41452bb2e00eSFilipe Manana 
41462bb2e00eSFilipe Manana /*
41472bb2e00eSFilipe Manana  * Reserve space in the system space, if needed, for doing a modification to the
41482bb2e00eSFilipe Manana  * chunk btree.
41492bb2e00eSFilipe Manana  *
41502bb2e00eSFilipe Manana  * @trans:		A transaction handle.
41512bb2e00eSFilipe Manana  * @is_item_insertion:	Indicate if the modification is for inserting a new item
41522bb2e00eSFilipe Manana  *			in the chunk btree or if it's for the deletion or update
41532bb2e00eSFilipe Manana  *			of an existing item.
41542bb2e00eSFilipe Manana  *
41552bb2e00eSFilipe Manana  * This is used in a context where we need to update the chunk btree outside
41562bb2e00eSFilipe Manana  * block group allocation and removal, to avoid a deadlock with a concurrent
41572bb2e00eSFilipe Manana  * task that is allocating a metadata or data block group and therefore needs to
41582bb2e00eSFilipe Manana  * update the chunk btree while holding the chunk mutex. After the update to the
41592bb2e00eSFilipe Manana  * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called.
41602bb2e00eSFilipe Manana  *
41612bb2e00eSFilipe Manana  */
41622bb2e00eSFilipe Manana void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans,
41632bb2e00eSFilipe Manana 				  bool is_item_insertion)
41642bb2e00eSFilipe Manana {
41652bb2e00eSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
41662bb2e00eSFilipe Manana 	u64 bytes;
41672bb2e00eSFilipe Manana 
41682bb2e00eSFilipe Manana 	if (is_item_insertion)
41692bb2e00eSFilipe Manana 		bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
41702bb2e00eSFilipe Manana 	else
41712bb2e00eSFilipe Manana 		bytes = btrfs_calc_metadata_size(fs_info, 1);
41722bb2e00eSFilipe Manana 
41732bb2e00eSFilipe Manana 	mutex_lock(&fs_info->chunk_mutex);
41742bb2e00eSFilipe Manana 	reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM);
41752bb2e00eSFilipe Manana 	mutex_unlock(&fs_info->chunk_mutex);
41762bb2e00eSFilipe Manana }
41772bb2e00eSFilipe Manana 
41783e43c279SJosef Bacik void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
41793e43c279SJosef Bacik {
418032da5386SDavid Sterba 	struct btrfs_block_group *block_group;
41813e43c279SJosef Bacik 
418250c31eaaSJosef Bacik 	block_group = btrfs_lookup_first_block_group(info, 0);
41833e43c279SJosef Bacik 	while (block_group) {
41843e43c279SJosef Bacik 		btrfs_wait_block_group_cache_done(block_group);
41853e43c279SJosef Bacik 		spin_lock(&block_group->lock);
418650c31eaaSJosef Bacik 		if (test_and_clear_bit(BLOCK_GROUP_FLAG_IREF,
418750c31eaaSJosef Bacik 				       &block_group->runtime_flags)) {
418850c31eaaSJosef Bacik 			struct inode *inode = block_group->inode;
41893e43c279SJosef Bacik 
41903e43c279SJosef Bacik 			block_group->inode = NULL;
41913e43c279SJosef Bacik 			spin_unlock(&block_group->lock);
419250c31eaaSJosef Bacik 
41933e43c279SJosef Bacik 			ASSERT(block_group->io_ctl.inode == NULL);
41943e43c279SJosef Bacik 			iput(inode);
419550c31eaaSJosef Bacik 		} else {
419650c31eaaSJosef Bacik 			spin_unlock(&block_group->lock);
419750c31eaaSJosef Bacik 		}
419850c31eaaSJosef Bacik 		block_group = btrfs_next_block_group(block_group);
41993e43c279SJosef Bacik 	}
42003e43c279SJosef Bacik }
42013e43c279SJosef Bacik 
42023e43c279SJosef Bacik /*
42033e43c279SJosef Bacik  * Must be called only after stopping all workers, since we could have block
42043e43c279SJosef Bacik  * group caching kthreads running, and therefore they could race with us if we
42053e43c279SJosef Bacik  * freed the block groups before stopping them.
42063e43c279SJosef Bacik  */
42073e43c279SJosef Bacik int btrfs_free_block_groups(struct btrfs_fs_info *info)
42083e43c279SJosef Bacik {
420932da5386SDavid Sterba 	struct btrfs_block_group *block_group;
42103e43c279SJosef Bacik 	struct btrfs_space_info *space_info;
42113e43c279SJosef Bacik 	struct btrfs_caching_control *caching_ctl;
42123e43c279SJosef Bacik 	struct rb_node *n;
42133e43c279SJosef Bacik 
421416b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
42153e43c279SJosef Bacik 	while (!list_empty(&info->caching_block_groups)) {
42163e43c279SJosef Bacik 		caching_ctl = list_entry(info->caching_block_groups.next,
42173e43c279SJosef Bacik 					 struct btrfs_caching_control, list);
42183e43c279SJosef Bacik 		list_del(&caching_ctl->list);
42193e43c279SJosef Bacik 		btrfs_put_caching_control(caching_ctl);
42203e43c279SJosef Bacik 	}
422116b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
42223e43c279SJosef Bacik 
42233e43c279SJosef Bacik 	spin_lock(&info->unused_bgs_lock);
42243e43c279SJosef Bacik 	while (!list_empty(&info->unused_bgs)) {
42253e43c279SJosef Bacik 		block_group = list_first_entry(&info->unused_bgs,
422632da5386SDavid Sterba 					       struct btrfs_block_group,
42273e43c279SJosef Bacik 					       bg_list);
42283e43c279SJosef Bacik 		list_del_init(&block_group->bg_list);
42293e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
42303e43c279SJosef Bacik 	}
42313e43c279SJosef Bacik 
423218bb8bbfSJohannes Thumshirn 	while (!list_empty(&info->reclaim_bgs)) {
423318bb8bbfSJohannes Thumshirn 		block_group = list_first_entry(&info->reclaim_bgs,
423418bb8bbfSJohannes Thumshirn 					       struct btrfs_block_group,
423518bb8bbfSJohannes Thumshirn 					       bg_list);
423618bb8bbfSJohannes Thumshirn 		list_del_init(&block_group->bg_list);
423718bb8bbfSJohannes Thumshirn 		btrfs_put_block_group(block_group);
423818bb8bbfSJohannes Thumshirn 	}
423918bb8bbfSJohannes Thumshirn 	spin_unlock(&info->unused_bgs_lock);
424018bb8bbfSJohannes Thumshirn 
4241afba2bc0SNaohiro Aota 	spin_lock(&info->zone_active_bgs_lock);
4242afba2bc0SNaohiro Aota 	while (!list_empty(&info->zone_active_bgs)) {
4243afba2bc0SNaohiro Aota 		block_group = list_first_entry(&info->zone_active_bgs,
4244afba2bc0SNaohiro Aota 					       struct btrfs_block_group,
4245afba2bc0SNaohiro Aota 					       active_bg_list);
4246afba2bc0SNaohiro Aota 		list_del_init(&block_group->active_bg_list);
4247afba2bc0SNaohiro Aota 		btrfs_put_block_group(block_group);
4248afba2bc0SNaohiro Aota 	}
4249afba2bc0SNaohiro Aota 	spin_unlock(&info->zone_active_bgs_lock);
4250afba2bc0SNaohiro Aota 
425116b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
425208dddb29SFilipe Manana 	while ((n = rb_last(&info->block_group_cache_tree.rb_root)) != NULL) {
425332da5386SDavid Sterba 		block_group = rb_entry(n, struct btrfs_block_group,
42543e43c279SJosef Bacik 				       cache_node);
425508dddb29SFilipe Manana 		rb_erase_cached(&block_group->cache_node,
42563e43c279SJosef Bacik 				&info->block_group_cache_tree);
42573e43c279SJosef Bacik 		RB_CLEAR_NODE(&block_group->cache_node);
425816b0c258SFilipe Manana 		write_unlock(&info->block_group_cache_lock);
42593e43c279SJosef Bacik 
42603e43c279SJosef Bacik 		down_write(&block_group->space_info->groups_sem);
42613e43c279SJosef Bacik 		list_del(&block_group->list);
42623e43c279SJosef Bacik 		up_write(&block_group->space_info->groups_sem);
42633e43c279SJosef Bacik 
42643e43c279SJosef Bacik 		/*
42653e43c279SJosef Bacik 		 * We haven't cached this block group, which means we could
42663e43c279SJosef Bacik 		 * possibly have excluded extents on this block group.
42673e43c279SJosef Bacik 		 */
42683e43c279SJosef Bacik 		if (block_group->cached == BTRFS_CACHE_NO ||
42693e43c279SJosef Bacik 		    block_group->cached == BTRFS_CACHE_ERROR)
42703e43c279SJosef Bacik 			btrfs_free_excluded_extents(block_group);
42713e43c279SJosef Bacik 
42723e43c279SJosef Bacik 		btrfs_remove_free_space_cache(block_group);
42733e43c279SJosef Bacik 		ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
42743e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->dirty_list));
42753e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->io_list));
42763e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->bg_list));
427748aaeebeSJosef Bacik 		ASSERT(refcount_read(&block_group->refs) == 1);
4278195a49eaSFilipe Manana 		ASSERT(block_group->swap_extents == 0);
42793e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
42803e43c279SJosef Bacik 
428116b0c258SFilipe Manana 		write_lock(&info->block_group_cache_lock);
42823e43c279SJosef Bacik 	}
428316b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
42843e43c279SJosef Bacik 
42853e43c279SJosef Bacik 	btrfs_release_global_block_rsv(info);
42863e43c279SJosef Bacik 
42873e43c279SJosef Bacik 	while (!list_empty(&info->space_info)) {
42883e43c279SJosef Bacik 		space_info = list_entry(info->space_info.next,
42893e43c279SJosef Bacik 					struct btrfs_space_info,
42903e43c279SJosef Bacik 					list);
42913e43c279SJosef Bacik 
42923e43c279SJosef Bacik 		/*
42933e43c279SJosef Bacik 		 * Do not hide this behind enospc_debug, this is actually
42943e43c279SJosef Bacik 		 * important and indicates a real bug if this happens.
42953e43c279SJosef Bacik 		 */
42963e43c279SJosef Bacik 		if (WARN_ON(space_info->bytes_pinned > 0 ||
42973e43c279SJosef Bacik 			    space_info->bytes_may_use > 0))
42983e43c279SJosef Bacik 			btrfs_dump_space_info(info, space_info, 0, 0);
429940cdc509SFilipe Manana 
430040cdc509SFilipe Manana 		/*
430140cdc509SFilipe Manana 		 * If there was a failure to cleanup a log tree, very likely due
430240cdc509SFilipe Manana 		 * to an IO failure on a writeback attempt of one or more of its
430340cdc509SFilipe Manana 		 * extent buffers, we could not do proper (and cheap) unaccounting
430440cdc509SFilipe Manana 		 * of their reserved space, so don't warn on bytes_reserved > 0 in
430540cdc509SFilipe Manana 		 * that case.
430640cdc509SFilipe Manana 		 */
430740cdc509SFilipe Manana 		if (!(space_info->flags & BTRFS_BLOCK_GROUP_METADATA) ||
430840cdc509SFilipe Manana 		    !BTRFS_FS_LOG_CLEANUP_ERROR(info)) {
430940cdc509SFilipe Manana 			if (WARN_ON(space_info->bytes_reserved > 0))
431040cdc509SFilipe Manana 				btrfs_dump_space_info(info, space_info, 0, 0);
431140cdc509SFilipe Manana 		}
431240cdc509SFilipe Manana 
4313d611add4SFilipe Manana 		WARN_ON(space_info->reclaim_size > 0);
43143e43c279SJosef Bacik 		list_del(&space_info->list);
43153e43c279SJosef Bacik 		btrfs_sysfs_remove_space_info(space_info);
43163e43c279SJosef Bacik 	}
43173e43c279SJosef Bacik 	return 0;
43183e43c279SJosef Bacik }
4319684b752bSFilipe Manana 
4320684b752bSFilipe Manana void btrfs_freeze_block_group(struct btrfs_block_group *cache)
4321684b752bSFilipe Manana {
4322684b752bSFilipe Manana 	atomic_inc(&cache->frozen);
4323684b752bSFilipe Manana }
4324684b752bSFilipe Manana 
4325684b752bSFilipe Manana void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
4326684b752bSFilipe Manana {
4327684b752bSFilipe Manana 	struct btrfs_fs_info *fs_info = block_group->fs_info;
4328684b752bSFilipe Manana 	struct extent_map_tree *em_tree;
4329684b752bSFilipe Manana 	struct extent_map *em;
4330684b752bSFilipe Manana 	bool cleanup;
4331684b752bSFilipe Manana 
4332684b752bSFilipe Manana 	spin_lock(&block_group->lock);
4333684b752bSFilipe Manana 	cleanup = (atomic_dec_and_test(&block_group->frozen) &&
43343349b57fSJosef Bacik 		   test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags));
4335684b752bSFilipe Manana 	spin_unlock(&block_group->lock);
4336684b752bSFilipe Manana 
4337684b752bSFilipe Manana 	if (cleanup) {
4338684b752bSFilipe Manana 		em_tree = &fs_info->mapping_tree;
4339684b752bSFilipe Manana 		write_lock(&em_tree->lock);
4340684b752bSFilipe Manana 		em = lookup_extent_mapping(em_tree, block_group->start,
4341684b752bSFilipe Manana 					   1);
4342684b752bSFilipe Manana 		BUG_ON(!em); /* logic error, can't happen */
4343684b752bSFilipe Manana 		remove_extent_mapping(em_tree, em);
4344684b752bSFilipe Manana 		write_unlock(&em_tree->lock);
4345684b752bSFilipe Manana 
4346684b752bSFilipe Manana 		/* once for us and once for the tree */
4347684b752bSFilipe Manana 		free_extent_map(em);
4348684b752bSFilipe Manana 		free_extent_map(em);
4349684b752bSFilipe Manana 
4350684b752bSFilipe Manana 		/*
4351684b752bSFilipe Manana 		 * We may have left one free space entry and other possible
4352684b752bSFilipe Manana 		 * tasks trimming this block group have left 1 entry each one.
4353684b752bSFilipe Manana 		 * Free them if any.
4354684b752bSFilipe Manana 		 */
4355fc80f7acSJosef Bacik 		btrfs_remove_free_space_cache(block_group);
4356684b752bSFilipe Manana 	}
4357684b752bSFilipe Manana }
4358195a49eaSFilipe Manana 
4359195a49eaSFilipe Manana bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
4360195a49eaSFilipe Manana {
4361195a49eaSFilipe Manana 	bool ret = true;
4362195a49eaSFilipe Manana 
4363195a49eaSFilipe Manana 	spin_lock(&bg->lock);
4364195a49eaSFilipe Manana 	if (bg->ro)
4365195a49eaSFilipe Manana 		ret = false;
4366195a49eaSFilipe Manana 	else
4367195a49eaSFilipe Manana 		bg->swap_extents++;
4368195a49eaSFilipe Manana 	spin_unlock(&bg->lock);
4369195a49eaSFilipe Manana 
4370195a49eaSFilipe Manana 	return ret;
4371195a49eaSFilipe Manana }
4372195a49eaSFilipe Manana 
4373195a49eaSFilipe Manana void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
4374195a49eaSFilipe Manana {
4375195a49eaSFilipe Manana 	spin_lock(&bg->lock);
4376195a49eaSFilipe Manana 	ASSERT(!bg->ro);
4377195a49eaSFilipe Manana 	ASSERT(bg->swap_extents >= amount);
4378195a49eaSFilipe Manana 	bg->swap_extents -= amount;
4379195a49eaSFilipe Manana 	spin_unlock(&bg->lock);
4380195a49eaSFilipe Manana }
438152bb7a21SBoris Burkov 
438252bb7a21SBoris Burkov enum btrfs_block_group_size_class btrfs_calc_block_group_size_class(u64 size)
438352bb7a21SBoris Burkov {
438452bb7a21SBoris Burkov 	if (size <= SZ_128K)
438552bb7a21SBoris Burkov 		return BTRFS_BG_SZ_SMALL;
438652bb7a21SBoris Burkov 	if (size <= SZ_8M)
438752bb7a21SBoris Burkov 		return BTRFS_BG_SZ_MEDIUM;
438852bb7a21SBoris Burkov 	return BTRFS_BG_SZ_LARGE;
438952bb7a21SBoris Burkov }
439052bb7a21SBoris Burkov 
439152bb7a21SBoris Burkov /*
439252bb7a21SBoris Burkov  * Handle a block group allocating an extent in a size class
439352bb7a21SBoris Burkov  *
439452bb7a21SBoris Burkov  * @bg:				The block group we allocated in.
439552bb7a21SBoris Burkov  * @size_class:			The size class of the allocation.
439652bb7a21SBoris Burkov  * @force_wrong_size_class:	Whether we are desperate enough to allow
439752bb7a21SBoris Burkov  *				mismatched size classes.
439852bb7a21SBoris Burkov  *
439952bb7a21SBoris Burkov  * Returns: 0 if the size class was valid for this block_group, -EAGAIN in the
440052bb7a21SBoris Burkov  * case of a race that leads to the wrong size class without
440152bb7a21SBoris Burkov  * force_wrong_size_class set.
440252bb7a21SBoris Burkov  *
440352bb7a21SBoris Burkov  * find_free_extent will skip block groups with a mismatched size class until
440452bb7a21SBoris Burkov  * it really needs to avoid ENOSPC. In that case it will set
440552bb7a21SBoris Burkov  * force_wrong_size_class. However, if a block group is newly allocated and
440652bb7a21SBoris Burkov  * doesn't yet have a size class, then it is possible for two allocations of
440752bb7a21SBoris Burkov  * different sizes to race and both try to use it. The loser is caught here and
440852bb7a21SBoris Burkov  * has to retry.
440952bb7a21SBoris Burkov  */
441052bb7a21SBoris Burkov int btrfs_use_block_group_size_class(struct btrfs_block_group *bg,
441152bb7a21SBoris Burkov 				     enum btrfs_block_group_size_class size_class,
441252bb7a21SBoris Burkov 				     bool force_wrong_size_class)
441352bb7a21SBoris Burkov {
441452bb7a21SBoris Burkov 	ASSERT(size_class != BTRFS_BG_SZ_NONE);
441552bb7a21SBoris Burkov 
441652bb7a21SBoris Burkov 	/* The new allocation is in the right size class, do nothing */
441752bb7a21SBoris Burkov 	if (bg->size_class == size_class)
441852bb7a21SBoris Burkov 		return 0;
441952bb7a21SBoris Burkov 	/*
442052bb7a21SBoris Burkov 	 * The new allocation is in a mismatched size class.
442152bb7a21SBoris Burkov 	 * This means one of two things:
442252bb7a21SBoris Burkov 	 *
442352bb7a21SBoris Burkov 	 * 1. Two tasks in find_free_extent for different size_classes raced
442452bb7a21SBoris Burkov 	 *    and hit the same empty block_group. Make the loser try again.
442552bb7a21SBoris Burkov 	 * 2. A call to find_free_extent got desperate enough to set
442652bb7a21SBoris Burkov 	 *    'force_wrong_slab'. Don't change the size_class, but allow the
442752bb7a21SBoris Burkov 	 *    allocation.
442852bb7a21SBoris Burkov 	 */
442952bb7a21SBoris Burkov 	if (bg->size_class != BTRFS_BG_SZ_NONE) {
443052bb7a21SBoris Burkov 		if (force_wrong_size_class)
443152bb7a21SBoris Burkov 			return 0;
443252bb7a21SBoris Burkov 		return -EAGAIN;
443352bb7a21SBoris Burkov 	}
443452bb7a21SBoris Burkov 	/*
443552bb7a21SBoris Burkov 	 * The happy new block group case: the new allocation is the first
443652bb7a21SBoris Burkov 	 * one in the block_group so we set size_class.
443752bb7a21SBoris Burkov 	 */
443852bb7a21SBoris Burkov 	bg->size_class = size_class;
443952bb7a21SBoris Burkov 
444052bb7a21SBoris Burkov 	return 0;
444152bb7a21SBoris Burkov }
4442