xref: /linux/fs/btrfs/block-group.c (revision 2306e83e730a86fbf6855d4611438d8632ad2e73)
12e405ad8SJosef Bacik // SPDX-License-Identifier: GPL-2.0
22e405ad8SJosef Bacik 
32ca0ec77SJohannes Thumshirn #include <linux/list_sort.h>
4784352feSDavid Sterba #include "misc.h"
52e405ad8SJosef Bacik #include "ctree.h"
62e405ad8SJosef Bacik #include "block-group.h"
73eeb3226SJosef Bacik #include "space-info.h"
89f21246dSJosef Bacik #include "disk-io.h"
99f21246dSJosef Bacik #include "free-space-cache.h"
109f21246dSJosef Bacik #include "free-space-tree.h"
11e3e0520bSJosef Bacik #include "volumes.h"
12e3e0520bSJosef Bacik #include "transaction.h"
13e3e0520bSJosef Bacik #include "ref-verify.h"
144358d963SJosef Bacik #include "sysfs.h"
154358d963SJosef Bacik #include "tree-log.h"
1677745c05SJosef Bacik #include "delalloc-space.h"
17b0643e59SDennis Zhou #include "discard.h"
1896a14336SNikolay Borisov #include "raid56.h"
1908e11a3dSNaohiro Aota #include "zoned.h"
202e405ad8SJosef Bacik 
21878d7b67SJosef Bacik /*
22878d7b67SJosef Bacik  * Return target flags in extended format or 0 if restripe for this chunk_type
23878d7b67SJosef Bacik  * is not in progress
24878d7b67SJosef Bacik  *
25878d7b67SJosef Bacik  * Should be called with balance_lock held
26878d7b67SJosef Bacik  */
27e11c0406SJosef Bacik static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
28878d7b67SJosef Bacik {
29878d7b67SJosef Bacik 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
30878d7b67SJosef Bacik 	u64 target = 0;
31878d7b67SJosef Bacik 
32878d7b67SJosef Bacik 	if (!bctl)
33878d7b67SJosef Bacik 		return 0;
34878d7b67SJosef Bacik 
35878d7b67SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA &&
36878d7b67SJosef Bacik 	    bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
37878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
38878d7b67SJosef Bacik 	} else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
39878d7b67SJosef Bacik 		   bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
40878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
41878d7b67SJosef Bacik 	} else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
42878d7b67SJosef Bacik 		   bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
43878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
44878d7b67SJosef Bacik 	}
45878d7b67SJosef Bacik 
46878d7b67SJosef Bacik 	return target;
47878d7b67SJosef Bacik }
48878d7b67SJosef Bacik 
49878d7b67SJosef Bacik /*
50878d7b67SJosef Bacik  * @flags: available profiles in extended format (see ctree.h)
51878d7b67SJosef Bacik  *
52878d7b67SJosef Bacik  * Return reduced profile in chunk format.  If profile changing is in progress
53878d7b67SJosef Bacik  * (either running or paused) picks the target profile (if it's already
54878d7b67SJosef Bacik  * available), otherwise falls back to plain reducing.
55878d7b67SJosef Bacik  */
56878d7b67SJosef Bacik static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
57878d7b67SJosef Bacik {
58878d7b67SJosef Bacik 	u64 num_devices = fs_info->fs_devices->rw_devices;
59878d7b67SJosef Bacik 	u64 target;
60878d7b67SJosef Bacik 	u64 raid_type;
61878d7b67SJosef Bacik 	u64 allowed = 0;
62878d7b67SJosef Bacik 
63878d7b67SJosef Bacik 	/*
64878d7b67SJosef Bacik 	 * See if restripe for this chunk_type is in progress, if so try to
65878d7b67SJosef Bacik 	 * reduce to the target profile
66878d7b67SJosef Bacik 	 */
67878d7b67SJosef Bacik 	spin_lock(&fs_info->balance_lock);
68e11c0406SJosef Bacik 	target = get_restripe_target(fs_info, flags);
69878d7b67SJosef Bacik 	if (target) {
70878d7b67SJosef Bacik 		spin_unlock(&fs_info->balance_lock);
71878d7b67SJosef Bacik 		return extended_to_chunk(target);
72878d7b67SJosef Bacik 	}
73878d7b67SJosef Bacik 	spin_unlock(&fs_info->balance_lock);
74878d7b67SJosef Bacik 
75878d7b67SJosef Bacik 	/* First, mask out the RAID levels which aren't possible */
76878d7b67SJosef Bacik 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
77878d7b67SJosef Bacik 		if (num_devices >= btrfs_raid_array[raid_type].devs_min)
78878d7b67SJosef Bacik 			allowed |= btrfs_raid_array[raid_type].bg_flag;
79878d7b67SJosef Bacik 	}
80878d7b67SJosef Bacik 	allowed &= flags;
81878d7b67SJosef Bacik 
82878d7b67SJosef Bacik 	if (allowed & BTRFS_BLOCK_GROUP_RAID6)
83878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID6;
84878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
85878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID5;
86878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
87878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID10;
88878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
89878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID1;
90878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
91878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID0;
92878d7b67SJosef Bacik 
93878d7b67SJosef Bacik 	flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
94878d7b67SJosef Bacik 
95878d7b67SJosef Bacik 	return extended_to_chunk(flags | allowed);
96878d7b67SJosef Bacik }
97878d7b67SJosef Bacik 
98ef0a82daSJohannes Thumshirn u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
99878d7b67SJosef Bacik {
100878d7b67SJosef Bacik 	unsigned seq;
101878d7b67SJosef Bacik 	u64 flags;
102878d7b67SJosef Bacik 
103878d7b67SJosef Bacik 	do {
104878d7b67SJosef Bacik 		flags = orig_flags;
105878d7b67SJosef Bacik 		seq = read_seqbegin(&fs_info->profiles_lock);
106878d7b67SJosef Bacik 
107878d7b67SJosef Bacik 		if (flags & BTRFS_BLOCK_GROUP_DATA)
108878d7b67SJosef Bacik 			flags |= fs_info->avail_data_alloc_bits;
109878d7b67SJosef Bacik 		else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
110878d7b67SJosef Bacik 			flags |= fs_info->avail_system_alloc_bits;
111878d7b67SJosef Bacik 		else if (flags & BTRFS_BLOCK_GROUP_METADATA)
112878d7b67SJosef Bacik 			flags |= fs_info->avail_metadata_alloc_bits;
113878d7b67SJosef Bacik 	} while (read_seqretry(&fs_info->profiles_lock, seq));
114878d7b67SJosef Bacik 
115878d7b67SJosef Bacik 	return btrfs_reduce_alloc_profile(fs_info, flags);
116878d7b67SJosef Bacik }
117878d7b67SJosef Bacik 
11832da5386SDavid Sterba void btrfs_get_block_group(struct btrfs_block_group *cache)
1193cad1284SJosef Bacik {
12048aaeebeSJosef Bacik 	refcount_inc(&cache->refs);
1213cad1284SJosef Bacik }
1223cad1284SJosef Bacik 
12332da5386SDavid Sterba void btrfs_put_block_group(struct btrfs_block_group *cache)
1243cad1284SJosef Bacik {
12548aaeebeSJosef Bacik 	if (refcount_dec_and_test(&cache->refs)) {
1263cad1284SJosef Bacik 		WARN_ON(cache->pinned > 0);
12740cdc509SFilipe Manana 		/*
12840cdc509SFilipe Manana 		 * If there was a failure to cleanup a log tree, very likely due
12940cdc509SFilipe Manana 		 * to an IO failure on a writeback attempt of one or more of its
13040cdc509SFilipe Manana 		 * extent buffers, we could not do proper (and cheap) unaccounting
13140cdc509SFilipe Manana 		 * of their reserved space, so don't warn on reserved > 0 in that
13240cdc509SFilipe Manana 		 * case.
13340cdc509SFilipe Manana 		 */
13440cdc509SFilipe Manana 		if (!(cache->flags & BTRFS_BLOCK_GROUP_METADATA) ||
13540cdc509SFilipe Manana 		    !BTRFS_FS_LOG_CLEANUP_ERROR(cache->fs_info))
1363cad1284SJosef Bacik 			WARN_ON(cache->reserved > 0);
1373cad1284SJosef Bacik 
1383cad1284SJosef Bacik 		/*
139b0643e59SDennis Zhou 		 * A block_group shouldn't be on the discard_list anymore.
140b0643e59SDennis Zhou 		 * Remove the block_group from the discard_list to prevent us
141b0643e59SDennis Zhou 		 * from causing a panic due to NULL pointer dereference.
142b0643e59SDennis Zhou 		 */
143b0643e59SDennis Zhou 		if (WARN_ON(!list_empty(&cache->discard_list)))
144b0643e59SDennis Zhou 			btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
145b0643e59SDennis Zhou 						  cache);
146b0643e59SDennis Zhou 
147b0643e59SDennis Zhou 		/*
1483cad1284SJosef Bacik 		 * If not empty, someone is still holding mutex of
1493cad1284SJosef Bacik 		 * full_stripe_lock, which can only be released by caller.
1503cad1284SJosef Bacik 		 * And it will definitely cause use-after-free when caller
1513cad1284SJosef Bacik 		 * tries to release full stripe lock.
1523cad1284SJosef Bacik 		 *
1533cad1284SJosef Bacik 		 * No better way to resolve, but only to warn.
1543cad1284SJosef Bacik 		 */
1553cad1284SJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
1563cad1284SJosef Bacik 		kfree(cache->free_space_ctl);
157dafc340dSNaohiro Aota 		kfree(cache->physical_map);
1583cad1284SJosef Bacik 		kfree(cache);
1593cad1284SJosef Bacik 	}
1603cad1284SJosef Bacik }
1613cad1284SJosef Bacik 
1622e405ad8SJosef Bacik /*
1634358d963SJosef Bacik  * This adds the block group to the fs_info rb tree for the block group cache
1644358d963SJosef Bacik  */
1654358d963SJosef Bacik static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
16632da5386SDavid Sterba 				       struct btrfs_block_group *block_group)
1674358d963SJosef Bacik {
1684358d963SJosef Bacik 	struct rb_node **p;
1694358d963SJosef Bacik 	struct rb_node *parent = NULL;
17032da5386SDavid Sterba 	struct btrfs_block_group *cache;
17108dddb29SFilipe Manana 	bool leftmost = true;
1724358d963SJosef Bacik 
1739afc6649SQu Wenruo 	ASSERT(block_group->length != 0);
1749afc6649SQu Wenruo 
17516b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
17608dddb29SFilipe Manana 	p = &info->block_group_cache_tree.rb_root.rb_node;
1774358d963SJosef Bacik 
1784358d963SJosef Bacik 	while (*p) {
1794358d963SJosef Bacik 		parent = *p;
18032da5386SDavid Sterba 		cache = rb_entry(parent, struct btrfs_block_group, cache_node);
181b3470b5dSDavid Sterba 		if (block_group->start < cache->start) {
1824358d963SJosef Bacik 			p = &(*p)->rb_left;
183b3470b5dSDavid Sterba 		} else if (block_group->start > cache->start) {
1844358d963SJosef Bacik 			p = &(*p)->rb_right;
18508dddb29SFilipe Manana 			leftmost = false;
1864358d963SJosef Bacik 		} else {
18716b0c258SFilipe Manana 			write_unlock(&info->block_group_cache_lock);
1884358d963SJosef Bacik 			return -EEXIST;
1894358d963SJosef Bacik 		}
1904358d963SJosef Bacik 	}
1914358d963SJosef Bacik 
1924358d963SJosef Bacik 	rb_link_node(&block_group->cache_node, parent, p);
19308dddb29SFilipe Manana 	rb_insert_color_cached(&block_group->cache_node,
19408dddb29SFilipe Manana 			       &info->block_group_cache_tree, leftmost);
1954358d963SJosef Bacik 
19616b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
1974358d963SJosef Bacik 
1984358d963SJosef Bacik 	return 0;
1994358d963SJosef Bacik }
2004358d963SJosef Bacik 
2014358d963SJosef Bacik /*
2022e405ad8SJosef Bacik  * This will return the block group at or after bytenr if contains is 0, else
2032e405ad8SJosef Bacik  * it will return the block group that contains the bytenr
2042e405ad8SJosef Bacik  */
20532da5386SDavid Sterba static struct btrfs_block_group *block_group_cache_tree_search(
2062e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr, int contains)
2072e405ad8SJosef Bacik {
20832da5386SDavid Sterba 	struct btrfs_block_group *cache, *ret = NULL;
2092e405ad8SJosef Bacik 	struct rb_node *n;
2102e405ad8SJosef Bacik 	u64 end, start;
2112e405ad8SJosef Bacik 
21216b0c258SFilipe Manana 	read_lock(&info->block_group_cache_lock);
21308dddb29SFilipe Manana 	n = info->block_group_cache_tree.rb_root.rb_node;
2142e405ad8SJosef Bacik 
2152e405ad8SJosef Bacik 	while (n) {
21632da5386SDavid Sterba 		cache = rb_entry(n, struct btrfs_block_group, cache_node);
217b3470b5dSDavid Sterba 		end = cache->start + cache->length - 1;
218b3470b5dSDavid Sterba 		start = cache->start;
2192e405ad8SJosef Bacik 
2202e405ad8SJosef Bacik 		if (bytenr < start) {
221b3470b5dSDavid Sterba 			if (!contains && (!ret || start < ret->start))
2222e405ad8SJosef Bacik 				ret = cache;
2232e405ad8SJosef Bacik 			n = n->rb_left;
2242e405ad8SJosef Bacik 		} else if (bytenr > start) {
2252e405ad8SJosef Bacik 			if (contains && bytenr <= end) {
2262e405ad8SJosef Bacik 				ret = cache;
2272e405ad8SJosef Bacik 				break;
2282e405ad8SJosef Bacik 			}
2292e405ad8SJosef Bacik 			n = n->rb_right;
2302e405ad8SJosef Bacik 		} else {
2312e405ad8SJosef Bacik 			ret = cache;
2322e405ad8SJosef Bacik 			break;
2332e405ad8SJosef Bacik 		}
2342e405ad8SJosef Bacik 	}
23508dddb29SFilipe Manana 	if (ret)
2362e405ad8SJosef Bacik 		btrfs_get_block_group(ret);
23716b0c258SFilipe Manana 	read_unlock(&info->block_group_cache_lock);
2382e405ad8SJosef Bacik 
2392e405ad8SJosef Bacik 	return ret;
2402e405ad8SJosef Bacik }
2412e405ad8SJosef Bacik 
2422e405ad8SJosef Bacik /*
2432e405ad8SJosef Bacik  * Return the block group that starts at or after bytenr
2442e405ad8SJosef Bacik  */
24532da5386SDavid Sterba struct btrfs_block_group *btrfs_lookup_first_block_group(
2462e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr)
2472e405ad8SJosef Bacik {
2482e405ad8SJosef Bacik 	return block_group_cache_tree_search(info, bytenr, 0);
2492e405ad8SJosef Bacik }
2502e405ad8SJosef Bacik 
2512e405ad8SJosef Bacik /*
2522e405ad8SJosef Bacik  * Return the block group that contains the given bytenr
2532e405ad8SJosef Bacik  */
25432da5386SDavid Sterba struct btrfs_block_group *btrfs_lookup_block_group(
2552e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr)
2562e405ad8SJosef Bacik {
2572e405ad8SJosef Bacik 	return block_group_cache_tree_search(info, bytenr, 1);
2582e405ad8SJosef Bacik }
2592e405ad8SJosef Bacik 
26032da5386SDavid Sterba struct btrfs_block_group *btrfs_next_block_group(
26132da5386SDavid Sterba 		struct btrfs_block_group *cache)
2622e405ad8SJosef Bacik {
2632e405ad8SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
2642e405ad8SJosef Bacik 	struct rb_node *node;
2652e405ad8SJosef Bacik 
26616b0c258SFilipe Manana 	read_lock(&fs_info->block_group_cache_lock);
2672e405ad8SJosef Bacik 
2682e405ad8SJosef Bacik 	/* If our block group was removed, we need a full search. */
2692e405ad8SJosef Bacik 	if (RB_EMPTY_NODE(&cache->cache_node)) {
270b3470b5dSDavid Sterba 		const u64 next_bytenr = cache->start + cache->length;
2712e405ad8SJosef Bacik 
27216b0c258SFilipe Manana 		read_unlock(&fs_info->block_group_cache_lock);
2732e405ad8SJosef Bacik 		btrfs_put_block_group(cache);
2748b01f931SFilipe Manana 		return btrfs_lookup_first_block_group(fs_info, next_bytenr);
2752e405ad8SJosef Bacik 	}
2762e405ad8SJosef Bacik 	node = rb_next(&cache->cache_node);
2772e405ad8SJosef Bacik 	btrfs_put_block_group(cache);
2782e405ad8SJosef Bacik 	if (node) {
27932da5386SDavid Sterba 		cache = rb_entry(node, struct btrfs_block_group, cache_node);
2802e405ad8SJosef Bacik 		btrfs_get_block_group(cache);
2812e405ad8SJosef Bacik 	} else
2822e405ad8SJosef Bacik 		cache = NULL;
28316b0c258SFilipe Manana 	read_unlock(&fs_info->block_group_cache_lock);
2842e405ad8SJosef Bacik 	return cache;
2852e405ad8SJosef Bacik }
2863eeb3226SJosef Bacik 
287*2306e83eSFilipe Manana /**
288*2306e83eSFilipe Manana  * Check if we can do a NOCOW write for a given extent.
289*2306e83eSFilipe Manana  *
290*2306e83eSFilipe Manana  * @fs_info:       The filesystem information object.
291*2306e83eSFilipe Manana  * @bytenr:        Logical start address of the extent.
292*2306e83eSFilipe Manana  *
293*2306e83eSFilipe Manana  * Check if we can do a NOCOW write for the given extent, and increments the
294*2306e83eSFilipe Manana  * number of NOCOW writers in the block group that contains the extent, as long
295*2306e83eSFilipe Manana  * as the block group exists and it's currently not in read-only mode.
296*2306e83eSFilipe Manana  *
297*2306e83eSFilipe Manana  * Returns: A non-NULL block group pointer if we can do a NOCOW write, the caller
298*2306e83eSFilipe Manana  *          is responsible for calling btrfs_dec_nocow_writers() later.
299*2306e83eSFilipe Manana  *
300*2306e83eSFilipe Manana  *          Or NULL if we can not do a NOCOW write
301*2306e83eSFilipe Manana  */
302*2306e83eSFilipe Manana struct btrfs_block_group *btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info,
303*2306e83eSFilipe Manana 						  u64 bytenr)
3043eeb3226SJosef Bacik {
30532da5386SDavid Sterba 	struct btrfs_block_group *bg;
306*2306e83eSFilipe Manana 	bool can_nocow = true;
3073eeb3226SJosef Bacik 
3083eeb3226SJosef Bacik 	bg = btrfs_lookup_block_group(fs_info, bytenr);
3093eeb3226SJosef Bacik 	if (!bg)
310*2306e83eSFilipe Manana 		return NULL;
3113eeb3226SJosef Bacik 
3123eeb3226SJosef Bacik 	spin_lock(&bg->lock);
3133eeb3226SJosef Bacik 	if (bg->ro)
314*2306e83eSFilipe Manana 		can_nocow = false;
3153eeb3226SJosef Bacik 	else
3163eeb3226SJosef Bacik 		atomic_inc(&bg->nocow_writers);
3173eeb3226SJosef Bacik 	spin_unlock(&bg->lock);
3183eeb3226SJosef Bacik 
319*2306e83eSFilipe Manana 	if (!can_nocow) {
3203eeb3226SJosef Bacik 		btrfs_put_block_group(bg);
321*2306e83eSFilipe Manana 		return NULL;
3223eeb3226SJosef Bacik 	}
3233eeb3226SJosef Bacik 
324*2306e83eSFilipe Manana 	/* No put on block group, done by btrfs_dec_nocow_writers(). */
325*2306e83eSFilipe Manana 	return bg;
326*2306e83eSFilipe Manana }
3273eeb3226SJosef Bacik 
328*2306e83eSFilipe Manana /**
329*2306e83eSFilipe Manana  * Decrement the number of NOCOW writers in a block group.
330*2306e83eSFilipe Manana  *
331*2306e83eSFilipe Manana  * @bg:       The block group.
332*2306e83eSFilipe Manana  *
333*2306e83eSFilipe Manana  * This is meant to be called after a previous call to btrfs_inc_nocow_writers(),
334*2306e83eSFilipe Manana  * and on the block group returned by that call. Typically this is called after
335*2306e83eSFilipe Manana  * creating an ordered extent for a NOCOW write, to prevent races with scrub and
336*2306e83eSFilipe Manana  * relocation.
337*2306e83eSFilipe Manana  *
338*2306e83eSFilipe Manana  * After this call, the caller should not use the block group anymore. It it wants
339*2306e83eSFilipe Manana  * to use it, then it should get a reference on it before calling this function.
340*2306e83eSFilipe Manana  */
341*2306e83eSFilipe Manana void btrfs_dec_nocow_writers(struct btrfs_block_group *bg)
342*2306e83eSFilipe Manana {
3433eeb3226SJosef Bacik 	if (atomic_dec_and_test(&bg->nocow_writers))
3443eeb3226SJosef Bacik 		wake_up_var(&bg->nocow_writers);
345*2306e83eSFilipe Manana 
346*2306e83eSFilipe Manana 	/* For the lookup done by a previous call to btrfs_inc_nocow_writers(). */
3473eeb3226SJosef Bacik 	btrfs_put_block_group(bg);
3483eeb3226SJosef Bacik }
3493eeb3226SJosef Bacik 
35032da5386SDavid Sterba void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
3513eeb3226SJosef Bacik {
3523eeb3226SJosef Bacik 	wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
3533eeb3226SJosef Bacik }
3543eeb3226SJosef Bacik 
3553eeb3226SJosef Bacik void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
3563eeb3226SJosef Bacik 					const u64 start)
3573eeb3226SJosef Bacik {
35832da5386SDavid Sterba 	struct btrfs_block_group *bg;
3593eeb3226SJosef Bacik 
3603eeb3226SJosef Bacik 	bg = btrfs_lookup_block_group(fs_info, start);
3613eeb3226SJosef Bacik 	ASSERT(bg);
3623eeb3226SJosef Bacik 	if (atomic_dec_and_test(&bg->reservations))
3633eeb3226SJosef Bacik 		wake_up_var(&bg->reservations);
3643eeb3226SJosef Bacik 	btrfs_put_block_group(bg);
3653eeb3226SJosef Bacik }
3663eeb3226SJosef Bacik 
36732da5386SDavid Sterba void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
3683eeb3226SJosef Bacik {
3693eeb3226SJosef Bacik 	struct btrfs_space_info *space_info = bg->space_info;
3703eeb3226SJosef Bacik 
3713eeb3226SJosef Bacik 	ASSERT(bg->ro);
3723eeb3226SJosef Bacik 
3733eeb3226SJosef Bacik 	if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
3743eeb3226SJosef Bacik 		return;
3753eeb3226SJosef Bacik 
3763eeb3226SJosef Bacik 	/*
3773eeb3226SJosef Bacik 	 * Our block group is read only but before we set it to read only,
3783eeb3226SJosef Bacik 	 * some task might have had allocated an extent from it already, but it
3793eeb3226SJosef Bacik 	 * has not yet created a respective ordered extent (and added it to a
3803eeb3226SJosef Bacik 	 * root's list of ordered extents).
3813eeb3226SJosef Bacik 	 * Therefore wait for any task currently allocating extents, since the
3823eeb3226SJosef Bacik 	 * block group's reservations counter is incremented while a read lock
3833eeb3226SJosef Bacik 	 * on the groups' semaphore is held and decremented after releasing
3843eeb3226SJosef Bacik 	 * the read access on that semaphore and creating the ordered extent.
3853eeb3226SJosef Bacik 	 */
3863eeb3226SJosef Bacik 	down_write(&space_info->groups_sem);
3873eeb3226SJosef Bacik 	up_write(&space_info->groups_sem);
3883eeb3226SJosef Bacik 
3893eeb3226SJosef Bacik 	wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
3903eeb3226SJosef Bacik }
3919f21246dSJosef Bacik 
3929f21246dSJosef Bacik struct btrfs_caching_control *btrfs_get_caching_control(
39332da5386SDavid Sterba 		struct btrfs_block_group *cache)
3949f21246dSJosef Bacik {
3959f21246dSJosef Bacik 	struct btrfs_caching_control *ctl;
3969f21246dSJosef Bacik 
3979f21246dSJosef Bacik 	spin_lock(&cache->lock);
3989f21246dSJosef Bacik 	if (!cache->caching_ctl) {
3999f21246dSJosef Bacik 		spin_unlock(&cache->lock);
4009f21246dSJosef Bacik 		return NULL;
4019f21246dSJosef Bacik 	}
4029f21246dSJosef Bacik 
4039f21246dSJosef Bacik 	ctl = cache->caching_ctl;
4049f21246dSJosef Bacik 	refcount_inc(&ctl->count);
4059f21246dSJosef Bacik 	spin_unlock(&cache->lock);
4069f21246dSJosef Bacik 	return ctl;
4079f21246dSJosef Bacik }
4089f21246dSJosef Bacik 
4099f21246dSJosef Bacik void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
4109f21246dSJosef Bacik {
4119f21246dSJosef Bacik 	if (refcount_dec_and_test(&ctl->count))
4129f21246dSJosef Bacik 		kfree(ctl);
4139f21246dSJosef Bacik }
4149f21246dSJosef Bacik 
4159f21246dSJosef Bacik /*
4169f21246dSJosef Bacik  * When we wait for progress in the block group caching, its because our
4179f21246dSJosef Bacik  * allocation attempt failed at least once.  So, we must sleep and let some
4189f21246dSJosef Bacik  * progress happen before we try again.
4199f21246dSJosef Bacik  *
4209f21246dSJosef Bacik  * This function will sleep at least once waiting for new free space to show
4219f21246dSJosef Bacik  * up, and then it will check the block group free space numbers for our min
4229f21246dSJosef Bacik  * num_bytes.  Another option is to have it go ahead and look in the rbtree for
4239f21246dSJosef Bacik  * a free extent of a given size, but this is a good start.
4249f21246dSJosef Bacik  *
4259f21246dSJosef Bacik  * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
4269f21246dSJosef Bacik  * any of the information in this block group.
4279f21246dSJosef Bacik  */
42832da5386SDavid Sterba void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
4299f21246dSJosef Bacik 					   u64 num_bytes)
4309f21246dSJosef Bacik {
4319f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
4329f21246dSJosef Bacik 
4339f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4349f21246dSJosef Bacik 	if (!caching_ctl)
4359f21246dSJosef Bacik 		return;
4369f21246dSJosef Bacik 
43732da5386SDavid Sterba 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
4389f21246dSJosef Bacik 		   (cache->free_space_ctl->free_space >= num_bytes));
4399f21246dSJosef Bacik 
4409f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4419f21246dSJosef Bacik }
4429f21246dSJosef Bacik 
44332da5386SDavid Sterba int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
4449f21246dSJosef Bacik {
4459f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
4469f21246dSJosef Bacik 	int ret = 0;
4479f21246dSJosef Bacik 
4489f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4499f21246dSJosef Bacik 	if (!caching_ctl)
4509f21246dSJosef Bacik 		return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
4519f21246dSJosef Bacik 
45232da5386SDavid Sterba 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
4539f21246dSJosef Bacik 	if (cache->cached == BTRFS_CACHE_ERROR)
4549f21246dSJosef Bacik 		ret = -EIO;
4559f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4569f21246dSJosef Bacik 	return ret;
4579f21246dSJosef Bacik }
4589f21246dSJosef Bacik 
459e747853cSJosef Bacik static bool space_cache_v1_done(struct btrfs_block_group *cache)
460e747853cSJosef Bacik {
461e747853cSJosef Bacik 	bool ret;
462e747853cSJosef Bacik 
463e747853cSJosef Bacik 	spin_lock(&cache->lock);
464e747853cSJosef Bacik 	ret = cache->cached != BTRFS_CACHE_FAST;
465e747853cSJosef Bacik 	spin_unlock(&cache->lock);
466e747853cSJosef Bacik 
467e747853cSJosef Bacik 	return ret;
468e747853cSJosef Bacik }
469e747853cSJosef Bacik 
470e747853cSJosef Bacik void btrfs_wait_space_cache_v1_finished(struct btrfs_block_group *cache,
471e747853cSJosef Bacik 				struct btrfs_caching_control *caching_ctl)
472e747853cSJosef Bacik {
473e747853cSJosef Bacik 	wait_event(caching_ctl->wait, space_cache_v1_done(cache));
474e747853cSJosef Bacik }
475e747853cSJosef Bacik 
4769f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
47732da5386SDavid Sterba static void fragment_free_space(struct btrfs_block_group *block_group)
4789f21246dSJosef Bacik {
4799f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
480b3470b5dSDavid Sterba 	u64 start = block_group->start;
481b3470b5dSDavid Sterba 	u64 len = block_group->length;
4829f21246dSJosef Bacik 	u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
4839f21246dSJosef Bacik 		fs_info->nodesize : fs_info->sectorsize;
4849f21246dSJosef Bacik 	u64 step = chunk << 1;
4859f21246dSJosef Bacik 
4869f21246dSJosef Bacik 	while (len > chunk) {
4879f21246dSJosef Bacik 		btrfs_remove_free_space(block_group, start, chunk);
4889f21246dSJosef Bacik 		start += step;
4899f21246dSJosef Bacik 		if (len < step)
4909f21246dSJosef Bacik 			len = 0;
4919f21246dSJosef Bacik 		else
4929f21246dSJosef Bacik 			len -= step;
4939f21246dSJosef Bacik 	}
4949f21246dSJosef Bacik }
4959f21246dSJosef Bacik #endif
4969f21246dSJosef Bacik 
4979f21246dSJosef Bacik /*
4989f21246dSJosef Bacik  * This is only called by btrfs_cache_block_group, since we could have freed
4999f21246dSJosef Bacik  * extents we need to check the pinned_extents for any extents that can't be
5009f21246dSJosef Bacik  * used yet since their free space will be released as soon as the transaction
5019f21246dSJosef Bacik  * commits.
5029f21246dSJosef Bacik  */
50332da5386SDavid Sterba u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
5049f21246dSJosef Bacik {
5059f21246dSJosef Bacik 	struct btrfs_fs_info *info = block_group->fs_info;
5069f21246dSJosef Bacik 	u64 extent_start, extent_end, size, total_added = 0;
5079f21246dSJosef Bacik 	int ret;
5089f21246dSJosef Bacik 
5099f21246dSJosef Bacik 	while (start < end) {
510fe119a6eSNikolay Borisov 		ret = find_first_extent_bit(&info->excluded_extents, start,
5119f21246dSJosef Bacik 					    &extent_start, &extent_end,
5129f21246dSJosef Bacik 					    EXTENT_DIRTY | EXTENT_UPTODATE,
5139f21246dSJosef Bacik 					    NULL);
5149f21246dSJosef Bacik 		if (ret)
5159f21246dSJosef Bacik 			break;
5169f21246dSJosef Bacik 
5179f21246dSJosef Bacik 		if (extent_start <= start) {
5189f21246dSJosef Bacik 			start = extent_end + 1;
5199f21246dSJosef Bacik 		} else if (extent_start > start && extent_start < end) {
5209f21246dSJosef Bacik 			size = extent_start - start;
5219f21246dSJosef Bacik 			total_added += size;
522b0643e59SDennis Zhou 			ret = btrfs_add_free_space_async_trimmed(block_group,
523b0643e59SDennis Zhou 								 start, size);
5249f21246dSJosef Bacik 			BUG_ON(ret); /* -ENOMEM or logic error */
5259f21246dSJosef Bacik 			start = extent_end + 1;
5269f21246dSJosef Bacik 		} else {
5279f21246dSJosef Bacik 			break;
5289f21246dSJosef Bacik 		}
5299f21246dSJosef Bacik 	}
5309f21246dSJosef Bacik 
5319f21246dSJosef Bacik 	if (start < end) {
5329f21246dSJosef Bacik 		size = end - start;
5339f21246dSJosef Bacik 		total_added += size;
534b0643e59SDennis Zhou 		ret = btrfs_add_free_space_async_trimmed(block_group, start,
535b0643e59SDennis Zhou 							 size);
5369f21246dSJosef Bacik 		BUG_ON(ret); /* -ENOMEM or logic error */
5379f21246dSJosef Bacik 	}
5389f21246dSJosef Bacik 
5399f21246dSJosef Bacik 	return total_added;
5409f21246dSJosef Bacik }
5419f21246dSJosef Bacik 
5429f21246dSJosef Bacik static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
5439f21246dSJosef Bacik {
54432da5386SDavid Sterba 	struct btrfs_block_group *block_group = caching_ctl->block_group;
5459f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
54629cbcf40SJosef Bacik 	struct btrfs_root *extent_root;
5479f21246dSJosef Bacik 	struct btrfs_path *path;
5489f21246dSJosef Bacik 	struct extent_buffer *leaf;
5499f21246dSJosef Bacik 	struct btrfs_key key;
5509f21246dSJosef Bacik 	u64 total_found = 0;
5519f21246dSJosef Bacik 	u64 last = 0;
5529f21246dSJosef Bacik 	u32 nritems;
5539f21246dSJosef Bacik 	int ret;
5549f21246dSJosef Bacik 	bool wakeup = true;
5559f21246dSJosef Bacik 
5569f21246dSJosef Bacik 	path = btrfs_alloc_path();
5579f21246dSJosef Bacik 	if (!path)
5589f21246dSJosef Bacik 		return -ENOMEM;
5599f21246dSJosef Bacik 
560b3470b5dSDavid Sterba 	last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
56129cbcf40SJosef Bacik 	extent_root = btrfs_extent_root(fs_info, last);
5629f21246dSJosef Bacik 
5639f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
5649f21246dSJosef Bacik 	/*
5659f21246dSJosef Bacik 	 * If we're fragmenting we don't want to make anybody think we can
5669f21246dSJosef Bacik 	 * allocate from this block group until we've had a chance to fragment
5679f21246dSJosef Bacik 	 * the free space.
5689f21246dSJosef Bacik 	 */
5699f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group))
5709f21246dSJosef Bacik 		wakeup = false;
5719f21246dSJosef Bacik #endif
5729f21246dSJosef Bacik 	/*
5739f21246dSJosef Bacik 	 * We don't want to deadlock with somebody trying to allocate a new
5749f21246dSJosef Bacik 	 * extent for the extent root while also trying to search the extent
5759f21246dSJosef Bacik 	 * root to add free space.  So we skip locking and search the commit
5769f21246dSJosef Bacik 	 * root, since its read-only
5779f21246dSJosef Bacik 	 */
5789f21246dSJosef Bacik 	path->skip_locking = 1;
5799f21246dSJosef Bacik 	path->search_commit_root = 1;
5809f21246dSJosef Bacik 	path->reada = READA_FORWARD;
5819f21246dSJosef Bacik 
5829f21246dSJosef Bacik 	key.objectid = last;
5839f21246dSJosef Bacik 	key.offset = 0;
5849f21246dSJosef Bacik 	key.type = BTRFS_EXTENT_ITEM_KEY;
5859f21246dSJosef Bacik 
5869f21246dSJosef Bacik next:
5879f21246dSJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
5889f21246dSJosef Bacik 	if (ret < 0)
5899f21246dSJosef Bacik 		goto out;
5909f21246dSJosef Bacik 
5919f21246dSJosef Bacik 	leaf = path->nodes[0];
5929f21246dSJosef Bacik 	nritems = btrfs_header_nritems(leaf);
5939f21246dSJosef Bacik 
5949f21246dSJosef Bacik 	while (1) {
5959f21246dSJosef Bacik 		if (btrfs_fs_closing(fs_info) > 1) {
5969f21246dSJosef Bacik 			last = (u64)-1;
5979f21246dSJosef Bacik 			break;
5989f21246dSJosef Bacik 		}
5999f21246dSJosef Bacik 
6009f21246dSJosef Bacik 		if (path->slots[0] < nritems) {
6019f21246dSJosef Bacik 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6029f21246dSJosef Bacik 		} else {
6039f21246dSJosef Bacik 			ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
6049f21246dSJosef Bacik 			if (ret)
6059f21246dSJosef Bacik 				break;
6069f21246dSJosef Bacik 
6079f21246dSJosef Bacik 			if (need_resched() ||
6089f21246dSJosef Bacik 			    rwsem_is_contended(&fs_info->commit_root_sem)) {
6099f21246dSJosef Bacik 				if (wakeup)
6109f21246dSJosef Bacik 					caching_ctl->progress = last;
6119f21246dSJosef Bacik 				btrfs_release_path(path);
6129f21246dSJosef Bacik 				up_read(&fs_info->commit_root_sem);
6139f21246dSJosef Bacik 				mutex_unlock(&caching_ctl->mutex);
6149f21246dSJosef Bacik 				cond_resched();
6159f21246dSJosef Bacik 				mutex_lock(&caching_ctl->mutex);
6169f21246dSJosef Bacik 				down_read(&fs_info->commit_root_sem);
6179f21246dSJosef Bacik 				goto next;
6189f21246dSJosef Bacik 			}
6199f21246dSJosef Bacik 
6209f21246dSJosef Bacik 			ret = btrfs_next_leaf(extent_root, path);
6219f21246dSJosef Bacik 			if (ret < 0)
6229f21246dSJosef Bacik 				goto out;
6239f21246dSJosef Bacik 			if (ret)
6249f21246dSJosef Bacik 				break;
6259f21246dSJosef Bacik 			leaf = path->nodes[0];
6269f21246dSJosef Bacik 			nritems = btrfs_header_nritems(leaf);
6279f21246dSJosef Bacik 			continue;
6289f21246dSJosef Bacik 		}
6299f21246dSJosef Bacik 
6309f21246dSJosef Bacik 		if (key.objectid < last) {
6319f21246dSJosef Bacik 			key.objectid = last;
6329f21246dSJosef Bacik 			key.offset = 0;
6339f21246dSJosef Bacik 			key.type = BTRFS_EXTENT_ITEM_KEY;
6349f21246dSJosef Bacik 
6359f21246dSJosef Bacik 			if (wakeup)
6369f21246dSJosef Bacik 				caching_ctl->progress = last;
6379f21246dSJosef Bacik 			btrfs_release_path(path);
6389f21246dSJosef Bacik 			goto next;
6399f21246dSJosef Bacik 		}
6409f21246dSJosef Bacik 
641b3470b5dSDavid Sterba 		if (key.objectid < block_group->start) {
6429f21246dSJosef Bacik 			path->slots[0]++;
6439f21246dSJosef Bacik 			continue;
6449f21246dSJosef Bacik 		}
6459f21246dSJosef Bacik 
646b3470b5dSDavid Sterba 		if (key.objectid >= block_group->start + block_group->length)
6479f21246dSJosef Bacik 			break;
6489f21246dSJosef Bacik 
6499f21246dSJosef Bacik 		if (key.type == BTRFS_EXTENT_ITEM_KEY ||
6509f21246dSJosef Bacik 		    key.type == BTRFS_METADATA_ITEM_KEY) {
6519f21246dSJosef Bacik 			total_found += add_new_free_space(block_group, last,
6529f21246dSJosef Bacik 							  key.objectid);
6539f21246dSJosef Bacik 			if (key.type == BTRFS_METADATA_ITEM_KEY)
6549f21246dSJosef Bacik 				last = key.objectid +
6559f21246dSJosef Bacik 					fs_info->nodesize;
6569f21246dSJosef Bacik 			else
6579f21246dSJosef Bacik 				last = key.objectid + key.offset;
6589f21246dSJosef Bacik 
6599f21246dSJosef Bacik 			if (total_found > CACHING_CTL_WAKE_UP) {
6609f21246dSJosef Bacik 				total_found = 0;
6619f21246dSJosef Bacik 				if (wakeup)
6629f21246dSJosef Bacik 					wake_up(&caching_ctl->wait);
6639f21246dSJosef Bacik 			}
6649f21246dSJosef Bacik 		}
6659f21246dSJosef Bacik 		path->slots[0]++;
6669f21246dSJosef Bacik 	}
6679f21246dSJosef Bacik 	ret = 0;
6689f21246dSJosef Bacik 
6699f21246dSJosef Bacik 	total_found += add_new_free_space(block_group, last,
670b3470b5dSDavid Sterba 				block_group->start + block_group->length);
6719f21246dSJosef Bacik 	caching_ctl->progress = (u64)-1;
6729f21246dSJosef Bacik 
6739f21246dSJosef Bacik out:
6749f21246dSJosef Bacik 	btrfs_free_path(path);
6759f21246dSJosef Bacik 	return ret;
6769f21246dSJosef Bacik }
6779f21246dSJosef Bacik 
6789f21246dSJosef Bacik static noinline void caching_thread(struct btrfs_work *work)
6799f21246dSJosef Bacik {
68032da5386SDavid Sterba 	struct btrfs_block_group *block_group;
6819f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info;
6829f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
6839f21246dSJosef Bacik 	int ret;
6849f21246dSJosef Bacik 
6859f21246dSJosef Bacik 	caching_ctl = container_of(work, struct btrfs_caching_control, work);
6869f21246dSJosef Bacik 	block_group = caching_ctl->block_group;
6879f21246dSJosef Bacik 	fs_info = block_group->fs_info;
6889f21246dSJosef Bacik 
6899f21246dSJosef Bacik 	mutex_lock(&caching_ctl->mutex);
6909f21246dSJosef Bacik 	down_read(&fs_info->commit_root_sem);
6919f21246dSJosef Bacik 
692e747853cSJosef Bacik 	if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
693e747853cSJosef Bacik 		ret = load_free_space_cache(block_group);
694e747853cSJosef Bacik 		if (ret == 1) {
695e747853cSJosef Bacik 			ret = 0;
696e747853cSJosef Bacik 			goto done;
697e747853cSJosef Bacik 		}
698e747853cSJosef Bacik 
699e747853cSJosef Bacik 		/*
700e747853cSJosef Bacik 		 * We failed to load the space cache, set ourselves to
701e747853cSJosef Bacik 		 * CACHE_STARTED and carry on.
702e747853cSJosef Bacik 		 */
703e747853cSJosef Bacik 		spin_lock(&block_group->lock);
704e747853cSJosef Bacik 		block_group->cached = BTRFS_CACHE_STARTED;
705e747853cSJosef Bacik 		spin_unlock(&block_group->lock);
706e747853cSJosef Bacik 		wake_up(&caching_ctl->wait);
707e747853cSJosef Bacik 	}
708e747853cSJosef Bacik 
7092f96e402SJosef Bacik 	/*
7102f96e402SJosef Bacik 	 * If we are in the transaction that populated the free space tree we
7112f96e402SJosef Bacik 	 * can't actually cache from the free space tree as our commit root and
7122f96e402SJosef Bacik 	 * real root are the same, so we could change the contents of the blocks
7132f96e402SJosef Bacik 	 * while caching.  Instead do the slow caching in this case, and after
7142f96e402SJosef Bacik 	 * the transaction has committed we will be safe.
7152f96e402SJosef Bacik 	 */
7162f96e402SJosef Bacik 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
7172f96e402SJosef Bacik 	    !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
7189f21246dSJosef Bacik 		ret = load_free_space_tree(caching_ctl);
7199f21246dSJosef Bacik 	else
7209f21246dSJosef Bacik 		ret = load_extent_tree_free(caching_ctl);
721e747853cSJosef Bacik done:
7229f21246dSJosef Bacik 	spin_lock(&block_group->lock);
7239f21246dSJosef Bacik 	block_group->caching_ctl = NULL;
7249f21246dSJosef Bacik 	block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
7259f21246dSJosef Bacik 	spin_unlock(&block_group->lock);
7269f21246dSJosef Bacik 
7279f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
7289f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group)) {
7299f21246dSJosef Bacik 		u64 bytes_used;
7309f21246dSJosef Bacik 
7319f21246dSJosef Bacik 		spin_lock(&block_group->space_info->lock);
7329f21246dSJosef Bacik 		spin_lock(&block_group->lock);
733b3470b5dSDavid Sterba 		bytes_used = block_group->length - block_group->used;
7349f21246dSJosef Bacik 		block_group->space_info->bytes_used += bytes_used >> 1;
7359f21246dSJosef Bacik 		spin_unlock(&block_group->lock);
7369f21246dSJosef Bacik 		spin_unlock(&block_group->space_info->lock);
737e11c0406SJosef Bacik 		fragment_free_space(block_group);
7389f21246dSJosef Bacik 	}
7399f21246dSJosef Bacik #endif
7409f21246dSJosef Bacik 
7419f21246dSJosef Bacik 	caching_ctl->progress = (u64)-1;
7429f21246dSJosef Bacik 
7439f21246dSJosef Bacik 	up_read(&fs_info->commit_root_sem);
7449f21246dSJosef Bacik 	btrfs_free_excluded_extents(block_group);
7459f21246dSJosef Bacik 	mutex_unlock(&caching_ctl->mutex);
7469f21246dSJosef Bacik 
7479f21246dSJosef Bacik 	wake_up(&caching_ctl->wait);
7489f21246dSJosef Bacik 
7499f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
7509f21246dSJosef Bacik 	btrfs_put_block_group(block_group);
7519f21246dSJosef Bacik }
7529f21246dSJosef Bacik 
75332da5386SDavid Sterba int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
7549f21246dSJosef Bacik {
7559f21246dSJosef Bacik 	DEFINE_WAIT(wait);
7569f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
757e747853cSJosef Bacik 	struct btrfs_caching_control *caching_ctl = NULL;
7589f21246dSJosef Bacik 	int ret = 0;
7599f21246dSJosef Bacik 
7602eda5708SNaohiro Aota 	/* Allocator for zoned filesystems does not use the cache at all */
7612eda5708SNaohiro Aota 	if (btrfs_is_zoned(fs_info))
7622eda5708SNaohiro Aota 		return 0;
7632eda5708SNaohiro Aota 
7649f21246dSJosef Bacik 	caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
7659f21246dSJosef Bacik 	if (!caching_ctl)
7669f21246dSJosef Bacik 		return -ENOMEM;
7679f21246dSJosef Bacik 
7689f21246dSJosef Bacik 	INIT_LIST_HEAD(&caching_ctl->list);
7699f21246dSJosef Bacik 	mutex_init(&caching_ctl->mutex);
7709f21246dSJosef Bacik 	init_waitqueue_head(&caching_ctl->wait);
7719f21246dSJosef Bacik 	caching_ctl->block_group = cache;
772b3470b5dSDavid Sterba 	caching_ctl->progress = cache->start;
773e747853cSJosef Bacik 	refcount_set(&caching_ctl->count, 2);
774a0cac0ecSOmar Sandoval 	btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
7759f21246dSJosef Bacik 
7769f21246dSJosef Bacik 	spin_lock(&cache->lock);
7779f21246dSJosef Bacik 	if (cache->cached != BTRFS_CACHE_NO) {
7789f21246dSJosef Bacik 		kfree(caching_ctl);
779e747853cSJosef Bacik 
780e747853cSJosef Bacik 		caching_ctl = cache->caching_ctl;
781e747853cSJosef Bacik 		if (caching_ctl)
782e747853cSJosef Bacik 			refcount_inc(&caching_ctl->count);
783e747853cSJosef Bacik 		spin_unlock(&cache->lock);
784e747853cSJosef Bacik 		goto out;
7859f21246dSJosef Bacik 	}
7869f21246dSJosef Bacik 	WARN_ON(cache->caching_ctl);
7879f21246dSJosef Bacik 	cache->caching_ctl = caching_ctl;
788e747853cSJosef Bacik 	if (btrfs_test_opt(fs_info, SPACE_CACHE))
7899f21246dSJosef Bacik 		cache->cached = BTRFS_CACHE_FAST;
790e747853cSJosef Bacik 	else
7919f21246dSJosef Bacik 		cache->cached = BTRFS_CACHE_STARTED;
7929f21246dSJosef Bacik 	cache->has_caching_ctl = 1;
7939f21246dSJosef Bacik 	spin_unlock(&cache->lock);
7949f21246dSJosef Bacik 
79516b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
7969f21246dSJosef Bacik 	refcount_inc(&caching_ctl->count);
7979f21246dSJosef Bacik 	list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
79816b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
7999f21246dSJosef Bacik 
8009f21246dSJosef Bacik 	btrfs_get_block_group(cache);
8019f21246dSJosef Bacik 
8029f21246dSJosef Bacik 	btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
803e747853cSJosef Bacik out:
804e747853cSJosef Bacik 	if (load_cache_only && caching_ctl)
805e747853cSJosef Bacik 		btrfs_wait_space_cache_v1_finished(cache, caching_ctl);
806e747853cSJosef Bacik 	if (caching_ctl)
807e747853cSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
8089f21246dSJosef Bacik 
8099f21246dSJosef Bacik 	return ret;
8109f21246dSJosef Bacik }
811e3e0520bSJosef Bacik 
812e3e0520bSJosef Bacik static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
813e3e0520bSJosef Bacik {
814e3e0520bSJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
815e3e0520bSJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
816e3e0520bSJosef Bacik 
817e3e0520bSJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
818e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
819e3e0520bSJosef Bacik 		fs_info->avail_data_alloc_bits &= ~extra_flags;
820e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
821e3e0520bSJosef Bacik 		fs_info->avail_metadata_alloc_bits &= ~extra_flags;
822e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
823e3e0520bSJosef Bacik 		fs_info->avail_system_alloc_bits &= ~extra_flags;
824e3e0520bSJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
825e3e0520bSJosef Bacik }
826e3e0520bSJosef Bacik 
827e3e0520bSJosef Bacik /*
828e3e0520bSJosef Bacik  * Clear incompat bits for the following feature(s):
829e3e0520bSJosef Bacik  *
830e3e0520bSJosef Bacik  * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
831e3e0520bSJosef Bacik  *            in the whole filesystem
8329c907446SDavid Sterba  *
8339c907446SDavid Sterba  * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
834e3e0520bSJosef Bacik  */
835e3e0520bSJosef Bacik static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
836e3e0520bSJosef Bacik {
8379c907446SDavid Sterba 	bool found_raid56 = false;
8389c907446SDavid Sterba 	bool found_raid1c34 = false;
8399c907446SDavid Sterba 
8409c907446SDavid Sterba 	if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
8419c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
8429c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
843e3e0520bSJosef Bacik 		struct list_head *head = &fs_info->space_info;
844e3e0520bSJosef Bacik 		struct btrfs_space_info *sinfo;
845e3e0520bSJosef Bacik 
846e3e0520bSJosef Bacik 		list_for_each_entry_rcu(sinfo, head, list) {
847e3e0520bSJosef Bacik 			down_read(&sinfo->groups_sem);
848e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
8499c907446SDavid Sterba 				found_raid56 = true;
850e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
8519c907446SDavid Sterba 				found_raid56 = true;
8529c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
8539c907446SDavid Sterba 				found_raid1c34 = true;
8549c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
8559c907446SDavid Sterba 				found_raid1c34 = true;
856e3e0520bSJosef Bacik 			up_read(&sinfo->groups_sem);
857e3e0520bSJosef Bacik 		}
858d8e6fd5cSFilipe Manana 		if (!found_raid56)
859e3e0520bSJosef Bacik 			btrfs_clear_fs_incompat(fs_info, RAID56);
860d8e6fd5cSFilipe Manana 		if (!found_raid1c34)
8619c907446SDavid Sterba 			btrfs_clear_fs_incompat(fs_info, RAID1C34);
862e3e0520bSJosef Bacik 	}
863e3e0520bSJosef Bacik }
864e3e0520bSJosef Bacik 
8657357623aSQu Wenruo static int remove_block_group_item(struct btrfs_trans_handle *trans,
8667357623aSQu Wenruo 				   struct btrfs_path *path,
8677357623aSQu Wenruo 				   struct btrfs_block_group *block_group)
8687357623aSQu Wenruo {
8697357623aSQu Wenruo 	struct btrfs_fs_info *fs_info = trans->fs_info;
8707357623aSQu Wenruo 	struct btrfs_root *root;
8717357623aSQu Wenruo 	struct btrfs_key key;
8727357623aSQu Wenruo 	int ret;
8737357623aSQu Wenruo 
874dfe8aec4SJosef Bacik 	root = btrfs_block_group_root(fs_info);
8757357623aSQu Wenruo 	key.objectid = block_group->start;
8767357623aSQu Wenruo 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
8777357623aSQu Wenruo 	key.offset = block_group->length;
8787357623aSQu Wenruo 
8797357623aSQu Wenruo 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8807357623aSQu Wenruo 	if (ret > 0)
8817357623aSQu Wenruo 		ret = -ENOENT;
8827357623aSQu Wenruo 	if (ret < 0)
8837357623aSQu Wenruo 		return ret;
8847357623aSQu Wenruo 
8857357623aSQu Wenruo 	ret = btrfs_del_item(trans, root, path);
8867357623aSQu Wenruo 	return ret;
8877357623aSQu Wenruo }
8887357623aSQu Wenruo 
889e3e0520bSJosef Bacik int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
890e3e0520bSJosef Bacik 			     u64 group_start, struct extent_map *em)
891e3e0520bSJosef Bacik {
892e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
893e3e0520bSJosef Bacik 	struct btrfs_path *path;
89432da5386SDavid Sterba 	struct btrfs_block_group *block_group;
895e3e0520bSJosef Bacik 	struct btrfs_free_cluster *cluster;
896e3e0520bSJosef Bacik 	struct inode *inode;
897e3e0520bSJosef Bacik 	struct kobject *kobj = NULL;
898e3e0520bSJosef Bacik 	int ret;
899e3e0520bSJosef Bacik 	int index;
900e3e0520bSJosef Bacik 	int factor;
901e3e0520bSJosef Bacik 	struct btrfs_caching_control *caching_ctl = NULL;
902e3e0520bSJosef Bacik 	bool remove_em;
903e3e0520bSJosef Bacik 	bool remove_rsv = false;
904e3e0520bSJosef Bacik 
905e3e0520bSJosef Bacik 	block_group = btrfs_lookup_block_group(fs_info, group_start);
906e3e0520bSJosef Bacik 	BUG_ON(!block_group);
907e3e0520bSJosef Bacik 	BUG_ON(!block_group->ro);
908e3e0520bSJosef Bacik 
909e3e0520bSJosef Bacik 	trace_btrfs_remove_block_group(block_group);
910e3e0520bSJosef Bacik 	/*
911e3e0520bSJosef Bacik 	 * Free the reserved super bytes from this block group before
912e3e0520bSJosef Bacik 	 * remove it.
913e3e0520bSJosef Bacik 	 */
914e3e0520bSJosef Bacik 	btrfs_free_excluded_extents(block_group);
915b3470b5dSDavid Sterba 	btrfs_free_ref_tree_range(fs_info, block_group->start,
916b3470b5dSDavid Sterba 				  block_group->length);
917e3e0520bSJosef Bacik 
918e3e0520bSJosef Bacik 	index = btrfs_bg_flags_to_raid_index(block_group->flags);
919e3e0520bSJosef Bacik 	factor = btrfs_bg_type_to_factor(block_group->flags);
920e3e0520bSJosef Bacik 
921e3e0520bSJosef Bacik 	/* make sure this block group isn't part of an allocation cluster */
922e3e0520bSJosef Bacik 	cluster = &fs_info->data_alloc_cluster;
923e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
924e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
925e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
926e3e0520bSJosef Bacik 
927e3e0520bSJosef Bacik 	/*
928e3e0520bSJosef Bacik 	 * make sure this block group isn't part of a metadata
929e3e0520bSJosef Bacik 	 * allocation cluster
930e3e0520bSJosef Bacik 	 */
931e3e0520bSJosef Bacik 	cluster = &fs_info->meta_alloc_cluster;
932e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
933e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
934e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
935e3e0520bSJosef Bacik 
93640ab3be1SNaohiro Aota 	btrfs_clear_treelog_bg(block_group);
937c2707a25SJohannes Thumshirn 	btrfs_clear_data_reloc_bg(block_group);
93840ab3be1SNaohiro Aota 
939e3e0520bSJosef Bacik 	path = btrfs_alloc_path();
940e3e0520bSJosef Bacik 	if (!path) {
941e3e0520bSJosef Bacik 		ret = -ENOMEM;
9429fecd132SFilipe Manana 		goto out;
943e3e0520bSJosef Bacik 	}
944e3e0520bSJosef Bacik 
945e3e0520bSJosef Bacik 	/*
946e3e0520bSJosef Bacik 	 * get the inode first so any iput calls done for the io_list
947e3e0520bSJosef Bacik 	 * aren't the final iput (no unlinks allowed now)
948e3e0520bSJosef Bacik 	 */
949e3e0520bSJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
950e3e0520bSJosef Bacik 
951e3e0520bSJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
952e3e0520bSJosef Bacik 	/*
953e3e0520bSJosef Bacik 	 * Make sure our free space cache IO is done before removing the
954e3e0520bSJosef Bacik 	 * free space inode
955e3e0520bSJosef Bacik 	 */
956e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
957e3e0520bSJosef Bacik 	if (!list_empty(&block_group->io_list)) {
958e3e0520bSJosef Bacik 		list_del_init(&block_group->io_list);
959e3e0520bSJosef Bacik 
960e3e0520bSJosef Bacik 		WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
961e3e0520bSJosef Bacik 
962e3e0520bSJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
963e3e0520bSJosef Bacik 		btrfs_wait_cache_io(trans, block_group, path);
964e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
965e3e0520bSJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
966e3e0520bSJosef Bacik 	}
967e3e0520bSJosef Bacik 
968e3e0520bSJosef Bacik 	if (!list_empty(&block_group->dirty_list)) {
969e3e0520bSJosef Bacik 		list_del_init(&block_group->dirty_list);
970e3e0520bSJosef Bacik 		remove_rsv = true;
971e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
972e3e0520bSJosef Bacik 	}
973e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
974e3e0520bSJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
975e3e0520bSJosef Bacik 
97636b216c8SBoris Burkov 	ret = btrfs_remove_free_space_inode(trans, inode, block_group);
977e3e0520bSJosef Bacik 	if (ret)
9789fecd132SFilipe Manana 		goto out;
979e3e0520bSJosef Bacik 
98016b0c258SFilipe Manana 	write_lock(&fs_info->block_group_cache_lock);
98108dddb29SFilipe Manana 	rb_erase_cached(&block_group->cache_node,
982e3e0520bSJosef Bacik 			&fs_info->block_group_cache_tree);
983e3e0520bSJosef Bacik 	RB_CLEAR_NODE(&block_group->cache_node);
984e3e0520bSJosef Bacik 
9859fecd132SFilipe Manana 	/* Once for the block groups rbtree */
9869fecd132SFilipe Manana 	btrfs_put_block_group(block_group);
9879fecd132SFilipe Manana 
98816b0c258SFilipe Manana 	write_unlock(&fs_info->block_group_cache_lock);
989e3e0520bSJosef Bacik 
990e3e0520bSJosef Bacik 	down_write(&block_group->space_info->groups_sem);
991e3e0520bSJosef Bacik 	/*
992e3e0520bSJosef Bacik 	 * we must use list_del_init so people can check to see if they
993e3e0520bSJosef Bacik 	 * are still on the list after taking the semaphore
994e3e0520bSJosef Bacik 	 */
995e3e0520bSJosef Bacik 	list_del_init(&block_group->list);
996e3e0520bSJosef Bacik 	if (list_empty(&block_group->space_info->block_groups[index])) {
997e3e0520bSJosef Bacik 		kobj = block_group->space_info->block_group_kobjs[index];
998e3e0520bSJosef Bacik 		block_group->space_info->block_group_kobjs[index] = NULL;
999e3e0520bSJosef Bacik 		clear_avail_alloc_bits(fs_info, block_group->flags);
1000e3e0520bSJosef Bacik 	}
1001e3e0520bSJosef Bacik 	up_write(&block_group->space_info->groups_sem);
1002e3e0520bSJosef Bacik 	clear_incompat_bg_bits(fs_info, block_group->flags);
1003e3e0520bSJosef Bacik 	if (kobj) {
1004e3e0520bSJosef Bacik 		kobject_del(kobj);
1005e3e0520bSJosef Bacik 		kobject_put(kobj);
1006e3e0520bSJosef Bacik 	}
1007e3e0520bSJosef Bacik 
1008e3e0520bSJosef Bacik 	if (block_group->has_caching_ctl)
1009e3e0520bSJosef Bacik 		caching_ctl = btrfs_get_caching_control(block_group);
1010e3e0520bSJosef Bacik 	if (block_group->cached == BTRFS_CACHE_STARTED)
1011e3e0520bSJosef Bacik 		btrfs_wait_block_group_cache_done(block_group);
1012e3e0520bSJosef Bacik 	if (block_group->has_caching_ctl) {
101316b0c258SFilipe Manana 		write_lock(&fs_info->block_group_cache_lock);
1014e3e0520bSJosef Bacik 		if (!caching_ctl) {
1015e3e0520bSJosef Bacik 			struct btrfs_caching_control *ctl;
1016e3e0520bSJosef Bacik 
1017e3e0520bSJosef Bacik 			list_for_each_entry(ctl,
1018e3e0520bSJosef Bacik 				    &fs_info->caching_block_groups, list)
1019e3e0520bSJosef Bacik 				if (ctl->block_group == block_group) {
1020e3e0520bSJosef Bacik 					caching_ctl = ctl;
1021e3e0520bSJosef Bacik 					refcount_inc(&caching_ctl->count);
1022e3e0520bSJosef Bacik 					break;
1023e3e0520bSJosef Bacik 				}
1024e3e0520bSJosef Bacik 		}
1025e3e0520bSJosef Bacik 		if (caching_ctl)
1026e3e0520bSJosef Bacik 			list_del_init(&caching_ctl->list);
102716b0c258SFilipe Manana 		write_unlock(&fs_info->block_group_cache_lock);
1028e3e0520bSJosef Bacik 		if (caching_ctl) {
1029e3e0520bSJosef Bacik 			/* Once for the caching bgs list and once for us. */
1030e3e0520bSJosef Bacik 			btrfs_put_caching_control(caching_ctl);
1031e3e0520bSJosef Bacik 			btrfs_put_caching_control(caching_ctl);
1032e3e0520bSJosef Bacik 		}
1033e3e0520bSJosef Bacik 	}
1034e3e0520bSJosef Bacik 
1035e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
1036e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->dirty_list));
1037e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->io_list));
1038e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1039e3e0520bSJosef Bacik 
1040e3e0520bSJosef Bacik 	btrfs_remove_free_space_cache(block_group);
1041e3e0520bSJosef Bacik 
1042e3e0520bSJosef Bacik 	spin_lock(&block_group->space_info->lock);
1043e3e0520bSJosef Bacik 	list_del_init(&block_group->ro_list);
1044e3e0520bSJosef Bacik 
1045e3e0520bSJosef Bacik 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1046e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->total_bytes
1047b3470b5dSDavid Sterba 			< block_group->length);
1048e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->bytes_readonly
1049169e0da9SNaohiro Aota 			< block_group->length - block_group->zone_unusable);
1050169e0da9SNaohiro Aota 		WARN_ON(block_group->space_info->bytes_zone_unusable
1051169e0da9SNaohiro Aota 			< block_group->zone_unusable);
1052e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->disk_total
1053b3470b5dSDavid Sterba 			< block_group->length * factor);
1054e3e0520bSJosef Bacik 	}
1055b3470b5dSDavid Sterba 	block_group->space_info->total_bytes -= block_group->length;
1056169e0da9SNaohiro Aota 	block_group->space_info->bytes_readonly -=
1057169e0da9SNaohiro Aota 		(block_group->length - block_group->zone_unusable);
1058169e0da9SNaohiro Aota 	block_group->space_info->bytes_zone_unusable -=
1059169e0da9SNaohiro Aota 		block_group->zone_unusable;
1060b3470b5dSDavid Sterba 	block_group->space_info->disk_total -= block_group->length * factor;
1061e3e0520bSJosef Bacik 
1062e3e0520bSJosef Bacik 	spin_unlock(&block_group->space_info->lock);
1063e3e0520bSJosef Bacik 
1064ffcb9d44SFilipe Manana 	/*
1065ffcb9d44SFilipe Manana 	 * Remove the free space for the block group from the free space tree
1066ffcb9d44SFilipe Manana 	 * and the block group's item from the extent tree before marking the
1067ffcb9d44SFilipe Manana 	 * block group as removed. This is to prevent races with tasks that
1068ffcb9d44SFilipe Manana 	 * freeze and unfreeze a block group, this task and another task
1069ffcb9d44SFilipe Manana 	 * allocating a new block group - the unfreeze task ends up removing
1070ffcb9d44SFilipe Manana 	 * the block group's extent map before the task calling this function
1071ffcb9d44SFilipe Manana 	 * deletes the block group item from the extent tree, allowing for
1072ffcb9d44SFilipe Manana 	 * another task to attempt to create another block group with the same
1073ffcb9d44SFilipe Manana 	 * item key (and failing with -EEXIST and a transaction abort).
1074ffcb9d44SFilipe Manana 	 */
1075ffcb9d44SFilipe Manana 	ret = remove_block_group_free_space(trans, block_group);
1076ffcb9d44SFilipe Manana 	if (ret)
1077ffcb9d44SFilipe Manana 		goto out;
1078ffcb9d44SFilipe Manana 
1079ffcb9d44SFilipe Manana 	ret = remove_block_group_item(trans, path, block_group);
1080ffcb9d44SFilipe Manana 	if (ret < 0)
1081ffcb9d44SFilipe Manana 		goto out;
1082ffcb9d44SFilipe Manana 
1083e3e0520bSJosef Bacik 	spin_lock(&block_group->lock);
1084e3e0520bSJosef Bacik 	block_group->removed = 1;
1085e3e0520bSJosef Bacik 	/*
10866b7304afSFilipe Manana 	 * At this point trimming or scrub can't start on this block group,
10876b7304afSFilipe Manana 	 * because we removed the block group from the rbtree
10886b7304afSFilipe Manana 	 * fs_info->block_group_cache_tree so no one can't find it anymore and
10896b7304afSFilipe Manana 	 * even if someone already got this block group before we removed it
10906b7304afSFilipe Manana 	 * from the rbtree, they have already incremented block_group->frozen -
10916b7304afSFilipe Manana 	 * if they didn't, for the trimming case they won't find any free space
10926b7304afSFilipe Manana 	 * entries because we already removed them all when we called
10936b7304afSFilipe Manana 	 * btrfs_remove_free_space_cache().
1094e3e0520bSJosef Bacik 	 *
1095e3e0520bSJosef Bacik 	 * And we must not remove the extent map from the fs_info->mapping_tree
1096e3e0520bSJosef Bacik 	 * to prevent the same logical address range and physical device space
10976b7304afSFilipe Manana 	 * ranges from being reused for a new block group. This is needed to
10986b7304afSFilipe Manana 	 * avoid races with trimming and scrub.
10996b7304afSFilipe Manana 	 *
11006b7304afSFilipe Manana 	 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1101e3e0520bSJosef Bacik 	 * completely transactionless, so while it is trimming a range the
1102e3e0520bSJosef Bacik 	 * currently running transaction might finish and a new one start,
1103e3e0520bSJosef Bacik 	 * allowing for new block groups to be created that can reuse the same
1104e3e0520bSJosef Bacik 	 * physical device locations unless we take this special care.
1105e3e0520bSJosef Bacik 	 *
1106e3e0520bSJosef Bacik 	 * There may also be an implicit trim operation if the file system
1107e3e0520bSJosef Bacik 	 * is mounted with -odiscard. The same protections must remain
1108e3e0520bSJosef Bacik 	 * in place until the extents have been discarded completely when
1109e3e0520bSJosef Bacik 	 * the transaction commit has completed.
1110e3e0520bSJosef Bacik 	 */
11116b7304afSFilipe Manana 	remove_em = (atomic_read(&block_group->frozen) == 0);
1112e3e0520bSJosef Bacik 	spin_unlock(&block_group->lock);
1113e3e0520bSJosef Bacik 
1114e3e0520bSJosef Bacik 	if (remove_em) {
1115e3e0520bSJosef Bacik 		struct extent_map_tree *em_tree;
1116e3e0520bSJosef Bacik 
1117e3e0520bSJosef Bacik 		em_tree = &fs_info->mapping_tree;
1118e3e0520bSJosef Bacik 		write_lock(&em_tree->lock);
1119e3e0520bSJosef Bacik 		remove_extent_mapping(em_tree, em);
1120e3e0520bSJosef Bacik 		write_unlock(&em_tree->lock);
1121e3e0520bSJosef Bacik 		/* once for the tree */
1122e3e0520bSJosef Bacik 		free_extent_map(em);
1123e3e0520bSJosef Bacik 	}
1124f6033c5eSXiyu Yang 
11259fecd132SFilipe Manana out:
1126f6033c5eSXiyu Yang 	/* Once for the lookup reference */
1127f6033c5eSXiyu Yang 	btrfs_put_block_group(block_group);
1128e3e0520bSJosef Bacik 	if (remove_rsv)
1129e3e0520bSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
1130e3e0520bSJosef Bacik 	btrfs_free_path(path);
1131e3e0520bSJosef Bacik 	return ret;
1132e3e0520bSJosef Bacik }
1133e3e0520bSJosef Bacik 
1134e3e0520bSJosef Bacik struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1135e3e0520bSJosef Bacik 		struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1136e3e0520bSJosef Bacik {
1137dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
1138e3e0520bSJosef Bacik 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1139e3e0520bSJosef Bacik 	struct extent_map *em;
1140e3e0520bSJosef Bacik 	struct map_lookup *map;
1141e3e0520bSJosef Bacik 	unsigned int num_items;
1142e3e0520bSJosef Bacik 
1143e3e0520bSJosef Bacik 	read_lock(&em_tree->lock);
1144e3e0520bSJosef Bacik 	em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1145e3e0520bSJosef Bacik 	read_unlock(&em_tree->lock);
1146e3e0520bSJosef Bacik 	ASSERT(em && em->start == chunk_offset);
1147e3e0520bSJosef Bacik 
1148e3e0520bSJosef Bacik 	/*
1149e3e0520bSJosef Bacik 	 * We need to reserve 3 + N units from the metadata space info in order
1150e3e0520bSJosef Bacik 	 * to remove a block group (done at btrfs_remove_chunk() and at
1151e3e0520bSJosef Bacik 	 * btrfs_remove_block_group()), which are used for:
1152e3e0520bSJosef Bacik 	 *
1153e3e0520bSJosef Bacik 	 * 1 unit for adding the free space inode's orphan (located in the tree
1154e3e0520bSJosef Bacik 	 * of tree roots).
1155e3e0520bSJosef Bacik 	 * 1 unit for deleting the block group item (located in the extent
1156e3e0520bSJosef Bacik 	 * tree).
1157e3e0520bSJosef Bacik 	 * 1 unit for deleting the free space item (located in tree of tree
1158e3e0520bSJosef Bacik 	 * roots).
1159e3e0520bSJosef Bacik 	 * N units for deleting N device extent items corresponding to each
1160e3e0520bSJosef Bacik 	 * stripe (located in the device tree).
1161e3e0520bSJosef Bacik 	 *
1162e3e0520bSJosef Bacik 	 * In order to remove a block group we also need to reserve units in the
1163e3e0520bSJosef Bacik 	 * system space info in order to update the chunk tree (update one or
1164e3e0520bSJosef Bacik 	 * more device items and remove one chunk item), but this is done at
1165e3e0520bSJosef Bacik 	 * btrfs_remove_chunk() through a call to check_system_chunk().
1166e3e0520bSJosef Bacik 	 */
1167e3e0520bSJosef Bacik 	map = em->map_lookup;
1168e3e0520bSJosef Bacik 	num_items = 3 + map->num_stripes;
1169e3e0520bSJosef Bacik 	free_extent_map(em);
1170e3e0520bSJosef Bacik 
1171dfe8aec4SJosef Bacik 	return btrfs_start_transaction_fallback_global_rsv(root, num_items);
1172e3e0520bSJosef Bacik }
1173e3e0520bSJosef Bacik 
1174e3e0520bSJosef Bacik /*
117526ce2095SJosef Bacik  * Mark block group @cache read-only, so later write won't happen to block
117626ce2095SJosef Bacik  * group @cache.
117726ce2095SJosef Bacik  *
117826ce2095SJosef Bacik  * If @force is not set, this function will only mark the block group readonly
117926ce2095SJosef Bacik  * if we have enough free space (1M) in other metadata/system block groups.
118026ce2095SJosef Bacik  * If @force is not set, this function will mark the block group readonly
118126ce2095SJosef Bacik  * without checking free space.
118226ce2095SJosef Bacik  *
118326ce2095SJosef Bacik  * NOTE: This function doesn't care if other block groups can contain all the
118426ce2095SJosef Bacik  * data in this block group. That check should be done by relocation routine,
118526ce2095SJosef Bacik  * not this function.
118626ce2095SJosef Bacik  */
118732da5386SDavid Sterba static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
118826ce2095SJosef Bacik {
118926ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
119026ce2095SJosef Bacik 	u64 num_bytes;
119126ce2095SJosef Bacik 	int ret = -ENOSPC;
119226ce2095SJosef Bacik 
119326ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
119426ce2095SJosef Bacik 	spin_lock(&cache->lock);
119526ce2095SJosef Bacik 
1196195a49eaSFilipe Manana 	if (cache->swap_extents) {
1197195a49eaSFilipe Manana 		ret = -ETXTBSY;
1198195a49eaSFilipe Manana 		goto out;
1199195a49eaSFilipe Manana 	}
1200195a49eaSFilipe Manana 
120126ce2095SJosef Bacik 	if (cache->ro) {
120226ce2095SJosef Bacik 		cache->ro++;
120326ce2095SJosef Bacik 		ret = 0;
120426ce2095SJosef Bacik 		goto out;
120526ce2095SJosef Bacik 	}
120626ce2095SJosef Bacik 
1207b3470b5dSDavid Sterba 	num_bytes = cache->length - cache->reserved - cache->pinned -
1208169e0da9SNaohiro Aota 		    cache->bytes_super - cache->zone_unusable - cache->used;
120926ce2095SJosef Bacik 
121026ce2095SJosef Bacik 	/*
1211a30a3d20SJosef Bacik 	 * Data never overcommits, even in mixed mode, so do just the straight
1212a30a3d20SJosef Bacik 	 * check of left over space in how much we have allocated.
1213a30a3d20SJosef Bacik 	 */
1214a30a3d20SJosef Bacik 	if (force) {
1215a30a3d20SJosef Bacik 		ret = 0;
1216a30a3d20SJosef Bacik 	} else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1217a30a3d20SJosef Bacik 		u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1218a30a3d20SJosef Bacik 
1219a30a3d20SJosef Bacik 		/*
122026ce2095SJosef Bacik 		 * Here we make sure if we mark this bg RO, we still have enough
1221f8935566SJosef Bacik 		 * free space as buffer.
122226ce2095SJosef Bacik 		 */
1223a30a3d20SJosef Bacik 		if (sinfo_used + num_bytes <= sinfo->total_bytes)
1224a30a3d20SJosef Bacik 			ret = 0;
1225a30a3d20SJosef Bacik 	} else {
1226a30a3d20SJosef Bacik 		/*
1227a30a3d20SJosef Bacik 		 * We overcommit metadata, so we need to do the
1228a30a3d20SJosef Bacik 		 * btrfs_can_overcommit check here, and we need to pass in
1229a30a3d20SJosef Bacik 		 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1230a30a3d20SJosef Bacik 		 * leeway to allow us to mark this block group as read only.
1231a30a3d20SJosef Bacik 		 */
1232a30a3d20SJosef Bacik 		if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1233a30a3d20SJosef Bacik 					 BTRFS_RESERVE_NO_FLUSH))
1234a30a3d20SJosef Bacik 			ret = 0;
1235a30a3d20SJosef Bacik 	}
1236a30a3d20SJosef Bacik 
1237a30a3d20SJosef Bacik 	if (!ret) {
123826ce2095SJosef Bacik 		sinfo->bytes_readonly += num_bytes;
1239169e0da9SNaohiro Aota 		if (btrfs_is_zoned(cache->fs_info)) {
1240169e0da9SNaohiro Aota 			/* Migrate zone_unusable bytes to readonly */
1241169e0da9SNaohiro Aota 			sinfo->bytes_readonly += cache->zone_unusable;
1242169e0da9SNaohiro Aota 			sinfo->bytes_zone_unusable -= cache->zone_unusable;
1243169e0da9SNaohiro Aota 			cache->zone_unusable = 0;
1244169e0da9SNaohiro Aota 		}
124526ce2095SJosef Bacik 		cache->ro++;
124626ce2095SJosef Bacik 		list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
124726ce2095SJosef Bacik 	}
124826ce2095SJosef Bacik out:
124926ce2095SJosef Bacik 	spin_unlock(&cache->lock);
125026ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
125126ce2095SJosef Bacik 	if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
125226ce2095SJosef Bacik 		btrfs_info(cache->fs_info,
1253b3470b5dSDavid Sterba 			"unable to make block group %llu ro", cache->start);
125426ce2095SJosef Bacik 		btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
125526ce2095SJosef Bacik 	}
125626ce2095SJosef Bacik 	return ret;
125726ce2095SJosef Bacik }
125826ce2095SJosef Bacik 
1259fe119a6eSNikolay Borisov static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1260fe119a6eSNikolay Borisov 				 struct btrfs_block_group *bg)
126145bb5d6aSNikolay Borisov {
126245bb5d6aSNikolay Borisov 	struct btrfs_fs_info *fs_info = bg->fs_info;
1263fe119a6eSNikolay Borisov 	struct btrfs_transaction *prev_trans = NULL;
126445bb5d6aSNikolay Borisov 	const u64 start = bg->start;
126545bb5d6aSNikolay Borisov 	const u64 end = start + bg->length - 1;
126645bb5d6aSNikolay Borisov 	int ret;
126745bb5d6aSNikolay Borisov 
1268fe119a6eSNikolay Borisov 	spin_lock(&fs_info->trans_lock);
1269fe119a6eSNikolay Borisov 	if (trans->transaction->list.prev != &fs_info->trans_list) {
1270fe119a6eSNikolay Borisov 		prev_trans = list_last_entry(&trans->transaction->list,
1271fe119a6eSNikolay Borisov 					     struct btrfs_transaction, list);
1272fe119a6eSNikolay Borisov 		refcount_inc(&prev_trans->use_count);
1273fe119a6eSNikolay Borisov 	}
1274fe119a6eSNikolay Borisov 	spin_unlock(&fs_info->trans_lock);
1275fe119a6eSNikolay Borisov 
127645bb5d6aSNikolay Borisov 	/*
127745bb5d6aSNikolay Borisov 	 * Hold the unused_bg_unpin_mutex lock to avoid racing with
127845bb5d6aSNikolay Borisov 	 * btrfs_finish_extent_commit(). If we are at transaction N, another
127945bb5d6aSNikolay Borisov 	 * task might be running finish_extent_commit() for the previous
128045bb5d6aSNikolay Borisov 	 * transaction N - 1, and have seen a range belonging to the block
1281fe119a6eSNikolay Borisov 	 * group in pinned_extents before we were able to clear the whole block
1282fe119a6eSNikolay Borisov 	 * group range from pinned_extents. This means that task can lookup for
1283fe119a6eSNikolay Borisov 	 * the block group after we unpinned it from pinned_extents and removed
1284fe119a6eSNikolay Borisov 	 * it, leading to a BUG_ON() at unpin_extent_range().
128545bb5d6aSNikolay Borisov 	 */
128645bb5d6aSNikolay Borisov 	mutex_lock(&fs_info->unused_bg_unpin_mutex);
1287fe119a6eSNikolay Borisov 	if (prev_trans) {
1288fe119a6eSNikolay Borisov 		ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
128945bb5d6aSNikolay Borisov 					EXTENT_DIRTY);
129045bb5d6aSNikolay Borisov 		if (ret)
1291534cf531SFilipe Manana 			goto out;
1292fe119a6eSNikolay Borisov 	}
129345bb5d6aSNikolay Borisov 
1294fe119a6eSNikolay Borisov 	ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
129545bb5d6aSNikolay Borisov 				EXTENT_DIRTY);
1296534cf531SFilipe Manana out:
129745bb5d6aSNikolay Borisov 	mutex_unlock(&fs_info->unused_bg_unpin_mutex);
12985150bf19SFilipe Manana 	if (prev_trans)
12995150bf19SFilipe Manana 		btrfs_put_transaction(prev_trans);
130045bb5d6aSNikolay Borisov 
1301534cf531SFilipe Manana 	return ret == 0;
130245bb5d6aSNikolay Borisov }
130345bb5d6aSNikolay Borisov 
130426ce2095SJosef Bacik /*
1305e3e0520bSJosef Bacik  * Process the unused_bgs list and remove any that don't have any allocated
1306e3e0520bSJosef Bacik  * space inside of them.
1307e3e0520bSJosef Bacik  */
1308e3e0520bSJosef Bacik void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1309e3e0520bSJosef Bacik {
131032da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1311e3e0520bSJosef Bacik 	struct btrfs_space_info *space_info;
1312e3e0520bSJosef Bacik 	struct btrfs_trans_handle *trans;
13136e80d4f8SDennis Zhou 	const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1314e3e0520bSJosef Bacik 	int ret = 0;
1315e3e0520bSJosef Bacik 
1316e3e0520bSJosef Bacik 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1317e3e0520bSJosef Bacik 		return;
1318e3e0520bSJosef Bacik 
1319ddfd08cbSJosef Bacik 	/*
1320ddfd08cbSJosef Bacik 	 * Long running balances can keep us blocked here for eternity, so
1321ddfd08cbSJosef Bacik 	 * simply skip deletion if we're unable to get the mutex.
1322ddfd08cbSJosef Bacik 	 */
1323f3372065SJohannes Thumshirn 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
1324ddfd08cbSJosef Bacik 		return;
1325ddfd08cbSJosef Bacik 
1326e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1327e3e0520bSJosef Bacik 	while (!list_empty(&fs_info->unused_bgs)) {
1328e3e0520bSJosef Bacik 		int trimming;
1329e3e0520bSJosef Bacik 
1330e3e0520bSJosef Bacik 		block_group = list_first_entry(&fs_info->unused_bgs,
133132da5386SDavid Sterba 					       struct btrfs_block_group,
1332e3e0520bSJosef Bacik 					       bg_list);
1333e3e0520bSJosef Bacik 		list_del_init(&block_group->bg_list);
1334e3e0520bSJosef Bacik 
1335e3e0520bSJosef Bacik 		space_info = block_group->space_info;
1336e3e0520bSJosef Bacik 
1337e3e0520bSJosef Bacik 		if (ret || btrfs_mixed_space_info(space_info)) {
1338e3e0520bSJosef Bacik 			btrfs_put_block_group(block_group);
1339e3e0520bSJosef Bacik 			continue;
1340e3e0520bSJosef Bacik 		}
1341e3e0520bSJosef Bacik 		spin_unlock(&fs_info->unused_bgs_lock);
1342e3e0520bSJosef Bacik 
1343b0643e59SDennis Zhou 		btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1344b0643e59SDennis Zhou 
1345e3e0520bSJosef Bacik 		/* Don't want to race with allocators so take the groups_sem */
1346e3e0520bSJosef Bacik 		down_write(&space_info->groups_sem);
13476e80d4f8SDennis Zhou 
13486e80d4f8SDennis Zhou 		/*
13496e80d4f8SDennis Zhou 		 * Async discard moves the final block group discard to be prior
13506e80d4f8SDennis Zhou 		 * to the unused_bgs code path.  Therefore, if it's not fully
13516e80d4f8SDennis Zhou 		 * trimmed, punt it back to the async discard lists.
13526e80d4f8SDennis Zhou 		 */
13536e80d4f8SDennis Zhou 		if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
13546e80d4f8SDennis Zhou 		    !btrfs_is_free_space_trimmed(block_group)) {
13556e80d4f8SDennis Zhou 			trace_btrfs_skip_unused_block_group(block_group);
13566e80d4f8SDennis Zhou 			up_write(&space_info->groups_sem);
13576e80d4f8SDennis Zhou 			/* Requeue if we failed because of async discard */
13586e80d4f8SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
13596e80d4f8SDennis Zhou 						 block_group);
13606e80d4f8SDennis Zhou 			goto next;
13616e80d4f8SDennis Zhou 		}
13626e80d4f8SDennis Zhou 
1363e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1364e3e0520bSJosef Bacik 		if (block_group->reserved || block_group->pinned ||
1365bf38be65SDavid Sterba 		    block_group->used || block_group->ro ||
1366e3e0520bSJosef Bacik 		    list_is_singular(&block_group->list)) {
1367e3e0520bSJosef Bacik 			/*
1368e3e0520bSJosef Bacik 			 * We want to bail if we made new allocations or have
1369e3e0520bSJosef Bacik 			 * outstanding allocations in this block group.  We do
1370e3e0520bSJosef Bacik 			 * the ro check in case balance is currently acting on
1371e3e0520bSJosef Bacik 			 * this block group.
1372e3e0520bSJosef Bacik 			 */
1373e3e0520bSJosef Bacik 			trace_btrfs_skip_unused_block_group(block_group);
1374e3e0520bSJosef Bacik 			spin_unlock(&block_group->lock);
1375e3e0520bSJosef Bacik 			up_write(&space_info->groups_sem);
1376e3e0520bSJosef Bacik 			goto next;
1377e3e0520bSJosef Bacik 		}
1378e3e0520bSJosef Bacik 		spin_unlock(&block_group->lock);
1379e3e0520bSJosef Bacik 
1380e3e0520bSJosef Bacik 		/* We don't want to force the issue, only flip if it's ok. */
1381e11c0406SJosef Bacik 		ret = inc_block_group_ro(block_group, 0);
1382e3e0520bSJosef Bacik 		up_write(&space_info->groups_sem);
1383e3e0520bSJosef Bacik 		if (ret < 0) {
1384e3e0520bSJosef Bacik 			ret = 0;
1385e3e0520bSJosef Bacik 			goto next;
1386e3e0520bSJosef Bacik 		}
1387e3e0520bSJosef Bacik 
1388e3e0520bSJosef Bacik 		/*
1389e3e0520bSJosef Bacik 		 * Want to do this before we do anything else so we can recover
1390e3e0520bSJosef Bacik 		 * properly if we fail to join the transaction.
1391e3e0520bSJosef Bacik 		 */
1392e3e0520bSJosef Bacik 		trans = btrfs_start_trans_remove_block_group(fs_info,
1393b3470b5dSDavid Sterba 						     block_group->start);
1394e3e0520bSJosef Bacik 		if (IS_ERR(trans)) {
1395e3e0520bSJosef Bacik 			btrfs_dec_block_group_ro(block_group);
1396e3e0520bSJosef Bacik 			ret = PTR_ERR(trans);
1397e3e0520bSJosef Bacik 			goto next;
1398e3e0520bSJosef Bacik 		}
1399e3e0520bSJosef Bacik 
1400e3e0520bSJosef Bacik 		/*
1401e3e0520bSJosef Bacik 		 * We could have pending pinned extents for this block group,
1402e3e0520bSJosef Bacik 		 * just delete them, we don't care about them anymore.
1403e3e0520bSJosef Bacik 		 */
1404534cf531SFilipe Manana 		if (!clean_pinned_extents(trans, block_group)) {
1405534cf531SFilipe Manana 			btrfs_dec_block_group_ro(block_group);
1406e3e0520bSJosef Bacik 			goto end_trans;
1407534cf531SFilipe Manana 		}
1408e3e0520bSJosef Bacik 
1409b0643e59SDennis Zhou 		/*
1410b0643e59SDennis Zhou 		 * At this point, the block_group is read only and should fail
1411b0643e59SDennis Zhou 		 * new allocations.  However, btrfs_finish_extent_commit() can
1412b0643e59SDennis Zhou 		 * cause this block_group to be placed back on the discard
1413b0643e59SDennis Zhou 		 * lists because now the block_group isn't fully discarded.
1414b0643e59SDennis Zhou 		 * Bail here and try again later after discarding everything.
1415b0643e59SDennis Zhou 		 */
1416b0643e59SDennis Zhou 		spin_lock(&fs_info->discard_ctl.lock);
1417b0643e59SDennis Zhou 		if (!list_empty(&block_group->discard_list)) {
1418b0643e59SDennis Zhou 			spin_unlock(&fs_info->discard_ctl.lock);
1419b0643e59SDennis Zhou 			btrfs_dec_block_group_ro(block_group);
1420b0643e59SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
1421b0643e59SDennis Zhou 						 block_group);
1422b0643e59SDennis Zhou 			goto end_trans;
1423b0643e59SDennis Zhou 		}
1424b0643e59SDennis Zhou 		spin_unlock(&fs_info->discard_ctl.lock);
1425b0643e59SDennis Zhou 
1426e3e0520bSJosef Bacik 		/* Reset pinned so btrfs_put_block_group doesn't complain */
1427e3e0520bSJosef Bacik 		spin_lock(&space_info->lock);
1428e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1429e3e0520bSJosef Bacik 
1430e3e0520bSJosef Bacik 		btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1431e3e0520bSJosef Bacik 						     -block_group->pinned);
1432e3e0520bSJosef Bacik 		space_info->bytes_readonly += block_group->pinned;
1433e3e0520bSJosef Bacik 		block_group->pinned = 0;
1434e3e0520bSJosef Bacik 
1435e3e0520bSJosef Bacik 		spin_unlock(&block_group->lock);
1436e3e0520bSJosef Bacik 		spin_unlock(&space_info->lock);
1437e3e0520bSJosef Bacik 
14386e80d4f8SDennis Zhou 		/*
14396e80d4f8SDennis Zhou 		 * The normal path here is an unused block group is passed here,
14406e80d4f8SDennis Zhou 		 * then trimming is handled in the transaction commit path.
14416e80d4f8SDennis Zhou 		 * Async discard interposes before this to do the trimming
14426e80d4f8SDennis Zhou 		 * before coming down the unused block group path as trimming
14436e80d4f8SDennis Zhou 		 * will no longer be done later in the transaction commit path.
14446e80d4f8SDennis Zhou 		 */
14456e80d4f8SDennis Zhou 		if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
14466e80d4f8SDennis Zhou 			goto flip_async;
14476e80d4f8SDennis Zhou 
1448dcba6e48SNaohiro Aota 		/*
1449dcba6e48SNaohiro Aota 		 * DISCARD can flip during remount. On zoned filesystems, we
1450dcba6e48SNaohiro Aota 		 * need to reset sequential-required zones.
1451dcba6e48SNaohiro Aota 		 */
1452dcba6e48SNaohiro Aota 		trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) ||
1453dcba6e48SNaohiro Aota 				btrfs_is_zoned(fs_info);
1454e3e0520bSJosef Bacik 
1455e3e0520bSJosef Bacik 		/* Implicit trim during transaction commit. */
1456e3e0520bSJosef Bacik 		if (trimming)
14576b7304afSFilipe Manana 			btrfs_freeze_block_group(block_group);
1458e3e0520bSJosef Bacik 
1459e3e0520bSJosef Bacik 		/*
1460e3e0520bSJosef Bacik 		 * Btrfs_remove_chunk will abort the transaction if things go
1461e3e0520bSJosef Bacik 		 * horribly wrong.
1462e3e0520bSJosef Bacik 		 */
1463b3470b5dSDavid Sterba 		ret = btrfs_remove_chunk(trans, block_group->start);
1464e3e0520bSJosef Bacik 
1465e3e0520bSJosef Bacik 		if (ret) {
1466e3e0520bSJosef Bacik 			if (trimming)
14676b7304afSFilipe Manana 				btrfs_unfreeze_block_group(block_group);
1468e3e0520bSJosef Bacik 			goto end_trans;
1469e3e0520bSJosef Bacik 		}
1470e3e0520bSJosef Bacik 
1471e3e0520bSJosef Bacik 		/*
1472e3e0520bSJosef Bacik 		 * If we're not mounted with -odiscard, we can just forget
1473e3e0520bSJosef Bacik 		 * about this block group. Otherwise we'll need to wait
1474e3e0520bSJosef Bacik 		 * until transaction commit to do the actual discard.
1475e3e0520bSJosef Bacik 		 */
1476e3e0520bSJosef Bacik 		if (trimming) {
1477e3e0520bSJosef Bacik 			spin_lock(&fs_info->unused_bgs_lock);
1478e3e0520bSJosef Bacik 			/*
1479e3e0520bSJosef Bacik 			 * A concurrent scrub might have added us to the list
1480e3e0520bSJosef Bacik 			 * fs_info->unused_bgs, so use a list_move operation
1481e3e0520bSJosef Bacik 			 * to add the block group to the deleted_bgs list.
1482e3e0520bSJosef Bacik 			 */
1483e3e0520bSJosef Bacik 			list_move(&block_group->bg_list,
1484e3e0520bSJosef Bacik 				  &trans->transaction->deleted_bgs);
1485e3e0520bSJosef Bacik 			spin_unlock(&fs_info->unused_bgs_lock);
1486e3e0520bSJosef Bacik 			btrfs_get_block_group(block_group);
1487e3e0520bSJosef Bacik 		}
1488e3e0520bSJosef Bacik end_trans:
1489e3e0520bSJosef Bacik 		btrfs_end_transaction(trans);
1490e3e0520bSJosef Bacik next:
1491e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1492e3e0520bSJosef Bacik 		spin_lock(&fs_info->unused_bgs_lock);
1493e3e0520bSJosef Bacik 	}
1494e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
1495f3372065SJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
14966e80d4f8SDennis Zhou 	return;
14976e80d4f8SDennis Zhou 
14986e80d4f8SDennis Zhou flip_async:
14996e80d4f8SDennis Zhou 	btrfs_end_transaction(trans);
1500f3372065SJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
15016e80d4f8SDennis Zhou 	btrfs_put_block_group(block_group);
15026e80d4f8SDennis Zhou 	btrfs_discard_punt_unused_bgs_list(fs_info);
1503e3e0520bSJosef Bacik }
1504e3e0520bSJosef Bacik 
150532da5386SDavid Sterba void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1506e3e0520bSJosef Bacik {
1507e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = bg->fs_info;
1508e3e0520bSJosef Bacik 
1509e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1510e3e0520bSJosef Bacik 	if (list_empty(&bg->bg_list)) {
1511e3e0520bSJosef Bacik 		btrfs_get_block_group(bg);
1512e3e0520bSJosef Bacik 		trace_btrfs_add_unused_block_group(bg);
1513e3e0520bSJosef Bacik 		list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1514e3e0520bSJosef Bacik 	}
1515e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
1516e3e0520bSJosef Bacik }
15174358d963SJosef Bacik 
15182ca0ec77SJohannes Thumshirn /*
15192ca0ec77SJohannes Thumshirn  * We want block groups with a low number of used bytes to be in the beginning
15202ca0ec77SJohannes Thumshirn  * of the list, so they will get reclaimed first.
15212ca0ec77SJohannes Thumshirn  */
15222ca0ec77SJohannes Thumshirn static int reclaim_bgs_cmp(void *unused, const struct list_head *a,
15232ca0ec77SJohannes Thumshirn 			   const struct list_head *b)
15242ca0ec77SJohannes Thumshirn {
15252ca0ec77SJohannes Thumshirn 	const struct btrfs_block_group *bg1, *bg2;
15262ca0ec77SJohannes Thumshirn 
15272ca0ec77SJohannes Thumshirn 	bg1 = list_entry(a, struct btrfs_block_group, bg_list);
15282ca0ec77SJohannes Thumshirn 	bg2 = list_entry(b, struct btrfs_block_group, bg_list);
15292ca0ec77SJohannes Thumshirn 
15302ca0ec77SJohannes Thumshirn 	return bg1->used > bg2->used;
15312ca0ec77SJohannes Thumshirn }
15322ca0ec77SJohannes Thumshirn 
15333687fcb0SJohannes Thumshirn static inline bool btrfs_should_reclaim(struct btrfs_fs_info *fs_info)
15343687fcb0SJohannes Thumshirn {
15353687fcb0SJohannes Thumshirn 	if (btrfs_is_zoned(fs_info))
15363687fcb0SJohannes Thumshirn 		return btrfs_zoned_should_reclaim(fs_info);
15373687fcb0SJohannes Thumshirn 	return true;
15383687fcb0SJohannes Thumshirn }
15393687fcb0SJohannes Thumshirn 
154018bb8bbfSJohannes Thumshirn void btrfs_reclaim_bgs_work(struct work_struct *work)
154118bb8bbfSJohannes Thumshirn {
154218bb8bbfSJohannes Thumshirn 	struct btrfs_fs_info *fs_info =
154318bb8bbfSJohannes Thumshirn 		container_of(work, struct btrfs_fs_info, reclaim_bgs_work);
154418bb8bbfSJohannes Thumshirn 	struct btrfs_block_group *bg;
154518bb8bbfSJohannes Thumshirn 	struct btrfs_space_info *space_info;
154618bb8bbfSJohannes Thumshirn 
154718bb8bbfSJohannes Thumshirn 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
154818bb8bbfSJohannes Thumshirn 		return;
154918bb8bbfSJohannes Thumshirn 
15503687fcb0SJohannes Thumshirn 	if (!btrfs_should_reclaim(fs_info))
15513687fcb0SJohannes Thumshirn 		return;
15523687fcb0SJohannes Thumshirn 
1553ca5e4ea0SNaohiro Aota 	sb_start_write(fs_info->sb);
1554ca5e4ea0SNaohiro Aota 
1555ca5e4ea0SNaohiro Aota 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
1556ca5e4ea0SNaohiro Aota 		sb_end_write(fs_info->sb);
155718bb8bbfSJohannes Thumshirn 		return;
1558ca5e4ea0SNaohiro Aota 	}
155918bb8bbfSJohannes Thumshirn 
15609cc0b837SJohannes Thumshirn 	/*
15619cc0b837SJohannes Thumshirn 	 * Long running balances can keep us blocked here for eternity, so
15629cc0b837SJohannes Thumshirn 	 * simply skip reclaim if we're unable to get the mutex.
15639cc0b837SJohannes Thumshirn 	 */
15649cc0b837SJohannes Thumshirn 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) {
15659cc0b837SJohannes Thumshirn 		btrfs_exclop_finish(fs_info);
1566ca5e4ea0SNaohiro Aota 		sb_end_write(fs_info->sb);
15679cc0b837SJohannes Thumshirn 		return;
15689cc0b837SJohannes Thumshirn 	}
15699cc0b837SJohannes Thumshirn 
157018bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
15712ca0ec77SJohannes Thumshirn 	/*
15722ca0ec77SJohannes Thumshirn 	 * Sort happens under lock because we can't simply splice it and sort.
15732ca0ec77SJohannes Thumshirn 	 * The block groups might still be in use and reachable via bg_list,
15742ca0ec77SJohannes Thumshirn 	 * and their presence in the reclaim_bgs list must be preserved.
15752ca0ec77SJohannes Thumshirn 	 */
15762ca0ec77SJohannes Thumshirn 	list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp);
157718bb8bbfSJohannes Thumshirn 	while (!list_empty(&fs_info->reclaim_bgs)) {
15785f93e776SJohannes Thumshirn 		u64 zone_unusable;
15791cea5cf0SFilipe Manana 		int ret = 0;
15801cea5cf0SFilipe Manana 
158118bb8bbfSJohannes Thumshirn 		bg = list_first_entry(&fs_info->reclaim_bgs,
158218bb8bbfSJohannes Thumshirn 				      struct btrfs_block_group,
158318bb8bbfSJohannes Thumshirn 				      bg_list);
158418bb8bbfSJohannes Thumshirn 		list_del_init(&bg->bg_list);
158518bb8bbfSJohannes Thumshirn 
158618bb8bbfSJohannes Thumshirn 		space_info = bg->space_info;
158718bb8bbfSJohannes Thumshirn 		spin_unlock(&fs_info->unused_bgs_lock);
158818bb8bbfSJohannes Thumshirn 
158918bb8bbfSJohannes Thumshirn 		/* Don't race with allocators so take the groups_sem */
159018bb8bbfSJohannes Thumshirn 		down_write(&space_info->groups_sem);
159118bb8bbfSJohannes Thumshirn 
159218bb8bbfSJohannes Thumshirn 		spin_lock(&bg->lock);
159318bb8bbfSJohannes Thumshirn 		if (bg->reserved || bg->pinned || bg->ro) {
159418bb8bbfSJohannes Thumshirn 			/*
159518bb8bbfSJohannes Thumshirn 			 * We want to bail if we made new allocations or have
159618bb8bbfSJohannes Thumshirn 			 * outstanding allocations in this block group.  We do
159718bb8bbfSJohannes Thumshirn 			 * the ro check in case balance is currently acting on
159818bb8bbfSJohannes Thumshirn 			 * this block group.
159918bb8bbfSJohannes Thumshirn 			 */
160018bb8bbfSJohannes Thumshirn 			spin_unlock(&bg->lock);
160118bb8bbfSJohannes Thumshirn 			up_write(&space_info->groups_sem);
160218bb8bbfSJohannes Thumshirn 			goto next;
160318bb8bbfSJohannes Thumshirn 		}
160418bb8bbfSJohannes Thumshirn 		spin_unlock(&bg->lock);
160518bb8bbfSJohannes Thumshirn 
160618bb8bbfSJohannes Thumshirn 		/* Get out fast, in case we're unmounting the filesystem */
160718bb8bbfSJohannes Thumshirn 		if (btrfs_fs_closing(fs_info)) {
160818bb8bbfSJohannes Thumshirn 			up_write(&space_info->groups_sem);
160918bb8bbfSJohannes Thumshirn 			goto next;
161018bb8bbfSJohannes Thumshirn 		}
161118bb8bbfSJohannes Thumshirn 
16125f93e776SJohannes Thumshirn 		/*
16135f93e776SJohannes Thumshirn 		 * Cache the zone_unusable value before turning the block group
16145f93e776SJohannes Thumshirn 		 * to read only. As soon as the blog group is read only it's
16155f93e776SJohannes Thumshirn 		 * zone_unusable value gets moved to the block group's read-only
16165f93e776SJohannes Thumshirn 		 * bytes and isn't available for calculations anymore.
16175f93e776SJohannes Thumshirn 		 */
16185f93e776SJohannes Thumshirn 		zone_unusable = bg->zone_unusable;
161918bb8bbfSJohannes Thumshirn 		ret = inc_block_group_ro(bg, 0);
162018bb8bbfSJohannes Thumshirn 		up_write(&space_info->groups_sem);
162118bb8bbfSJohannes Thumshirn 		if (ret < 0)
162218bb8bbfSJohannes Thumshirn 			goto next;
162318bb8bbfSJohannes Thumshirn 
16245f93e776SJohannes Thumshirn 		btrfs_info(fs_info,
16255f93e776SJohannes Thumshirn 			"reclaiming chunk %llu with %llu%% used %llu%% unusable",
16265f93e776SJohannes Thumshirn 				bg->start, div_u64(bg->used * 100, bg->length),
16275f93e776SJohannes Thumshirn 				div64_u64(zone_unusable * 100, bg->length));
162818bb8bbfSJohannes Thumshirn 		trace_btrfs_reclaim_block_group(bg);
162918bb8bbfSJohannes Thumshirn 		ret = btrfs_relocate_chunk(fs_info, bg->start);
1630d96b3424SFilipe Manana 		if (ret)
163118bb8bbfSJohannes Thumshirn 			btrfs_err(fs_info, "error relocating chunk %llu",
163218bb8bbfSJohannes Thumshirn 				  bg->start);
163318bb8bbfSJohannes Thumshirn 
163418bb8bbfSJohannes Thumshirn next:
16351cea5cf0SFilipe Manana 		btrfs_put_block_group(bg);
1636d96b3424SFilipe Manana 		spin_lock(&fs_info->unused_bgs_lock);
163718bb8bbfSJohannes Thumshirn 	}
163818bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
163918bb8bbfSJohannes Thumshirn 	mutex_unlock(&fs_info->reclaim_bgs_lock);
164018bb8bbfSJohannes Thumshirn 	btrfs_exclop_finish(fs_info);
1641ca5e4ea0SNaohiro Aota 	sb_end_write(fs_info->sb);
164218bb8bbfSJohannes Thumshirn }
164318bb8bbfSJohannes Thumshirn 
164418bb8bbfSJohannes Thumshirn void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
164518bb8bbfSJohannes Thumshirn {
164618bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
164718bb8bbfSJohannes Thumshirn 	if (!list_empty(&fs_info->reclaim_bgs))
164818bb8bbfSJohannes Thumshirn 		queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
164918bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
165018bb8bbfSJohannes Thumshirn }
165118bb8bbfSJohannes Thumshirn 
165218bb8bbfSJohannes Thumshirn void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
165318bb8bbfSJohannes Thumshirn {
165418bb8bbfSJohannes Thumshirn 	struct btrfs_fs_info *fs_info = bg->fs_info;
165518bb8bbfSJohannes Thumshirn 
165618bb8bbfSJohannes Thumshirn 	spin_lock(&fs_info->unused_bgs_lock);
165718bb8bbfSJohannes Thumshirn 	if (list_empty(&bg->bg_list)) {
165818bb8bbfSJohannes Thumshirn 		btrfs_get_block_group(bg);
165918bb8bbfSJohannes Thumshirn 		trace_btrfs_add_reclaim_block_group(bg);
166018bb8bbfSJohannes Thumshirn 		list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
166118bb8bbfSJohannes Thumshirn 	}
166218bb8bbfSJohannes Thumshirn 	spin_unlock(&fs_info->unused_bgs_lock);
166318bb8bbfSJohannes Thumshirn }
166418bb8bbfSJohannes Thumshirn 
1665e3ba67a1SJohannes Thumshirn static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1666e3ba67a1SJohannes Thumshirn 			   struct btrfs_path *path)
1667e3ba67a1SJohannes Thumshirn {
1668e3ba67a1SJohannes Thumshirn 	struct extent_map_tree *em_tree;
1669e3ba67a1SJohannes Thumshirn 	struct extent_map *em;
1670e3ba67a1SJohannes Thumshirn 	struct btrfs_block_group_item bg;
1671e3ba67a1SJohannes Thumshirn 	struct extent_buffer *leaf;
1672e3ba67a1SJohannes Thumshirn 	int slot;
1673e3ba67a1SJohannes Thumshirn 	u64 flags;
1674e3ba67a1SJohannes Thumshirn 	int ret = 0;
1675e3ba67a1SJohannes Thumshirn 
1676e3ba67a1SJohannes Thumshirn 	slot = path->slots[0];
1677e3ba67a1SJohannes Thumshirn 	leaf = path->nodes[0];
1678e3ba67a1SJohannes Thumshirn 
1679e3ba67a1SJohannes Thumshirn 	em_tree = &fs_info->mapping_tree;
1680e3ba67a1SJohannes Thumshirn 	read_lock(&em_tree->lock);
1681e3ba67a1SJohannes Thumshirn 	em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1682e3ba67a1SJohannes Thumshirn 	read_unlock(&em_tree->lock);
1683e3ba67a1SJohannes Thumshirn 	if (!em) {
1684e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1685e3ba67a1SJohannes Thumshirn 			  "logical %llu len %llu found bg but no related chunk",
1686e3ba67a1SJohannes Thumshirn 			  key->objectid, key->offset);
1687e3ba67a1SJohannes Thumshirn 		return -ENOENT;
1688e3ba67a1SJohannes Thumshirn 	}
1689e3ba67a1SJohannes Thumshirn 
1690e3ba67a1SJohannes Thumshirn 	if (em->start != key->objectid || em->len != key->offset) {
1691e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1692e3ba67a1SJohannes Thumshirn 			"block group %llu len %llu mismatch with chunk %llu len %llu",
1693e3ba67a1SJohannes Thumshirn 			key->objectid, key->offset, em->start, em->len);
1694e3ba67a1SJohannes Thumshirn 		ret = -EUCLEAN;
1695e3ba67a1SJohannes Thumshirn 		goto out_free_em;
1696e3ba67a1SJohannes Thumshirn 	}
1697e3ba67a1SJohannes Thumshirn 
1698e3ba67a1SJohannes Thumshirn 	read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1699e3ba67a1SJohannes Thumshirn 			   sizeof(bg));
1700e3ba67a1SJohannes Thumshirn 	flags = btrfs_stack_block_group_flags(&bg) &
1701e3ba67a1SJohannes Thumshirn 		BTRFS_BLOCK_GROUP_TYPE_MASK;
1702e3ba67a1SJohannes Thumshirn 
1703e3ba67a1SJohannes Thumshirn 	if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1704e3ba67a1SJohannes Thumshirn 		btrfs_err(fs_info,
1705e3ba67a1SJohannes Thumshirn "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1706e3ba67a1SJohannes Thumshirn 			  key->objectid, key->offset, flags,
1707e3ba67a1SJohannes Thumshirn 			  (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1708e3ba67a1SJohannes Thumshirn 		ret = -EUCLEAN;
1709e3ba67a1SJohannes Thumshirn 	}
1710e3ba67a1SJohannes Thumshirn 
1711e3ba67a1SJohannes Thumshirn out_free_em:
1712e3ba67a1SJohannes Thumshirn 	free_extent_map(em);
1713e3ba67a1SJohannes Thumshirn 	return ret;
1714e3ba67a1SJohannes Thumshirn }
1715e3ba67a1SJohannes Thumshirn 
17164358d963SJosef Bacik static int find_first_block_group(struct btrfs_fs_info *fs_info,
17174358d963SJosef Bacik 				  struct btrfs_path *path,
17184358d963SJosef Bacik 				  struct btrfs_key *key)
17194358d963SJosef Bacik {
1720dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
1721e3ba67a1SJohannes Thumshirn 	int ret;
17224358d963SJosef Bacik 	struct btrfs_key found_key;
17234358d963SJosef Bacik 
172436dfbbe2SGabriel Niebler 	btrfs_for_each_slot(root, key, &found_key, path, ret) {
17254358d963SJosef Bacik 		if (found_key.objectid >= key->objectid &&
17264358d963SJosef Bacik 		    found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
172736dfbbe2SGabriel Niebler 			return read_bg_from_eb(fs_info, &found_key, path);
1728e3ba67a1SJohannes Thumshirn 		}
17294358d963SJosef Bacik 	}
17304358d963SJosef Bacik 	return ret;
17314358d963SJosef Bacik }
17324358d963SJosef Bacik 
17334358d963SJosef Bacik static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
17344358d963SJosef Bacik {
17354358d963SJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
17364358d963SJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
17374358d963SJosef Bacik 
17384358d963SJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
17394358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
17404358d963SJosef Bacik 		fs_info->avail_data_alloc_bits |= extra_flags;
17414358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
17424358d963SJosef Bacik 		fs_info->avail_metadata_alloc_bits |= extra_flags;
17434358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
17444358d963SJosef Bacik 		fs_info->avail_system_alloc_bits |= extra_flags;
17454358d963SJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
17464358d963SJosef Bacik }
17474358d963SJosef Bacik 
174896a14336SNikolay Borisov /**
17499ee9b979SNikolay Borisov  * Map a physical disk address to a list of logical addresses
17509ee9b979SNikolay Borisov  *
17519ee9b979SNikolay Borisov  * @fs_info:       the filesystem
175296a14336SNikolay Borisov  * @chunk_start:   logical address of block group
1753138082f3SNaohiro Aota  * @bdev:	   physical device to resolve, can be NULL to indicate any device
175496a14336SNikolay Borisov  * @physical:	   physical address to map to logical addresses
175596a14336SNikolay Borisov  * @logical:	   return array of logical addresses which map to @physical
175696a14336SNikolay Borisov  * @naddrs:	   length of @logical
175796a14336SNikolay Borisov  * @stripe_len:    size of IO stripe for the given block group
175896a14336SNikolay Borisov  *
175996a14336SNikolay Borisov  * Maps a particular @physical disk address to a list of @logical addresses.
176096a14336SNikolay Borisov  * Used primarily to exclude those portions of a block group that contain super
176196a14336SNikolay Borisov  * block copies.
176296a14336SNikolay Borisov  */
176396a14336SNikolay Borisov int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1764138082f3SNaohiro Aota 		     struct block_device *bdev, u64 physical, u64 **logical,
1765138082f3SNaohiro Aota 		     int *naddrs, int *stripe_len)
176696a14336SNikolay Borisov {
176796a14336SNikolay Borisov 	struct extent_map *em;
176896a14336SNikolay Borisov 	struct map_lookup *map;
176996a14336SNikolay Borisov 	u64 *buf;
177096a14336SNikolay Borisov 	u64 bytenr;
17711776ad17SNikolay Borisov 	u64 data_stripe_length;
17721776ad17SNikolay Borisov 	u64 io_stripe_size;
17731776ad17SNikolay Borisov 	int i, nr = 0;
17741776ad17SNikolay Borisov 	int ret = 0;
177596a14336SNikolay Borisov 
177696a14336SNikolay Borisov 	em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
177796a14336SNikolay Borisov 	if (IS_ERR(em))
177896a14336SNikolay Borisov 		return -EIO;
177996a14336SNikolay Borisov 
178096a14336SNikolay Borisov 	map = em->map_lookup;
17819e22b925SNikolay Borisov 	data_stripe_length = em->orig_block_len;
17821776ad17SNikolay Borisov 	io_stripe_size = map->stripe_len;
1783138082f3SNaohiro Aota 	chunk_start = em->start;
178496a14336SNikolay Borisov 
17859e22b925SNikolay Borisov 	/* For RAID5/6 adjust to a full IO stripe length */
17869e22b925SNikolay Borisov 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
17871776ad17SNikolay Borisov 		io_stripe_size = map->stripe_len * nr_data_stripes(map);
178896a14336SNikolay Borisov 
178996a14336SNikolay Borisov 	buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
17901776ad17SNikolay Borisov 	if (!buf) {
17911776ad17SNikolay Borisov 		ret = -ENOMEM;
17921776ad17SNikolay Borisov 		goto out;
17931776ad17SNikolay Borisov 	}
179496a14336SNikolay Borisov 
179596a14336SNikolay Borisov 	for (i = 0; i < map->num_stripes; i++) {
17961776ad17SNikolay Borisov 		bool already_inserted = false;
17971776ad17SNikolay Borisov 		u64 stripe_nr;
1798138082f3SNaohiro Aota 		u64 offset;
17991776ad17SNikolay Borisov 		int j;
18001776ad17SNikolay Borisov 
18011776ad17SNikolay Borisov 		if (!in_range(physical, map->stripes[i].physical,
18021776ad17SNikolay Borisov 			      data_stripe_length))
180396a14336SNikolay Borisov 			continue;
180496a14336SNikolay Borisov 
1805138082f3SNaohiro Aota 		if (bdev && map->stripes[i].dev->bdev != bdev)
1806138082f3SNaohiro Aota 			continue;
1807138082f3SNaohiro Aota 
180896a14336SNikolay Borisov 		stripe_nr = physical - map->stripes[i].physical;
1809138082f3SNaohiro Aota 		stripe_nr = div64_u64_rem(stripe_nr, map->stripe_len, &offset);
181096a14336SNikolay Borisov 
181196a14336SNikolay Borisov 		if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
181296a14336SNikolay Borisov 			stripe_nr = stripe_nr * map->num_stripes + i;
181396a14336SNikolay Borisov 			stripe_nr = div_u64(stripe_nr, map->sub_stripes);
181496a14336SNikolay Borisov 		} else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
181596a14336SNikolay Borisov 			stripe_nr = stripe_nr * map->num_stripes + i;
181696a14336SNikolay Borisov 		}
181796a14336SNikolay Borisov 		/*
181896a14336SNikolay Borisov 		 * The remaining case would be for RAID56, multiply by
181996a14336SNikolay Borisov 		 * nr_data_stripes().  Alternatively, just use rmap_len below
182096a14336SNikolay Borisov 		 * instead of map->stripe_len
182196a14336SNikolay Borisov 		 */
182296a14336SNikolay Borisov 
1823138082f3SNaohiro Aota 		bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
18241776ad17SNikolay Borisov 
18251776ad17SNikolay Borisov 		/* Ensure we don't add duplicate addresses */
182696a14336SNikolay Borisov 		for (j = 0; j < nr; j++) {
18271776ad17SNikolay Borisov 			if (buf[j] == bytenr) {
18281776ad17SNikolay Borisov 				already_inserted = true;
182996a14336SNikolay Borisov 				break;
183096a14336SNikolay Borisov 			}
183196a14336SNikolay Borisov 		}
18321776ad17SNikolay Borisov 
18331776ad17SNikolay Borisov 		if (!already_inserted)
18341776ad17SNikolay Borisov 			buf[nr++] = bytenr;
183596a14336SNikolay Borisov 	}
183696a14336SNikolay Borisov 
183796a14336SNikolay Borisov 	*logical = buf;
183896a14336SNikolay Borisov 	*naddrs = nr;
18391776ad17SNikolay Borisov 	*stripe_len = io_stripe_size;
18401776ad17SNikolay Borisov out:
184196a14336SNikolay Borisov 	free_extent_map(em);
18421776ad17SNikolay Borisov 	return ret;
184396a14336SNikolay Borisov }
184496a14336SNikolay Borisov 
184532da5386SDavid Sterba static int exclude_super_stripes(struct btrfs_block_group *cache)
18464358d963SJosef Bacik {
18474358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
184812659251SNaohiro Aota 	const bool zoned = btrfs_is_zoned(fs_info);
18494358d963SJosef Bacik 	u64 bytenr;
18504358d963SJosef Bacik 	u64 *logical;
18514358d963SJosef Bacik 	int stripe_len;
18524358d963SJosef Bacik 	int i, nr, ret;
18534358d963SJosef Bacik 
1854b3470b5dSDavid Sterba 	if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1855b3470b5dSDavid Sterba 		stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
18564358d963SJosef Bacik 		cache->bytes_super += stripe_len;
1857b3470b5dSDavid Sterba 		ret = btrfs_add_excluded_extent(fs_info, cache->start,
18584358d963SJosef Bacik 						stripe_len);
18594358d963SJosef Bacik 		if (ret)
18604358d963SJosef Bacik 			return ret;
18614358d963SJosef Bacik 	}
18624358d963SJosef Bacik 
18634358d963SJosef Bacik 	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
18644358d963SJosef Bacik 		bytenr = btrfs_sb_offset(i);
1865138082f3SNaohiro Aota 		ret = btrfs_rmap_block(fs_info, cache->start, NULL,
18664358d963SJosef Bacik 				       bytenr, &logical, &nr, &stripe_len);
18674358d963SJosef Bacik 		if (ret)
18684358d963SJosef Bacik 			return ret;
18694358d963SJosef Bacik 
187012659251SNaohiro Aota 		/* Shouldn't have super stripes in sequential zones */
187112659251SNaohiro Aota 		if (zoned && nr) {
187212659251SNaohiro Aota 			btrfs_err(fs_info,
187312659251SNaohiro Aota 			"zoned: block group %llu must not contain super block",
187412659251SNaohiro Aota 				  cache->start);
187512659251SNaohiro Aota 			return -EUCLEAN;
187612659251SNaohiro Aota 		}
187712659251SNaohiro Aota 
18784358d963SJosef Bacik 		while (nr--) {
187996f9b0f2SNikolay Borisov 			u64 len = min_t(u64, stripe_len,
188096f9b0f2SNikolay Borisov 				cache->start + cache->length - logical[nr]);
18814358d963SJosef Bacik 
18824358d963SJosef Bacik 			cache->bytes_super += len;
188396f9b0f2SNikolay Borisov 			ret = btrfs_add_excluded_extent(fs_info, logical[nr],
188496f9b0f2SNikolay Borisov 							len);
18854358d963SJosef Bacik 			if (ret) {
18864358d963SJosef Bacik 				kfree(logical);
18874358d963SJosef Bacik 				return ret;
18884358d963SJosef Bacik 			}
18894358d963SJosef Bacik 		}
18904358d963SJosef Bacik 
18914358d963SJosef Bacik 		kfree(logical);
18924358d963SJosef Bacik 	}
18934358d963SJosef Bacik 	return 0;
18944358d963SJosef Bacik }
18954358d963SJosef Bacik 
189632da5386SDavid Sterba static void link_block_group(struct btrfs_block_group *cache)
18974358d963SJosef Bacik {
18984358d963SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
18994358d963SJosef Bacik 	int index = btrfs_bg_flags_to_raid_index(cache->flags);
19004358d963SJosef Bacik 
19014358d963SJosef Bacik 	down_write(&space_info->groups_sem);
19024358d963SJosef Bacik 	list_add_tail(&cache->list, &space_info->block_groups[index]);
19034358d963SJosef Bacik 	up_write(&space_info->groups_sem);
19044358d963SJosef Bacik }
19054358d963SJosef Bacik 
190632da5386SDavid Sterba static struct btrfs_block_group *btrfs_create_block_group_cache(
19079afc6649SQu Wenruo 		struct btrfs_fs_info *fs_info, u64 start)
19084358d963SJosef Bacik {
190932da5386SDavid Sterba 	struct btrfs_block_group *cache;
19104358d963SJosef Bacik 
19114358d963SJosef Bacik 	cache = kzalloc(sizeof(*cache), GFP_NOFS);
19124358d963SJosef Bacik 	if (!cache)
19134358d963SJosef Bacik 		return NULL;
19144358d963SJosef Bacik 
19154358d963SJosef Bacik 	cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
19164358d963SJosef Bacik 					GFP_NOFS);
19174358d963SJosef Bacik 	if (!cache->free_space_ctl) {
19184358d963SJosef Bacik 		kfree(cache);
19194358d963SJosef Bacik 		return NULL;
19204358d963SJosef Bacik 	}
19214358d963SJosef Bacik 
1922b3470b5dSDavid Sterba 	cache->start = start;
19234358d963SJosef Bacik 
19244358d963SJosef Bacik 	cache->fs_info = fs_info;
19254358d963SJosef Bacik 	cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
19264358d963SJosef Bacik 
19276e80d4f8SDennis Zhou 	cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
19286e80d4f8SDennis Zhou 
192948aaeebeSJosef Bacik 	refcount_set(&cache->refs, 1);
19304358d963SJosef Bacik 	spin_lock_init(&cache->lock);
19314358d963SJosef Bacik 	init_rwsem(&cache->data_rwsem);
19324358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->list);
19334358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->cluster_list);
19344358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->bg_list);
19354358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->ro_list);
1936b0643e59SDennis Zhou 	INIT_LIST_HEAD(&cache->discard_list);
19374358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->dirty_list);
19384358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->io_list);
1939afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&cache->active_bg_list);
1940cd79909bSJosef Bacik 	btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
19416b7304afSFilipe Manana 	atomic_set(&cache->frozen, 0);
19424358d963SJosef Bacik 	mutex_init(&cache->free_space_lock);
19434358d963SJosef Bacik 	btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
19444358d963SJosef Bacik 
19454358d963SJosef Bacik 	return cache;
19464358d963SJosef Bacik }
19474358d963SJosef Bacik 
19484358d963SJosef Bacik /*
19494358d963SJosef Bacik  * Iterate all chunks and verify that each of them has the corresponding block
19504358d963SJosef Bacik  * group
19514358d963SJosef Bacik  */
19524358d963SJosef Bacik static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
19534358d963SJosef Bacik {
19544358d963SJosef Bacik 	struct extent_map_tree *map_tree = &fs_info->mapping_tree;
19554358d963SJosef Bacik 	struct extent_map *em;
195632da5386SDavid Sterba 	struct btrfs_block_group *bg;
19574358d963SJosef Bacik 	u64 start = 0;
19584358d963SJosef Bacik 	int ret = 0;
19594358d963SJosef Bacik 
19604358d963SJosef Bacik 	while (1) {
19614358d963SJosef Bacik 		read_lock(&map_tree->lock);
19624358d963SJosef Bacik 		/*
19634358d963SJosef Bacik 		 * lookup_extent_mapping will return the first extent map
19644358d963SJosef Bacik 		 * intersecting the range, so setting @len to 1 is enough to
19654358d963SJosef Bacik 		 * get the first chunk.
19664358d963SJosef Bacik 		 */
19674358d963SJosef Bacik 		em = lookup_extent_mapping(map_tree, start, 1);
19684358d963SJosef Bacik 		read_unlock(&map_tree->lock);
19694358d963SJosef Bacik 		if (!em)
19704358d963SJosef Bacik 			break;
19714358d963SJosef Bacik 
19724358d963SJosef Bacik 		bg = btrfs_lookup_block_group(fs_info, em->start);
19734358d963SJosef Bacik 		if (!bg) {
19744358d963SJosef Bacik 			btrfs_err(fs_info,
19754358d963SJosef Bacik 	"chunk start=%llu len=%llu doesn't have corresponding block group",
19764358d963SJosef Bacik 				     em->start, em->len);
19774358d963SJosef Bacik 			ret = -EUCLEAN;
19784358d963SJosef Bacik 			free_extent_map(em);
19794358d963SJosef Bacik 			break;
19804358d963SJosef Bacik 		}
1981b3470b5dSDavid Sterba 		if (bg->start != em->start || bg->length != em->len ||
19824358d963SJosef Bacik 		    (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
19834358d963SJosef Bacik 		    (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
19844358d963SJosef Bacik 			btrfs_err(fs_info,
19854358d963SJosef Bacik "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
19864358d963SJosef Bacik 				em->start, em->len,
19874358d963SJosef Bacik 				em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
1988b3470b5dSDavid Sterba 				bg->start, bg->length,
19894358d963SJosef Bacik 				bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
19904358d963SJosef Bacik 			ret = -EUCLEAN;
19914358d963SJosef Bacik 			free_extent_map(em);
19924358d963SJosef Bacik 			btrfs_put_block_group(bg);
19934358d963SJosef Bacik 			break;
19944358d963SJosef Bacik 		}
19954358d963SJosef Bacik 		start = em->start + em->len;
19964358d963SJosef Bacik 		free_extent_map(em);
19974358d963SJosef Bacik 		btrfs_put_block_group(bg);
19984358d963SJosef Bacik 	}
19994358d963SJosef Bacik 	return ret;
20004358d963SJosef Bacik }
20014358d963SJosef Bacik 
2002ffb9e0f0SQu Wenruo static int read_one_block_group(struct btrfs_fs_info *info,
20034afd2fe8SJohannes Thumshirn 				struct btrfs_block_group_item *bgi,
2004d49a2ddbSQu Wenruo 				const struct btrfs_key *key,
2005ffb9e0f0SQu Wenruo 				int need_clear)
2006ffb9e0f0SQu Wenruo {
200732da5386SDavid Sterba 	struct btrfs_block_group *cache;
2008ffb9e0f0SQu Wenruo 	struct btrfs_space_info *space_info;
2009ffb9e0f0SQu Wenruo 	const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
2010ffb9e0f0SQu Wenruo 	int ret;
2011ffb9e0f0SQu Wenruo 
2012d49a2ddbSQu Wenruo 	ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
2013ffb9e0f0SQu Wenruo 
20149afc6649SQu Wenruo 	cache = btrfs_create_block_group_cache(info, key->objectid);
2015ffb9e0f0SQu Wenruo 	if (!cache)
2016ffb9e0f0SQu Wenruo 		return -ENOMEM;
2017ffb9e0f0SQu Wenruo 
20184afd2fe8SJohannes Thumshirn 	cache->length = key->offset;
20194afd2fe8SJohannes Thumshirn 	cache->used = btrfs_stack_block_group_used(bgi);
20204afd2fe8SJohannes Thumshirn 	cache->flags = btrfs_stack_block_group_flags(bgi);
2021f7238e50SJosef Bacik 	cache->global_root_id = btrfs_stack_block_group_chunk_objectid(bgi);
20229afc6649SQu Wenruo 
2023e3e39c72SMarcos Paulo de Souza 	set_free_space_tree_thresholds(cache);
2024e3e39c72SMarcos Paulo de Souza 
2025ffb9e0f0SQu Wenruo 	if (need_clear) {
2026ffb9e0f0SQu Wenruo 		/*
2027ffb9e0f0SQu Wenruo 		 * When we mount with old space cache, we need to
2028ffb9e0f0SQu Wenruo 		 * set BTRFS_DC_CLEAR and set dirty flag.
2029ffb9e0f0SQu Wenruo 		 *
2030ffb9e0f0SQu Wenruo 		 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
2031ffb9e0f0SQu Wenruo 		 *    truncate the old free space cache inode and
2032ffb9e0f0SQu Wenruo 		 *    setup a new one.
2033ffb9e0f0SQu Wenruo 		 * b) Setting 'dirty flag' makes sure that we flush
2034ffb9e0f0SQu Wenruo 		 *    the new space cache info onto disk.
2035ffb9e0f0SQu Wenruo 		 */
2036ffb9e0f0SQu Wenruo 		if (btrfs_test_opt(info, SPACE_CACHE))
2037ffb9e0f0SQu Wenruo 			cache->disk_cache_state = BTRFS_DC_CLEAR;
2038ffb9e0f0SQu Wenruo 	}
2039ffb9e0f0SQu Wenruo 	if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
2040ffb9e0f0SQu Wenruo 	    (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
2041ffb9e0f0SQu Wenruo 			btrfs_err(info,
2042ffb9e0f0SQu Wenruo "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2043ffb9e0f0SQu Wenruo 				  cache->start);
2044ffb9e0f0SQu Wenruo 			ret = -EINVAL;
2045ffb9e0f0SQu Wenruo 			goto error;
2046ffb9e0f0SQu Wenruo 	}
2047ffb9e0f0SQu Wenruo 
2048a94794d5SNaohiro Aota 	ret = btrfs_load_block_group_zone_info(cache, false);
204908e11a3dSNaohiro Aota 	if (ret) {
205008e11a3dSNaohiro Aota 		btrfs_err(info, "zoned: failed to load zone info of bg %llu",
205108e11a3dSNaohiro Aota 			  cache->start);
205208e11a3dSNaohiro Aota 		goto error;
205308e11a3dSNaohiro Aota 	}
205408e11a3dSNaohiro Aota 
2055ffb9e0f0SQu Wenruo 	/*
2056ffb9e0f0SQu Wenruo 	 * We need to exclude the super stripes now so that the space info has
2057ffb9e0f0SQu Wenruo 	 * super bytes accounted for, otherwise we'll think we have more space
2058ffb9e0f0SQu Wenruo 	 * than we actually do.
2059ffb9e0f0SQu Wenruo 	 */
2060ffb9e0f0SQu Wenruo 	ret = exclude_super_stripes(cache);
2061ffb9e0f0SQu Wenruo 	if (ret) {
2062ffb9e0f0SQu Wenruo 		/* We may have excluded something, so call this just in case. */
2063ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2064ffb9e0f0SQu Wenruo 		goto error;
2065ffb9e0f0SQu Wenruo 	}
2066ffb9e0f0SQu Wenruo 
2067ffb9e0f0SQu Wenruo 	/*
2068169e0da9SNaohiro Aota 	 * For zoned filesystem, space after the allocation offset is the only
2069169e0da9SNaohiro Aota 	 * free space for a block group. So, we don't need any caching work.
2070169e0da9SNaohiro Aota 	 * btrfs_calc_zone_unusable() will set the amount of free space and
2071169e0da9SNaohiro Aota 	 * zone_unusable space.
2072169e0da9SNaohiro Aota 	 *
2073169e0da9SNaohiro Aota 	 * For regular filesystem, check for two cases, either we are full, and
2074169e0da9SNaohiro Aota 	 * therefore don't need to bother with the caching work since we won't
2075169e0da9SNaohiro Aota 	 * find any space, or we are empty, and we can just add all the space
2076169e0da9SNaohiro Aota 	 * in and be done with it.  This saves us _a_lot_ of time, particularly
2077169e0da9SNaohiro Aota 	 * in the full case.
2078ffb9e0f0SQu Wenruo 	 */
2079169e0da9SNaohiro Aota 	if (btrfs_is_zoned(info)) {
2080169e0da9SNaohiro Aota 		btrfs_calc_zone_unusable(cache);
2081c46c4247SNaohiro Aota 		/* Should not have any excluded extents. Just in case, though. */
2082c46c4247SNaohiro Aota 		btrfs_free_excluded_extents(cache);
2083169e0da9SNaohiro Aota 	} else if (cache->length == cache->used) {
2084ffb9e0f0SQu Wenruo 		cache->last_byte_to_unpin = (u64)-1;
2085ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
2086ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2087ffb9e0f0SQu Wenruo 	} else if (cache->used == 0) {
2088ffb9e0f0SQu Wenruo 		cache->last_byte_to_unpin = (u64)-1;
2089ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
20909afc6649SQu Wenruo 		add_new_free_space(cache, cache->start,
20919afc6649SQu Wenruo 				   cache->start + cache->length);
2092ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
2093ffb9e0f0SQu Wenruo 	}
2094ffb9e0f0SQu Wenruo 
2095ffb9e0f0SQu Wenruo 	ret = btrfs_add_block_group_cache(info, cache);
2096ffb9e0f0SQu Wenruo 	if (ret) {
2097ffb9e0f0SQu Wenruo 		btrfs_remove_free_space_cache(cache);
2098ffb9e0f0SQu Wenruo 		goto error;
2099ffb9e0f0SQu Wenruo 	}
2100ffb9e0f0SQu Wenruo 	trace_btrfs_add_block_group(info, cache, 0);
21019afc6649SQu Wenruo 	btrfs_update_space_info(info, cache->flags, cache->length,
2102169e0da9SNaohiro Aota 				cache->used, cache->bytes_super,
2103169e0da9SNaohiro Aota 				cache->zone_unusable, &space_info);
2104ffb9e0f0SQu Wenruo 
2105ffb9e0f0SQu Wenruo 	cache->space_info = space_info;
2106ffb9e0f0SQu Wenruo 
2107ffb9e0f0SQu Wenruo 	link_block_group(cache);
2108ffb9e0f0SQu Wenruo 
2109ffb9e0f0SQu Wenruo 	set_avail_alloc_bits(info, cache->flags);
2110a09f23c3SAnand Jain 	if (btrfs_chunk_writeable(info, cache->start)) {
2111a09f23c3SAnand Jain 		if (cache->used == 0) {
2112ffb9e0f0SQu Wenruo 			ASSERT(list_empty(&cache->bg_list));
21136e80d4f8SDennis Zhou 			if (btrfs_test_opt(info, DISCARD_ASYNC))
21146e80d4f8SDennis Zhou 				btrfs_discard_queue_work(&info->discard_ctl, cache);
21156e80d4f8SDennis Zhou 			else
2116ffb9e0f0SQu Wenruo 				btrfs_mark_bg_unused(cache);
2117ffb9e0f0SQu Wenruo 		}
2118a09f23c3SAnand Jain 	} else {
2119a09f23c3SAnand Jain 		inc_block_group_ro(cache, 1);
2120a09f23c3SAnand Jain 	}
2121a09f23c3SAnand Jain 
2122ffb9e0f0SQu Wenruo 	return 0;
2123ffb9e0f0SQu Wenruo error:
2124ffb9e0f0SQu Wenruo 	btrfs_put_block_group(cache);
2125ffb9e0f0SQu Wenruo 	return ret;
2126ffb9e0f0SQu Wenruo }
2127ffb9e0f0SQu Wenruo 
212842437a63SJosef Bacik static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
212942437a63SJosef Bacik {
213042437a63SJosef Bacik 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
213142437a63SJosef Bacik 	struct btrfs_space_info *space_info;
213242437a63SJosef Bacik 	struct rb_node *node;
213342437a63SJosef Bacik 	int ret = 0;
213442437a63SJosef Bacik 
213542437a63SJosef Bacik 	for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
213642437a63SJosef Bacik 		struct extent_map *em;
213742437a63SJosef Bacik 		struct map_lookup *map;
213842437a63SJosef Bacik 		struct btrfs_block_group *bg;
213942437a63SJosef Bacik 
214042437a63SJosef Bacik 		em = rb_entry(node, struct extent_map, rb_node);
214142437a63SJosef Bacik 		map = em->map_lookup;
214242437a63SJosef Bacik 		bg = btrfs_create_block_group_cache(fs_info, em->start);
214342437a63SJosef Bacik 		if (!bg) {
214442437a63SJosef Bacik 			ret = -ENOMEM;
214542437a63SJosef Bacik 			break;
214642437a63SJosef Bacik 		}
214742437a63SJosef Bacik 
214842437a63SJosef Bacik 		/* Fill dummy cache as FULL */
214942437a63SJosef Bacik 		bg->length = em->len;
215042437a63SJosef Bacik 		bg->flags = map->type;
215142437a63SJosef Bacik 		bg->last_byte_to_unpin = (u64)-1;
215242437a63SJosef Bacik 		bg->cached = BTRFS_CACHE_FINISHED;
215342437a63SJosef Bacik 		bg->used = em->len;
215442437a63SJosef Bacik 		bg->flags = map->type;
215542437a63SJosef Bacik 		ret = btrfs_add_block_group_cache(fs_info, bg);
21562b29726cSQu Wenruo 		/*
21572b29726cSQu Wenruo 		 * We may have some valid block group cache added already, in
21582b29726cSQu Wenruo 		 * that case we skip to the next one.
21592b29726cSQu Wenruo 		 */
21602b29726cSQu Wenruo 		if (ret == -EEXIST) {
21612b29726cSQu Wenruo 			ret = 0;
21622b29726cSQu Wenruo 			btrfs_put_block_group(bg);
21632b29726cSQu Wenruo 			continue;
21642b29726cSQu Wenruo 		}
21652b29726cSQu Wenruo 
216642437a63SJosef Bacik 		if (ret) {
216742437a63SJosef Bacik 			btrfs_remove_free_space_cache(bg);
216842437a63SJosef Bacik 			btrfs_put_block_group(bg);
216942437a63SJosef Bacik 			break;
217042437a63SJosef Bacik 		}
21712b29726cSQu Wenruo 
217242437a63SJosef Bacik 		btrfs_update_space_info(fs_info, bg->flags, em->len, em->len,
2173169e0da9SNaohiro Aota 					0, 0, &space_info);
217442437a63SJosef Bacik 		bg->space_info = space_info;
217542437a63SJosef Bacik 		link_block_group(bg);
217642437a63SJosef Bacik 
217742437a63SJosef Bacik 		set_avail_alloc_bits(fs_info, bg->flags);
217842437a63SJosef Bacik 	}
217942437a63SJosef Bacik 	if (!ret)
218042437a63SJosef Bacik 		btrfs_init_global_block_rsv(fs_info);
218142437a63SJosef Bacik 	return ret;
218242437a63SJosef Bacik }
218342437a63SJosef Bacik 
21844358d963SJosef Bacik int btrfs_read_block_groups(struct btrfs_fs_info *info)
21854358d963SJosef Bacik {
2186dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(info);
21874358d963SJosef Bacik 	struct btrfs_path *path;
21884358d963SJosef Bacik 	int ret;
218932da5386SDavid Sterba 	struct btrfs_block_group *cache;
21904358d963SJosef Bacik 	struct btrfs_space_info *space_info;
21914358d963SJosef Bacik 	struct btrfs_key key;
21924358d963SJosef Bacik 	int need_clear = 0;
21934358d963SJosef Bacik 	u64 cache_gen;
21944358d963SJosef Bacik 
2195dfe8aec4SJosef Bacik 	if (!root)
219642437a63SJosef Bacik 		return fill_dummy_bgs(info);
219742437a63SJosef Bacik 
21984358d963SJosef Bacik 	key.objectid = 0;
21994358d963SJosef Bacik 	key.offset = 0;
22004358d963SJosef Bacik 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
22014358d963SJosef Bacik 	path = btrfs_alloc_path();
22024358d963SJosef Bacik 	if (!path)
22034358d963SJosef Bacik 		return -ENOMEM;
22044358d963SJosef Bacik 
22054358d963SJosef Bacik 	cache_gen = btrfs_super_cache_generation(info->super_copy);
22064358d963SJosef Bacik 	if (btrfs_test_opt(info, SPACE_CACHE) &&
22074358d963SJosef Bacik 	    btrfs_super_generation(info->super_copy) != cache_gen)
22084358d963SJosef Bacik 		need_clear = 1;
22094358d963SJosef Bacik 	if (btrfs_test_opt(info, CLEAR_CACHE))
22104358d963SJosef Bacik 		need_clear = 1;
22114358d963SJosef Bacik 
22124358d963SJosef Bacik 	while (1) {
22134afd2fe8SJohannes Thumshirn 		struct btrfs_block_group_item bgi;
22144afd2fe8SJohannes Thumshirn 		struct extent_buffer *leaf;
22154afd2fe8SJohannes Thumshirn 		int slot;
22164afd2fe8SJohannes Thumshirn 
22174358d963SJosef Bacik 		ret = find_first_block_group(info, path, &key);
22184358d963SJosef Bacik 		if (ret > 0)
22194358d963SJosef Bacik 			break;
22204358d963SJosef Bacik 		if (ret != 0)
22214358d963SJosef Bacik 			goto error;
22224358d963SJosef Bacik 
22234afd2fe8SJohannes Thumshirn 		leaf = path->nodes[0];
22244afd2fe8SJohannes Thumshirn 		slot = path->slots[0];
22254afd2fe8SJohannes Thumshirn 
22264afd2fe8SJohannes Thumshirn 		read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
22274afd2fe8SJohannes Thumshirn 				   sizeof(bgi));
22284afd2fe8SJohannes Thumshirn 
22294afd2fe8SJohannes Thumshirn 		btrfs_item_key_to_cpu(leaf, &key, slot);
22304afd2fe8SJohannes Thumshirn 		btrfs_release_path(path);
22314afd2fe8SJohannes Thumshirn 		ret = read_one_block_group(info, &bgi, &key, need_clear);
2232ffb9e0f0SQu Wenruo 		if (ret < 0)
22334358d963SJosef Bacik 			goto error;
2234ffb9e0f0SQu Wenruo 		key.objectid += key.offset;
2235ffb9e0f0SQu Wenruo 		key.offset = 0;
22364358d963SJosef Bacik 	}
22377837fa88SJosef Bacik 	btrfs_release_path(path);
22384358d963SJosef Bacik 
223972804905SJosef Bacik 	list_for_each_entry(space_info, &info->space_info, list) {
224049ea112dSJosef Bacik 		int i;
224149ea112dSJosef Bacik 
224249ea112dSJosef Bacik 		for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
224349ea112dSJosef Bacik 			if (list_empty(&space_info->block_groups[i]))
224449ea112dSJosef Bacik 				continue;
224549ea112dSJosef Bacik 			cache = list_first_entry(&space_info->block_groups[i],
224649ea112dSJosef Bacik 						 struct btrfs_block_group,
224749ea112dSJosef Bacik 						 list);
224849ea112dSJosef Bacik 			btrfs_sysfs_add_block_group_type(cache);
224949ea112dSJosef Bacik 		}
225049ea112dSJosef Bacik 
22514358d963SJosef Bacik 		if (!(btrfs_get_alloc_profile(info, space_info->flags) &
22524358d963SJosef Bacik 		      (BTRFS_BLOCK_GROUP_RAID10 |
22534358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID1_MASK |
22544358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID56_MASK |
22554358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_DUP)))
22564358d963SJosef Bacik 			continue;
22574358d963SJosef Bacik 		/*
22584358d963SJosef Bacik 		 * Avoid allocating from un-mirrored block group if there are
22594358d963SJosef Bacik 		 * mirrored block groups.
22604358d963SJosef Bacik 		 */
22614358d963SJosef Bacik 		list_for_each_entry(cache,
22624358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_RAID0],
22634358d963SJosef Bacik 				list)
2264e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
22654358d963SJosef Bacik 		list_for_each_entry(cache,
22664358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_SINGLE],
22674358d963SJosef Bacik 				list)
2268e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
22694358d963SJosef Bacik 	}
22704358d963SJosef Bacik 
22714358d963SJosef Bacik 	btrfs_init_global_block_rsv(info);
22724358d963SJosef Bacik 	ret = check_chunk_block_group_mappings(info);
22734358d963SJosef Bacik error:
22744358d963SJosef Bacik 	btrfs_free_path(path);
22752b29726cSQu Wenruo 	/*
22762b29726cSQu Wenruo 	 * We've hit some error while reading the extent tree, and have
22772b29726cSQu Wenruo 	 * rescue=ibadroots mount option.
22782b29726cSQu Wenruo 	 * Try to fill the tree using dummy block groups so that the user can
22792b29726cSQu Wenruo 	 * continue to mount and grab their data.
22802b29726cSQu Wenruo 	 */
22812b29726cSQu Wenruo 	if (ret && btrfs_test_opt(info, IGNOREBADROOTS))
22822b29726cSQu Wenruo 		ret = fill_dummy_bgs(info);
22834358d963SJosef Bacik 	return ret;
22844358d963SJosef Bacik }
22854358d963SJosef Bacik 
228679bd3712SFilipe Manana /*
228779bd3712SFilipe Manana  * This function, insert_block_group_item(), belongs to the phase 2 of chunk
228879bd3712SFilipe Manana  * allocation.
228979bd3712SFilipe Manana  *
229079bd3712SFilipe Manana  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
229179bd3712SFilipe Manana  * phases.
229279bd3712SFilipe Manana  */
229397f4728aSQu Wenruo static int insert_block_group_item(struct btrfs_trans_handle *trans,
229497f4728aSQu Wenruo 				   struct btrfs_block_group *block_group)
229597f4728aSQu Wenruo {
229697f4728aSQu Wenruo 	struct btrfs_fs_info *fs_info = trans->fs_info;
229797f4728aSQu Wenruo 	struct btrfs_block_group_item bgi;
2298dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
229997f4728aSQu Wenruo 	struct btrfs_key key;
230097f4728aSQu Wenruo 
230197f4728aSQu Wenruo 	spin_lock(&block_group->lock);
230297f4728aSQu Wenruo 	btrfs_set_stack_block_group_used(&bgi, block_group->used);
230397f4728aSQu Wenruo 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
2304f7238e50SJosef Bacik 						   block_group->global_root_id);
230597f4728aSQu Wenruo 	btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
230697f4728aSQu Wenruo 	key.objectid = block_group->start;
230797f4728aSQu Wenruo 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
230897f4728aSQu Wenruo 	key.offset = block_group->length;
230997f4728aSQu Wenruo 	spin_unlock(&block_group->lock);
231097f4728aSQu Wenruo 
231197f4728aSQu Wenruo 	return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
231297f4728aSQu Wenruo }
231397f4728aSQu Wenruo 
23142eadb9e7SNikolay Borisov static int insert_dev_extent(struct btrfs_trans_handle *trans,
23152eadb9e7SNikolay Borisov 			    struct btrfs_device *device, u64 chunk_offset,
23162eadb9e7SNikolay Borisov 			    u64 start, u64 num_bytes)
23172eadb9e7SNikolay Borisov {
23182eadb9e7SNikolay Borisov 	struct btrfs_fs_info *fs_info = device->fs_info;
23192eadb9e7SNikolay Borisov 	struct btrfs_root *root = fs_info->dev_root;
23202eadb9e7SNikolay Borisov 	struct btrfs_path *path;
23212eadb9e7SNikolay Borisov 	struct btrfs_dev_extent *extent;
23222eadb9e7SNikolay Borisov 	struct extent_buffer *leaf;
23232eadb9e7SNikolay Borisov 	struct btrfs_key key;
23242eadb9e7SNikolay Borisov 	int ret;
23252eadb9e7SNikolay Borisov 
23262eadb9e7SNikolay Borisov 	WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
23272eadb9e7SNikolay Borisov 	WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
23282eadb9e7SNikolay Borisov 	path = btrfs_alloc_path();
23292eadb9e7SNikolay Borisov 	if (!path)
23302eadb9e7SNikolay Borisov 		return -ENOMEM;
23312eadb9e7SNikolay Borisov 
23322eadb9e7SNikolay Borisov 	key.objectid = device->devid;
23332eadb9e7SNikolay Borisov 	key.type = BTRFS_DEV_EXTENT_KEY;
23342eadb9e7SNikolay Borisov 	key.offset = start;
23352eadb9e7SNikolay Borisov 	ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent));
23362eadb9e7SNikolay Borisov 	if (ret)
23372eadb9e7SNikolay Borisov 		goto out;
23382eadb9e7SNikolay Borisov 
23392eadb9e7SNikolay Borisov 	leaf = path->nodes[0];
23402eadb9e7SNikolay Borisov 	extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
23412eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID);
23422eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_objectid(leaf, extent,
23432eadb9e7SNikolay Borisov 					    BTRFS_FIRST_CHUNK_TREE_OBJECTID);
23442eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
23452eadb9e7SNikolay Borisov 
23462eadb9e7SNikolay Borisov 	btrfs_set_dev_extent_length(leaf, extent, num_bytes);
23472eadb9e7SNikolay Borisov 	btrfs_mark_buffer_dirty(leaf);
23482eadb9e7SNikolay Borisov out:
23492eadb9e7SNikolay Borisov 	btrfs_free_path(path);
23502eadb9e7SNikolay Borisov 	return ret;
23512eadb9e7SNikolay Borisov }
23522eadb9e7SNikolay Borisov 
23532eadb9e7SNikolay Borisov /*
23542eadb9e7SNikolay Borisov  * This function belongs to phase 2.
23552eadb9e7SNikolay Borisov  *
23562eadb9e7SNikolay Borisov  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
23572eadb9e7SNikolay Borisov  * phases.
23582eadb9e7SNikolay Borisov  */
23592eadb9e7SNikolay Borisov static int insert_dev_extents(struct btrfs_trans_handle *trans,
23602eadb9e7SNikolay Borisov 				   u64 chunk_offset, u64 chunk_size)
23612eadb9e7SNikolay Borisov {
23622eadb9e7SNikolay Borisov 	struct btrfs_fs_info *fs_info = trans->fs_info;
23632eadb9e7SNikolay Borisov 	struct btrfs_device *device;
23642eadb9e7SNikolay Borisov 	struct extent_map *em;
23652eadb9e7SNikolay Borisov 	struct map_lookup *map;
23662eadb9e7SNikolay Borisov 	u64 dev_offset;
23672eadb9e7SNikolay Borisov 	u64 stripe_size;
23682eadb9e7SNikolay Borisov 	int i;
23692eadb9e7SNikolay Borisov 	int ret = 0;
23702eadb9e7SNikolay Borisov 
23712eadb9e7SNikolay Borisov 	em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
23722eadb9e7SNikolay Borisov 	if (IS_ERR(em))
23732eadb9e7SNikolay Borisov 		return PTR_ERR(em);
23742eadb9e7SNikolay Borisov 
23752eadb9e7SNikolay Borisov 	map = em->map_lookup;
23762eadb9e7SNikolay Borisov 	stripe_size = em->orig_block_len;
23772eadb9e7SNikolay Borisov 
23782eadb9e7SNikolay Borisov 	/*
23792eadb9e7SNikolay Borisov 	 * Take the device list mutex to prevent races with the final phase of
23802eadb9e7SNikolay Borisov 	 * a device replace operation that replaces the device object associated
23812eadb9e7SNikolay Borisov 	 * with the map's stripes, because the device object's id can change
23822eadb9e7SNikolay Borisov 	 * at any time during that final phase of the device replace operation
23832eadb9e7SNikolay Borisov 	 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
23842eadb9e7SNikolay Borisov 	 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
23852eadb9e7SNikolay Borisov 	 * resulting in persisting a device extent item with such ID.
23862eadb9e7SNikolay Borisov 	 */
23872eadb9e7SNikolay Borisov 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
23882eadb9e7SNikolay Borisov 	for (i = 0; i < map->num_stripes; i++) {
23892eadb9e7SNikolay Borisov 		device = map->stripes[i].dev;
23902eadb9e7SNikolay Borisov 		dev_offset = map->stripes[i].physical;
23912eadb9e7SNikolay Borisov 
23922eadb9e7SNikolay Borisov 		ret = insert_dev_extent(trans, device, chunk_offset, dev_offset,
23932eadb9e7SNikolay Borisov 				       stripe_size);
23942eadb9e7SNikolay Borisov 		if (ret)
23952eadb9e7SNikolay Borisov 			break;
23962eadb9e7SNikolay Borisov 	}
23972eadb9e7SNikolay Borisov 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
23982eadb9e7SNikolay Borisov 
23992eadb9e7SNikolay Borisov 	free_extent_map(em);
24002eadb9e7SNikolay Borisov 	return ret;
24012eadb9e7SNikolay Borisov }
24022eadb9e7SNikolay Borisov 
240379bd3712SFilipe Manana /*
240479bd3712SFilipe Manana  * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
240579bd3712SFilipe Manana  * chunk allocation.
240679bd3712SFilipe Manana  *
240779bd3712SFilipe Manana  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
240879bd3712SFilipe Manana  * phases.
240979bd3712SFilipe Manana  */
24104358d963SJosef Bacik void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
24114358d963SJosef Bacik {
24124358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
241332da5386SDavid Sterba 	struct btrfs_block_group *block_group;
24144358d963SJosef Bacik 	int ret = 0;
24154358d963SJosef Bacik 
24164358d963SJosef Bacik 	while (!list_empty(&trans->new_bgs)) {
241749ea112dSJosef Bacik 		int index;
241849ea112dSJosef Bacik 
24194358d963SJosef Bacik 		block_group = list_first_entry(&trans->new_bgs,
242032da5386SDavid Sterba 					       struct btrfs_block_group,
24214358d963SJosef Bacik 					       bg_list);
24224358d963SJosef Bacik 		if (ret)
24234358d963SJosef Bacik 			goto next;
24244358d963SJosef Bacik 
242549ea112dSJosef Bacik 		index = btrfs_bg_flags_to_raid_index(block_group->flags);
242649ea112dSJosef Bacik 
242797f4728aSQu Wenruo 		ret = insert_block_group_item(trans, block_group);
24284358d963SJosef Bacik 		if (ret)
24294358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
243079bd3712SFilipe Manana 		if (!block_group->chunk_item_inserted) {
243179bd3712SFilipe Manana 			mutex_lock(&fs_info->chunk_mutex);
243279bd3712SFilipe Manana 			ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group);
243379bd3712SFilipe Manana 			mutex_unlock(&fs_info->chunk_mutex);
243479bd3712SFilipe Manana 			if (ret)
243579bd3712SFilipe Manana 				btrfs_abort_transaction(trans, ret);
243679bd3712SFilipe Manana 		}
24372eadb9e7SNikolay Borisov 		ret = insert_dev_extents(trans, block_group->start,
243897f4728aSQu Wenruo 					 block_group->length);
24394358d963SJosef Bacik 		if (ret)
24404358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
24414358d963SJosef Bacik 		add_block_group_free_space(trans, block_group);
244249ea112dSJosef Bacik 
244349ea112dSJosef Bacik 		/*
244449ea112dSJosef Bacik 		 * If we restriped during balance, we may have added a new raid
244549ea112dSJosef Bacik 		 * type, so now add the sysfs entries when it is safe to do so.
244649ea112dSJosef Bacik 		 * We don't have to worry about locking here as it's handled in
244749ea112dSJosef Bacik 		 * btrfs_sysfs_add_block_group_type.
244849ea112dSJosef Bacik 		 */
244949ea112dSJosef Bacik 		if (block_group->space_info->block_group_kobjs[index] == NULL)
245049ea112dSJosef Bacik 			btrfs_sysfs_add_block_group_type(block_group);
245149ea112dSJosef Bacik 
24524358d963SJosef Bacik 		/* Already aborted the transaction if it failed. */
24534358d963SJosef Bacik next:
24544358d963SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
24554358d963SJosef Bacik 		list_del_init(&block_group->bg_list);
24564358d963SJosef Bacik 	}
24574358d963SJosef Bacik 	btrfs_trans_release_chunk_metadata(trans);
24584358d963SJosef Bacik }
24594358d963SJosef Bacik 
2460f7238e50SJosef Bacik /*
2461f7238e50SJosef Bacik  * For extent tree v2 we use the block_group_item->chunk_offset to point at our
2462f7238e50SJosef Bacik  * global root id.  For v1 it's always set to BTRFS_FIRST_CHUNK_TREE_OBJECTID.
2463f7238e50SJosef Bacik  */
2464f7238e50SJosef Bacik static u64 calculate_global_root_id(struct btrfs_fs_info *fs_info, u64 offset)
2465f7238e50SJosef Bacik {
2466f7238e50SJosef Bacik 	u64 div = SZ_1G;
2467f7238e50SJosef Bacik 	u64 index;
2468f7238e50SJosef Bacik 
2469f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2470f7238e50SJosef Bacik 		return BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2471f7238e50SJosef Bacik 
2472f7238e50SJosef Bacik 	/* If we have a smaller fs index based on 128MiB. */
2473f7238e50SJosef Bacik 	if (btrfs_super_total_bytes(fs_info->super_copy) <= (SZ_1G * 10ULL))
2474f7238e50SJosef Bacik 		div = SZ_128M;
2475f7238e50SJosef Bacik 
2476f7238e50SJosef Bacik 	offset = div64_u64(offset, div);
2477f7238e50SJosef Bacik 	div64_u64_rem(offset, fs_info->nr_global_roots, &index);
2478f7238e50SJosef Bacik 	return index;
2479f7238e50SJosef Bacik }
2480f7238e50SJosef Bacik 
248179bd3712SFilipe Manana struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
248279bd3712SFilipe Manana 						 u64 bytes_used, u64 type,
248379bd3712SFilipe Manana 						 u64 chunk_offset, u64 size)
24844358d963SJosef Bacik {
24854358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
248632da5386SDavid Sterba 	struct btrfs_block_group *cache;
24874358d963SJosef Bacik 	int ret;
24884358d963SJosef Bacik 
24894358d963SJosef Bacik 	btrfs_set_log_full_commit(trans);
24904358d963SJosef Bacik 
24919afc6649SQu Wenruo 	cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
24924358d963SJosef Bacik 	if (!cache)
249379bd3712SFilipe Manana 		return ERR_PTR(-ENOMEM);
24944358d963SJosef Bacik 
24959afc6649SQu Wenruo 	cache->length = size;
2496e3e39c72SMarcos Paulo de Souza 	set_free_space_tree_thresholds(cache);
2497bf38be65SDavid Sterba 	cache->used = bytes_used;
24984358d963SJosef Bacik 	cache->flags = type;
24994358d963SJosef Bacik 	cache->last_byte_to_unpin = (u64)-1;
25004358d963SJosef Bacik 	cache->cached = BTRFS_CACHE_FINISHED;
2501f7238e50SJosef Bacik 	cache->global_root_id = calculate_global_root_id(fs_info, cache->start);
2502f7238e50SJosef Bacik 
2503997e3e2eSBoris Burkov 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
25044358d963SJosef Bacik 		cache->needs_free_space = 1;
250508e11a3dSNaohiro Aota 
2506a94794d5SNaohiro Aota 	ret = btrfs_load_block_group_zone_info(cache, true);
250708e11a3dSNaohiro Aota 	if (ret) {
250808e11a3dSNaohiro Aota 		btrfs_put_block_group(cache);
250979bd3712SFilipe Manana 		return ERR_PTR(ret);
251008e11a3dSNaohiro Aota 	}
251108e11a3dSNaohiro Aota 
25124358d963SJosef Bacik 	ret = exclude_super_stripes(cache);
25134358d963SJosef Bacik 	if (ret) {
25144358d963SJosef Bacik 		/* We may have excluded something, so call this just in case */
25154358d963SJosef Bacik 		btrfs_free_excluded_extents(cache);
25164358d963SJosef Bacik 		btrfs_put_block_group(cache);
251779bd3712SFilipe Manana 		return ERR_PTR(ret);
25184358d963SJosef Bacik 	}
25194358d963SJosef Bacik 
25204358d963SJosef Bacik 	add_new_free_space(cache, chunk_offset, chunk_offset + size);
25214358d963SJosef Bacik 
25224358d963SJosef Bacik 	btrfs_free_excluded_extents(cache);
25234358d963SJosef Bacik 
25244358d963SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
25254358d963SJosef Bacik 	if (btrfs_should_fragment_free_space(cache)) {
25264358d963SJosef Bacik 		u64 new_bytes_used = size - bytes_used;
25274358d963SJosef Bacik 
25284358d963SJosef Bacik 		bytes_used += new_bytes_used >> 1;
2529e11c0406SJosef Bacik 		fragment_free_space(cache);
25304358d963SJosef Bacik 	}
25314358d963SJosef Bacik #endif
25324358d963SJosef Bacik 	/*
25334358d963SJosef Bacik 	 * Ensure the corresponding space_info object is created and
25344358d963SJosef Bacik 	 * assigned to our block group. We want our bg to be added to the rbtree
25354358d963SJosef Bacik 	 * with its ->space_info set.
25364358d963SJosef Bacik 	 */
25374358d963SJosef Bacik 	cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
25384358d963SJosef Bacik 	ASSERT(cache->space_info);
25394358d963SJosef Bacik 
25404358d963SJosef Bacik 	ret = btrfs_add_block_group_cache(fs_info, cache);
25414358d963SJosef Bacik 	if (ret) {
25424358d963SJosef Bacik 		btrfs_remove_free_space_cache(cache);
25434358d963SJosef Bacik 		btrfs_put_block_group(cache);
254479bd3712SFilipe Manana 		return ERR_PTR(ret);
25454358d963SJosef Bacik 	}
25464358d963SJosef Bacik 
25474358d963SJosef Bacik 	/*
25484358d963SJosef Bacik 	 * Now that our block group has its ->space_info set and is inserted in
25494358d963SJosef Bacik 	 * the rbtree, update the space info's counters.
25504358d963SJosef Bacik 	 */
25514358d963SJosef Bacik 	trace_btrfs_add_block_group(fs_info, cache, 1);
25524358d963SJosef Bacik 	btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
255398173255SNaohiro Aota 				cache->bytes_super, cache->zone_unusable,
255498173255SNaohiro Aota 				&cache->space_info);
25554358d963SJosef Bacik 	btrfs_update_global_block_rsv(fs_info);
25564358d963SJosef Bacik 
25574358d963SJosef Bacik 	link_block_group(cache);
25584358d963SJosef Bacik 
25594358d963SJosef Bacik 	list_add_tail(&cache->bg_list, &trans->new_bgs);
25604358d963SJosef Bacik 	trans->delayed_ref_updates++;
25614358d963SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
25624358d963SJosef Bacik 
25634358d963SJosef Bacik 	set_avail_alloc_bits(fs_info, type);
256479bd3712SFilipe Manana 	return cache;
25654358d963SJosef Bacik }
256626ce2095SJosef Bacik 
2567b12de528SQu Wenruo /*
2568b12de528SQu Wenruo  * Mark one block group RO, can be called several times for the same block
2569b12de528SQu Wenruo  * group.
2570b12de528SQu Wenruo  *
2571b12de528SQu Wenruo  * @cache:		the destination block group
2572b12de528SQu Wenruo  * @do_chunk_alloc:	whether need to do chunk pre-allocation, this is to
2573b12de528SQu Wenruo  * 			ensure we still have some free space after marking this
2574b12de528SQu Wenruo  * 			block group RO.
2575b12de528SQu Wenruo  */
2576b12de528SQu Wenruo int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2577b12de528SQu Wenruo 			     bool do_chunk_alloc)
257826ce2095SJosef Bacik {
257926ce2095SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
258026ce2095SJosef Bacik 	struct btrfs_trans_handle *trans;
2581dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
258226ce2095SJosef Bacik 	u64 alloc_flags;
258326ce2095SJosef Bacik 	int ret;
2584b6e9f16cSNikolay Borisov 	bool dirty_bg_running;
258526ce2095SJosef Bacik 
25862d192fc4SQu Wenruo 	/*
25872d192fc4SQu Wenruo 	 * This can only happen when we are doing read-only scrub on read-only
25882d192fc4SQu Wenruo 	 * mount.
25892d192fc4SQu Wenruo 	 * In that case we should not start a new transaction on read-only fs.
25902d192fc4SQu Wenruo 	 * Thus here we skip all chunk allocations.
25912d192fc4SQu Wenruo 	 */
25922d192fc4SQu Wenruo 	if (sb_rdonly(fs_info->sb)) {
25932d192fc4SQu Wenruo 		mutex_lock(&fs_info->ro_block_group_mutex);
25942d192fc4SQu Wenruo 		ret = inc_block_group_ro(cache, 0);
25952d192fc4SQu Wenruo 		mutex_unlock(&fs_info->ro_block_group_mutex);
25962d192fc4SQu Wenruo 		return ret;
25972d192fc4SQu Wenruo 	}
25982d192fc4SQu Wenruo 
2599b6e9f16cSNikolay Borisov 	do {
2600dfe8aec4SJosef Bacik 		trans = btrfs_join_transaction(root);
260126ce2095SJosef Bacik 		if (IS_ERR(trans))
260226ce2095SJosef Bacik 			return PTR_ERR(trans);
260326ce2095SJosef Bacik 
2604b6e9f16cSNikolay Borisov 		dirty_bg_running = false;
2605b6e9f16cSNikolay Borisov 
260626ce2095SJosef Bacik 		/*
2607b6e9f16cSNikolay Borisov 		 * We're not allowed to set block groups readonly after the dirty
2608b6e9f16cSNikolay Borisov 		 * block group cache has started writing.  If it already started,
2609b6e9f16cSNikolay Borisov 		 * back off and let this transaction commit.
261026ce2095SJosef Bacik 		 */
261126ce2095SJosef Bacik 		mutex_lock(&fs_info->ro_block_group_mutex);
261226ce2095SJosef Bacik 		if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
261326ce2095SJosef Bacik 			u64 transid = trans->transid;
261426ce2095SJosef Bacik 
261526ce2095SJosef Bacik 			mutex_unlock(&fs_info->ro_block_group_mutex);
261626ce2095SJosef Bacik 			btrfs_end_transaction(trans);
261726ce2095SJosef Bacik 
261826ce2095SJosef Bacik 			ret = btrfs_wait_for_commit(fs_info, transid);
261926ce2095SJosef Bacik 			if (ret)
262026ce2095SJosef Bacik 				return ret;
2621b6e9f16cSNikolay Borisov 			dirty_bg_running = true;
262226ce2095SJosef Bacik 		}
2623b6e9f16cSNikolay Borisov 	} while (dirty_bg_running);
262426ce2095SJosef Bacik 
2625b12de528SQu Wenruo 	if (do_chunk_alloc) {
262626ce2095SJosef Bacik 		/*
2627b12de528SQu Wenruo 		 * If we are changing raid levels, try to allocate a
2628b12de528SQu Wenruo 		 * corresponding block group with the new raid level.
262926ce2095SJosef Bacik 		 */
2630349e120eSJosef Bacik 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
263126ce2095SJosef Bacik 		if (alloc_flags != cache->flags) {
2632b12de528SQu Wenruo 			ret = btrfs_chunk_alloc(trans, alloc_flags,
2633b12de528SQu Wenruo 						CHUNK_ALLOC_FORCE);
263426ce2095SJosef Bacik 			/*
263526ce2095SJosef Bacik 			 * ENOSPC is allowed here, we may have enough space
2636b12de528SQu Wenruo 			 * already allocated at the new raid level to carry on
263726ce2095SJosef Bacik 			 */
263826ce2095SJosef Bacik 			if (ret == -ENOSPC)
263926ce2095SJosef Bacik 				ret = 0;
264026ce2095SJosef Bacik 			if (ret < 0)
264126ce2095SJosef Bacik 				goto out;
264226ce2095SJosef Bacik 		}
2643b12de528SQu Wenruo 	}
264426ce2095SJosef Bacik 
2645a7a63accSJosef Bacik 	ret = inc_block_group_ro(cache, 0);
2646195a49eaSFilipe Manana 	if (!do_chunk_alloc || ret == -ETXTBSY)
2647b12de528SQu Wenruo 		goto unlock_out;
264826ce2095SJosef Bacik 	if (!ret)
264926ce2095SJosef Bacik 		goto out;
265026ce2095SJosef Bacik 	alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
265126ce2095SJosef Bacik 	ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
265226ce2095SJosef Bacik 	if (ret < 0)
265326ce2095SJosef Bacik 		goto out;
2654e11c0406SJosef Bacik 	ret = inc_block_group_ro(cache, 0);
2655195a49eaSFilipe Manana 	if (ret == -ETXTBSY)
2656195a49eaSFilipe Manana 		goto unlock_out;
265726ce2095SJosef Bacik out:
265826ce2095SJosef Bacik 	if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2659349e120eSJosef Bacik 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
266026ce2095SJosef Bacik 		mutex_lock(&fs_info->chunk_mutex);
266126ce2095SJosef Bacik 		check_system_chunk(trans, alloc_flags);
266226ce2095SJosef Bacik 		mutex_unlock(&fs_info->chunk_mutex);
266326ce2095SJosef Bacik 	}
2664b12de528SQu Wenruo unlock_out:
266526ce2095SJosef Bacik 	mutex_unlock(&fs_info->ro_block_group_mutex);
266626ce2095SJosef Bacik 
266726ce2095SJosef Bacik 	btrfs_end_transaction(trans);
266826ce2095SJosef Bacik 	return ret;
266926ce2095SJosef Bacik }
267026ce2095SJosef Bacik 
267132da5386SDavid Sterba void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
267226ce2095SJosef Bacik {
267326ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
267426ce2095SJosef Bacik 	u64 num_bytes;
267526ce2095SJosef Bacik 
267626ce2095SJosef Bacik 	BUG_ON(!cache->ro);
267726ce2095SJosef Bacik 
267826ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
267926ce2095SJosef Bacik 	spin_lock(&cache->lock);
268026ce2095SJosef Bacik 	if (!--cache->ro) {
2681169e0da9SNaohiro Aota 		if (btrfs_is_zoned(cache->fs_info)) {
2682169e0da9SNaohiro Aota 			/* Migrate zone_unusable bytes back */
268398173255SNaohiro Aota 			cache->zone_unusable =
268498173255SNaohiro Aota 				(cache->alloc_offset - cache->used) +
268598173255SNaohiro Aota 				(cache->length - cache->zone_capacity);
2686169e0da9SNaohiro Aota 			sinfo->bytes_zone_unusable += cache->zone_unusable;
2687169e0da9SNaohiro Aota 			sinfo->bytes_readonly -= cache->zone_unusable;
2688169e0da9SNaohiro Aota 		}
2689f9f28e5bSNaohiro Aota 		num_bytes = cache->length - cache->reserved -
2690f9f28e5bSNaohiro Aota 			    cache->pinned - cache->bytes_super -
2691f9f28e5bSNaohiro Aota 			    cache->zone_unusable - cache->used;
2692f9f28e5bSNaohiro Aota 		sinfo->bytes_readonly -= num_bytes;
269326ce2095SJosef Bacik 		list_del_init(&cache->ro_list);
269426ce2095SJosef Bacik 	}
269526ce2095SJosef Bacik 	spin_unlock(&cache->lock);
269626ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
269726ce2095SJosef Bacik }
269877745c05SJosef Bacik 
26993be4d8efSQu Wenruo static int update_block_group_item(struct btrfs_trans_handle *trans,
270077745c05SJosef Bacik 				   struct btrfs_path *path,
270132da5386SDavid Sterba 				   struct btrfs_block_group *cache)
270277745c05SJosef Bacik {
270377745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
270477745c05SJosef Bacik 	int ret;
2705dfe8aec4SJosef Bacik 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
270677745c05SJosef Bacik 	unsigned long bi;
270777745c05SJosef Bacik 	struct extent_buffer *leaf;
2708bf38be65SDavid Sterba 	struct btrfs_block_group_item bgi;
2709b3470b5dSDavid Sterba 	struct btrfs_key key;
271077745c05SJosef Bacik 
2711b3470b5dSDavid Sterba 	key.objectid = cache->start;
2712b3470b5dSDavid Sterba 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2713b3470b5dSDavid Sterba 	key.offset = cache->length;
2714b3470b5dSDavid Sterba 
27153be4d8efSQu Wenruo 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
271677745c05SJosef Bacik 	if (ret) {
271777745c05SJosef Bacik 		if (ret > 0)
271877745c05SJosef Bacik 			ret = -ENOENT;
271977745c05SJosef Bacik 		goto fail;
272077745c05SJosef Bacik 	}
272177745c05SJosef Bacik 
272277745c05SJosef Bacik 	leaf = path->nodes[0];
272377745c05SJosef Bacik 	bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2724de0dc456SDavid Sterba 	btrfs_set_stack_block_group_used(&bgi, cache->used);
2725de0dc456SDavid Sterba 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
2726f7238e50SJosef Bacik 						   cache->global_root_id);
2727de0dc456SDavid Sterba 	btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2728bf38be65SDavid Sterba 	write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
272977745c05SJosef Bacik 	btrfs_mark_buffer_dirty(leaf);
273077745c05SJosef Bacik fail:
273177745c05SJosef Bacik 	btrfs_release_path(path);
273277745c05SJosef Bacik 	return ret;
273377745c05SJosef Bacik 
273477745c05SJosef Bacik }
273577745c05SJosef Bacik 
273632da5386SDavid Sterba static int cache_save_setup(struct btrfs_block_group *block_group,
273777745c05SJosef Bacik 			    struct btrfs_trans_handle *trans,
273877745c05SJosef Bacik 			    struct btrfs_path *path)
273977745c05SJosef Bacik {
274077745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
274177745c05SJosef Bacik 	struct btrfs_root *root = fs_info->tree_root;
274277745c05SJosef Bacik 	struct inode *inode = NULL;
274377745c05SJosef Bacik 	struct extent_changeset *data_reserved = NULL;
274477745c05SJosef Bacik 	u64 alloc_hint = 0;
274577745c05SJosef Bacik 	int dcs = BTRFS_DC_ERROR;
27460044ae11SQu Wenruo 	u64 cache_size = 0;
274777745c05SJosef Bacik 	int retries = 0;
274877745c05SJosef Bacik 	int ret = 0;
274977745c05SJosef Bacik 
2750af456a2cSBoris Burkov 	if (!btrfs_test_opt(fs_info, SPACE_CACHE))
2751af456a2cSBoris Burkov 		return 0;
2752af456a2cSBoris Burkov 
275377745c05SJosef Bacik 	/*
275477745c05SJosef Bacik 	 * If this block group is smaller than 100 megs don't bother caching the
275577745c05SJosef Bacik 	 * block group.
275677745c05SJosef Bacik 	 */
2757b3470b5dSDavid Sterba 	if (block_group->length < (100 * SZ_1M)) {
275877745c05SJosef Bacik 		spin_lock(&block_group->lock);
275977745c05SJosef Bacik 		block_group->disk_cache_state = BTRFS_DC_WRITTEN;
276077745c05SJosef Bacik 		spin_unlock(&block_group->lock);
276177745c05SJosef Bacik 		return 0;
276277745c05SJosef Bacik 	}
276377745c05SJosef Bacik 
2764bf31f87fSDavid Sterba 	if (TRANS_ABORTED(trans))
276577745c05SJosef Bacik 		return 0;
276677745c05SJosef Bacik again:
276777745c05SJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
276877745c05SJosef Bacik 	if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
276977745c05SJosef Bacik 		ret = PTR_ERR(inode);
277077745c05SJosef Bacik 		btrfs_release_path(path);
277177745c05SJosef Bacik 		goto out;
277277745c05SJosef Bacik 	}
277377745c05SJosef Bacik 
277477745c05SJosef Bacik 	if (IS_ERR(inode)) {
277577745c05SJosef Bacik 		BUG_ON(retries);
277677745c05SJosef Bacik 		retries++;
277777745c05SJosef Bacik 
277877745c05SJosef Bacik 		if (block_group->ro)
277977745c05SJosef Bacik 			goto out_free;
278077745c05SJosef Bacik 
278177745c05SJosef Bacik 		ret = create_free_space_inode(trans, block_group, path);
278277745c05SJosef Bacik 		if (ret)
278377745c05SJosef Bacik 			goto out_free;
278477745c05SJosef Bacik 		goto again;
278577745c05SJosef Bacik 	}
278677745c05SJosef Bacik 
278777745c05SJosef Bacik 	/*
278877745c05SJosef Bacik 	 * We want to set the generation to 0, that way if anything goes wrong
278977745c05SJosef Bacik 	 * from here on out we know not to trust this cache when we load up next
279077745c05SJosef Bacik 	 * time.
279177745c05SJosef Bacik 	 */
279277745c05SJosef Bacik 	BTRFS_I(inode)->generation = 0;
27939a56fcd1SNikolay Borisov 	ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
279477745c05SJosef Bacik 	if (ret) {
279577745c05SJosef Bacik 		/*
279677745c05SJosef Bacik 		 * So theoretically we could recover from this, simply set the
279777745c05SJosef Bacik 		 * super cache generation to 0 so we know to invalidate the
279877745c05SJosef Bacik 		 * cache, but then we'd have to keep track of the block groups
279977745c05SJosef Bacik 		 * that fail this way so we know we _have_ to reset this cache
280077745c05SJosef Bacik 		 * before the next commit or risk reading stale cache.  So to
280177745c05SJosef Bacik 		 * limit our exposure to horrible edge cases lets just abort the
280277745c05SJosef Bacik 		 * transaction, this only happens in really bad situations
280377745c05SJosef Bacik 		 * anyway.
280477745c05SJosef Bacik 		 */
280577745c05SJosef Bacik 		btrfs_abort_transaction(trans, ret);
280677745c05SJosef Bacik 		goto out_put;
280777745c05SJosef Bacik 	}
280877745c05SJosef Bacik 	WARN_ON(ret);
280977745c05SJosef Bacik 
281077745c05SJosef Bacik 	/* We've already setup this transaction, go ahead and exit */
281177745c05SJosef Bacik 	if (block_group->cache_generation == trans->transid &&
281277745c05SJosef Bacik 	    i_size_read(inode)) {
281377745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
281477745c05SJosef Bacik 		goto out_put;
281577745c05SJosef Bacik 	}
281677745c05SJosef Bacik 
281777745c05SJosef Bacik 	if (i_size_read(inode) > 0) {
281877745c05SJosef Bacik 		ret = btrfs_check_trunc_cache_free_space(fs_info,
281977745c05SJosef Bacik 					&fs_info->global_block_rsv);
282077745c05SJosef Bacik 		if (ret)
282177745c05SJosef Bacik 			goto out_put;
282277745c05SJosef Bacik 
282377745c05SJosef Bacik 		ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
282477745c05SJosef Bacik 		if (ret)
282577745c05SJosef Bacik 			goto out_put;
282677745c05SJosef Bacik 	}
282777745c05SJosef Bacik 
282877745c05SJosef Bacik 	spin_lock(&block_group->lock);
282977745c05SJosef Bacik 	if (block_group->cached != BTRFS_CACHE_FINISHED ||
283077745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE)) {
283177745c05SJosef Bacik 		/*
283277745c05SJosef Bacik 		 * don't bother trying to write stuff out _if_
283377745c05SJosef Bacik 		 * a) we're not cached,
283477745c05SJosef Bacik 		 * b) we're with nospace_cache mount option,
283577745c05SJosef Bacik 		 * c) we're with v2 space_cache (FREE_SPACE_TREE).
283677745c05SJosef Bacik 		 */
283777745c05SJosef Bacik 		dcs = BTRFS_DC_WRITTEN;
283877745c05SJosef Bacik 		spin_unlock(&block_group->lock);
283977745c05SJosef Bacik 		goto out_put;
284077745c05SJosef Bacik 	}
284177745c05SJosef Bacik 	spin_unlock(&block_group->lock);
284277745c05SJosef Bacik 
284377745c05SJosef Bacik 	/*
284477745c05SJosef Bacik 	 * We hit an ENOSPC when setting up the cache in this transaction, just
284577745c05SJosef Bacik 	 * skip doing the setup, we've already cleared the cache so we're safe.
284677745c05SJosef Bacik 	 */
284777745c05SJosef Bacik 	if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
284877745c05SJosef Bacik 		ret = -ENOSPC;
284977745c05SJosef Bacik 		goto out_put;
285077745c05SJosef Bacik 	}
285177745c05SJosef Bacik 
285277745c05SJosef Bacik 	/*
285377745c05SJosef Bacik 	 * Try to preallocate enough space based on how big the block group is.
285477745c05SJosef Bacik 	 * Keep in mind this has to include any pinned space which could end up
285577745c05SJosef Bacik 	 * taking up quite a bit since it's not folded into the other space
285677745c05SJosef Bacik 	 * cache.
285777745c05SJosef Bacik 	 */
28580044ae11SQu Wenruo 	cache_size = div_u64(block_group->length, SZ_256M);
28590044ae11SQu Wenruo 	if (!cache_size)
28600044ae11SQu Wenruo 		cache_size = 1;
286177745c05SJosef Bacik 
28620044ae11SQu Wenruo 	cache_size *= 16;
28630044ae11SQu Wenruo 	cache_size *= fs_info->sectorsize;
286477745c05SJosef Bacik 
286536ea6f3eSNikolay Borisov 	ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
28660044ae11SQu Wenruo 					  cache_size);
286777745c05SJosef Bacik 	if (ret)
286877745c05SJosef Bacik 		goto out_put;
286977745c05SJosef Bacik 
28700044ae11SQu Wenruo 	ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
28710044ae11SQu Wenruo 					      cache_size, cache_size,
287277745c05SJosef Bacik 					      &alloc_hint);
287377745c05SJosef Bacik 	/*
287477745c05SJosef Bacik 	 * Our cache requires contiguous chunks so that we don't modify a bunch
287577745c05SJosef Bacik 	 * of metadata or split extents when writing the cache out, which means
287677745c05SJosef Bacik 	 * we can enospc if we are heavily fragmented in addition to just normal
287777745c05SJosef Bacik 	 * out of space conditions.  So if we hit this just skip setting up any
287877745c05SJosef Bacik 	 * other block groups for this transaction, maybe we'll unpin enough
287977745c05SJosef Bacik 	 * space the next time around.
288077745c05SJosef Bacik 	 */
288177745c05SJosef Bacik 	if (!ret)
288277745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
288377745c05SJosef Bacik 	else if (ret == -ENOSPC)
288477745c05SJosef Bacik 		set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
288577745c05SJosef Bacik 
288677745c05SJosef Bacik out_put:
288777745c05SJosef Bacik 	iput(inode);
288877745c05SJosef Bacik out_free:
288977745c05SJosef Bacik 	btrfs_release_path(path);
289077745c05SJosef Bacik out:
289177745c05SJosef Bacik 	spin_lock(&block_group->lock);
289277745c05SJosef Bacik 	if (!ret && dcs == BTRFS_DC_SETUP)
289377745c05SJosef Bacik 		block_group->cache_generation = trans->transid;
289477745c05SJosef Bacik 	block_group->disk_cache_state = dcs;
289577745c05SJosef Bacik 	spin_unlock(&block_group->lock);
289677745c05SJosef Bacik 
289777745c05SJosef Bacik 	extent_changeset_free(data_reserved);
289877745c05SJosef Bacik 	return ret;
289977745c05SJosef Bacik }
290077745c05SJosef Bacik 
290177745c05SJosef Bacik int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
290277745c05SJosef Bacik {
290377745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
290432da5386SDavid Sterba 	struct btrfs_block_group *cache, *tmp;
290577745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
290677745c05SJosef Bacik 	struct btrfs_path *path;
290777745c05SJosef Bacik 
290877745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs) ||
290977745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE))
291077745c05SJosef Bacik 		return 0;
291177745c05SJosef Bacik 
291277745c05SJosef Bacik 	path = btrfs_alloc_path();
291377745c05SJosef Bacik 	if (!path)
291477745c05SJosef Bacik 		return -ENOMEM;
291577745c05SJosef Bacik 
291677745c05SJosef Bacik 	/* Could add new block groups, use _safe just in case */
291777745c05SJosef Bacik 	list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
291877745c05SJosef Bacik 				 dirty_list) {
291977745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_CLEAR)
292077745c05SJosef Bacik 			cache_save_setup(cache, trans, path);
292177745c05SJosef Bacik 	}
292277745c05SJosef Bacik 
292377745c05SJosef Bacik 	btrfs_free_path(path);
292477745c05SJosef Bacik 	return 0;
292577745c05SJosef Bacik }
292677745c05SJosef Bacik 
292777745c05SJosef Bacik /*
292877745c05SJosef Bacik  * Transaction commit does final block group cache writeback during a critical
292977745c05SJosef Bacik  * section where nothing is allowed to change the FS.  This is required in
293077745c05SJosef Bacik  * order for the cache to actually match the block group, but can introduce a
293177745c05SJosef Bacik  * lot of latency into the commit.
293277745c05SJosef Bacik  *
293377745c05SJosef Bacik  * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
293477745c05SJosef Bacik  * There's a chance we'll have to redo some of it if the block group changes
293577745c05SJosef Bacik  * again during the commit, but it greatly reduces the commit latency by
293677745c05SJosef Bacik  * getting rid of the easy block groups while we're still allowing others to
293777745c05SJosef Bacik  * join the commit.
293877745c05SJosef Bacik  */
293977745c05SJosef Bacik int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
294077745c05SJosef Bacik {
294177745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
294232da5386SDavid Sterba 	struct btrfs_block_group *cache;
294377745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
294477745c05SJosef Bacik 	int ret = 0;
294577745c05SJosef Bacik 	int should_put;
294677745c05SJosef Bacik 	struct btrfs_path *path = NULL;
294777745c05SJosef Bacik 	LIST_HEAD(dirty);
294877745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
294977745c05SJosef Bacik 	int loops = 0;
295077745c05SJosef Bacik 
295177745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
295277745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs)) {
295377745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
295477745c05SJosef Bacik 		return 0;
295577745c05SJosef Bacik 	}
295677745c05SJosef Bacik 	list_splice_init(&cur_trans->dirty_bgs, &dirty);
295777745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
295877745c05SJosef Bacik 
295977745c05SJosef Bacik again:
296077745c05SJosef Bacik 	/* Make sure all the block groups on our dirty list actually exist */
296177745c05SJosef Bacik 	btrfs_create_pending_block_groups(trans);
296277745c05SJosef Bacik 
296377745c05SJosef Bacik 	if (!path) {
296477745c05SJosef Bacik 		path = btrfs_alloc_path();
2965938fcbfbSJosef Bacik 		if (!path) {
2966938fcbfbSJosef Bacik 			ret = -ENOMEM;
2967938fcbfbSJosef Bacik 			goto out;
2968938fcbfbSJosef Bacik 		}
296977745c05SJosef Bacik 	}
297077745c05SJosef Bacik 
297177745c05SJosef Bacik 	/*
297277745c05SJosef Bacik 	 * cache_write_mutex is here only to save us from balance or automatic
297377745c05SJosef Bacik 	 * removal of empty block groups deleting this block group while we are
297477745c05SJosef Bacik 	 * writing out the cache
297577745c05SJosef Bacik 	 */
297677745c05SJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
297777745c05SJosef Bacik 	while (!list_empty(&dirty)) {
297877745c05SJosef Bacik 		bool drop_reserve = true;
297977745c05SJosef Bacik 
298032da5386SDavid Sterba 		cache = list_first_entry(&dirty, struct btrfs_block_group,
298177745c05SJosef Bacik 					 dirty_list);
298277745c05SJosef Bacik 		/*
298377745c05SJosef Bacik 		 * This can happen if something re-dirties a block group that
298477745c05SJosef Bacik 		 * is already under IO.  Just wait for it to finish and then do
298577745c05SJosef Bacik 		 * it all again
298677745c05SJosef Bacik 		 */
298777745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
298877745c05SJosef Bacik 			list_del_init(&cache->io_list);
298977745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
299077745c05SJosef Bacik 			btrfs_put_block_group(cache);
299177745c05SJosef Bacik 		}
299277745c05SJosef Bacik 
299377745c05SJosef Bacik 
299477745c05SJosef Bacik 		/*
299577745c05SJosef Bacik 		 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
299677745c05SJosef Bacik 		 * it should update the cache_state.  Don't delete until after
299777745c05SJosef Bacik 		 * we wait.
299877745c05SJosef Bacik 		 *
299977745c05SJosef Bacik 		 * Since we're not running in the commit critical section
300077745c05SJosef Bacik 		 * we need the dirty_bgs_lock to protect from update_block_group
300177745c05SJosef Bacik 		 */
300277745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
300377745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
300477745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
300577745c05SJosef Bacik 
300677745c05SJosef Bacik 		should_put = 1;
300777745c05SJosef Bacik 
300877745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
300977745c05SJosef Bacik 
301077745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_SETUP) {
301177745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
301277745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
301377745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
301477745c05SJosef Bacik 				should_put = 0;
301577745c05SJosef Bacik 
301677745c05SJosef Bacik 				/*
301777745c05SJosef Bacik 				 * The cache_write_mutex is protecting the
301877745c05SJosef Bacik 				 * io_list, also refer to the definition of
301977745c05SJosef Bacik 				 * btrfs_transaction::io_bgs for more details
302077745c05SJosef Bacik 				 */
302177745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
302277745c05SJosef Bacik 			} else {
302377745c05SJosef Bacik 				/*
302477745c05SJosef Bacik 				 * If we failed to write the cache, the
302577745c05SJosef Bacik 				 * generation will be bad and life goes on
302677745c05SJosef Bacik 				 */
302777745c05SJosef Bacik 				ret = 0;
302877745c05SJosef Bacik 			}
302977745c05SJosef Bacik 		}
303077745c05SJosef Bacik 		if (!ret) {
30313be4d8efSQu Wenruo 			ret = update_block_group_item(trans, path, cache);
303277745c05SJosef Bacik 			/*
303377745c05SJosef Bacik 			 * Our block group might still be attached to the list
303477745c05SJosef Bacik 			 * of new block groups in the transaction handle of some
303577745c05SJosef Bacik 			 * other task (struct btrfs_trans_handle->new_bgs). This
303677745c05SJosef Bacik 			 * means its block group item isn't yet in the extent
303777745c05SJosef Bacik 			 * tree. If this happens ignore the error, as we will
303877745c05SJosef Bacik 			 * try again later in the critical section of the
303977745c05SJosef Bacik 			 * transaction commit.
304077745c05SJosef Bacik 			 */
304177745c05SJosef Bacik 			if (ret == -ENOENT) {
304277745c05SJosef Bacik 				ret = 0;
304377745c05SJosef Bacik 				spin_lock(&cur_trans->dirty_bgs_lock);
304477745c05SJosef Bacik 				if (list_empty(&cache->dirty_list)) {
304577745c05SJosef Bacik 					list_add_tail(&cache->dirty_list,
304677745c05SJosef Bacik 						      &cur_trans->dirty_bgs);
304777745c05SJosef Bacik 					btrfs_get_block_group(cache);
304877745c05SJosef Bacik 					drop_reserve = false;
304977745c05SJosef Bacik 				}
305077745c05SJosef Bacik 				spin_unlock(&cur_trans->dirty_bgs_lock);
305177745c05SJosef Bacik 			} else if (ret) {
305277745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
305377745c05SJosef Bacik 			}
305477745c05SJosef Bacik 		}
305577745c05SJosef Bacik 
305677745c05SJosef Bacik 		/* If it's not on the io list, we need to put the block group */
305777745c05SJosef Bacik 		if (should_put)
305877745c05SJosef Bacik 			btrfs_put_block_group(cache);
305977745c05SJosef Bacik 		if (drop_reserve)
306077745c05SJosef Bacik 			btrfs_delayed_refs_rsv_release(fs_info, 1);
306177745c05SJosef Bacik 		/*
306277745c05SJosef Bacik 		 * Avoid blocking other tasks for too long. It might even save
306377745c05SJosef Bacik 		 * us from writing caches for block groups that are going to be
306477745c05SJosef Bacik 		 * removed.
306577745c05SJosef Bacik 		 */
306677745c05SJosef Bacik 		mutex_unlock(&trans->transaction->cache_write_mutex);
3067938fcbfbSJosef Bacik 		if (ret)
3068938fcbfbSJosef Bacik 			goto out;
306977745c05SJosef Bacik 		mutex_lock(&trans->transaction->cache_write_mutex);
307077745c05SJosef Bacik 	}
307177745c05SJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
307277745c05SJosef Bacik 
307377745c05SJosef Bacik 	/*
307477745c05SJosef Bacik 	 * Go through delayed refs for all the stuff we've just kicked off
307577745c05SJosef Bacik 	 * and then loop back (just once)
307677745c05SJosef Bacik 	 */
307734d1eb0eSJosef Bacik 	if (!ret)
307877745c05SJosef Bacik 		ret = btrfs_run_delayed_refs(trans, 0);
307977745c05SJosef Bacik 	if (!ret && loops == 0) {
308077745c05SJosef Bacik 		loops++;
308177745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
308277745c05SJosef Bacik 		list_splice_init(&cur_trans->dirty_bgs, &dirty);
308377745c05SJosef Bacik 		/*
308477745c05SJosef Bacik 		 * dirty_bgs_lock protects us from concurrent block group
308577745c05SJosef Bacik 		 * deletes too (not just cache_write_mutex).
308677745c05SJosef Bacik 		 */
308777745c05SJosef Bacik 		if (!list_empty(&dirty)) {
308877745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
308977745c05SJosef Bacik 			goto again;
309077745c05SJosef Bacik 		}
309177745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
3092938fcbfbSJosef Bacik 	}
3093938fcbfbSJosef Bacik out:
3094938fcbfbSJosef Bacik 	if (ret < 0) {
3095938fcbfbSJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
3096938fcbfbSJosef Bacik 		list_splice_init(&dirty, &cur_trans->dirty_bgs);
3097938fcbfbSJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
309877745c05SJosef Bacik 		btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
309977745c05SJosef Bacik 	}
310077745c05SJosef Bacik 
310177745c05SJosef Bacik 	btrfs_free_path(path);
310277745c05SJosef Bacik 	return ret;
310377745c05SJosef Bacik }
310477745c05SJosef Bacik 
310577745c05SJosef Bacik int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
310677745c05SJosef Bacik {
310777745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
310832da5386SDavid Sterba 	struct btrfs_block_group *cache;
310977745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
311077745c05SJosef Bacik 	int ret = 0;
311177745c05SJosef Bacik 	int should_put;
311277745c05SJosef Bacik 	struct btrfs_path *path;
311377745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
311477745c05SJosef Bacik 
311577745c05SJosef Bacik 	path = btrfs_alloc_path();
311677745c05SJosef Bacik 	if (!path)
311777745c05SJosef Bacik 		return -ENOMEM;
311877745c05SJosef Bacik 
311977745c05SJosef Bacik 	/*
312077745c05SJosef Bacik 	 * Even though we are in the critical section of the transaction commit,
312177745c05SJosef Bacik 	 * we can still have concurrent tasks adding elements to this
312277745c05SJosef Bacik 	 * transaction's list of dirty block groups. These tasks correspond to
312377745c05SJosef Bacik 	 * endio free space workers started when writeback finishes for a
312477745c05SJosef Bacik 	 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
312577745c05SJosef Bacik 	 * allocate new block groups as a result of COWing nodes of the root
312677745c05SJosef Bacik 	 * tree when updating the free space inode. The writeback for the space
312777745c05SJosef Bacik 	 * caches is triggered by an earlier call to
312877745c05SJosef Bacik 	 * btrfs_start_dirty_block_groups() and iterations of the following
312977745c05SJosef Bacik 	 * loop.
313077745c05SJosef Bacik 	 * Also we want to do the cache_save_setup first and then run the
313177745c05SJosef Bacik 	 * delayed refs to make sure we have the best chance at doing this all
313277745c05SJosef Bacik 	 * in one shot.
313377745c05SJosef Bacik 	 */
313477745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
313577745c05SJosef Bacik 	while (!list_empty(&cur_trans->dirty_bgs)) {
313677745c05SJosef Bacik 		cache = list_first_entry(&cur_trans->dirty_bgs,
313732da5386SDavid Sterba 					 struct btrfs_block_group,
313877745c05SJosef Bacik 					 dirty_list);
313977745c05SJosef Bacik 
314077745c05SJosef Bacik 		/*
314177745c05SJosef Bacik 		 * This can happen if cache_save_setup re-dirties a block group
314277745c05SJosef Bacik 		 * that is already under IO.  Just wait for it to finish and
314377745c05SJosef Bacik 		 * then do it all again
314477745c05SJosef Bacik 		 */
314577745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
314677745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
314777745c05SJosef Bacik 			list_del_init(&cache->io_list);
314877745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
314977745c05SJosef Bacik 			btrfs_put_block_group(cache);
315077745c05SJosef Bacik 			spin_lock(&cur_trans->dirty_bgs_lock);
315177745c05SJosef Bacik 		}
315277745c05SJosef Bacik 
315377745c05SJosef Bacik 		/*
315477745c05SJosef Bacik 		 * Don't remove from the dirty list until after we've waited on
315577745c05SJosef Bacik 		 * any pending IO
315677745c05SJosef Bacik 		 */
315777745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
315877745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
315977745c05SJosef Bacik 		should_put = 1;
316077745c05SJosef Bacik 
316177745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
316277745c05SJosef Bacik 
316377745c05SJosef Bacik 		if (!ret)
316477745c05SJosef Bacik 			ret = btrfs_run_delayed_refs(trans,
316577745c05SJosef Bacik 						     (unsigned long) -1);
316677745c05SJosef Bacik 
316777745c05SJosef Bacik 		if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
316877745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
316977745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
317077745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
317177745c05SJosef Bacik 				should_put = 0;
317277745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
317377745c05SJosef Bacik 			} else {
317477745c05SJosef Bacik 				/*
317577745c05SJosef Bacik 				 * If we failed to write the cache, the
317677745c05SJosef Bacik 				 * generation will be bad and life goes on
317777745c05SJosef Bacik 				 */
317877745c05SJosef Bacik 				ret = 0;
317977745c05SJosef Bacik 			}
318077745c05SJosef Bacik 		}
318177745c05SJosef Bacik 		if (!ret) {
31823be4d8efSQu Wenruo 			ret = update_block_group_item(trans, path, cache);
318377745c05SJosef Bacik 			/*
318477745c05SJosef Bacik 			 * One of the free space endio workers might have
318577745c05SJosef Bacik 			 * created a new block group while updating a free space
318677745c05SJosef Bacik 			 * cache's inode (at inode.c:btrfs_finish_ordered_io())
318777745c05SJosef Bacik 			 * and hasn't released its transaction handle yet, in
318877745c05SJosef Bacik 			 * which case the new block group is still attached to
318977745c05SJosef Bacik 			 * its transaction handle and its creation has not
319077745c05SJosef Bacik 			 * finished yet (no block group item in the extent tree
319177745c05SJosef Bacik 			 * yet, etc). If this is the case, wait for all free
319277745c05SJosef Bacik 			 * space endio workers to finish and retry. This is a
3193260db43cSRandy Dunlap 			 * very rare case so no need for a more efficient and
319477745c05SJosef Bacik 			 * complex approach.
319577745c05SJosef Bacik 			 */
319677745c05SJosef Bacik 			if (ret == -ENOENT) {
319777745c05SJosef Bacik 				wait_event(cur_trans->writer_wait,
319877745c05SJosef Bacik 				   atomic_read(&cur_trans->num_writers) == 1);
31993be4d8efSQu Wenruo 				ret = update_block_group_item(trans, path, cache);
320077745c05SJosef Bacik 			}
320177745c05SJosef Bacik 			if (ret)
320277745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
320377745c05SJosef Bacik 		}
320477745c05SJosef Bacik 
320577745c05SJosef Bacik 		/* If its not on the io list, we need to put the block group */
320677745c05SJosef Bacik 		if (should_put)
320777745c05SJosef Bacik 			btrfs_put_block_group(cache);
320877745c05SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
320977745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
321077745c05SJosef Bacik 	}
321177745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
321277745c05SJosef Bacik 
321377745c05SJosef Bacik 	/*
321477745c05SJosef Bacik 	 * Refer to the definition of io_bgs member for details why it's safe
321577745c05SJosef Bacik 	 * to use it without any locking
321677745c05SJosef Bacik 	 */
321777745c05SJosef Bacik 	while (!list_empty(io)) {
321832da5386SDavid Sterba 		cache = list_first_entry(io, struct btrfs_block_group,
321977745c05SJosef Bacik 					 io_list);
322077745c05SJosef Bacik 		list_del_init(&cache->io_list);
322177745c05SJosef Bacik 		btrfs_wait_cache_io(trans, cache, path);
322277745c05SJosef Bacik 		btrfs_put_block_group(cache);
322377745c05SJosef Bacik 	}
322477745c05SJosef Bacik 
322577745c05SJosef Bacik 	btrfs_free_path(path);
322677745c05SJosef Bacik 	return ret;
322777745c05SJosef Bacik }
3228606d1bf1SJosef Bacik 
3229ac2f1e63SJosef Bacik static inline bool should_reclaim_block_group(struct btrfs_block_group *bg,
3230ac2f1e63SJosef Bacik 					      u64 bytes_freed)
3231ac2f1e63SJosef Bacik {
3232ac2f1e63SJosef Bacik 	const struct btrfs_space_info *space_info = bg->space_info;
3233ac2f1e63SJosef Bacik 	const int reclaim_thresh = READ_ONCE(space_info->bg_reclaim_threshold);
3234ac2f1e63SJosef Bacik 	const u64 new_val = bg->used;
3235ac2f1e63SJosef Bacik 	const u64 old_val = new_val + bytes_freed;
3236ac2f1e63SJosef Bacik 	u64 thresh;
3237ac2f1e63SJosef Bacik 
3238ac2f1e63SJosef Bacik 	if (reclaim_thresh == 0)
3239ac2f1e63SJosef Bacik 		return false;
3240ac2f1e63SJosef Bacik 
3241ac2f1e63SJosef Bacik 	thresh = div_factor_fine(bg->length, reclaim_thresh);
3242ac2f1e63SJosef Bacik 
3243ac2f1e63SJosef Bacik 	/*
3244ac2f1e63SJosef Bacik 	 * If we were below the threshold before don't reclaim, we are likely a
3245ac2f1e63SJosef Bacik 	 * brand new block group and we don't want to relocate new block groups.
3246ac2f1e63SJosef Bacik 	 */
3247ac2f1e63SJosef Bacik 	if (old_val < thresh)
3248ac2f1e63SJosef Bacik 		return false;
3249ac2f1e63SJosef Bacik 	if (new_val >= thresh)
3250ac2f1e63SJosef Bacik 		return false;
3251ac2f1e63SJosef Bacik 	return true;
3252ac2f1e63SJosef Bacik }
3253ac2f1e63SJosef Bacik 
3254606d1bf1SJosef Bacik int btrfs_update_block_group(struct btrfs_trans_handle *trans,
325511b66fa6SAnand Jain 			     u64 bytenr, u64 num_bytes, bool alloc)
3256606d1bf1SJosef Bacik {
3257606d1bf1SJosef Bacik 	struct btrfs_fs_info *info = trans->fs_info;
325832da5386SDavid Sterba 	struct btrfs_block_group *cache = NULL;
3259606d1bf1SJosef Bacik 	u64 total = num_bytes;
3260606d1bf1SJosef Bacik 	u64 old_val;
3261606d1bf1SJosef Bacik 	u64 byte_in_group;
3262606d1bf1SJosef Bacik 	int factor;
3263606d1bf1SJosef Bacik 	int ret = 0;
3264606d1bf1SJosef Bacik 
3265606d1bf1SJosef Bacik 	/* Block accounting for super block */
3266606d1bf1SJosef Bacik 	spin_lock(&info->delalloc_root_lock);
3267606d1bf1SJosef Bacik 	old_val = btrfs_super_bytes_used(info->super_copy);
3268606d1bf1SJosef Bacik 	if (alloc)
3269606d1bf1SJosef Bacik 		old_val += num_bytes;
3270606d1bf1SJosef Bacik 	else
3271606d1bf1SJosef Bacik 		old_val -= num_bytes;
3272606d1bf1SJosef Bacik 	btrfs_set_super_bytes_used(info->super_copy, old_val);
3273606d1bf1SJosef Bacik 	spin_unlock(&info->delalloc_root_lock);
3274606d1bf1SJosef Bacik 
3275606d1bf1SJosef Bacik 	while (total) {
3276ac2f1e63SJosef Bacik 		bool reclaim;
3277ac2f1e63SJosef Bacik 
3278606d1bf1SJosef Bacik 		cache = btrfs_lookup_block_group(info, bytenr);
3279606d1bf1SJosef Bacik 		if (!cache) {
3280606d1bf1SJosef Bacik 			ret = -ENOENT;
3281606d1bf1SJosef Bacik 			break;
3282606d1bf1SJosef Bacik 		}
3283606d1bf1SJosef Bacik 		factor = btrfs_bg_type_to_factor(cache->flags);
3284606d1bf1SJosef Bacik 
3285606d1bf1SJosef Bacik 		/*
3286606d1bf1SJosef Bacik 		 * If this block group has free space cache written out, we
3287606d1bf1SJosef Bacik 		 * need to make sure to load it if we are removing space.  This
3288606d1bf1SJosef Bacik 		 * is because we need the unpinning stage to actually add the
3289606d1bf1SJosef Bacik 		 * space back to the block group, otherwise we will leak space.
3290606d1bf1SJosef Bacik 		 */
329132da5386SDavid Sterba 		if (!alloc && !btrfs_block_group_done(cache))
3292606d1bf1SJosef Bacik 			btrfs_cache_block_group(cache, 1);
3293606d1bf1SJosef Bacik 
3294b3470b5dSDavid Sterba 		byte_in_group = bytenr - cache->start;
3295b3470b5dSDavid Sterba 		WARN_ON(byte_in_group > cache->length);
3296606d1bf1SJosef Bacik 
3297606d1bf1SJosef Bacik 		spin_lock(&cache->space_info->lock);
3298606d1bf1SJosef Bacik 		spin_lock(&cache->lock);
3299606d1bf1SJosef Bacik 
3300606d1bf1SJosef Bacik 		if (btrfs_test_opt(info, SPACE_CACHE) &&
3301606d1bf1SJosef Bacik 		    cache->disk_cache_state < BTRFS_DC_CLEAR)
3302606d1bf1SJosef Bacik 			cache->disk_cache_state = BTRFS_DC_CLEAR;
3303606d1bf1SJosef Bacik 
3304bf38be65SDavid Sterba 		old_val = cache->used;
3305b3470b5dSDavid Sterba 		num_bytes = min(total, cache->length - byte_in_group);
3306606d1bf1SJosef Bacik 		if (alloc) {
3307606d1bf1SJosef Bacik 			old_val += num_bytes;
3308bf38be65SDavid Sterba 			cache->used = old_val;
3309606d1bf1SJosef Bacik 			cache->reserved -= num_bytes;
3310606d1bf1SJosef Bacik 			cache->space_info->bytes_reserved -= num_bytes;
3311606d1bf1SJosef Bacik 			cache->space_info->bytes_used += num_bytes;
3312606d1bf1SJosef Bacik 			cache->space_info->disk_used += num_bytes * factor;
3313606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
3314606d1bf1SJosef Bacik 			spin_unlock(&cache->space_info->lock);
3315606d1bf1SJosef Bacik 		} else {
3316606d1bf1SJosef Bacik 			old_val -= num_bytes;
3317bf38be65SDavid Sterba 			cache->used = old_val;
3318606d1bf1SJosef Bacik 			cache->pinned += num_bytes;
3319606d1bf1SJosef Bacik 			btrfs_space_info_update_bytes_pinned(info,
3320606d1bf1SJosef Bacik 					cache->space_info, num_bytes);
3321606d1bf1SJosef Bacik 			cache->space_info->bytes_used -= num_bytes;
3322606d1bf1SJosef Bacik 			cache->space_info->disk_used -= num_bytes * factor;
3323ac2f1e63SJosef Bacik 
3324ac2f1e63SJosef Bacik 			reclaim = should_reclaim_block_group(cache, num_bytes);
3325606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
3326606d1bf1SJosef Bacik 			spin_unlock(&cache->space_info->lock);
3327606d1bf1SJosef Bacik 
3328fe119a6eSNikolay Borisov 			set_extent_dirty(&trans->transaction->pinned_extents,
3329606d1bf1SJosef Bacik 					 bytenr, bytenr + num_bytes - 1,
3330606d1bf1SJosef Bacik 					 GFP_NOFS | __GFP_NOFAIL);
3331606d1bf1SJosef Bacik 		}
3332606d1bf1SJosef Bacik 
3333606d1bf1SJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
3334606d1bf1SJosef Bacik 		if (list_empty(&cache->dirty_list)) {
3335606d1bf1SJosef Bacik 			list_add_tail(&cache->dirty_list,
3336606d1bf1SJosef Bacik 				      &trans->transaction->dirty_bgs);
3337606d1bf1SJosef Bacik 			trans->delayed_ref_updates++;
3338606d1bf1SJosef Bacik 			btrfs_get_block_group(cache);
3339606d1bf1SJosef Bacik 		}
3340606d1bf1SJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
3341606d1bf1SJosef Bacik 
3342606d1bf1SJosef Bacik 		/*
3343606d1bf1SJosef Bacik 		 * No longer have used bytes in this block group, queue it for
3344606d1bf1SJosef Bacik 		 * deletion. We do this after adding the block group to the
3345606d1bf1SJosef Bacik 		 * dirty list to avoid races between cleaner kthread and space
3346606d1bf1SJosef Bacik 		 * cache writeout.
3347606d1bf1SJosef Bacik 		 */
33486e80d4f8SDennis Zhou 		if (!alloc && old_val == 0) {
33496e80d4f8SDennis Zhou 			if (!btrfs_test_opt(info, DISCARD_ASYNC))
3350606d1bf1SJosef Bacik 				btrfs_mark_bg_unused(cache);
3351ac2f1e63SJosef Bacik 		} else if (!alloc && reclaim) {
3352ac2f1e63SJosef Bacik 			btrfs_mark_bg_to_reclaim(cache);
33536e80d4f8SDennis Zhou 		}
3354606d1bf1SJosef Bacik 
3355606d1bf1SJosef Bacik 		btrfs_put_block_group(cache);
3356606d1bf1SJosef Bacik 		total -= num_bytes;
3357606d1bf1SJosef Bacik 		bytenr += num_bytes;
3358606d1bf1SJosef Bacik 	}
3359606d1bf1SJosef Bacik 
3360606d1bf1SJosef Bacik 	/* Modified block groups are accounted for in the delayed_refs_rsv. */
3361606d1bf1SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
3362606d1bf1SJosef Bacik 	return ret;
3363606d1bf1SJosef Bacik }
3364606d1bf1SJosef Bacik 
3365606d1bf1SJosef Bacik /**
3366606d1bf1SJosef Bacik  * btrfs_add_reserved_bytes - update the block_group and space info counters
3367606d1bf1SJosef Bacik  * @cache:	The cache we are manipulating
3368606d1bf1SJosef Bacik  * @ram_bytes:  The number of bytes of file content, and will be same to
3369606d1bf1SJosef Bacik  *              @num_bytes except for the compress path.
3370606d1bf1SJosef Bacik  * @num_bytes:	The number of bytes in question
3371606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
3372606d1bf1SJosef Bacik  *
3373606d1bf1SJosef Bacik  * This is called by the allocator when it reserves space. If this is a
3374606d1bf1SJosef Bacik  * reservation and the block group has become read only we cannot make the
3375606d1bf1SJosef Bacik  * reservation and return -EAGAIN, otherwise this function always succeeds.
3376606d1bf1SJosef Bacik  */
337732da5386SDavid Sterba int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
3378606d1bf1SJosef Bacik 			     u64 ram_bytes, u64 num_bytes, int delalloc)
3379606d1bf1SJosef Bacik {
3380606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
3381606d1bf1SJosef Bacik 	int ret = 0;
3382606d1bf1SJosef Bacik 
3383606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
3384606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
3385606d1bf1SJosef Bacik 	if (cache->ro) {
3386606d1bf1SJosef Bacik 		ret = -EAGAIN;
3387606d1bf1SJosef Bacik 	} else {
3388606d1bf1SJosef Bacik 		cache->reserved += num_bytes;
3389606d1bf1SJosef Bacik 		space_info->bytes_reserved += num_bytes;
3390a43c3835SJosef Bacik 		trace_btrfs_space_reservation(cache->fs_info, "space_info",
3391a43c3835SJosef Bacik 					      space_info->flags, num_bytes, 1);
3392606d1bf1SJosef Bacik 		btrfs_space_info_update_bytes_may_use(cache->fs_info,
3393606d1bf1SJosef Bacik 						      space_info, -ram_bytes);
3394606d1bf1SJosef Bacik 		if (delalloc)
3395606d1bf1SJosef Bacik 			cache->delalloc_bytes += num_bytes;
339699ffb43eSJosef Bacik 
339799ffb43eSJosef Bacik 		/*
339899ffb43eSJosef Bacik 		 * Compression can use less space than we reserved, so wake
339999ffb43eSJosef Bacik 		 * tickets if that happens
340099ffb43eSJosef Bacik 		 */
340199ffb43eSJosef Bacik 		if (num_bytes < ram_bytes)
340299ffb43eSJosef Bacik 			btrfs_try_granting_tickets(cache->fs_info, space_info);
3403606d1bf1SJosef Bacik 	}
3404606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
3405606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
3406606d1bf1SJosef Bacik 	return ret;
3407606d1bf1SJosef Bacik }
3408606d1bf1SJosef Bacik 
3409606d1bf1SJosef Bacik /**
3410606d1bf1SJosef Bacik  * btrfs_free_reserved_bytes - update the block_group and space info counters
3411606d1bf1SJosef Bacik  * @cache:      The cache we are manipulating
3412606d1bf1SJosef Bacik  * @num_bytes:  The number of bytes in question
3413606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
3414606d1bf1SJosef Bacik  *
3415606d1bf1SJosef Bacik  * This is called by somebody who is freeing space that was never actually used
3416606d1bf1SJosef Bacik  * on disk.  For example if you reserve some space for a new leaf in transaction
3417606d1bf1SJosef Bacik  * A and before transaction A commits you free that leaf, you call this with
3418606d1bf1SJosef Bacik  * reserve set to 0 in order to clear the reservation.
3419606d1bf1SJosef Bacik  */
342032da5386SDavid Sterba void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3421606d1bf1SJosef Bacik 			       u64 num_bytes, int delalloc)
3422606d1bf1SJosef Bacik {
3423606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
3424606d1bf1SJosef Bacik 
3425606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
3426606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
3427606d1bf1SJosef Bacik 	if (cache->ro)
3428606d1bf1SJosef Bacik 		space_info->bytes_readonly += num_bytes;
3429606d1bf1SJosef Bacik 	cache->reserved -= num_bytes;
3430606d1bf1SJosef Bacik 	space_info->bytes_reserved -= num_bytes;
3431606d1bf1SJosef Bacik 	space_info->max_extent_size = 0;
3432606d1bf1SJosef Bacik 
3433606d1bf1SJosef Bacik 	if (delalloc)
3434606d1bf1SJosef Bacik 		cache->delalloc_bytes -= num_bytes;
3435606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
34363308234aSJosef Bacik 
34373308234aSJosef Bacik 	btrfs_try_granting_tickets(cache->fs_info, space_info);
3438606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
3439606d1bf1SJosef Bacik }
344007730d87SJosef Bacik 
344107730d87SJosef Bacik static void force_metadata_allocation(struct btrfs_fs_info *info)
344207730d87SJosef Bacik {
344307730d87SJosef Bacik 	struct list_head *head = &info->space_info;
344407730d87SJosef Bacik 	struct btrfs_space_info *found;
344507730d87SJosef Bacik 
344672804905SJosef Bacik 	list_for_each_entry(found, head, list) {
344707730d87SJosef Bacik 		if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
344807730d87SJosef Bacik 			found->force_alloc = CHUNK_ALLOC_FORCE;
344907730d87SJosef Bacik 	}
345007730d87SJosef Bacik }
345107730d87SJosef Bacik 
345207730d87SJosef Bacik static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
345307730d87SJosef Bacik 			      struct btrfs_space_info *sinfo, int force)
345407730d87SJosef Bacik {
345507730d87SJosef Bacik 	u64 bytes_used = btrfs_space_info_used(sinfo, false);
345607730d87SJosef Bacik 	u64 thresh;
345707730d87SJosef Bacik 
345807730d87SJosef Bacik 	if (force == CHUNK_ALLOC_FORCE)
345907730d87SJosef Bacik 		return 1;
346007730d87SJosef Bacik 
346107730d87SJosef Bacik 	/*
346207730d87SJosef Bacik 	 * in limited mode, we want to have some free space up to
346307730d87SJosef Bacik 	 * about 1% of the FS size.
346407730d87SJosef Bacik 	 */
346507730d87SJosef Bacik 	if (force == CHUNK_ALLOC_LIMITED) {
346607730d87SJosef Bacik 		thresh = btrfs_super_total_bytes(fs_info->super_copy);
346707730d87SJosef Bacik 		thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
346807730d87SJosef Bacik 
346907730d87SJosef Bacik 		if (sinfo->total_bytes - bytes_used < thresh)
347007730d87SJosef Bacik 			return 1;
347107730d87SJosef Bacik 	}
347207730d87SJosef Bacik 
347307730d87SJosef Bacik 	if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
347407730d87SJosef Bacik 		return 0;
347507730d87SJosef Bacik 	return 1;
347607730d87SJosef Bacik }
347707730d87SJosef Bacik 
347807730d87SJosef Bacik int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
347907730d87SJosef Bacik {
348007730d87SJosef Bacik 	u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
348107730d87SJosef Bacik 
348207730d87SJosef Bacik 	return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
348307730d87SJosef Bacik }
348407730d87SJosef Bacik 
3485820c363bSNaohiro Aota static struct btrfs_block_group *do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags)
348679bd3712SFilipe Manana {
348779bd3712SFilipe Manana 	struct btrfs_block_group *bg;
348879bd3712SFilipe Manana 	int ret;
348979bd3712SFilipe Manana 
349007730d87SJosef Bacik 	/*
349179bd3712SFilipe Manana 	 * Check if we have enough space in the system space info because we
349279bd3712SFilipe Manana 	 * will need to update device items in the chunk btree and insert a new
349379bd3712SFilipe Manana 	 * chunk item in the chunk btree as well. This will allocate a new
349479bd3712SFilipe Manana 	 * system block group if needed.
349579bd3712SFilipe Manana 	 */
349679bd3712SFilipe Manana 	check_system_chunk(trans, flags);
349779bd3712SFilipe Manana 
3498f6f39f7aSNikolay Borisov 	bg = btrfs_create_chunk(trans, flags);
349979bd3712SFilipe Manana 	if (IS_ERR(bg)) {
350079bd3712SFilipe Manana 		ret = PTR_ERR(bg);
350179bd3712SFilipe Manana 		goto out;
350279bd3712SFilipe Manana 	}
350379bd3712SFilipe Manana 
350479bd3712SFilipe Manana 	ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
350579bd3712SFilipe Manana 	/*
350679bd3712SFilipe Manana 	 * Normally we are not expected to fail with -ENOSPC here, since we have
350779bd3712SFilipe Manana 	 * previously reserved space in the system space_info and allocated one
3508ecd84d54SFilipe Manana 	 * new system chunk if necessary. However there are three exceptions:
350979bd3712SFilipe Manana 	 *
351079bd3712SFilipe Manana 	 * 1) We may have enough free space in the system space_info but all the
351179bd3712SFilipe Manana 	 *    existing system block groups have a profile which can not be used
351279bd3712SFilipe Manana 	 *    for extent allocation.
351379bd3712SFilipe Manana 	 *
351479bd3712SFilipe Manana 	 *    This happens when mounting in degraded mode. For example we have a
351579bd3712SFilipe Manana 	 *    RAID1 filesystem with 2 devices, lose one device and mount the fs
351679bd3712SFilipe Manana 	 *    using the other device in degraded mode. If we then allocate a chunk,
351779bd3712SFilipe Manana 	 *    we may have enough free space in the existing system space_info, but
351879bd3712SFilipe Manana 	 *    none of the block groups can be used for extent allocation since they
351979bd3712SFilipe Manana 	 *    have a RAID1 profile, and because we are in degraded mode with a
352079bd3712SFilipe Manana 	 *    single device, we are forced to allocate a new system chunk with a
352179bd3712SFilipe Manana 	 *    SINGLE profile. Making check_system_chunk() iterate over all system
352279bd3712SFilipe Manana 	 *    block groups and check if they have a usable profile and enough space
352379bd3712SFilipe Manana 	 *    can be slow on very large filesystems, so we tolerate the -ENOSPC and
352479bd3712SFilipe Manana 	 *    try again after forcing allocation of a new system chunk. Like this
352579bd3712SFilipe Manana 	 *    we avoid paying the cost of that search in normal circumstances, when
352679bd3712SFilipe Manana 	 *    we were not mounted in degraded mode;
352779bd3712SFilipe Manana 	 *
352879bd3712SFilipe Manana 	 * 2) We had enough free space info the system space_info, and one suitable
352979bd3712SFilipe Manana 	 *    block group to allocate from when we called check_system_chunk()
353079bd3712SFilipe Manana 	 *    above. However right after we called it, the only system block group
353179bd3712SFilipe Manana 	 *    with enough free space got turned into RO mode by a running scrub,
353279bd3712SFilipe Manana 	 *    and in this case we have to allocate a new one and retry. We only
353379bd3712SFilipe Manana 	 *    need do this allocate and retry once, since we have a transaction
3534ecd84d54SFilipe Manana 	 *    handle and scrub uses the commit root to search for block groups;
3535ecd84d54SFilipe Manana 	 *
3536ecd84d54SFilipe Manana 	 * 3) We had one system block group with enough free space when we called
3537ecd84d54SFilipe Manana 	 *    check_system_chunk(), but after that, right before we tried to
3538ecd84d54SFilipe Manana 	 *    allocate the last extent buffer we needed, a discard operation came
3539ecd84d54SFilipe Manana 	 *    in and it temporarily removed the last free space entry from the
3540ecd84d54SFilipe Manana 	 *    block group (discard removes a free space entry, discards it, and
3541ecd84d54SFilipe Manana 	 *    then adds back the entry to the block group cache).
354279bd3712SFilipe Manana 	 */
354379bd3712SFilipe Manana 	if (ret == -ENOSPC) {
354479bd3712SFilipe Manana 		const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info);
354579bd3712SFilipe Manana 		struct btrfs_block_group *sys_bg;
354679bd3712SFilipe Manana 
3547f6f39f7aSNikolay Borisov 		sys_bg = btrfs_create_chunk(trans, sys_flags);
354879bd3712SFilipe Manana 		if (IS_ERR(sys_bg)) {
354979bd3712SFilipe Manana 			ret = PTR_ERR(sys_bg);
355079bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
355179bd3712SFilipe Manana 			goto out;
355279bd3712SFilipe Manana 		}
355379bd3712SFilipe Manana 
355479bd3712SFilipe Manana 		ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
355579bd3712SFilipe Manana 		if (ret) {
355679bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
355779bd3712SFilipe Manana 			goto out;
355879bd3712SFilipe Manana 		}
355979bd3712SFilipe Manana 
356079bd3712SFilipe Manana 		ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
356179bd3712SFilipe Manana 		if (ret) {
356279bd3712SFilipe Manana 			btrfs_abort_transaction(trans, ret);
356379bd3712SFilipe Manana 			goto out;
356479bd3712SFilipe Manana 		}
356579bd3712SFilipe Manana 	} else if (ret) {
356679bd3712SFilipe Manana 		btrfs_abort_transaction(trans, ret);
356779bd3712SFilipe Manana 		goto out;
356879bd3712SFilipe Manana 	}
356979bd3712SFilipe Manana out:
357079bd3712SFilipe Manana 	btrfs_trans_release_chunk_metadata(trans);
357179bd3712SFilipe Manana 
3572820c363bSNaohiro Aota 	if (ret)
3573820c363bSNaohiro Aota 		return ERR_PTR(ret);
3574820c363bSNaohiro Aota 
3575820c363bSNaohiro Aota 	btrfs_get_block_group(bg);
3576820c363bSNaohiro Aota 	return bg;
357779bd3712SFilipe Manana }
357879bd3712SFilipe Manana 
357979bd3712SFilipe Manana /*
358079bd3712SFilipe Manana  * Chunk allocation is done in 2 phases:
358179bd3712SFilipe Manana  *
358279bd3712SFilipe Manana  * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
358379bd3712SFilipe Manana  *    the chunk, the chunk mapping, create its block group and add the items
358479bd3712SFilipe Manana  *    that belong in the chunk btree to it - more specifically, we need to
358579bd3712SFilipe Manana  *    update device items in the chunk btree and add a new chunk item to it.
358679bd3712SFilipe Manana  *
358779bd3712SFilipe Manana  * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
358879bd3712SFilipe Manana  *    group item to the extent btree and the device extent items to the devices
358979bd3712SFilipe Manana  *    btree.
359079bd3712SFilipe Manana  *
359179bd3712SFilipe Manana  * This is done to prevent deadlocks. For example when COWing a node from the
359279bd3712SFilipe Manana  * extent btree we are holding a write lock on the node's parent and if we
359379bd3712SFilipe Manana  * trigger chunk allocation and attempted to insert the new block group item
359479bd3712SFilipe Manana  * in the extent btree right way, we could deadlock because the path for the
359579bd3712SFilipe Manana  * insertion can include that parent node. At first glance it seems impossible
359679bd3712SFilipe Manana  * to trigger chunk allocation after starting a transaction since tasks should
359779bd3712SFilipe Manana  * reserve enough transaction units (metadata space), however while that is true
359879bd3712SFilipe Manana  * most of the time, chunk allocation may still be triggered for several reasons:
359979bd3712SFilipe Manana  *
360079bd3712SFilipe Manana  * 1) When reserving metadata, we check if there is enough free space in the
360179bd3712SFilipe Manana  *    metadata space_info and therefore don't trigger allocation of a new chunk.
360279bd3712SFilipe Manana  *    However later when the task actually tries to COW an extent buffer from
360379bd3712SFilipe Manana  *    the extent btree or from the device btree for example, it is forced to
360479bd3712SFilipe Manana  *    allocate a new block group (chunk) because the only one that had enough
360579bd3712SFilipe Manana  *    free space was just turned to RO mode by a running scrub for example (or
360679bd3712SFilipe Manana  *    device replace, block group reclaim thread, etc), so we can not use it
360779bd3712SFilipe Manana  *    for allocating an extent and end up being forced to allocate a new one;
360879bd3712SFilipe Manana  *
360979bd3712SFilipe Manana  * 2) Because we only check that the metadata space_info has enough free bytes,
361079bd3712SFilipe Manana  *    we end up not allocating a new metadata chunk in that case. However if
361179bd3712SFilipe Manana  *    the filesystem was mounted in degraded mode, none of the existing block
361279bd3712SFilipe Manana  *    groups might be suitable for extent allocation due to their incompatible
361379bd3712SFilipe Manana  *    profile (for e.g. mounting a 2 devices filesystem, where all block groups
361479bd3712SFilipe Manana  *    use a RAID1 profile, in degraded mode using a single device). In this case
361579bd3712SFilipe Manana  *    when the task attempts to COW some extent buffer of the extent btree for
361679bd3712SFilipe Manana  *    example, it will trigger allocation of a new metadata block group with a
361779bd3712SFilipe Manana  *    suitable profile (SINGLE profile in the example of the degraded mount of
361879bd3712SFilipe Manana  *    the RAID1 filesystem);
361979bd3712SFilipe Manana  *
362079bd3712SFilipe Manana  * 3) The task has reserved enough transaction units / metadata space, but when
362179bd3712SFilipe Manana  *    it attempts to COW an extent buffer from the extent or device btree for
362279bd3712SFilipe Manana  *    example, it does not find any free extent in any metadata block group,
362379bd3712SFilipe Manana  *    therefore forced to try to allocate a new metadata block group.
362479bd3712SFilipe Manana  *    This is because some other task allocated all available extents in the
362579bd3712SFilipe Manana  *    meanwhile - this typically happens with tasks that don't reserve space
362679bd3712SFilipe Manana  *    properly, either intentionally or as a bug. One example where this is
362779bd3712SFilipe Manana  *    done intentionally is fsync, as it does not reserve any transaction units
362879bd3712SFilipe Manana  *    and ends up allocating a variable number of metadata extents for log
3629ecd84d54SFilipe Manana  *    tree extent buffers;
3630ecd84d54SFilipe Manana  *
3631ecd84d54SFilipe Manana  * 4) The task has reserved enough transaction units / metadata space, but right
3632ecd84d54SFilipe Manana  *    before it tries to allocate the last extent buffer it needs, a discard
3633ecd84d54SFilipe Manana  *    operation comes in and, temporarily, removes the last free space entry from
3634ecd84d54SFilipe Manana  *    the only metadata block group that had free space (discard starts by
3635ecd84d54SFilipe Manana  *    removing a free space entry from a block group, then does the discard
3636ecd84d54SFilipe Manana  *    operation and, once it's done, it adds back the free space entry to the
3637ecd84d54SFilipe Manana  *    block group).
363879bd3712SFilipe Manana  *
363979bd3712SFilipe Manana  * We also need this 2 phases setup when adding a device to a filesystem with
364079bd3712SFilipe Manana  * a seed device - we must create new metadata and system chunks without adding
364179bd3712SFilipe Manana  * any of the block group items to the chunk, extent and device btrees. If we
364279bd3712SFilipe Manana  * did not do it this way, we would get ENOSPC when attempting to update those
364379bd3712SFilipe Manana  * btrees, since all the chunks from the seed device are read-only.
364479bd3712SFilipe Manana  *
364579bd3712SFilipe Manana  * Phase 1 does the updates and insertions to the chunk btree because if we had
364679bd3712SFilipe Manana  * it done in phase 2 and have a thundering herd of tasks allocating chunks in
364779bd3712SFilipe Manana  * parallel, we risk having too many system chunks allocated by many tasks if
364879bd3712SFilipe Manana  * many tasks reach phase 1 without the previous ones completing phase 2. In the
364979bd3712SFilipe Manana  * extreme case this leads to exhaustion of the system chunk array in the
365079bd3712SFilipe Manana  * superblock. This is easier to trigger if using a btree node/leaf size of 64K
365179bd3712SFilipe Manana  * and with RAID filesystems (so we have more device items in the chunk btree).
365279bd3712SFilipe Manana  * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
365379bd3712SFilipe Manana  * the system chunk array due to concurrent allocations") provides more details.
365479bd3712SFilipe Manana  *
36552bb2e00eSFilipe Manana  * Allocation of system chunks does not happen through this function. A task that
36562bb2e00eSFilipe Manana  * needs to update the chunk btree (the only btree that uses system chunks), must
36572bb2e00eSFilipe Manana  * preallocate chunk space by calling either check_system_chunk() or
36582bb2e00eSFilipe Manana  * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or
36592bb2e00eSFilipe Manana  * metadata chunk or when removing a chunk, while the later is used before doing
36602bb2e00eSFilipe Manana  * a modification to the chunk btree - use cases for the later are adding,
36612bb2e00eSFilipe Manana  * removing and resizing a device as well as relocation of a system chunk.
36622bb2e00eSFilipe Manana  * See the comment below for more details.
366379bd3712SFilipe Manana  *
366479bd3712SFilipe Manana  * The reservation of system space, done through check_system_chunk(), as well
366579bd3712SFilipe Manana  * as all the updates and insertions into the chunk btree must be done while
366679bd3712SFilipe Manana  * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
366779bd3712SFilipe Manana  * an extent buffer from the chunks btree we never trigger allocation of a new
366879bd3712SFilipe Manana  * system chunk, which would result in a deadlock (trying to lock twice an
366979bd3712SFilipe Manana  * extent buffer of the chunk btree, first time before triggering the chunk
367079bd3712SFilipe Manana  * allocation and the second time during chunk allocation while attempting to
367179bd3712SFilipe Manana  * update the chunks btree). The system chunk array is also updated while holding
367279bd3712SFilipe Manana  * that mutex. The same logic applies to removing chunks - we must reserve system
367379bd3712SFilipe Manana  * space, update the chunk btree and the system chunk array in the superblock
367479bd3712SFilipe Manana  * while holding fs_info->chunk_mutex.
367579bd3712SFilipe Manana  *
367679bd3712SFilipe Manana  * This function, btrfs_chunk_alloc(), belongs to phase 1.
367779bd3712SFilipe Manana  *
367879bd3712SFilipe Manana  * If @force is CHUNK_ALLOC_FORCE:
367907730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
368007730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
368179bd3712SFilipe Manana  * If @force is NOT CHUNK_ALLOC_FORCE:
368207730d87SJosef Bacik  *    - return 0 if it doesn't need to allocate a new chunk,
368307730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
368407730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
368507730d87SJosef Bacik  */
368607730d87SJosef Bacik int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
368707730d87SJosef Bacik 		      enum btrfs_chunk_alloc_enum force)
368807730d87SJosef Bacik {
368907730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
369007730d87SJosef Bacik 	struct btrfs_space_info *space_info;
3691820c363bSNaohiro Aota 	struct btrfs_block_group *ret_bg;
369207730d87SJosef Bacik 	bool wait_for_alloc = false;
369307730d87SJosef Bacik 	bool should_alloc = false;
3694760e69c4SNaohiro Aota 	bool from_extent_allocation = false;
369507730d87SJosef Bacik 	int ret = 0;
369607730d87SJosef Bacik 
3697760e69c4SNaohiro Aota 	if (force == CHUNK_ALLOC_FORCE_FOR_EXTENT) {
3698760e69c4SNaohiro Aota 		from_extent_allocation = true;
3699760e69c4SNaohiro Aota 		force = CHUNK_ALLOC_FORCE;
3700760e69c4SNaohiro Aota 	}
3701760e69c4SNaohiro Aota 
370207730d87SJosef Bacik 	/* Don't re-enter if we're already allocating a chunk */
370307730d87SJosef Bacik 	if (trans->allocating_chunk)
370407730d87SJosef Bacik 		return -ENOSPC;
370579bd3712SFilipe Manana 	/*
37062bb2e00eSFilipe Manana 	 * Allocation of system chunks can not happen through this path, as we
37072bb2e00eSFilipe Manana 	 * could end up in a deadlock if we are allocating a data or metadata
37082bb2e00eSFilipe Manana 	 * chunk and there is another task modifying the chunk btree.
37092bb2e00eSFilipe Manana 	 *
37102bb2e00eSFilipe Manana 	 * This is because while we are holding the chunk mutex, we will attempt
37112bb2e00eSFilipe Manana 	 * to add the new chunk item to the chunk btree or update an existing
37122bb2e00eSFilipe Manana 	 * device item in the chunk btree, while the other task that is modifying
37132bb2e00eSFilipe Manana 	 * the chunk btree is attempting to COW an extent buffer while holding a
37142bb2e00eSFilipe Manana 	 * lock on it and on its parent - if the COW operation triggers a system
37152bb2e00eSFilipe Manana 	 * chunk allocation, then we can deadlock because we are holding the
37162bb2e00eSFilipe Manana 	 * chunk mutex and we may need to access that extent buffer or its parent
37172bb2e00eSFilipe Manana 	 * in order to add the chunk item or update a device item.
37182bb2e00eSFilipe Manana 	 *
37192bb2e00eSFilipe Manana 	 * Tasks that want to modify the chunk tree should reserve system space
37202bb2e00eSFilipe Manana 	 * before updating the chunk btree, by calling either
37212bb2e00eSFilipe Manana 	 * btrfs_reserve_chunk_metadata() or check_system_chunk().
37222bb2e00eSFilipe Manana 	 * It's possible that after a task reserves the space, it still ends up
37232bb2e00eSFilipe Manana 	 * here - this happens in the cases described above at do_chunk_alloc().
37242bb2e00eSFilipe Manana 	 * The task will have to either retry or fail.
372579bd3712SFilipe Manana 	 */
37262bb2e00eSFilipe Manana 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
372779bd3712SFilipe Manana 		return -ENOSPC;
372807730d87SJosef Bacik 
372907730d87SJosef Bacik 	space_info = btrfs_find_space_info(fs_info, flags);
373007730d87SJosef Bacik 	ASSERT(space_info);
373107730d87SJosef Bacik 
373207730d87SJosef Bacik 	do {
373307730d87SJosef Bacik 		spin_lock(&space_info->lock);
373407730d87SJosef Bacik 		if (force < space_info->force_alloc)
373507730d87SJosef Bacik 			force = space_info->force_alloc;
373607730d87SJosef Bacik 		should_alloc = should_alloc_chunk(fs_info, space_info, force);
373707730d87SJosef Bacik 		if (space_info->full) {
373807730d87SJosef Bacik 			/* No more free physical space */
373907730d87SJosef Bacik 			if (should_alloc)
374007730d87SJosef Bacik 				ret = -ENOSPC;
374107730d87SJosef Bacik 			else
374207730d87SJosef Bacik 				ret = 0;
374307730d87SJosef Bacik 			spin_unlock(&space_info->lock);
374407730d87SJosef Bacik 			return ret;
374507730d87SJosef Bacik 		} else if (!should_alloc) {
374607730d87SJosef Bacik 			spin_unlock(&space_info->lock);
374707730d87SJosef Bacik 			return 0;
374807730d87SJosef Bacik 		} else if (space_info->chunk_alloc) {
374907730d87SJosef Bacik 			/*
375007730d87SJosef Bacik 			 * Someone is already allocating, so we need to block
375107730d87SJosef Bacik 			 * until this someone is finished and then loop to
375207730d87SJosef Bacik 			 * recheck if we should continue with our allocation
375307730d87SJosef Bacik 			 * attempt.
375407730d87SJosef Bacik 			 */
375507730d87SJosef Bacik 			wait_for_alloc = true;
375607730d87SJosef Bacik 			spin_unlock(&space_info->lock);
375707730d87SJosef Bacik 			mutex_lock(&fs_info->chunk_mutex);
375807730d87SJosef Bacik 			mutex_unlock(&fs_info->chunk_mutex);
375907730d87SJosef Bacik 		} else {
376007730d87SJosef Bacik 			/* Proceed with allocation */
376107730d87SJosef Bacik 			space_info->chunk_alloc = 1;
376207730d87SJosef Bacik 			wait_for_alloc = false;
376307730d87SJosef Bacik 			spin_unlock(&space_info->lock);
376407730d87SJosef Bacik 		}
376507730d87SJosef Bacik 
376607730d87SJosef Bacik 		cond_resched();
376707730d87SJosef Bacik 	} while (wait_for_alloc);
376807730d87SJosef Bacik 
376907730d87SJosef Bacik 	mutex_lock(&fs_info->chunk_mutex);
377007730d87SJosef Bacik 	trans->allocating_chunk = true;
377107730d87SJosef Bacik 
377207730d87SJosef Bacik 	/*
377307730d87SJosef Bacik 	 * If we have mixed data/metadata chunks we want to make sure we keep
377407730d87SJosef Bacik 	 * allocating mixed chunks instead of individual chunks.
377507730d87SJosef Bacik 	 */
377607730d87SJosef Bacik 	if (btrfs_mixed_space_info(space_info))
377707730d87SJosef Bacik 		flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
377807730d87SJosef Bacik 
377907730d87SJosef Bacik 	/*
378007730d87SJosef Bacik 	 * if we're doing a data chunk, go ahead and make sure that
378107730d87SJosef Bacik 	 * we keep a reasonable number of metadata chunks allocated in the
378207730d87SJosef Bacik 	 * FS as well.
378307730d87SJosef Bacik 	 */
378407730d87SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
378507730d87SJosef Bacik 		fs_info->data_chunk_allocations++;
378607730d87SJosef Bacik 		if (!(fs_info->data_chunk_allocations %
378707730d87SJosef Bacik 		      fs_info->metadata_ratio))
378807730d87SJosef Bacik 			force_metadata_allocation(fs_info);
378907730d87SJosef Bacik 	}
379007730d87SJosef Bacik 
3791820c363bSNaohiro Aota 	ret_bg = do_chunk_alloc(trans, flags);
379207730d87SJosef Bacik 	trans->allocating_chunk = false;
379307730d87SJosef Bacik 
3794760e69c4SNaohiro Aota 	if (IS_ERR(ret_bg)) {
3795820c363bSNaohiro Aota 		ret = PTR_ERR(ret_bg);
3796760e69c4SNaohiro Aota 	} else if (from_extent_allocation) {
3797760e69c4SNaohiro Aota 		/*
3798760e69c4SNaohiro Aota 		 * New block group is likely to be used soon. Try to activate
3799760e69c4SNaohiro Aota 		 * it now. Failure is OK for now.
3800760e69c4SNaohiro Aota 		 */
3801760e69c4SNaohiro Aota 		btrfs_zone_activate(ret_bg);
3802760e69c4SNaohiro Aota 	}
3803760e69c4SNaohiro Aota 
3804760e69c4SNaohiro Aota 	if (!ret)
3805820c363bSNaohiro Aota 		btrfs_put_block_group(ret_bg);
3806820c363bSNaohiro Aota 
380707730d87SJosef Bacik 	spin_lock(&space_info->lock);
380807730d87SJosef Bacik 	if (ret < 0) {
380907730d87SJosef Bacik 		if (ret == -ENOSPC)
381007730d87SJosef Bacik 			space_info->full = 1;
381107730d87SJosef Bacik 		else
381207730d87SJosef Bacik 			goto out;
381307730d87SJosef Bacik 	} else {
381407730d87SJosef Bacik 		ret = 1;
381507730d87SJosef Bacik 		space_info->max_extent_size = 0;
381607730d87SJosef Bacik 	}
381707730d87SJosef Bacik 
381807730d87SJosef Bacik 	space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
381907730d87SJosef Bacik out:
382007730d87SJosef Bacik 	space_info->chunk_alloc = 0;
382107730d87SJosef Bacik 	spin_unlock(&space_info->lock);
382207730d87SJosef Bacik 	mutex_unlock(&fs_info->chunk_mutex);
382307730d87SJosef Bacik 
382407730d87SJosef Bacik 	return ret;
382507730d87SJosef Bacik }
382607730d87SJosef Bacik 
382707730d87SJosef Bacik static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
382807730d87SJosef Bacik {
382907730d87SJosef Bacik 	u64 num_dev;
383007730d87SJosef Bacik 
383107730d87SJosef Bacik 	num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
383207730d87SJosef Bacik 	if (!num_dev)
383307730d87SJosef Bacik 		num_dev = fs_info->fs_devices->rw_devices;
383407730d87SJosef Bacik 
383507730d87SJosef Bacik 	return num_dev;
383607730d87SJosef Bacik }
383707730d87SJosef Bacik 
38382bb2e00eSFilipe Manana static void reserve_chunk_space(struct btrfs_trans_handle *trans,
38392bb2e00eSFilipe Manana 				u64 bytes,
38402bb2e00eSFilipe Manana 				u64 type)
384107730d87SJosef Bacik {
384207730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
384307730d87SJosef Bacik 	struct btrfs_space_info *info;
384407730d87SJosef Bacik 	u64 left;
384507730d87SJosef Bacik 	int ret = 0;
384607730d87SJosef Bacik 
384707730d87SJosef Bacik 	/*
384807730d87SJosef Bacik 	 * Needed because we can end up allocating a system chunk and for an
384907730d87SJosef Bacik 	 * atomic and race free space reservation in the chunk block reserve.
385007730d87SJosef Bacik 	 */
385107730d87SJosef Bacik 	lockdep_assert_held(&fs_info->chunk_mutex);
385207730d87SJosef Bacik 
385307730d87SJosef Bacik 	info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
385407730d87SJosef Bacik 	spin_lock(&info->lock);
385507730d87SJosef Bacik 	left = info->total_bytes - btrfs_space_info_used(info, true);
385607730d87SJosef Bacik 	spin_unlock(&info->lock);
385707730d87SJosef Bacik 
38582bb2e00eSFilipe Manana 	if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
385907730d87SJosef Bacik 		btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
38602bb2e00eSFilipe Manana 			   left, bytes, type);
386107730d87SJosef Bacik 		btrfs_dump_space_info(fs_info, info, 0, 0);
386207730d87SJosef Bacik 	}
386307730d87SJosef Bacik 
38642bb2e00eSFilipe Manana 	if (left < bytes) {
386507730d87SJosef Bacik 		u64 flags = btrfs_system_alloc_profile(fs_info);
386679bd3712SFilipe Manana 		struct btrfs_block_group *bg;
386707730d87SJosef Bacik 
386807730d87SJosef Bacik 		/*
386907730d87SJosef Bacik 		 * Ignore failure to create system chunk. We might end up not
387007730d87SJosef Bacik 		 * needing it, as we might not need to COW all nodes/leafs from
387107730d87SJosef Bacik 		 * the paths we visit in the chunk tree (they were already COWed
387207730d87SJosef Bacik 		 * or created in the current transaction for example).
387307730d87SJosef Bacik 		 */
3874f6f39f7aSNikolay Borisov 		bg = btrfs_create_chunk(trans, flags);
387579bd3712SFilipe Manana 		if (IS_ERR(bg)) {
387679bd3712SFilipe Manana 			ret = PTR_ERR(bg);
38772bb2e00eSFilipe Manana 		} else {
387879bd3712SFilipe Manana 			/*
387979bd3712SFilipe Manana 			 * If we fail to add the chunk item here, we end up
388079bd3712SFilipe Manana 			 * trying again at phase 2 of chunk allocation, at
388179bd3712SFilipe Manana 			 * btrfs_create_pending_block_groups(). So ignore
38822bb2e00eSFilipe Manana 			 * any error here. An ENOSPC here could happen, due to
38832bb2e00eSFilipe Manana 			 * the cases described at do_chunk_alloc() - the system
38842bb2e00eSFilipe Manana 			 * block group we just created was just turned into RO
38852bb2e00eSFilipe Manana 			 * mode by a scrub for example, or a running discard
38862bb2e00eSFilipe Manana 			 * temporarily removed its free space entries, etc.
388779bd3712SFilipe Manana 			 */
388879bd3712SFilipe Manana 			btrfs_chunk_alloc_add_chunk_item(trans, bg);
388979bd3712SFilipe Manana 		}
389007730d87SJosef Bacik 	}
389107730d87SJosef Bacik 
389207730d87SJosef Bacik 	if (!ret) {
38939270501cSJosef Bacik 		ret = btrfs_block_rsv_add(fs_info,
389407730d87SJosef Bacik 					  &fs_info->chunk_block_rsv,
38952bb2e00eSFilipe Manana 					  bytes, BTRFS_RESERVE_NO_FLUSH);
38961cb3db1cSFilipe Manana 		if (!ret)
38972bb2e00eSFilipe Manana 			trans->chunk_bytes_reserved += bytes;
389807730d87SJosef Bacik 	}
389907730d87SJosef Bacik }
390007730d87SJosef Bacik 
39012bb2e00eSFilipe Manana /*
39022bb2e00eSFilipe Manana  * Reserve space in the system space for allocating or removing a chunk.
39032bb2e00eSFilipe Manana  * The caller must be holding fs_info->chunk_mutex.
39042bb2e00eSFilipe Manana  */
39052bb2e00eSFilipe Manana void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
39062bb2e00eSFilipe Manana {
39072bb2e00eSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
39082bb2e00eSFilipe Manana 	const u64 num_devs = get_profile_num_devs(fs_info, type);
39092bb2e00eSFilipe Manana 	u64 bytes;
39102bb2e00eSFilipe Manana 
39112bb2e00eSFilipe Manana 	/* num_devs device items to update and 1 chunk item to add or remove. */
39122bb2e00eSFilipe Manana 	bytes = btrfs_calc_metadata_size(fs_info, num_devs) +
39132bb2e00eSFilipe Manana 		btrfs_calc_insert_metadata_size(fs_info, 1);
39142bb2e00eSFilipe Manana 
39152bb2e00eSFilipe Manana 	reserve_chunk_space(trans, bytes, type);
39162bb2e00eSFilipe Manana }
39172bb2e00eSFilipe Manana 
39182bb2e00eSFilipe Manana /*
39192bb2e00eSFilipe Manana  * Reserve space in the system space, if needed, for doing a modification to the
39202bb2e00eSFilipe Manana  * chunk btree.
39212bb2e00eSFilipe Manana  *
39222bb2e00eSFilipe Manana  * @trans:		A transaction handle.
39232bb2e00eSFilipe Manana  * @is_item_insertion:	Indicate if the modification is for inserting a new item
39242bb2e00eSFilipe Manana  *			in the chunk btree or if it's for the deletion or update
39252bb2e00eSFilipe Manana  *			of an existing item.
39262bb2e00eSFilipe Manana  *
39272bb2e00eSFilipe Manana  * This is used in a context where we need to update the chunk btree outside
39282bb2e00eSFilipe Manana  * block group allocation and removal, to avoid a deadlock with a concurrent
39292bb2e00eSFilipe Manana  * task that is allocating a metadata or data block group and therefore needs to
39302bb2e00eSFilipe Manana  * update the chunk btree while holding the chunk mutex. After the update to the
39312bb2e00eSFilipe Manana  * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called.
39322bb2e00eSFilipe Manana  *
39332bb2e00eSFilipe Manana  */
39342bb2e00eSFilipe Manana void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans,
39352bb2e00eSFilipe Manana 				  bool is_item_insertion)
39362bb2e00eSFilipe Manana {
39372bb2e00eSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
39382bb2e00eSFilipe Manana 	u64 bytes;
39392bb2e00eSFilipe Manana 
39402bb2e00eSFilipe Manana 	if (is_item_insertion)
39412bb2e00eSFilipe Manana 		bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
39422bb2e00eSFilipe Manana 	else
39432bb2e00eSFilipe Manana 		bytes = btrfs_calc_metadata_size(fs_info, 1);
39442bb2e00eSFilipe Manana 
39452bb2e00eSFilipe Manana 	mutex_lock(&fs_info->chunk_mutex);
39462bb2e00eSFilipe Manana 	reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM);
39472bb2e00eSFilipe Manana 	mutex_unlock(&fs_info->chunk_mutex);
39482bb2e00eSFilipe Manana }
39492bb2e00eSFilipe Manana 
39503e43c279SJosef Bacik void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
39513e43c279SJosef Bacik {
395232da5386SDavid Sterba 	struct btrfs_block_group *block_group;
39533e43c279SJosef Bacik 	u64 last = 0;
39543e43c279SJosef Bacik 
39553e43c279SJosef Bacik 	while (1) {
39563e43c279SJosef Bacik 		struct inode *inode;
39573e43c279SJosef Bacik 
39583e43c279SJosef Bacik 		block_group = btrfs_lookup_first_block_group(info, last);
39593e43c279SJosef Bacik 		while (block_group) {
39603e43c279SJosef Bacik 			btrfs_wait_block_group_cache_done(block_group);
39613e43c279SJosef Bacik 			spin_lock(&block_group->lock);
39623e43c279SJosef Bacik 			if (block_group->iref)
39633e43c279SJosef Bacik 				break;
39643e43c279SJosef Bacik 			spin_unlock(&block_group->lock);
39653e43c279SJosef Bacik 			block_group = btrfs_next_block_group(block_group);
39663e43c279SJosef Bacik 		}
39673e43c279SJosef Bacik 		if (!block_group) {
39683e43c279SJosef Bacik 			if (last == 0)
39693e43c279SJosef Bacik 				break;
39703e43c279SJosef Bacik 			last = 0;
39713e43c279SJosef Bacik 			continue;
39723e43c279SJosef Bacik 		}
39733e43c279SJosef Bacik 
39743e43c279SJosef Bacik 		inode = block_group->inode;
39753e43c279SJosef Bacik 		block_group->iref = 0;
39763e43c279SJosef Bacik 		block_group->inode = NULL;
39773e43c279SJosef Bacik 		spin_unlock(&block_group->lock);
39783e43c279SJosef Bacik 		ASSERT(block_group->io_ctl.inode == NULL);
39793e43c279SJosef Bacik 		iput(inode);
3980b3470b5dSDavid Sterba 		last = block_group->start + block_group->length;
39813e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
39823e43c279SJosef Bacik 	}
39833e43c279SJosef Bacik }
39843e43c279SJosef Bacik 
39853e43c279SJosef Bacik /*
39863e43c279SJosef Bacik  * Must be called only after stopping all workers, since we could have block
39873e43c279SJosef Bacik  * group caching kthreads running, and therefore they could race with us if we
39883e43c279SJosef Bacik  * freed the block groups before stopping them.
39893e43c279SJosef Bacik  */
39903e43c279SJosef Bacik int btrfs_free_block_groups(struct btrfs_fs_info *info)
39913e43c279SJosef Bacik {
399232da5386SDavid Sterba 	struct btrfs_block_group *block_group;
39933e43c279SJosef Bacik 	struct btrfs_space_info *space_info;
39943e43c279SJosef Bacik 	struct btrfs_caching_control *caching_ctl;
39953e43c279SJosef Bacik 	struct rb_node *n;
39963e43c279SJosef Bacik 
399716b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
39983e43c279SJosef Bacik 	while (!list_empty(&info->caching_block_groups)) {
39993e43c279SJosef Bacik 		caching_ctl = list_entry(info->caching_block_groups.next,
40003e43c279SJosef Bacik 					 struct btrfs_caching_control, list);
40013e43c279SJosef Bacik 		list_del(&caching_ctl->list);
40023e43c279SJosef Bacik 		btrfs_put_caching_control(caching_ctl);
40033e43c279SJosef Bacik 	}
400416b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
40053e43c279SJosef Bacik 
40063e43c279SJosef Bacik 	spin_lock(&info->unused_bgs_lock);
40073e43c279SJosef Bacik 	while (!list_empty(&info->unused_bgs)) {
40083e43c279SJosef Bacik 		block_group = list_first_entry(&info->unused_bgs,
400932da5386SDavid Sterba 					       struct btrfs_block_group,
40103e43c279SJosef Bacik 					       bg_list);
40113e43c279SJosef Bacik 		list_del_init(&block_group->bg_list);
40123e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
40133e43c279SJosef Bacik 	}
40143e43c279SJosef Bacik 
401518bb8bbfSJohannes Thumshirn 	while (!list_empty(&info->reclaim_bgs)) {
401618bb8bbfSJohannes Thumshirn 		block_group = list_first_entry(&info->reclaim_bgs,
401718bb8bbfSJohannes Thumshirn 					       struct btrfs_block_group,
401818bb8bbfSJohannes Thumshirn 					       bg_list);
401918bb8bbfSJohannes Thumshirn 		list_del_init(&block_group->bg_list);
402018bb8bbfSJohannes Thumshirn 		btrfs_put_block_group(block_group);
402118bb8bbfSJohannes Thumshirn 	}
402218bb8bbfSJohannes Thumshirn 	spin_unlock(&info->unused_bgs_lock);
402318bb8bbfSJohannes Thumshirn 
4024afba2bc0SNaohiro Aota 	spin_lock(&info->zone_active_bgs_lock);
4025afba2bc0SNaohiro Aota 	while (!list_empty(&info->zone_active_bgs)) {
4026afba2bc0SNaohiro Aota 		block_group = list_first_entry(&info->zone_active_bgs,
4027afba2bc0SNaohiro Aota 					       struct btrfs_block_group,
4028afba2bc0SNaohiro Aota 					       active_bg_list);
4029afba2bc0SNaohiro Aota 		list_del_init(&block_group->active_bg_list);
4030afba2bc0SNaohiro Aota 		btrfs_put_block_group(block_group);
4031afba2bc0SNaohiro Aota 	}
4032afba2bc0SNaohiro Aota 	spin_unlock(&info->zone_active_bgs_lock);
4033afba2bc0SNaohiro Aota 
403416b0c258SFilipe Manana 	write_lock(&info->block_group_cache_lock);
403508dddb29SFilipe Manana 	while ((n = rb_last(&info->block_group_cache_tree.rb_root)) != NULL) {
403632da5386SDavid Sterba 		block_group = rb_entry(n, struct btrfs_block_group,
40373e43c279SJosef Bacik 				       cache_node);
403808dddb29SFilipe Manana 		rb_erase_cached(&block_group->cache_node,
40393e43c279SJosef Bacik 				&info->block_group_cache_tree);
40403e43c279SJosef Bacik 		RB_CLEAR_NODE(&block_group->cache_node);
404116b0c258SFilipe Manana 		write_unlock(&info->block_group_cache_lock);
40423e43c279SJosef Bacik 
40433e43c279SJosef Bacik 		down_write(&block_group->space_info->groups_sem);
40443e43c279SJosef Bacik 		list_del(&block_group->list);
40453e43c279SJosef Bacik 		up_write(&block_group->space_info->groups_sem);
40463e43c279SJosef Bacik 
40473e43c279SJosef Bacik 		/*
40483e43c279SJosef Bacik 		 * We haven't cached this block group, which means we could
40493e43c279SJosef Bacik 		 * possibly have excluded extents on this block group.
40503e43c279SJosef Bacik 		 */
40513e43c279SJosef Bacik 		if (block_group->cached == BTRFS_CACHE_NO ||
40523e43c279SJosef Bacik 		    block_group->cached == BTRFS_CACHE_ERROR)
40533e43c279SJosef Bacik 			btrfs_free_excluded_extents(block_group);
40543e43c279SJosef Bacik 
40553e43c279SJosef Bacik 		btrfs_remove_free_space_cache(block_group);
40563e43c279SJosef Bacik 		ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
40573e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->dirty_list));
40583e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->io_list));
40593e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->bg_list));
406048aaeebeSJosef Bacik 		ASSERT(refcount_read(&block_group->refs) == 1);
4061195a49eaSFilipe Manana 		ASSERT(block_group->swap_extents == 0);
40623e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
40633e43c279SJosef Bacik 
406416b0c258SFilipe Manana 		write_lock(&info->block_group_cache_lock);
40653e43c279SJosef Bacik 	}
406616b0c258SFilipe Manana 	write_unlock(&info->block_group_cache_lock);
40673e43c279SJosef Bacik 
40683e43c279SJosef Bacik 	btrfs_release_global_block_rsv(info);
40693e43c279SJosef Bacik 
40703e43c279SJosef Bacik 	while (!list_empty(&info->space_info)) {
40713e43c279SJosef Bacik 		space_info = list_entry(info->space_info.next,
40723e43c279SJosef Bacik 					struct btrfs_space_info,
40733e43c279SJosef Bacik 					list);
40743e43c279SJosef Bacik 
40753e43c279SJosef Bacik 		/*
40763e43c279SJosef Bacik 		 * Do not hide this behind enospc_debug, this is actually
40773e43c279SJosef Bacik 		 * important and indicates a real bug if this happens.
40783e43c279SJosef Bacik 		 */
40793e43c279SJosef Bacik 		if (WARN_ON(space_info->bytes_pinned > 0 ||
40803e43c279SJosef Bacik 			    space_info->bytes_may_use > 0))
40813e43c279SJosef Bacik 			btrfs_dump_space_info(info, space_info, 0, 0);
408240cdc509SFilipe Manana 
408340cdc509SFilipe Manana 		/*
408440cdc509SFilipe Manana 		 * If there was a failure to cleanup a log tree, very likely due
408540cdc509SFilipe Manana 		 * to an IO failure on a writeback attempt of one or more of its
408640cdc509SFilipe Manana 		 * extent buffers, we could not do proper (and cheap) unaccounting
408740cdc509SFilipe Manana 		 * of their reserved space, so don't warn on bytes_reserved > 0 in
408840cdc509SFilipe Manana 		 * that case.
408940cdc509SFilipe Manana 		 */
409040cdc509SFilipe Manana 		if (!(space_info->flags & BTRFS_BLOCK_GROUP_METADATA) ||
409140cdc509SFilipe Manana 		    !BTRFS_FS_LOG_CLEANUP_ERROR(info)) {
409240cdc509SFilipe Manana 			if (WARN_ON(space_info->bytes_reserved > 0))
409340cdc509SFilipe Manana 				btrfs_dump_space_info(info, space_info, 0, 0);
409440cdc509SFilipe Manana 		}
409540cdc509SFilipe Manana 
4096d611add4SFilipe Manana 		WARN_ON(space_info->reclaim_size > 0);
40973e43c279SJosef Bacik 		list_del(&space_info->list);
40983e43c279SJosef Bacik 		btrfs_sysfs_remove_space_info(space_info);
40993e43c279SJosef Bacik 	}
41003e43c279SJosef Bacik 	return 0;
41013e43c279SJosef Bacik }
4102684b752bSFilipe Manana 
4103684b752bSFilipe Manana void btrfs_freeze_block_group(struct btrfs_block_group *cache)
4104684b752bSFilipe Manana {
4105684b752bSFilipe Manana 	atomic_inc(&cache->frozen);
4106684b752bSFilipe Manana }
4107684b752bSFilipe Manana 
4108684b752bSFilipe Manana void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
4109684b752bSFilipe Manana {
4110684b752bSFilipe Manana 	struct btrfs_fs_info *fs_info = block_group->fs_info;
4111684b752bSFilipe Manana 	struct extent_map_tree *em_tree;
4112684b752bSFilipe Manana 	struct extent_map *em;
4113684b752bSFilipe Manana 	bool cleanup;
4114684b752bSFilipe Manana 
4115684b752bSFilipe Manana 	spin_lock(&block_group->lock);
4116684b752bSFilipe Manana 	cleanup = (atomic_dec_and_test(&block_group->frozen) &&
4117684b752bSFilipe Manana 		   block_group->removed);
4118684b752bSFilipe Manana 	spin_unlock(&block_group->lock);
4119684b752bSFilipe Manana 
4120684b752bSFilipe Manana 	if (cleanup) {
4121684b752bSFilipe Manana 		em_tree = &fs_info->mapping_tree;
4122684b752bSFilipe Manana 		write_lock(&em_tree->lock);
4123684b752bSFilipe Manana 		em = lookup_extent_mapping(em_tree, block_group->start,
4124684b752bSFilipe Manana 					   1);
4125684b752bSFilipe Manana 		BUG_ON(!em); /* logic error, can't happen */
4126684b752bSFilipe Manana 		remove_extent_mapping(em_tree, em);
4127684b752bSFilipe Manana 		write_unlock(&em_tree->lock);
4128684b752bSFilipe Manana 
4129684b752bSFilipe Manana 		/* once for us and once for the tree */
4130684b752bSFilipe Manana 		free_extent_map(em);
4131684b752bSFilipe Manana 		free_extent_map(em);
4132684b752bSFilipe Manana 
4133684b752bSFilipe Manana 		/*
4134684b752bSFilipe Manana 		 * We may have left one free space entry and other possible
4135684b752bSFilipe Manana 		 * tasks trimming this block group have left 1 entry each one.
4136684b752bSFilipe Manana 		 * Free them if any.
4137684b752bSFilipe Manana 		 */
4138684b752bSFilipe Manana 		__btrfs_remove_free_space_cache(block_group->free_space_ctl);
4139684b752bSFilipe Manana 	}
4140684b752bSFilipe Manana }
4141195a49eaSFilipe Manana 
4142195a49eaSFilipe Manana bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
4143195a49eaSFilipe Manana {
4144195a49eaSFilipe Manana 	bool ret = true;
4145195a49eaSFilipe Manana 
4146195a49eaSFilipe Manana 	spin_lock(&bg->lock);
4147195a49eaSFilipe Manana 	if (bg->ro)
4148195a49eaSFilipe Manana 		ret = false;
4149195a49eaSFilipe Manana 	else
4150195a49eaSFilipe Manana 		bg->swap_extents++;
4151195a49eaSFilipe Manana 	spin_unlock(&bg->lock);
4152195a49eaSFilipe Manana 
4153195a49eaSFilipe Manana 	return ret;
4154195a49eaSFilipe Manana }
4155195a49eaSFilipe Manana 
4156195a49eaSFilipe Manana void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
4157195a49eaSFilipe Manana {
4158195a49eaSFilipe Manana 	spin_lock(&bg->lock);
4159195a49eaSFilipe Manana 	ASSERT(!bg->ro);
4160195a49eaSFilipe Manana 	ASSERT(bg->swap_extents >= amount);
4161195a49eaSFilipe Manana 	bg->swap_extents -= amount;
4162195a49eaSFilipe Manana 	spin_unlock(&bg->lock);
4163195a49eaSFilipe Manana }
4164