xref: /linux/fs/btrfs/block-group.c (revision 5758d1bd2d320467e6d539dd693ff2b4dc07f345)
12e405ad8SJosef Bacik // SPDX-License-Identifier: GPL-2.0
22e405ad8SJosef Bacik 
352bb7a21SBoris Burkov #include <linux/sizes.h>
42ca0ec77SJohannes Thumshirn #include <linux/list_sort.h>
5784352feSDavid Sterba #include "misc.h"
62e405ad8SJosef Bacik #include "ctree.h"
72e405ad8SJosef Bacik #include "block-group.h"
83eeb3226SJosef Bacik #include "space-info.h"
99f21246dSJosef Bacik #include "disk-io.h"
109f21246dSJosef Bacik #include "free-space-cache.h"
119f21246dSJosef Bacik #include "free-space-tree.h"
12e3e0520bSJosef Bacik #include "volumes.h"
13e3e0520bSJosef Bacik #include "transaction.h"
14e3e0520bSJosef Bacik #include "ref-verify.h"
154358d963SJosef Bacik #include "sysfs.h"
164358d963SJosef Bacik #include "tree-log.h"
1777745c05SJosef Bacik #include "delalloc-space.h"
18b0643e59SDennis Zhou #include "discard.h"
1996a14336SNikolay Borisov #include "raid56.h"
2008e11a3dSNaohiro Aota #include "zoned.h"
21c7f13d42SJosef Bacik #include "fs.h"
2207e81dc9SJosef Bacik #include "accessors.h"
23a0231804SJosef Bacik #include "extent-tree.h"
242e405ad8SJosef Bacik 
2506d61cb1SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2606d61cb1SJosef Bacik int btrfs_should_fragment_free_space(struct btrfs_block_group *block_group)
2706d61cb1SJosef Bacik {
2806d61cb1SJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
2906d61cb1SJosef Bacik 
3006d61cb1SJosef Bacik 	return (btrfs_test_opt(fs_info, FRAGMENT_METADATA) &&
3106d61cb1SJosef Bacik 		block_group->flags & BTRFS_BLOCK_GROUP_METADATA) ||
3206d61cb1SJosef Bacik 	       (btrfs_test_opt(fs_info, FRAGMENT_DATA) &&
3306d61cb1SJosef Bacik 		block_group->flags &  BTRFS_BLOCK_GROUP_DATA);
3406d61cb1SJosef Bacik }
3506d61cb1SJosef Bacik #endif
3606d61cb1SJosef Bacik 
37878d7b67SJosef Bacik /*
38878d7b67SJosef Bacik  * Return target flags in extended format or 0 if restripe for this chunk_type
39878d7b67SJosef Bacik  * is not in progress
40878d7b67SJosef Bacik  *
41878d7b67SJosef Bacik  * Should be called with balance_lock held
42878d7b67SJosef Bacik  */
43e11c0406SJosef Bacik static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
44878d7b67SJosef Bacik {
45878d7b67SJosef Bacik 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
46878d7b67SJosef Bacik 	u64 target = 0;
47878d7b67SJosef Bacik 
48878d7b67SJosef Bacik 	if (!bctl)
49878d7b67SJosef Bacik 		return 0;
50878d7b67SJosef Bacik 
51878d7b67SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA &&
52878d7b67SJosef Bacik 	    bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
53878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
54878d7b67SJosef Bacik 	} else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
55878d7b67SJosef Bacik 		   bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
56878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
57878d7b67SJosef Bacik 	} else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
58878d7b67SJosef Bacik 		   bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
59878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
60878d7b67SJosef Bacik 	}
61878d7b67SJosef Bacik 
62878d7b67SJosef Bacik 	return target;
63878d7b67SJosef Bacik }
64878d7b67SJosef Bacik 
65878d7b67SJosef Bacik /*
66878d7b67SJosef Bacik  * @flags: available profiles in extended format (see ctree.h)
67878d7b67SJosef Bacik  *
68878d7b67SJosef Bacik  * Return reduced profile in chunk format.  If profile changing is in progress
69878d7b67SJosef Bacik  * (either running or paused) picks the target profile (if it's already
70878d7b67SJosef Bacik  * available), otherwise falls back to plain reducing.
71878d7b67SJosef Bacik  */
72878d7b67SJosef Bacik static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
73878d7b67SJosef Bacik {
74878d7b67SJosef Bacik 	u64 num_devices = fs_info->fs_devices->rw_devices;
75878d7b67SJosef Bacik 	u64 target;
76878d7b67SJosef Bacik 	u64 raid_type;
77878d7b67SJosef Bacik 	u64 allowed = 0;
78878d7b67SJosef Bacik 
79878d7b67SJosef Bacik 	/*
80878d7b67SJosef Bacik 	 * See if restripe for this chunk_type is in progress, if so try to
81878d7b67SJosef Bacik 	 * reduce to the target profile
82878d7b67SJosef Bacik 	 */
83878d7b67SJosef Bacik 	spin_lock(&fs_info->balance_lock);
84e11c0406SJosef Bacik 	target = get_restripe_target(fs_info, flags);
85878d7b67SJosef Bacik 	if (target) {
86878d7b67SJosef Bacik 		spin_unlock(&fs_info->balance_lock);
87878d7b67SJosef Bacik 		return extended_to_chunk(target);
88878d7b67SJosef Bacik 	}
89878d7b67SJosef Bacik 	spin_unlock(&fs_info->balance_lock);
90878d7b67SJosef Bacik 
91878d7b67SJosef Bacik 	/* First, mask out the RAID levels which aren't possible */
92878d7b67SJosef Bacik 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
93878d7b67SJosef Bacik 		if (num_devices >= btrfs_raid_array[raid_type].devs_min)
94878d7b67SJosef Bacik 			allowed |= btrfs_raid_array[raid_type].bg_flag;
95878d7b67SJosef Bacik 	}
96878d7b67SJosef Bacik 	allowed &= flags;
97878d7b67SJosef Bacik 
98878d7b67SJosef Bacik 	if (allowed & BTRFS_BLOCK_GROUP_RAID6)
99878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID6;
100878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
101878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID5;
102878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
103878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID10;
104878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
105878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID1;
106878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
107878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID0;
108878d7b67SJosef Bacik 
109878d7b67SJosef Bacik 	flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
110878d7b67SJosef Bacik 
111878d7b67SJosef Bacik 	return extended_to_chunk(flags | allowed);
112878d7b67SJosef Bacik }
113878d7b67SJosef Bacik 
114ef0a82daSJohannes Thumshirn u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
115878d7b67SJosef Bacik {
116878d7b67SJosef Bacik 	unsigned seq;
117878d7b67SJosef Bacik 	u64 flags;
118878d7b67SJosef Bacik 
119878d7b67SJosef Bacik 	do {
120878d7b67SJosef Bacik 		flags = orig_flags;
121878d7b67SJosef Bacik 		seq = read_seqbegin(&fs_info->profiles_lock);
122878d7b67SJosef Bacik 
123878d7b67SJosef Bacik 		if (flags & BTRFS_BLOCK_GROUP_DATA)
124878d7b67SJosef Bacik 			flags |= fs_info->avail_data_alloc_bits;
125878d7b67SJosef Bacik 		else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
126878d7b67SJosef Bacik 			flags |= fs_info->avail_system_alloc_bits;
127878d7b67SJosef Bacik 		else if (flags & BTRFS_BLOCK_GROUP_METADATA)
128878d7b67SJosef Bacik 			flags |= fs_info->avail_metadata_alloc_bits;
129878d7b67SJosef Bacik 	} while (read_seqretry(&fs_info->profiles_lock, seq));
130878d7b67SJosef Bacik 
131878d7b67SJosef Bacik 	return btrfs_reduce_alloc_profile(fs_info, flags);
132878d7b67SJosef Bacik }
133878d7b67SJosef Bacik 
13432da5386SDavid Sterba void btrfs_get_block_group(struct btrfs_block_group *cache)
1353cad1284SJosef Bacik {
13648aaeebeSJosef Bacik 	refcount_inc(&cache->refs);
1373cad1284SJosef Bacik }
1383cad1284SJosef Bacik 
13932da5386SDavid Sterba void btrfs_put_block_group(struct btrfs_block_group *cache)
1403cad1284SJosef Bacik {
14148aaeebeSJosef Bacik 	if (refcount_dec_and_test(&cache->refs)) {
1423cad1284SJosef Bacik 		WARN_ON(cache->pinned > 0);
14340cdc509SFilipe Manana 		/*
14440cdc509SFilipe Manana 		 * If there was a failure to cleanup a log tree, very likely due
14540cdc509SFilipe Manana 		 * to an IO failure on a writeback attempt of one or more of its
14640cdc509SFilipe Manana 		 * extent buffers, we could not do proper (and cheap) unaccounting
14740cdc509SFilipe Manana 		 * of their reserved space, so don't warn on reserved > 0 in that
14840cdc509SFilipe Manana 		 * case.
14940cdc509SFilipe Manana 		 */
15040cdc509SFilipe Manana 		if (!(cache->flags & BTRFS_BLOCK_GROUP_METADATA) ||
15140cdc509SFilipe Manana 		    !BTRFS_FS_LOG_CLEANUP_ERROR(cache->fs_info))
1523cad1284SJosef Bacik 			WARN_ON(cache->reserved > 0);
1533cad1284SJosef Bacik 
1543cad1284SJosef Bacik 		/*
155b0643e59SDennis Zhou 		 * A block_group shouldn't be on the discard_list anymore.
156b0643e59SDennis Zhou 		 * Remove the block_group from the discard_list to prevent us
157b0643e59SDennis Zhou 		 * from causing a panic due to NULL pointer dereference.
158b0643e59SDennis Zhou 		 */
159b0643e59SDennis Zhou 		if (WARN_ON(!list_empty(&cache->discard_list)))
160b0643e59SDennis Zhou 			btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
161b0643e59SDennis Zhou 						  cache);
162b0643e59SDennis Zhou 
163b0643e59SDennis Zhou 		/*
1643cad1284SJosef Bacik 		 * If not empty, someone is still holding mutex of
1653cad1284SJosef Bacik 		 * full_stripe_lock, which can only be released by caller.
1663cad1284SJosef Bacik 		 * And it will definitely cause use-after-free when caller
1673cad1284SJosef Bacik 		 * tries to release full stripe lock.
1683cad1284SJosef Bacik 		 *
1693cad1284SJosef Bacik 		 * No better way to resolve, but only to warn.
1703cad1284SJosef Bacik 		 */
1713cad1284SJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
1723cad1284SJosef Bacik 		kfree(cache->free_space_ctl);
173dafc340dSNaohiro Aota 		kfree(cache->physical_map);
1743cad1284SJosef Bacik 		kfree(cache);
1753cad1284SJosef Bacik 	}
1763cad1284SJosef Bacik }
1773cad1284SJosef Bacik 
1782e405ad8SJosef Bacik /*
1794358d963SJosef Bacik  * This adds the block group to the fs_info rb tree for the block group cache
1804358d963SJosef Bacik  */
1814358d963SJosef Bacik static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
18232da5386SDavid Sterba 				       struct btrfs_block_group *block_group)
1834358d963SJosef Bacik {
1844358d963SJosef Bacik 	struct rb_node **p;
1854358d963SJosef Bacik 	struct rb_node *parent = NULL;
18632da5386SDavid Sterba 	struct btrfs_block_group *cache;
18708dddb29SFilipe Manana 	bool leftmost = true;
1884358d963SJosef Bacik 
1899afc6649SQu Wenruo 	ASSERT(block_group->length != 0);
1909afc6649SQu Wenruo 
19116b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
19208dddb29SFilipe Manana 	p = &info->block_group_cache_tree.rb_root.rb_node;
1934358d963SJosef Bacik 
1944358d963SJosef Bacik 	while (*p) {
1954358d963SJosef Bacik 		parent = *p;
19632da5386SDavid Sterba 		cache = rb_entry(parent, struct btrfs_block_group, cache_node);
197b3470b5dSDavid Sterba 		if (block_group->start < cache->start) {
1984358d963SJosef Bacik 			p = &(*p)->rb_left;
199b3470b5dSDavid Sterba 		} else if (block_group->start > cache->start) {
2004358d963SJosef Bacik 			p = &(*p)->rb_right;
20108dddb29SFilipe Manana 			leftmost = false;
2024358d963SJosef Bacik 		} else {
20316b0c258SFilipe Manana 			write_unlock(&info->block_group_cache_lock);
2044358d963SJosef Bacik 			return -EEXIST;
2054358d963SJosef Bacik 		}
2064358d963SJosef Bacik 	}
2074358d963SJosef Bacik 
2084358d963SJosef Bacik 	rb_link_node(&block_group->cache_node, parent, p);
20908dddb29SFilipe Manana 	rb_insert_color_cached(&block_group->cache_node,
21008dddb29SFilipe Manana 			       &info->block_group_cache_tree, leftmost);
2114358d963SJosef Bacik 
21216b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
2134358d963SJosef Bacik 
2144358d963SJosef Bacik 	return 0;
2154358d963SJosef Bacik }
2164358d963SJosef Bacik 
2174358d963SJosef Bacik /*
2182e405ad8SJosef Bacik  * This will return the block group at or after bytenr if contains is 0, else
2192e405ad8SJosef Bacik  * it will return the block group that contains the bytenr
2202e405ad8SJosef Bacik  */
22132da5386SDavid Sterba static struct btrfs_block_group *block_group_cache_tree_search(
2222e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr, int contains)
2232e405ad8SJosef Bacik {
22432da5386SDavid Sterba 	struct btrfs_block_group *cache, *ret = NULL;
2252e405ad8SJosef Bacik 	struct rb_node *n;
2262e405ad8SJosef Bacik 	u64 end, start;
2272e405ad8SJosef Bacik 
22816b0c258SFilipe Manana 	read_lock(&info->block_group_cache_lock);
22908dddb29SFilipe Manana 	n = info->block_group_cache_tree.rb_root.rb_node;
2302e405ad8SJosef Bacik 
2312e405ad8SJosef Bacik 	while (n) {
23232da5386SDavid Sterba 		cache = rb_entry(n, struct btrfs_block_group, cache_node);
233b3470b5dSDavid Sterba 		end = cache->start + cache->length - 1;
234b3470b5dSDavid Sterba 		start = cache->start;
2352e405ad8SJosef Bacik 
2362e405ad8SJosef Bacik 		if (bytenr < start) {
237b3470b5dSDavid Sterba 			if (!contains && (!ret || start < ret->start))
2382e405ad8SJosef Bacik 				ret = cache;
2392e405ad8SJosef Bacik 			n = n->rb_left;
2402e405ad8SJosef Bacik 		} else if (bytenr > start) {
2412e405ad8SJosef Bacik 			if (contains && bytenr <= end) {
2422e405ad8SJosef Bacik 				ret = cache;
2432e405ad8SJosef Bacik 				break;
2442e405ad8SJosef Bacik 			}
2452e405ad8SJosef Bacik 			n = n->rb_right;
2462e405ad8SJosef Bacik 		} else {
2472e405ad8SJosef Bacik 			ret = cache;
2482e405ad8SJosef Bacik 			break;
2492e405ad8SJosef Bacik 		}
2502e405ad8SJosef Bacik 	}
25108dddb29SFilipe Manana 	if (ret)
2522e405ad8SJosef Bacik 		btrfs_get_block_group(ret);
25316b0c258SFilipe Manana 	read_unlock(&info->block_group_cache_lock);
2542e405ad8SJosef Bacik 
2552e405ad8SJosef Bacik 	return ret;
2562e405ad8SJosef Bacik }
2572e405ad8SJosef Bacik 
2582e405ad8SJosef Bacik /*
2592e405ad8SJosef Bacik  * Return the block group that starts at or after bytenr
2602e405ad8SJosef Bacik  */
26132da5386SDavid Sterba struct btrfs_block_group *btrfs_lookup_first_block_group(
2622e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr)
2632e405ad8SJosef Bacik {
2642e405ad8SJosef Bacik 	return block_group_cache_tree_search(info, bytenr, 0);
2652e405ad8SJosef Bacik }
2662e405ad8SJosef Bacik 
2672e405ad8SJosef Bacik /*
2682e405ad8SJosef Bacik  * Return the block group that contains the given bytenr
2692e405ad8SJosef Bacik  */
27032da5386SDavid Sterba struct btrfs_block_group *btrfs_lookup_block_group(
2712e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr)
2722e405ad8SJosef Bacik {
2732e405ad8SJosef Bacik 	return block_group_cache_tree_search(info, bytenr, 1);
2742e405ad8SJosef Bacik }
2752e405ad8SJosef Bacik 
27632da5386SDavid Sterba struct btrfs_block_group *btrfs_next_block_group(
27732da5386SDavid Sterba 		struct btrfs_block_group *cache)
2782e405ad8SJosef Bacik {
2792e405ad8SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
2802e405ad8SJosef Bacik 	struct rb_node *node;
2812e405ad8SJosef Bacik 
28216b0c258SFilipe Manana 	read_lock(&fs_info->block_group_cache_lock);
2832e405ad8SJosef Bacik 
2842e405ad8SJosef Bacik 	/* If our block group was removed, we need a full search. */
2852e405ad8SJosef Bacik 	if (RB_EMPTY_NODE(&cache->cache_node)) {
286b3470b5dSDavid Sterba 		const u64 next_bytenr = cache->start + cache->length;
2872e405ad8SJosef Bacik 
28816b0c258SFilipe Manana 		read_unlock(&fs_info->block_group_cache_lock);
2892e405ad8SJosef Bacik 		btrfs_put_block_group(cache);
2908b01f931SFilipe Manana 		return btrfs_lookup_first_block_group(fs_info, next_bytenr);
2912e405ad8SJosef Bacik 	}
2922e405ad8SJosef Bacik 	node = rb_next(&cache->cache_node);
2932e405ad8SJosef Bacik 	btrfs_put_block_group(cache);
2942e405ad8SJosef Bacik 	if (node) {
29532da5386SDavid Sterba 		cache = rb_entry(node, struct btrfs_block_group, cache_node);
2962e405ad8SJosef Bacik 		btrfs_get_block_group(cache);
2972e405ad8SJosef Bacik 	} else
2982e405ad8SJosef Bacik 		cache = NULL;
29916b0c258SFilipe Manana 	read_unlock(&fs_info->block_group_cache_lock);
3002e405ad8SJosef Bacik 	return cache;
3012e405ad8SJosef Bacik }
3023eeb3226SJosef Bacik 
30343dd529aSDavid Sterba /*
3042306e83eSFilipe Manana  * Check if we can do a NOCOW write for a given extent.
3052306e83eSFilipe Manana  *
3062306e83eSFilipe Manana  * @fs_info:       The filesystem information object.
3072306e83eSFilipe Manana  * @bytenr:        Logical start address of the extent.
3082306e83eSFilipe Manana  *
3092306e83eSFilipe Manana  * Check if we can do a NOCOW write for the given extent, and increments the
3102306e83eSFilipe Manana  * number of NOCOW writers in the block group that contains the extent, as long
3112306e83eSFilipe Manana  * as the block group exists and it's currently not in read-only mode.
3122306e83eSFilipe Manana  *
3132306e83eSFilipe Manana  * Returns: A non-NULL block group pointer if we can do a NOCOW write, the caller
3142306e83eSFilipe Manana  *          is responsible for calling btrfs_dec_nocow_writers() later.
3152306e83eSFilipe Manana  *
3162306e83eSFilipe Manana  *          Or NULL if we can not do a NOCOW write
3172306e83eSFilipe Manana  */
3182306e83eSFilipe Manana struct btrfs_block_group *btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info,
3192306e83eSFilipe Manana 						  u64 bytenr)
3203eeb3226SJosef Bacik {
32132da5386SDavid Sterba 	struct btrfs_block_group *bg;
3222306e83eSFilipe Manana 	bool can_nocow = true;
3233eeb3226SJosef Bacik 
3243eeb3226SJosef Bacik 	bg = btrfs_lookup_block_group(fs_info, bytenr);
3253eeb3226SJosef Bacik 	if (!bg)
3262306e83eSFilipe Manana 		return NULL;
3273eeb3226SJosef Bacik 
3283eeb3226SJosef Bacik 	spin_lock(&bg->lock);
3293eeb3226SJosef Bacik 	if (bg->ro)
3302306e83eSFilipe Manana 		can_nocow = false;
3313eeb3226SJosef Bacik 	else
3323eeb3226SJosef Bacik 		atomic_inc(&bg->nocow_writers);
3333eeb3226SJosef Bacik 	spin_unlock(&bg->lock);
3343eeb3226SJosef Bacik 
3352306e83eSFilipe Manana 	if (!can_nocow) {
3363eeb3226SJosef Bacik 		btrfs_put_block_group(bg);
3372306e83eSFilipe Manana 		return NULL;
3383eeb3226SJosef Bacik 	}
3393eeb3226SJosef Bacik 
3402306e83eSFilipe Manana 	/* No put on block group, done by btrfs_dec_nocow_writers(). */
3412306e83eSFilipe Manana 	return bg;
3422306e83eSFilipe Manana }
3433eeb3226SJosef Bacik 
34443dd529aSDavid Sterba /*
3452306e83eSFilipe Manana  * Decrement the number of NOCOW writers in a block group.
3462306e83eSFilipe Manana  *
3472306e83eSFilipe Manana  * This is meant to be called after a previous call to btrfs_inc_nocow_writers(),
3482306e83eSFilipe Manana  * and on the block group returned by that call. Typically this is called after
3492306e83eSFilipe Manana  * creating an ordered extent for a NOCOW write, to prevent races with scrub and
3502306e83eSFilipe Manana  * relocation.
3512306e83eSFilipe Manana  *
3522306e83eSFilipe Manana  * After this call, the caller should not use the block group anymore. It it wants
3532306e83eSFilipe Manana  * to use it, then it should get a reference on it before calling this function.
3542306e83eSFilipe Manana  */
3552306e83eSFilipe Manana void btrfs_dec_nocow_writers(struct btrfs_block_group *bg)
3562306e83eSFilipe Manana {
3573eeb3226SJosef Bacik 	if (atomic_dec_and_test(&bg->nocow_writers))
3583eeb3226SJosef Bacik 		wake_up_var(&bg->nocow_writers);
3592306e83eSFilipe Manana 
3602306e83eSFilipe Manana 	/* For the lookup done by a previous call to btrfs_inc_nocow_writers(). */
3613eeb3226SJosef Bacik 	btrfs_put_block_group(bg);
3623eeb3226SJosef Bacik }
3633eeb3226SJosef Bacik 
36432da5386SDavid Sterba void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
3653eeb3226SJosef Bacik {
3663eeb3226SJosef Bacik 	wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
3673eeb3226SJosef Bacik }
3683eeb3226SJosef Bacik 
3693eeb3226SJosef Bacik void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
3703eeb3226SJosef Bacik 					const u64 start)
3713eeb3226SJosef Bacik {
37232da5386SDavid Sterba 	struct btrfs_block_group *bg;
3733eeb3226SJosef Bacik 
3743eeb3226SJosef Bacik 	bg = btrfs_lookup_block_group(fs_info, start);
3753eeb3226SJosef Bacik 	ASSERT(bg);
3763eeb3226SJosef Bacik 	if (atomic_dec_and_test(&bg->reservations))
3773eeb3226SJosef Bacik 		wake_up_var(&bg->reservations);
3783eeb3226SJosef Bacik 	btrfs_put_block_group(bg);
3793eeb3226SJosef Bacik }
3803eeb3226SJosef Bacik 
38132da5386SDavid Sterba void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
3823eeb3226SJosef Bacik {
3833eeb3226SJosef Bacik 	struct btrfs_space_info *space_info = bg->space_info;
3843eeb3226SJosef Bacik 
3853eeb3226SJosef Bacik 	ASSERT(bg->ro);
3863eeb3226SJosef Bacik 
3873eeb3226SJosef Bacik 	if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
3883eeb3226SJosef Bacik 		return;
3893eeb3226SJosef Bacik 
3903eeb3226SJosef Bacik 	/*
3913eeb3226SJosef Bacik 	 * Our block group is read only but before we set it to read only,
3923eeb3226SJosef Bacik 	 * some task might have had allocated an extent from it already, but it
3933eeb3226SJosef Bacik 	 * has not yet created a respective ordered extent (and added it to a
3943eeb3226SJosef Bacik 	 * root's list of ordered extents).
3953eeb3226SJosef Bacik 	 * Therefore wait for any task currently allocating extents, since the
3963eeb3226SJosef Bacik 	 * block group's reservations counter is incremented while a read lock
3973eeb3226SJosef Bacik 	 * on the groups' semaphore is held and decremented after releasing
3983eeb3226SJosef Bacik 	 * the read access on that semaphore and creating the ordered extent.
3993eeb3226SJosef Bacik 	 */
4003eeb3226SJosef Bacik 	down_write(&space_info->groups_sem);
4013eeb3226SJosef Bacik 	up_write(&space_info->groups_sem);
4023eeb3226SJosef Bacik 
4033eeb3226SJosef Bacik 	wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
4043eeb3226SJosef Bacik }
4059f21246dSJosef Bacik 
4069f21246dSJosef Bacik struct btrfs_caching_control *btrfs_get_caching_control(
40732da5386SDavid Sterba 		struct btrfs_block_group *cache)
4089f21246dSJosef Bacik {
4099f21246dSJosef Bacik 	struct btrfs_caching_control *ctl;
4109f21246dSJosef Bacik 
4119f21246dSJosef Bacik 	spin_lock(&cache->lock);
4129f21246dSJosef Bacik 	if (!cache->caching_ctl) {
4139f21246dSJosef Bacik 		spin_unlock(&cache->lock);
4149f21246dSJosef Bacik 		return NULL;
4159f21246dSJosef Bacik 	}
4169f21246dSJosef Bacik 
4179f21246dSJosef Bacik 	ctl = cache->caching_ctl;
4189f21246dSJosef Bacik 	refcount_inc(&ctl->count);
4199f21246dSJosef Bacik 	spin_unlock(&cache->lock);
4209f21246dSJosef Bacik 	return ctl;
4219f21246dSJosef Bacik }
4229f21246dSJosef Bacik 
4239f21246dSJosef Bacik void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
4249f21246dSJosef Bacik {
4259f21246dSJosef Bacik 	if (refcount_dec_and_test(&ctl->count))
4269f21246dSJosef Bacik 		kfree(ctl);
4279f21246dSJosef Bacik }
4289f21246dSJosef Bacik 
4299f21246dSJosef Bacik /*
4309f21246dSJosef Bacik  * When we wait for progress in the block group caching, its because our
4319f21246dSJosef Bacik  * allocation attempt failed at least once.  So, we must sleep and let some
4329f21246dSJosef Bacik  * progress happen before we try again.
4339f21246dSJosef Bacik  *
4349f21246dSJosef Bacik  * This function will sleep at least once waiting for new free space to show
4359f21246dSJosef Bacik  * up, and then it will check the block group free space numbers for our min
4369f21246dSJosef Bacik  * num_bytes.  Another option is to have it go ahead and look in the rbtree for
4379f21246dSJosef Bacik  * a free extent of a given size, but this is a good start.
4389f21246dSJosef Bacik  *
4399f21246dSJosef Bacik  * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
4409f21246dSJosef Bacik  * any of the information in this block group.
4419f21246dSJosef Bacik  */
44232da5386SDavid Sterba void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
4439f21246dSJosef Bacik 					   u64 num_bytes)
4449f21246dSJosef Bacik {
4459f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
4469f21246dSJosef Bacik 
4479f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4489f21246dSJosef Bacik 	if (!caching_ctl)
4499f21246dSJosef Bacik 		return;
4509f21246dSJosef Bacik 
45132da5386SDavid Sterba 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
4529f21246dSJosef Bacik 		   (cache->free_space_ctl->free_space >= num_bytes));
4539f21246dSJosef Bacik 
4549f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4559f21246dSJosef Bacik }
4569f21246dSJosef Bacik 
457ced8ecf0SOmar Sandoval static int btrfs_caching_ctl_wait_done(struct btrfs_block_group *cache,
458ced8ecf0SOmar Sandoval 				       struct btrfs_caching_control *caching_ctl)
459ced8ecf0SOmar Sandoval {
460ced8ecf0SOmar Sandoval 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
461ced8ecf0SOmar Sandoval 	return cache->cached == BTRFS_CACHE_ERROR ? -EIO : 0;
462ced8ecf0SOmar Sandoval }
463ced8ecf0SOmar Sandoval 
464ced8ecf0SOmar Sandoval static int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
4659f21246dSJosef Bacik {
4669f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
467ced8ecf0SOmar Sandoval 	int ret;
4689f21246dSJosef Bacik 
4699f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4709f21246dSJosef Bacik 	if (!caching_ctl)
4719f21246dSJosef Bacik 		return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
472ced8ecf0SOmar Sandoval 	ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
4739f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4749f21246dSJosef Bacik 	return ret;
4759f21246dSJosef Bacik }
4769f21246dSJosef Bacik 
4779f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
47832da5386SDavid Sterba static void fragment_free_space(struct btrfs_block_group *block_group)
4799f21246dSJosef Bacik {
4809f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
481b3470b5dSDavid Sterba 	u64 start = block_group->start;
482b3470b5dSDavid Sterba 	u64 len = block_group->length;
4839f21246dSJosef Bacik 	u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
4849f21246dSJosef Bacik 		fs_info->nodesize : fs_info->sectorsize;
4859f21246dSJosef Bacik 	u64 step = chunk << 1;
4869f21246dSJosef Bacik 
4879f21246dSJosef Bacik 	while (len > chunk) {
4889f21246dSJosef Bacik 		btrfs_remove_free_space(block_group, start, chunk);
4899f21246dSJosef Bacik 		start += step;
4909f21246dSJosef Bacik 		if (len < step)
4919f21246dSJosef Bacik 			len = 0;
4929f21246dSJosef Bacik 		else
4939f21246dSJosef Bacik 			len -= step;
4949f21246dSJosef Bacik 	}
4959f21246dSJosef Bacik }
4969f21246dSJosef Bacik #endif
4979f21246dSJosef Bacik 
4989f21246dSJosef Bacik /*
4999f21246dSJosef Bacik  * This is only called by btrfs_cache_block_group, since we could have freed
5009f21246dSJosef Bacik  * extents we need to check the pinned_extents for any extents that can't be
5019f21246dSJosef Bacik  * used yet since their free space will be released as soon as the transaction
5029f21246dSJosef Bacik  * commits.
5039f21246dSJosef Bacik  */
50432da5386SDavid Sterba u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
5059f21246dSJosef Bacik {
5069f21246dSJosef Bacik 	struct btrfs_fs_info *info = block_group->fs_info;
5079f21246dSJosef Bacik 	u64 extent_start, extent_end, size, total_added = 0;
5089f21246dSJosef Bacik 	int ret;
5099f21246dSJosef Bacik 
5109f21246dSJosef Bacik 	while (start < end) {
511fe119a6eSNikolay Borisov 		ret = find_first_extent_bit(&info->excluded_extents, start,
5129f21246dSJosef Bacik 					    &extent_start, &extent_end,
5139f21246dSJosef Bacik 					    EXTENT_DIRTY | EXTENT_UPTODATE,
5149f21246dSJosef Bacik 					    NULL);
5159f21246dSJosef Bacik 		if (ret)
5169f21246dSJosef Bacik 			break;
5179f21246dSJosef Bacik 
5189f21246dSJosef Bacik 		if (extent_start <= start) {
5199f21246dSJosef Bacik 			start = extent_end + 1;
5209f21246dSJosef Bacik 		} else if (extent_start > start && extent_start < end) {
5219f21246dSJosef Bacik 			size = extent_start - start;
5229f21246dSJosef Bacik 			total_added += size;
523b0643e59SDennis Zhou 			ret = btrfs_add_free_space_async_trimmed(block_group,
524b0643e59SDennis Zhou 								 start, size);
5259f21246dSJosef Bacik 			BUG_ON(ret); /* -ENOMEM or logic error */
5269f21246dSJosef Bacik 			start = extent_end + 1;
5279f21246dSJosef Bacik 		} else {
5289f21246dSJosef Bacik 			break;
5299f21246dSJosef Bacik 		}
5309f21246dSJosef Bacik 	}
5319f21246dSJosef Bacik 
5329f21246dSJosef Bacik 	if (start < end) {
5339f21246dSJosef Bacik 		size = end - start;
5349f21246dSJosef Bacik 		total_added += size;
535b0643e59SDennis Zhou 		ret = btrfs_add_free_space_async_trimmed(block_group, start,
536b0643e59SDennis Zhou 							 size);
5379f21246dSJosef Bacik 		BUG_ON(ret); /* -ENOMEM or logic error */
5389f21246dSJosef Bacik 	}
5399f21246dSJosef Bacik 
5409f21246dSJosef Bacik 	return total_added;
5419f21246dSJosef Bacik }
5429f21246dSJosef Bacik 
543c7eec3d9SBoris Burkov /*
544c7eec3d9SBoris Burkov  * Get an arbitrary extent item index / max_index through the block group
545c7eec3d9SBoris Burkov  *
546c7eec3d9SBoris Burkov  * @block_group   the block group to sample from
547c7eec3d9SBoris Burkov  * @index:        the integral step through the block group to grab from
548c7eec3d9SBoris Burkov  * @max_index:    the granularity of the sampling
549c7eec3d9SBoris Burkov  * @key:          return value parameter for the item we find
550c7eec3d9SBoris Burkov  *
551c7eec3d9SBoris Burkov  * Pre-conditions on indices:
552c7eec3d9SBoris Burkov  * 0 <= index <= max_index
553c7eec3d9SBoris Burkov  * 0 < max_index
554c7eec3d9SBoris Burkov  *
555c7eec3d9SBoris Burkov  * Returns: 0 on success, 1 if the search didn't yield a useful item, negative
556c7eec3d9SBoris Burkov  * error code on error.
557c7eec3d9SBoris Burkov  */
558c7eec3d9SBoris Burkov static int sample_block_group_extent_item(struct btrfs_caching_control *caching_ctl,
559c7eec3d9SBoris Burkov 					  struct btrfs_block_group *block_group,
560c7eec3d9SBoris Burkov 					  int index, int max_index,
56112148367SBoris Burkov 					  struct btrfs_key *found_key)
562c7eec3d9SBoris Burkov {
563c7eec3d9SBoris Burkov 	struct btrfs_fs_info *fs_info = block_group->fs_info;
564c7eec3d9SBoris Burkov 	struct btrfs_root *extent_root;
565c7eec3d9SBoris Burkov 	u64 search_offset;
566c7eec3d9SBoris Burkov 	u64 search_end = block_group->start + block_group->length;
567c7eec3d9SBoris Burkov 	struct btrfs_path *path;
56812148367SBoris Burkov 	struct btrfs_key search_key;
56912148367SBoris Burkov 	int ret = 0;
570c7eec3d9SBoris Burkov 
571c7eec3d9SBoris Burkov 	ASSERT(index >= 0);
572c7eec3d9SBoris Burkov 	ASSERT(index <= max_index);
573c7eec3d9SBoris Burkov 	ASSERT(max_index > 0);
574c7eec3d9SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
575c7eec3d9SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
576c7eec3d9SBoris Burkov 
577c7eec3d9SBoris Burkov 	path = btrfs_alloc_path();
578c7eec3d9SBoris Burkov 	if (!path)
579c7eec3d9SBoris Burkov 		return -ENOMEM;
580c7eec3d9SBoris Burkov 
581c7eec3d9SBoris Burkov 	extent_root = btrfs_extent_root(fs_info, max_t(u64, block_group->start,
582c7eec3d9SBoris Burkov 						       BTRFS_SUPER_INFO_OFFSET));
583c7eec3d9SBoris Burkov 
584c7eec3d9SBoris Burkov 	path->skip_locking = 1;
585c7eec3d9SBoris Burkov 	path->search_commit_root = 1;
586c7eec3d9SBoris Burkov 	path->reada = READA_FORWARD;
587c7eec3d9SBoris Burkov 
588c7eec3d9SBoris Burkov 	search_offset = index * div_u64(block_group->length, max_index);
58912148367SBoris Burkov 	search_key.objectid = block_group->start + search_offset;
59012148367SBoris Burkov 	search_key.type = BTRFS_EXTENT_ITEM_KEY;
59112148367SBoris Burkov 	search_key.offset = 0;
592c7eec3d9SBoris Burkov 
59312148367SBoris Burkov 	btrfs_for_each_slot(extent_root, &search_key, found_key, path, ret) {
594c7eec3d9SBoris Burkov 		/* Success; sampled an extent item in the block group */
59512148367SBoris Burkov 		if (found_key->type == BTRFS_EXTENT_ITEM_KEY &&
59612148367SBoris Burkov 		    found_key->objectid >= block_group->start &&
59712148367SBoris Burkov 		    found_key->objectid + found_key->offset <= search_end)
59812148367SBoris Burkov 			break;
599c7eec3d9SBoris Burkov 
600c7eec3d9SBoris Burkov 		/* We can't possibly find a valid extent item anymore */
60112148367SBoris Burkov 		if (found_key->objectid >= search_end) {
602c7eec3d9SBoris Burkov 			ret = 1;
603c7eec3d9SBoris Burkov 			break;
604c7eec3d9SBoris Burkov 		}
605c7eec3d9SBoris Burkov 	}
60612148367SBoris Burkov 
607c7eec3d9SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
608c7eec3d9SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
609c7eec3d9SBoris Burkov 	btrfs_free_path(path);
610c7eec3d9SBoris Burkov 	return ret;
611c7eec3d9SBoris Burkov }
612c7eec3d9SBoris Burkov 
613c7eec3d9SBoris Burkov /*
614c7eec3d9SBoris Burkov  * Best effort attempt to compute a block group's size class while caching it.
615c7eec3d9SBoris Burkov  *
616c7eec3d9SBoris Burkov  * @block_group: the block group we are caching
617c7eec3d9SBoris Burkov  *
618c7eec3d9SBoris Burkov  * We cannot infer the size class while adding free space extents, because that
619c7eec3d9SBoris Burkov  * logic doesn't care about contiguous file extents (it doesn't differentiate
620c7eec3d9SBoris Burkov  * between a 100M extent and 100 contiguous 1M extents). So we need to read the
621c7eec3d9SBoris Burkov  * file extent items. Reading all of them is quite wasteful, because usually
622c7eec3d9SBoris Burkov  * only a handful are enough to give a good answer. Therefore, we just grab 5 of
623c7eec3d9SBoris Burkov  * them at even steps through the block group and pick the smallest size class
624c7eec3d9SBoris Burkov  * we see. Since size class is best effort, and not guaranteed in general,
625c7eec3d9SBoris Burkov  * inaccuracy is acceptable.
626c7eec3d9SBoris Burkov  *
627c7eec3d9SBoris Burkov  * To be more explicit about why this algorithm makes sense:
628c7eec3d9SBoris Burkov  *
629c7eec3d9SBoris Burkov  * If we are caching in a block group from disk, then there are three major cases
630c7eec3d9SBoris Burkov  * to consider:
631c7eec3d9SBoris Burkov  * 1. the block group is well behaved and all extents in it are the same size
632c7eec3d9SBoris Burkov  *    class.
633c7eec3d9SBoris Burkov  * 2. the block group is mostly one size class with rare exceptions for last
634c7eec3d9SBoris Burkov  *    ditch allocations
635c7eec3d9SBoris Burkov  * 3. the block group was populated before size classes and can have a totally
636c7eec3d9SBoris Burkov  *    arbitrary mix of size classes.
637c7eec3d9SBoris Burkov  *
638c7eec3d9SBoris Burkov  * In case 1, looking at any extent in the block group will yield the correct
639c7eec3d9SBoris Burkov  * result. For the mixed cases, taking the minimum size class seems like a good
640c7eec3d9SBoris Burkov  * approximation, since gaps from frees will be usable to the size class. For
641c7eec3d9SBoris Burkov  * 2., a small handful of file extents is likely to yield the right answer. For
642c7eec3d9SBoris Burkov  * 3, we can either read every file extent, or admit that this is best effort
643c7eec3d9SBoris Burkov  * anyway and try to stay fast.
644c7eec3d9SBoris Burkov  *
645c7eec3d9SBoris Burkov  * Returns: 0 on success, negative error code on error.
646c7eec3d9SBoris Burkov  */
647c7eec3d9SBoris Burkov static int load_block_group_size_class(struct btrfs_caching_control *caching_ctl,
648c7eec3d9SBoris Burkov 				       struct btrfs_block_group *block_group)
649c7eec3d9SBoris Burkov {
65012148367SBoris Burkov 	struct btrfs_fs_info *fs_info = block_group->fs_info;
651c7eec3d9SBoris Burkov 	struct btrfs_key key;
652c7eec3d9SBoris Burkov 	int i;
653c7eec3d9SBoris Burkov 	u64 min_size = block_group->length;
654c7eec3d9SBoris Burkov 	enum btrfs_block_group_size_class size_class = BTRFS_BG_SZ_NONE;
655c7eec3d9SBoris Burkov 	int ret;
656c7eec3d9SBoris Burkov 
657cb0922f2SBoris Burkov 	if (!btrfs_block_group_should_use_size_class(block_group))
658c7eec3d9SBoris Burkov 		return 0;
659c7eec3d9SBoris Burkov 
66012148367SBoris Burkov 	lockdep_assert_held(&caching_ctl->mutex);
66112148367SBoris Burkov 	lockdep_assert_held_read(&fs_info->commit_root_sem);
662c7eec3d9SBoris Burkov 	for (i = 0; i < 5; ++i) {
663c7eec3d9SBoris Burkov 		ret = sample_block_group_extent_item(caching_ctl, block_group, i, 5, &key);
664c7eec3d9SBoris Burkov 		if (ret < 0)
665c7eec3d9SBoris Burkov 			goto out;
666c7eec3d9SBoris Burkov 		if (ret > 0)
667c7eec3d9SBoris Burkov 			continue;
668c7eec3d9SBoris Burkov 		min_size = min_t(u64, min_size, key.offset);
669c7eec3d9SBoris Burkov 		size_class = btrfs_calc_block_group_size_class(min_size);
670c7eec3d9SBoris Burkov 	}
671c7eec3d9SBoris Burkov 	if (size_class != BTRFS_BG_SZ_NONE) {
672c7eec3d9SBoris Burkov 		spin_lock(&block_group->lock);
673c7eec3d9SBoris Burkov 		block_group->size_class = size_class;
674c7eec3d9SBoris Burkov 		spin_unlock(&block_group->lock);
675c7eec3d9SBoris Burkov 	}
676c7eec3d9SBoris Burkov out:
677c7eec3d9SBoris Burkov 	return ret;
678c7eec3d9SBoris Burkov }
679c7eec3d9SBoris Burkov 
6809f21246dSJosef Bacik static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
6819f21246dSJosef Bacik {
68232da5386SDavid Sterba 	struct btrfs_block_group *block_group = caching_ctl->block_group;
6839f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
68429cbcf40SJosef Bacik 	struct btrfs_root *extent_root;
6859f21246dSJosef Bacik 	struct btrfs_path *path;
6869f21246dSJosef Bacik 	struct extent_buffer *leaf;
6879f21246dSJosef Bacik 	struct btrfs_key key;
6889f21246dSJosef Bacik 	u64 total_found = 0;
6899f21246dSJosef Bacik 	u64 last = 0;
6909f21246dSJosef Bacik 	u32 nritems;
6919f21246dSJosef Bacik 	int ret;
6929f21246dSJosef Bacik 	bool wakeup = true;
6939f21246dSJosef Bacik 
6949f21246dSJosef Bacik 	path = btrfs_alloc_path();
6959f21246dSJosef Bacik 	if (!path)
6969f21246dSJosef Bacik 		return -ENOMEM;
6979f21246dSJosef Bacik 
698b3470b5dSDavid Sterba 	last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
69929cbcf40SJosef Bacik 	extent_root = btrfs_extent_root(fs_info, last);
7009f21246dSJosef Bacik 
7019f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
7029f21246dSJosef Bacik 	/*
7039f21246dSJosef Bacik 	 * If we're fragmenting we don't want to make anybody think we can
7049f21246dSJosef Bacik 	 * allocate from this block group until we've had a chance to fragment
7059f21246dSJosef Bacik 	 * the free space.
7069f21246dSJosef Bacik 	 */
7079f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group))
7089f21246dSJosef Bacik 		wakeup = false;
7099f21246dSJosef Bacik #endif
7109f21246dSJosef Bacik 	/*
7119f21246dSJosef Bacik 	 * We don't want to deadlock with somebody trying to allocate a new
7129f21246dSJosef Bacik 	 * extent for the extent root while also trying to search the extent
7139f21246dSJosef Bacik 	 * root to add free space.  So we skip locking and search the commit
7149f21246dSJosef Bacik 	 * root, since its read-only
7159f21246dSJosef Bacik 	 */
7169f21246dSJosef Bacik 	path->skip_locking = 1;
7179f21246dSJosef Bacik 	path->search_commit_root = 1;
7189f21246dSJosef Bacik 	path->reada = READA_FORWARD;
7199f21246dSJosef Bacik 
7209f21246dSJosef Bacik 	key.objectid = last;
7219f21246dSJosef Bacik 	key.offset = 0;
7229f21246dSJosef Bacik 	key.type = BTRFS_EXTENT_ITEM_KEY;
7239f21246dSJosef Bacik 
7249f21246dSJosef Bacik next:
7259f21246dSJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
7269f21246dSJosef Bacik 	if (ret < 0)
7279f21246dSJosef Bacik 		goto out;
7289f21246dSJosef Bacik 
7299f21246dSJosef Bacik 	leaf = path->nodes[0];
7309f21246dSJosef Bacik 	nritems = btrfs_header_nritems(leaf);
7319f21246dSJosef Bacik 
7329f21246dSJosef Bacik 	while (1) {
7339f21246dSJosef Bacik 		if (btrfs_fs_closing(fs_info) > 1) {
7349f21246dSJosef Bacik 			last = (u64)-1;
7359f21246dSJosef Bacik 			break;
7369f21246dSJosef Bacik 		}
7379f21246dSJosef Bacik 
7389f21246dSJosef Bacik 		if (path->slots[0] < nritems) {
7399f21246dSJosef Bacik 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7409f21246dSJosef Bacik 		} else {
7419f21246dSJosef Bacik 			ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
7429f21246dSJosef Bacik 			if (ret)
7439f21246dSJosef Bacik 				break;
7449f21246dSJosef Bacik 
7459f21246dSJosef Bacik 			if (need_resched() ||
7469f21246dSJosef Bacik 			    rwsem_is_contended(&fs_info->commit_root_sem)) {
7479f21246dSJosef Bacik 				btrfs_release_path(path);
7489f21246dSJosef Bacik 				up_read(&fs_info->commit_root_sem);
7499f21246dSJosef Bacik 				mutex_unlock(&caching_ctl->mutex);
7509f21246dSJosef Bacik 				cond_resched();
7519f21246dSJosef Bacik 				mutex_lock(&caching_ctl->mutex);
7529f21246dSJosef Bacik 				down_read(&fs_info->commit_root_sem);
7539f21246dSJosef Bacik 				goto next;
7549f21246dSJosef Bacik 			}
7559f21246dSJosef Bacik 
7569f21246dSJosef Bacik 			ret = btrfs_next_leaf(extent_root, path);
7579f21246dSJosef Bacik 			if (ret < 0)
7589f21246dSJosef Bacik 				goto out;
7599f21246dSJosef Bacik 			if (ret)
7609f21246dSJosef Bacik 				break;
7619f21246dSJosef Bacik 			leaf = path->nodes[0];
7629f21246dSJosef Bacik 			nritems = btrfs_header_nritems(leaf);
7639f21246dSJosef Bacik 			continue;
7649f21246dSJosef Bacik 		}
7659f21246dSJosef Bacik 
7669f21246dSJosef Bacik 		if (key.objectid < last) {
7679f21246dSJosef Bacik 			key.objectid = last;
7689f21246dSJosef Bacik 			key.offset = 0;
7699f21246dSJosef Bacik 			key.type = BTRFS_EXTENT_ITEM_KEY;
7709f21246dSJosef Bacik 			btrfs_release_path(path);
7719f21246dSJosef Bacik 			goto next;
7729f21246dSJosef Bacik 		}
7739f21246dSJosef Bacik 
774b3470b5dSDavid Sterba 		if (key.objectid < block_group->start) {
7759f21246dSJosef Bacik 			path->slots[0]++;
7769f21246dSJosef Bacik 			continue;
7779f21246dSJosef Bacik 		}
7789f21246dSJosef Bacik 
779b3470b5dSDavid Sterba 		if (key.objectid >= block_group->start + block_group->length)
7809f21246dSJosef Bacik 			break;
7819f21246dSJosef Bacik 
7829f21246dSJosef Bacik 		if (key.type == BTRFS_EXTENT_ITEM_KEY ||
7839f21246dSJosef Bacik 		    key.type == BTRFS_METADATA_ITEM_KEY) {
7849f21246dSJosef Bacik 			total_found += add_new_free_space(block_group, last,
7859f21246dSJosef Bacik 							  key.objectid);
7869f21246dSJosef Bacik 			if (key.type == BTRFS_METADATA_ITEM_KEY)
7879f21246dSJosef Bacik 				last = key.objectid +
7889f21246dSJosef Bacik 					fs_info->nodesize;
7899f21246dSJosef Bacik 			else
7909f21246dSJosef Bacik 				last = key.objectid + key.offset;
7919f21246dSJosef Bacik 
7929f21246dSJosef Bacik 			if (total_found > CACHING_CTL_WAKE_UP) {
7939f21246dSJosef Bacik 				total_found = 0;
7949f21246dSJosef Bacik 				if (wakeup)
7959f21246dSJosef Bacik 					wake_up(&caching_ctl->wait);
7969f21246dSJosef Bacik 			}
7979f21246dSJosef Bacik 		}
7989f21246dSJosef Bacik 		path->slots[0]++;
7999f21246dSJosef Bacik 	}
8009f21246dSJosef Bacik 	ret = 0;
8019f21246dSJosef Bacik 
8029f21246dSJosef Bacik 	total_found += add_new_free_space(block_group, last,
803b3470b5dSDavid Sterba 				block_group->start + block_group->length);
8049f21246dSJosef Bacik 
8059f21246dSJosef Bacik out:
8069f21246dSJosef Bacik 	btrfs_free_path(path);
8079f21246dSJosef Bacik 	return ret;
8089f21246dSJosef Bacik }
8099f21246dSJosef Bacik 
8109f21246dSJosef Bacik static noinline void caching_thread(struct btrfs_work *work)
8119f21246dSJosef Bacik {
81232da5386SDavid Sterba 	struct btrfs_block_group *block_group;
8139f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info;
8149f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
8159f21246dSJosef Bacik 	int ret;
8169f21246dSJosef Bacik 
8179f21246dSJosef Bacik 	caching_ctl = container_of(work, struct btrfs_caching_control, work);
8189f21246dSJosef Bacik 	block_group = caching_ctl->block_group;
8199f21246dSJosef Bacik 	fs_info = block_group->fs_info;
8209f21246dSJosef Bacik 
8219f21246dSJosef Bacik 	mutex_lock(&caching_ctl->mutex);
8229f21246dSJosef Bacik 	down_read(&fs_info->commit_root_sem);
8239f21246dSJosef Bacik 
824c7eec3d9SBoris Burkov 	load_block_group_size_class(caching_ctl, block_group);
825e747853cSJosef Bacik 	if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
826e747853cSJosef Bacik 		ret = load_free_space_cache(block_group);
827e747853cSJosef Bacik 		if (ret == 1) {
828e747853cSJosef Bacik 			ret = 0;
829e747853cSJosef Bacik 			goto done;
830e747853cSJosef Bacik 		}
831e747853cSJosef Bacik 
832e747853cSJosef Bacik 		/*
833e747853cSJosef Bacik 		 * We failed to load the space cache, set ourselves to
834e747853cSJosef Bacik 		 * CACHE_STARTED and carry on.
835e747853cSJosef Bacik 		 */
836e747853cSJosef Bacik 		spin_lock(&block_group->lock);
837e747853cSJosef Bacik 		block_group->cached = BTRFS_CACHE_STARTED;
838e747853cSJosef Bacik 		spin_unlock(&block_group->lock);
839e747853cSJosef Bacik 		wake_up(&caching_ctl->wait);
840e747853cSJosef Bacik 	}
841e747853cSJosef Bacik 
8422f96e402SJosef Bacik 	/*
8432f96e402SJosef Bacik 	 * If we are in the transaction that populated the free space tree we
8442f96e402SJosef Bacik 	 * can't actually cache from the free space tree as our commit root and
8452f96e402SJosef Bacik 	 * real root are the same, so we could change the contents of the blocks
8462f96e402SJosef Bacik 	 * while caching.  Instead do the slow caching in this case, and after
8472f96e402SJosef Bacik 	 * the transaction has committed we will be safe.
8482f96e402SJosef Bacik 	 */
8492f96e402SJosef Bacik 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
8502f96e402SJosef Bacik 	    !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
8519f21246dSJosef Bacik 		ret = load_free_space_tree(caching_ctl);
8529f21246dSJosef Bacik 	else
8539f21246dSJosef Bacik 		ret = load_extent_tree_free(caching_ctl);
854e747853cSJosef Bacik done:
8559f21246dSJosef Bacik 	spin_lock(&block_group->lock);
8569f21246dSJosef Bacik 	block_group->caching_ctl = NULL;
8579f21246dSJosef Bacik 	block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
8589f21246dSJosef Bacik 	spin_unlock(&block_group->lock);
8599f21246dSJosef Bacik 
8609f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
8619f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group)) {
8629f21246dSJosef Bacik 		u64 bytes_used;
8639f21246dSJosef Bacik 
8649f21246dSJosef Bacik 		spin_lock(&block_group->space_info->lock);
8659f21246dSJosef Bacik 		spin_lock(&block_group->lock);
866b3470b5dSDavid Sterba 		bytes_used = block_group->length - block_group->used;
8679f21246dSJosef Bacik 		block_group->space_info->bytes_used += bytes_used >> 1;
8689f21246dSJosef Bacik 		spin_unlock(&block_group->lock);
8699f21246dSJosef Bacik 		spin_unlock(&block_group->space_info->lock);
870e11c0406SJosef Bacik 		fragment_free_space(block_group);
8719f21246dSJosef Bacik 	}
8729f21246dSJosef Bacik #endif
8739f21246dSJosef Bacik 
8749f21246dSJosef Bacik 	up_read(&fs_info->commit_root_sem);
8759f21246dSJosef Bacik 	btrfs_free_excluded_extents(block_group);
8769f21246dSJosef Bacik 	mutex_unlock(&caching_ctl->mutex);
8779f21246dSJosef Bacik 
8789f21246dSJosef Bacik 	wake_up(&caching_ctl->wait);
8799f21246dSJosef Bacik 
8809f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
8819f21246dSJosef Bacik 	btrfs_put_block_group(block_group);
8829f21246dSJosef Bacik }
8839f21246dSJosef Bacik 
884ced8ecf0SOmar Sandoval int btrfs_cache_block_group(struct btrfs_block_group *cache, bool wait)
8859f21246dSJosef Bacik {
8869f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
887e747853cSJosef Bacik 	struct btrfs_caching_control *caching_ctl = NULL;
8889f21246dSJosef Bacik 	int ret = 0;
8899f21246dSJosef Bacik 
8902eda5708SNaohiro Aota 	/* Allocator for zoned filesystems does not use the cache at all */
8912eda5708SNaohiro Aota 	if (btrfs_is_zoned(fs_info))
8922eda5708SNaohiro Aota 		return 0;
8932eda5708SNaohiro Aota 
8949f21246dSJosef Bacik 	caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
8959f21246dSJosef Bacik 	if (!caching_ctl)
8969f21246dSJosef Bacik 		return -ENOMEM;
8979f21246dSJosef Bacik 
8989f21246dSJosef Bacik 	INIT_LIST_HEAD(&caching_ctl->list);
8999f21246dSJosef Bacik 	mutex_init(&caching_ctl->mutex);
9009f21246dSJosef Bacik 	init_waitqueue_head(&caching_ctl->wait);
9019f21246dSJosef Bacik 	caching_ctl->block_group = cache;
902e747853cSJosef Bacik 	refcount_set(&caching_ctl->count, 2);
903a0cac0ecSOmar Sandoval 	btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
9049f21246dSJosef Bacik 
9059f21246dSJosef Bacik 	spin_lock(&cache->lock);
9069f21246dSJosef Bacik 	if (cache->cached != BTRFS_CACHE_NO) {
9079f21246dSJosef Bacik 		kfree(caching_ctl);
908e747853cSJosef Bacik 
909e747853cSJosef Bacik 		caching_ctl = cache->caching_ctl;
910e747853cSJosef Bacik 		if (caching_ctl)
911e747853cSJosef Bacik 			refcount_inc(&caching_ctl->count);
912e747853cSJosef Bacik 		spin_unlock(&cache->lock);
913e747853cSJosef Bacik 		goto out;
9149f21246dSJosef Bacik 	}
9159f21246dSJosef Bacik 	WARN_ON(cache->caching_ctl);
9169f21246dSJosef Bacik 	cache->caching_ctl = caching_ctl;
9179f21246dSJosef Bacik 	cache->cached = BTRFS_CACHE_STARTED;
9189f21246dSJosef Bacik 	spin_unlock(&cache->lock);
9199f21246dSJosef Bacik 
92016b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
9219f21246dSJosef Bacik 	refcount_inc(&caching_ctl->count);
9229f21246dSJosef Bacik 	list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
92316b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
9249f21246dSJosef Bacik 
9259f21246dSJosef Bacik 	btrfs_get_block_group(cache);
9269f21246dSJosef Bacik 
9279f21246dSJosef Bacik 	btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
928e747853cSJosef Bacik out:
929ced8ecf0SOmar Sandoval 	if (wait && caching_ctl)
930ced8ecf0SOmar Sandoval 		ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
931e747853cSJosef Bacik 	if (caching_ctl)
932e747853cSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
9339f21246dSJosef Bacik 
9349f21246dSJosef Bacik 	return ret;
9359f21246dSJosef Bacik }
936e3e0520bSJosef Bacik 
937e3e0520bSJosef Bacik static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
938e3e0520bSJosef Bacik {
939e3e0520bSJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
940e3e0520bSJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
941e3e0520bSJosef Bacik 
942e3e0520bSJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
943e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
944e3e0520bSJosef Bacik 		fs_info->avail_data_alloc_bits &= ~extra_flags;
945e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
946e3e0520bSJosef Bacik 		fs_info->avail_metadata_alloc_bits &= ~extra_flags;
947e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
948e3e0520bSJosef Bacik 		fs_info->avail_system_alloc_bits &= ~extra_flags;
949e3e0520bSJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
950e3e0520bSJosef Bacik }
951e3e0520bSJosef Bacik 
952e3e0520bSJosef Bacik /*
953e3e0520bSJosef Bacik  * Clear incompat bits for the following feature(s):
954e3e0520bSJosef Bacik  *
955e3e0520bSJosef Bacik  * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
956e3e0520bSJosef Bacik  *            in the whole filesystem
9579c907446SDavid Sterba  *
9589c907446SDavid Sterba  * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
959e3e0520bSJosef Bacik  */
960e3e0520bSJosef Bacik static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
961e3e0520bSJosef Bacik {
9629c907446SDavid Sterba 	bool found_raid56 = false;
9639c907446SDavid Sterba 	bool found_raid1c34 = false;
9649c907446SDavid Sterba 
9659c907446SDavid Sterba 	if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
9669c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
9679c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
968e3e0520bSJosef Bacik 		struct list_head *head = &fs_info->space_info;
969e3e0520bSJosef Bacik 		struct btrfs_space_info *sinfo;
970e3e0520bSJosef Bacik 
971e3e0520bSJosef Bacik 		list_for_each_entry_rcu(sinfo, head, list) {
972e3e0520bSJosef Bacik 			down_read(&sinfo->groups_sem);
973e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
9749c907446SDavid Sterba 				found_raid56 = true;
975e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
9769c907446SDavid Sterba 				found_raid56 = true;
9779c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
9789c907446SDavid Sterba 				found_raid1c34 = true;
9799c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
9809c907446SDavid Sterba 				found_raid1c34 = true;
981e3e0520bSJosef Bacik 			up_read(&sinfo->groups_sem);
982e3e0520bSJosef Bacik 		}
983d8e6fd5cSFilipe Manana 		if (!found_raid56)
984e3e0520bSJosef Bacik 			btrfs_clear_fs_incompat(fs_info, RAID56);
985d8e6fd5cSFilipe Manana 		if (!found_raid1c34)
9869c907446SDavid Sterba 			btrfs_clear_fs_incompat(fs_info, RAID1C34);
987e3e0520bSJosef Bacik 	}
988e3e0520bSJosef Bacik }
989e3e0520bSJosef Bacik 
9907357623aSQu Wenruo static int remove_block_group_item(struct btrfs_trans_handle *trans,
9917357623aSQu Wenruo 				   struct btrfs_path *path,
9927357623aSQu Wenruo 				   struct btrfs_block_group *block_group)
9937357623aSQu Wenruo {
9947357623aSQu Wenruo 	struct btrfs_fs_info *fs_info = trans->fs_info;
9957357623aSQu Wenruo 	struct btrfs_root *root;
9967357623aSQu Wenruo 	struct btrfs_key key;
9977357623aSQu Wenruo 	int ret;
9987357623aSQu Wenruo 
999dfe8aec4SJosef Bacik 	root = btrfs_block_group_root(fs_info);
10007357623aSQu Wenruo 	key.objectid = block_group->start;
10017357623aSQu Wenruo 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
10027357623aSQu Wenruo 	key.offset = block_group->length;
10037357623aSQu Wenruo 
10047357623aSQu Wenruo 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10057357623aSQu Wenruo 	if (ret > 0)
10067357623aSQu Wenruo 		ret = -ENOENT;
10077357623aSQu Wenruo 	if (ret < 0)
10087357623aSQu Wenruo 		return ret;
10097357623aSQu Wenruo 
10107357623aSQu Wenruo 	ret = btrfs_del_item(trans, root, path);
10117357623aSQu Wenruo 	return ret;
10127357623aSQu Wenruo }
10137357623aSQu Wenruo 
1014e3e0520bSJosef Bacik int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
1015e3e0520bSJosef Bacik 			     u64 group_start, struct extent_map *em)
1016e3e0520bSJosef Bacik {
1017e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
1018e3e0520bSJosef Bacik 	struct btrfs_path *path;
101932da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1020e3e0520bSJosef Bacik 	struct btrfs_free_cluster *cluster;
1021e3e0520bSJosef Bacik 	struct inode *inode;
1022e3e0520bSJosef Bacik 	struct kobject *kobj = NULL;
1023e3e0520bSJosef Bacik 	int ret;
1024e3e0520bSJosef Bacik 	int index;
1025e3e0520bSJosef Bacik 	int factor;
1026e3e0520bSJosef Bacik 	struct btrfs_caching_control *caching_ctl = NULL;
1027e3e0520bSJosef Bacik 	bool remove_em;
1028e3e0520bSJosef Bacik 	bool remove_rsv = false;
1029e3e0520bSJosef Bacik 
1030e3e0520bSJosef Bacik 	block_group = btrfs_lookup_block_group(fs_info, group_start);
1031e3e0520bSJosef Bacik 	BUG_ON(!block_group);
1032e3e0520bSJosef Bacik 	BUG_ON(!block_group->ro);
1033e3e0520bSJosef Bacik 
1034e3e0520bSJosef Bacik 	trace_btrfs_remove_block_group(block_group);
1035e3e0520bSJosef Bacik 	/*
1036e3e0520bSJosef Bacik 	 * Free the reserved super bytes from this block group before
1037e3e0520bSJosef Bacik 	 * remove it.
1038e3e0520bSJosef Bacik 	 */
1039e3e0520bSJosef Bacik 	btrfs_free_excluded_extents(block_group);
1040b3470b5dSDavid Sterba 	btrfs_free_ref_tree_range(fs_info, block_group->start,
1041b3470b5dSDavid Sterba 				  block_group->length);
1042e3e0520bSJosef Bacik 
1043e3e0520bSJosef Bacik 	index = btrfs_bg_flags_to_raid_index(block_group->flags);
1044e3e0520bSJosef Bacik 	factor = btrfs_bg_type_to_factor(block_group->flags);
1045e3e0520bSJosef Bacik 
1046e3e0520bSJosef Bacik 	/* make sure this block group isn't part of an allocation cluster */
1047e3e0520bSJosef Bacik 	cluster = &fs_info->data_alloc_cluster;
1048e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
1049e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
1050e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
1051e3e0520bSJosef Bacik 
1052e3e0520bSJosef Bacik 	/*
1053e3e0520bSJosef Bacik 	 * make sure this block group isn't part of a metadata
1054e3e0520bSJosef Bacik 	 * allocation cluster
1055e3e0520bSJosef Bacik 	 */
1056e3e0520bSJosef Bacik 	cluster = &fs_info->meta_alloc_cluster;
1057e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
1058e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
1059e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
1060e3e0520bSJosef Bacik 
106140ab3be1SNaohiro Aota 	btrfs_clear_treelog_bg(block_group);
1062c2707a25SJohannes Thumshirn 	btrfs_clear_data_reloc_bg(block_group);
106340ab3be1SNaohiro Aota 
1064e3e0520bSJosef Bacik 	path = btrfs_alloc_path();
1065e3e0520bSJosef Bacik 	if (!path) {
1066e3e0520bSJosef Bacik 		ret = -ENOMEM;
10679fecd132SFilipe Manana 		goto out;
1068e3e0520bSJosef Bacik 	}
1069e3e0520bSJosef Bacik 
1070e3e0520bSJosef Bacik 	/*
1071e3e0520bSJosef Bacik 	 * get the inode first so any iput calls done for the io_list
1072e3e0520bSJosef Bacik 	 * aren't the final iput (no unlinks allowed now)
1073e3e0520bSJosef Bacik 	 */
1074e3e0520bSJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
1075e3e0520bSJosef Bacik 
1076e3e0520bSJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
1077e3e0520bSJosef Bacik 	/*
1078e3e0520bSJosef Bacik 	 * Make sure our free space cache IO is done before removing the
1079e3e0520bSJosef Bacik 	 * free space inode
1080e3e0520bSJosef Bacik 	 */
1081e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
1082e3e0520bSJosef Bacik 	if (!list_empty(&block_group->io_list)) {
1083e3e0520bSJosef Bacik 		list_del_init(&block_group->io_list);
1084e3e0520bSJosef Bacik 
1085e3e0520bSJosef Bacik 		WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
1086e3e0520bSJosef Bacik 
1087e3e0520bSJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
1088e3e0520bSJosef Bacik 		btrfs_wait_cache_io(trans, block_group, path);
1089e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1090e3e0520bSJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
1091e3e0520bSJosef Bacik 	}
1092e3e0520bSJosef Bacik 
1093e3e0520bSJosef Bacik 	if (!list_empty(&block_group->dirty_list)) {
1094e3e0520bSJosef Bacik 		list_del_init(&block_group->dirty_list);
1095e3e0520bSJosef Bacik 		remove_rsv = true;
1096e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1097e3e0520bSJosef Bacik 	}
1098e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1099e3e0520bSJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
1100e3e0520bSJosef Bacik 
110136b216c8SBoris Burkov 	ret = btrfs_remove_free_space_inode(trans, inode, block_group);
1102e3e0520bSJosef Bacik 	if (ret)
11039fecd132SFilipe Manana 		goto out;
1104e3e0520bSJosef Bacik 
110516b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
110608dddb29SFilipe Manana 	rb_erase_cached(&block_group->cache_node,
1107e3e0520bSJosef Bacik 			&fs_info->block_group_cache_tree);
1108e3e0520bSJosef Bacik 	RB_CLEAR_NODE(&block_group->cache_node);
1109e3e0520bSJosef Bacik 
11109fecd132SFilipe Manana 	/* Once for the block groups rbtree */
11119fecd132SFilipe Manana 	btrfs_put_block_group(block_group);
11129fecd132SFilipe Manana 
111316b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
1114e3e0520bSJosef Bacik 
1115e3e0520bSJosef Bacik 	down_write(&block_group->space_info->groups_sem);
1116e3e0520bSJosef Bacik 	/*
1117e3e0520bSJosef Bacik 	 * we must use list_del_init so people can check to see if they
1118e3e0520bSJosef Bacik 	 * are still on the list after taking the semaphore
1119e3e0520bSJosef Bacik 	 */
1120e3e0520bSJosef Bacik 	list_del_init(&block_group->list);
1121e3e0520bSJosef Bacik 	if (list_empty(&block_group->space_info->block_groups[index])) {
1122e3e0520bSJosef Bacik 		kobj = block_group->space_info->block_group_kobjs[index];
1123e3e0520bSJosef Bacik 		block_group->space_info->block_group_kobjs[index] = NULL;
1124e3e0520bSJosef Bacik 		clear_avail_alloc_bits(fs_info, block_group->flags);
1125e3e0520bSJosef Bacik 	}
1126e3e0520bSJosef Bacik 	up_write(&block_group->space_info->groups_sem);
1127e3e0520bSJosef Bacik 	clear_incompat_bg_bits(fs_info, block_group->flags);
1128e3e0520bSJosef Bacik 	if (kobj) {
1129e3e0520bSJosef Bacik 		kobject_del(kobj);
1130e3e0520bSJosef Bacik 		kobject_put(kobj);
1131e3e0520bSJosef Bacik 	}
1132e3e0520bSJosef Bacik 
1133e3e0520bSJosef Bacik 	if (block_group->cached == BTRFS_CACHE_STARTED)
1134e3e0520bSJosef Bacik 		btrfs_wait_block_group_cache_done(block_group);
11357b9c293bSJosef Bacik 
113616b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
11377b9c293bSJosef Bacik 	caching_ctl = btrfs_get_caching_control(block_group);
1138e3e0520bSJosef Bacik 	if (!caching_ctl) {
1139e3e0520bSJosef Bacik 		struct btrfs_caching_control *ctl;
1140e3e0520bSJosef Bacik 
11417b9c293bSJosef Bacik 		list_for_each_entry(ctl, &fs_info->caching_block_groups, list) {
1142e3e0520bSJosef Bacik 			if (ctl->block_group == block_group) {
1143e3e0520bSJosef Bacik 				caching_ctl = ctl;
1144e3e0520bSJosef Bacik 				refcount_inc(&caching_ctl->count);
1145e3e0520bSJosef Bacik 				break;
1146e3e0520bSJosef Bacik 			}
1147e3e0520bSJosef Bacik 		}
11487b9c293bSJosef Bacik 	}
1149e3e0520bSJosef Bacik 	if (caching_ctl)
1150e3e0520bSJosef Bacik 		list_del_init(&caching_ctl->list);
115116b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
11527b9c293bSJosef Bacik 
1153e3e0520bSJosef Bacik 	if (caching_ctl) {
1154e3e0520bSJosef Bacik 		/* Once for the caching bgs list and once for us. */
1155e3e0520bSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
1156e3e0520bSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
1157e3e0520bSJosef Bacik 	}
1158e3e0520bSJosef Bacik 
1159e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
1160e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->dirty_list));
1161e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->io_list));
1162e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1163e3e0520bSJosef Bacik 
1164e3e0520bSJosef Bacik 	btrfs_remove_free_space_cache(block_group);
1165e3e0520bSJosef Bacik 
1166e3e0520bSJosef Bacik 	spin_lock(&block_group->space_info->lock);
1167e3e0520bSJosef Bacik 	list_del_init(&block_group->ro_list);
1168e3e0520bSJosef Bacik 
1169e3e0520bSJosef Bacik 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1170e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->total_bytes
1171b3470b5dSDavid Sterba 			< block_group->length);
1172e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->bytes_readonly
1173169e0da9SNaohiro Aota 			< block_group->length - block_group->zone_unusable);
1174169e0da9SNaohiro Aota 		WARN_ON(block_group->space_info->bytes_zone_unusable
1175169e0da9SNaohiro Aota 			< block_group->zone_unusable);
1176e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->disk_total
1177b3470b5dSDavid Sterba 			< block_group->length * factor);
1178e3e0520bSJosef Bacik 	}
1179b3470b5dSDavid Sterba 	block_group->space_info->total_bytes -= block_group->length;
1180169e0da9SNaohiro Aota 	block_group->space_info->bytes_readonly -=
1181169e0da9SNaohiro Aota 		(block_group->length - block_group->zone_unusable);
1182169e0da9SNaohiro Aota 	block_group->space_info->bytes_zone_unusable -=
1183169e0da9SNaohiro Aota 		block_group->zone_unusable;
1184b3470b5dSDavid Sterba 	block_group->space_info->disk_total -= block_group->length * factor;
1185e3e0520bSJosef Bacik 
1186e3e0520bSJosef Bacik 	spin_unlock(&block_group->space_info->lock);
1187e3e0520bSJosef Bacik 
1188ffcb9d44SFilipe Manana 	/*
1189ffcb9d44SFilipe Manana 	 * Remove the free space for the block group from the free space tree
1190ffcb9d44SFilipe Manana 	 * and the block group's item from the extent tree before marking the
1191ffcb9d44SFilipe Manana 	 * block group as removed. This is to prevent races with tasks that
1192ffcb9d44SFilipe Manana 	 * freeze and unfreeze a block group, this task and another task
1193ffcb9d44SFilipe Manana 	 * allocating a new block group - the unfreeze task ends up removing
1194ffcb9d44SFilipe Manana 	 * the block group's extent map before the task calling this function
1195ffcb9d44SFilipe Manana 	 * deletes the block group item from the extent tree, allowing for
1196ffcb9d44SFilipe Manana 	 * another task to attempt to create another block group with the same
1197ffcb9d44SFilipe Manana 	 * item key (and failing with -EEXIST and a transaction abort).
1198ffcb9d44SFilipe Manana 	 */
1199ffcb9d44SFilipe Manana 	ret = remove_block_group_free_space(trans, block_group);
1200ffcb9d44SFilipe Manana 	if (ret)
1201ffcb9d44SFilipe Manana 		goto out;
1202ffcb9d44SFilipe Manana 
1203ffcb9d44SFilipe Manana 	ret = remove_block_group_item(trans, path, block_group);
1204ffcb9d44SFilipe Manana 	if (ret < 0)
1205ffcb9d44SFilipe Manana 		goto out;
1206ffcb9d44SFilipe Manana 
1207e3e0520bSJosef Bacik 	spin_lock(&block_group->lock);
12083349b57fSJosef Bacik 	set_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags);
12093349b57fSJosef Bacik 
1210e3e0520bSJosef Bacik 	/*
12116b7304afSFilipe Manana 	 * At this point trimming or scrub can't start on this block group,
12126b7304afSFilipe Manana 	 * because we removed the block group from the rbtree
12136b7304afSFilipe Manana 	 * fs_info->block_group_cache_tree so no one can't find it anymore and
12146b7304afSFilipe Manana 	 * even if someone already got this block group before we removed it
12156b7304afSFilipe Manana 	 * from the rbtree, they have already incremented block_group->frozen -
12166b7304afSFilipe Manana 	 * if they didn't, for the trimming case they won't find any free space
12176b7304afSFilipe Manana 	 * entries because we already removed them all when we called
12186b7304afSFilipe Manana 	 * btrfs_remove_free_space_cache().
1219e3e0520bSJosef Bacik 	 *
1220e3e0520bSJosef Bacik 	 * And we must not remove the extent map from the fs_info->mapping_tree
1221e3e0520bSJosef Bacik 	 * to prevent the same logical address range and physical device space
12226b7304afSFilipe Manana 	 * ranges from being reused for a new block group. This is needed to
12236b7304afSFilipe Manana 	 * avoid races with trimming and scrub.
12246b7304afSFilipe Manana 	 *
12256b7304afSFilipe Manana 	 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1226e3e0520bSJosef Bacik 	 * completely transactionless, so while it is trimming a range the
1227e3e0520bSJosef Bacik 	 * currently running transaction might finish and a new one start,
1228e3e0520bSJosef Bacik 	 * allowing for new block groups to be created that can reuse the same
1229e3e0520bSJosef Bacik 	 * physical device locations unless we take this special care.
1230e3e0520bSJosef Bacik 	 *
1231e3e0520bSJosef Bacik 	 * There may also be an implicit trim operation if the file system
1232e3e0520bSJosef Bacik 	 * is mounted with -odiscard. The same protections must remain
1233e3e0520bSJosef Bacik 	 * in place until the extents have been discarded completely when
1234e3e0520bSJosef Bacik 	 * the transaction commit has completed.
1235e3e0520bSJosef Bacik 	 */
12366b7304afSFilipe Manana 	remove_em = (atomic_read(&block_group->frozen) == 0);
1237e3e0520bSJosef Bacik 	spin_unlock(&block_group->lock);
1238e3e0520bSJosef Bacik 
1239e3e0520bSJosef Bacik 	if (remove_em) {
1240e3e0520bSJosef Bacik 		struct extent_map_tree *em_tree;
1241e3e0520bSJosef Bacik 
1242e3e0520bSJosef Bacik 		em_tree = &fs_info->mapping_tree;
1243e3e0520bSJosef Bacik 		write_lock(&em_tree->lock);
1244e3e0520bSJosef Bacik 		remove_extent_mapping(em_tree, em);
1245e3e0520bSJosef Bacik 		write_unlock(&em_tree->lock);
1246e3e0520bSJosef Bacik 		/* once for the tree */
1247e3e0520bSJosef Bacik 		free_extent_map(em);
1248e3e0520bSJosef Bacik 	}
1249f6033c5eSXiyu Yang 
12509fecd132SFilipe Manana out:
1251f6033c5eSXiyu Yang 	/* Once for the lookup reference */
1252f6033c5eSXiyu Yang 	btrfs_put_block_group(block_group);
1253e3e0520bSJosef Bacik 	if (remove_rsv)
1254e3e0520bSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
1255e3e0520bSJosef Bacik 	btrfs_free_path(path);
1256e3e0520bSJosef Bacik 	return ret;
1257e3e0520bSJosef Bacik }
1258e3e0520bSJosef Bacik 
1259e3e0520bSJosef Bacik struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1260e3e0520bSJosef Bacik 		struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1261e3e0520bSJosef Bacik {
1262dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
1263e3e0520bSJosef Bacik 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1264e3e0520bSJosef Bacik 	struct extent_map *em;
1265e3e0520bSJosef Bacik 	struct map_lookup *map;
1266e3e0520bSJosef Bacik 	unsigned int num_items;
1267e3e0520bSJosef Bacik 
1268e3e0520bSJosef Bacik 	read_lock(&em_tree->lock);
1269e3e0520bSJosef Bacik 	em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1270e3e0520bSJosef Bacik 	read_unlock(&em_tree->lock);
1271e3e0520bSJosef Bacik 	ASSERT(em && em->start == chunk_offset);
1272e3e0520bSJosef Bacik 
1273e3e0520bSJosef Bacik 	/*
1274e3e0520bSJosef Bacik 	 * We need to reserve 3 + N units from the metadata space info in order
1275e3e0520bSJosef Bacik 	 * to remove a block group (done at btrfs_remove_chunk() and at
1276e3e0520bSJosef Bacik 	 * btrfs_remove_block_group()), which are used for:
1277e3e0520bSJosef Bacik 	 *
1278e3e0520bSJosef Bacik 	 * 1 unit for adding the free space inode's orphan (located in the tree
1279e3e0520bSJosef Bacik 	 * of tree roots).
1280e3e0520bSJosef Bacik 	 * 1 unit for deleting the block group item (located in the extent
1281e3e0520bSJosef Bacik 	 * tree).
1282e3e0520bSJosef Bacik 	 * 1 unit for deleting the free space item (located in tree of tree
1283e3e0520bSJosef Bacik 	 * roots).
1284e3e0520bSJosef Bacik 	 * N units for deleting N device extent items corresponding to each
1285e3e0520bSJosef Bacik 	 * stripe (located in the device tree).
1286e3e0520bSJosef Bacik 	 *
1287e3e0520bSJosef Bacik 	 * In order to remove a block group we also need to reserve units in the
1288e3e0520bSJosef Bacik 	 * system space info in order to update the chunk tree (update one or
1289e3e0520bSJosef Bacik 	 * more device items and remove one chunk item), but this is done at
1290e3e0520bSJosef Bacik 	 * btrfs_remove_chunk() through a call to check_system_chunk().
1291e3e0520bSJosef Bacik 	 */
1292e3e0520bSJosef Bacik 	map = em->map_lookup;
1293e3e0520bSJosef Bacik 	num_items = 3 + map->num_stripes;
1294e3e0520bSJosef Bacik 	free_extent_map(em);
1295e3e0520bSJosef Bacik 
1296dfe8aec4SJosef Bacik 	return btrfs_start_transaction_fallback_global_rsv(root, num_items);
1297e3e0520bSJosef Bacik }
1298e3e0520bSJosef Bacik 
1299e3e0520bSJosef Bacik /*
130026ce2095SJosef Bacik  * Mark block group @cache read-only, so later write won't happen to block
130126ce2095SJosef Bacik  * group @cache.
130226ce2095SJosef Bacik  *
130326ce2095SJosef Bacik  * If @force is not set, this function will only mark the block group readonly
130426ce2095SJosef Bacik  * if we have enough free space (1M) in other metadata/system block groups.
130526ce2095SJosef Bacik  * If @force is not set, this function will mark the block group readonly
130626ce2095SJosef Bacik  * without checking free space.
130726ce2095SJosef Bacik  *
130826ce2095SJosef Bacik  * NOTE: This function doesn't care if other block groups can contain all the
130926ce2095SJosef Bacik  * data in this block group. That check should be done by relocation routine,
131026ce2095SJosef Bacik  * not this function.
131126ce2095SJosef Bacik  */
131232da5386SDavid Sterba static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
131326ce2095SJosef Bacik {
131426ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
131526ce2095SJosef Bacik 	u64 num_bytes;
131626ce2095SJosef Bacik 	int ret = -ENOSPC;
131726ce2095SJosef Bacik 
131826ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
131926ce2095SJosef Bacik 	spin_lock(&cache->lock);
132026ce2095SJosef Bacik 
1321195a49eaSFilipe Manana 	if (cache->swap_extents) {
1322195a49eaSFilipe Manana 		ret = -ETXTBSY;
1323195a49eaSFilipe Manana 		goto out;
1324195a49eaSFilipe Manana 	}
1325195a49eaSFilipe Manana 
132626ce2095SJosef Bacik 	if (cache->ro) {
132726ce2095SJosef Bacik 		cache->ro++;
132826ce2095SJosef Bacik 		ret = 0;
132926ce2095SJosef Bacik 		goto out;
133026ce2095SJosef Bacik 	}
133126ce2095SJosef Bacik 
1332b3470b5dSDavid Sterba 	num_bytes = cache->length - cache->reserved - cache->pinned -
1333169e0da9SNaohiro Aota 		    cache->bytes_super - cache->zone_unusable - cache->used;
133426ce2095SJosef Bacik 
133526ce2095SJosef Bacik 	/*
1336a30a3d20SJosef Bacik 	 * Data never overcommits, even in mixed mode, so do just the straight
1337a30a3d20SJosef Bacik 	 * check of left over space in how much we have allocated.
1338a30a3d20SJosef Bacik 	 */
1339a30a3d20SJosef Bacik 	if (force) {
1340a30a3d20SJosef Bacik 		ret = 0;
1341a30a3d20SJosef Bacik 	} else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1342a30a3d20SJosef Bacik 		u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1343a30a3d20SJosef Bacik 
1344a30a3d20SJosef Bacik 		/*
134526ce2095SJosef Bacik 		 * Here we make sure if we mark this bg RO, we still have enough
1346f8935566SJosef Bacik 		 * free space as buffer.
134726ce2095SJosef Bacik 		 */
1348a30a3d20SJosef Bacik 		if (sinfo_used + num_bytes <= sinfo->total_bytes)
1349a30a3d20SJosef Bacik 			ret = 0;
1350a30a3d20SJosef Bacik 	} else {
1351a30a3d20SJosef Bacik 		/*
1352a30a3d20SJosef Bacik 		 * We overcommit metadata, so we need to do the
1353a30a3d20SJosef Bacik 		 * btrfs_can_overcommit check here, and we need to pass in
1354a30a3d20SJosef Bacik 		 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1355a30a3d20SJosef Bacik 		 * leeway to allow us to mark this block group as read only.
1356a30a3d20SJosef Bacik 		 */
1357a30a3d20SJosef Bacik 		if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1358a30a3d20SJosef Bacik 					 BTRFS_RESERVE_NO_FLUSH))
1359a30a3d20SJosef Bacik 			ret = 0;
1360a30a3d20SJosef Bacik 	}
1361a30a3d20SJosef Bacik 
1362a30a3d20SJosef Bacik 	if (!ret) {
136326ce2095SJosef Bacik 		sinfo->bytes_readonly += num_bytes;
1364169e0da9SNaohiro Aota 		if (btrfs_is_zoned(cache->fs_info)) {
1365169e0da9SNaohiro Aota 			/* Migrate zone_unusable bytes to readonly */
1366169e0da9SNaohiro Aota 			sinfo->bytes_readonly += cache->zone_unusable;
1367169e0da9SNaohiro Aota 			sinfo->bytes_zone_unusable -= cache->zone_unusable;
1368169e0da9SNaohiro Aota 			cache->zone_unusable = 0;
1369169e0da9SNaohiro Aota 		}
137026ce2095SJosef Bacik 		cache->ro++;
137126ce2095SJosef Bacik 		list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
137226ce2095SJosef Bacik 	}
137326ce2095SJosef Bacik out:
137426ce2095SJosef Bacik 	spin_unlock(&cache->lock);
137526ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
137626ce2095SJosef Bacik 	if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
137726ce2095SJosef Bacik 		btrfs_info(cache->fs_info,
1378b3470b5dSDavid Sterba 			"unable to make block group %llu ro", cache->start);
137926ce2095SJosef Bacik 		btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
138026ce2095SJosef Bacik 	}
138126ce2095SJosef Bacik 	return ret;
138226ce2095SJosef Bacik }
138326ce2095SJosef Bacik 
1384fe119a6eSNikolay Borisov static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1385fe119a6eSNikolay Borisov 				 struct btrfs_block_group *bg)
138645bb5d6aSNikolay Borisov {
138745bb5d6aSNikolay Borisov 	struct btrfs_fs_info *fs_info = bg->fs_info;
1388fe119a6eSNikolay Borisov 	struct btrfs_transaction *prev_trans = NULL;
138945bb5d6aSNikolay Borisov 	const u64 start = bg->start;
139045bb5d6aSNikolay Borisov 	const u64 end = start + bg->length - 1;
139145bb5d6aSNikolay Borisov 	int ret;
139245bb5d6aSNikolay Borisov 
1393fe119a6eSNikolay Borisov 	spin_lock(&fs_info->trans_lock);
1394fe119a6eSNikolay Borisov 	if (trans->transaction->list.prev != &fs_info->trans_list) {
1395fe119a6eSNikolay Borisov 		prev_trans = list_last_entry(&trans->transaction->list,
1396fe119a6eSNikolay Borisov 					     struct btrfs_transaction, list);
1397fe119a6eSNikolay Borisov 		refcount_inc(&prev_trans->use_count);
1398fe119a6eSNikolay Borisov 	}
1399fe119a6eSNikolay Borisov 	spin_unlock(&fs_info->trans_lock);
1400fe119a6eSNikolay Borisov 
140145bb5d6aSNikolay Borisov 	/*
140245bb5d6aSNikolay Borisov 	 * Hold the unused_bg_unpin_mutex lock to avoid racing with
140345bb5d6aSNikolay Borisov 	 * btrfs_finish_extent_commit(). If we are at transaction N, another
140445bb5d6aSNikolay Borisov 	 * task might be running finish_extent_commit() for the previous
140545bb5d6aSNikolay Borisov 	 * transaction N - 1, and have seen a range belonging to the block
1406fe119a6eSNikolay Borisov 	 * group in pinned_extents before we were able to clear the whole block
1407fe119a6eSNikolay Borisov 	 * group range from pinned_extents. This means that task can lookup for
1408fe119a6eSNikolay Borisov 	 * the block group after we unpinned it from pinned_extents and removed
1409fe119a6eSNikolay Borisov 	 * it, leading to a BUG_ON() at unpin_extent_range().
141045bb5d6aSNikolay Borisov 	 */
141145bb5d6aSNikolay Borisov 	mutex_lock(&fs_info->unused_bg_unpin_mutex);
1412fe119a6eSNikolay Borisov 	if (prev_trans) {
1413fe119a6eSNikolay Borisov 		ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
141445bb5d6aSNikolay Borisov 					EXTENT_DIRTY);
141545bb5d6aSNikolay Borisov 		if (ret)
1416534cf531SFilipe Manana 			goto out;
1417fe119a6eSNikolay Borisov 	}
141845bb5d6aSNikolay Borisov 
1419fe119a6eSNikolay Borisov 	ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
142045bb5d6aSNikolay Borisov 				EXTENT_DIRTY);
1421534cf531SFilipe Manana out:
142245bb5d6aSNikolay Borisov 	mutex_unlock(&fs_info->unused_bg_unpin_mutex);
14235150bf19SFilipe Manana 	if (prev_trans)
14245150bf19SFilipe Manana 		btrfs_put_transaction(prev_trans);
142545bb5d6aSNikolay Borisov 
1426534cf531SFilipe Manana 	return ret == 0;
142745bb5d6aSNikolay Borisov }
142845bb5d6aSNikolay Borisov 
142926ce2095SJosef Bacik /*
1430e3e0520bSJosef Bacik  * Process the unused_bgs list and remove any that don't have any allocated
1431e3e0520bSJosef Bacik  * space inside of them.
1432e3e0520bSJosef Bacik  */
1433e3e0520bSJosef Bacik void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1434e3e0520bSJosef Bacik {
143532da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1436e3e0520bSJosef Bacik 	struct btrfs_space_info *space_info;
1437e3e0520bSJosef Bacik 	struct btrfs_trans_handle *trans;
14386e80d4f8SDennis Zhou 	const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1439e3e0520bSJosef Bacik 	int ret = 0;
1440e3e0520bSJosef Bacik 
1441e3e0520bSJosef Bacik 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1442e3e0520bSJosef Bacik 		return;
1443e3e0520bSJosef Bacik 
14442f12741fSJosef Bacik 	if (btrfs_fs_closing(fs_info))
14452f12741fSJosef Bacik 		return;
14462f12741fSJosef Bacik 
1447ddfd08cbSJosef Bacik 	/*
1448ddfd08cbSJosef Bacik 	 * Long running balances can keep us blocked here for eternity, so
1449ddfd08cbSJosef Bacik 	 * simply skip deletion if we're unable to get the mutex.
1450ddfd08cbSJosef Bacik 	 */
1451f3372065SJohannes Thumshirn 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
1452ddfd08cbSJosef Bacik 		return;
1453ddfd08cbSJosef Bacik 
1454e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1455e3e0520bSJosef Bacik 	while (!list_empty(&fs_info->unused_bgs)) {
1456e3e0520bSJosef Bacik 		int trimming;
1457e3e0520bSJosef Bacik 
1458e3e0520bSJosef Bacik 		block_group = list_first_entry(&fs_info->unused_bgs,
145932da5386SDavid Sterba 					       struct btrfs_block_group,
1460e3e0520bSJosef Bacik 					       bg_list);
1461e3e0520bSJosef Bacik 		list_del_init(&block_group->bg_list);
1462e3e0520bSJosef Bacik 
1463e3e0520bSJosef Bacik 		space_info = block_group->space_info;
1464e3e0520bSJosef Bacik 
1465e3e0520bSJosef Bacik 		if (ret || btrfs_mixed_space_info(space_info)) {
1466e3e0520bSJosef Bacik 			btrfs_put_block_group(block_group);
1467e3e0520bSJosef Bacik 			continue;
1468e3e0520bSJosef Bacik 		}
1469e3e0520bSJosef Bacik 		spin_unlock(&fs_info->unused_bgs_lock);
1470e3e0520bSJosef Bacik 
1471b0643e59SDennis Zhou 		btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1472b0643e59SDennis Zhou 
1473e3e0520bSJosef Bacik 		/* Don't want to race with allocators so take the groups_sem */
1474e3e0520bSJosef Bacik 		down_write(&space_info->groups_sem);
14756e80d4f8SDennis Zhou 
14766e80d4f8SDennis Zhou 		/*
14776e80d4f8SDennis Zhou 		 * Async discard moves the final block group discard to be prior
14786e80d4f8SDennis Zhou 		 * to the unused_bgs code path.  Therefore, if it's not fully
14796e80d4f8SDennis Zhou 		 * trimmed, punt it back to the async discard lists.
14806e80d4f8SDennis Zhou 		 */
14816e80d4f8SDennis Zhou 		if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
14826e80d4f8SDennis Zhou 		    !btrfs_is_free_space_trimmed(block_group)) {
14836e80d4f8SDennis Zhou 			trace_btrfs_skip_unused_block_group(block_group);
14846e80d4f8SDennis Zhou 			up_write(&space_info->groups_sem);
14856e80d4f8SDennis Zhou 			/* Requeue if we failed because of async discard */
14866e80d4f8SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
14876e80d4f8SDennis Zhou 						 block_group);
14886e80d4f8SDennis Zhou 			goto next;
14896e80d4f8SDennis Zhou 		}
14906e80d4f8SDennis Zhou 
1491e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1492e3e0520bSJosef Bacik 		if (block_group->reserved || block_group->pinned ||
1493bf38be65SDavid Sterba 		    block_group->used || block_group->ro ||
1494e3e0520bSJosef Bacik 		    list_is_singular(&block_group->list)) {
1495e3e0520bSJosef Bacik 			/*
1496e3e0520bSJosef Bacik 			 * We want to bail if we made new allocations or have
1497e3e0520bSJosef Bacik 			 * outstanding allocations in this block group.  We do
1498e3e0520bSJosef Bacik 			 * the ro check in case balance is currently acting on
1499e3e0520bSJosef Bacik 			 * this block group.
1500e3e0520bSJosef Bacik 			 */
1501e3e0520bSJosef Bacik 			trace_btrfs_skip_unused_block_group(block_group);
1502e3e0520bSJosef Bacik 			spin_unlock(&block_group->lock);
1503e3e0520bSJosef Bacik 			up_write(&space_info->groups_sem);
1504e3e0520bSJosef Bacik 			goto next;
1505e3e0520bSJosef Bacik 		}
1506e3e0520bSJosef Bacik 		spin_unlock(&block_group->lock);
1507e3e0520bSJosef Bacik 
1508e3e0520bSJosef Bacik 		/* We don't want to force the issue, only flip if it's ok. */
1509e11c0406SJosef Bacik 		ret = inc_block_group_ro(block_group, 0);
1510e3e0520bSJosef Bacik 		up_write(&space_info->groups_sem);
1511e3e0520bSJosef Bacik 		if (ret < 0) {
1512e3e0520bSJosef Bacik 			ret = 0;
1513e3e0520bSJosef Bacik 			goto next;
1514e3e0520bSJosef Bacik 		}
1515e3e0520bSJosef Bacik 
151674e91b12SNaohiro Aota 		ret = btrfs_zone_finish(block_group);
151774e91b12SNaohiro Aota 		if (ret < 0) {
151874e91b12SNaohiro Aota 			btrfs_dec_block_group_ro(block_group);
151974e91b12SNaohiro Aota 			if (ret == -EAGAIN)
152074e91b12SNaohiro Aota 				ret = 0;
152174e91b12SNaohiro Aota 			goto next;
152274e91b12SNaohiro Aota 		}
152374e91b12SNaohiro Aota 
1524e3e0520bSJosef Bacik 		/*
1525e3e0520bSJosef Bacik 		 * Want to do this before we do anything else so we can recover
1526e3e0520bSJosef Bacik 		 * properly if we fail to join the transaction.
1527e3e0520bSJosef Bacik 		 */
1528e3e0520bSJosef Bacik 		trans = btrfs_start_trans_remove_block_group(fs_info,
1529b3470b5dSDavid Sterba 						     block_group->start);
1530e3e0520bSJosef Bacik 		if (IS_ERR(trans)) {
1531e3e0520bSJosef Bacik 			btrfs_dec_block_group_ro(block_group);
1532e3e0520bSJosef Bacik 			ret = PTR_ERR(trans);
1533e3e0520bSJosef Bacik 			goto next;
1534e3e0520bSJosef Bacik 		}
1535e3e0520bSJosef Bacik 
1536e3e0520bSJosef Bacik 		/*
1537e3e0520bSJosef Bacik 		 * We could have pending pinned extents for this block group,
1538e3e0520bSJosef Bacik 		 * just delete them, we don't care about them anymore.
1539e3e0520bSJosef Bacik 		 */
1540534cf531SFilipe Manana 		if (!clean_pinned_extents(trans, block_group)) {
1541534cf531SFilipe Manana 			btrfs_dec_block_group_ro(block_group);
1542e3e0520bSJosef Bacik 			goto end_trans;
1543534cf531SFilipe Manana 		}
1544e3e0520bSJosef Bacik 
1545b0643e59SDennis Zhou 		/*
1546b0643e59SDennis Zhou 		 * At this point, the block_group is read only and should fail
1547b0643e59SDennis Zhou 		 * new allocations.  However, btrfs_finish_extent_commit() can
1548b0643e59SDennis Zhou 		 * cause this block_group to be placed back on the discard
1549b0643e59SDennis Zhou 		 * lists because now the block_group isn't fully discarded.
1550b0643e59SDennis Zhou 		 * Bail here and try again later after discarding everything.
1551b0643e59SDennis Zhou 		 */
1552b0643e59SDennis Zhou 		spin_lock(&fs_info->discard_ctl.lock);
1553b0643e59SDennis Zhou 		if (!list_empty(&block_group->discard_list)) {
1554b0643e59SDennis Zhou 			spin_unlock(&fs_info->discard_ctl.lock);
1555b0643e59SDennis Zhou 			btrfs_dec_block_group_ro(block_group);
1556b0643e59SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
1557b0643e59SDennis Zhou 						 block_group);
1558b0643e59SDennis Zhou 			goto end_trans;
1559b0643e59SDennis Zhou 		}
1560b0643e59SDennis Zhou 		spin_unlock(&fs_info->discard_ctl.lock);
1561b0643e59SDennis Zhou 
1562e3e0520bSJosef Bacik 		/* Reset pinned so btrfs_put_block_group doesn't complain */
1563e3e0520bSJosef Bacik 		spin_lock(&space_info->lock);
1564e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1565e3e0520bSJosef Bacik 
1566e3e0520bSJosef Bacik 		btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1567e3e0520bSJosef Bacik 						     -block_group->pinned);
1568e3e0520bSJosef Bacik 		space_info->bytes_readonly += block_group->pinned;
1569e3e0520bSJosef Bacik 		block_group->pinned = 0;
1570e3e0520bSJosef Bacik 
1571e3e0520bSJosef Bacik 		spin_unlock(&block_group->lock);
1572e3e0520bSJosef Bacik 		spin_unlock(&space_info->lock);
1573e3e0520bSJosef Bacik 
15746e80d4f8SDennis Zhou 		/*
15756e80d4f8SDennis Zhou 		 * The normal path here is an unused block group is passed here,
15766e80d4f8SDennis Zhou 		 * then trimming is handled in the transaction commit path.
15776e80d4f8SDennis Zhou 		 * Async discard interposes before this to do the trimming
15786e80d4f8SDennis Zhou 		 * before coming down the unused block group path as trimming
15796e80d4f8SDennis Zhou 		 * will no longer be done later in the transaction commit path.
15806e80d4f8SDennis Zhou 		 */
15816e80d4f8SDennis Zhou 		if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
15826e80d4f8SDennis Zhou 			goto flip_async;
15836e80d4f8SDennis Zhou 
1584dcba6e48SNaohiro Aota 		/*
1585dcba6e48SNaohiro Aota 		 * DISCARD can flip during remount. On zoned filesystems, we
1586dcba6e48SNaohiro Aota 		 * need to reset sequential-required zones.
1587dcba6e48SNaohiro Aota 		 */
1588dcba6e48SNaohiro Aota 		trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) ||
1589dcba6e48SNaohiro Aota 				btrfs_is_zoned(fs_info);
1590e3e0520bSJosef Bacik 
1591e3e0520bSJosef Bacik 		/* Implicit trim during transaction commit. */
1592e3e0520bSJosef Bacik 		if (trimming)
15936b7304afSFilipe Manana 			btrfs_freeze_block_group(block_group);
1594e3e0520bSJosef Bacik 
1595e3e0520bSJosef Bacik 		/*
1596e3e0520bSJosef Bacik 		 * Btrfs_remove_chunk will abort the transaction if things go
1597e3e0520bSJosef Bacik 		 * horribly wrong.
1598e3e0520bSJosef Bacik 		 */
1599b3470b5dSDavid Sterba 		ret = btrfs_remove_chunk(trans, block_group->start);
1600e3e0520bSJosef Bacik 
1601e3e0520bSJosef Bacik 		if (ret) {
1602e3e0520bSJosef Bacik 			if (trimming)
16036b7304afSFilipe Manana 				btrfs_unfreeze_block_group(block_group);
1604e3e0520bSJosef Bacik 			goto end_trans;
1605e3e0520bSJosef Bacik 		}
1606e3e0520bSJosef Bacik 
1607e3e0520bSJosef Bacik 		/*
1608e3e0520bSJosef Bacik 		 * If we're not mounted with -odiscard, we can just forget
1609e3e0520bSJosef Bacik 		 * about this block group. Otherwise we'll need to wait
1610e3e0520bSJosef Bacik 		 * until transaction commit to do the actual discard.
1611e3e0520bSJosef Bacik 		 */
1612e3e0520bSJosef Bacik 		if (trimming) {
1613e3e0520bSJosef Bacik 			spin_lock(&fs_info->unused_bgs_lock);
1614e3e0520bSJosef Bacik 			/*
1615e3e0520bSJosef Bacik 			 * A concurrent scrub might have added us to the list
1616e3e0520bSJosef Bacik 			 * fs_info->unused_bgs, so use a list_move operation
1617e3e0520bSJosef Bacik 			 * to add the block group to the deleted_bgs list.
1618e3e0520bSJosef Bacik 			 */
1619e3e0520bSJosef Bacik 			list_move(&block_group->bg_list,
1620e3e0520bSJosef Bacik 				  &trans->transaction->deleted_bgs);
1621e3e0520bSJosef Bacik 			spin_unlock(&fs_info->unused_bgs_lock);
1622e3e0520bSJosef Bacik 			btrfs_get_block_group(block_group);
1623e3e0520bSJosef Bacik 		}
1624e3e0520bSJosef Bacik end_trans:
1625e3e0520bSJosef Bacik 		btrfs_end_transaction(trans);
1626e3e0520bSJosef Bacik next:
1627e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1628e3e0520bSJosef Bacik 		spin_lock(&fs_info->unused_bgs_lock);
1629e3e0520bSJosef Bacik 	}
1630e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
1631f3372065SJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
16326e80d4f8SDennis Zhou 	return;
16336e80d4f8SDennis Zhou 
16346e80d4f8SDennis Zhou flip_async:
16356e80d4f8SDennis Zhou 	btrfs_end_transaction(trans);
1636f3372065SJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
16376e80d4f8SDennis Zhou 	btrfs_put_block_group(block_group);
16386e80d4f8SDennis Zhou 	btrfs_discard_punt_unused_bgs_list(fs_info);
1639e3e0520bSJosef Bacik }
1640e3e0520bSJosef Bacik 
164132da5386SDavid Sterba void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1642e3e0520bSJosef Bacik {
1643e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = bg->fs_info;
1644e3e0520bSJosef Bacik 
1645e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1646e3e0520bSJosef Bacik 	if (list_empty(&bg->bg_list)) {
1647e3e0520bSJosef Bacik 		btrfs_get_block_group(bg);
1648e3e0520bSJosef Bacik 		trace_btrfs_add_unused_block_group(bg);
1649e3e0520bSJosef Bacik 		list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1650e3e0520bSJosef Bacik 	}
1651e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
1652e3e0520bSJosef Bacik }
16534358d963SJosef Bacik 
16542ca0ec77SJohannes Thumshirn /*
16552ca0ec77SJohannes Thumshirn  * We want block groups with a low number of used bytes to be in the beginning
16562ca0ec77SJohannes Thumshirn  * of the list, so they will get reclaimed first.
16572ca0ec77SJohannes Thumshirn  */
16582ca0ec77SJohannes Thumshirn static int reclaim_bgs_cmp(void *unused, const struct list_head *a,
16592ca0ec77SJohannes Thumshirn 			   const struct list_head *b)
16602ca0ec77SJohannes Thumshirn {
16612ca0ec77SJohannes Thumshirn 	const struct btrfs_block_group *bg1, *bg2;
16622ca0ec77SJohannes Thumshirn 
16632ca0ec77SJohannes Thumshirn 	bg1 = list_entry(a, struct btrfs_block_group, bg_list);
16642ca0ec77SJohannes Thumshirn 	bg2 = list_entry(b, struct btrfs_block_group, bg_list);
16652ca0ec77SJohannes Thumshirn 
16662ca0ec77SJohannes Thumshirn 	return bg1->used > bg2->used;
16672ca0ec77SJohannes Thumshirn }
16682ca0ec77SJohannes Thumshirn 
16693687fcb0SJohannes Thumshirn static inline bool btrfs_should_reclaim(struct btrfs_fs_info *fs_info)
16703687fcb0SJohannes Thumshirn {
16713687fcb0SJohannes Thumshirn 	if (btrfs_is_zoned(fs_info))
16723687fcb0SJohannes Thumshirn 		return btrfs_zoned_should_reclaim(fs_info);
16733687fcb0SJohannes Thumshirn 	return true;
16743687fcb0SJohannes Thumshirn }
16753687fcb0SJohannes Thumshirn 
167681531225SBoris Burkov static bool should_reclaim_block_group(struct btrfs_block_group *bg, u64 bytes_freed)
167781531225SBoris Burkov {
167881531225SBoris Burkov 	const struct btrfs_space_info *space_info = bg->space_info;
167981531225SBoris Burkov 	const int reclaim_thresh = READ_ONCE(space_info->bg_reclaim_threshold);
168081531225SBoris Burkov 	const u64 new_val = bg->used;
168181531225SBoris Burkov 	const u64 old_val = new_val + bytes_freed;
168281531225SBoris Burkov 	u64 thresh;
168381531225SBoris Burkov 
168481531225SBoris Burkov 	if (reclaim_thresh == 0)
168581531225SBoris Burkov 		return false;
168681531225SBoris Burkov 
1687428c8e03SDavid Sterba 	thresh = mult_perc(bg->length, reclaim_thresh);
168881531225SBoris Burkov 
168981531225SBoris Burkov 	/*
169081531225SBoris Burkov 	 * If we were below the threshold before don't reclaim, we are likely a
169181531225SBoris Burkov 	 * brand new block group and we don't want to relocate new block groups.
169281531225SBoris Burkov 	 */
169381531225SBoris Burkov 	if (old_val < thresh)
169481531225SBoris Burkov 		return false;
169581531225SBoris Burkov 	if (new_val >= thresh)
169681531225SBoris Burkov 		return false;
169781531225SBoris Burkov 	return true;
169881531225SBoris Burkov }
169981531225SBoris Burkov 
170018bb8bbfSJohannes Thumshirn void btrfs_reclaim_bgs_work(struct work_struct *work)
170118bb8bbfSJohannes Thumshirn {
170218bb8bbfSJohannes Thumshirn 	struct btrfs_fs_info *fs_info =
170318bb8bbfSJohannes Thumshirn 		container_of(work, struct btrfs_fs_info, reclaim_bgs_work);
170418bb8bbfSJohannes Thumshirn 	struct btrfs_block_group *bg;
170518bb8bbfSJohannes Thumshirn 	struct btrfs_space_info *space_info;
170618bb8bbfSJohannes Thumshirn 
170718bb8bbfSJohannes Thumshirn 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
170818bb8bbfSJohannes Thumshirn 		return;
170918bb8bbfSJohannes Thumshirn 
17102f12741fSJosef Bacik 	if (btrfs_fs_closing(fs_info))
17112f12741fSJosef Bacik 		return;
17122f12741fSJosef Bacik 
17133687fcb0SJohannes Thumshirn 	if (!btrfs_should_reclaim(fs_info))
17143687fcb0SJohannes Thumshirn 		return;
17153687fcb0SJohannes Thumshirn 
1716ca5e4ea0SNaohiro Aota 	sb_start_write(fs_info->sb);
1717ca5e4ea0SNaohiro Aota 
1718ca5e4ea0SNaohiro Aota 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
1719ca5e4ea0SNaohiro Aota 		sb_end_write(fs_info->sb);
172018bb8bbfSJohannes Thumshirn 		return;
1721ca5e4ea0SNaohiro Aota 	}
172218bb8bbfSJohannes Thumshirn 
17239cc0b837SJohannes Thumshirn 	/*
17249cc0b837SJohannes Thumshirn 	 * Long running balances can keep us blocked here for eternity, so
17259cc0b837SJohannes Thumshirn 	 * simply skip reclaim if we're unable to get the mutex.
17269cc0b837SJohannes Thumshirn 	 */
17279cc0b837SJohannes Thumshirn 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) {
17289cc0b837SJohannes Thumshirn 		btrfs_exclop_finish(fs_info);
1729ca5e4ea0SNaohiro Aota 		sb_end_write(fs_info->sb);
17309cc0b837SJohannes Thumshirn 		return;
17319cc0b837SJohannes Thumshirn 	}
17329cc0b837SJohannes Thumshirn 
173318bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
17342ca0ec77SJohannes Thumshirn 	/*
17352ca0ec77SJohannes Thumshirn 	 * Sort happens under lock because we can't simply splice it and sort.
17362ca0ec77SJohannes Thumshirn 	 * The block groups might still be in use and reachable via bg_list,
17372ca0ec77SJohannes Thumshirn 	 * and their presence in the reclaim_bgs list must be preserved.
17382ca0ec77SJohannes Thumshirn 	 */
17392ca0ec77SJohannes Thumshirn 	list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp);
174018bb8bbfSJohannes Thumshirn 	while (!list_empty(&fs_info->reclaim_bgs)) {
17415f93e776SJohannes Thumshirn 		u64 zone_unusable;
17421cea5cf0SFilipe Manana 		int ret = 0;
17431cea5cf0SFilipe Manana 
174418bb8bbfSJohannes Thumshirn 		bg = list_first_entry(&fs_info->reclaim_bgs,
174518bb8bbfSJohannes Thumshirn 				      struct btrfs_block_group,
174618bb8bbfSJohannes Thumshirn 				      bg_list);
174718bb8bbfSJohannes Thumshirn 		list_del_init(&bg->bg_list);
174818bb8bbfSJohannes Thumshirn 
174918bb8bbfSJohannes Thumshirn 		space_info = bg->space_info;
175018bb8bbfSJohannes Thumshirn 		spin_unlock(&fs_info->unused_bgs_lock);
175118bb8bbfSJohannes Thumshirn 
175218bb8bbfSJohannes Thumshirn 		/* Don't race with allocators so take the groups_sem */
175318bb8bbfSJohannes Thumshirn 		down_write(&space_info->groups_sem);
175418bb8bbfSJohannes Thumshirn 
175518bb8bbfSJohannes Thumshirn 		spin_lock(&bg->lock);
175618bb8bbfSJohannes Thumshirn 		if (bg->reserved || bg->pinned || bg->ro) {
175718bb8bbfSJohannes Thumshirn 			/*
175818bb8bbfSJohannes Thumshirn 			 * We want to bail if we made new allocations or have
175918bb8bbfSJohannes Thumshirn 			 * outstanding allocations in this block group.  We do
176018bb8bbfSJohannes Thumshirn 			 * the ro check in case balance is currently acting on
176118bb8bbfSJohannes Thumshirn 			 * this block group.
176218bb8bbfSJohannes Thumshirn 			 */
176318bb8bbfSJohannes Thumshirn 			spin_unlock(&bg->lock);
176418bb8bbfSJohannes Thumshirn 			up_write(&space_info->groups_sem);
176518bb8bbfSJohannes Thumshirn 			goto next;
176618bb8bbfSJohannes Thumshirn 		}
1767cc4804bfSBoris Burkov 		if (bg->used == 0) {
1768cc4804bfSBoris Burkov 			/*
1769cc4804bfSBoris Burkov 			 * It is possible that we trigger relocation on a block
1770cc4804bfSBoris Burkov 			 * group as its extents are deleted and it first goes
1771cc4804bfSBoris Burkov 			 * below the threshold, then shortly after goes empty.
1772cc4804bfSBoris Burkov 			 *
1773cc4804bfSBoris Burkov 			 * In this case, relocating it does delete it, but has
1774cc4804bfSBoris Burkov 			 * some overhead in relocation specific metadata, looking
1775cc4804bfSBoris Burkov 			 * for the non-existent extents and running some extra
1776cc4804bfSBoris Burkov 			 * transactions, which we can avoid by using one of the
1777cc4804bfSBoris Burkov 			 * other mechanisms for dealing with empty block groups.
1778cc4804bfSBoris Burkov 			 */
1779cc4804bfSBoris Burkov 			if (!btrfs_test_opt(fs_info, DISCARD_ASYNC))
1780cc4804bfSBoris Burkov 				btrfs_mark_bg_unused(bg);
1781cc4804bfSBoris Burkov 			spin_unlock(&bg->lock);
1782cc4804bfSBoris Burkov 			up_write(&space_info->groups_sem);
1783cc4804bfSBoris Burkov 			goto next;
178481531225SBoris Burkov 
178581531225SBoris Burkov 		}
178681531225SBoris Burkov 		/*
178781531225SBoris Burkov 		 * The block group might no longer meet the reclaim condition by
178881531225SBoris Burkov 		 * the time we get around to reclaiming it, so to avoid
178981531225SBoris Burkov 		 * reclaiming overly full block_groups, skip reclaiming them.
179081531225SBoris Burkov 		 *
179181531225SBoris Burkov 		 * Since the decision making process also depends on the amount
179281531225SBoris Burkov 		 * being freed, pass in a fake giant value to skip that extra
179381531225SBoris Burkov 		 * check, which is more meaningful when adding to the list in
179481531225SBoris Burkov 		 * the first place.
179581531225SBoris Burkov 		 */
179681531225SBoris Burkov 		if (!should_reclaim_block_group(bg, bg->length)) {
179781531225SBoris Burkov 			spin_unlock(&bg->lock);
179881531225SBoris Burkov 			up_write(&space_info->groups_sem);
179981531225SBoris Burkov 			goto next;
1800cc4804bfSBoris Burkov 		}
180118bb8bbfSJohannes Thumshirn 		spin_unlock(&bg->lock);
180218bb8bbfSJohannes Thumshirn 
180318bb8bbfSJohannes Thumshirn 		/* Get out fast, in case we're unmounting the filesystem */
180418bb8bbfSJohannes Thumshirn 		if (btrfs_fs_closing(fs_info)) {
180518bb8bbfSJohannes Thumshirn 			up_write(&space_info->groups_sem);
180618bb8bbfSJohannes Thumshirn 			goto next;
180718bb8bbfSJohannes Thumshirn 		}
180818bb8bbfSJohannes Thumshirn 
18095f93e776SJohannes Thumshirn 		/*
18105f93e776SJohannes Thumshirn 		 * Cache the zone_unusable value before turning the block group
18115f93e776SJohannes Thumshirn 		 * to read only. As soon as the blog group is read only it's
18125f93e776SJohannes Thumshirn 		 * zone_unusable value gets moved to the block group's read-only
18135f93e776SJohannes Thumshirn 		 * bytes and isn't available for calculations anymore.
18145f93e776SJohannes Thumshirn 		 */
18155f93e776SJohannes Thumshirn 		zone_unusable = bg->zone_unusable;
181618bb8bbfSJohannes Thumshirn 		ret = inc_block_group_ro(bg, 0);
181718bb8bbfSJohannes Thumshirn 		up_write(&space_info->groups_sem);
181818bb8bbfSJohannes Thumshirn 		if (ret < 0)
181918bb8bbfSJohannes Thumshirn 			goto next;
182018bb8bbfSJohannes Thumshirn 
18215f93e776SJohannes Thumshirn 		btrfs_info(fs_info,
18225f93e776SJohannes Thumshirn 			"reclaiming chunk %llu with %llu%% used %llu%% unusable",
182395cd356cSJohannes Thumshirn 				bg->start,
182495cd356cSJohannes Thumshirn 				div64_u64(bg->used * 100, bg->length),
18255f93e776SJohannes Thumshirn 				div64_u64(zone_unusable * 100, bg->length));
182618bb8bbfSJohannes Thumshirn 		trace_btrfs_reclaim_block_group(bg);
182718bb8bbfSJohannes Thumshirn 		ret = btrfs_relocate_chunk(fs_info, bg->start);
182874944c87SJosef Bacik 		if (ret) {
182974944c87SJosef Bacik 			btrfs_dec_block_group_ro(bg);
183018bb8bbfSJohannes Thumshirn 			btrfs_err(fs_info, "error relocating chunk %llu",
183118bb8bbfSJohannes Thumshirn 				  bg->start);
183274944c87SJosef Bacik 		}
183318bb8bbfSJohannes Thumshirn 
183418bb8bbfSJohannes Thumshirn next:
18351cea5cf0SFilipe Manana 		btrfs_put_block_group(bg);
1836d96b3424SFilipe Manana 		spin_lock(&fs_info->unused_bgs_lock);
183718bb8bbfSJohannes Thumshirn 	}
183818bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
183918bb8bbfSJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
184018bb8bbfSJohannes Thumshirn 	btrfs_exclop_finish(fs_info);
1841ca5e4ea0SNaohiro Aota 	sb_end_write(fs_info->sb);
184218bb8bbfSJohannes Thumshirn }
184318bb8bbfSJohannes Thumshirn 
184418bb8bbfSJohannes Thumshirn void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
184518bb8bbfSJohannes Thumshirn {
184618bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
184718bb8bbfSJohannes Thumshirn 	if (!list_empty(&fs_info->reclaim_bgs))
184818bb8bbfSJohannes Thumshirn 		queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
184918bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
185018bb8bbfSJohannes Thumshirn }
185118bb8bbfSJohannes Thumshirn 
185218bb8bbfSJohannes Thumshirn void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
185318bb8bbfSJohannes Thumshirn {
185418bb8bbfSJohannes Thumshirn 	struct btrfs_fs_info *fs_info = bg->fs_info;
185518bb8bbfSJohannes Thumshirn 
185618bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
185718bb8bbfSJohannes Thumshirn 	if (list_empty(&bg->bg_list)) {
185818bb8bbfSJohannes Thumshirn 		btrfs_get_block_group(bg);
185918bb8bbfSJohannes Thumshirn 		trace_btrfs_add_reclaim_block_group(bg);
186018bb8bbfSJohannes Thumshirn 		list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
186118bb8bbfSJohannes Thumshirn 	}
186218bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
186318bb8bbfSJohannes Thumshirn }
186418bb8bbfSJohannes Thumshirn 
1865e3ba67a1SJohannes Thumshirn static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1866e3ba67a1SJohannes Thumshirn 			   struct btrfs_path *path)
1867e3ba67a1SJohannes Thumshirn {
1868e3ba67a1SJohannes Thumshirn 	struct extent_map_tree *em_tree;
1869e3ba67a1SJohannes Thumshirn 	struct extent_map *em;
1870e3ba67a1SJohannes Thumshirn 	struct btrfs_block_group_item bg;
1871e3ba67a1SJohannes Thumshirn 	struct extent_buffer *leaf;
1872e3ba67a1SJohannes Thumshirn 	int slot;
1873e3ba67a1SJohannes Thumshirn 	u64 flags;
1874e3ba67a1SJohannes Thumshirn 	int ret = 0;
1875e3ba67a1SJohannes Thumshirn 
1876e3ba67a1SJohannes Thumshirn 	slot = path->slots[0];
1877e3ba67a1SJohannes Thumshirn 	leaf = path->nodes[0];
1878e3ba67a1SJohannes Thumshirn 
1879e3ba67a1SJohannes Thumshirn 	em_tree = &fs_info->mapping_tree;
1880e3ba67a1SJohannes Thumshirn 	read_lock(&em_tree->lock);
1881e3ba67a1SJohannes Thumshirn 	em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1882e3ba67a1SJohannes Thumshirn 	read_unlock(&em_tree->lock);
1883e3ba67a1SJohannes Thumshirn 	if (!em) {
1884e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1885e3ba67a1SJohannes Thumshirn 			  "logical %llu len %llu found bg but no related chunk",
1886e3ba67a1SJohannes Thumshirn 			  key->objectid, key->offset);
1887e3ba67a1SJohannes Thumshirn 		return -ENOENT;
1888e3ba67a1SJohannes Thumshirn 	}
1889e3ba67a1SJohannes Thumshirn 
1890e3ba67a1SJohannes Thumshirn 	if (em->start != key->objectid || em->len != key->offset) {
1891e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1892e3ba67a1SJohannes Thumshirn 			"block group %llu len %llu mismatch with chunk %llu len %llu",
1893e3ba67a1SJohannes Thumshirn 			key->objectid, key->offset, em->start, em->len);
1894e3ba67a1SJohannes Thumshirn 		ret = -EUCLEAN;
1895e3ba67a1SJohannes Thumshirn 		goto out_free_em;
1896e3ba67a1SJohannes Thumshirn 	}
1897e3ba67a1SJohannes Thumshirn 
1898e3ba67a1SJohannes Thumshirn 	read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1899e3ba67a1SJohannes Thumshirn 			   sizeof(bg));
1900e3ba67a1SJohannes Thumshirn 	flags = btrfs_stack_block_group_flags(&bg) &
1901e3ba67a1SJohannes Thumshirn 		BTRFS_BLOCK_GROUP_TYPE_MASK;
1902e3ba67a1SJohannes Thumshirn 
1903e3ba67a1SJohannes Thumshirn 	if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1904e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1905e3ba67a1SJohannes Thumshirn "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1906e3ba67a1SJohannes Thumshirn 			  key->objectid, key->offset, flags,
1907e3ba67a1SJohannes Thumshirn 			  (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1908e3ba67a1SJohannes Thumshirn 		ret = -EUCLEAN;
1909e3ba67a1SJohannes Thumshirn 	}
1910e3ba67a1SJohannes Thumshirn 
1911e3ba67a1SJohannes Thumshirn out_free_em:
1912e3ba67a1SJohannes Thumshirn 	free_extent_map(em);
1913e3ba67a1SJohannes Thumshirn 	return ret;
1914e3ba67a1SJohannes Thumshirn }
1915e3ba67a1SJohannes Thumshirn 
19164358d963SJosef Bacik static int find_first_block_group(struct btrfs_fs_info *fs_info,
19174358d963SJosef Bacik 				  struct btrfs_path *path,
19184358d963SJosef Bacik 				  struct btrfs_key *key)
19194358d963SJosef Bacik {
1920dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
1921e3ba67a1SJohannes Thumshirn 	int ret;
19224358d963SJosef Bacik 	struct btrfs_key found_key;
19234358d963SJosef Bacik 
192436dfbbe2SGabriel Niebler 	btrfs_for_each_slot(root, key, &found_key, path, ret) {
19254358d963SJosef Bacik 		if (found_key.objectid >= key->objectid &&
19264358d963SJosef Bacik 		    found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
192736dfbbe2SGabriel Niebler 			return read_bg_from_eb(fs_info, &found_key, path);
1928e3ba67a1SJohannes Thumshirn 		}
19294358d963SJosef Bacik 	}
19304358d963SJosef Bacik 	return ret;
19314358d963SJosef Bacik }
19324358d963SJosef Bacik 
19334358d963SJosef Bacik static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
19344358d963SJosef Bacik {
19354358d963SJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
19364358d963SJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
19374358d963SJosef Bacik 
19384358d963SJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
19394358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
19404358d963SJosef Bacik 		fs_info->avail_data_alloc_bits |= extra_flags;
19414358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
19424358d963SJosef Bacik 		fs_info->avail_metadata_alloc_bits |= extra_flags;
19434358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
19444358d963SJosef Bacik 		fs_info->avail_system_alloc_bits |= extra_flags;
19454358d963SJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
19464358d963SJosef Bacik }
19474358d963SJosef Bacik 
194843dd529aSDavid Sterba /*
194943dd529aSDavid Sterba  * Map a physical disk address to a list of logical addresses.
19509ee9b979SNikolay Borisov  *
19519ee9b979SNikolay Borisov  * @fs_info:       the filesystem
195296a14336SNikolay Borisov  * @chunk_start:   logical address of block group
195396a14336SNikolay Borisov  * @physical:	   physical address to map to logical addresses
195496a14336SNikolay Borisov  * @logical:	   return array of logical addresses which map to @physical
195596a14336SNikolay Borisov  * @naddrs:	   length of @logical
195696a14336SNikolay Borisov  * @stripe_len:    size of IO stripe for the given block group
195796a14336SNikolay Borisov  *
195896a14336SNikolay Borisov  * Maps a particular @physical disk address to a list of @logical addresses.
195996a14336SNikolay Borisov  * Used primarily to exclude those portions of a block group that contain super
196096a14336SNikolay Borisov  * block copies.
196196a14336SNikolay Borisov  */
196296a14336SNikolay Borisov int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
19631eb82ef8SChristoph Hellwig 		     u64 physical, u64 **logical, int *naddrs, int *stripe_len)
196496a14336SNikolay Borisov {
196596a14336SNikolay Borisov 	struct extent_map *em;
196696a14336SNikolay Borisov 	struct map_lookup *map;
196796a14336SNikolay Borisov 	u64 *buf;
196896a14336SNikolay Borisov 	u64 bytenr;
19691776ad17SNikolay Borisov 	u64 data_stripe_length;
19701776ad17SNikolay Borisov 	u64 io_stripe_size;
19711776ad17SNikolay Borisov 	int i, nr = 0;
19721776ad17SNikolay Borisov 	int ret = 0;
197396a14336SNikolay Borisov 
197496a14336SNikolay Borisov 	em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
197596a14336SNikolay Borisov 	if (IS_ERR(em))
197696a14336SNikolay Borisov 		return -EIO;
197796a14336SNikolay Borisov 
197896a14336SNikolay Borisov 	map = em->map_lookup;
19799e22b925SNikolay Borisov 	data_stripe_length = em->orig_block_len;
1980a97699d1SQu Wenruo 	io_stripe_size = BTRFS_STRIPE_LEN;
1981138082f3SNaohiro Aota 	chunk_start = em->start;
198296a14336SNikolay Borisov 
19839e22b925SNikolay Borisov 	/* For RAID5/6 adjust to a full IO stripe length */
19849e22b925SNikolay Borisov 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
1985a97699d1SQu Wenruo 		io_stripe_size = nr_data_stripes(map) << BTRFS_STRIPE_LEN_SHIFT;
198696a14336SNikolay Borisov 
198796a14336SNikolay Borisov 	buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
19881776ad17SNikolay Borisov 	if (!buf) {
19891776ad17SNikolay Borisov 		ret = -ENOMEM;
19901776ad17SNikolay Borisov 		goto out;
19911776ad17SNikolay Borisov 	}
199296a14336SNikolay Borisov 
199396a14336SNikolay Borisov 	for (i = 0; i < map->num_stripes; i++) {
19941776ad17SNikolay Borisov 		bool already_inserted = false;
19956ded22c1SQu Wenruo 		u32 stripe_nr;
19966ded22c1SQu Wenruo 		u32 offset;
19971776ad17SNikolay Borisov 		int j;
19981776ad17SNikolay Borisov 
19991776ad17SNikolay Borisov 		if (!in_range(physical, map->stripes[i].physical,
20001776ad17SNikolay Borisov 			      data_stripe_length))
200196a14336SNikolay Borisov 			continue;
200296a14336SNikolay Borisov 
2003a97699d1SQu Wenruo 		stripe_nr = (physical - map->stripes[i].physical) >>
2004a97699d1SQu Wenruo 			    BTRFS_STRIPE_LEN_SHIFT;
2005a97699d1SQu Wenruo 		offset = (physical - map->stripes[i].physical) &
2006a97699d1SQu Wenruo 			 BTRFS_STRIPE_LEN_MASK;
200796a14336SNikolay Borisov 
2008ac067734SDavid Sterba 		if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
20096ded22c1SQu Wenruo 				 BTRFS_BLOCK_GROUP_RAID10))
20106ded22c1SQu Wenruo 			stripe_nr = div_u64(stripe_nr * map->num_stripes + i,
20116ded22c1SQu Wenruo 					    map->sub_stripes);
201296a14336SNikolay Borisov 		/*
201396a14336SNikolay Borisov 		 * The remaining case would be for RAID56, multiply by
201496a14336SNikolay Borisov 		 * nr_data_stripes().  Alternatively, just use rmap_len below
201596a14336SNikolay Borisov 		 * instead of map->stripe_len
201696a14336SNikolay Borisov 		 */
2017138082f3SNaohiro Aota 		bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
20181776ad17SNikolay Borisov 
20191776ad17SNikolay Borisov 		/* Ensure we don't add duplicate addresses */
202096a14336SNikolay Borisov 		for (j = 0; j < nr; j++) {
20211776ad17SNikolay Borisov 			if (buf[j] == bytenr) {
20221776ad17SNikolay Borisov 				already_inserted = true;
202396a14336SNikolay Borisov 				break;
202496a14336SNikolay Borisov 			}
202596a14336SNikolay Borisov 		}
20261776ad17SNikolay Borisov 
20271776ad17SNikolay Borisov 		if (!already_inserted)
20281776ad17SNikolay Borisov 			buf[nr++] = bytenr;
202996a14336SNikolay Borisov 	}
203096a14336SNikolay Borisov 
203196a14336SNikolay Borisov 	*logical = buf;
203296a14336SNikolay Borisov 	*naddrs = nr;
20331776ad17SNikolay Borisov 	*stripe_len = io_stripe_size;
20341776ad17SNikolay Borisov out:
203596a14336SNikolay Borisov 	free_extent_map(em);
20361776ad17SNikolay Borisov 	return ret;
203796a14336SNikolay Borisov }
203896a14336SNikolay Borisov 
203932da5386SDavid Sterba static int exclude_super_stripes(struct btrfs_block_group *cache)
20404358d963SJosef Bacik {
20414358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
204212659251SNaohiro Aota 	const bool zoned = btrfs_is_zoned(fs_info);
20434358d963SJosef Bacik 	u64 bytenr;
20444358d963SJosef Bacik 	u64 *logical;
20454358d963SJosef Bacik 	int stripe_len;
20464358d963SJosef Bacik 	int i, nr, ret;
20474358d963SJosef Bacik 
2048b3470b5dSDavid Sterba 	if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
2049b3470b5dSDavid Sterba 		stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
20504358d963SJosef Bacik 		cache->bytes_super += stripe_len;
2051b3470b5dSDavid Sterba 		ret = btrfs_add_excluded_extent(fs_info, cache->start,
20524358d963SJosef Bacik 						stripe_len);
20534358d963SJosef Bacik 		if (ret)
20544358d963SJosef Bacik 			return ret;
20554358d963SJosef Bacik 	}
20564358d963SJosef Bacik 
20574358d963SJosef Bacik 	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
20584358d963SJosef Bacik 		bytenr = btrfs_sb_offset(i);
20591eb82ef8SChristoph Hellwig 		ret = btrfs_rmap_block(fs_info, cache->start,
20604358d963SJosef Bacik 				       bytenr, &logical, &nr, &stripe_len);
20614358d963SJosef Bacik 		if (ret)
20624358d963SJosef Bacik 			return ret;
20634358d963SJosef Bacik 
206412659251SNaohiro Aota 		/* Shouldn't have super stripes in sequential zones */
206512659251SNaohiro Aota 		if (zoned && nr) {
206612659251SNaohiro Aota 			btrfs_err(fs_info,
206712659251SNaohiro Aota 			"zoned: block group %llu must not contain super block",
206812659251SNaohiro Aota 				  cache->start);
206912659251SNaohiro Aota 			return -EUCLEAN;
207012659251SNaohiro Aota 		}
207112659251SNaohiro Aota 
20724358d963SJosef Bacik 		while (nr--) {
207396f9b0f2SNikolay Borisov 			u64 len = min_t(u64, stripe_len,
207496f9b0f2SNikolay Borisov 				cache->start + cache->length - logical[nr]);
20754358d963SJosef Bacik 
20764358d963SJosef Bacik 			cache->bytes_super += len;
207796f9b0f2SNikolay Borisov 			ret = btrfs_add_excluded_extent(fs_info, logical[nr],
207896f9b0f2SNikolay Borisov 							len);
20794358d963SJosef Bacik 			if (ret) {
20804358d963SJosef Bacik 				kfree(logical);
20814358d963SJosef Bacik 				return ret;
20824358d963SJosef Bacik 			}
20834358d963SJosef Bacik 		}
20844358d963SJosef Bacik 
20854358d963SJosef Bacik 		kfree(logical);
20864358d963SJosef Bacik 	}
20874358d963SJosef Bacik 	return 0;
20884358d963SJosef Bacik }
20894358d963SJosef Bacik 
209032da5386SDavid Sterba static struct btrfs_block_group *btrfs_create_block_group_cache(
20919afc6649SQu Wenruo 		struct btrfs_fs_info *fs_info, u64 start)
20924358d963SJosef Bacik {
209332da5386SDavid Sterba 	struct btrfs_block_group *cache;
20944358d963SJosef Bacik 
20954358d963SJosef Bacik 	cache = kzalloc(sizeof(*cache), GFP_NOFS);
20964358d963SJosef Bacik 	if (!cache)
20974358d963SJosef Bacik 		return NULL;
20984358d963SJosef Bacik 
20994358d963SJosef Bacik 	cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
21004358d963SJosef Bacik 					GFP_NOFS);
21014358d963SJosef Bacik 	if (!cache->free_space_ctl) {
21024358d963SJosef Bacik 		kfree(cache);
21034358d963SJosef Bacik 		return NULL;
21044358d963SJosef Bacik 	}
21054358d963SJosef Bacik 
2106b3470b5dSDavid Sterba 	cache->start = start;
21074358d963SJosef Bacik 
21084358d963SJosef Bacik 	cache->fs_info = fs_info;
21094358d963SJosef Bacik 	cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
21104358d963SJosef Bacik 
21116e80d4f8SDennis Zhou 	cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
21126e80d4f8SDennis Zhou 
211348aaeebeSJosef Bacik 	refcount_set(&cache->refs, 1);
21144358d963SJosef Bacik 	spin_lock_init(&cache->lock);
21154358d963SJosef Bacik 	init_rwsem(&cache->data_rwsem);
21164358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->list);
21174358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->cluster_list);
21184358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->bg_list);
21194358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->ro_list);
2120b0643e59SDennis Zhou 	INIT_LIST_HEAD(&cache->discard_list);
21214358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->dirty_list);
21224358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->io_list);
2123afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&cache->active_bg_list);
2124cd79909bSJosef Bacik 	btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
21256b7304afSFilipe Manana 	atomic_set(&cache->frozen, 0);
21264358d963SJosef Bacik 	mutex_init(&cache->free_space_lock);
2127c29abab4SJosef Bacik 	cache->full_stripe_locks_root.root = RB_ROOT;
2128c29abab4SJosef Bacik 	mutex_init(&cache->full_stripe_locks_root.lock);
21294358d963SJosef Bacik 
21304358d963SJosef Bacik 	return cache;
21314358d963SJosef Bacik }
21324358d963SJosef Bacik 
21334358d963SJosef Bacik /*
21344358d963SJosef Bacik  * Iterate all chunks and verify that each of them has the corresponding block
21354358d963SJosef Bacik  * group
21364358d963SJosef Bacik  */
21374358d963SJosef Bacik static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
21384358d963SJosef Bacik {
21394358d963SJosef Bacik 	struct extent_map_tree *map_tree = &fs_info->mapping_tree;
21404358d963SJosef Bacik 	struct extent_map *em;
214132da5386SDavid Sterba 	struct btrfs_block_group *bg;
21424358d963SJosef Bacik 	u64 start = 0;
21434358d963SJosef Bacik 	int ret = 0;
21444358d963SJosef Bacik 
21454358d963SJosef Bacik 	while (1) {
21464358d963SJosef Bacik 		read_lock(&map_tree->lock);
21474358d963SJosef Bacik 		/*
21484358d963SJosef Bacik 		 * lookup_extent_mapping will return the first extent map
21494358d963SJosef Bacik 		 * intersecting the range, so setting @len to 1 is enough to
21504358d963SJosef Bacik 		 * get the first chunk.
21514358d963SJosef Bacik 		 */
21524358d963SJosef Bacik 		em = lookup_extent_mapping(map_tree, start, 1);
21534358d963SJosef Bacik 		read_unlock(&map_tree->lock);
21544358d963SJosef Bacik 		if (!em)
21554358d963SJosef Bacik 			break;
21564358d963SJosef Bacik 
21574358d963SJosef Bacik 		bg = btrfs_lookup_block_group(fs_info, em->start);
21584358d963SJosef Bacik 		if (!bg) {
21594358d963SJosef Bacik 			btrfs_err(fs_info,
21604358d963SJosef Bacik 	"chunk start=%llu len=%llu doesn't have corresponding block group",
21614358d963SJosef Bacik 				     em->start, em->len);
21624358d963SJosef Bacik 			ret = -EUCLEAN;
21634358d963SJosef Bacik 			free_extent_map(em);
21644358d963SJosef Bacik 			break;
21654358d963SJosef Bacik 		}
2166b3470b5dSDavid Sterba 		if (bg->start != em->start || bg->length != em->len ||
21674358d963SJosef Bacik 		    (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
21684358d963SJosef Bacik 		    (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
21694358d963SJosef Bacik 			btrfs_err(fs_info,
21704358d963SJosef Bacik "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
21714358d963SJosef Bacik 				em->start, em->len,
21724358d963SJosef Bacik 				em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
2173b3470b5dSDavid Sterba 				bg->start, bg->length,
21744358d963SJosef Bacik 				bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
21754358d963SJosef Bacik 			ret = -EUCLEAN;
21764358d963SJosef Bacik 			free_extent_map(em);
21774358d963SJosef Bacik 			btrfs_put_block_group(bg);
21784358d963SJosef Bacik 			break;
21794358d963SJosef Bacik 		}
21804358d963SJosef Bacik 		start = em->start + em->len;
21814358d963SJosef Bacik 		free_extent_map(em);
21824358d963SJosef Bacik 		btrfs_put_block_group(bg);
21834358d963SJosef Bacik 	}
21844358d963SJosef Bacik 	return ret;
21854358d963SJosef Bacik }
21864358d963SJosef Bacik 
2187ffb9e0f0SQu Wenruo static int read_one_block_group(struct btrfs_fs_info *info,
21884afd2fe8SJohannes Thumshirn 				struct btrfs_block_group_item *bgi,
2189d49a2ddbSQu Wenruo 				const struct btrfs_key *key,
2190ffb9e0f0SQu Wenruo 				int need_clear)
2191ffb9e0f0SQu Wenruo {
219232da5386SDavid Sterba 	struct btrfs_block_group *cache;
2193ffb9e0f0SQu Wenruo 	const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
2194ffb9e0f0SQu Wenruo 	int ret;
2195ffb9e0f0SQu Wenruo 
2196d49a2ddbSQu Wenruo 	ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
2197ffb9e0f0SQu Wenruo 
21989afc6649SQu Wenruo 	cache = btrfs_create_block_group_cache(info, key->objectid);
2199ffb9e0f0SQu Wenruo 	if (!cache)
2200ffb9e0f0SQu Wenruo 		return -ENOMEM;
2201ffb9e0f0SQu Wenruo 
22024afd2fe8SJohannes Thumshirn 	cache->length = key->offset;
22034afd2fe8SJohannes Thumshirn 	cache->used = btrfs_stack_block_group_used(bgi);
22047248e0ceSQu Wenruo 	cache->commit_used = cache->used;
22054afd2fe8SJohannes Thumshirn 	cache->flags = btrfs_stack_block_group_flags(bgi);
2206f7238e50SJosef Bacik 	cache->global_root_id = btrfs_stack_block_group_chunk_objectid(bgi);
22079afc6649SQu Wenruo 
2208e3e39c72SMarcos Paulo de Souza 	set_free_space_tree_thresholds(cache);
2209e3e39c72SMarcos Paulo de Souza 
2210ffb9e0f0SQu Wenruo 	if (need_clear) {
2211ffb9e0f0SQu Wenruo 		/*
2212ffb9e0f0SQu Wenruo 		 * When we mount with old space cache, we need to
2213ffb9e0f0SQu Wenruo 		 * set BTRFS_DC_CLEAR and set dirty flag.
2214ffb9e0f0SQu Wenruo 		 *
2215ffb9e0f0SQu Wenruo 		 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
2216ffb9e0f0SQu Wenruo 		 *    truncate the old free space cache inode and
2217ffb9e0f0SQu Wenruo 		 *    setup a new one.
2218ffb9e0f0SQu Wenruo 		 * b) Setting 'dirty flag' makes sure that we flush
2219ffb9e0f0SQu Wenruo 		 *    the new space cache info onto disk.
2220ffb9e0f0SQu Wenruo 		 */
2221ffb9e0f0SQu Wenruo 		if (btrfs_test_opt(info, SPACE_CACHE))
2222ffb9e0f0SQu Wenruo 			cache->disk_cache_state = BTRFS_DC_CLEAR;
2223ffb9e0f0SQu Wenruo 	}
2224ffb9e0f0SQu Wenruo 	if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
2225ffb9e0f0SQu Wenruo 	    (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
2226ffb9e0f0SQu Wenruo 			btrfs_err(info,
2227ffb9e0f0SQu Wenruo "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2228ffb9e0f0SQu Wenruo 				  cache->start);
2229ffb9e0f0SQu Wenruo 			ret = -EINVAL;
2230ffb9e0f0SQu Wenruo 			goto error;
2231ffb9e0f0SQu Wenruo 	}
2232ffb9e0f0SQu Wenruo 
2233a94794d5SNaohiro Aota 	ret = btrfs_load_block_group_zone_info(cache, false);
223408e11a3dSNaohiro Aota 	if (ret) {
223508e11a3dSNaohiro Aota 		btrfs_err(info, "zoned: failed to load zone info of bg %llu",
223608e11a3dSNaohiro Aota 			  cache->start);
223708e11a3dSNaohiro Aota 		goto error;
223808e11a3dSNaohiro Aota 	}
223908e11a3dSNaohiro Aota 
2240ffb9e0f0SQu Wenruo 	/*
2241ffb9e0f0SQu Wenruo 	 * We need to exclude the super stripes now so that the space info has
2242ffb9e0f0SQu Wenruo 	 * super bytes accounted for, otherwise we'll think we have more space
2243ffb9e0f0SQu Wenruo 	 * than we actually do.
2244ffb9e0f0SQu Wenruo 	 */
2245ffb9e0f0SQu Wenruo 	ret = exclude_super_stripes(cache);
2246ffb9e0f0SQu Wenruo 	if (ret) {
2247ffb9e0f0SQu Wenruo 		/* We may have excluded something, so call this just in case. */
2248ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2249ffb9e0f0SQu Wenruo 		goto error;
2250ffb9e0f0SQu Wenruo 	}
2251ffb9e0f0SQu Wenruo 
2252ffb9e0f0SQu Wenruo 	/*
2253169e0da9SNaohiro Aota 	 * For zoned filesystem, space after the allocation offset is the only
2254169e0da9SNaohiro Aota 	 * free space for a block group. So, we don't need any caching work.
2255169e0da9SNaohiro Aota 	 * btrfs_calc_zone_unusable() will set the amount of free space and
2256169e0da9SNaohiro Aota 	 * zone_unusable space.
2257169e0da9SNaohiro Aota 	 *
2258169e0da9SNaohiro Aota 	 * For regular filesystem, check for two cases, either we are full, and
2259169e0da9SNaohiro Aota 	 * therefore don't need to bother with the caching work since we won't
2260169e0da9SNaohiro Aota 	 * find any space, or we are empty, and we can just add all the space
2261169e0da9SNaohiro Aota 	 * in and be done with it.  This saves us _a_lot_ of time, particularly
2262169e0da9SNaohiro Aota 	 * in the full case.
2263ffb9e0f0SQu Wenruo 	 */
2264169e0da9SNaohiro Aota 	if (btrfs_is_zoned(info)) {
2265169e0da9SNaohiro Aota 		btrfs_calc_zone_unusable(cache);
2266c46c4247SNaohiro Aota 		/* Should not have any excluded extents. Just in case, though. */
2267c46c4247SNaohiro Aota 		btrfs_free_excluded_extents(cache);
2268169e0da9SNaohiro Aota 	} else if (cache->length == cache->used) {
2269ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
2270ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2271ffb9e0f0SQu Wenruo 	} else if (cache->used == 0) {
2272ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
22739afc6649SQu Wenruo 		add_new_free_space(cache, cache->start,
22749afc6649SQu Wenruo 				   cache->start + cache->length);
2275ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2276ffb9e0f0SQu Wenruo 	}
2277ffb9e0f0SQu Wenruo 
2278ffb9e0f0SQu Wenruo 	ret = btrfs_add_block_group_cache(info, cache);
2279ffb9e0f0SQu Wenruo 	if (ret) {
2280ffb9e0f0SQu Wenruo 		btrfs_remove_free_space_cache(cache);
2281ffb9e0f0SQu Wenruo 		goto error;
2282ffb9e0f0SQu Wenruo 	}
2283ffb9e0f0SQu Wenruo 	trace_btrfs_add_block_group(info, cache, 0);
2284723de71dSJosef Bacik 	btrfs_add_bg_to_space_info(info, cache);
2285ffb9e0f0SQu Wenruo 
2286ffb9e0f0SQu Wenruo 	set_avail_alloc_bits(info, cache->flags);
2287a09f23c3SAnand Jain 	if (btrfs_chunk_writeable(info, cache->start)) {
2288a09f23c3SAnand Jain 		if (cache->used == 0) {
2289ffb9e0f0SQu Wenruo 			ASSERT(list_empty(&cache->bg_list));
22906e80d4f8SDennis Zhou 			if (btrfs_test_opt(info, DISCARD_ASYNC))
22916e80d4f8SDennis Zhou 				btrfs_discard_queue_work(&info->discard_ctl, cache);
22926e80d4f8SDennis Zhou 			else
2293ffb9e0f0SQu Wenruo 				btrfs_mark_bg_unused(cache);
2294ffb9e0f0SQu Wenruo 		}
2295a09f23c3SAnand Jain 	} else {
2296a09f23c3SAnand Jain 		inc_block_group_ro(cache, 1);
2297a09f23c3SAnand Jain 	}
2298a09f23c3SAnand Jain 
2299ffb9e0f0SQu Wenruo 	return 0;
2300ffb9e0f0SQu Wenruo error:
2301ffb9e0f0SQu Wenruo 	btrfs_put_block_group(cache);
2302ffb9e0f0SQu Wenruo 	return ret;
2303ffb9e0f0SQu Wenruo }
2304ffb9e0f0SQu Wenruo 
230542437a63SJosef Bacik static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
230642437a63SJosef Bacik {
230742437a63SJosef Bacik 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
230842437a63SJosef Bacik 	struct rb_node *node;
230942437a63SJosef Bacik 	int ret = 0;
231042437a63SJosef Bacik 
231142437a63SJosef Bacik 	for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
231242437a63SJosef Bacik 		struct extent_map *em;
231342437a63SJosef Bacik 		struct map_lookup *map;
231442437a63SJosef Bacik 		struct btrfs_block_group *bg;
231542437a63SJosef Bacik 
231642437a63SJosef Bacik 		em = rb_entry(node, struct extent_map, rb_node);
231742437a63SJosef Bacik 		map = em->map_lookup;
231842437a63SJosef Bacik 		bg = btrfs_create_block_group_cache(fs_info, em->start);
231942437a63SJosef Bacik 		if (!bg) {
232042437a63SJosef Bacik 			ret = -ENOMEM;
232142437a63SJosef Bacik 			break;
232242437a63SJosef Bacik 		}
232342437a63SJosef Bacik 
232442437a63SJosef Bacik 		/* Fill dummy cache as FULL */
232542437a63SJosef Bacik 		bg->length = em->len;
232642437a63SJosef Bacik 		bg->flags = map->type;
232742437a63SJosef Bacik 		bg->cached = BTRFS_CACHE_FINISHED;
232842437a63SJosef Bacik 		bg->used = em->len;
232942437a63SJosef Bacik 		bg->flags = map->type;
233042437a63SJosef Bacik 		ret = btrfs_add_block_group_cache(fs_info, bg);
23312b29726cSQu Wenruo 		/*
23322b29726cSQu Wenruo 		 * We may have some valid block group cache added already, in
23332b29726cSQu Wenruo 		 * that case we skip to the next one.
23342b29726cSQu Wenruo 		 */
23352b29726cSQu Wenruo 		if (ret == -EEXIST) {
23362b29726cSQu Wenruo 			ret = 0;
23372b29726cSQu Wenruo 			btrfs_put_block_group(bg);
23382b29726cSQu Wenruo 			continue;
23392b29726cSQu Wenruo 		}
23402b29726cSQu Wenruo 
234142437a63SJosef Bacik 		if (ret) {
234242437a63SJosef Bacik 			btrfs_remove_free_space_cache(bg);
234342437a63SJosef Bacik 			btrfs_put_block_group(bg);
234442437a63SJosef Bacik 			break;
234542437a63SJosef Bacik 		}
23462b29726cSQu Wenruo 
2347723de71dSJosef Bacik 		btrfs_add_bg_to_space_info(fs_info, bg);
234842437a63SJosef Bacik 
234942437a63SJosef Bacik 		set_avail_alloc_bits(fs_info, bg->flags);
235042437a63SJosef Bacik 	}
235142437a63SJosef Bacik 	if (!ret)
235242437a63SJosef Bacik 		btrfs_init_global_block_rsv(fs_info);
235342437a63SJosef Bacik 	return ret;
235442437a63SJosef Bacik }
235542437a63SJosef Bacik 
23564358d963SJosef Bacik int btrfs_read_block_groups(struct btrfs_fs_info *info)
23574358d963SJosef Bacik {
2358dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(info);
23594358d963SJosef Bacik 	struct btrfs_path *path;
23604358d963SJosef Bacik 	int ret;
236132da5386SDavid Sterba 	struct btrfs_block_group *cache;
23624358d963SJosef Bacik 	struct btrfs_space_info *space_info;
23634358d963SJosef Bacik 	struct btrfs_key key;
23644358d963SJosef Bacik 	int need_clear = 0;
23654358d963SJosef Bacik 	u64 cache_gen;
23664358d963SJosef Bacik 
236781d5d614SQu Wenruo 	/*
236881d5d614SQu Wenruo 	 * Either no extent root (with ibadroots rescue option) or we have
236981d5d614SQu Wenruo 	 * unsupported RO options. The fs can never be mounted read-write, so no
237081d5d614SQu Wenruo 	 * need to waste time searching block group items.
237181d5d614SQu Wenruo 	 *
237281d5d614SQu Wenruo 	 * This also allows new extent tree related changes to be RO compat,
237381d5d614SQu Wenruo 	 * no need for a full incompat flag.
237481d5d614SQu Wenruo 	 */
237581d5d614SQu Wenruo 	if (!root || (btrfs_super_compat_ro_flags(info->super_copy) &
237681d5d614SQu Wenruo 		      ~BTRFS_FEATURE_COMPAT_RO_SUPP))
237742437a63SJosef Bacik 		return fill_dummy_bgs(info);
237842437a63SJosef Bacik 
23794358d963SJosef Bacik 	key.objectid = 0;
23804358d963SJosef Bacik 	key.offset = 0;
23814358d963SJosef Bacik 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
23824358d963SJosef Bacik 	path = btrfs_alloc_path();
23834358d963SJosef Bacik 	if (!path)
23844358d963SJosef Bacik 		return -ENOMEM;
23854358d963SJosef Bacik 
23864358d963SJosef Bacik 	cache_gen = btrfs_super_cache_generation(info->super_copy);
23874358d963SJosef Bacik 	if (btrfs_test_opt(info, SPACE_CACHE) &&
23884358d963SJosef Bacik 	    btrfs_super_generation(info->super_copy) != cache_gen)
23894358d963SJosef Bacik 		need_clear = 1;
23904358d963SJosef Bacik 	if (btrfs_test_opt(info, CLEAR_CACHE))
23914358d963SJosef Bacik 		need_clear = 1;
23924358d963SJosef Bacik 
23934358d963SJosef Bacik 	while (1) {
23944afd2fe8SJohannes Thumshirn 		struct btrfs_block_group_item bgi;
23954afd2fe8SJohannes Thumshirn 		struct extent_buffer *leaf;
23964afd2fe8SJohannes Thumshirn 		int slot;
23974afd2fe8SJohannes Thumshirn 
23984358d963SJosef Bacik 		ret = find_first_block_group(info, path, &key);
23994358d963SJosef Bacik 		if (ret > 0)
24004358d963SJosef Bacik 			break;
24014358d963SJosef Bacik 		if (ret != 0)
24024358d963SJosef Bacik 			goto error;
24034358d963SJosef Bacik 
24044afd2fe8SJohannes Thumshirn 		leaf = path->nodes[0];
24054afd2fe8SJohannes Thumshirn 		slot = path->slots[0];
24064afd2fe8SJohannes Thumshirn 
24074afd2fe8SJohannes Thumshirn 		read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
24084afd2fe8SJohannes Thumshirn 				   sizeof(bgi));
24094afd2fe8SJohannes Thumshirn 
24104afd2fe8SJohannes Thumshirn 		btrfs_item_key_to_cpu(leaf, &key, slot);
24114afd2fe8SJohannes Thumshirn 		btrfs_release_path(path);
24124afd2fe8SJohannes Thumshirn 		ret = read_one_block_group(info, &bgi, &key, need_clear);
2413ffb9e0f0SQu Wenruo 		if (ret < 0)
24144358d963SJosef Bacik 			goto error;
2415ffb9e0f0SQu Wenruo 		key.objectid += key.offset;
2416ffb9e0f0SQu Wenruo 		key.offset = 0;
24174358d963SJosef Bacik 	}
24187837fa88SJosef Bacik 	btrfs_release_path(path);
24194358d963SJosef Bacik 
242072804905SJosef Bacik 	list_for_each_entry(space_info, &info->space_info, list) {
242149ea112dSJosef Bacik 		int i;
242249ea112dSJosef Bacik 
242349ea112dSJosef Bacik 		for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
242449ea112dSJosef Bacik 			if (list_empty(&space_info->block_groups[i]))
242549ea112dSJosef Bacik 				continue;
242649ea112dSJosef Bacik 			cache = list_first_entry(&space_info->block_groups[i],
242749ea112dSJosef Bacik 						 struct btrfs_block_group,
242849ea112dSJosef Bacik 						 list);
242949ea112dSJosef Bacik 			btrfs_sysfs_add_block_group_type(cache);
243049ea112dSJosef Bacik 		}
243149ea112dSJosef Bacik 
24324358d963SJosef Bacik 		if (!(btrfs_get_alloc_profile(info, space_info->flags) &
24334358d963SJosef Bacik 		      (BTRFS_BLOCK_GROUP_RAID10 |
24344358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID1_MASK |
24354358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID56_MASK |
24364358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_DUP)))
24374358d963SJosef Bacik 			continue;
24384358d963SJosef Bacik 		/*
24394358d963SJosef Bacik 		 * Avoid allocating from un-mirrored block group if there are
24404358d963SJosef Bacik 		 * mirrored block groups.
24414358d963SJosef Bacik 		 */
24424358d963SJosef Bacik 		list_for_each_entry(cache,
24434358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_RAID0],
24444358d963SJosef Bacik 				list)
2445e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
24464358d963SJosef Bacik 		list_for_each_entry(cache,
24474358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_SINGLE],
24484358d963SJosef Bacik 				list)
2449e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
24504358d963SJosef Bacik 	}
24514358d963SJosef Bacik 
24524358d963SJosef Bacik 	btrfs_init_global_block_rsv(info);
24534358d963SJosef Bacik 	ret = check_chunk_block_group_mappings(info);
24544358d963SJosef Bacik error:
24554358d963SJosef Bacik 	btrfs_free_path(path);
24562b29726cSQu Wenruo 	/*
24572b29726cSQu Wenruo 	 * We've hit some error while reading the extent tree, and have
24582b29726cSQu Wenruo 	 * rescue=ibadroots mount option.
24592b29726cSQu Wenruo 	 * Try to fill the tree using dummy block groups so that the user can
24602b29726cSQu Wenruo 	 * continue to mount and grab their data.
24612b29726cSQu Wenruo 	 */
24622b29726cSQu Wenruo 	if (ret && btrfs_test_opt(info, IGNOREBADROOTS))
24632b29726cSQu Wenruo 		ret = fill_dummy_bgs(info);
24644358d963SJosef Bacik 	return ret;
24654358d963SJosef Bacik }
24664358d963SJosef Bacik 
246779bd3712SFilipe Manana /*
246879bd3712SFilipe Manana  * This function, insert_block_group_item(), belongs to the phase 2 of chunk
246979bd3712SFilipe Manana  * allocation.
247079bd3712SFilipe Manana  *
247179bd3712SFilipe Manana  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
247279bd3712SFilipe Manana  * phases.
247379bd3712SFilipe Manana  */
247497f4728aSQu Wenruo static int insert_block_group_item(struct btrfs_trans_handle *trans,
247597f4728aSQu Wenruo 				   struct btrfs_block_group *block_group)
247697f4728aSQu Wenruo {
247797f4728aSQu Wenruo 	struct btrfs_fs_info *fs_info = trans->fs_info;
247897f4728aSQu Wenruo 	struct btrfs_block_group_item bgi;
2479dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
248097f4728aSQu Wenruo 	struct btrfs_key key;
2481675dfe12SFilipe Manana 	u64 old_commit_used;
2482675dfe12SFilipe Manana 	int ret;
248397f4728aSQu Wenruo 
248497f4728aSQu Wenruo 	spin_lock(&block_group->lock);
248597f4728aSQu Wenruo 	btrfs_set_stack_block_group_used(&bgi, block_group->used);
248697f4728aSQu Wenruo 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
2487f7238e50SJosef Bacik 						   block_group->global_root_id);
248897f4728aSQu Wenruo 	btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2489675dfe12SFilipe Manana 	old_commit_used = block_group->commit_used;
2490675dfe12SFilipe Manana 	block_group->commit_used = block_group->used;
249197f4728aSQu Wenruo 	key.objectid = block_group->start;
249297f4728aSQu Wenruo 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
249397f4728aSQu Wenruo 	key.offset = block_group->length;
249497f4728aSQu Wenruo 	spin_unlock(&block_group->lock);
249597f4728aSQu Wenruo 
2496675dfe12SFilipe Manana 	ret = btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2497675dfe12SFilipe Manana 	if (ret < 0) {
2498675dfe12SFilipe Manana 		spin_lock(&block_group->lock);
2499675dfe12SFilipe Manana 		block_group->commit_used = old_commit_used;
2500675dfe12SFilipe Manana 		spin_unlock(&block_group->lock);
2501675dfe12SFilipe Manana 	}
2502675dfe12SFilipe Manana 
2503675dfe12SFilipe Manana 	return ret;
250497f4728aSQu Wenruo }
250597f4728aSQu Wenruo 
25062eadb9e7SNikolay Borisov static int insert_dev_extent(struct btrfs_trans_handle *trans,
25072eadb9e7SNikolay Borisov 			    struct btrfs_device *device, u64 chunk_offset,
25082eadb9e7SNikolay Borisov 			    u64 start, u64 num_bytes)
25092eadb9e7SNikolay Borisov {
25102eadb9e7SNikolay Borisov 	struct btrfs_fs_info *fs_info = device->fs_info;
25112eadb9e7SNikolay Borisov 	struct btrfs_root *root = fs_info->dev_root;
25122eadb9e7SNikolay Borisov 	struct btrfs_path *path;
25132eadb9e7SNikolay Borisov 	struct btrfs_dev_extent *extent;
25142eadb9e7SNikolay Borisov 	struct extent_buffer *leaf;
25152eadb9e7SNikolay Borisov 	struct btrfs_key key;
25162eadb9e7SNikolay Borisov 	int ret;
25172eadb9e7SNikolay Borisov 
25182eadb9e7SNikolay Borisov 	WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
25192eadb9e7SNikolay Borisov 	WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
25202eadb9e7SNikolay Borisov 	path = btrfs_alloc_path();
25212eadb9e7SNikolay Borisov 	if (!path)
25222eadb9e7SNikolay Borisov 		return -ENOMEM;
25232eadb9e7SNikolay Borisov 
25242eadb9e7SNikolay Borisov 	key.objectid = device->devid;
25252eadb9e7SNikolay Borisov 	key.type = BTRFS_DEV_EXTENT_KEY;
25262eadb9e7SNikolay Borisov 	key.offset = start;
25272eadb9e7SNikolay Borisov 	ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent));
25282eadb9e7SNikolay Borisov 	if (ret)
25292eadb9e7SNikolay Borisov 		goto out;
25302eadb9e7SNikolay Borisov 
25312eadb9e7SNikolay Borisov 	leaf = path->nodes[0];
25322eadb9e7SNikolay Borisov 	extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
25332eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID);
25342eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_objectid(leaf, extent,
25352eadb9e7SNikolay Borisov 					    BTRFS_FIRST_CHUNK_TREE_OBJECTID);
25362eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
25372eadb9e7SNikolay Borisov 
25382eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_length(leaf, extent, num_bytes);
25392eadb9e7SNikolay Borisov 	btrfs_mark_buffer_dirty(leaf);
25402eadb9e7SNikolay Borisov out:
25412eadb9e7SNikolay Borisov 	btrfs_free_path(path);
25422eadb9e7SNikolay Borisov 	return ret;
25432eadb9e7SNikolay Borisov }
25442eadb9e7SNikolay Borisov 
25452eadb9e7SNikolay Borisov /*
25462eadb9e7SNikolay Borisov  * This function belongs to phase 2.
25472eadb9e7SNikolay Borisov  *
25482eadb9e7SNikolay Borisov  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
25492eadb9e7SNikolay Borisov  * phases.
25502eadb9e7SNikolay Borisov  */
25512eadb9e7SNikolay Borisov static int insert_dev_extents(struct btrfs_trans_handle *trans,
25522eadb9e7SNikolay Borisov 				   u64 chunk_offset, u64 chunk_size)
25532eadb9e7SNikolay Borisov {
25542eadb9e7SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
25552eadb9e7SNikolay Borisov 	struct btrfs_device *device;
25562eadb9e7SNikolay Borisov 	struct extent_map *em;
25572eadb9e7SNikolay Borisov 	struct map_lookup *map;
25582eadb9e7SNikolay Borisov 	u64 dev_offset;
25592eadb9e7SNikolay Borisov 	u64 stripe_size;
25602eadb9e7SNikolay Borisov 	int i;
25612eadb9e7SNikolay Borisov 	int ret = 0;
25622eadb9e7SNikolay Borisov 
25632eadb9e7SNikolay Borisov 	em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
25642eadb9e7SNikolay Borisov 	if (IS_ERR(em))
25652eadb9e7SNikolay Borisov 		return PTR_ERR(em);
25662eadb9e7SNikolay Borisov 
25672eadb9e7SNikolay Borisov 	map = em->map_lookup;
25682eadb9e7SNikolay Borisov 	stripe_size = em->orig_block_len;
25692eadb9e7SNikolay Borisov 
25702eadb9e7SNikolay Borisov 	/*
25712eadb9e7SNikolay Borisov 	 * Take the device list mutex to prevent races with the final phase of
25722eadb9e7SNikolay Borisov 	 * a device replace operation that replaces the device object associated
25732eadb9e7SNikolay Borisov 	 * with the map's stripes, because the device object's id can change
25742eadb9e7SNikolay Borisov 	 * at any time during that final phase of the device replace operation
25752eadb9e7SNikolay Borisov 	 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
25762eadb9e7SNikolay Borisov 	 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
25772eadb9e7SNikolay Borisov 	 * resulting in persisting a device extent item with such ID.
25782eadb9e7SNikolay Borisov 	 */
25792eadb9e7SNikolay Borisov 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
25802eadb9e7SNikolay Borisov 	for (i = 0; i < map->num_stripes; i++) {
25812eadb9e7SNikolay Borisov 		device = map->stripes[i].dev;
25822eadb9e7SNikolay Borisov 		dev_offset = map->stripes[i].physical;
25832eadb9e7SNikolay Borisov 
25842eadb9e7SNikolay Borisov 		ret = insert_dev_extent(trans, device, chunk_offset, dev_offset,
25852eadb9e7SNikolay Borisov 				       stripe_size);
25862eadb9e7SNikolay Borisov 		if (ret)
25872eadb9e7SNikolay Borisov 			break;
25882eadb9e7SNikolay Borisov 	}
25892eadb9e7SNikolay Borisov 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
25902eadb9e7SNikolay Borisov 
25912eadb9e7SNikolay Borisov 	free_extent_map(em);
25922eadb9e7SNikolay Borisov 	return ret;
25932eadb9e7SNikolay Borisov }
25942eadb9e7SNikolay Borisov 
259579bd3712SFilipe Manana /*
259679bd3712SFilipe Manana  * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
259779bd3712SFilipe Manana  * chunk allocation.
259879bd3712SFilipe Manana  *
259979bd3712SFilipe Manana  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
260079bd3712SFilipe Manana  * phases.
260179bd3712SFilipe Manana  */
26024358d963SJosef Bacik void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
26034358d963SJosef Bacik {
26044358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
260532da5386SDavid Sterba 	struct btrfs_block_group *block_group;
26064358d963SJosef Bacik 	int ret = 0;
26074358d963SJosef Bacik 
26084358d963SJosef Bacik 	while (!list_empty(&trans->new_bgs)) {
260949ea112dSJosef Bacik 		int index;
261049ea112dSJosef Bacik 
26114358d963SJosef Bacik 		block_group = list_first_entry(&trans->new_bgs,
261232da5386SDavid Sterba 					       struct btrfs_block_group,
26134358d963SJosef Bacik 					       bg_list);
26144358d963SJosef Bacik 		if (ret)
26154358d963SJosef Bacik 			goto next;
26164358d963SJosef Bacik 
261749ea112dSJosef Bacik 		index = btrfs_bg_flags_to_raid_index(block_group->flags);
261849ea112dSJosef Bacik 
261997f4728aSQu Wenruo 		ret = insert_block_group_item(trans, block_group);
26204358d963SJosef Bacik 		if (ret)
26214358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
26223349b57fSJosef Bacik 		if (!test_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED,
26233349b57fSJosef Bacik 			      &block_group->runtime_flags)) {
262479bd3712SFilipe Manana 			mutex_lock(&fs_info->chunk_mutex);
262579bd3712SFilipe Manana 			ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group);
262679bd3712SFilipe Manana 			mutex_unlock(&fs_info->chunk_mutex);
262779bd3712SFilipe Manana 			if (ret)
262879bd3712SFilipe Manana 				btrfs_abort_transaction(trans, ret);
262979bd3712SFilipe Manana 		}
26302eadb9e7SNikolay Borisov 		ret = insert_dev_extents(trans, block_group->start,
263197f4728aSQu Wenruo 					 block_group->length);
26324358d963SJosef Bacik 		if (ret)
26334358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
26344358d963SJosef Bacik 		add_block_group_free_space(trans, block_group);
263549ea112dSJosef Bacik 
263649ea112dSJosef Bacik 		/*
263749ea112dSJosef Bacik 		 * If we restriped during balance, we may have added a new raid
263849ea112dSJosef Bacik 		 * type, so now add the sysfs entries when it is safe to do so.
263949ea112dSJosef Bacik 		 * We don't have to worry about locking here as it's handled in
264049ea112dSJosef Bacik 		 * btrfs_sysfs_add_block_group_type.
264149ea112dSJosef Bacik 		 */
264249ea112dSJosef Bacik 		if (block_group->space_info->block_group_kobjs[index] == NULL)
264349ea112dSJosef Bacik 			btrfs_sysfs_add_block_group_type(block_group);
264449ea112dSJosef Bacik 
26454358d963SJosef Bacik 		/* Already aborted the transaction if it failed. */
26464358d963SJosef Bacik next:
26474358d963SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
26484358d963SJosef Bacik 		list_del_init(&block_group->bg_list);
26494358d963SJosef Bacik 	}
26504358d963SJosef Bacik 	btrfs_trans_release_chunk_metadata(trans);
26514358d963SJosef Bacik }
26524358d963SJosef Bacik 
2653f7238e50SJosef Bacik /*
2654f7238e50SJosef Bacik  * For extent tree v2 we use the block_group_item->chunk_offset to point at our
2655f7238e50SJosef Bacik  * global root id.  For v1 it's always set to BTRFS_FIRST_CHUNK_TREE_OBJECTID.
2656f7238e50SJosef Bacik  */
2657f7238e50SJosef Bacik static u64 calculate_global_root_id(struct btrfs_fs_info *fs_info, u64 offset)
2658f7238e50SJosef Bacik {
2659f7238e50SJosef Bacik 	u64 div = SZ_1G;
2660f7238e50SJosef Bacik 	u64 index;
2661f7238e50SJosef Bacik 
2662f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2663f7238e50SJosef Bacik 		return BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2664f7238e50SJosef Bacik 
2665f7238e50SJosef Bacik 	/* If we have a smaller fs index based on 128MiB. */
2666f7238e50SJosef Bacik 	if (btrfs_super_total_bytes(fs_info->super_copy) <= (SZ_1G * 10ULL))
2667f7238e50SJosef Bacik 		div = SZ_128M;
2668f7238e50SJosef Bacik 
2669f7238e50SJosef Bacik 	offset = div64_u64(offset, div);
2670f7238e50SJosef Bacik 	div64_u64_rem(offset, fs_info->nr_global_roots, &index);
2671f7238e50SJosef Bacik 	return index;
2672f7238e50SJosef Bacik }
2673f7238e50SJosef Bacik 
267479bd3712SFilipe Manana struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
2675*5758d1bdSFilipe Manana 						 u64 type,
267679bd3712SFilipe Manana 						 u64 chunk_offset, u64 size)
26774358d963SJosef Bacik {
26784358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
267932da5386SDavid Sterba 	struct btrfs_block_group *cache;
26804358d963SJosef Bacik 	int ret;
26814358d963SJosef Bacik 
26824358d963SJosef Bacik 	btrfs_set_log_full_commit(trans);
26834358d963SJosef Bacik 
26849afc6649SQu Wenruo 	cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
26854358d963SJosef Bacik 	if (!cache)
268679bd3712SFilipe Manana 		return ERR_PTR(-ENOMEM);
26874358d963SJosef Bacik 
26889afc6649SQu Wenruo 	cache->length = size;
2689e3e39c72SMarcos Paulo de Souza 	set_free_space_tree_thresholds(cache);
26904358d963SJosef Bacik 	cache->flags = type;
26914358d963SJosef Bacik 	cache->cached = BTRFS_CACHE_FINISHED;
2692f7238e50SJosef Bacik 	cache->global_root_id = calculate_global_root_id(fs_info, cache->start);
2693f7238e50SJosef Bacik 
2694997e3e2eSBoris Burkov 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
26950d7764ffSDavid Sterba 		set_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE, &cache->runtime_flags);
269608e11a3dSNaohiro Aota 
2697a94794d5SNaohiro Aota 	ret = btrfs_load_block_group_zone_info(cache, true);
269808e11a3dSNaohiro Aota 	if (ret) {
269908e11a3dSNaohiro Aota 		btrfs_put_block_group(cache);
270079bd3712SFilipe Manana 		return ERR_PTR(ret);
270108e11a3dSNaohiro Aota 	}
270208e11a3dSNaohiro Aota 
27034358d963SJosef Bacik 	ret = exclude_super_stripes(cache);
27044358d963SJosef Bacik 	if (ret) {
27054358d963SJosef Bacik 		/* We may have excluded something, so call this just in case */
27064358d963SJosef Bacik 		btrfs_free_excluded_extents(cache);
27074358d963SJosef Bacik 		btrfs_put_block_group(cache);
270879bd3712SFilipe Manana 		return ERR_PTR(ret);
27094358d963SJosef Bacik 	}
27104358d963SJosef Bacik 
27114358d963SJosef Bacik 	add_new_free_space(cache, chunk_offset, chunk_offset + size);
27124358d963SJosef Bacik 
27134358d963SJosef Bacik 	btrfs_free_excluded_extents(cache);
27144358d963SJosef Bacik 
27154358d963SJosef Bacik 	/*
27164358d963SJosef Bacik 	 * Ensure the corresponding space_info object is created and
27174358d963SJosef Bacik 	 * assigned to our block group. We want our bg to be added to the rbtree
27184358d963SJosef Bacik 	 * with its ->space_info set.
27194358d963SJosef Bacik 	 */
27204358d963SJosef Bacik 	cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
27214358d963SJosef Bacik 	ASSERT(cache->space_info);
27224358d963SJosef Bacik 
27234358d963SJosef Bacik 	ret = btrfs_add_block_group_cache(fs_info, cache);
27244358d963SJosef Bacik 	if (ret) {
27254358d963SJosef Bacik 		btrfs_remove_free_space_cache(cache);
27264358d963SJosef Bacik 		btrfs_put_block_group(cache);
272779bd3712SFilipe Manana 		return ERR_PTR(ret);
27284358d963SJosef Bacik 	}
27294358d963SJosef Bacik 
27304358d963SJosef Bacik 	/*
27314358d963SJosef Bacik 	 * Now that our block group has its ->space_info set and is inserted in
27324358d963SJosef Bacik 	 * the rbtree, update the space info's counters.
27334358d963SJosef Bacik 	 */
27344358d963SJosef Bacik 	trace_btrfs_add_block_group(fs_info, cache, 1);
2735723de71dSJosef Bacik 	btrfs_add_bg_to_space_info(fs_info, cache);
27364358d963SJosef Bacik 	btrfs_update_global_block_rsv(fs_info);
27374358d963SJosef Bacik 
27389d4b0a12SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
27399d4b0a12SJosef Bacik 	if (btrfs_should_fragment_free_space(cache)) {
2740*5758d1bdSFilipe Manana 		cache->space_info->bytes_used += size >> 1;
27419d4b0a12SJosef Bacik 		fragment_free_space(cache);
27429d4b0a12SJosef Bacik 	}
27439d4b0a12SJosef Bacik #endif
27444358d963SJosef Bacik 
27454358d963SJosef Bacik 	list_add_tail(&cache->bg_list, &trans->new_bgs);
27464358d963SJosef Bacik 	trans->delayed_ref_updates++;
27474358d963SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
27484358d963SJosef Bacik 
27494358d963SJosef Bacik 	set_avail_alloc_bits(fs_info, type);
275079bd3712SFilipe Manana 	return cache;
27514358d963SJosef Bacik }
275226ce2095SJosef Bacik 
2753b12de528SQu Wenruo /*
2754b12de528SQu Wenruo  * Mark one block group RO, can be called several times for the same block
2755b12de528SQu Wenruo  * group.
2756b12de528SQu Wenruo  *
2757b12de528SQu Wenruo  * @cache:		the destination block group
2758b12de528SQu Wenruo  * @do_chunk_alloc:	whether need to do chunk pre-allocation, this is to
2759b12de528SQu Wenruo  * 			ensure we still have some free space after marking this
2760b12de528SQu Wenruo  * 			block group RO.
2761b12de528SQu Wenruo  */
2762b12de528SQu Wenruo int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2763b12de528SQu Wenruo 			     bool do_chunk_alloc)
276426ce2095SJosef Bacik {
276526ce2095SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
276626ce2095SJosef Bacik 	struct btrfs_trans_handle *trans;
2767dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
276826ce2095SJosef Bacik 	u64 alloc_flags;
276926ce2095SJosef Bacik 	int ret;
2770b6e9f16cSNikolay Borisov 	bool dirty_bg_running;
277126ce2095SJosef Bacik 
27722d192fc4SQu Wenruo 	/*
27732d192fc4SQu Wenruo 	 * This can only happen when we are doing read-only scrub on read-only
27742d192fc4SQu Wenruo 	 * mount.
27752d192fc4SQu Wenruo 	 * In that case we should not start a new transaction on read-only fs.
27762d192fc4SQu Wenruo 	 * Thus here we skip all chunk allocations.
27772d192fc4SQu Wenruo 	 */
27782d192fc4SQu Wenruo 	if (sb_rdonly(fs_info->sb)) {
27792d192fc4SQu Wenruo 		mutex_lock(&fs_info->ro_block_group_mutex);
27802d192fc4SQu Wenruo 		ret = inc_block_group_ro(cache, 0);
27812d192fc4SQu Wenruo 		mutex_unlock(&fs_info->ro_block_group_mutex);
27822d192fc4SQu Wenruo 		return ret;
27832d192fc4SQu Wenruo 	}
27842d192fc4SQu Wenruo 
2785b6e9f16cSNikolay Borisov 	do {
2786dfe8aec4SJosef Bacik 		trans = btrfs_join_transaction(root);
278726ce2095SJosef Bacik 		if (IS_ERR(trans))
278826ce2095SJosef Bacik 			return PTR_ERR(trans);
278926ce2095SJosef Bacik 
2790b6e9f16cSNikolay Borisov 		dirty_bg_running = false;
2791b6e9f16cSNikolay Borisov 
279226ce2095SJosef Bacik 		/*
2793b6e9f16cSNikolay Borisov 		 * We're not allowed to set block groups readonly after the dirty
2794b6e9f16cSNikolay Borisov 		 * block group cache has started writing.  If it already started,
2795b6e9f16cSNikolay Borisov 		 * back off and let this transaction commit.
279626ce2095SJosef Bacik 		 */
279726ce2095SJosef Bacik 		mutex_lock(&fs_info->ro_block_group_mutex);
279826ce2095SJosef Bacik 		if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
279926ce2095SJosef Bacik 			u64 transid = trans->transid;
280026ce2095SJosef Bacik 
280126ce2095SJosef Bacik 			mutex_unlock(&fs_info->ro_block_group_mutex);
280226ce2095SJosef Bacik 			btrfs_end_transaction(trans);
280326ce2095SJosef Bacik 
280426ce2095SJosef Bacik 			ret = btrfs_wait_for_commit(fs_info, transid);
280526ce2095SJosef Bacik 			if (ret)
280626ce2095SJosef Bacik 				return ret;
2807b6e9f16cSNikolay Borisov 			dirty_bg_running = true;
280826ce2095SJosef Bacik 		}
2809b6e9f16cSNikolay Borisov 	} while (dirty_bg_running);
281026ce2095SJosef Bacik 
2811b12de528SQu Wenruo 	if (do_chunk_alloc) {
281226ce2095SJosef Bacik 		/*
2813b12de528SQu Wenruo 		 * If we are changing raid levels, try to allocate a
2814b12de528SQu Wenruo 		 * corresponding block group with the new raid level.
281526ce2095SJosef Bacik 		 */
2816349e120eSJosef Bacik 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
281726ce2095SJosef Bacik 		if (alloc_flags != cache->flags) {
2818b12de528SQu Wenruo 			ret = btrfs_chunk_alloc(trans, alloc_flags,
2819b12de528SQu Wenruo 						CHUNK_ALLOC_FORCE);
282026ce2095SJosef Bacik 			/*
282126ce2095SJosef Bacik 			 * ENOSPC is allowed here, we may have enough space
2822b12de528SQu Wenruo 			 * already allocated at the new raid level to carry on
282326ce2095SJosef Bacik 			 */
282426ce2095SJosef Bacik 			if (ret == -ENOSPC)
282526ce2095SJosef Bacik 				ret = 0;
282626ce2095SJosef Bacik 			if (ret < 0)
282726ce2095SJosef Bacik 				goto out;
282826ce2095SJosef Bacik 		}
2829b12de528SQu Wenruo 	}
283026ce2095SJosef Bacik 
2831a7a63accSJosef Bacik 	ret = inc_block_group_ro(cache, 0);
2832195a49eaSFilipe Manana 	if (!do_chunk_alloc || ret == -ETXTBSY)
2833b12de528SQu Wenruo 		goto unlock_out;
283426ce2095SJosef Bacik 	if (!ret)
283526ce2095SJosef Bacik 		goto out;
283626ce2095SJosef Bacik 	alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
283726ce2095SJosef Bacik 	ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
283826ce2095SJosef Bacik 	if (ret < 0)
283926ce2095SJosef Bacik 		goto out;
2840b6a98021SNaohiro Aota 	/*
2841b6a98021SNaohiro Aota 	 * We have allocated a new chunk. We also need to activate that chunk to
2842b6a98021SNaohiro Aota 	 * grant metadata tickets for zoned filesystem.
2843b6a98021SNaohiro Aota 	 */
2844b6a98021SNaohiro Aota 	ret = btrfs_zoned_activate_one_bg(fs_info, cache->space_info, true);
2845b6a98021SNaohiro Aota 	if (ret < 0)
2846b6a98021SNaohiro Aota 		goto out;
2847b6a98021SNaohiro Aota 
2848e11c0406SJosef Bacik 	ret = inc_block_group_ro(cache, 0);
2849195a49eaSFilipe Manana 	if (ret == -ETXTBSY)
2850195a49eaSFilipe Manana 		goto unlock_out;
285126ce2095SJosef Bacik out:
285226ce2095SJosef Bacik 	if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2853349e120eSJosef Bacik 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
285426ce2095SJosef Bacik 		mutex_lock(&fs_info->chunk_mutex);
285526ce2095SJosef Bacik 		check_system_chunk(trans, alloc_flags);
285626ce2095SJosef Bacik 		mutex_unlock(&fs_info->chunk_mutex);
285726ce2095SJosef Bacik 	}
2858b12de528SQu Wenruo unlock_out:
285926ce2095SJosef Bacik 	mutex_unlock(&fs_info->ro_block_group_mutex);
286026ce2095SJosef Bacik 
286126ce2095SJosef Bacik 	btrfs_end_transaction(trans);
286226ce2095SJosef Bacik 	return ret;
286326ce2095SJosef Bacik }
286426ce2095SJosef Bacik 
286532da5386SDavid Sterba void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
286626ce2095SJosef Bacik {
286726ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
286826ce2095SJosef Bacik 	u64 num_bytes;
286926ce2095SJosef Bacik 
287026ce2095SJosef Bacik 	BUG_ON(!cache->ro);
287126ce2095SJosef Bacik 
287226ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
287326ce2095SJosef Bacik 	spin_lock(&cache->lock);
287426ce2095SJosef Bacik 	if (!--cache->ro) {
2875169e0da9SNaohiro Aota 		if (btrfs_is_zoned(cache->fs_info)) {
2876169e0da9SNaohiro Aota 			/* Migrate zone_unusable bytes back */
287798173255SNaohiro Aota 			cache->zone_unusable =
287898173255SNaohiro Aota 				(cache->alloc_offset - cache->used) +
287998173255SNaohiro Aota 				(cache->length - cache->zone_capacity);
2880169e0da9SNaohiro Aota 			sinfo->bytes_zone_unusable += cache->zone_unusable;
2881169e0da9SNaohiro Aota 			sinfo->bytes_readonly -= cache->zone_unusable;
2882169e0da9SNaohiro Aota 		}
2883f9f28e5bSNaohiro Aota 		num_bytes = cache->length - cache->reserved -
2884f9f28e5bSNaohiro Aota 			    cache->pinned - cache->bytes_super -
2885f9f28e5bSNaohiro Aota 			    cache->zone_unusable - cache->used;
2886f9f28e5bSNaohiro Aota 		sinfo->bytes_readonly -= num_bytes;
288726ce2095SJosef Bacik 		list_del_init(&cache->ro_list);
288826ce2095SJosef Bacik 	}
288926ce2095SJosef Bacik 	spin_unlock(&cache->lock);
289026ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
289126ce2095SJosef Bacik }
289277745c05SJosef Bacik 
28933be4d8efSQu Wenruo static int update_block_group_item(struct btrfs_trans_handle *trans,
289477745c05SJosef Bacik 				   struct btrfs_path *path,
289532da5386SDavid Sterba 				   struct btrfs_block_group *cache)
289677745c05SJosef Bacik {
289777745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
289877745c05SJosef Bacik 	int ret;
2899dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
290077745c05SJosef Bacik 	unsigned long bi;
290177745c05SJosef Bacik 	struct extent_buffer *leaf;
2902bf38be65SDavid Sterba 	struct btrfs_block_group_item bgi;
2903b3470b5dSDavid Sterba 	struct btrfs_key key;
29047248e0ceSQu Wenruo 	u64 old_commit_used;
29057248e0ceSQu Wenruo 	u64 used;
29067248e0ceSQu Wenruo 
29077248e0ceSQu Wenruo 	/*
29087248e0ceSQu Wenruo 	 * Block group items update can be triggered out of commit transaction
29097248e0ceSQu Wenruo 	 * critical section, thus we need a consistent view of used bytes.
29107248e0ceSQu Wenruo 	 * We cannot use cache->used directly outside of the spin lock, as it
29117248e0ceSQu Wenruo 	 * may be changed.
29127248e0ceSQu Wenruo 	 */
29137248e0ceSQu Wenruo 	spin_lock(&cache->lock);
29147248e0ceSQu Wenruo 	old_commit_used = cache->commit_used;
29157248e0ceSQu Wenruo 	used = cache->used;
29167248e0ceSQu Wenruo 	/* No change in used bytes, can safely skip it. */
29177248e0ceSQu Wenruo 	if (cache->commit_used == used) {
29187248e0ceSQu Wenruo 		spin_unlock(&cache->lock);
29197248e0ceSQu Wenruo 		return 0;
29207248e0ceSQu Wenruo 	}
29217248e0ceSQu Wenruo 	cache->commit_used = used;
29227248e0ceSQu Wenruo 	spin_unlock(&cache->lock);
292377745c05SJosef Bacik 
2924b3470b5dSDavid Sterba 	key.objectid = cache->start;
2925b3470b5dSDavid Sterba 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2926b3470b5dSDavid Sterba 	key.offset = cache->length;
2927b3470b5dSDavid Sterba 
29283be4d8efSQu Wenruo 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
292977745c05SJosef Bacik 	if (ret) {
293077745c05SJosef Bacik 		if (ret > 0)
293177745c05SJosef Bacik 			ret = -ENOENT;
293277745c05SJosef Bacik 		goto fail;
293377745c05SJosef Bacik 	}
293477745c05SJosef Bacik 
293577745c05SJosef Bacik 	leaf = path->nodes[0];
293677745c05SJosef Bacik 	bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
29377248e0ceSQu Wenruo 	btrfs_set_stack_block_group_used(&bgi, used);
2938de0dc456SDavid Sterba 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
2939f7238e50SJosef Bacik 						   cache->global_root_id);
2940de0dc456SDavid Sterba 	btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2941bf38be65SDavid Sterba 	write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
294277745c05SJosef Bacik 	btrfs_mark_buffer_dirty(leaf);
294377745c05SJosef Bacik fail:
294477745c05SJosef Bacik 	btrfs_release_path(path);
29457248e0ceSQu Wenruo 	/* We didn't update the block group item, need to revert @commit_used. */
29467248e0ceSQu Wenruo 	if (ret < 0) {
29477248e0ceSQu Wenruo 		spin_lock(&cache->lock);
29487248e0ceSQu Wenruo 		cache->commit_used = old_commit_used;
29497248e0ceSQu Wenruo 		spin_unlock(&cache->lock);
29507248e0ceSQu Wenruo 	}
295177745c05SJosef Bacik 	return ret;
295277745c05SJosef Bacik 
295377745c05SJosef Bacik }
295477745c05SJosef Bacik 
295532da5386SDavid Sterba static int cache_save_setup(struct btrfs_block_group *block_group,
295677745c05SJosef Bacik 			    struct btrfs_trans_handle *trans,
295777745c05SJosef Bacik 			    struct btrfs_path *path)
295877745c05SJosef Bacik {
295977745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
296077745c05SJosef Bacik 	struct btrfs_root *root = fs_info->tree_root;
296177745c05SJosef Bacik 	struct inode *inode = NULL;
296277745c05SJosef Bacik 	struct extent_changeset *data_reserved = NULL;
296377745c05SJosef Bacik 	u64 alloc_hint = 0;
296477745c05SJosef Bacik 	int dcs = BTRFS_DC_ERROR;
29650044ae11SQu Wenruo 	u64 cache_size = 0;
296677745c05SJosef Bacik 	int retries = 0;
296777745c05SJosef Bacik 	int ret = 0;
296877745c05SJosef Bacik 
2969af456a2cSBoris Burkov 	if (!btrfs_test_opt(fs_info, SPACE_CACHE))
2970af456a2cSBoris Burkov 		return 0;
2971af456a2cSBoris Burkov 
297277745c05SJosef Bacik 	/*
297377745c05SJosef Bacik 	 * If this block group is smaller than 100 megs don't bother caching the
297477745c05SJosef Bacik 	 * block group.
297577745c05SJosef Bacik 	 */
2976b3470b5dSDavid Sterba 	if (block_group->length < (100 * SZ_1M)) {
297777745c05SJosef Bacik 		spin_lock(&block_group->lock);
297877745c05SJosef Bacik 		block_group->disk_cache_state = BTRFS_DC_WRITTEN;
297977745c05SJosef Bacik 		spin_unlock(&block_group->lock);
298077745c05SJosef Bacik 		return 0;
298177745c05SJosef Bacik 	}
298277745c05SJosef Bacik 
2983bf31f87fSDavid Sterba 	if (TRANS_ABORTED(trans))
298477745c05SJosef Bacik 		return 0;
298577745c05SJosef Bacik again:
298677745c05SJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
298777745c05SJosef Bacik 	if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
298877745c05SJosef Bacik 		ret = PTR_ERR(inode);
298977745c05SJosef Bacik 		btrfs_release_path(path);
299077745c05SJosef Bacik 		goto out;
299177745c05SJosef Bacik 	}
299277745c05SJosef Bacik 
299377745c05SJosef Bacik 	if (IS_ERR(inode)) {
299477745c05SJosef Bacik 		BUG_ON(retries);
299577745c05SJosef Bacik 		retries++;
299677745c05SJosef Bacik 
299777745c05SJosef Bacik 		if (block_group->ro)
299877745c05SJosef Bacik 			goto out_free;
299977745c05SJosef Bacik 
300077745c05SJosef Bacik 		ret = create_free_space_inode(trans, block_group, path);
300177745c05SJosef Bacik 		if (ret)
300277745c05SJosef Bacik 			goto out_free;
300377745c05SJosef Bacik 		goto again;
300477745c05SJosef Bacik 	}
300577745c05SJosef Bacik 
300677745c05SJosef Bacik 	/*
300777745c05SJosef Bacik 	 * We want to set the generation to 0, that way if anything goes wrong
300877745c05SJosef Bacik 	 * from here on out we know not to trust this cache when we load up next
300977745c05SJosef Bacik 	 * time.
301077745c05SJosef Bacik 	 */
301177745c05SJosef Bacik 	BTRFS_I(inode)->generation = 0;
30129a56fcd1SNikolay Borisov 	ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
301377745c05SJosef Bacik 	if (ret) {
301477745c05SJosef Bacik 		/*
301577745c05SJosef Bacik 		 * So theoretically we could recover from this, simply set the
301677745c05SJosef Bacik 		 * super cache generation to 0 so we know to invalidate the
301777745c05SJosef Bacik 		 * cache, but then we'd have to keep track of the block groups
301877745c05SJosef Bacik 		 * that fail this way so we know we _have_ to reset this cache
301977745c05SJosef Bacik 		 * before the next commit or risk reading stale cache.  So to
302077745c05SJosef Bacik 		 * limit our exposure to horrible edge cases lets just abort the
302177745c05SJosef Bacik 		 * transaction, this only happens in really bad situations
302277745c05SJosef Bacik 		 * anyway.
302377745c05SJosef Bacik 		 */
302477745c05SJosef Bacik 		btrfs_abort_transaction(trans, ret);
302577745c05SJosef Bacik 		goto out_put;
302677745c05SJosef Bacik 	}
302777745c05SJosef Bacik 	WARN_ON(ret);
302877745c05SJosef Bacik 
302977745c05SJosef Bacik 	/* We've already setup this transaction, go ahead and exit */
303077745c05SJosef Bacik 	if (block_group->cache_generation == trans->transid &&
303177745c05SJosef Bacik 	    i_size_read(inode)) {
303277745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
303377745c05SJosef Bacik 		goto out_put;
303477745c05SJosef Bacik 	}
303577745c05SJosef Bacik 
303677745c05SJosef Bacik 	if (i_size_read(inode) > 0) {
303777745c05SJosef Bacik 		ret = btrfs_check_trunc_cache_free_space(fs_info,
303877745c05SJosef Bacik 					&fs_info->global_block_rsv);
303977745c05SJosef Bacik 		if (ret)
304077745c05SJosef Bacik 			goto out_put;
304177745c05SJosef Bacik 
304277745c05SJosef Bacik 		ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
304377745c05SJosef Bacik 		if (ret)
304477745c05SJosef Bacik 			goto out_put;
304577745c05SJosef Bacik 	}
304677745c05SJosef Bacik 
304777745c05SJosef Bacik 	spin_lock(&block_group->lock);
304877745c05SJosef Bacik 	if (block_group->cached != BTRFS_CACHE_FINISHED ||
304977745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE)) {
305077745c05SJosef Bacik 		/*
305177745c05SJosef Bacik 		 * don't bother trying to write stuff out _if_
305277745c05SJosef Bacik 		 * a) we're not cached,
305377745c05SJosef Bacik 		 * b) we're with nospace_cache mount option,
305477745c05SJosef Bacik 		 * c) we're with v2 space_cache (FREE_SPACE_TREE).
305577745c05SJosef Bacik 		 */
305677745c05SJosef Bacik 		dcs = BTRFS_DC_WRITTEN;
305777745c05SJosef Bacik 		spin_unlock(&block_group->lock);
305877745c05SJosef Bacik 		goto out_put;
305977745c05SJosef Bacik 	}
306077745c05SJosef Bacik 	spin_unlock(&block_group->lock);
306177745c05SJosef Bacik 
306277745c05SJosef Bacik 	/*
306377745c05SJosef Bacik 	 * We hit an ENOSPC when setting up the cache in this transaction, just
306477745c05SJosef Bacik 	 * skip doing the setup, we've already cleared the cache so we're safe.
306577745c05SJosef Bacik 	 */
306677745c05SJosef Bacik 	if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
306777745c05SJosef Bacik 		ret = -ENOSPC;
306877745c05SJosef Bacik 		goto out_put;
306977745c05SJosef Bacik 	}
307077745c05SJosef Bacik 
307177745c05SJosef Bacik 	/*
307277745c05SJosef Bacik 	 * Try to preallocate enough space based on how big the block group is.
307377745c05SJosef Bacik 	 * Keep in mind this has to include any pinned space which could end up
307477745c05SJosef Bacik 	 * taking up quite a bit since it's not folded into the other space
307577745c05SJosef Bacik 	 * cache.
307677745c05SJosef Bacik 	 */
30770044ae11SQu Wenruo 	cache_size = div_u64(block_group->length, SZ_256M);
30780044ae11SQu Wenruo 	if (!cache_size)
30790044ae11SQu Wenruo 		cache_size = 1;
308077745c05SJosef Bacik 
30810044ae11SQu Wenruo 	cache_size *= 16;
30820044ae11SQu Wenruo 	cache_size *= fs_info->sectorsize;
308377745c05SJosef Bacik 
308436ea6f3eSNikolay Borisov 	ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
30851daedb1dSJosef Bacik 					  cache_size, false);
308677745c05SJosef Bacik 	if (ret)
308777745c05SJosef Bacik 		goto out_put;
308877745c05SJosef Bacik 
30890044ae11SQu Wenruo 	ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
30900044ae11SQu Wenruo 					      cache_size, cache_size,
309177745c05SJosef Bacik 					      &alloc_hint);
309277745c05SJosef Bacik 	/*
309377745c05SJosef Bacik 	 * Our cache requires contiguous chunks so that we don't modify a bunch
309477745c05SJosef Bacik 	 * of metadata or split extents when writing the cache out, which means
309577745c05SJosef Bacik 	 * we can enospc if we are heavily fragmented in addition to just normal
309677745c05SJosef Bacik 	 * out of space conditions.  So if we hit this just skip setting up any
309777745c05SJosef Bacik 	 * other block groups for this transaction, maybe we'll unpin enough
309877745c05SJosef Bacik 	 * space the next time around.
309977745c05SJosef Bacik 	 */
310077745c05SJosef Bacik 	if (!ret)
310177745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
310277745c05SJosef Bacik 	else if (ret == -ENOSPC)
310377745c05SJosef Bacik 		set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
310477745c05SJosef Bacik 
310577745c05SJosef Bacik out_put:
310677745c05SJosef Bacik 	iput(inode);
310777745c05SJosef Bacik out_free:
310877745c05SJosef Bacik 	btrfs_release_path(path);
310977745c05SJosef Bacik out:
311077745c05SJosef Bacik 	spin_lock(&block_group->lock);
311177745c05SJosef Bacik 	if (!ret && dcs == BTRFS_DC_SETUP)
311277745c05SJosef Bacik 		block_group->cache_generation = trans->transid;
311377745c05SJosef Bacik 	block_group->disk_cache_state = dcs;
311477745c05SJosef Bacik 	spin_unlock(&block_group->lock);
311577745c05SJosef Bacik 
311677745c05SJosef Bacik 	extent_changeset_free(data_reserved);
311777745c05SJosef Bacik 	return ret;
311877745c05SJosef Bacik }
311977745c05SJosef Bacik 
312077745c05SJosef Bacik int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
312177745c05SJosef Bacik {
312277745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
312332da5386SDavid Sterba 	struct btrfs_block_group *cache, *tmp;
312477745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
312577745c05SJosef Bacik 	struct btrfs_path *path;
312677745c05SJosef Bacik 
312777745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs) ||
312877745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE))
312977745c05SJosef Bacik 		return 0;
313077745c05SJosef Bacik 
313177745c05SJosef Bacik 	path = btrfs_alloc_path();
313277745c05SJosef Bacik 	if (!path)
313377745c05SJosef Bacik 		return -ENOMEM;
313477745c05SJosef Bacik 
313577745c05SJosef Bacik 	/* Could add new block groups, use _safe just in case */
313677745c05SJosef Bacik 	list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
313777745c05SJosef Bacik 				 dirty_list) {
313877745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_CLEAR)
313977745c05SJosef Bacik 			cache_save_setup(cache, trans, path);
314077745c05SJosef Bacik 	}
314177745c05SJosef Bacik 
314277745c05SJosef Bacik 	btrfs_free_path(path);
314377745c05SJosef Bacik 	return 0;
314477745c05SJosef Bacik }
314577745c05SJosef Bacik 
314677745c05SJosef Bacik /*
314777745c05SJosef Bacik  * Transaction commit does final block group cache writeback during a critical
314877745c05SJosef Bacik  * section where nothing is allowed to change the FS.  This is required in
314977745c05SJosef Bacik  * order for the cache to actually match the block group, but can introduce a
315077745c05SJosef Bacik  * lot of latency into the commit.
315177745c05SJosef Bacik  *
315277745c05SJosef Bacik  * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
315377745c05SJosef Bacik  * There's a chance we'll have to redo some of it if the block group changes
315477745c05SJosef Bacik  * again during the commit, but it greatly reduces the commit latency by
315577745c05SJosef Bacik  * getting rid of the easy block groups while we're still allowing others to
315677745c05SJosef Bacik  * join the commit.
315777745c05SJosef Bacik  */
315877745c05SJosef Bacik int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
315977745c05SJosef Bacik {
316077745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
316132da5386SDavid Sterba 	struct btrfs_block_group *cache;
316277745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
316377745c05SJosef Bacik 	int ret = 0;
316477745c05SJosef Bacik 	int should_put;
316577745c05SJosef Bacik 	struct btrfs_path *path = NULL;
316677745c05SJosef Bacik 	LIST_HEAD(dirty);
316777745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
316877745c05SJosef Bacik 	int loops = 0;
316977745c05SJosef Bacik 
317077745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
317177745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs)) {
317277745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
317377745c05SJosef Bacik 		return 0;
317477745c05SJosef Bacik 	}
317577745c05SJosef Bacik 	list_splice_init(&cur_trans->dirty_bgs, &dirty);
317677745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
317777745c05SJosef Bacik 
317877745c05SJosef Bacik again:
317977745c05SJosef Bacik 	/* Make sure all the block groups on our dirty list actually exist */
318077745c05SJosef Bacik 	btrfs_create_pending_block_groups(trans);
318177745c05SJosef Bacik 
318277745c05SJosef Bacik 	if (!path) {
318377745c05SJosef Bacik 		path = btrfs_alloc_path();
3184938fcbfbSJosef Bacik 		if (!path) {
3185938fcbfbSJosef Bacik 			ret = -ENOMEM;
3186938fcbfbSJosef Bacik 			goto out;
3187938fcbfbSJosef Bacik 		}
318877745c05SJosef Bacik 	}
318977745c05SJosef Bacik 
319077745c05SJosef Bacik 	/*
319177745c05SJosef Bacik 	 * cache_write_mutex is here only to save us from balance or automatic
319277745c05SJosef Bacik 	 * removal of empty block groups deleting this block group while we are
319377745c05SJosef Bacik 	 * writing out the cache
319477745c05SJosef Bacik 	 */
319577745c05SJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
319677745c05SJosef Bacik 	while (!list_empty(&dirty)) {
319777745c05SJosef Bacik 		bool drop_reserve = true;
319877745c05SJosef Bacik 
319932da5386SDavid Sterba 		cache = list_first_entry(&dirty, struct btrfs_block_group,
320077745c05SJosef Bacik 					 dirty_list);
320177745c05SJosef Bacik 		/*
320277745c05SJosef Bacik 		 * This can happen if something re-dirties a block group that
320377745c05SJosef Bacik 		 * is already under IO.  Just wait for it to finish and then do
320477745c05SJosef Bacik 		 * it all again
320577745c05SJosef Bacik 		 */
320677745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
320777745c05SJosef Bacik 			list_del_init(&cache->io_list);
320877745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
320977745c05SJosef Bacik 			btrfs_put_block_group(cache);
321077745c05SJosef Bacik 		}
321177745c05SJosef Bacik 
321277745c05SJosef Bacik 
321377745c05SJosef Bacik 		/*
321477745c05SJosef Bacik 		 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
321577745c05SJosef Bacik 		 * it should update the cache_state.  Don't delete until after
321677745c05SJosef Bacik 		 * we wait.
321777745c05SJosef Bacik 		 *
321877745c05SJosef Bacik 		 * Since we're not running in the commit critical section
321977745c05SJosef Bacik 		 * we need the dirty_bgs_lock to protect from update_block_group
322077745c05SJosef Bacik 		 */
322177745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
322277745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
322377745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
322477745c05SJosef Bacik 
322577745c05SJosef Bacik 		should_put = 1;
322677745c05SJosef Bacik 
322777745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
322877745c05SJosef Bacik 
322977745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_SETUP) {
323077745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
323177745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
323277745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
323377745c05SJosef Bacik 				should_put = 0;
323477745c05SJosef Bacik 
323577745c05SJosef Bacik 				/*
323677745c05SJosef Bacik 				 * The cache_write_mutex is protecting the
323777745c05SJosef Bacik 				 * io_list, also refer to the definition of
323877745c05SJosef Bacik 				 * btrfs_transaction::io_bgs for more details
323977745c05SJosef Bacik 				 */
324077745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
324177745c05SJosef Bacik 			} else {
324277745c05SJosef Bacik 				/*
324377745c05SJosef Bacik 				 * If we failed to write the cache, the
324477745c05SJosef Bacik 				 * generation will be bad and life goes on
324577745c05SJosef Bacik 				 */
324677745c05SJosef Bacik 				ret = 0;
324777745c05SJosef Bacik 			}
324877745c05SJosef Bacik 		}
324977745c05SJosef Bacik 		if (!ret) {
32503be4d8efSQu Wenruo 			ret = update_block_group_item(trans, path, cache);
325177745c05SJosef Bacik 			/*
325277745c05SJosef Bacik 			 * Our block group might still be attached to the list
325377745c05SJosef Bacik 			 * of new block groups in the transaction handle of some
325477745c05SJosef Bacik 			 * other task (struct btrfs_trans_handle->new_bgs). This
325577745c05SJosef Bacik 			 * means its block group item isn't yet in the extent
325677745c05SJosef Bacik 			 * tree. If this happens ignore the error, as we will
325777745c05SJosef Bacik 			 * try again later in the critical section of the
325877745c05SJosef Bacik 			 * transaction commit.
325977745c05SJosef Bacik 			 */
326077745c05SJosef Bacik 			if (ret == -ENOENT) {
326177745c05SJosef Bacik 				ret = 0;
326277745c05SJosef Bacik 				spin_lock(&cur_trans->dirty_bgs_lock);
326377745c05SJosef Bacik 				if (list_empty(&cache->dirty_list)) {
326477745c05SJosef Bacik 					list_add_tail(&cache->dirty_list,
326577745c05SJosef Bacik 						      &cur_trans->dirty_bgs);
326677745c05SJosef Bacik 					btrfs_get_block_group(cache);
326777745c05SJosef Bacik 					drop_reserve = false;
326877745c05SJosef Bacik 				}
326977745c05SJosef Bacik 				spin_unlock(&cur_trans->dirty_bgs_lock);
327077745c05SJosef Bacik 			} else if (ret) {
327177745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
327277745c05SJosef Bacik 			}
327377745c05SJosef Bacik 		}
327477745c05SJosef Bacik 
327577745c05SJosef Bacik 		/* If it's not on the io list, we need to put the block group */
327677745c05SJosef Bacik 		if (should_put)
327777745c05SJosef Bacik 			btrfs_put_block_group(cache);
327877745c05SJosef Bacik 		if (drop_reserve)
327977745c05SJosef Bacik 			btrfs_delayed_refs_rsv_release(fs_info, 1);
328077745c05SJosef Bacik 		/*
328177745c05SJosef Bacik 		 * Avoid blocking other tasks for too long. It might even save
328277745c05SJosef Bacik 		 * us from writing caches for block groups that are going to be
328377745c05SJosef Bacik 		 * removed.
328477745c05SJosef Bacik 		 */
328577745c05SJosef Bacik 		mutex_unlock(&trans->transaction->cache_write_mutex);
3286938fcbfbSJosef Bacik 		if (ret)
3287938fcbfbSJosef Bacik 			goto out;
328877745c05SJosef Bacik 		mutex_lock(&trans->transaction->cache_write_mutex);
328977745c05SJosef Bacik 	}
329077745c05SJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
329177745c05SJosef Bacik 
329277745c05SJosef Bacik 	/*
329377745c05SJosef Bacik 	 * Go through delayed refs for all the stuff we've just kicked off
329477745c05SJosef Bacik 	 * and then loop back (just once)
329577745c05SJosef Bacik 	 */
329634d1eb0eSJosef Bacik 	if (!ret)
329777745c05SJosef Bacik 		ret = btrfs_run_delayed_refs(trans, 0);
329877745c05SJosef Bacik 	if (!ret && loops == 0) {
329977745c05SJosef Bacik 		loops++;
330077745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
330177745c05SJosef Bacik 		list_splice_init(&cur_trans->dirty_bgs, &dirty);
330277745c05SJosef Bacik 		/*
330377745c05SJosef Bacik 		 * dirty_bgs_lock protects us from concurrent block group
330477745c05SJosef Bacik 		 * deletes too (not just cache_write_mutex).
330577745c05SJosef Bacik 		 */
330677745c05SJosef Bacik 		if (!list_empty(&dirty)) {
330777745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
330877745c05SJosef Bacik 			goto again;
330977745c05SJosef Bacik 		}
331077745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
3311938fcbfbSJosef Bacik 	}
3312938fcbfbSJosef Bacik out:
3313938fcbfbSJosef Bacik 	if (ret < 0) {
3314938fcbfbSJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
3315938fcbfbSJosef Bacik 		list_splice_init(&dirty, &cur_trans->dirty_bgs);
3316938fcbfbSJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
331777745c05SJosef Bacik 		btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
331877745c05SJosef Bacik 	}
331977745c05SJosef Bacik 
332077745c05SJosef Bacik 	btrfs_free_path(path);
332177745c05SJosef Bacik 	return ret;
332277745c05SJosef Bacik }
332377745c05SJosef Bacik 
332477745c05SJosef Bacik int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
332577745c05SJosef Bacik {
332677745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
332732da5386SDavid Sterba 	struct btrfs_block_group *cache;
332877745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
332977745c05SJosef Bacik 	int ret = 0;
333077745c05SJosef Bacik 	int should_put;
333177745c05SJosef Bacik 	struct btrfs_path *path;
333277745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
333377745c05SJosef Bacik 
333477745c05SJosef Bacik 	path = btrfs_alloc_path();
333577745c05SJosef Bacik 	if (!path)
333677745c05SJosef Bacik 		return -ENOMEM;
333777745c05SJosef Bacik 
333877745c05SJosef Bacik 	/*
333977745c05SJosef Bacik 	 * Even though we are in the critical section of the transaction commit,
334077745c05SJosef Bacik 	 * we can still have concurrent tasks adding elements to this
334177745c05SJosef Bacik 	 * transaction's list of dirty block groups. These tasks correspond to
334277745c05SJosef Bacik 	 * endio free space workers started when writeback finishes for a
334377745c05SJosef Bacik 	 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
334477745c05SJosef Bacik 	 * allocate new block groups as a result of COWing nodes of the root
334577745c05SJosef Bacik 	 * tree when updating the free space inode. The writeback for the space
334677745c05SJosef Bacik 	 * caches is triggered by an earlier call to
334777745c05SJosef Bacik 	 * btrfs_start_dirty_block_groups() and iterations of the following
334877745c05SJosef Bacik 	 * loop.
334977745c05SJosef Bacik 	 * Also we want to do the cache_save_setup first and then run the
335077745c05SJosef Bacik 	 * delayed refs to make sure we have the best chance at doing this all
335177745c05SJosef Bacik 	 * in one shot.
335277745c05SJosef Bacik 	 */
335377745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
335477745c05SJosef Bacik 	while (!list_empty(&cur_trans->dirty_bgs)) {
335577745c05SJosef Bacik 		cache = list_first_entry(&cur_trans->dirty_bgs,
335632da5386SDavid Sterba 					 struct btrfs_block_group,
335777745c05SJosef Bacik 					 dirty_list);
335877745c05SJosef Bacik 
335977745c05SJosef Bacik 		/*
336077745c05SJosef Bacik 		 * This can happen if cache_save_setup re-dirties a block group
336177745c05SJosef Bacik 		 * that is already under IO.  Just wait for it to finish and
336277745c05SJosef Bacik 		 * then do it all again
336377745c05SJosef Bacik 		 */
336477745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
336577745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
336677745c05SJosef Bacik 			list_del_init(&cache->io_list);
336777745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
336877745c05SJosef Bacik 			btrfs_put_block_group(cache);
336977745c05SJosef Bacik 			spin_lock(&cur_trans->dirty_bgs_lock);
337077745c05SJosef Bacik 		}
337177745c05SJosef Bacik 
337277745c05SJosef Bacik 		/*
337377745c05SJosef Bacik 		 * Don't remove from the dirty list until after we've waited on
337477745c05SJosef Bacik 		 * any pending IO
337577745c05SJosef Bacik 		 */
337677745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
337777745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
337877745c05SJosef Bacik 		should_put = 1;
337977745c05SJosef Bacik 
338077745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
338177745c05SJosef Bacik 
338277745c05SJosef Bacik 		if (!ret)
338377745c05SJosef Bacik 			ret = btrfs_run_delayed_refs(trans,
338477745c05SJosef Bacik 						     (unsigned long) -1);
338577745c05SJosef Bacik 
338677745c05SJosef Bacik 		if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
338777745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
338877745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
338977745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
339077745c05SJosef Bacik 				should_put = 0;
339177745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
339277745c05SJosef Bacik 			} else {
339377745c05SJosef Bacik 				/*
339477745c05SJosef Bacik 				 * If we failed to write the cache, the
339577745c05SJosef Bacik 				 * generation will be bad and life goes on
339677745c05SJosef Bacik 				 */
339777745c05SJosef Bacik 				ret = 0;
339877745c05SJosef Bacik 			}
339977745c05SJosef Bacik 		}
340077745c05SJosef Bacik 		if (!ret) {
34013be4d8efSQu Wenruo 			ret = update_block_group_item(trans, path, cache);
340277745c05SJosef Bacik 			/*
340377745c05SJosef Bacik 			 * One of the free space endio workers might have
340477745c05SJosef Bacik 			 * created a new block group while updating a free space
340577745c05SJosef Bacik 			 * cache's inode (at inode.c:btrfs_finish_ordered_io())
340677745c05SJosef Bacik 			 * and hasn't released its transaction handle yet, in
340777745c05SJosef Bacik 			 * which case the new block group is still attached to
340877745c05SJosef Bacik 			 * its transaction handle and its creation has not
340977745c05SJosef Bacik 			 * finished yet (no block group item in the extent tree
341077745c05SJosef Bacik 			 * yet, etc). If this is the case, wait for all free
341177745c05SJosef Bacik 			 * space endio workers to finish and retry. This is a
3412260db43cSRandy Dunlap 			 * very rare case so no need for a more efficient and
341377745c05SJosef Bacik 			 * complex approach.
341477745c05SJosef Bacik 			 */
341577745c05SJosef Bacik 			if (ret == -ENOENT) {
341677745c05SJosef Bacik 				wait_event(cur_trans->writer_wait,
341777745c05SJosef Bacik 				   atomic_read(&cur_trans->num_writers) == 1);
34183be4d8efSQu Wenruo 				ret = update_block_group_item(trans, path, cache);
341977745c05SJosef Bacik 			}
342077745c05SJosef Bacik 			if (ret)
342177745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
342277745c05SJosef Bacik 		}
342377745c05SJosef Bacik 
342477745c05SJosef Bacik 		/* If its not on the io list, we need to put the block group */
342577745c05SJosef Bacik 		if (should_put)
342677745c05SJosef Bacik 			btrfs_put_block_group(cache);
342777745c05SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
342877745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
342977745c05SJosef Bacik 	}
343077745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
343177745c05SJosef Bacik 
343277745c05SJosef Bacik 	/*
343377745c05SJosef Bacik 	 * Refer to the definition of io_bgs member for details why it's safe
343477745c05SJosef Bacik 	 * to use it without any locking
343577745c05SJosef Bacik 	 */
343677745c05SJosef Bacik 	while (!list_empty(io)) {
343732da5386SDavid Sterba 		cache = list_first_entry(io, struct btrfs_block_group,
343877745c05SJosef Bacik 					 io_list);
343977745c05SJosef Bacik 		list_del_init(&cache->io_list);
344077745c05SJosef Bacik 		btrfs_wait_cache_io(trans, cache, path);
344177745c05SJosef Bacik 		btrfs_put_block_group(cache);
344277745c05SJosef Bacik 	}
344377745c05SJosef Bacik 
344477745c05SJosef Bacik 	btrfs_free_path(path);
344577745c05SJosef Bacik 	return ret;
344677745c05SJosef Bacik }
3447606d1bf1SJosef Bacik 
3448606d1bf1SJosef Bacik int btrfs_update_block_group(struct btrfs_trans_handle *trans,
344911b66fa6SAnand Jain 			     u64 bytenr, u64 num_bytes, bool alloc)
3450606d1bf1SJosef Bacik {
3451606d1bf1SJosef Bacik 	struct btrfs_fs_info *info = trans->fs_info;
345232da5386SDavid Sterba 	struct btrfs_block_group *cache = NULL;
3453606d1bf1SJosef Bacik 	u64 total = num_bytes;
3454606d1bf1SJosef Bacik 	u64 old_val;
3455606d1bf1SJosef Bacik 	u64 byte_in_group;
3456606d1bf1SJosef Bacik 	int factor;
3457606d1bf1SJosef Bacik 	int ret = 0;
3458606d1bf1SJosef Bacik 
3459606d1bf1SJosef Bacik 	/* Block accounting for super block */
3460606d1bf1SJosef Bacik 	spin_lock(&info->delalloc_root_lock);
3461606d1bf1SJosef Bacik 	old_val = btrfs_super_bytes_used(info->super_copy);
3462606d1bf1SJosef Bacik 	if (alloc)
3463606d1bf1SJosef Bacik 		old_val += num_bytes;
3464606d1bf1SJosef Bacik 	else
3465606d1bf1SJosef Bacik 		old_val -= num_bytes;
3466606d1bf1SJosef Bacik 	btrfs_set_super_bytes_used(info->super_copy, old_val);
3467606d1bf1SJosef Bacik 	spin_unlock(&info->delalloc_root_lock);
3468606d1bf1SJosef Bacik 
3469606d1bf1SJosef Bacik 	while (total) {
3470df384da5SJosef Bacik 		struct btrfs_space_info *space_info;
3471efbf35a1SJosef Bacik 		bool reclaim = false;
3472ac2f1e63SJosef Bacik 
3473606d1bf1SJosef Bacik 		cache = btrfs_lookup_block_group(info, bytenr);
3474606d1bf1SJosef Bacik 		if (!cache) {
3475606d1bf1SJosef Bacik 			ret = -ENOENT;
3476606d1bf1SJosef Bacik 			break;
3477606d1bf1SJosef Bacik 		}
3478df384da5SJosef Bacik 		space_info = cache->space_info;
3479606d1bf1SJosef Bacik 		factor = btrfs_bg_type_to_factor(cache->flags);
3480606d1bf1SJosef Bacik 
3481606d1bf1SJosef Bacik 		/*
3482606d1bf1SJosef Bacik 		 * If this block group has free space cache written out, we
3483606d1bf1SJosef Bacik 		 * need to make sure to load it if we are removing space.  This
3484606d1bf1SJosef Bacik 		 * is because we need the unpinning stage to actually add the
3485606d1bf1SJosef Bacik 		 * space back to the block group, otherwise we will leak space.
3486606d1bf1SJosef Bacik 		 */
348732da5386SDavid Sterba 		if (!alloc && !btrfs_block_group_done(cache))
3488ced8ecf0SOmar Sandoval 			btrfs_cache_block_group(cache, true);
3489606d1bf1SJosef Bacik 
3490b3470b5dSDavid Sterba 		byte_in_group = bytenr - cache->start;
3491b3470b5dSDavid Sterba 		WARN_ON(byte_in_group > cache->length);
3492606d1bf1SJosef Bacik 
3493df384da5SJosef Bacik 		spin_lock(&space_info->lock);
3494606d1bf1SJosef Bacik 		spin_lock(&cache->lock);
3495606d1bf1SJosef Bacik 
3496606d1bf1SJosef Bacik 		if (btrfs_test_opt(info, SPACE_CACHE) &&
3497606d1bf1SJosef Bacik 		    cache->disk_cache_state < BTRFS_DC_CLEAR)
3498606d1bf1SJosef Bacik 			cache->disk_cache_state = BTRFS_DC_CLEAR;
3499606d1bf1SJosef Bacik 
3500bf38be65SDavid Sterba 		old_val = cache->used;
3501b3470b5dSDavid Sterba 		num_bytes = min(total, cache->length - byte_in_group);
3502606d1bf1SJosef Bacik 		if (alloc) {
3503606d1bf1SJosef Bacik 			old_val += num_bytes;
3504bf38be65SDavid Sterba 			cache->used = old_val;
3505606d1bf1SJosef Bacik 			cache->reserved -= num_bytes;
3506df384da5SJosef Bacik 			space_info->bytes_reserved -= num_bytes;
3507df384da5SJosef Bacik 			space_info->bytes_used += num_bytes;
3508df384da5SJosef Bacik 			space_info->disk_used += num_bytes * factor;
3509606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
3510df384da5SJosef Bacik 			spin_unlock(&space_info->lock);
3511606d1bf1SJosef Bacik 		} else {
3512606d1bf1SJosef Bacik 			old_val -= num_bytes;
3513bf38be65SDavid Sterba 			cache->used = old_val;
3514606d1bf1SJosef Bacik 			cache->pinned += num_bytes;
3515df384da5SJosef Bacik 			btrfs_space_info_update_bytes_pinned(info, space_info,
3516df384da5SJosef Bacik 							     num_bytes);
3517df384da5SJosef Bacik 			space_info->bytes_used -= num_bytes;
3518df384da5SJosef Bacik 			space_info->disk_used -= num_bytes * factor;
3519ac2f1e63SJosef Bacik 
3520ac2f1e63SJosef Bacik 			reclaim = should_reclaim_block_group(cache, num_bytes);
352152bb7a21SBoris Burkov 
3522606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
3523df384da5SJosef Bacik 			spin_unlock(&space_info->lock);
3524606d1bf1SJosef Bacik 
3525fe119a6eSNikolay Borisov 			set_extent_dirty(&trans->transaction->pinned_extents,
3526606d1bf1SJosef Bacik 					 bytenr, bytenr + num_bytes - 1,
3527606d1bf1SJosef Bacik 					 GFP_NOFS | __GFP_NOFAIL);
3528606d1bf1SJosef Bacik 		}
3529606d1bf1SJosef Bacik 
3530606d1bf1SJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
3531606d1bf1SJosef Bacik 		if (list_empty(&cache->dirty_list)) {
3532606d1bf1SJosef Bacik 			list_add_tail(&cache->dirty_list,
3533606d1bf1SJosef Bacik 				      &trans->transaction->dirty_bgs);
3534606d1bf1SJosef Bacik 			trans->delayed_ref_updates++;
3535606d1bf1SJosef Bacik 			btrfs_get_block_group(cache);
3536606d1bf1SJosef Bacik 		}
3537606d1bf1SJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
3538606d1bf1SJosef Bacik 
3539606d1bf1SJosef Bacik 		/*
3540606d1bf1SJosef Bacik 		 * No longer have used bytes in this block group, queue it for
3541606d1bf1SJosef Bacik 		 * deletion. We do this after adding the block group to the
3542606d1bf1SJosef Bacik 		 * dirty list to avoid races between cleaner kthread and space
3543606d1bf1SJosef Bacik 		 * cache writeout.
3544606d1bf1SJosef Bacik 		 */
35456e80d4f8SDennis Zhou 		if (!alloc && old_val == 0) {
35466e80d4f8SDennis Zhou 			if (!btrfs_test_opt(info, DISCARD_ASYNC))
3547606d1bf1SJosef Bacik 				btrfs_mark_bg_unused(cache);
3548ac2f1e63SJosef Bacik 		} else if (!alloc && reclaim) {
3549ac2f1e63SJosef Bacik 			btrfs_mark_bg_to_reclaim(cache);
35506e80d4f8SDennis Zhou 		}
3551606d1bf1SJosef Bacik 
3552606d1bf1SJosef Bacik 		btrfs_put_block_group(cache);
3553606d1bf1SJosef Bacik 		total -= num_bytes;
3554606d1bf1SJosef Bacik 		bytenr += num_bytes;
3555606d1bf1SJosef Bacik 	}
3556606d1bf1SJosef Bacik 
3557606d1bf1SJosef Bacik 	/* Modified block groups are accounted for in the delayed_refs_rsv. */
3558606d1bf1SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
3559606d1bf1SJosef Bacik 	return ret;
3560606d1bf1SJosef Bacik }
3561606d1bf1SJosef Bacik 
356243dd529aSDavid Sterba /*
356343dd529aSDavid Sterba  * Update the block_group and space info counters.
356443dd529aSDavid Sterba  *
3565606d1bf1SJosef Bacik  * @cache:	The cache we are manipulating
3566606d1bf1SJosef Bacik  * @ram_bytes:  The number of bytes of file content, and will be same to
3567606d1bf1SJosef Bacik  *              @num_bytes except for the compress path.
3568606d1bf1SJosef Bacik  * @num_bytes:	The number of bytes in question
3569606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
3570606d1bf1SJosef Bacik  *
3571606d1bf1SJosef Bacik  * This is called by the allocator when it reserves space. If this is a
3572606d1bf1SJosef Bacik  * reservation and the block group has become read only we cannot make the
3573606d1bf1SJosef Bacik  * reservation and return -EAGAIN, otherwise this function always succeeds.
3574606d1bf1SJosef Bacik  */
357532da5386SDavid Sterba int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
357652bb7a21SBoris Burkov 			     u64 ram_bytes, u64 num_bytes, int delalloc,
357752bb7a21SBoris Burkov 			     bool force_wrong_size_class)
3578606d1bf1SJosef Bacik {
3579606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
358052bb7a21SBoris Burkov 	enum btrfs_block_group_size_class size_class;
3581606d1bf1SJosef Bacik 	int ret = 0;
3582606d1bf1SJosef Bacik 
3583606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
3584606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
3585606d1bf1SJosef Bacik 	if (cache->ro) {
3586606d1bf1SJosef Bacik 		ret = -EAGAIN;
358752bb7a21SBoris Burkov 		goto out;
358852bb7a21SBoris Burkov 	}
358952bb7a21SBoris Burkov 
3590cb0922f2SBoris Burkov 	if (btrfs_block_group_should_use_size_class(cache)) {
359152bb7a21SBoris Burkov 		size_class = btrfs_calc_block_group_size_class(num_bytes);
359252bb7a21SBoris Burkov 		ret = btrfs_use_block_group_size_class(cache, size_class, force_wrong_size_class);
359352bb7a21SBoris Burkov 		if (ret)
359452bb7a21SBoris Burkov 			goto out;
359552bb7a21SBoris Burkov 	}
3596606d1bf1SJosef Bacik 	cache->reserved += num_bytes;
3597606d1bf1SJosef Bacik 	space_info->bytes_reserved += num_bytes;
3598a43c3835SJosef Bacik 	trace_btrfs_space_reservation(cache->fs_info, "space_info",
3599a43c3835SJosef Bacik 				      space_info->flags, num_bytes, 1);
3600606d1bf1SJosef Bacik 	btrfs_space_info_update_bytes_may_use(cache->fs_info,
3601606d1bf1SJosef Bacik 					      space_info, -ram_bytes);
3602606d1bf1SJosef Bacik 	if (delalloc)
3603606d1bf1SJosef Bacik 		cache->delalloc_bytes += num_bytes;
360499ffb43eSJosef Bacik 
360599ffb43eSJosef Bacik 	/*
360652bb7a21SBoris Burkov 	 * Compression can use less space than we reserved, so wake tickets if
360752bb7a21SBoris Burkov 	 * that happens.
360899ffb43eSJosef Bacik 	 */
360999ffb43eSJosef Bacik 	if (num_bytes < ram_bytes)
361099ffb43eSJosef Bacik 		btrfs_try_granting_tickets(cache->fs_info, space_info);
361152bb7a21SBoris Burkov out:
3612606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
3613606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
3614606d1bf1SJosef Bacik 	return ret;
3615606d1bf1SJosef Bacik }
3616606d1bf1SJosef Bacik 
361743dd529aSDavid Sterba /*
361843dd529aSDavid Sterba  * Update the block_group and space info counters.
361943dd529aSDavid Sterba  *
3620606d1bf1SJosef Bacik  * @cache:      The cache we are manipulating
3621606d1bf1SJosef Bacik  * @num_bytes:  The number of bytes in question
3622606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
3623606d1bf1SJosef Bacik  *
3624606d1bf1SJosef Bacik  * This is called by somebody who is freeing space that was never actually used
3625606d1bf1SJosef Bacik  * on disk.  For example if you reserve some space for a new leaf in transaction
3626606d1bf1SJosef Bacik  * A and before transaction A commits you free that leaf, you call this with
3627606d1bf1SJosef Bacik  * reserve set to 0 in order to clear the reservation.
3628606d1bf1SJosef Bacik  */
362932da5386SDavid Sterba void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3630606d1bf1SJosef Bacik 			       u64 num_bytes, int delalloc)
3631606d1bf1SJosef Bacik {
3632606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
3633606d1bf1SJosef Bacik 
3634606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
3635606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
3636606d1bf1SJosef Bacik 	if (cache->ro)
3637606d1bf1SJosef Bacik 		space_info->bytes_readonly += num_bytes;
3638606d1bf1SJosef Bacik 	cache->reserved -= num_bytes;
3639606d1bf1SJosef Bacik 	space_info->bytes_reserved -= num_bytes;
3640606d1bf1SJosef Bacik 	space_info->max_extent_size = 0;
3641606d1bf1SJosef Bacik 
3642606d1bf1SJosef Bacik 	if (delalloc)
3643606d1bf1SJosef Bacik 		cache->delalloc_bytes -= num_bytes;
3644606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
36453308234aSJosef Bacik 
36463308234aSJosef Bacik 	btrfs_try_granting_tickets(cache->fs_info, space_info);
3647606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
3648606d1bf1SJosef Bacik }
364907730d87SJosef Bacik 
365007730d87SJosef Bacik static void force_metadata_allocation(struct btrfs_fs_info *info)
365107730d87SJosef Bacik {
365207730d87SJosef Bacik 	struct list_head *head = &info->space_info;
365307730d87SJosef Bacik 	struct btrfs_space_info *found;
365407730d87SJosef Bacik 
365572804905SJosef Bacik 	list_for_each_entry(found, head, list) {
365607730d87SJosef Bacik 		if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
365707730d87SJosef Bacik 			found->force_alloc = CHUNK_ALLOC_FORCE;
365807730d87SJosef Bacik 	}
365907730d87SJosef Bacik }
366007730d87SJosef Bacik 
366107730d87SJosef Bacik static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
366207730d87SJosef Bacik 			      struct btrfs_space_info *sinfo, int force)
366307730d87SJosef Bacik {
366407730d87SJosef Bacik 	u64 bytes_used = btrfs_space_info_used(sinfo, false);
366507730d87SJosef Bacik 	u64 thresh;
366607730d87SJosef Bacik 
366707730d87SJosef Bacik 	if (force == CHUNK_ALLOC_FORCE)
366807730d87SJosef Bacik 		return 1;
366907730d87SJosef Bacik 
367007730d87SJosef Bacik 	/*
367107730d87SJosef Bacik 	 * in limited mode, we want to have some free space up to
367207730d87SJosef Bacik 	 * about 1% of the FS size.
367307730d87SJosef Bacik 	 */
367407730d87SJosef Bacik 	if (force == CHUNK_ALLOC_LIMITED) {
367507730d87SJosef Bacik 		thresh = btrfs_super_total_bytes(fs_info->super_copy);
3676428c8e03SDavid Sterba 		thresh = max_t(u64, SZ_64M, mult_perc(thresh, 1));
367707730d87SJosef Bacik 
367807730d87SJosef Bacik 		if (sinfo->total_bytes - bytes_used < thresh)
367907730d87SJosef Bacik 			return 1;
368007730d87SJosef Bacik 	}
368107730d87SJosef Bacik 
3682428c8e03SDavid Sterba 	if (bytes_used + SZ_2M < mult_perc(sinfo->total_bytes, 80))
368307730d87SJosef Bacik 		return 0;
368407730d87SJosef Bacik 	return 1;
368507730d87SJosef Bacik }
368607730d87SJosef Bacik 
368707730d87SJosef Bacik int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
368807730d87SJosef Bacik {
368907730d87SJosef Bacik 	u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
369007730d87SJosef Bacik 
369107730d87SJosef Bacik 	return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
369207730d87SJosef Bacik }
369307730d87SJosef Bacik 
3694820c363bSNaohiro Aota static struct btrfs_block_group *do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags)
369579bd3712SFilipe Manana {
369679bd3712SFilipe Manana 	struct btrfs_block_group *bg;
369779bd3712SFilipe Manana 	int ret;
369879bd3712SFilipe Manana 
369907730d87SJosef Bacik 	/*
370079bd3712SFilipe Manana 	 * Check if we have enough space in the system space info because we
370179bd3712SFilipe Manana 	 * will need to update device items in the chunk btree and insert a new
370279bd3712SFilipe Manana 	 * chunk item in the chunk btree as well. This will allocate a new
370379bd3712SFilipe Manana 	 * system block group if needed.
370479bd3712SFilipe Manana 	 */
370579bd3712SFilipe Manana 	check_system_chunk(trans, flags);
370679bd3712SFilipe Manana 
3707f6f39f7aSNikolay Borisov 	bg = btrfs_create_chunk(trans, flags);
370879bd3712SFilipe Manana 	if (IS_ERR(bg)) {
370979bd3712SFilipe Manana 		ret = PTR_ERR(bg);
371079bd3712SFilipe Manana 		goto out;
371179bd3712SFilipe Manana 	}
371279bd3712SFilipe Manana 
371379bd3712SFilipe Manana 	ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
371479bd3712SFilipe Manana 	/*
371579bd3712SFilipe Manana 	 * Normally we are not expected to fail with -ENOSPC here, since we have
371679bd3712SFilipe Manana 	 * previously reserved space in the system space_info and allocated one
3717ecd84d54SFilipe Manana 	 * new system chunk if necessary. However there are three exceptions:
371879bd3712SFilipe Manana 	 *
371979bd3712SFilipe Manana 	 * 1) We may have enough free space in the system space_info but all the
372079bd3712SFilipe Manana 	 *    existing system block groups have a profile which can not be used
372179bd3712SFilipe Manana 	 *    for extent allocation.
372279bd3712SFilipe Manana 	 *
372379bd3712SFilipe Manana 	 *    This happens when mounting in degraded mode. For example we have a
372479bd3712SFilipe Manana 	 *    RAID1 filesystem with 2 devices, lose one device and mount the fs
372579bd3712SFilipe Manana 	 *    using the other device in degraded mode. If we then allocate a chunk,
372679bd3712SFilipe Manana 	 *    we may have enough free space in the existing system space_info, but
372779bd3712SFilipe Manana 	 *    none of the block groups can be used for extent allocation since they
372879bd3712SFilipe Manana 	 *    have a RAID1 profile, and because we are in degraded mode with a
372979bd3712SFilipe Manana 	 *    single device, we are forced to allocate a new system chunk with a
373079bd3712SFilipe Manana 	 *    SINGLE profile. Making check_system_chunk() iterate over all system
373179bd3712SFilipe Manana 	 *    block groups and check if they have a usable profile and enough space
373279bd3712SFilipe Manana 	 *    can be slow on very large filesystems, so we tolerate the -ENOSPC and
373379bd3712SFilipe Manana 	 *    try again after forcing allocation of a new system chunk. Like this
373479bd3712SFilipe Manana 	 *    we avoid paying the cost of that search in normal circumstances, when
373579bd3712SFilipe Manana 	 *    we were not mounted in degraded mode;
373679bd3712SFilipe Manana 	 *
373779bd3712SFilipe Manana 	 * 2) We had enough free space info the system space_info, and one suitable
373879bd3712SFilipe Manana 	 *    block group to allocate from when we called check_system_chunk()
373979bd3712SFilipe Manana 	 *    above. However right after we called it, the only system block group
374079bd3712SFilipe Manana 	 *    with enough free space got turned into RO mode by a running scrub,
374179bd3712SFilipe Manana 	 *    and in this case we have to allocate a new one and retry. We only
374279bd3712SFilipe Manana 	 *    need do this allocate and retry once, since we have a transaction
3743ecd84d54SFilipe Manana 	 *    handle and scrub uses the commit root to search for block groups;
3744ecd84d54SFilipe Manana 	 *
3745ecd84d54SFilipe Manana 	 * 3) We had one system block group with enough free space when we called
3746ecd84d54SFilipe Manana 	 *    check_system_chunk(), but after that, right before we tried to
3747ecd84d54SFilipe Manana 	 *    allocate the last extent buffer we needed, a discard operation came
3748ecd84d54SFilipe Manana 	 *    in and it temporarily removed the last free space entry from the
3749ecd84d54SFilipe Manana 	 *    block group (discard removes a free space entry, discards it, and
3750ecd84d54SFilipe Manana 	 *    then adds back the entry to the block group cache).
375179bd3712SFilipe Manana 	 */
375279bd3712SFilipe Manana 	if (ret == -ENOSPC) {
375379bd3712SFilipe Manana 		const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info);
375479bd3712SFilipe Manana 		struct btrfs_block_group *sys_bg;
375579bd3712SFilipe Manana 
3756f6f39f7aSNikolay Borisov 		sys_bg = btrfs_create_chunk(trans, sys_flags);
375779bd3712SFilipe Manana 		if (IS_ERR(sys_bg)) {
375879bd3712SFilipe Manana 			ret = PTR_ERR(sys_bg);
375979bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
376079bd3712SFilipe Manana 			goto out;
376179bd3712SFilipe Manana 		}
376279bd3712SFilipe Manana 
376379bd3712SFilipe Manana 		ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
376479bd3712SFilipe Manana 		if (ret) {
376579bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
376679bd3712SFilipe Manana 			goto out;
376779bd3712SFilipe Manana 		}
376879bd3712SFilipe Manana 
376979bd3712SFilipe Manana 		ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
377079bd3712SFilipe Manana 		if (ret) {
377179bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
377279bd3712SFilipe Manana 			goto out;
377379bd3712SFilipe Manana 		}
377479bd3712SFilipe Manana 	} else if (ret) {
377579bd3712SFilipe Manana 		btrfs_abort_transaction(trans, ret);
377679bd3712SFilipe Manana 		goto out;
377779bd3712SFilipe Manana 	}
377879bd3712SFilipe Manana out:
377979bd3712SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
378079bd3712SFilipe Manana 
3781820c363bSNaohiro Aota 	if (ret)
3782820c363bSNaohiro Aota 		return ERR_PTR(ret);
3783820c363bSNaohiro Aota 
3784820c363bSNaohiro Aota 	btrfs_get_block_group(bg);
3785820c363bSNaohiro Aota 	return bg;
378679bd3712SFilipe Manana }
378779bd3712SFilipe Manana 
378879bd3712SFilipe Manana /*
378979bd3712SFilipe Manana  * Chunk allocation is done in 2 phases:
379079bd3712SFilipe Manana  *
379179bd3712SFilipe Manana  * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
379279bd3712SFilipe Manana  *    the chunk, the chunk mapping, create its block group and add the items
379379bd3712SFilipe Manana  *    that belong in the chunk btree to it - more specifically, we need to
379479bd3712SFilipe Manana  *    update device items in the chunk btree and add a new chunk item to it.
379579bd3712SFilipe Manana  *
379679bd3712SFilipe Manana  * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
379779bd3712SFilipe Manana  *    group item to the extent btree and the device extent items to the devices
379879bd3712SFilipe Manana  *    btree.
379979bd3712SFilipe Manana  *
380079bd3712SFilipe Manana  * This is done to prevent deadlocks. For example when COWing a node from the
380179bd3712SFilipe Manana  * extent btree we are holding a write lock on the node's parent and if we
380279bd3712SFilipe Manana  * trigger chunk allocation and attempted to insert the new block group item
380379bd3712SFilipe Manana  * in the extent btree right way, we could deadlock because the path for the
380479bd3712SFilipe Manana  * insertion can include that parent node. At first glance it seems impossible
380579bd3712SFilipe Manana  * to trigger chunk allocation after starting a transaction since tasks should
380679bd3712SFilipe Manana  * reserve enough transaction units (metadata space), however while that is true
380779bd3712SFilipe Manana  * most of the time, chunk allocation may still be triggered for several reasons:
380879bd3712SFilipe Manana  *
380979bd3712SFilipe Manana  * 1) When reserving metadata, we check if there is enough free space in the
381079bd3712SFilipe Manana  *    metadata space_info and therefore don't trigger allocation of a new chunk.
381179bd3712SFilipe Manana  *    However later when the task actually tries to COW an extent buffer from
381279bd3712SFilipe Manana  *    the extent btree or from the device btree for example, it is forced to
381379bd3712SFilipe Manana  *    allocate a new block group (chunk) because the only one that had enough
381479bd3712SFilipe Manana  *    free space was just turned to RO mode by a running scrub for example (or
381579bd3712SFilipe Manana  *    device replace, block group reclaim thread, etc), so we can not use it
381679bd3712SFilipe Manana  *    for allocating an extent and end up being forced to allocate a new one;
381779bd3712SFilipe Manana  *
381879bd3712SFilipe Manana  * 2) Because we only check that the metadata space_info has enough free bytes,
381979bd3712SFilipe Manana  *    we end up not allocating a new metadata chunk in that case. However if
382079bd3712SFilipe Manana  *    the filesystem was mounted in degraded mode, none of the existing block
382179bd3712SFilipe Manana  *    groups might be suitable for extent allocation due to their incompatible
382279bd3712SFilipe Manana  *    profile (for e.g. mounting a 2 devices filesystem, where all block groups
382379bd3712SFilipe Manana  *    use a RAID1 profile, in degraded mode using a single device). In this case
382479bd3712SFilipe Manana  *    when the task attempts to COW some extent buffer of the extent btree for
382579bd3712SFilipe Manana  *    example, it will trigger allocation of a new metadata block group with a
382679bd3712SFilipe Manana  *    suitable profile (SINGLE profile in the example of the degraded mount of
382779bd3712SFilipe Manana  *    the RAID1 filesystem);
382879bd3712SFilipe Manana  *
382979bd3712SFilipe Manana  * 3) The task has reserved enough transaction units / metadata space, but when
383079bd3712SFilipe Manana  *    it attempts to COW an extent buffer from the extent or device btree for
383179bd3712SFilipe Manana  *    example, it does not find any free extent in any metadata block group,
383279bd3712SFilipe Manana  *    therefore forced to try to allocate a new metadata block group.
383379bd3712SFilipe Manana  *    This is because some other task allocated all available extents in the
383479bd3712SFilipe Manana  *    meanwhile - this typically happens with tasks that don't reserve space
383579bd3712SFilipe Manana  *    properly, either intentionally or as a bug. One example where this is
383679bd3712SFilipe Manana  *    done intentionally is fsync, as it does not reserve any transaction units
383779bd3712SFilipe Manana  *    and ends up allocating a variable number of metadata extents for log
3838ecd84d54SFilipe Manana  *    tree extent buffers;
3839ecd84d54SFilipe Manana  *
3840ecd84d54SFilipe Manana  * 4) The task has reserved enough transaction units / metadata space, but right
3841ecd84d54SFilipe Manana  *    before it tries to allocate the last extent buffer it needs, a discard
3842ecd84d54SFilipe Manana  *    operation comes in and, temporarily, removes the last free space entry from
3843ecd84d54SFilipe Manana  *    the only metadata block group that had free space (discard starts by
3844ecd84d54SFilipe Manana  *    removing a free space entry from a block group, then does the discard
3845ecd84d54SFilipe Manana  *    operation and, once it's done, it adds back the free space entry to the
3846ecd84d54SFilipe Manana  *    block group).
384779bd3712SFilipe Manana  *
384879bd3712SFilipe Manana  * We also need this 2 phases setup when adding a device to a filesystem with
384979bd3712SFilipe Manana  * a seed device - we must create new metadata and system chunks without adding
385079bd3712SFilipe Manana  * any of the block group items to the chunk, extent and device btrees. If we
385179bd3712SFilipe Manana  * did not do it this way, we would get ENOSPC when attempting to update those
385279bd3712SFilipe Manana  * btrees, since all the chunks from the seed device are read-only.
385379bd3712SFilipe Manana  *
385479bd3712SFilipe Manana  * Phase 1 does the updates and insertions to the chunk btree because if we had
385579bd3712SFilipe Manana  * it done in phase 2 and have a thundering herd of tasks allocating chunks in
385679bd3712SFilipe Manana  * parallel, we risk having too many system chunks allocated by many tasks if
385779bd3712SFilipe Manana  * many tasks reach phase 1 without the previous ones completing phase 2. In the
385879bd3712SFilipe Manana  * extreme case this leads to exhaustion of the system chunk array in the
385979bd3712SFilipe Manana  * superblock. This is easier to trigger if using a btree node/leaf size of 64K
386079bd3712SFilipe Manana  * and with RAID filesystems (so we have more device items in the chunk btree).
386179bd3712SFilipe Manana  * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
386279bd3712SFilipe Manana  * the system chunk array due to concurrent allocations") provides more details.
386379bd3712SFilipe Manana  *
38642bb2e00eSFilipe Manana  * Allocation of system chunks does not happen through this function. A task that
38652bb2e00eSFilipe Manana  * needs to update the chunk btree (the only btree that uses system chunks), must
38662bb2e00eSFilipe Manana  * preallocate chunk space by calling either check_system_chunk() or
38672bb2e00eSFilipe Manana  * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or
38682bb2e00eSFilipe Manana  * metadata chunk or when removing a chunk, while the later is used before doing
38692bb2e00eSFilipe Manana  * a modification to the chunk btree - use cases for the later are adding,
38702bb2e00eSFilipe Manana  * removing and resizing a device as well as relocation of a system chunk.
38712bb2e00eSFilipe Manana  * See the comment below for more details.
387279bd3712SFilipe Manana  *
387379bd3712SFilipe Manana  * The reservation of system space, done through check_system_chunk(), as well
387479bd3712SFilipe Manana  * as all the updates and insertions into the chunk btree must be done while
387579bd3712SFilipe Manana  * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
387679bd3712SFilipe Manana  * an extent buffer from the chunks btree we never trigger allocation of a new
387779bd3712SFilipe Manana  * system chunk, which would result in a deadlock (trying to lock twice an
387879bd3712SFilipe Manana  * extent buffer of the chunk btree, first time before triggering the chunk
387979bd3712SFilipe Manana  * allocation and the second time during chunk allocation while attempting to
388079bd3712SFilipe Manana  * update the chunks btree). The system chunk array is also updated while holding
388179bd3712SFilipe Manana  * that mutex. The same logic applies to removing chunks - we must reserve system
388279bd3712SFilipe Manana  * space, update the chunk btree and the system chunk array in the superblock
388379bd3712SFilipe Manana  * while holding fs_info->chunk_mutex.
388479bd3712SFilipe Manana  *
388579bd3712SFilipe Manana  * This function, btrfs_chunk_alloc(), belongs to phase 1.
388679bd3712SFilipe Manana  *
388779bd3712SFilipe Manana  * If @force is CHUNK_ALLOC_FORCE:
388807730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
388907730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
389079bd3712SFilipe Manana  * If @force is NOT CHUNK_ALLOC_FORCE:
389107730d87SJosef Bacik  *    - return 0 if it doesn't need to allocate a new chunk,
389207730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
389307730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
389407730d87SJosef Bacik  */
389507730d87SJosef Bacik int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
389607730d87SJosef Bacik 		      enum btrfs_chunk_alloc_enum force)
389707730d87SJosef Bacik {
389807730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
389907730d87SJosef Bacik 	struct btrfs_space_info *space_info;
3900820c363bSNaohiro Aota 	struct btrfs_block_group *ret_bg;
390107730d87SJosef Bacik 	bool wait_for_alloc = false;
390207730d87SJosef Bacik 	bool should_alloc = false;
3903760e69c4SNaohiro Aota 	bool from_extent_allocation = false;
390407730d87SJosef Bacik 	int ret = 0;
390507730d87SJosef Bacik 
3906760e69c4SNaohiro Aota 	if (force == CHUNK_ALLOC_FORCE_FOR_EXTENT) {
3907760e69c4SNaohiro Aota 		from_extent_allocation = true;
3908760e69c4SNaohiro Aota 		force = CHUNK_ALLOC_FORCE;
3909760e69c4SNaohiro Aota 	}
3910760e69c4SNaohiro Aota 
391107730d87SJosef Bacik 	/* Don't re-enter if we're already allocating a chunk */
391207730d87SJosef Bacik 	if (trans->allocating_chunk)
391307730d87SJosef Bacik 		return -ENOSPC;
391479bd3712SFilipe Manana 	/*
39152bb2e00eSFilipe Manana 	 * Allocation of system chunks can not happen through this path, as we
39162bb2e00eSFilipe Manana 	 * could end up in a deadlock if we are allocating a data or metadata
39172bb2e00eSFilipe Manana 	 * chunk and there is another task modifying the chunk btree.
39182bb2e00eSFilipe Manana 	 *
39192bb2e00eSFilipe Manana 	 * This is because while we are holding the chunk mutex, we will attempt
39202bb2e00eSFilipe Manana 	 * to add the new chunk item to the chunk btree or update an existing
39212bb2e00eSFilipe Manana 	 * device item in the chunk btree, while the other task that is modifying
39222bb2e00eSFilipe Manana 	 * the chunk btree is attempting to COW an extent buffer while holding a
39232bb2e00eSFilipe Manana 	 * lock on it and on its parent - if the COW operation triggers a system
39242bb2e00eSFilipe Manana 	 * chunk allocation, then we can deadlock because we are holding the
39252bb2e00eSFilipe Manana 	 * chunk mutex and we may need to access that extent buffer or its parent
39262bb2e00eSFilipe Manana 	 * in order to add the chunk item or update a device item.
39272bb2e00eSFilipe Manana 	 *
39282bb2e00eSFilipe Manana 	 * Tasks that want to modify the chunk tree should reserve system space
39292bb2e00eSFilipe Manana 	 * before updating the chunk btree, by calling either
39302bb2e00eSFilipe Manana 	 * btrfs_reserve_chunk_metadata() or check_system_chunk().
39312bb2e00eSFilipe Manana 	 * It's possible that after a task reserves the space, it still ends up
39322bb2e00eSFilipe Manana 	 * here - this happens in the cases described above at do_chunk_alloc().
39332bb2e00eSFilipe Manana 	 * The task will have to either retry or fail.
393479bd3712SFilipe Manana 	 */
39352bb2e00eSFilipe Manana 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
393679bd3712SFilipe Manana 		return -ENOSPC;
393707730d87SJosef Bacik 
393807730d87SJosef Bacik 	space_info = btrfs_find_space_info(fs_info, flags);
393907730d87SJosef Bacik 	ASSERT(space_info);
394007730d87SJosef Bacik 
394107730d87SJosef Bacik 	do {
394207730d87SJosef Bacik 		spin_lock(&space_info->lock);
394307730d87SJosef Bacik 		if (force < space_info->force_alloc)
394407730d87SJosef Bacik 			force = space_info->force_alloc;
394507730d87SJosef Bacik 		should_alloc = should_alloc_chunk(fs_info, space_info, force);
394607730d87SJosef Bacik 		if (space_info->full) {
394707730d87SJosef Bacik 			/* No more free physical space */
394807730d87SJosef Bacik 			if (should_alloc)
394907730d87SJosef Bacik 				ret = -ENOSPC;
395007730d87SJosef Bacik 			else
395107730d87SJosef Bacik 				ret = 0;
395207730d87SJosef Bacik 			spin_unlock(&space_info->lock);
395307730d87SJosef Bacik 			return ret;
395407730d87SJosef Bacik 		} else if (!should_alloc) {
395507730d87SJosef Bacik 			spin_unlock(&space_info->lock);
395607730d87SJosef Bacik 			return 0;
395707730d87SJosef Bacik 		} else if (space_info->chunk_alloc) {
395807730d87SJosef Bacik 			/*
395907730d87SJosef Bacik 			 * Someone is already allocating, so we need to block
396007730d87SJosef Bacik 			 * until this someone is finished and then loop to
396107730d87SJosef Bacik 			 * recheck if we should continue with our allocation
396207730d87SJosef Bacik 			 * attempt.
396307730d87SJosef Bacik 			 */
396407730d87SJosef Bacik 			wait_for_alloc = true;
39651314ca78SJosef Bacik 			force = CHUNK_ALLOC_NO_FORCE;
396607730d87SJosef Bacik 			spin_unlock(&space_info->lock);
396707730d87SJosef Bacik 			mutex_lock(&fs_info->chunk_mutex);
396807730d87SJosef Bacik 			mutex_unlock(&fs_info->chunk_mutex);
396907730d87SJosef Bacik 		} else {
397007730d87SJosef Bacik 			/* Proceed with allocation */
397107730d87SJosef Bacik 			space_info->chunk_alloc = 1;
397207730d87SJosef Bacik 			wait_for_alloc = false;
397307730d87SJosef Bacik 			spin_unlock(&space_info->lock);
397407730d87SJosef Bacik 		}
397507730d87SJosef Bacik 
397607730d87SJosef Bacik 		cond_resched();
397707730d87SJosef Bacik 	} while (wait_for_alloc);
397807730d87SJosef Bacik 
397907730d87SJosef Bacik 	mutex_lock(&fs_info->chunk_mutex);
398007730d87SJosef Bacik 	trans->allocating_chunk = true;
398107730d87SJosef Bacik 
398207730d87SJosef Bacik 	/*
398307730d87SJosef Bacik 	 * If we have mixed data/metadata chunks we want to make sure we keep
398407730d87SJosef Bacik 	 * allocating mixed chunks instead of individual chunks.
398507730d87SJosef Bacik 	 */
398607730d87SJosef Bacik 	if (btrfs_mixed_space_info(space_info))
398707730d87SJosef Bacik 		flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
398807730d87SJosef Bacik 
398907730d87SJosef Bacik 	/*
399007730d87SJosef Bacik 	 * if we're doing a data chunk, go ahead and make sure that
399107730d87SJosef Bacik 	 * we keep a reasonable number of metadata chunks allocated in the
399207730d87SJosef Bacik 	 * FS as well.
399307730d87SJosef Bacik 	 */
399407730d87SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
399507730d87SJosef Bacik 		fs_info->data_chunk_allocations++;
399607730d87SJosef Bacik 		if (!(fs_info->data_chunk_allocations %
399707730d87SJosef Bacik 		      fs_info->metadata_ratio))
399807730d87SJosef Bacik 			force_metadata_allocation(fs_info);
399907730d87SJosef Bacik 	}
400007730d87SJosef Bacik 
4001820c363bSNaohiro Aota 	ret_bg = do_chunk_alloc(trans, flags);
400207730d87SJosef Bacik 	trans->allocating_chunk = false;
400307730d87SJosef Bacik 
4004760e69c4SNaohiro Aota 	if (IS_ERR(ret_bg)) {
4005820c363bSNaohiro Aota 		ret = PTR_ERR(ret_bg);
4006760e69c4SNaohiro Aota 	} else if (from_extent_allocation) {
4007760e69c4SNaohiro Aota 		/*
4008760e69c4SNaohiro Aota 		 * New block group is likely to be used soon. Try to activate
4009760e69c4SNaohiro Aota 		 * it now. Failure is OK for now.
4010760e69c4SNaohiro Aota 		 */
4011760e69c4SNaohiro Aota 		btrfs_zone_activate(ret_bg);
4012760e69c4SNaohiro Aota 	}
4013760e69c4SNaohiro Aota 
4014760e69c4SNaohiro Aota 	if (!ret)
4015820c363bSNaohiro Aota 		btrfs_put_block_group(ret_bg);
4016820c363bSNaohiro Aota 
401707730d87SJosef Bacik 	spin_lock(&space_info->lock);
401807730d87SJosef Bacik 	if (ret < 0) {
401907730d87SJosef Bacik 		if (ret == -ENOSPC)
402007730d87SJosef Bacik 			space_info->full = 1;
402107730d87SJosef Bacik 		else
402207730d87SJosef Bacik 			goto out;
402307730d87SJosef Bacik 	} else {
402407730d87SJosef Bacik 		ret = 1;
402507730d87SJosef Bacik 		space_info->max_extent_size = 0;
402607730d87SJosef Bacik 	}
402707730d87SJosef Bacik 
402807730d87SJosef Bacik 	space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
402907730d87SJosef Bacik out:
403007730d87SJosef Bacik 	space_info->chunk_alloc = 0;
403107730d87SJosef Bacik 	spin_unlock(&space_info->lock);
403207730d87SJosef Bacik 	mutex_unlock(&fs_info->chunk_mutex);
403307730d87SJosef Bacik 
403407730d87SJosef Bacik 	return ret;
403507730d87SJosef Bacik }
403607730d87SJosef Bacik 
403707730d87SJosef Bacik static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
403807730d87SJosef Bacik {
403907730d87SJosef Bacik 	u64 num_dev;
404007730d87SJosef Bacik 
404107730d87SJosef Bacik 	num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
404207730d87SJosef Bacik 	if (!num_dev)
404307730d87SJosef Bacik 		num_dev = fs_info->fs_devices->rw_devices;
404407730d87SJosef Bacik 
404507730d87SJosef Bacik 	return num_dev;
404607730d87SJosef Bacik }
404707730d87SJosef Bacik 
40482bb2e00eSFilipe Manana static void reserve_chunk_space(struct btrfs_trans_handle *trans,
40492bb2e00eSFilipe Manana 				u64 bytes,
40502bb2e00eSFilipe Manana 				u64 type)
405107730d87SJosef Bacik {
405207730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
405307730d87SJosef Bacik 	struct btrfs_space_info *info;
405407730d87SJosef Bacik 	u64 left;
405507730d87SJosef Bacik 	int ret = 0;
405607730d87SJosef Bacik 
405707730d87SJosef Bacik 	/*
405807730d87SJosef Bacik 	 * Needed because we can end up allocating a system chunk and for an
405907730d87SJosef Bacik 	 * atomic and race free space reservation in the chunk block reserve.
406007730d87SJosef Bacik 	 */
406107730d87SJosef Bacik 	lockdep_assert_held(&fs_info->chunk_mutex);
406207730d87SJosef Bacik 
406307730d87SJosef Bacik 	info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
406407730d87SJosef Bacik 	spin_lock(&info->lock);
406507730d87SJosef Bacik 	left = info->total_bytes - btrfs_space_info_used(info, true);
406607730d87SJosef Bacik 	spin_unlock(&info->lock);
406707730d87SJosef Bacik 
40682bb2e00eSFilipe Manana 	if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
406907730d87SJosef Bacik 		btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
40702bb2e00eSFilipe Manana 			   left, bytes, type);
407107730d87SJosef Bacik 		btrfs_dump_space_info(fs_info, info, 0, 0);
407207730d87SJosef Bacik 	}
407307730d87SJosef Bacik 
40742bb2e00eSFilipe Manana 	if (left < bytes) {
407507730d87SJosef Bacik 		u64 flags = btrfs_system_alloc_profile(fs_info);
407679bd3712SFilipe Manana 		struct btrfs_block_group *bg;
407707730d87SJosef Bacik 
407807730d87SJosef Bacik 		/*
407907730d87SJosef Bacik 		 * Ignore failure to create system chunk. We might end up not
408007730d87SJosef Bacik 		 * needing it, as we might not need to COW all nodes/leafs from
408107730d87SJosef Bacik 		 * the paths we visit in the chunk tree (they were already COWed
408207730d87SJosef Bacik 		 * or created in the current transaction for example).
408307730d87SJosef Bacik 		 */
4084f6f39f7aSNikolay Borisov 		bg = btrfs_create_chunk(trans, flags);
408579bd3712SFilipe Manana 		if (IS_ERR(bg)) {
408679bd3712SFilipe Manana 			ret = PTR_ERR(bg);
40872bb2e00eSFilipe Manana 		} else {
408879bd3712SFilipe Manana 			/*
4089b6a98021SNaohiro Aota 			 * We have a new chunk. We also need to activate it for
4090b6a98021SNaohiro Aota 			 * zoned filesystem.
4091b6a98021SNaohiro Aota 			 */
4092b6a98021SNaohiro Aota 			ret = btrfs_zoned_activate_one_bg(fs_info, info, true);
4093b6a98021SNaohiro Aota 			if (ret < 0)
4094b6a98021SNaohiro Aota 				return;
4095b6a98021SNaohiro Aota 
4096b6a98021SNaohiro Aota 			/*
409779bd3712SFilipe Manana 			 * If we fail to add the chunk item here, we end up
409879bd3712SFilipe Manana 			 * trying again at phase 2 of chunk allocation, at
409979bd3712SFilipe Manana 			 * btrfs_create_pending_block_groups(). So ignore
41002bb2e00eSFilipe Manana 			 * any error here. An ENOSPC here could happen, due to
41012bb2e00eSFilipe Manana 			 * the cases described at do_chunk_alloc() - the system
41022bb2e00eSFilipe Manana 			 * block group we just created was just turned into RO
41032bb2e00eSFilipe Manana 			 * mode by a scrub for example, or a running discard
41042bb2e00eSFilipe Manana 			 * temporarily removed its free space entries, etc.
410579bd3712SFilipe Manana 			 */
410679bd3712SFilipe Manana 			btrfs_chunk_alloc_add_chunk_item(trans, bg);
410779bd3712SFilipe Manana 		}
410807730d87SJosef Bacik 	}
410907730d87SJosef Bacik 
411007730d87SJosef Bacik 	if (!ret) {
41119270501cSJosef Bacik 		ret = btrfs_block_rsv_add(fs_info,
411207730d87SJosef Bacik 					  &fs_info->chunk_block_rsv,
41132bb2e00eSFilipe Manana 					  bytes, BTRFS_RESERVE_NO_FLUSH);
41141cb3db1cSFilipe Manana 		if (!ret)
41152bb2e00eSFilipe Manana 			trans->chunk_bytes_reserved += bytes;
411607730d87SJosef Bacik 	}
411707730d87SJosef Bacik }
411807730d87SJosef Bacik 
41192bb2e00eSFilipe Manana /*
41202bb2e00eSFilipe Manana  * Reserve space in the system space for allocating or removing a chunk.
41212bb2e00eSFilipe Manana  * The caller must be holding fs_info->chunk_mutex.
41222bb2e00eSFilipe Manana  */
41232bb2e00eSFilipe Manana void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
41242bb2e00eSFilipe Manana {
41252bb2e00eSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
41262bb2e00eSFilipe Manana 	const u64 num_devs = get_profile_num_devs(fs_info, type);
41272bb2e00eSFilipe Manana 	u64 bytes;
41282bb2e00eSFilipe Manana 
41292bb2e00eSFilipe Manana 	/* num_devs device items to update and 1 chunk item to add or remove. */
41302bb2e00eSFilipe Manana 	bytes = btrfs_calc_metadata_size(fs_info, num_devs) +
41312bb2e00eSFilipe Manana 		btrfs_calc_insert_metadata_size(fs_info, 1);
41322bb2e00eSFilipe Manana 
41332bb2e00eSFilipe Manana 	reserve_chunk_space(trans, bytes, type);
41342bb2e00eSFilipe Manana }
41352bb2e00eSFilipe Manana 
41362bb2e00eSFilipe Manana /*
41372bb2e00eSFilipe Manana  * Reserve space in the system space, if needed, for doing a modification to the
41382bb2e00eSFilipe Manana  * chunk btree.
41392bb2e00eSFilipe Manana  *
41402bb2e00eSFilipe Manana  * @trans:		A transaction handle.
41412bb2e00eSFilipe Manana  * @is_item_insertion:	Indicate if the modification is for inserting a new item
41422bb2e00eSFilipe Manana  *			in the chunk btree or if it's for the deletion or update
41432bb2e00eSFilipe Manana  *			of an existing item.
41442bb2e00eSFilipe Manana  *
41452bb2e00eSFilipe Manana  * This is used in a context where we need to update the chunk btree outside
41462bb2e00eSFilipe Manana  * block group allocation and removal, to avoid a deadlock with a concurrent
41472bb2e00eSFilipe Manana  * task that is allocating a metadata or data block group and therefore needs to
41482bb2e00eSFilipe Manana  * update the chunk btree while holding the chunk mutex. After the update to the
41492bb2e00eSFilipe Manana  * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called.
41502bb2e00eSFilipe Manana  *
41512bb2e00eSFilipe Manana  */
41522bb2e00eSFilipe Manana void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans,
41532bb2e00eSFilipe Manana 				  bool is_item_insertion)
41542bb2e00eSFilipe Manana {
41552bb2e00eSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
41562bb2e00eSFilipe Manana 	u64 bytes;
41572bb2e00eSFilipe Manana 
41582bb2e00eSFilipe Manana 	if (is_item_insertion)
41592bb2e00eSFilipe Manana 		bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
41602bb2e00eSFilipe Manana 	else
41612bb2e00eSFilipe Manana 		bytes = btrfs_calc_metadata_size(fs_info, 1);
41622bb2e00eSFilipe Manana 
41632bb2e00eSFilipe Manana 	mutex_lock(&fs_info->chunk_mutex);
41642bb2e00eSFilipe Manana 	reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM);
41652bb2e00eSFilipe Manana 	mutex_unlock(&fs_info->chunk_mutex);
41662bb2e00eSFilipe Manana }
41672bb2e00eSFilipe Manana 
41683e43c279SJosef Bacik void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
41693e43c279SJosef Bacik {
417032da5386SDavid Sterba 	struct btrfs_block_group *block_group;
41713e43c279SJosef Bacik 
417250c31eaaSJosef Bacik 	block_group = btrfs_lookup_first_block_group(info, 0);
41733e43c279SJosef Bacik 	while (block_group) {
41743e43c279SJosef Bacik 		btrfs_wait_block_group_cache_done(block_group);
41753e43c279SJosef Bacik 		spin_lock(&block_group->lock);
417650c31eaaSJosef Bacik 		if (test_and_clear_bit(BLOCK_GROUP_FLAG_IREF,
417750c31eaaSJosef Bacik 				       &block_group->runtime_flags)) {
417850c31eaaSJosef Bacik 			struct inode *inode = block_group->inode;
41793e43c279SJosef Bacik 
41803e43c279SJosef Bacik 			block_group->inode = NULL;
41813e43c279SJosef Bacik 			spin_unlock(&block_group->lock);
418250c31eaaSJosef Bacik 
41833e43c279SJosef Bacik 			ASSERT(block_group->io_ctl.inode == NULL);
41843e43c279SJosef Bacik 			iput(inode);
418550c31eaaSJosef Bacik 		} else {
418650c31eaaSJosef Bacik 			spin_unlock(&block_group->lock);
418750c31eaaSJosef Bacik 		}
418850c31eaaSJosef Bacik 		block_group = btrfs_next_block_group(block_group);
41893e43c279SJosef Bacik 	}
41903e43c279SJosef Bacik }
41913e43c279SJosef Bacik 
41923e43c279SJosef Bacik /*
41933e43c279SJosef Bacik  * Must be called only after stopping all workers, since we could have block
41943e43c279SJosef Bacik  * group caching kthreads running, and therefore they could race with us if we
41953e43c279SJosef Bacik  * freed the block groups before stopping them.
41963e43c279SJosef Bacik  */
41973e43c279SJosef Bacik int btrfs_free_block_groups(struct btrfs_fs_info *info)
41983e43c279SJosef Bacik {
419932da5386SDavid Sterba 	struct btrfs_block_group *block_group;
42003e43c279SJosef Bacik 	struct btrfs_space_info *space_info;
42013e43c279SJosef Bacik 	struct btrfs_caching_control *caching_ctl;
42023e43c279SJosef Bacik 	struct rb_node *n;
42033e43c279SJosef Bacik 
420416b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
42053e43c279SJosef Bacik 	while (!list_empty(&info->caching_block_groups)) {
42063e43c279SJosef Bacik 		caching_ctl = list_entry(info->caching_block_groups.next,
42073e43c279SJosef Bacik 					 struct btrfs_caching_control, list);
42083e43c279SJosef Bacik 		list_del(&caching_ctl->list);
42093e43c279SJosef Bacik 		btrfs_put_caching_control(caching_ctl);
42103e43c279SJosef Bacik 	}
421116b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
42123e43c279SJosef Bacik 
42133e43c279SJosef Bacik 	spin_lock(&info->unused_bgs_lock);
42143e43c279SJosef Bacik 	while (!list_empty(&info->unused_bgs)) {
42153e43c279SJosef Bacik 		block_group = list_first_entry(&info->unused_bgs,
421632da5386SDavid Sterba 					       struct btrfs_block_group,
42173e43c279SJosef Bacik 					       bg_list);
42183e43c279SJosef Bacik 		list_del_init(&block_group->bg_list);
42193e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
42203e43c279SJosef Bacik 	}
42213e43c279SJosef Bacik 
422218bb8bbfSJohannes Thumshirn 	while (!list_empty(&info->reclaim_bgs)) {
422318bb8bbfSJohannes Thumshirn 		block_group = list_first_entry(&info->reclaim_bgs,
422418bb8bbfSJohannes Thumshirn 					       struct btrfs_block_group,
422518bb8bbfSJohannes Thumshirn 					       bg_list);
422618bb8bbfSJohannes Thumshirn 		list_del_init(&block_group->bg_list);
422718bb8bbfSJohannes Thumshirn 		btrfs_put_block_group(block_group);
422818bb8bbfSJohannes Thumshirn 	}
422918bb8bbfSJohannes Thumshirn 	spin_unlock(&info->unused_bgs_lock);
423018bb8bbfSJohannes Thumshirn 
4231afba2bc0SNaohiro Aota 	spin_lock(&info->zone_active_bgs_lock);
4232afba2bc0SNaohiro Aota 	while (!list_empty(&info->zone_active_bgs)) {
4233afba2bc0SNaohiro Aota 		block_group = list_first_entry(&info->zone_active_bgs,
4234afba2bc0SNaohiro Aota 					       struct btrfs_block_group,
4235afba2bc0SNaohiro Aota 					       active_bg_list);
4236afba2bc0SNaohiro Aota 		list_del_init(&block_group->active_bg_list);
4237afba2bc0SNaohiro Aota 		btrfs_put_block_group(block_group);
4238afba2bc0SNaohiro Aota 	}
4239afba2bc0SNaohiro Aota 	spin_unlock(&info->zone_active_bgs_lock);
4240afba2bc0SNaohiro Aota 
424116b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
424208dddb29SFilipe Manana 	while ((n = rb_last(&info->block_group_cache_tree.rb_root)) != NULL) {
424332da5386SDavid Sterba 		block_group = rb_entry(n, struct btrfs_block_group,
42443e43c279SJosef Bacik 				       cache_node);
424508dddb29SFilipe Manana 		rb_erase_cached(&block_group->cache_node,
42463e43c279SJosef Bacik 				&info->block_group_cache_tree);
42473e43c279SJosef Bacik 		RB_CLEAR_NODE(&block_group->cache_node);
424816b0c258SFilipe Manana 		write_unlock(&info->block_group_cache_lock);
42493e43c279SJosef Bacik 
42503e43c279SJosef Bacik 		down_write(&block_group->space_info->groups_sem);
42513e43c279SJosef Bacik 		list_del(&block_group->list);
42523e43c279SJosef Bacik 		up_write(&block_group->space_info->groups_sem);
42533e43c279SJosef Bacik 
42543e43c279SJosef Bacik 		/*
42553e43c279SJosef Bacik 		 * We haven't cached this block group, which means we could
42563e43c279SJosef Bacik 		 * possibly have excluded extents on this block group.
42573e43c279SJosef Bacik 		 */
42583e43c279SJosef Bacik 		if (block_group->cached == BTRFS_CACHE_NO ||
42593e43c279SJosef Bacik 		    block_group->cached == BTRFS_CACHE_ERROR)
42603e43c279SJosef Bacik 			btrfs_free_excluded_extents(block_group);
42613e43c279SJosef Bacik 
42623e43c279SJosef Bacik 		btrfs_remove_free_space_cache(block_group);
42633e43c279SJosef Bacik 		ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
42643e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->dirty_list));
42653e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->io_list));
42663e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->bg_list));
426748aaeebeSJosef Bacik 		ASSERT(refcount_read(&block_group->refs) == 1);
4268195a49eaSFilipe Manana 		ASSERT(block_group->swap_extents == 0);
42693e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
42703e43c279SJosef Bacik 
427116b0c258SFilipe Manana 		write_lock(&info->block_group_cache_lock);
42723e43c279SJosef Bacik 	}
427316b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
42743e43c279SJosef Bacik 
42753e43c279SJosef Bacik 	btrfs_release_global_block_rsv(info);
42763e43c279SJosef Bacik 
42773e43c279SJosef Bacik 	while (!list_empty(&info->space_info)) {
42783e43c279SJosef Bacik 		space_info = list_entry(info->space_info.next,
42793e43c279SJosef Bacik 					struct btrfs_space_info,
42803e43c279SJosef Bacik 					list);
42813e43c279SJosef Bacik 
42823e43c279SJosef Bacik 		/*
42833e43c279SJosef Bacik 		 * Do not hide this behind enospc_debug, this is actually
42843e43c279SJosef Bacik 		 * important and indicates a real bug if this happens.
42853e43c279SJosef Bacik 		 */
42863e43c279SJosef Bacik 		if (WARN_ON(space_info->bytes_pinned > 0 ||
42873e43c279SJosef Bacik 			    space_info->bytes_may_use > 0))
42883e43c279SJosef Bacik 			btrfs_dump_space_info(info, space_info, 0, 0);
428940cdc509SFilipe Manana 
429040cdc509SFilipe Manana 		/*
429140cdc509SFilipe Manana 		 * If there was a failure to cleanup a log tree, very likely due
429240cdc509SFilipe Manana 		 * to an IO failure on a writeback attempt of one or more of its
429340cdc509SFilipe Manana 		 * extent buffers, we could not do proper (and cheap) unaccounting
429440cdc509SFilipe Manana 		 * of their reserved space, so don't warn on bytes_reserved > 0 in
429540cdc509SFilipe Manana 		 * that case.
429640cdc509SFilipe Manana 		 */
429740cdc509SFilipe Manana 		if (!(space_info->flags & BTRFS_BLOCK_GROUP_METADATA) ||
429840cdc509SFilipe Manana 		    !BTRFS_FS_LOG_CLEANUP_ERROR(info)) {
429940cdc509SFilipe Manana 			if (WARN_ON(space_info->bytes_reserved > 0))
430040cdc509SFilipe Manana 				btrfs_dump_space_info(info, space_info, 0, 0);
430140cdc509SFilipe Manana 		}
430240cdc509SFilipe Manana 
4303d611add4SFilipe Manana 		WARN_ON(space_info->reclaim_size > 0);
43043e43c279SJosef Bacik 		list_del(&space_info->list);
43053e43c279SJosef Bacik 		btrfs_sysfs_remove_space_info(space_info);
43063e43c279SJosef Bacik 	}
43073e43c279SJosef Bacik 	return 0;
43083e43c279SJosef Bacik }
4309684b752bSFilipe Manana 
4310684b752bSFilipe Manana void btrfs_freeze_block_group(struct btrfs_block_group *cache)
4311684b752bSFilipe Manana {
4312684b752bSFilipe Manana 	atomic_inc(&cache->frozen);
4313684b752bSFilipe Manana }
4314684b752bSFilipe Manana 
4315684b752bSFilipe Manana void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
4316684b752bSFilipe Manana {
4317684b752bSFilipe Manana 	struct btrfs_fs_info *fs_info = block_group->fs_info;
4318684b752bSFilipe Manana 	struct extent_map_tree *em_tree;
4319684b752bSFilipe Manana 	struct extent_map *em;
4320684b752bSFilipe Manana 	bool cleanup;
4321684b752bSFilipe Manana 
4322684b752bSFilipe Manana 	spin_lock(&block_group->lock);
4323684b752bSFilipe Manana 	cleanup = (atomic_dec_and_test(&block_group->frozen) &&
43243349b57fSJosef Bacik 		   test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags));
4325684b752bSFilipe Manana 	spin_unlock(&block_group->lock);
4326684b752bSFilipe Manana 
4327684b752bSFilipe Manana 	if (cleanup) {
4328684b752bSFilipe Manana 		em_tree = &fs_info->mapping_tree;
4329684b752bSFilipe Manana 		write_lock(&em_tree->lock);
4330684b752bSFilipe Manana 		em = lookup_extent_mapping(em_tree, block_group->start,
4331684b752bSFilipe Manana 					   1);
4332684b752bSFilipe Manana 		BUG_ON(!em); /* logic error, can't happen */
4333684b752bSFilipe Manana 		remove_extent_mapping(em_tree, em);
4334684b752bSFilipe Manana 		write_unlock(&em_tree->lock);
4335684b752bSFilipe Manana 
4336684b752bSFilipe Manana 		/* once for us and once for the tree */
4337684b752bSFilipe Manana 		free_extent_map(em);
4338684b752bSFilipe Manana 		free_extent_map(em);
4339684b752bSFilipe Manana 
4340684b752bSFilipe Manana 		/*
4341684b752bSFilipe Manana 		 * We may have left one free space entry and other possible
4342684b752bSFilipe Manana 		 * tasks trimming this block group have left 1 entry each one.
4343684b752bSFilipe Manana 		 * Free them if any.
4344684b752bSFilipe Manana 		 */
4345fc80f7acSJosef Bacik 		btrfs_remove_free_space_cache(block_group);
4346684b752bSFilipe Manana 	}
4347684b752bSFilipe Manana }
4348195a49eaSFilipe Manana 
4349195a49eaSFilipe Manana bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
4350195a49eaSFilipe Manana {
4351195a49eaSFilipe Manana 	bool ret = true;
4352195a49eaSFilipe Manana 
4353195a49eaSFilipe Manana 	spin_lock(&bg->lock);
4354195a49eaSFilipe Manana 	if (bg->ro)
4355195a49eaSFilipe Manana 		ret = false;
4356195a49eaSFilipe Manana 	else
4357195a49eaSFilipe Manana 		bg->swap_extents++;
4358195a49eaSFilipe Manana 	spin_unlock(&bg->lock);
4359195a49eaSFilipe Manana 
4360195a49eaSFilipe Manana 	return ret;
4361195a49eaSFilipe Manana }
4362195a49eaSFilipe Manana 
4363195a49eaSFilipe Manana void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
4364195a49eaSFilipe Manana {
4365195a49eaSFilipe Manana 	spin_lock(&bg->lock);
4366195a49eaSFilipe Manana 	ASSERT(!bg->ro);
4367195a49eaSFilipe Manana 	ASSERT(bg->swap_extents >= amount);
4368195a49eaSFilipe Manana 	bg->swap_extents -= amount;
4369195a49eaSFilipe Manana 	spin_unlock(&bg->lock);
4370195a49eaSFilipe Manana }
437152bb7a21SBoris Burkov 
437252bb7a21SBoris Burkov enum btrfs_block_group_size_class btrfs_calc_block_group_size_class(u64 size)
437352bb7a21SBoris Burkov {
437452bb7a21SBoris Burkov 	if (size <= SZ_128K)
437552bb7a21SBoris Burkov 		return BTRFS_BG_SZ_SMALL;
437652bb7a21SBoris Burkov 	if (size <= SZ_8M)
437752bb7a21SBoris Burkov 		return BTRFS_BG_SZ_MEDIUM;
437852bb7a21SBoris Burkov 	return BTRFS_BG_SZ_LARGE;
437952bb7a21SBoris Burkov }
438052bb7a21SBoris Burkov 
438152bb7a21SBoris Burkov /*
438252bb7a21SBoris Burkov  * Handle a block group allocating an extent in a size class
438352bb7a21SBoris Burkov  *
438452bb7a21SBoris Burkov  * @bg:				The block group we allocated in.
438552bb7a21SBoris Burkov  * @size_class:			The size class of the allocation.
438652bb7a21SBoris Burkov  * @force_wrong_size_class:	Whether we are desperate enough to allow
438752bb7a21SBoris Burkov  *				mismatched size classes.
438852bb7a21SBoris Burkov  *
438952bb7a21SBoris Burkov  * Returns: 0 if the size class was valid for this block_group, -EAGAIN in the
439052bb7a21SBoris Burkov  * case of a race that leads to the wrong size class without
439152bb7a21SBoris Burkov  * force_wrong_size_class set.
439252bb7a21SBoris Burkov  *
439352bb7a21SBoris Burkov  * find_free_extent will skip block groups with a mismatched size class until
439452bb7a21SBoris Burkov  * it really needs to avoid ENOSPC. In that case it will set
439552bb7a21SBoris Burkov  * force_wrong_size_class. However, if a block group is newly allocated and
439652bb7a21SBoris Burkov  * doesn't yet have a size class, then it is possible for two allocations of
439752bb7a21SBoris Burkov  * different sizes to race and both try to use it. The loser is caught here and
439852bb7a21SBoris Burkov  * has to retry.
439952bb7a21SBoris Burkov  */
440052bb7a21SBoris Burkov int btrfs_use_block_group_size_class(struct btrfs_block_group *bg,
440152bb7a21SBoris Burkov 				     enum btrfs_block_group_size_class size_class,
440252bb7a21SBoris Burkov 				     bool force_wrong_size_class)
440352bb7a21SBoris Burkov {
440452bb7a21SBoris Burkov 	ASSERT(size_class != BTRFS_BG_SZ_NONE);
440552bb7a21SBoris Burkov 
440652bb7a21SBoris Burkov 	/* The new allocation is in the right size class, do nothing */
440752bb7a21SBoris Burkov 	if (bg->size_class == size_class)
440852bb7a21SBoris Burkov 		return 0;
440952bb7a21SBoris Burkov 	/*
441052bb7a21SBoris Burkov 	 * The new allocation is in a mismatched size class.
441152bb7a21SBoris Burkov 	 * This means one of two things:
441252bb7a21SBoris Burkov 	 *
441352bb7a21SBoris Burkov 	 * 1. Two tasks in find_free_extent for different size_classes raced
441452bb7a21SBoris Burkov 	 *    and hit the same empty block_group. Make the loser try again.
441552bb7a21SBoris Burkov 	 * 2. A call to find_free_extent got desperate enough to set
441652bb7a21SBoris Burkov 	 *    'force_wrong_slab'. Don't change the size_class, but allow the
441752bb7a21SBoris Burkov 	 *    allocation.
441852bb7a21SBoris Burkov 	 */
441952bb7a21SBoris Burkov 	if (bg->size_class != BTRFS_BG_SZ_NONE) {
442052bb7a21SBoris Burkov 		if (force_wrong_size_class)
442152bb7a21SBoris Burkov 			return 0;
442252bb7a21SBoris Burkov 		return -EAGAIN;
442352bb7a21SBoris Burkov 	}
442452bb7a21SBoris Burkov 	/*
442552bb7a21SBoris Burkov 	 * The happy new block group case: the new allocation is the first
442652bb7a21SBoris Burkov 	 * one in the block_group so we set size_class.
442752bb7a21SBoris Burkov 	 */
442852bb7a21SBoris Burkov 	bg->size_class = size_class;
442952bb7a21SBoris Burkov 
443052bb7a21SBoris Burkov 	return 0;
443152bb7a21SBoris Burkov }
4432cb0922f2SBoris Burkov 
4433cb0922f2SBoris Burkov bool btrfs_block_group_should_use_size_class(struct btrfs_block_group *bg)
4434cb0922f2SBoris Burkov {
4435cb0922f2SBoris Burkov 	if (btrfs_is_zoned(bg->fs_info))
4436cb0922f2SBoris Burkov 		return false;
4437cb0922f2SBoris Burkov 	if (!btrfs_is_block_group_data_only(bg))
4438cb0922f2SBoris Burkov 		return false;
4439cb0922f2SBoris Burkov 	return true;
4440cb0922f2SBoris Burkov }
4441