xref: /linux/fs/btrfs/block-group.c (revision a7a63acc6575ded6f48ab293e275e8b903325e54)
12e405ad8SJosef Bacik // SPDX-License-Identifier: GPL-2.0
22e405ad8SJosef Bacik 
3784352feSDavid Sterba #include "misc.h"
42e405ad8SJosef Bacik #include "ctree.h"
52e405ad8SJosef Bacik #include "block-group.h"
63eeb3226SJosef Bacik #include "space-info.h"
79f21246dSJosef Bacik #include "disk-io.h"
89f21246dSJosef Bacik #include "free-space-cache.h"
99f21246dSJosef Bacik #include "free-space-tree.h"
10e3e0520bSJosef Bacik #include "disk-io.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"
192e405ad8SJosef Bacik 
20878d7b67SJosef Bacik /*
21878d7b67SJosef Bacik  * Return target flags in extended format or 0 if restripe for this chunk_type
22878d7b67SJosef Bacik  * is not in progress
23878d7b67SJosef Bacik  *
24878d7b67SJosef Bacik  * Should be called with balance_lock held
25878d7b67SJosef Bacik  */
26e11c0406SJosef Bacik static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
27878d7b67SJosef Bacik {
28878d7b67SJosef Bacik 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
29878d7b67SJosef Bacik 	u64 target = 0;
30878d7b67SJosef Bacik 
31878d7b67SJosef Bacik 	if (!bctl)
32878d7b67SJosef Bacik 		return 0;
33878d7b67SJosef Bacik 
34878d7b67SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA &&
35878d7b67SJosef Bacik 	    bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
36878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
37878d7b67SJosef Bacik 	} else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
38878d7b67SJosef Bacik 		   bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
39878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
40878d7b67SJosef Bacik 	} else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
41878d7b67SJosef Bacik 		   bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
42878d7b67SJosef Bacik 		target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
43878d7b67SJosef Bacik 	}
44878d7b67SJosef Bacik 
45878d7b67SJosef Bacik 	return target;
46878d7b67SJosef Bacik }
47878d7b67SJosef Bacik 
48878d7b67SJosef Bacik /*
49878d7b67SJosef Bacik  * @flags: available profiles in extended format (see ctree.h)
50878d7b67SJosef Bacik  *
51878d7b67SJosef Bacik  * Return reduced profile in chunk format.  If profile changing is in progress
52878d7b67SJosef Bacik  * (either running or paused) picks the target profile (if it's already
53878d7b67SJosef Bacik  * available), otherwise falls back to plain reducing.
54878d7b67SJosef Bacik  */
55878d7b67SJosef Bacik static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
56878d7b67SJosef Bacik {
57878d7b67SJosef Bacik 	u64 num_devices = fs_info->fs_devices->rw_devices;
58878d7b67SJosef Bacik 	u64 target;
59878d7b67SJosef Bacik 	u64 raid_type;
60878d7b67SJosef Bacik 	u64 allowed = 0;
61878d7b67SJosef Bacik 
62878d7b67SJosef Bacik 	/*
63878d7b67SJosef Bacik 	 * See if restripe for this chunk_type is in progress, if so try to
64878d7b67SJosef Bacik 	 * reduce to the target profile
65878d7b67SJosef Bacik 	 */
66878d7b67SJosef Bacik 	spin_lock(&fs_info->balance_lock);
67e11c0406SJosef Bacik 	target = get_restripe_target(fs_info, flags);
68878d7b67SJosef Bacik 	if (target) {
69878d7b67SJosef Bacik 		/* Pick target profile only if it's already available */
70878d7b67SJosef Bacik 		if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
71878d7b67SJosef Bacik 			spin_unlock(&fs_info->balance_lock);
72878d7b67SJosef Bacik 			return extended_to_chunk(target);
73878d7b67SJosef Bacik 		}
74878d7b67SJosef Bacik 	}
75878d7b67SJosef Bacik 	spin_unlock(&fs_info->balance_lock);
76878d7b67SJosef Bacik 
77878d7b67SJosef Bacik 	/* First, mask out the RAID levels which aren't possible */
78878d7b67SJosef Bacik 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
79878d7b67SJosef Bacik 		if (num_devices >= btrfs_raid_array[raid_type].devs_min)
80878d7b67SJosef Bacik 			allowed |= btrfs_raid_array[raid_type].bg_flag;
81878d7b67SJosef Bacik 	}
82878d7b67SJosef Bacik 	allowed &= flags;
83878d7b67SJosef Bacik 
84878d7b67SJosef Bacik 	if (allowed & BTRFS_BLOCK_GROUP_RAID6)
85878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID6;
86878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
87878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID5;
88878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
89878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID10;
90878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
91878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID1;
92878d7b67SJosef Bacik 	else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
93878d7b67SJosef Bacik 		allowed = BTRFS_BLOCK_GROUP_RAID0;
94878d7b67SJosef Bacik 
95878d7b67SJosef Bacik 	flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
96878d7b67SJosef Bacik 
97878d7b67SJosef Bacik 	return extended_to_chunk(flags | allowed);
98878d7b67SJosef Bacik }
99878d7b67SJosef Bacik 
100ef0a82daSJohannes Thumshirn u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
101878d7b67SJosef Bacik {
102878d7b67SJosef Bacik 	unsigned seq;
103878d7b67SJosef Bacik 	u64 flags;
104878d7b67SJosef Bacik 
105878d7b67SJosef Bacik 	do {
106878d7b67SJosef Bacik 		flags = orig_flags;
107878d7b67SJosef Bacik 		seq = read_seqbegin(&fs_info->profiles_lock);
108878d7b67SJosef Bacik 
109878d7b67SJosef Bacik 		if (flags & BTRFS_BLOCK_GROUP_DATA)
110878d7b67SJosef Bacik 			flags |= fs_info->avail_data_alloc_bits;
111878d7b67SJosef Bacik 		else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
112878d7b67SJosef Bacik 			flags |= fs_info->avail_system_alloc_bits;
113878d7b67SJosef Bacik 		else if (flags & BTRFS_BLOCK_GROUP_METADATA)
114878d7b67SJosef Bacik 			flags |= fs_info->avail_metadata_alloc_bits;
115878d7b67SJosef Bacik 	} while (read_seqretry(&fs_info->profiles_lock, seq));
116878d7b67SJosef Bacik 
117878d7b67SJosef Bacik 	return btrfs_reduce_alloc_profile(fs_info, flags);
118878d7b67SJosef Bacik }
119878d7b67SJosef Bacik 
12032da5386SDavid Sterba void btrfs_get_block_group(struct btrfs_block_group *cache)
1213cad1284SJosef Bacik {
1223cad1284SJosef Bacik 	atomic_inc(&cache->count);
1233cad1284SJosef Bacik }
1243cad1284SJosef Bacik 
12532da5386SDavid Sterba void btrfs_put_block_group(struct btrfs_block_group *cache)
1263cad1284SJosef Bacik {
1273cad1284SJosef Bacik 	if (atomic_dec_and_test(&cache->count)) {
1283cad1284SJosef Bacik 		WARN_ON(cache->pinned > 0);
1293cad1284SJosef Bacik 		WARN_ON(cache->reserved > 0);
1303cad1284SJosef Bacik 
1313cad1284SJosef Bacik 		/*
132b0643e59SDennis Zhou 		 * A block_group shouldn't be on the discard_list anymore.
133b0643e59SDennis Zhou 		 * Remove the block_group from the discard_list to prevent us
134b0643e59SDennis Zhou 		 * from causing a panic due to NULL pointer dereference.
135b0643e59SDennis Zhou 		 */
136b0643e59SDennis Zhou 		if (WARN_ON(!list_empty(&cache->discard_list)))
137b0643e59SDennis Zhou 			btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
138b0643e59SDennis Zhou 						  cache);
139b0643e59SDennis Zhou 
140b0643e59SDennis Zhou 		/*
1413cad1284SJosef Bacik 		 * If not empty, someone is still holding mutex of
1423cad1284SJosef Bacik 		 * full_stripe_lock, which can only be released by caller.
1433cad1284SJosef Bacik 		 * And it will definitely cause use-after-free when caller
1443cad1284SJosef Bacik 		 * tries to release full stripe lock.
1453cad1284SJosef Bacik 		 *
1463cad1284SJosef Bacik 		 * No better way to resolve, but only to warn.
1473cad1284SJosef Bacik 		 */
1483cad1284SJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
1493cad1284SJosef Bacik 		kfree(cache->free_space_ctl);
1503cad1284SJosef Bacik 		kfree(cache);
1513cad1284SJosef Bacik 	}
1523cad1284SJosef Bacik }
1533cad1284SJosef Bacik 
1542e405ad8SJosef Bacik /*
1554358d963SJosef Bacik  * This adds the block group to the fs_info rb tree for the block group cache
1564358d963SJosef Bacik  */
1574358d963SJosef Bacik static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
15832da5386SDavid Sterba 				       struct btrfs_block_group *block_group)
1594358d963SJosef Bacik {
1604358d963SJosef Bacik 	struct rb_node **p;
1614358d963SJosef Bacik 	struct rb_node *parent = NULL;
16232da5386SDavid Sterba 	struct btrfs_block_group *cache;
1634358d963SJosef Bacik 
1644358d963SJosef Bacik 	spin_lock(&info->block_group_cache_lock);
1654358d963SJosef Bacik 	p = &info->block_group_cache_tree.rb_node;
1664358d963SJosef Bacik 
1674358d963SJosef Bacik 	while (*p) {
1684358d963SJosef Bacik 		parent = *p;
16932da5386SDavid Sterba 		cache = rb_entry(parent, struct btrfs_block_group, cache_node);
170b3470b5dSDavid Sterba 		if (block_group->start < cache->start) {
1714358d963SJosef Bacik 			p = &(*p)->rb_left;
172b3470b5dSDavid Sterba 		} else if (block_group->start > cache->start) {
1734358d963SJosef Bacik 			p = &(*p)->rb_right;
1744358d963SJosef Bacik 		} else {
1754358d963SJosef Bacik 			spin_unlock(&info->block_group_cache_lock);
1764358d963SJosef Bacik 			return -EEXIST;
1774358d963SJosef Bacik 		}
1784358d963SJosef Bacik 	}
1794358d963SJosef Bacik 
1804358d963SJosef Bacik 	rb_link_node(&block_group->cache_node, parent, p);
1814358d963SJosef Bacik 	rb_insert_color(&block_group->cache_node,
1824358d963SJosef Bacik 			&info->block_group_cache_tree);
1834358d963SJosef Bacik 
184b3470b5dSDavid Sterba 	if (info->first_logical_byte > block_group->start)
185b3470b5dSDavid Sterba 		info->first_logical_byte = block_group->start;
1864358d963SJosef Bacik 
1874358d963SJosef Bacik 	spin_unlock(&info->block_group_cache_lock);
1884358d963SJosef Bacik 
1894358d963SJosef Bacik 	return 0;
1904358d963SJosef Bacik }
1914358d963SJosef Bacik 
1924358d963SJosef Bacik /*
1932e405ad8SJosef Bacik  * This will return the block group at or after bytenr if contains is 0, else
1942e405ad8SJosef Bacik  * it will return the block group that contains the bytenr
1952e405ad8SJosef Bacik  */
19632da5386SDavid Sterba static struct btrfs_block_group *block_group_cache_tree_search(
1972e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr, int contains)
1982e405ad8SJosef Bacik {
19932da5386SDavid Sterba 	struct btrfs_block_group *cache, *ret = NULL;
2002e405ad8SJosef Bacik 	struct rb_node *n;
2012e405ad8SJosef Bacik 	u64 end, start;
2022e405ad8SJosef Bacik 
2032e405ad8SJosef Bacik 	spin_lock(&info->block_group_cache_lock);
2042e405ad8SJosef Bacik 	n = info->block_group_cache_tree.rb_node;
2052e405ad8SJosef Bacik 
2062e405ad8SJosef Bacik 	while (n) {
20732da5386SDavid Sterba 		cache = rb_entry(n, struct btrfs_block_group, cache_node);
208b3470b5dSDavid Sterba 		end = cache->start + cache->length - 1;
209b3470b5dSDavid Sterba 		start = cache->start;
2102e405ad8SJosef Bacik 
2112e405ad8SJosef Bacik 		if (bytenr < start) {
212b3470b5dSDavid Sterba 			if (!contains && (!ret || start < ret->start))
2132e405ad8SJosef Bacik 				ret = cache;
2142e405ad8SJosef Bacik 			n = n->rb_left;
2152e405ad8SJosef Bacik 		} else if (bytenr > start) {
2162e405ad8SJosef Bacik 			if (contains && bytenr <= end) {
2172e405ad8SJosef Bacik 				ret = cache;
2182e405ad8SJosef Bacik 				break;
2192e405ad8SJosef Bacik 			}
2202e405ad8SJosef Bacik 			n = n->rb_right;
2212e405ad8SJosef Bacik 		} else {
2222e405ad8SJosef Bacik 			ret = cache;
2232e405ad8SJosef Bacik 			break;
2242e405ad8SJosef Bacik 		}
2252e405ad8SJosef Bacik 	}
2262e405ad8SJosef Bacik 	if (ret) {
2272e405ad8SJosef Bacik 		btrfs_get_block_group(ret);
228b3470b5dSDavid Sterba 		if (bytenr == 0 && info->first_logical_byte > ret->start)
229b3470b5dSDavid Sterba 			info->first_logical_byte = ret->start;
2302e405ad8SJosef Bacik 	}
2312e405ad8SJosef Bacik 	spin_unlock(&info->block_group_cache_lock);
2322e405ad8SJosef Bacik 
2332e405ad8SJosef Bacik 	return ret;
2342e405ad8SJosef Bacik }
2352e405ad8SJosef Bacik 
2362e405ad8SJosef Bacik /*
2372e405ad8SJosef Bacik  * Return the block group that starts at or after bytenr
2382e405ad8SJosef Bacik  */
23932da5386SDavid Sterba struct btrfs_block_group *btrfs_lookup_first_block_group(
2402e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr)
2412e405ad8SJosef Bacik {
2422e405ad8SJosef Bacik 	return block_group_cache_tree_search(info, bytenr, 0);
2432e405ad8SJosef Bacik }
2442e405ad8SJosef Bacik 
2452e405ad8SJosef Bacik /*
2462e405ad8SJosef Bacik  * Return the block group that contains the given bytenr
2472e405ad8SJosef Bacik  */
24832da5386SDavid Sterba struct btrfs_block_group *btrfs_lookup_block_group(
2492e405ad8SJosef Bacik 		struct btrfs_fs_info *info, u64 bytenr)
2502e405ad8SJosef Bacik {
2512e405ad8SJosef Bacik 	return block_group_cache_tree_search(info, bytenr, 1);
2522e405ad8SJosef Bacik }
2532e405ad8SJosef Bacik 
25432da5386SDavid Sterba struct btrfs_block_group *btrfs_next_block_group(
25532da5386SDavid Sterba 		struct btrfs_block_group *cache)
2562e405ad8SJosef Bacik {
2572e405ad8SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
2582e405ad8SJosef Bacik 	struct rb_node *node;
2592e405ad8SJosef Bacik 
2602e405ad8SJosef Bacik 	spin_lock(&fs_info->block_group_cache_lock);
2612e405ad8SJosef Bacik 
2622e405ad8SJosef Bacik 	/* If our block group was removed, we need a full search. */
2632e405ad8SJosef Bacik 	if (RB_EMPTY_NODE(&cache->cache_node)) {
264b3470b5dSDavid Sterba 		const u64 next_bytenr = cache->start + cache->length;
2652e405ad8SJosef Bacik 
2662e405ad8SJosef Bacik 		spin_unlock(&fs_info->block_group_cache_lock);
2672e405ad8SJosef Bacik 		btrfs_put_block_group(cache);
2682e405ad8SJosef Bacik 		cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
2692e405ad8SJosef Bacik 	}
2702e405ad8SJosef Bacik 	node = rb_next(&cache->cache_node);
2712e405ad8SJosef Bacik 	btrfs_put_block_group(cache);
2722e405ad8SJosef Bacik 	if (node) {
27332da5386SDavid Sterba 		cache = rb_entry(node, struct btrfs_block_group, cache_node);
2742e405ad8SJosef Bacik 		btrfs_get_block_group(cache);
2752e405ad8SJosef Bacik 	} else
2762e405ad8SJosef Bacik 		cache = NULL;
2772e405ad8SJosef Bacik 	spin_unlock(&fs_info->block_group_cache_lock);
2782e405ad8SJosef Bacik 	return cache;
2792e405ad8SJosef Bacik }
2803eeb3226SJosef Bacik 
2813eeb3226SJosef Bacik bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
2823eeb3226SJosef Bacik {
28332da5386SDavid Sterba 	struct btrfs_block_group *bg;
2843eeb3226SJosef Bacik 	bool ret = true;
2853eeb3226SJosef Bacik 
2863eeb3226SJosef Bacik 	bg = btrfs_lookup_block_group(fs_info, bytenr);
2873eeb3226SJosef Bacik 	if (!bg)
2883eeb3226SJosef Bacik 		return false;
2893eeb3226SJosef Bacik 
2903eeb3226SJosef Bacik 	spin_lock(&bg->lock);
2913eeb3226SJosef Bacik 	if (bg->ro)
2923eeb3226SJosef Bacik 		ret = false;
2933eeb3226SJosef Bacik 	else
2943eeb3226SJosef Bacik 		atomic_inc(&bg->nocow_writers);
2953eeb3226SJosef Bacik 	spin_unlock(&bg->lock);
2963eeb3226SJosef Bacik 
2973eeb3226SJosef Bacik 	/* No put on block group, done by btrfs_dec_nocow_writers */
2983eeb3226SJosef Bacik 	if (!ret)
2993eeb3226SJosef Bacik 		btrfs_put_block_group(bg);
3003eeb3226SJosef Bacik 
3013eeb3226SJosef Bacik 	return ret;
3023eeb3226SJosef Bacik }
3033eeb3226SJosef Bacik 
3043eeb3226SJosef Bacik void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3053eeb3226SJosef Bacik {
30632da5386SDavid Sterba 	struct btrfs_block_group *bg;
3073eeb3226SJosef Bacik 
3083eeb3226SJosef Bacik 	bg = btrfs_lookup_block_group(fs_info, bytenr);
3093eeb3226SJosef Bacik 	ASSERT(bg);
3103eeb3226SJosef Bacik 	if (atomic_dec_and_test(&bg->nocow_writers))
3113eeb3226SJosef Bacik 		wake_up_var(&bg->nocow_writers);
3123eeb3226SJosef Bacik 	/*
3133eeb3226SJosef Bacik 	 * Once for our lookup and once for the lookup done by a previous call
3143eeb3226SJosef Bacik 	 * to btrfs_inc_nocow_writers()
3153eeb3226SJosef Bacik 	 */
3163eeb3226SJosef Bacik 	btrfs_put_block_group(bg);
3173eeb3226SJosef Bacik 	btrfs_put_block_group(bg);
3183eeb3226SJosef Bacik }
3193eeb3226SJosef Bacik 
32032da5386SDavid Sterba void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
3213eeb3226SJosef Bacik {
3223eeb3226SJosef Bacik 	wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
3233eeb3226SJosef Bacik }
3243eeb3226SJosef Bacik 
3253eeb3226SJosef Bacik void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
3263eeb3226SJosef Bacik 					const u64 start)
3273eeb3226SJosef Bacik {
32832da5386SDavid Sterba 	struct btrfs_block_group *bg;
3293eeb3226SJosef Bacik 
3303eeb3226SJosef Bacik 	bg = btrfs_lookup_block_group(fs_info, start);
3313eeb3226SJosef Bacik 	ASSERT(bg);
3323eeb3226SJosef Bacik 	if (atomic_dec_and_test(&bg->reservations))
3333eeb3226SJosef Bacik 		wake_up_var(&bg->reservations);
3343eeb3226SJosef Bacik 	btrfs_put_block_group(bg);
3353eeb3226SJosef Bacik }
3363eeb3226SJosef Bacik 
33732da5386SDavid Sterba void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
3383eeb3226SJosef Bacik {
3393eeb3226SJosef Bacik 	struct btrfs_space_info *space_info = bg->space_info;
3403eeb3226SJosef Bacik 
3413eeb3226SJosef Bacik 	ASSERT(bg->ro);
3423eeb3226SJosef Bacik 
3433eeb3226SJosef Bacik 	if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
3443eeb3226SJosef Bacik 		return;
3453eeb3226SJosef Bacik 
3463eeb3226SJosef Bacik 	/*
3473eeb3226SJosef Bacik 	 * Our block group is read only but before we set it to read only,
3483eeb3226SJosef Bacik 	 * some task might have had allocated an extent from it already, but it
3493eeb3226SJosef Bacik 	 * has not yet created a respective ordered extent (and added it to a
3503eeb3226SJosef Bacik 	 * root's list of ordered extents).
3513eeb3226SJosef Bacik 	 * Therefore wait for any task currently allocating extents, since the
3523eeb3226SJosef Bacik 	 * block group's reservations counter is incremented while a read lock
3533eeb3226SJosef Bacik 	 * on the groups' semaphore is held and decremented after releasing
3543eeb3226SJosef Bacik 	 * the read access on that semaphore and creating the ordered extent.
3553eeb3226SJosef Bacik 	 */
3563eeb3226SJosef Bacik 	down_write(&space_info->groups_sem);
3573eeb3226SJosef Bacik 	up_write(&space_info->groups_sem);
3583eeb3226SJosef Bacik 
3593eeb3226SJosef Bacik 	wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
3603eeb3226SJosef Bacik }
3619f21246dSJosef Bacik 
3629f21246dSJosef Bacik struct btrfs_caching_control *btrfs_get_caching_control(
36332da5386SDavid Sterba 		struct btrfs_block_group *cache)
3649f21246dSJosef Bacik {
3659f21246dSJosef Bacik 	struct btrfs_caching_control *ctl;
3669f21246dSJosef Bacik 
3679f21246dSJosef Bacik 	spin_lock(&cache->lock);
3689f21246dSJosef Bacik 	if (!cache->caching_ctl) {
3699f21246dSJosef Bacik 		spin_unlock(&cache->lock);
3709f21246dSJosef Bacik 		return NULL;
3719f21246dSJosef Bacik 	}
3729f21246dSJosef Bacik 
3739f21246dSJosef Bacik 	ctl = cache->caching_ctl;
3749f21246dSJosef Bacik 	refcount_inc(&ctl->count);
3759f21246dSJosef Bacik 	spin_unlock(&cache->lock);
3769f21246dSJosef Bacik 	return ctl;
3779f21246dSJosef Bacik }
3789f21246dSJosef Bacik 
3799f21246dSJosef Bacik void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
3809f21246dSJosef Bacik {
3819f21246dSJosef Bacik 	if (refcount_dec_and_test(&ctl->count))
3829f21246dSJosef Bacik 		kfree(ctl);
3839f21246dSJosef Bacik }
3849f21246dSJosef Bacik 
3859f21246dSJosef Bacik /*
3869f21246dSJosef Bacik  * When we wait for progress in the block group caching, its because our
3879f21246dSJosef Bacik  * allocation attempt failed at least once.  So, we must sleep and let some
3889f21246dSJosef Bacik  * progress happen before we try again.
3899f21246dSJosef Bacik  *
3909f21246dSJosef Bacik  * This function will sleep at least once waiting for new free space to show
3919f21246dSJosef Bacik  * up, and then it will check the block group free space numbers for our min
3929f21246dSJosef Bacik  * num_bytes.  Another option is to have it go ahead and look in the rbtree for
3939f21246dSJosef Bacik  * a free extent of a given size, but this is a good start.
3949f21246dSJosef Bacik  *
3959f21246dSJosef Bacik  * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
3969f21246dSJosef Bacik  * any of the information in this block group.
3979f21246dSJosef Bacik  */
39832da5386SDavid Sterba void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
3999f21246dSJosef Bacik 					   u64 num_bytes)
4009f21246dSJosef Bacik {
4019f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
4029f21246dSJosef Bacik 
4039f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4049f21246dSJosef Bacik 	if (!caching_ctl)
4059f21246dSJosef Bacik 		return;
4069f21246dSJosef Bacik 
40732da5386SDavid Sterba 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
4089f21246dSJosef Bacik 		   (cache->free_space_ctl->free_space >= num_bytes));
4099f21246dSJosef Bacik 
4109f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4119f21246dSJosef Bacik }
4129f21246dSJosef Bacik 
41332da5386SDavid Sterba int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
4149f21246dSJosef Bacik {
4159f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
4169f21246dSJosef Bacik 	int ret = 0;
4179f21246dSJosef Bacik 
4189f21246dSJosef Bacik 	caching_ctl = btrfs_get_caching_control(cache);
4199f21246dSJosef Bacik 	if (!caching_ctl)
4209f21246dSJosef Bacik 		return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
4219f21246dSJosef Bacik 
42232da5386SDavid Sterba 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
4239f21246dSJosef Bacik 	if (cache->cached == BTRFS_CACHE_ERROR)
4249f21246dSJosef Bacik 		ret = -EIO;
4259f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
4269f21246dSJosef Bacik 	return ret;
4279f21246dSJosef Bacik }
4289f21246dSJosef Bacik 
4299f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
43032da5386SDavid Sterba static void fragment_free_space(struct btrfs_block_group *block_group)
4319f21246dSJosef Bacik {
4329f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
433b3470b5dSDavid Sterba 	u64 start = block_group->start;
434b3470b5dSDavid Sterba 	u64 len = block_group->length;
4359f21246dSJosef Bacik 	u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
4369f21246dSJosef Bacik 		fs_info->nodesize : fs_info->sectorsize;
4379f21246dSJosef Bacik 	u64 step = chunk << 1;
4389f21246dSJosef Bacik 
4399f21246dSJosef Bacik 	while (len > chunk) {
4409f21246dSJosef Bacik 		btrfs_remove_free_space(block_group, start, chunk);
4419f21246dSJosef Bacik 		start += step;
4429f21246dSJosef Bacik 		if (len < step)
4439f21246dSJosef Bacik 			len = 0;
4449f21246dSJosef Bacik 		else
4459f21246dSJosef Bacik 			len -= step;
4469f21246dSJosef Bacik 	}
4479f21246dSJosef Bacik }
4489f21246dSJosef Bacik #endif
4499f21246dSJosef Bacik 
4509f21246dSJosef Bacik /*
4519f21246dSJosef Bacik  * This is only called by btrfs_cache_block_group, since we could have freed
4529f21246dSJosef Bacik  * extents we need to check the pinned_extents for any extents that can't be
4539f21246dSJosef Bacik  * used yet since their free space will be released as soon as the transaction
4549f21246dSJosef Bacik  * commits.
4559f21246dSJosef Bacik  */
45632da5386SDavid Sterba u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
4579f21246dSJosef Bacik {
4589f21246dSJosef Bacik 	struct btrfs_fs_info *info = block_group->fs_info;
4599f21246dSJosef Bacik 	u64 extent_start, extent_end, size, total_added = 0;
4609f21246dSJosef Bacik 	int ret;
4619f21246dSJosef Bacik 
4629f21246dSJosef Bacik 	while (start < end) {
4639f21246dSJosef Bacik 		ret = find_first_extent_bit(info->pinned_extents, start,
4649f21246dSJosef Bacik 					    &extent_start, &extent_end,
4659f21246dSJosef Bacik 					    EXTENT_DIRTY | EXTENT_UPTODATE,
4669f21246dSJosef Bacik 					    NULL);
4679f21246dSJosef Bacik 		if (ret)
4689f21246dSJosef Bacik 			break;
4699f21246dSJosef Bacik 
4709f21246dSJosef Bacik 		if (extent_start <= start) {
4719f21246dSJosef Bacik 			start = extent_end + 1;
4729f21246dSJosef Bacik 		} else if (extent_start > start && extent_start < end) {
4739f21246dSJosef Bacik 			size = extent_start - start;
4749f21246dSJosef Bacik 			total_added += size;
475b0643e59SDennis Zhou 			ret = btrfs_add_free_space_async_trimmed(block_group,
476b0643e59SDennis Zhou 								 start, size);
4779f21246dSJosef Bacik 			BUG_ON(ret); /* -ENOMEM or logic error */
4789f21246dSJosef Bacik 			start = extent_end + 1;
4799f21246dSJosef Bacik 		} else {
4809f21246dSJosef Bacik 			break;
4819f21246dSJosef Bacik 		}
4829f21246dSJosef Bacik 	}
4839f21246dSJosef Bacik 
4849f21246dSJosef Bacik 	if (start < end) {
4859f21246dSJosef Bacik 		size = end - start;
4869f21246dSJosef Bacik 		total_added += size;
487b0643e59SDennis Zhou 		ret = btrfs_add_free_space_async_trimmed(block_group, start,
488b0643e59SDennis Zhou 							 size);
4899f21246dSJosef Bacik 		BUG_ON(ret); /* -ENOMEM or logic error */
4909f21246dSJosef Bacik 	}
4919f21246dSJosef Bacik 
4929f21246dSJosef Bacik 	return total_added;
4939f21246dSJosef Bacik }
4949f21246dSJosef Bacik 
4959f21246dSJosef Bacik static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
4969f21246dSJosef Bacik {
49732da5386SDavid Sterba 	struct btrfs_block_group *block_group = caching_ctl->block_group;
4989f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
4999f21246dSJosef Bacik 	struct btrfs_root *extent_root = fs_info->extent_root;
5009f21246dSJosef Bacik 	struct btrfs_path *path;
5019f21246dSJosef Bacik 	struct extent_buffer *leaf;
5029f21246dSJosef Bacik 	struct btrfs_key key;
5039f21246dSJosef Bacik 	u64 total_found = 0;
5049f21246dSJosef Bacik 	u64 last = 0;
5059f21246dSJosef Bacik 	u32 nritems;
5069f21246dSJosef Bacik 	int ret;
5079f21246dSJosef Bacik 	bool wakeup = true;
5089f21246dSJosef Bacik 
5099f21246dSJosef Bacik 	path = btrfs_alloc_path();
5109f21246dSJosef Bacik 	if (!path)
5119f21246dSJosef Bacik 		return -ENOMEM;
5129f21246dSJosef Bacik 
513b3470b5dSDavid Sterba 	last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
5149f21246dSJosef Bacik 
5159f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
5169f21246dSJosef Bacik 	/*
5179f21246dSJosef Bacik 	 * If we're fragmenting we don't want to make anybody think we can
5189f21246dSJosef Bacik 	 * allocate from this block group until we've had a chance to fragment
5199f21246dSJosef Bacik 	 * the free space.
5209f21246dSJosef Bacik 	 */
5219f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group))
5229f21246dSJosef Bacik 		wakeup = false;
5239f21246dSJosef Bacik #endif
5249f21246dSJosef Bacik 	/*
5259f21246dSJosef Bacik 	 * We don't want to deadlock with somebody trying to allocate a new
5269f21246dSJosef Bacik 	 * extent for the extent root while also trying to search the extent
5279f21246dSJosef Bacik 	 * root to add free space.  So we skip locking and search the commit
5289f21246dSJosef Bacik 	 * root, since its read-only
5299f21246dSJosef Bacik 	 */
5309f21246dSJosef Bacik 	path->skip_locking = 1;
5319f21246dSJosef Bacik 	path->search_commit_root = 1;
5329f21246dSJosef Bacik 	path->reada = READA_FORWARD;
5339f21246dSJosef Bacik 
5349f21246dSJosef Bacik 	key.objectid = last;
5359f21246dSJosef Bacik 	key.offset = 0;
5369f21246dSJosef Bacik 	key.type = BTRFS_EXTENT_ITEM_KEY;
5379f21246dSJosef Bacik 
5389f21246dSJosef Bacik next:
5399f21246dSJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
5409f21246dSJosef Bacik 	if (ret < 0)
5419f21246dSJosef Bacik 		goto out;
5429f21246dSJosef Bacik 
5439f21246dSJosef Bacik 	leaf = path->nodes[0];
5449f21246dSJosef Bacik 	nritems = btrfs_header_nritems(leaf);
5459f21246dSJosef Bacik 
5469f21246dSJosef Bacik 	while (1) {
5479f21246dSJosef Bacik 		if (btrfs_fs_closing(fs_info) > 1) {
5489f21246dSJosef Bacik 			last = (u64)-1;
5499f21246dSJosef Bacik 			break;
5509f21246dSJosef Bacik 		}
5519f21246dSJosef Bacik 
5529f21246dSJosef Bacik 		if (path->slots[0] < nritems) {
5539f21246dSJosef Bacik 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5549f21246dSJosef Bacik 		} else {
5559f21246dSJosef Bacik 			ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
5569f21246dSJosef Bacik 			if (ret)
5579f21246dSJosef Bacik 				break;
5589f21246dSJosef Bacik 
5599f21246dSJosef Bacik 			if (need_resched() ||
5609f21246dSJosef Bacik 			    rwsem_is_contended(&fs_info->commit_root_sem)) {
5619f21246dSJosef Bacik 				if (wakeup)
5629f21246dSJosef Bacik 					caching_ctl->progress = last;
5639f21246dSJosef Bacik 				btrfs_release_path(path);
5649f21246dSJosef Bacik 				up_read(&fs_info->commit_root_sem);
5659f21246dSJosef Bacik 				mutex_unlock(&caching_ctl->mutex);
5669f21246dSJosef Bacik 				cond_resched();
5679f21246dSJosef Bacik 				mutex_lock(&caching_ctl->mutex);
5689f21246dSJosef Bacik 				down_read(&fs_info->commit_root_sem);
5699f21246dSJosef Bacik 				goto next;
5709f21246dSJosef Bacik 			}
5719f21246dSJosef Bacik 
5729f21246dSJosef Bacik 			ret = btrfs_next_leaf(extent_root, path);
5739f21246dSJosef Bacik 			if (ret < 0)
5749f21246dSJosef Bacik 				goto out;
5759f21246dSJosef Bacik 			if (ret)
5769f21246dSJosef Bacik 				break;
5779f21246dSJosef Bacik 			leaf = path->nodes[0];
5789f21246dSJosef Bacik 			nritems = btrfs_header_nritems(leaf);
5799f21246dSJosef Bacik 			continue;
5809f21246dSJosef Bacik 		}
5819f21246dSJosef Bacik 
5829f21246dSJosef Bacik 		if (key.objectid < last) {
5839f21246dSJosef Bacik 			key.objectid = last;
5849f21246dSJosef Bacik 			key.offset = 0;
5859f21246dSJosef Bacik 			key.type = BTRFS_EXTENT_ITEM_KEY;
5869f21246dSJosef Bacik 
5879f21246dSJosef Bacik 			if (wakeup)
5889f21246dSJosef Bacik 				caching_ctl->progress = last;
5899f21246dSJosef Bacik 			btrfs_release_path(path);
5909f21246dSJosef Bacik 			goto next;
5919f21246dSJosef Bacik 		}
5929f21246dSJosef Bacik 
593b3470b5dSDavid Sterba 		if (key.objectid < block_group->start) {
5949f21246dSJosef Bacik 			path->slots[0]++;
5959f21246dSJosef Bacik 			continue;
5969f21246dSJosef Bacik 		}
5979f21246dSJosef Bacik 
598b3470b5dSDavid Sterba 		if (key.objectid >= block_group->start + block_group->length)
5999f21246dSJosef Bacik 			break;
6009f21246dSJosef Bacik 
6019f21246dSJosef Bacik 		if (key.type == BTRFS_EXTENT_ITEM_KEY ||
6029f21246dSJosef Bacik 		    key.type == BTRFS_METADATA_ITEM_KEY) {
6039f21246dSJosef Bacik 			total_found += add_new_free_space(block_group, last,
6049f21246dSJosef Bacik 							  key.objectid);
6059f21246dSJosef Bacik 			if (key.type == BTRFS_METADATA_ITEM_KEY)
6069f21246dSJosef Bacik 				last = key.objectid +
6079f21246dSJosef Bacik 					fs_info->nodesize;
6089f21246dSJosef Bacik 			else
6099f21246dSJosef Bacik 				last = key.objectid + key.offset;
6109f21246dSJosef Bacik 
6119f21246dSJosef Bacik 			if (total_found > CACHING_CTL_WAKE_UP) {
6129f21246dSJosef Bacik 				total_found = 0;
6139f21246dSJosef Bacik 				if (wakeup)
6149f21246dSJosef Bacik 					wake_up(&caching_ctl->wait);
6159f21246dSJosef Bacik 			}
6169f21246dSJosef Bacik 		}
6179f21246dSJosef Bacik 		path->slots[0]++;
6189f21246dSJosef Bacik 	}
6199f21246dSJosef Bacik 	ret = 0;
6209f21246dSJosef Bacik 
6219f21246dSJosef Bacik 	total_found += add_new_free_space(block_group, last,
622b3470b5dSDavid Sterba 				block_group->start + block_group->length);
6239f21246dSJosef Bacik 	caching_ctl->progress = (u64)-1;
6249f21246dSJosef Bacik 
6259f21246dSJosef Bacik out:
6269f21246dSJosef Bacik 	btrfs_free_path(path);
6279f21246dSJosef Bacik 	return ret;
6289f21246dSJosef Bacik }
6299f21246dSJosef Bacik 
6309f21246dSJosef Bacik static noinline void caching_thread(struct btrfs_work *work)
6319f21246dSJosef Bacik {
63232da5386SDavid Sterba 	struct btrfs_block_group *block_group;
6339f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info;
6349f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
6359f21246dSJosef Bacik 	int ret;
6369f21246dSJosef Bacik 
6379f21246dSJosef Bacik 	caching_ctl = container_of(work, struct btrfs_caching_control, work);
6389f21246dSJosef Bacik 	block_group = caching_ctl->block_group;
6399f21246dSJosef Bacik 	fs_info = block_group->fs_info;
6409f21246dSJosef Bacik 
6419f21246dSJosef Bacik 	mutex_lock(&caching_ctl->mutex);
6429f21246dSJosef Bacik 	down_read(&fs_info->commit_root_sem);
6439f21246dSJosef Bacik 
6449f21246dSJosef Bacik 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
6459f21246dSJosef Bacik 		ret = load_free_space_tree(caching_ctl);
6469f21246dSJosef Bacik 	else
6479f21246dSJosef Bacik 		ret = load_extent_tree_free(caching_ctl);
6489f21246dSJosef Bacik 
6499f21246dSJosef Bacik 	spin_lock(&block_group->lock);
6509f21246dSJosef Bacik 	block_group->caching_ctl = NULL;
6519f21246dSJosef Bacik 	block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
6529f21246dSJosef Bacik 	spin_unlock(&block_group->lock);
6539f21246dSJosef Bacik 
6549f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
6559f21246dSJosef Bacik 	if (btrfs_should_fragment_free_space(block_group)) {
6569f21246dSJosef Bacik 		u64 bytes_used;
6579f21246dSJosef Bacik 
6589f21246dSJosef Bacik 		spin_lock(&block_group->space_info->lock);
6599f21246dSJosef Bacik 		spin_lock(&block_group->lock);
660b3470b5dSDavid Sterba 		bytes_used = block_group->length - block_group->used;
6619f21246dSJosef Bacik 		block_group->space_info->bytes_used += bytes_used >> 1;
6629f21246dSJosef Bacik 		spin_unlock(&block_group->lock);
6639f21246dSJosef Bacik 		spin_unlock(&block_group->space_info->lock);
664e11c0406SJosef Bacik 		fragment_free_space(block_group);
6659f21246dSJosef Bacik 	}
6669f21246dSJosef Bacik #endif
6679f21246dSJosef Bacik 
6689f21246dSJosef Bacik 	caching_ctl->progress = (u64)-1;
6699f21246dSJosef Bacik 
6709f21246dSJosef Bacik 	up_read(&fs_info->commit_root_sem);
6719f21246dSJosef Bacik 	btrfs_free_excluded_extents(block_group);
6729f21246dSJosef Bacik 	mutex_unlock(&caching_ctl->mutex);
6739f21246dSJosef Bacik 
6749f21246dSJosef Bacik 	wake_up(&caching_ctl->wait);
6759f21246dSJosef Bacik 
6769f21246dSJosef Bacik 	btrfs_put_caching_control(caching_ctl);
6779f21246dSJosef Bacik 	btrfs_put_block_group(block_group);
6789f21246dSJosef Bacik }
6799f21246dSJosef Bacik 
68032da5386SDavid Sterba int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
6819f21246dSJosef Bacik {
6829f21246dSJosef Bacik 	DEFINE_WAIT(wait);
6839f21246dSJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
6849f21246dSJosef Bacik 	struct btrfs_caching_control *caching_ctl;
6859f21246dSJosef Bacik 	int ret = 0;
6869f21246dSJosef Bacik 
6879f21246dSJosef Bacik 	caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
6889f21246dSJosef Bacik 	if (!caching_ctl)
6899f21246dSJosef Bacik 		return -ENOMEM;
6909f21246dSJosef Bacik 
6919f21246dSJosef Bacik 	INIT_LIST_HEAD(&caching_ctl->list);
6929f21246dSJosef Bacik 	mutex_init(&caching_ctl->mutex);
6939f21246dSJosef Bacik 	init_waitqueue_head(&caching_ctl->wait);
6949f21246dSJosef Bacik 	caching_ctl->block_group = cache;
695b3470b5dSDavid Sterba 	caching_ctl->progress = cache->start;
6969f21246dSJosef Bacik 	refcount_set(&caching_ctl->count, 1);
697a0cac0ecSOmar Sandoval 	btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
6989f21246dSJosef Bacik 
6999f21246dSJosef Bacik 	spin_lock(&cache->lock);
7009f21246dSJosef Bacik 	/*
7019f21246dSJosef Bacik 	 * This should be a rare occasion, but this could happen I think in the
7029f21246dSJosef Bacik 	 * case where one thread starts to load the space cache info, and then
7039f21246dSJosef Bacik 	 * some other thread starts a transaction commit which tries to do an
7049f21246dSJosef Bacik 	 * allocation while the other thread is still loading the space cache
7059f21246dSJosef Bacik 	 * info.  The previous loop should have kept us from choosing this block
7069f21246dSJosef Bacik 	 * group, but if we've moved to the state where we will wait on caching
7079f21246dSJosef Bacik 	 * block groups we need to first check if we're doing a fast load here,
7089f21246dSJosef Bacik 	 * so we can wait for it to finish, otherwise we could end up allocating
7099f21246dSJosef Bacik 	 * from a block group who's cache gets evicted for one reason or
7109f21246dSJosef Bacik 	 * another.
7119f21246dSJosef Bacik 	 */
7129f21246dSJosef Bacik 	while (cache->cached == BTRFS_CACHE_FAST) {
7139f21246dSJosef Bacik 		struct btrfs_caching_control *ctl;
7149f21246dSJosef Bacik 
7159f21246dSJosef Bacik 		ctl = cache->caching_ctl;
7169f21246dSJosef Bacik 		refcount_inc(&ctl->count);
7179f21246dSJosef Bacik 		prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
7189f21246dSJosef Bacik 		spin_unlock(&cache->lock);
7199f21246dSJosef Bacik 
7209f21246dSJosef Bacik 		schedule();
7219f21246dSJosef Bacik 
7229f21246dSJosef Bacik 		finish_wait(&ctl->wait, &wait);
7239f21246dSJosef Bacik 		btrfs_put_caching_control(ctl);
7249f21246dSJosef Bacik 		spin_lock(&cache->lock);
7259f21246dSJosef Bacik 	}
7269f21246dSJosef Bacik 
7279f21246dSJosef Bacik 	if (cache->cached != BTRFS_CACHE_NO) {
7289f21246dSJosef Bacik 		spin_unlock(&cache->lock);
7299f21246dSJosef Bacik 		kfree(caching_ctl);
7309f21246dSJosef Bacik 		return 0;
7319f21246dSJosef Bacik 	}
7329f21246dSJosef Bacik 	WARN_ON(cache->caching_ctl);
7339f21246dSJosef Bacik 	cache->caching_ctl = caching_ctl;
7349f21246dSJosef Bacik 	cache->cached = BTRFS_CACHE_FAST;
7359f21246dSJosef Bacik 	spin_unlock(&cache->lock);
7369f21246dSJosef Bacik 
7379f21246dSJosef Bacik 	if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
7389f21246dSJosef Bacik 		mutex_lock(&caching_ctl->mutex);
7399f21246dSJosef Bacik 		ret = load_free_space_cache(cache);
7409f21246dSJosef Bacik 
7419f21246dSJosef Bacik 		spin_lock(&cache->lock);
7429f21246dSJosef Bacik 		if (ret == 1) {
7439f21246dSJosef Bacik 			cache->caching_ctl = NULL;
7449f21246dSJosef Bacik 			cache->cached = BTRFS_CACHE_FINISHED;
7459f21246dSJosef Bacik 			cache->last_byte_to_unpin = (u64)-1;
7469f21246dSJosef Bacik 			caching_ctl->progress = (u64)-1;
7479f21246dSJosef Bacik 		} else {
7489f21246dSJosef Bacik 			if (load_cache_only) {
7499f21246dSJosef Bacik 				cache->caching_ctl = NULL;
7509f21246dSJosef Bacik 				cache->cached = BTRFS_CACHE_NO;
7519f21246dSJosef Bacik 			} else {
7529f21246dSJosef Bacik 				cache->cached = BTRFS_CACHE_STARTED;
7539f21246dSJosef Bacik 				cache->has_caching_ctl = 1;
7549f21246dSJosef Bacik 			}
7559f21246dSJosef Bacik 		}
7569f21246dSJosef Bacik 		spin_unlock(&cache->lock);
7579f21246dSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
7589f21246dSJosef Bacik 		if (ret == 1 &&
7599f21246dSJosef Bacik 		    btrfs_should_fragment_free_space(cache)) {
7609f21246dSJosef Bacik 			u64 bytes_used;
7619f21246dSJosef Bacik 
7629f21246dSJosef Bacik 			spin_lock(&cache->space_info->lock);
7639f21246dSJosef Bacik 			spin_lock(&cache->lock);
764b3470b5dSDavid Sterba 			bytes_used = cache->length - cache->used;
7659f21246dSJosef Bacik 			cache->space_info->bytes_used += bytes_used >> 1;
7669f21246dSJosef Bacik 			spin_unlock(&cache->lock);
7679f21246dSJosef Bacik 			spin_unlock(&cache->space_info->lock);
768e11c0406SJosef Bacik 			fragment_free_space(cache);
7699f21246dSJosef Bacik 		}
7709f21246dSJosef Bacik #endif
7719f21246dSJosef Bacik 		mutex_unlock(&caching_ctl->mutex);
7729f21246dSJosef Bacik 
7739f21246dSJosef Bacik 		wake_up(&caching_ctl->wait);
7749f21246dSJosef Bacik 		if (ret == 1) {
7759f21246dSJosef Bacik 			btrfs_put_caching_control(caching_ctl);
7769f21246dSJosef Bacik 			btrfs_free_excluded_extents(cache);
7779f21246dSJosef Bacik 			return 0;
7789f21246dSJosef Bacik 		}
7799f21246dSJosef Bacik 	} else {
7809f21246dSJosef Bacik 		/*
7819f21246dSJosef Bacik 		 * We're either using the free space tree or no caching at all.
7829f21246dSJosef Bacik 		 * Set cached to the appropriate value and wakeup any waiters.
7839f21246dSJosef Bacik 		 */
7849f21246dSJosef Bacik 		spin_lock(&cache->lock);
7859f21246dSJosef Bacik 		if (load_cache_only) {
7869f21246dSJosef Bacik 			cache->caching_ctl = NULL;
7879f21246dSJosef Bacik 			cache->cached = BTRFS_CACHE_NO;
7889f21246dSJosef Bacik 		} else {
7899f21246dSJosef Bacik 			cache->cached = BTRFS_CACHE_STARTED;
7909f21246dSJosef Bacik 			cache->has_caching_ctl = 1;
7919f21246dSJosef Bacik 		}
7929f21246dSJosef Bacik 		spin_unlock(&cache->lock);
7939f21246dSJosef Bacik 		wake_up(&caching_ctl->wait);
7949f21246dSJosef Bacik 	}
7959f21246dSJosef Bacik 
7969f21246dSJosef Bacik 	if (load_cache_only) {
7979f21246dSJosef Bacik 		btrfs_put_caching_control(caching_ctl);
7989f21246dSJosef Bacik 		return 0;
7999f21246dSJosef Bacik 	}
8009f21246dSJosef Bacik 
8019f21246dSJosef Bacik 	down_write(&fs_info->commit_root_sem);
8029f21246dSJosef Bacik 	refcount_inc(&caching_ctl->count);
8039f21246dSJosef Bacik 	list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
8049f21246dSJosef Bacik 	up_write(&fs_info->commit_root_sem);
8059f21246dSJosef Bacik 
8069f21246dSJosef Bacik 	btrfs_get_block_group(cache);
8079f21246dSJosef Bacik 
8089f21246dSJosef Bacik 	btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
8099f21246dSJosef Bacik 
8109f21246dSJosef Bacik 	return ret;
8119f21246dSJosef Bacik }
812e3e0520bSJosef Bacik 
813e3e0520bSJosef Bacik static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
814e3e0520bSJosef Bacik {
815e3e0520bSJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
816e3e0520bSJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
817e3e0520bSJosef Bacik 
818e3e0520bSJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
819e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
820e3e0520bSJosef Bacik 		fs_info->avail_data_alloc_bits &= ~extra_flags;
821e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
822e3e0520bSJosef Bacik 		fs_info->avail_metadata_alloc_bits &= ~extra_flags;
823e3e0520bSJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
824e3e0520bSJosef Bacik 		fs_info->avail_system_alloc_bits &= ~extra_flags;
825e3e0520bSJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
826e3e0520bSJosef Bacik }
827e3e0520bSJosef Bacik 
828e3e0520bSJosef Bacik /*
829e3e0520bSJosef Bacik  * Clear incompat bits for the following feature(s):
830e3e0520bSJosef Bacik  *
831e3e0520bSJosef Bacik  * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
832e3e0520bSJosef Bacik  *            in the whole filesystem
8339c907446SDavid Sterba  *
8349c907446SDavid Sterba  * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
835e3e0520bSJosef Bacik  */
836e3e0520bSJosef Bacik static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
837e3e0520bSJosef Bacik {
8389c907446SDavid Sterba 	bool found_raid56 = false;
8399c907446SDavid Sterba 	bool found_raid1c34 = false;
8409c907446SDavid Sterba 
8419c907446SDavid Sterba 	if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
8429c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
8439c907446SDavid Sterba 	    (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
844e3e0520bSJosef Bacik 		struct list_head *head = &fs_info->space_info;
845e3e0520bSJosef Bacik 		struct btrfs_space_info *sinfo;
846e3e0520bSJosef Bacik 
847e3e0520bSJosef Bacik 		list_for_each_entry_rcu(sinfo, head, list) {
848e3e0520bSJosef Bacik 			down_read(&sinfo->groups_sem);
849e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
8509c907446SDavid Sterba 				found_raid56 = true;
851e3e0520bSJosef Bacik 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
8529c907446SDavid Sterba 				found_raid56 = true;
8539c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
8549c907446SDavid Sterba 				found_raid1c34 = true;
8559c907446SDavid Sterba 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
8569c907446SDavid Sterba 				found_raid1c34 = true;
857e3e0520bSJosef Bacik 			up_read(&sinfo->groups_sem);
858e3e0520bSJosef Bacik 		}
8599c907446SDavid Sterba 		if (found_raid56)
860e3e0520bSJosef Bacik 			btrfs_clear_fs_incompat(fs_info, RAID56);
8619c907446SDavid Sterba 		if (found_raid1c34)
8629c907446SDavid Sterba 			btrfs_clear_fs_incompat(fs_info, RAID1C34);
863e3e0520bSJosef Bacik 	}
864e3e0520bSJosef Bacik }
865e3e0520bSJosef Bacik 
866e3e0520bSJosef Bacik int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
867e3e0520bSJosef Bacik 			     u64 group_start, struct extent_map *em)
868e3e0520bSJosef Bacik {
869e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
870e3e0520bSJosef Bacik 	struct btrfs_root *root = fs_info->extent_root;
871e3e0520bSJosef Bacik 	struct btrfs_path *path;
87232da5386SDavid Sterba 	struct btrfs_block_group *block_group;
873e3e0520bSJosef Bacik 	struct btrfs_free_cluster *cluster;
874e3e0520bSJosef Bacik 	struct btrfs_root *tree_root = fs_info->tree_root;
875e3e0520bSJosef Bacik 	struct btrfs_key key;
876e3e0520bSJosef Bacik 	struct inode *inode;
877e3e0520bSJosef Bacik 	struct kobject *kobj = NULL;
878e3e0520bSJosef Bacik 	int ret;
879e3e0520bSJosef Bacik 	int index;
880e3e0520bSJosef Bacik 	int factor;
881e3e0520bSJosef Bacik 	struct btrfs_caching_control *caching_ctl = NULL;
882e3e0520bSJosef Bacik 	bool remove_em;
883e3e0520bSJosef Bacik 	bool remove_rsv = false;
884e3e0520bSJosef Bacik 
885e3e0520bSJosef Bacik 	block_group = btrfs_lookup_block_group(fs_info, group_start);
886e3e0520bSJosef Bacik 	BUG_ON(!block_group);
887e3e0520bSJosef Bacik 	BUG_ON(!block_group->ro);
888e3e0520bSJosef Bacik 
889e3e0520bSJosef Bacik 	trace_btrfs_remove_block_group(block_group);
890e3e0520bSJosef Bacik 	/*
891e3e0520bSJosef Bacik 	 * Free the reserved super bytes from this block group before
892e3e0520bSJosef Bacik 	 * remove it.
893e3e0520bSJosef Bacik 	 */
894e3e0520bSJosef Bacik 	btrfs_free_excluded_extents(block_group);
895b3470b5dSDavid Sterba 	btrfs_free_ref_tree_range(fs_info, block_group->start,
896b3470b5dSDavid Sterba 				  block_group->length);
897e3e0520bSJosef Bacik 
898e3e0520bSJosef Bacik 	index = btrfs_bg_flags_to_raid_index(block_group->flags);
899e3e0520bSJosef Bacik 	factor = btrfs_bg_type_to_factor(block_group->flags);
900e3e0520bSJosef Bacik 
901e3e0520bSJosef Bacik 	/* make sure this block group isn't part of an allocation cluster */
902e3e0520bSJosef Bacik 	cluster = &fs_info->data_alloc_cluster;
903e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
904e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
905e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
906e3e0520bSJosef Bacik 
907e3e0520bSJosef Bacik 	/*
908e3e0520bSJosef Bacik 	 * make sure this block group isn't part of a metadata
909e3e0520bSJosef Bacik 	 * allocation cluster
910e3e0520bSJosef Bacik 	 */
911e3e0520bSJosef Bacik 	cluster = &fs_info->meta_alloc_cluster;
912e3e0520bSJosef Bacik 	spin_lock(&cluster->refill_lock);
913e3e0520bSJosef Bacik 	btrfs_return_cluster_to_free_space(block_group, cluster);
914e3e0520bSJosef Bacik 	spin_unlock(&cluster->refill_lock);
915e3e0520bSJosef Bacik 
916e3e0520bSJosef Bacik 	path = btrfs_alloc_path();
917e3e0520bSJosef Bacik 	if (!path) {
918e3e0520bSJosef Bacik 		ret = -ENOMEM;
919e3e0520bSJosef Bacik 		goto out;
920e3e0520bSJosef Bacik 	}
921e3e0520bSJosef Bacik 
922e3e0520bSJosef Bacik 	/*
923e3e0520bSJosef Bacik 	 * get the inode first so any iput calls done for the io_list
924e3e0520bSJosef Bacik 	 * aren't the final iput (no unlinks allowed now)
925e3e0520bSJosef Bacik 	 */
926e3e0520bSJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
927e3e0520bSJosef Bacik 
928e3e0520bSJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
929e3e0520bSJosef Bacik 	/*
930e3e0520bSJosef Bacik 	 * Make sure our free space cache IO is done before removing the
931e3e0520bSJosef Bacik 	 * free space inode
932e3e0520bSJosef Bacik 	 */
933e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
934e3e0520bSJosef Bacik 	if (!list_empty(&block_group->io_list)) {
935e3e0520bSJosef Bacik 		list_del_init(&block_group->io_list);
936e3e0520bSJosef Bacik 
937e3e0520bSJosef Bacik 		WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
938e3e0520bSJosef Bacik 
939e3e0520bSJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
940e3e0520bSJosef Bacik 		btrfs_wait_cache_io(trans, block_group, path);
941e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
942e3e0520bSJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
943e3e0520bSJosef Bacik 	}
944e3e0520bSJosef Bacik 
945e3e0520bSJosef Bacik 	if (!list_empty(&block_group->dirty_list)) {
946e3e0520bSJosef Bacik 		list_del_init(&block_group->dirty_list);
947e3e0520bSJosef Bacik 		remove_rsv = true;
948e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
949e3e0520bSJosef Bacik 	}
950e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
951e3e0520bSJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
952e3e0520bSJosef Bacik 
953e3e0520bSJosef Bacik 	if (!IS_ERR(inode)) {
954e3e0520bSJosef Bacik 		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
955e3e0520bSJosef Bacik 		if (ret) {
956e3e0520bSJosef Bacik 			btrfs_add_delayed_iput(inode);
957e3e0520bSJosef Bacik 			goto out;
958e3e0520bSJosef Bacik 		}
959e3e0520bSJosef Bacik 		clear_nlink(inode);
960e3e0520bSJosef Bacik 		/* One for the block groups ref */
961e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
962e3e0520bSJosef Bacik 		if (block_group->iref) {
963e3e0520bSJosef Bacik 			block_group->iref = 0;
964e3e0520bSJosef Bacik 			block_group->inode = NULL;
965e3e0520bSJosef Bacik 			spin_unlock(&block_group->lock);
966e3e0520bSJosef Bacik 			iput(inode);
967e3e0520bSJosef Bacik 		} else {
968e3e0520bSJosef Bacik 			spin_unlock(&block_group->lock);
969e3e0520bSJosef Bacik 		}
970e3e0520bSJosef Bacik 		/* One for our lookup ref */
971e3e0520bSJosef Bacik 		btrfs_add_delayed_iput(inode);
972e3e0520bSJosef Bacik 	}
973e3e0520bSJosef Bacik 
974e3e0520bSJosef Bacik 	key.objectid = BTRFS_FREE_SPACE_OBJECTID;
975e3e0520bSJosef Bacik 	key.type = 0;
976b3470b5dSDavid Sterba 	key.offset = block_group->start;
977e3e0520bSJosef Bacik 
978e3e0520bSJosef Bacik 	ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
979e3e0520bSJosef Bacik 	if (ret < 0)
980e3e0520bSJosef Bacik 		goto out;
981e3e0520bSJosef Bacik 	if (ret > 0)
982e3e0520bSJosef Bacik 		btrfs_release_path(path);
983e3e0520bSJosef Bacik 	if (ret == 0) {
984e3e0520bSJosef Bacik 		ret = btrfs_del_item(trans, tree_root, path);
985e3e0520bSJosef Bacik 		if (ret)
986e3e0520bSJosef Bacik 			goto out;
987e3e0520bSJosef Bacik 		btrfs_release_path(path);
988e3e0520bSJosef Bacik 	}
989e3e0520bSJosef Bacik 
990e3e0520bSJosef Bacik 	spin_lock(&fs_info->block_group_cache_lock);
991e3e0520bSJosef Bacik 	rb_erase(&block_group->cache_node,
992e3e0520bSJosef Bacik 		 &fs_info->block_group_cache_tree);
993e3e0520bSJosef Bacik 	RB_CLEAR_NODE(&block_group->cache_node);
994e3e0520bSJosef Bacik 
995b3470b5dSDavid Sterba 	if (fs_info->first_logical_byte == block_group->start)
996e3e0520bSJosef Bacik 		fs_info->first_logical_byte = (u64)-1;
997e3e0520bSJosef Bacik 	spin_unlock(&fs_info->block_group_cache_lock);
998e3e0520bSJosef Bacik 
999e3e0520bSJosef Bacik 	down_write(&block_group->space_info->groups_sem);
1000e3e0520bSJosef Bacik 	/*
1001e3e0520bSJosef Bacik 	 * we must use list_del_init so people can check to see if they
1002e3e0520bSJosef Bacik 	 * are still on the list after taking the semaphore
1003e3e0520bSJosef Bacik 	 */
1004e3e0520bSJosef Bacik 	list_del_init(&block_group->list);
1005e3e0520bSJosef Bacik 	if (list_empty(&block_group->space_info->block_groups[index])) {
1006e3e0520bSJosef Bacik 		kobj = block_group->space_info->block_group_kobjs[index];
1007e3e0520bSJosef Bacik 		block_group->space_info->block_group_kobjs[index] = NULL;
1008e3e0520bSJosef Bacik 		clear_avail_alloc_bits(fs_info, block_group->flags);
1009e3e0520bSJosef Bacik 	}
1010e3e0520bSJosef Bacik 	up_write(&block_group->space_info->groups_sem);
1011e3e0520bSJosef Bacik 	clear_incompat_bg_bits(fs_info, block_group->flags);
1012e3e0520bSJosef Bacik 	if (kobj) {
1013e3e0520bSJosef Bacik 		kobject_del(kobj);
1014e3e0520bSJosef Bacik 		kobject_put(kobj);
1015e3e0520bSJosef Bacik 	}
1016e3e0520bSJosef Bacik 
1017e3e0520bSJosef Bacik 	if (block_group->has_caching_ctl)
1018e3e0520bSJosef Bacik 		caching_ctl = btrfs_get_caching_control(block_group);
1019e3e0520bSJosef Bacik 	if (block_group->cached == BTRFS_CACHE_STARTED)
1020e3e0520bSJosef Bacik 		btrfs_wait_block_group_cache_done(block_group);
1021e3e0520bSJosef Bacik 	if (block_group->has_caching_ctl) {
1022e3e0520bSJosef Bacik 		down_write(&fs_info->commit_root_sem);
1023e3e0520bSJosef Bacik 		if (!caching_ctl) {
1024e3e0520bSJosef Bacik 			struct btrfs_caching_control *ctl;
1025e3e0520bSJosef Bacik 
1026e3e0520bSJosef Bacik 			list_for_each_entry(ctl,
1027e3e0520bSJosef Bacik 				    &fs_info->caching_block_groups, list)
1028e3e0520bSJosef Bacik 				if (ctl->block_group == block_group) {
1029e3e0520bSJosef Bacik 					caching_ctl = ctl;
1030e3e0520bSJosef Bacik 					refcount_inc(&caching_ctl->count);
1031e3e0520bSJosef Bacik 					break;
1032e3e0520bSJosef Bacik 				}
1033e3e0520bSJosef Bacik 		}
1034e3e0520bSJosef Bacik 		if (caching_ctl)
1035e3e0520bSJosef Bacik 			list_del_init(&caching_ctl->list);
1036e3e0520bSJosef Bacik 		up_write(&fs_info->commit_root_sem);
1037e3e0520bSJosef Bacik 		if (caching_ctl) {
1038e3e0520bSJosef Bacik 			/* Once for the caching bgs list and once for us. */
1039e3e0520bSJosef Bacik 			btrfs_put_caching_control(caching_ctl);
1040e3e0520bSJosef Bacik 			btrfs_put_caching_control(caching_ctl);
1041e3e0520bSJosef Bacik 		}
1042e3e0520bSJosef Bacik 	}
1043e3e0520bSJosef Bacik 
1044e3e0520bSJosef Bacik 	spin_lock(&trans->transaction->dirty_bgs_lock);
1045e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->dirty_list));
1046e3e0520bSJosef Bacik 	WARN_ON(!list_empty(&block_group->io_list));
1047e3e0520bSJosef Bacik 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1048e3e0520bSJosef Bacik 
1049e3e0520bSJosef Bacik 	btrfs_remove_free_space_cache(block_group);
1050e3e0520bSJosef Bacik 
1051e3e0520bSJosef Bacik 	spin_lock(&block_group->space_info->lock);
1052e3e0520bSJosef Bacik 	list_del_init(&block_group->ro_list);
1053e3e0520bSJosef Bacik 
1054e3e0520bSJosef Bacik 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1055e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->total_bytes
1056b3470b5dSDavid Sterba 			< block_group->length);
1057e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->bytes_readonly
1058b3470b5dSDavid Sterba 			< block_group->length);
1059e3e0520bSJosef Bacik 		WARN_ON(block_group->space_info->disk_total
1060b3470b5dSDavid Sterba 			< block_group->length * factor);
1061e3e0520bSJosef Bacik 	}
1062b3470b5dSDavid Sterba 	block_group->space_info->total_bytes -= block_group->length;
1063b3470b5dSDavid Sterba 	block_group->space_info->bytes_readonly -= block_group->length;
1064b3470b5dSDavid Sterba 	block_group->space_info->disk_total -= block_group->length * factor;
1065e3e0520bSJosef Bacik 
1066e3e0520bSJosef Bacik 	spin_unlock(&block_group->space_info->lock);
1067e3e0520bSJosef Bacik 
1068b3470b5dSDavid Sterba 	key.objectid = block_group->start;
1069b3470b5dSDavid Sterba 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
1070b3470b5dSDavid Sterba 	key.offset = block_group->length;
1071e3e0520bSJosef Bacik 
1072e3e0520bSJosef Bacik 	mutex_lock(&fs_info->chunk_mutex);
1073e3e0520bSJosef Bacik 	spin_lock(&block_group->lock);
1074e3e0520bSJosef Bacik 	block_group->removed = 1;
1075e3e0520bSJosef Bacik 	/*
1076e3e0520bSJosef Bacik 	 * At this point trimming can't start on this block group, because we
1077e3e0520bSJosef Bacik 	 * removed the block group from the tree fs_info->block_group_cache_tree
1078e3e0520bSJosef Bacik 	 * so no one can't find it anymore and even if someone already got this
1079e3e0520bSJosef Bacik 	 * block group before we removed it from the rbtree, they have already
1080e3e0520bSJosef Bacik 	 * incremented block_group->trimming - if they didn't, they won't find
1081e3e0520bSJosef Bacik 	 * any free space entries because we already removed them all when we
1082e3e0520bSJosef Bacik 	 * called btrfs_remove_free_space_cache().
1083e3e0520bSJosef Bacik 	 *
1084e3e0520bSJosef Bacik 	 * And we must not remove the extent map from the fs_info->mapping_tree
1085e3e0520bSJosef Bacik 	 * to prevent the same logical address range and physical device space
1086e3e0520bSJosef Bacik 	 * ranges from being reused for a new block group. This is because our
1087e3e0520bSJosef Bacik 	 * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1088e3e0520bSJosef Bacik 	 * completely transactionless, so while it is trimming a range the
1089e3e0520bSJosef Bacik 	 * currently running transaction might finish and a new one start,
1090e3e0520bSJosef Bacik 	 * allowing for new block groups to be created that can reuse the same
1091e3e0520bSJosef Bacik 	 * physical device locations unless we take this special care.
1092e3e0520bSJosef Bacik 	 *
1093e3e0520bSJosef Bacik 	 * There may also be an implicit trim operation if the file system
1094e3e0520bSJosef Bacik 	 * is mounted with -odiscard. The same protections must remain
1095e3e0520bSJosef Bacik 	 * in place until the extents have been discarded completely when
1096e3e0520bSJosef Bacik 	 * the transaction commit has completed.
1097e3e0520bSJosef Bacik 	 */
1098e3e0520bSJosef Bacik 	remove_em = (atomic_read(&block_group->trimming) == 0);
1099e3e0520bSJosef Bacik 	spin_unlock(&block_group->lock);
1100e3e0520bSJosef Bacik 
1101e3e0520bSJosef Bacik 	mutex_unlock(&fs_info->chunk_mutex);
1102e3e0520bSJosef Bacik 
1103e3e0520bSJosef Bacik 	ret = remove_block_group_free_space(trans, block_group);
1104e3e0520bSJosef Bacik 	if (ret)
1105e3e0520bSJosef Bacik 		goto out;
1106e3e0520bSJosef Bacik 
1107e3e0520bSJosef Bacik 	btrfs_put_block_group(block_group);
1108e3e0520bSJosef Bacik 	btrfs_put_block_group(block_group);
1109e3e0520bSJosef Bacik 
1110e3e0520bSJosef Bacik 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1111e3e0520bSJosef Bacik 	if (ret > 0)
1112e3e0520bSJosef Bacik 		ret = -EIO;
1113e3e0520bSJosef Bacik 	if (ret < 0)
1114e3e0520bSJosef Bacik 		goto out;
1115e3e0520bSJosef Bacik 
1116e3e0520bSJosef Bacik 	ret = btrfs_del_item(trans, root, path);
1117e3e0520bSJosef Bacik 	if (ret)
1118e3e0520bSJosef Bacik 		goto out;
1119e3e0520bSJosef Bacik 
1120e3e0520bSJosef Bacik 	if (remove_em) {
1121e3e0520bSJosef Bacik 		struct extent_map_tree *em_tree;
1122e3e0520bSJosef Bacik 
1123e3e0520bSJosef Bacik 		em_tree = &fs_info->mapping_tree;
1124e3e0520bSJosef Bacik 		write_lock(&em_tree->lock);
1125e3e0520bSJosef Bacik 		remove_extent_mapping(em_tree, em);
1126e3e0520bSJosef Bacik 		write_unlock(&em_tree->lock);
1127e3e0520bSJosef Bacik 		/* once for the tree */
1128e3e0520bSJosef Bacik 		free_extent_map(em);
1129e3e0520bSJosef Bacik 	}
1130e3e0520bSJosef Bacik out:
1131e3e0520bSJosef Bacik 	if (remove_rsv)
1132e3e0520bSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
1133e3e0520bSJosef Bacik 	btrfs_free_path(path);
1134e3e0520bSJosef Bacik 	return ret;
1135e3e0520bSJosef Bacik }
1136e3e0520bSJosef Bacik 
1137e3e0520bSJosef Bacik struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1138e3e0520bSJosef Bacik 		struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1139e3e0520bSJosef Bacik {
1140e3e0520bSJosef Bacik 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1141e3e0520bSJosef Bacik 	struct extent_map *em;
1142e3e0520bSJosef Bacik 	struct map_lookup *map;
1143e3e0520bSJosef Bacik 	unsigned int num_items;
1144e3e0520bSJosef Bacik 
1145e3e0520bSJosef Bacik 	read_lock(&em_tree->lock);
1146e3e0520bSJosef Bacik 	em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1147e3e0520bSJosef Bacik 	read_unlock(&em_tree->lock);
1148e3e0520bSJosef Bacik 	ASSERT(em && em->start == chunk_offset);
1149e3e0520bSJosef Bacik 
1150e3e0520bSJosef Bacik 	/*
1151e3e0520bSJosef Bacik 	 * We need to reserve 3 + N units from the metadata space info in order
1152e3e0520bSJosef Bacik 	 * to remove a block group (done at btrfs_remove_chunk() and at
1153e3e0520bSJosef Bacik 	 * btrfs_remove_block_group()), which are used for:
1154e3e0520bSJosef Bacik 	 *
1155e3e0520bSJosef Bacik 	 * 1 unit for adding the free space inode's orphan (located in the tree
1156e3e0520bSJosef Bacik 	 * of tree roots).
1157e3e0520bSJosef Bacik 	 * 1 unit for deleting the block group item (located in the extent
1158e3e0520bSJosef Bacik 	 * tree).
1159e3e0520bSJosef Bacik 	 * 1 unit for deleting the free space item (located in tree of tree
1160e3e0520bSJosef Bacik 	 * roots).
1161e3e0520bSJosef Bacik 	 * N units for deleting N device extent items corresponding to each
1162e3e0520bSJosef Bacik 	 * stripe (located in the device tree).
1163e3e0520bSJosef Bacik 	 *
1164e3e0520bSJosef Bacik 	 * In order to remove a block group we also need to reserve units in the
1165e3e0520bSJosef Bacik 	 * system space info in order to update the chunk tree (update one or
1166e3e0520bSJosef Bacik 	 * more device items and remove one chunk item), but this is done at
1167e3e0520bSJosef Bacik 	 * btrfs_remove_chunk() through a call to check_system_chunk().
1168e3e0520bSJosef Bacik 	 */
1169e3e0520bSJosef Bacik 	map = em->map_lookup;
1170e3e0520bSJosef Bacik 	num_items = 3 + map->num_stripes;
1171e3e0520bSJosef Bacik 	free_extent_map(em);
1172e3e0520bSJosef Bacik 
1173e3e0520bSJosef Bacik 	return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
1174e3e0520bSJosef Bacik 							   num_items, 1);
1175e3e0520bSJosef Bacik }
1176e3e0520bSJosef Bacik 
1177e3e0520bSJosef Bacik /*
117826ce2095SJosef Bacik  * Mark block group @cache read-only, so later write won't happen to block
117926ce2095SJosef Bacik  * group @cache.
118026ce2095SJosef Bacik  *
118126ce2095SJosef Bacik  * If @force is not set, this function will only mark the block group readonly
118226ce2095SJosef Bacik  * if we have enough free space (1M) in other metadata/system block groups.
118326ce2095SJosef Bacik  * If @force is not set, this function will mark the block group readonly
118426ce2095SJosef Bacik  * without checking free space.
118526ce2095SJosef Bacik  *
118626ce2095SJosef Bacik  * NOTE: This function doesn't care if other block groups can contain all the
118726ce2095SJosef Bacik  * data in this block group. That check should be done by relocation routine,
118826ce2095SJosef Bacik  * not this function.
118926ce2095SJosef Bacik  */
119032da5386SDavid Sterba static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
119126ce2095SJosef Bacik {
119226ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
119326ce2095SJosef Bacik 	u64 num_bytes;
119426ce2095SJosef Bacik 	u64 sinfo_used;
119526ce2095SJosef Bacik 	int ret = -ENOSPC;
119626ce2095SJosef Bacik 
119726ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
119826ce2095SJosef Bacik 	spin_lock(&cache->lock);
119926ce2095SJosef Bacik 
120026ce2095SJosef Bacik 	if (cache->ro) {
120126ce2095SJosef Bacik 		cache->ro++;
120226ce2095SJosef Bacik 		ret = 0;
120326ce2095SJosef Bacik 		goto out;
120426ce2095SJosef Bacik 	}
120526ce2095SJosef Bacik 
1206b3470b5dSDavid Sterba 	num_bytes = cache->length - cache->reserved - cache->pinned -
1207bf38be65SDavid Sterba 		    cache->bytes_super - cache->used;
120826ce2095SJosef Bacik 	sinfo_used = btrfs_space_info_used(sinfo, true);
120926ce2095SJosef Bacik 
121026ce2095SJosef Bacik 	/*
121126ce2095SJosef Bacik 	 * sinfo_used + num_bytes should always <= sinfo->total_bytes.
121226ce2095SJosef Bacik 	 *
121326ce2095SJosef Bacik 	 * Here we make sure if we mark this bg RO, we still have enough
1214f8935566SJosef Bacik 	 * free space as buffer.
121526ce2095SJosef Bacik 	 */
1216*a7a63accSJosef Bacik 	if (force || (sinfo_used + num_bytes <= sinfo->total_bytes)) {
121726ce2095SJosef Bacik 		sinfo->bytes_readonly += num_bytes;
121826ce2095SJosef Bacik 		cache->ro++;
121926ce2095SJosef Bacik 		list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
122026ce2095SJosef Bacik 		ret = 0;
122126ce2095SJosef Bacik 	}
122226ce2095SJosef Bacik out:
122326ce2095SJosef Bacik 	spin_unlock(&cache->lock);
122426ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
122526ce2095SJosef Bacik 	if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
122626ce2095SJosef Bacik 		btrfs_info(cache->fs_info,
1227b3470b5dSDavid Sterba 			"unable to make block group %llu ro", cache->start);
122826ce2095SJosef Bacik 		btrfs_info(cache->fs_info,
1229f8935566SJosef Bacik 			"sinfo_used=%llu bg_num_bytes=%llu",
1230f8935566SJosef Bacik 			sinfo_used, num_bytes);
123126ce2095SJosef Bacik 		btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
123226ce2095SJosef Bacik 	}
123326ce2095SJosef Bacik 	return ret;
123426ce2095SJosef Bacik }
123526ce2095SJosef Bacik 
123626ce2095SJosef Bacik /*
1237e3e0520bSJosef Bacik  * Process the unused_bgs list and remove any that don't have any allocated
1238e3e0520bSJosef Bacik  * space inside of them.
1239e3e0520bSJosef Bacik  */
1240e3e0520bSJosef Bacik void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1241e3e0520bSJosef Bacik {
124232da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1243e3e0520bSJosef Bacik 	struct btrfs_space_info *space_info;
1244e3e0520bSJosef Bacik 	struct btrfs_trans_handle *trans;
12456e80d4f8SDennis Zhou 	const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1246e3e0520bSJosef Bacik 	int ret = 0;
1247e3e0520bSJosef Bacik 
1248e3e0520bSJosef Bacik 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1249e3e0520bSJosef Bacik 		return;
1250e3e0520bSJosef Bacik 
1251e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1252e3e0520bSJosef Bacik 	while (!list_empty(&fs_info->unused_bgs)) {
1253e3e0520bSJosef Bacik 		u64 start, end;
1254e3e0520bSJosef Bacik 		int trimming;
1255e3e0520bSJosef Bacik 
1256e3e0520bSJosef Bacik 		block_group = list_first_entry(&fs_info->unused_bgs,
125732da5386SDavid Sterba 					       struct btrfs_block_group,
1258e3e0520bSJosef Bacik 					       bg_list);
1259e3e0520bSJosef Bacik 		list_del_init(&block_group->bg_list);
1260e3e0520bSJosef Bacik 
1261e3e0520bSJosef Bacik 		space_info = block_group->space_info;
1262e3e0520bSJosef Bacik 
1263e3e0520bSJosef Bacik 		if (ret || btrfs_mixed_space_info(space_info)) {
1264e3e0520bSJosef Bacik 			btrfs_put_block_group(block_group);
1265e3e0520bSJosef Bacik 			continue;
1266e3e0520bSJosef Bacik 		}
1267e3e0520bSJosef Bacik 		spin_unlock(&fs_info->unused_bgs_lock);
1268e3e0520bSJosef Bacik 
1269b0643e59SDennis Zhou 		btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1270b0643e59SDennis Zhou 
1271e3e0520bSJosef Bacik 		mutex_lock(&fs_info->delete_unused_bgs_mutex);
1272e3e0520bSJosef Bacik 
1273e3e0520bSJosef Bacik 		/* Don't want to race with allocators so take the groups_sem */
1274e3e0520bSJosef Bacik 		down_write(&space_info->groups_sem);
12756e80d4f8SDennis Zhou 
12766e80d4f8SDennis Zhou 		/*
12776e80d4f8SDennis Zhou 		 * Async discard moves the final block group discard to be prior
12786e80d4f8SDennis Zhou 		 * to the unused_bgs code path.  Therefore, if it's not fully
12796e80d4f8SDennis Zhou 		 * trimmed, punt it back to the async discard lists.
12806e80d4f8SDennis Zhou 		 */
12816e80d4f8SDennis Zhou 		if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
12826e80d4f8SDennis Zhou 		    !btrfs_is_free_space_trimmed(block_group)) {
12836e80d4f8SDennis Zhou 			trace_btrfs_skip_unused_block_group(block_group);
12846e80d4f8SDennis Zhou 			up_write(&space_info->groups_sem);
12856e80d4f8SDennis Zhou 			/* Requeue if we failed because of async discard */
12866e80d4f8SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
12876e80d4f8SDennis Zhou 						 block_group);
12886e80d4f8SDennis Zhou 			goto next;
12896e80d4f8SDennis Zhou 		}
12906e80d4f8SDennis Zhou 
1291e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1292e3e0520bSJosef Bacik 		if (block_group->reserved || block_group->pinned ||
1293bf38be65SDavid Sterba 		    block_group->used || block_group->ro ||
1294e3e0520bSJosef Bacik 		    list_is_singular(&block_group->list)) {
1295e3e0520bSJosef Bacik 			/*
1296e3e0520bSJosef Bacik 			 * We want to bail if we made new allocations or have
1297e3e0520bSJosef Bacik 			 * outstanding allocations in this block group.  We do
1298e3e0520bSJosef Bacik 			 * the ro check in case balance is currently acting on
1299e3e0520bSJosef Bacik 			 * this block group.
1300e3e0520bSJosef Bacik 			 */
1301e3e0520bSJosef Bacik 			trace_btrfs_skip_unused_block_group(block_group);
1302e3e0520bSJosef Bacik 			spin_unlock(&block_group->lock);
1303e3e0520bSJosef Bacik 			up_write(&space_info->groups_sem);
1304e3e0520bSJosef Bacik 			goto next;
1305e3e0520bSJosef Bacik 		}
1306e3e0520bSJosef Bacik 		spin_unlock(&block_group->lock);
1307e3e0520bSJosef Bacik 
1308e3e0520bSJosef Bacik 		/* We don't want to force the issue, only flip if it's ok. */
1309e11c0406SJosef Bacik 		ret = inc_block_group_ro(block_group, 0);
1310e3e0520bSJosef Bacik 		up_write(&space_info->groups_sem);
1311e3e0520bSJosef Bacik 		if (ret < 0) {
1312e3e0520bSJosef Bacik 			ret = 0;
1313e3e0520bSJosef Bacik 			goto next;
1314e3e0520bSJosef Bacik 		}
1315e3e0520bSJosef Bacik 
1316e3e0520bSJosef Bacik 		/*
1317e3e0520bSJosef Bacik 		 * Want to do this before we do anything else so we can recover
1318e3e0520bSJosef Bacik 		 * properly if we fail to join the transaction.
1319e3e0520bSJosef Bacik 		 */
1320e3e0520bSJosef Bacik 		trans = btrfs_start_trans_remove_block_group(fs_info,
1321b3470b5dSDavid Sterba 						     block_group->start);
1322e3e0520bSJosef Bacik 		if (IS_ERR(trans)) {
1323e3e0520bSJosef Bacik 			btrfs_dec_block_group_ro(block_group);
1324e3e0520bSJosef Bacik 			ret = PTR_ERR(trans);
1325e3e0520bSJosef Bacik 			goto next;
1326e3e0520bSJosef Bacik 		}
1327e3e0520bSJosef Bacik 
1328e3e0520bSJosef Bacik 		/*
1329e3e0520bSJosef Bacik 		 * We could have pending pinned extents for this block group,
1330e3e0520bSJosef Bacik 		 * just delete them, we don't care about them anymore.
1331e3e0520bSJosef Bacik 		 */
1332b3470b5dSDavid Sterba 		start = block_group->start;
1333b3470b5dSDavid Sterba 		end = start + block_group->length - 1;
1334e3e0520bSJosef Bacik 		/*
1335e3e0520bSJosef Bacik 		 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1336e3e0520bSJosef Bacik 		 * btrfs_finish_extent_commit(). If we are at transaction N,
1337e3e0520bSJosef Bacik 		 * another task might be running finish_extent_commit() for the
1338e3e0520bSJosef Bacik 		 * previous transaction N - 1, and have seen a range belonging
1339e3e0520bSJosef Bacik 		 * to the block group in freed_extents[] before we were able to
1340e3e0520bSJosef Bacik 		 * clear the whole block group range from freed_extents[]. This
1341e3e0520bSJosef Bacik 		 * means that task can lookup for the block group after we
1342e3e0520bSJosef Bacik 		 * unpinned it from freed_extents[] and removed it, leading to
1343e3e0520bSJosef Bacik 		 * a BUG_ON() at btrfs_unpin_extent_range().
1344e3e0520bSJosef Bacik 		 */
1345e3e0520bSJosef Bacik 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
1346e3e0520bSJosef Bacik 		ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
1347e3e0520bSJosef Bacik 				  EXTENT_DIRTY);
1348e3e0520bSJosef Bacik 		if (ret) {
1349e3e0520bSJosef Bacik 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1350e3e0520bSJosef Bacik 			btrfs_dec_block_group_ro(block_group);
1351e3e0520bSJosef Bacik 			goto end_trans;
1352e3e0520bSJosef Bacik 		}
1353e3e0520bSJosef Bacik 		ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
1354e3e0520bSJosef Bacik 				  EXTENT_DIRTY);
1355e3e0520bSJosef Bacik 		if (ret) {
1356e3e0520bSJosef Bacik 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1357e3e0520bSJosef Bacik 			btrfs_dec_block_group_ro(block_group);
1358e3e0520bSJosef Bacik 			goto end_trans;
1359e3e0520bSJosef Bacik 		}
1360e3e0520bSJosef Bacik 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1361e3e0520bSJosef Bacik 
1362b0643e59SDennis Zhou 		/*
1363b0643e59SDennis Zhou 		 * At this point, the block_group is read only and should fail
1364b0643e59SDennis Zhou 		 * new allocations.  However, btrfs_finish_extent_commit() can
1365b0643e59SDennis Zhou 		 * cause this block_group to be placed back on the discard
1366b0643e59SDennis Zhou 		 * lists because now the block_group isn't fully discarded.
1367b0643e59SDennis Zhou 		 * Bail here and try again later after discarding everything.
1368b0643e59SDennis Zhou 		 */
1369b0643e59SDennis Zhou 		spin_lock(&fs_info->discard_ctl.lock);
1370b0643e59SDennis Zhou 		if (!list_empty(&block_group->discard_list)) {
1371b0643e59SDennis Zhou 			spin_unlock(&fs_info->discard_ctl.lock);
1372b0643e59SDennis Zhou 			btrfs_dec_block_group_ro(block_group);
1373b0643e59SDennis Zhou 			btrfs_discard_queue_work(&fs_info->discard_ctl,
1374b0643e59SDennis Zhou 						 block_group);
1375b0643e59SDennis Zhou 			goto end_trans;
1376b0643e59SDennis Zhou 		}
1377b0643e59SDennis Zhou 		spin_unlock(&fs_info->discard_ctl.lock);
1378b0643e59SDennis Zhou 
1379e3e0520bSJosef Bacik 		/* Reset pinned so btrfs_put_block_group doesn't complain */
1380e3e0520bSJosef Bacik 		spin_lock(&space_info->lock);
1381e3e0520bSJosef Bacik 		spin_lock(&block_group->lock);
1382e3e0520bSJosef Bacik 
1383e3e0520bSJosef Bacik 		btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1384e3e0520bSJosef Bacik 						     -block_group->pinned);
1385e3e0520bSJosef Bacik 		space_info->bytes_readonly += block_group->pinned;
1386e3e0520bSJosef Bacik 		percpu_counter_add_batch(&space_info->total_bytes_pinned,
1387e3e0520bSJosef Bacik 				   -block_group->pinned,
1388e3e0520bSJosef Bacik 				   BTRFS_TOTAL_BYTES_PINNED_BATCH);
1389e3e0520bSJosef Bacik 		block_group->pinned = 0;
1390e3e0520bSJosef Bacik 
1391e3e0520bSJosef Bacik 		spin_unlock(&block_group->lock);
1392e3e0520bSJosef Bacik 		spin_unlock(&space_info->lock);
1393e3e0520bSJosef Bacik 
13946e80d4f8SDennis Zhou 		/*
13956e80d4f8SDennis Zhou 		 * The normal path here is an unused block group is passed here,
13966e80d4f8SDennis Zhou 		 * then trimming is handled in the transaction commit path.
13976e80d4f8SDennis Zhou 		 * Async discard interposes before this to do the trimming
13986e80d4f8SDennis Zhou 		 * before coming down the unused block group path as trimming
13996e80d4f8SDennis Zhou 		 * will no longer be done later in the transaction commit path.
14006e80d4f8SDennis Zhou 		 */
14016e80d4f8SDennis Zhou 		if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
14026e80d4f8SDennis Zhou 			goto flip_async;
14036e80d4f8SDennis Zhou 
1404e3e0520bSJosef Bacik 		/* DISCARD can flip during remount */
140546b27f50SDennis Zhou 		trimming = btrfs_test_opt(fs_info, DISCARD_SYNC);
1406e3e0520bSJosef Bacik 
1407e3e0520bSJosef Bacik 		/* Implicit trim during transaction commit. */
1408e3e0520bSJosef Bacik 		if (trimming)
1409e3e0520bSJosef Bacik 			btrfs_get_block_group_trimming(block_group);
1410e3e0520bSJosef Bacik 
1411e3e0520bSJosef Bacik 		/*
1412e3e0520bSJosef Bacik 		 * Btrfs_remove_chunk will abort the transaction if things go
1413e3e0520bSJosef Bacik 		 * horribly wrong.
1414e3e0520bSJosef Bacik 		 */
1415b3470b5dSDavid Sterba 		ret = btrfs_remove_chunk(trans, block_group->start);
1416e3e0520bSJosef Bacik 
1417e3e0520bSJosef Bacik 		if (ret) {
1418e3e0520bSJosef Bacik 			if (trimming)
1419e3e0520bSJosef Bacik 				btrfs_put_block_group_trimming(block_group);
1420e3e0520bSJosef Bacik 			goto end_trans;
1421e3e0520bSJosef Bacik 		}
1422e3e0520bSJosef Bacik 
1423e3e0520bSJosef Bacik 		/*
1424e3e0520bSJosef Bacik 		 * If we're not mounted with -odiscard, we can just forget
1425e3e0520bSJosef Bacik 		 * about this block group. Otherwise we'll need to wait
1426e3e0520bSJosef Bacik 		 * until transaction commit to do the actual discard.
1427e3e0520bSJosef Bacik 		 */
1428e3e0520bSJosef Bacik 		if (trimming) {
1429e3e0520bSJosef Bacik 			spin_lock(&fs_info->unused_bgs_lock);
1430e3e0520bSJosef Bacik 			/*
1431e3e0520bSJosef Bacik 			 * A concurrent scrub might have added us to the list
1432e3e0520bSJosef Bacik 			 * fs_info->unused_bgs, so use a list_move operation
1433e3e0520bSJosef Bacik 			 * to add the block group to the deleted_bgs list.
1434e3e0520bSJosef Bacik 			 */
1435e3e0520bSJosef Bacik 			list_move(&block_group->bg_list,
1436e3e0520bSJosef Bacik 				  &trans->transaction->deleted_bgs);
1437e3e0520bSJosef Bacik 			spin_unlock(&fs_info->unused_bgs_lock);
1438e3e0520bSJosef Bacik 			btrfs_get_block_group(block_group);
1439e3e0520bSJosef Bacik 		}
1440e3e0520bSJosef Bacik end_trans:
1441e3e0520bSJosef Bacik 		btrfs_end_transaction(trans);
1442e3e0520bSJosef Bacik next:
1443e3e0520bSJosef Bacik 		mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1444e3e0520bSJosef Bacik 		btrfs_put_block_group(block_group);
1445e3e0520bSJosef Bacik 		spin_lock(&fs_info->unused_bgs_lock);
1446e3e0520bSJosef Bacik 	}
1447e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
14486e80d4f8SDennis Zhou 	return;
14496e80d4f8SDennis Zhou 
14506e80d4f8SDennis Zhou flip_async:
14516e80d4f8SDennis Zhou 	btrfs_end_transaction(trans);
14526e80d4f8SDennis Zhou 	mutex_unlock(&fs_info->delete_unused_bgs_mutex);
14536e80d4f8SDennis Zhou 	btrfs_put_block_group(block_group);
14546e80d4f8SDennis Zhou 	btrfs_discard_punt_unused_bgs_list(fs_info);
1455e3e0520bSJosef Bacik }
1456e3e0520bSJosef Bacik 
145732da5386SDavid Sterba void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1458e3e0520bSJosef Bacik {
1459e3e0520bSJosef Bacik 	struct btrfs_fs_info *fs_info = bg->fs_info;
1460e3e0520bSJosef Bacik 
1461e3e0520bSJosef Bacik 	spin_lock(&fs_info->unused_bgs_lock);
1462e3e0520bSJosef Bacik 	if (list_empty(&bg->bg_list)) {
1463e3e0520bSJosef Bacik 		btrfs_get_block_group(bg);
1464e3e0520bSJosef Bacik 		trace_btrfs_add_unused_block_group(bg);
1465e3e0520bSJosef Bacik 		list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1466e3e0520bSJosef Bacik 	}
1467e3e0520bSJosef Bacik 	spin_unlock(&fs_info->unused_bgs_lock);
1468e3e0520bSJosef Bacik }
14694358d963SJosef Bacik 
14704358d963SJosef Bacik static int find_first_block_group(struct btrfs_fs_info *fs_info,
14714358d963SJosef Bacik 				  struct btrfs_path *path,
14724358d963SJosef Bacik 				  struct btrfs_key *key)
14734358d963SJosef Bacik {
14744358d963SJosef Bacik 	struct btrfs_root *root = fs_info->extent_root;
14754358d963SJosef Bacik 	int ret = 0;
14764358d963SJosef Bacik 	struct btrfs_key found_key;
14774358d963SJosef Bacik 	struct extent_buffer *leaf;
14784358d963SJosef Bacik 	struct btrfs_block_group_item bg;
14794358d963SJosef Bacik 	u64 flags;
14804358d963SJosef Bacik 	int slot;
14814358d963SJosef Bacik 
14824358d963SJosef Bacik 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
14834358d963SJosef Bacik 	if (ret < 0)
14844358d963SJosef Bacik 		goto out;
14854358d963SJosef Bacik 
14864358d963SJosef Bacik 	while (1) {
14874358d963SJosef Bacik 		slot = path->slots[0];
14884358d963SJosef Bacik 		leaf = path->nodes[0];
14894358d963SJosef Bacik 		if (slot >= btrfs_header_nritems(leaf)) {
14904358d963SJosef Bacik 			ret = btrfs_next_leaf(root, path);
14914358d963SJosef Bacik 			if (ret == 0)
14924358d963SJosef Bacik 				continue;
14934358d963SJosef Bacik 			if (ret < 0)
14944358d963SJosef Bacik 				goto out;
14954358d963SJosef Bacik 			break;
14964358d963SJosef Bacik 		}
14974358d963SJosef Bacik 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
14984358d963SJosef Bacik 
14994358d963SJosef Bacik 		if (found_key.objectid >= key->objectid &&
15004358d963SJosef Bacik 		    found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
15014358d963SJosef Bacik 			struct extent_map_tree *em_tree;
15024358d963SJosef Bacik 			struct extent_map *em;
15034358d963SJosef Bacik 
15044358d963SJosef Bacik 			em_tree = &root->fs_info->mapping_tree;
15054358d963SJosef Bacik 			read_lock(&em_tree->lock);
15064358d963SJosef Bacik 			em = lookup_extent_mapping(em_tree, found_key.objectid,
15074358d963SJosef Bacik 						   found_key.offset);
15084358d963SJosef Bacik 			read_unlock(&em_tree->lock);
15094358d963SJosef Bacik 			if (!em) {
15104358d963SJosef Bacik 				btrfs_err(fs_info,
15114358d963SJosef Bacik 			"logical %llu len %llu found bg but no related chunk",
15124358d963SJosef Bacik 					  found_key.objectid, found_key.offset);
15134358d963SJosef Bacik 				ret = -ENOENT;
15144358d963SJosef Bacik 			} else if (em->start != found_key.objectid ||
15154358d963SJosef Bacik 				   em->len != found_key.offset) {
15164358d963SJosef Bacik 				btrfs_err(fs_info,
15174358d963SJosef Bacik 		"block group %llu len %llu mismatch with chunk %llu len %llu",
15184358d963SJosef Bacik 					  found_key.objectid, found_key.offset,
15194358d963SJosef Bacik 					  em->start, em->len);
15204358d963SJosef Bacik 				ret = -EUCLEAN;
15214358d963SJosef Bacik 			} else {
15224358d963SJosef Bacik 				read_extent_buffer(leaf, &bg,
15234358d963SJosef Bacik 					btrfs_item_ptr_offset(leaf, slot),
15244358d963SJosef Bacik 					sizeof(bg));
1525de0dc456SDavid Sterba 				flags = btrfs_stack_block_group_flags(&bg) &
15264358d963SJosef Bacik 					BTRFS_BLOCK_GROUP_TYPE_MASK;
15274358d963SJosef Bacik 
15284358d963SJosef Bacik 				if (flags != (em->map_lookup->type &
15294358d963SJosef Bacik 					      BTRFS_BLOCK_GROUP_TYPE_MASK)) {
15304358d963SJosef Bacik 					btrfs_err(fs_info,
15314358d963SJosef Bacik "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
15324358d963SJosef Bacik 						found_key.objectid,
15334358d963SJosef Bacik 						found_key.offset, flags,
15344358d963SJosef Bacik 						(BTRFS_BLOCK_GROUP_TYPE_MASK &
15354358d963SJosef Bacik 						 em->map_lookup->type));
15364358d963SJosef Bacik 					ret = -EUCLEAN;
15374358d963SJosef Bacik 				} else {
15384358d963SJosef Bacik 					ret = 0;
15394358d963SJosef Bacik 				}
15404358d963SJosef Bacik 			}
15414358d963SJosef Bacik 			free_extent_map(em);
15424358d963SJosef Bacik 			goto out;
15434358d963SJosef Bacik 		}
15444358d963SJosef Bacik 		path->slots[0]++;
15454358d963SJosef Bacik 	}
15464358d963SJosef Bacik out:
15474358d963SJosef Bacik 	return ret;
15484358d963SJosef Bacik }
15494358d963SJosef Bacik 
15504358d963SJosef Bacik static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
15514358d963SJosef Bacik {
15524358d963SJosef Bacik 	u64 extra_flags = chunk_to_extended(flags) &
15534358d963SJosef Bacik 				BTRFS_EXTENDED_PROFILE_MASK;
15544358d963SJosef Bacik 
15554358d963SJosef Bacik 	write_seqlock(&fs_info->profiles_lock);
15564358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA)
15574358d963SJosef Bacik 		fs_info->avail_data_alloc_bits |= extra_flags;
15584358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
15594358d963SJosef Bacik 		fs_info->avail_metadata_alloc_bits |= extra_flags;
15604358d963SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
15614358d963SJosef Bacik 		fs_info->avail_system_alloc_bits |= extra_flags;
15624358d963SJosef Bacik 	write_sequnlock(&fs_info->profiles_lock);
15634358d963SJosef Bacik }
15644358d963SJosef Bacik 
156596a14336SNikolay Borisov /**
156696a14336SNikolay Borisov  * btrfs_rmap_block - Map a physical disk address to a list of logical addresses
156796a14336SNikolay Borisov  * @chunk_start:   logical address of block group
156896a14336SNikolay Borisov  * @physical:	   physical address to map to logical addresses
156996a14336SNikolay Borisov  * @logical:	   return array of logical addresses which map to @physical
157096a14336SNikolay Borisov  * @naddrs:	   length of @logical
157196a14336SNikolay Borisov  * @stripe_len:    size of IO stripe for the given block group
157296a14336SNikolay Borisov  *
157396a14336SNikolay Borisov  * Maps a particular @physical disk address to a list of @logical addresses.
157496a14336SNikolay Borisov  * Used primarily to exclude those portions of a block group that contain super
157596a14336SNikolay Borisov  * block copies.
157696a14336SNikolay Borisov  */
157796a14336SNikolay Borisov EXPORT_FOR_TESTS
157896a14336SNikolay Borisov int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
157996a14336SNikolay Borisov 		     u64 physical, u64 **logical, int *naddrs, int *stripe_len)
158096a14336SNikolay Borisov {
158196a14336SNikolay Borisov 	struct extent_map *em;
158296a14336SNikolay Borisov 	struct map_lookup *map;
158396a14336SNikolay Borisov 	u64 *buf;
158496a14336SNikolay Borisov 	u64 bytenr;
15851776ad17SNikolay Borisov 	u64 data_stripe_length;
15861776ad17SNikolay Borisov 	u64 io_stripe_size;
15871776ad17SNikolay Borisov 	int i, nr = 0;
15881776ad17SNikolay Borisov 	int ret = 0;
158996a14336SNikolay Borisov 
159096a14336SNikolay Borisov 	em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
159196a14336SNikolay Borisov 	if (IS_ERR(em))
159296a14336SNikolay Borisov 		return -EIO;
159396a14336SNikolay Borisov 
159496a14336SNikolay Borisov 	map = em->map_lookup;
15951776ad17SNikolay Borisov 	data_stripe_length = em->len;
15961776ad17SNikolay Borisov 	io_stripe_size = map->stripe_len;
159796a14336SNikolay Borisov 
159896a14336SNikolay Borisov 	if (map->type & BTRFS_BLOCK_GROUP_RAID10)
15991776ad17SNikolay Borisov 		data_stripe_length = div_u64(data_stripe_length,
16001776ad17SNikolay Borisov 					     map->num_stripes / map->sub_stripes);
160196a14336SNikolay Borisov 	else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
16021776ad17SNikolay Borisov 		data_stripe_length = div_u64(data_stripe_length, map->num_stripes);
160396a14336SNikolay Borisov 	else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
16041776ad17SNikolay Borisov 		data_stripe_length = div_u64(data_stripe_length,
16051776ad17SNikolay Borisov 					     nr_data_stripes(map));
16061776ad17SNikolay Borisov 		io_stripe_size = map->stripe_len * nr_data_stripes(map);
160796a14336SNikolay Borisov 	}
160896a14336SNikolay Borisov 
160996a14336SNikolay Borisov 	buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
16101776ad17SNikolay Borisov 	if (!buf) {
16111776ad17SNikolay Borisov 		ret = -ENOMEM;
16121776ad17SNikolay Borisov 		goto out;
16131776ad17SNikolay Borisov 	}
161496a14336SNikolay Borisov 
161596a14336SNikolay Borisov 	for (i = 0; i < map->num_stripes; i++) {
16161776ad17SNikolay Borisov 		bool already_inserted = false;
16171776ad17SNikolay Borisov 		u64 stripe_nr;
16181776ad17SNikolay Borisov 		int j;
16191776ad17SNikolay Borisov 
16201776ad17SNikolay Borisov 		if (!in_range(physical, map->stripes[i].physical,
16211776ad17SNikolay Borisov 			      data_stripe_length))
162296a14336SNikolay Borisov 			continue;
162396a14336SNikolay Borisov 
162496a14336SNikolay Borisov 		stripe_nr = physical - map->stripes[i].physical;
162596a14336SNikolay Borisov 		stripe_nr = div64_u64(stripe_nr, map->stripe_len);
162696a14336SNikolay Borisov 
162796a14336SNikolay Borisov 		if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
162896a14336SNikolay Borisov 			stripe_nr = stripe_nr * map->num_stripes + i;
162996a14336SNikolay Borisov 			stripe_nr = div_u64(stripe_nr, map->sub_stripes);
163096a14336SNikolay Borisov 		} else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
163196a14336SNikolay Borisov 			stripe_nr = stripe_nr * map->num_stripes + i;
163296a14336SNikolay Borisov 		}
163396a14336SNikolay Borisov 		/*
163496a14336SNikolay Borisov 		 * The remaining case would be for RAID56, multiply by
163596a14336SNikolay Borisov 		 * nr_data_stripes().  Alternatively, just use rmap_len below
163696a14336SNikolay Borisov 		 * instead of map->stripe_len
163796a14336SNikolay Borisov 		 */
163896a14336SNikolay Borisov 
16391776ad17SNikolay Borisov 		bytenr = chunk_start + stripe_nr * io_stripe_size;
16401776ad17SNikolay Borisov 
16411776ad17SNikolay Borisov 		/* Ensure we don't add duplicate addresses */
164296a14336SNikolay Borisov 		for (j = 0; j < nr; j++) {
16431776ad17SNikolay Borisov 			if (buf[j] == bytenr) {
16441776ad17SNikolay Borisov 				already_inserted = true;
164596a14336SNikolay Borisov 				break;
164696a14336SNikolay Borisov 			}
164796a14336SNikolay Borisov 		}
16481776ad17SNikolay Borisov 
16491776ad17SNikolay Borisov 		if (!already_inserted)
16501776ad17SNikolay Borisov 			buf[nr++] = bytenr;
165196a14336SNikolay Borisov 	}
165296a14336SNikolay Borisov 
165396a14336SNikolay Borisov 	*logical = buf;
165496a14336SNikolay Borisov 	*naddrs = nr;
16551776ad17SNikolay Borisov 	*stripe_len = io_stripe_size;
16561776ad17SNikolay Borisov out:
165796a14336SNikolay Borisov 	free_extent_map(em);
16581776ad17SNikolay Borisov 	return ret;
165996a14336SNikolay Borisov }
166096a14336SNikolay Borisov 
166132da5386SDavid Sterba static int exclude_super_stripes(struct btrfs_block_group *cache)
16624358d963SJosef Bacik {
16634358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
16644358d963SJosef Bacik 	u64 bytenr;
16654358d963SJosef Bacik 	u64 *logical;
16664358d963SJosef Bacik 	int stripe_len;
16674358d963SJosef Bacik 	int i, nr, ret;
16684358d963SJosef Bacik 
1669b3470b5dSDavid Sterba 	if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1670b3470b5dSDavid Sterba 		stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
16714358d963SJosef Bacik 		cache->bytes_super += stripe_len;
1672b3470b5dSDavid Sterba 		ret = btrfs_add_excluded_extent(fs_info, cache->start,
16734358d963SJosef Bacik 						stripe_len);
16744358d963SJosef Bacik 		if (ret)
16754358d963SJosef Bacik 			return ret;
16764358d963SJosef Bacik 	}
16774358d963SJosef Bacik 
16784358d963SJosef Bacik 	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
16794358d963SJosef Bacik 		bytenr = btrfs_sb_offset(i);
1680b3470b5dSDavid Sterba 		ret = btrfs_rmap_block(fs_info, cache->start,
16814358d963SJosef Bacik 				       bytenr, &logical, &nr, &stripe_len);
16824358d963SJosef Bacik 		if (ret)
16834358d963SJosef Bacik 			return ret;
16844358d963SJosef Bacik 
16854358d963SJosef Bacik 		while (nr--) {
16864358d963SJosef Bacik 			u64 start, len;
16874358d963SJosef Bacik 
1688b3470b5dSDavid Sterba 			if (logical[nr] > cache->start + cache->length)
16894358d963SJosef Bacik 				continue;
16904358d963SJosef Bacik 
1691b3470b5dSDavid Sterba 			if (logical[nr] + stripe_len <= cache->start)
16924358d963SJosef Bacik 				continue;
16934358d963SJosef Bacik 
16944358d963SJosef Bacik 			start = logical[nr];
1695b3470b5dSDavid Sterba 			if (start < cache->start) {
1696b3470b5dSDavid Sterba 				start = cache->start;
16974358d963SJosef Bacik 				len = (logical[nr] + stripe_len) - start;
16984358d963SJosef Bacik 			} else {
16994358d963SJosef Bacik 				len = min_t(u64, stripe_len,
1700b3470b5dSDavid Sterba 					    cache->start + cache->length - start);
17014358d963SJosef Bacik 			}
17024358d963SJosef Bacik 
17034358d963SJosef Bacik 			cache->bytes_super += len;
17044358d963SJosef Bacik 			ret = btrfs_add_excluded_extent(fs_info, start, len);
17054358d963SJosef Bacik 			if (ret) {
17064358d963SJosef Bacik 				kfree(logical);
17074358d963SJosef Bacik 				return ret;
17084358d963SJosef Bacik 			}
17094358d963SJosef Bacik 		}
17104358d963SJosef Bacik 
17114358d963SJosef Bacik 		kfree(logical);
17124358d963SJosef Bacik 	}
17134358d963SJosef Bacik 	return 0;
17144358d963SJosef Bacik }
17154358d963SJosef Bacik 
171632da5386SDavid Sterba static void link_block_group(struct btrfs_block_group *cache)
17174358d963SJosef Bacik {
17184358d963SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
17194358d963SJosef Bacik 	int index = btrfs_bg_flags_to_raid_index(cache->flags);
17204358d963SJosef Bacik 	bool first = false;
17214358d963SJosef Bacik 
17224358d963SJosef Bacik 	down_write(&space_info->groups_sem);
17234358d963SJosef Bacik 	if (list_empty(&space_info->block_groups[index]))
17244358d963SJosef Bacik 		first = true;
17254358d963SJosef Bacik 	list_add_tail(&cache->list, &space_info->block_groups[index]);
17264358d963SJosef Bacik 	up_write(&space_info->groups_sem);
17274358d963SJosef Bacik 
17284358d963SJosef Bacik 	if (first)
17294358d963SJosef Bacik 		btrfs_sysfs_add_block_group_type(cache);
17304358d963SJosef Bacik }
17314358d963SJosef Bacik 
173232da5386SDavid Sterba static struct btrfs_block_group *btrfs_create_block_group_cache(
17334358d963SJosef Bacik 		struct btrfs_fs_info *fs_info, u64 start, u64 size)
17344358d963SJosef Bacik {
173532da5386SDavid Sterba 	struct btrfs_block_group *cache;
17364358d963SJosef Bacik 
17374358d963SJosef Bacik 	cache = kzalloc(sizeof(*cache), GFP_NOFS);
17384358d963SJosef Bacik 	if (!cache)
17394358d963SJosef Bacik 		return NULL;
17404358d963SJosef Bacik 
17414358d963SJosef Bacik 	cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
17424358d963SJosef Bacik 					GFP_NOFS);
17434358d963SJosef Bacik 	if (!cache->free_space_ctl) {
17444358d963SJosef Bacik 		kfree(cache);
17454358d963SJosef Bacik 		return NULL;
17464358d963SJosef Bacik 	}
17474358d963SJosef Bacik 
1748b3470b5dSDavid Sterba 	cache->start = start;
1749b3470b5dSDavid Sterba 	cache->length = size;
17504358d963SJosef Bacik 
17514358d963SJosef Bacik 	cache->fs_info = fs_info;
17524358d963SJosef Bacik 	cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
17534358d963SJosef Bacik 	set_free_space_tree_thresholds(cache);
17544358d963SJosef Bacik 
17556e80d4f8SDennis Zhou 	cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
17566e80d4f8SDennis Zhou 
17574358d963SJosef Bacik 	atomic_set(&cache->count, 1);
17584358d963SJosef Bacik 	spin_lock_init(&cache->lock);
17594358d963SJosef Bacik 	init_rwsem(&cache->data_rwsem);
17604358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->list);
17614358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->cluster_list);
17624358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->bg_list);
17634358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->ro_list);
1764b0643e59SDennis Zhou 	INIT_LIST_HEAD(&cache->discard_list);
17654358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->dirty_list);
17664358d963SJosef Bacik 	INIT_LIST_HEAD(&cache->io_list);
17674358d963SJosef Bacik 	btrfs_init_free_space_ctl(cache);
17684358d963SJosef Bacik 	atomic_set(&cache->trimming, 0);
17694358d963SJosef Bacik 	mutex_init(&cache->free_space_lock);
17704358d963SJosef Bacik 	btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
17714358d963SJosef Bacik 
17724358d963SJosef Bacik 	return cache;
17734358d963SJosef Bacik }
17744358d963SJosef Bacik 
17754358d963SJosef Bacik /*
17764358d963SJosef Bacik  * Iterate all chunks and verify that each of them has the corresponding block
17774358d963SJosef Bacik  * group
17784358d963SJosef Bacik  */
17794358d963SJosef Bacik static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
17804358d963SJosef Bacik {
17814358d963SJosef Bacik 	struct extent_map_tree *map_tree = &fs_info->mapping_tree;
17824358d963SJosef Bacik 	struct extent_map *em;
178332da5386SDavid Sterba 	struct btrfs_block_group *bg;
17844358d963SJosef Bacik 	u64 start = 0;
17854358d963SJosef Bacik 	int ret = 0;
17864358d963SJosef Bacik 
17874358d963SJosef Bacik 	while (1) {
17884358d963SJosef Bacik 		read_lock(&map_tree->lock);
17894358d963SJosef Bacik 		/*
17904358d963SJosef Bacik 		 * lookup_extent_mapping will return the first extent map
17914358d963SJosef Bacik 		 * intersecting the range, so setting @len to 1 is enough to
17924358d963SJosef Bacik 		 * get the first chunk.
17934358d963SJosef Bacik 		 */
17944358d963SJosef Bacik 		em = lookup_extent_mapping(map_tree, start, 1);
17954358d963SJosef Bacik 		read_unlock(&map_tree->lock);
17964358d963SJosef Bacik 		if (!em)
17974358d963SJosef Bacik 			break;
17984358d963SJosef Bacik 
17994358d963SJosef Bacik 		bg = btrfs_lookup_block_group(fs_info, em->start);
18004358d963SJosef Bacik 		if (!bg) {
18014358d963SJosef Bacik 			btrfs_err(fs_info,
18024358d963SJosef Bacik 	"chunk start=%llu len=%llu doesn't have corresponding block group",
18034358d963SJosef Bacik 				     em->start, em->len);
18044358d963SJosef Bacik 			ret = -EUCLEAN;
18054358d963SJosef Bacik 			free_extent_map(em);
18064358d963SJosef Bacik 			break;
18074358d963SJosef Bacik 		}
1808b3470b5dSDavid Sterba 		if (bg->start != em->start || bg->length != em->len ||
18094358d963SJosef Bacik 		    (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
18104358d963SJosef Bacik 		    (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
18114358d963SJosef Bacik 			btrfs_err(fs_info,
18124358d963SJosef Bacik "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
18134358d963SJosef Bacik 				em->start, em->len,
18144358d963SJosef Bacik 				em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
1815b3470b5dSDavid Sterba 				bg->start, bg->length,
18164358d963SJosef Bacik 				bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
18174358d963SJosef Bacik 			ret = -EUCLEAN;
18184358d963SJosef Bacik 			free_extent_map(em);
18194358d963SJosef Bacik 			btrfs_put_block_group(bg);
18204358d963SJosef Bacik 			break;
18214358d963SJosef Bacik 		}
18224358d963SJosef Bacik 		start = em->start + em->len;
18234358d963SJosef Bacik 		free_extent_map(em);
18244358d963SJosef Bacik 		btrfs_put_block_group(bg);
18254358d963SJosef Bacik 	}
18264358d963SJosef Bacik 	return ret;
18274358d963SJosef Bacik }
18284358d963SJosef Bacik 
1829ffb9e0f0SQu Wenruo static int read_one_block_group(struct btrfs_fs_info *info,
1830ffb9e0f0SQu Wenruo 				struct btrfs_path *path,
1831d49a2ddbSQu Wenruo 				const struct btrfs_key *key,
1832ffb9e0f0SQu Wenruo 				int need_clear)
1833ffb9e0f0SQu Wenruo {
1834ffb9e0f0SQu Wenruo 	struct extent_buffer *leaf = path->nodes[0];
183532da5386SDavid Sterba 	struct btrfs_block_group *cache;
1836ffb9e0f0SQu Wenruo 	struct btrfs_space_info *space_info;
1837ffb9e0f0SQu Wenruo 	struct btrfs_block_group_item bgi;
1838ffb9e0f0SQu Wenruo 	const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
1839ffb9e0f0SQu Wenruo 	int slot = path->slots[0];
1840ffb9e0f0SQu Wenruo 	int ret;
1841ffb9e0f0SQu Wenruo 
1842d49a2ddbSQu Wenruo 	ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
1843ffb9e0f0SQu Wenruo 
1844d49a2ddbSQu Wenruo 	cache = btrfs_create_block_group_cache(info, key->objectid, key->offset);
1845ffb9e0f0SQu Wenruo 	if (!cache)
1846ffb9e0f0SQu Wenruo 		return -ENOMEM;
1847ffb9e0f0SQu Wenruo 
1848ffb9e0f0SQu Wenruo 	if (need_clear) {
1849ffb9e0f0SQu Wenruo 		/*
1850ffb9e0f0SQu Wenruo 		 * When we mount with old space cache, we need to
1851ffb9e0f0SQu Wenruo 		 * set BTRFS_DC_CLEAR and set dirty flag.
1852ffb9e0f0SQu Wenruo 		 *
1853ffb9e0f0SQu Wenruo 		 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
1854ffb9e0f0SQu Wenruo 		 *    truncate the old free space cache inode and
1855ffb9e0f0SQu Wenruo 		 *    setup a new one.
1856ffb9e0f0SQu Wenruo 		 * b) Setting 'dirty flag' makes sure that we flush
1857ffb9e0f0SQu Wenruo 		 *    the new space cache info onto disk.
1858ffb9e0f0SQu Wenruo 		 */
1859ffb9e0f0SQu Wenruo 		if (btrfs_test_opt(info, SPACE_CACHE))
1860ffb9e0f0SQu Wenruo 			cache->disk_cache_state = BTRFS_DC_CLEAR;
1861ffb9e0f0SQu Wenruo 	}
1862ffb9e0f0SQu Wenruo 	read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
1863ffb9e0f0SQu Wenruo 			   sizeof(bgi));
1864ffb9e0f0SQu Wenruo 	cache->used = btrfs_stack_block_group_used(&bgi);
1865ffb9e0f0SQu Wenruo 	cache->flags = btrfs_stack_block_group_flags(&bgi);
1866ffb9e0f0SQu Wenruo 	if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
1867ffb9e0f0SQu Wenruo 	    (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
1868ffb9e0f0SQu Wenruo 			btrfs_err(info,
1869ffb9e0f0SQu Wenruo "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
1870ffb9e0f0SQu Wenruo 				  cache->start);
1871ffb9e0f0SQu Wenruo 			ret = -EINVAL;
1872ffb9e0f0SQu Wenruo 			goto error;
1873ffb9e0f0SQu Wenruo 	}
1874ffb9e0f0SQu Wenruo 
1875ffb9e0f0SQu Wenruo 	/*
1876ffb9e0f0SQu Wenruo 	 * We need to exclude the super stripes now so that the space info has
1877ffb9e0f0SQu Wenruo 	 * super bytes accounted for, otherwise we'll think we have more space
1878ffb9e0f0SQu Wenruo 	 * than we actually do.
1879ffb9e0f0SQu Wenruo 	 */
1880ffb9e0f0SQu Wenruo 	ret = exclude_super_stripes(cache);
1881ffb9e0f0SQu Wenruo 	if (ret) {
1882ffb9e0f0SQu Wenruo 		/* We may have excluded something, so call this just in case. */
1883ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
1884ffb9e0f0SQu Wenruo 		goto error;
1885ffb9e0f0SQu Wenruo 	}
1886ffb9e0f0SQu Wenruo 
1887ffb9e0f0SQu Wenruo 	/*
1888ffb9e0f0SQu Wenruo 	 * Check for two cases, either we are full, and therefore don't need
1889ffb9e0f0SQu Wenruo 	 * to bother with the caching work since we won't find any space, or we
1890ffb9e0f0SQu Wenruo 	 * are empty, and we can just add all the space in and be done with it.
1891ffb9e0f0SQu Wenruo 	 * This saves us _a_lot_ of time, particularly in the full case.
1892ffb9e0f0SQu Wenruo 	 */
1893d49a2ddbSQu Wenruo 	if (key->offset == cache->used) {
1894ffb9e0f0SQu Wenruo 		cache->last_byte_to_unpin = (u64)-1;
1895ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
1896ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
1897ffb9e0f0SQu Wenruo 	} else if (cache->used == 0) {
1898ffb9e0f0SQu Wenruo 		cache->last_byte_to_unpin = (u64)-1;
1899ffb9e0f0SQu Wenruo 		cache->cached = BTRFS_CACHE_FINISHED;
1900d49a2ddbSQu Wenruo 		add_new_free_space(cache, key->objectid,
1901d49a2ddbSQu Wenruo 				   key->objectid + key->offset);
1902ffb9e0f0SQu Wenruo 		btrfs_free_excluded_extents(cache);
1903ffb9e0f0SQu Wenruo 	}
1904ffb9e0f0SQu Wenruo 
1905ffb9e0f0SQu Wenruo 	ret = btrfs_add_block_group_cache(info, cache);
1906ffb9e0f0SQu Wenruo 	if (ret) {
1907ffb9e0f0SQu Wenruo 		btrfs_remove_free_space_cache(cache);
1908ffb9e0f0SQu Wenruo 		goto error;
1909ffb9e0f0SQu Wenruo 	}
1910ffb9e0f0SQu Wenruo 	trace_btrfs_add_block_group(info, cache, 0);
1911d49a2ddbSQu Wenruo 	btrfs_update_space_info(info, cache->flags, key->offset,
1912ffb9e0f0SQu Wenruo 				cache->used, cache->bytes_super, &space_info);
1913ffb9e0f0SQu Wenruo 
1914ffb9e0f0SQu Wenruo 	cache->space_info = space_info;
1915ffb9e0f0SQu Wenruo 
1916ffb9e0f0SQu Wenruo 	link_block_group(cache);
1917ffb9e0f0SQu Wenruo 
1918ffb9e0f0SQu Wenruo 	set_avail_alloc_bits(info, cache->flags);
1919ffb9e0f0SQu Wenruo 	if (btrfs_chunk_readonly(info, cache->start)) {
1920ffb9e0f0SQu Wenruo 		inc_block_group_ro(cache, 1);
1921ffb9e0f0SQu Wenruo 	} else if (cache->used == 0) {
1922ffb9e0f0SQu Wenruo 		ASSERT(list_empty(&cache->bg_list));
19236e80d4f8SDennis Zhou 		if (btrfs_test_opt(info, DISCARD_ASYNC))
19246e80d4f8SDennis Zhou 			btrfs_discard_queue_work(&info->discard_ctl, cache);
19256e80d4f8SDennis Zhou 		else
1926ffb9e0f0SQu Wenruo 			btrfs_mark_bg_unused(cache);
1927ffb9e0f0SQu Wenruo 	}
1928ffb9e0f0SQu Wenruo 	return 0;
1929ffb9e0f0SQu Wenruo error:
1930ffb9e0f0SQu Wenruo 	btrfs_put_block_group(cache);
1931ffb9e0f0SQu Wenruo 	return ret;
1932ffb9e0f0SQu Wenruo }
1933ffb9e0f0SQu Wenruo 
19344358d963SJosef Bacik int btrfs_read_block_groups(struct btrfs_fs_info *info)
19354358d963SJosef Bacik {
19364358d963SJosef Bacik 	struct btrfs_path *path;
19374358d963SJosef Bacik 	int ret;
193832da5386SDavid Sterba 	struct btrfs_block_group *cache;
19394358d963SJosef Bacik 	struct btrfs_space_info *space_info;
19404358d963SJosef Bacik 	struct btrfs_key key;
19414358d963SJosef Bacik 	int need_clear = 0;
19424358d963SJosef Bacik 	u64 cache_gen;
19434358d963SJosef Bacik 
19444358d963SJosef Bacik 	key.objectid = 0;
19454358d963SJosef Bacik 	key.offset = 0;
19464358d963SJosef Bacik 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
19474358d963SJosef Bacik 	path = btrfs_alloc_path();
19484358d963SJosef Bacik 	if (!path)
19494358d963SJosef Bacik 		return -ENOMEM;
19504358d963SJosef Bacik 	path->reada = READA_FORWARD;
19514358d963SJosef Bacik 
19524358d963SJosef Bacik 	cache_gen = btrfs_super_cache_generation(info->super_copy);
19534358d963SJosef Bacik 	if (btrfs_test_opt(info, SPACE_CACHE) &&
19544358d963SJosef Bacik 	    btrfs_super_generation(info->super_copy) != cache_gen)
19554358d963SJosef Bacik 		need_clear = 1;
19564358d963SJosef Bacik 	if (btrfs_test_opt(info, CLEAR_CACHE))
19574358d963SJosef Bacik 		need_clear = 1;
19584358d963SJosef Bacik 
19594358d963SJosef Bacik 	while (1) {
19604358d963SJosef Bacik 		ret = find_first_block_group(info, path, &key);
19614358d963SJosef Bacik 		if (ret > 0)
19624358d963SJosef Bacik 			break;
19634358d963SJosef Bacik 		if (ret != 0)
19644358d963SJosef Bacik 			goto error;
19654358d963SJosef Bacik 
1966ffb9e0f0SQu Wenruo 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1967d49a2ddbSQu Wenruo 		ret = read_one_block_group(info, path, &key, need_clear);
1968ffb9e0f0SQu Wenruo 		if (ret < 0)
19694358d963SJosef Bacik 			goto error;
1970ffb9e0f0SQu Wenruo 		key.objectid += key.offset;
1971ffb9e0f0SQu Wenruo 		key.offset = 0;
19724358d963SJosef Bacik 		btrfs_release_path(path);
19734358d963SJosef Bacik 	}
19744358d963SJosef Bacik 
19754358d963SJosef Bacik 	list_for_each_entry_rcu(space_info, &info->space_info, list) {
19764358d963SJosef Bacik 		if (!(btrfs_get_alloc_profile(info, space_info->flags) &
19774358d963SJosef Bacik 		      (BTRFS_BLOCK_GROUP_RAID10 |
19784358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID1_MASK |
19794358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_RAID56_MASK |
19804358d963SJosef Bacik 		       BTRFS_BLOCK_GROUP_DUP)))
19814358d963SJosef Bacik 			continue;
19824358d963SJosef Bacik 		/*
19834358d963SJosef Bacik 		 * Avoid allocating from un-mirrored block group if there are
19844358d963SJosef Bacik 		 * mirrored block groups.
19854358d963SJosef Bacik 		 */
19864358d963SJosef Bacik 		list_for_each_entry(cache,
19874358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_RAID0],
19884358d963SJosef Bacik 				list)
1989e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
19904358d963SJosef Bacik 		list_for_each_entry(cache,
19914358d963SJosef Bacik 				&space_info->block_groups[BTRFS_RAID_SINGLE],
19924358d963SJosef Bacik 				list)
1993e11c0406SJosef Bacik 			inc_block_group_ro(cache, 1);
19944358d963SJosef Bacik 	}
19954358d963SJosef Bacik 
19964358d963SJosef Bacik 	btrfs_init_global_block_rsv(info);
19974358d963SJosef Bacik 	ret = check_chunk_block_group_mappings(info);
19984358d963SJosef Bacik error:
19994358d963SJosef Bacik 	btrfs_free_path(path);
20004358d963SJosef Bacik 	return ret;
20014358d963SJosef Bacik }
20024358d963SJosef Bacik 
20034358d963SJosef Bacik void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
20044358d963SJosef Bacik {
20054358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
200632da5386SDavid Sterba 	struct btrfs_block_group *block_group;
20074358d963SJosef Bacik 	struct btrfs_root *extent_root = fs_info->extent_root;
20084358d963SJosef Bacik 	struct btrfs_block_group_item item;
20094358d963SJosef Bacik 	struct btrfs_key key;
20104358d963SJosef Bacik 	int ret = 0;
20114358d963SJosef Bacik 
20124358d963SJosef Bacik 	if (!trans->can_flush_pending_bgs)
20134358d963SJosef Bacik 		return;
20144358d963SJosef Bacik 
20154358d963SJosef Bacik 	while (!list_empty(&trans->new_bgs)) {
20164358d963SJosef Bacik 		block_group = list_first_entry(&trans->new_bgs,
201732da5386SDavid Sterba 					       struct btrfs_block_group,
20184358d963SJosef Bacik 					       bg_list);
20194358d963SJosef Bacik 		if (ret)
20204358d963SJosef Bacik 			goto next;
20214358d963SJosef Bacik 
20224358d963SJosef Bacik 		spin_lock(&block_group->lock);
2023de0dc456SDavid Sterba 		btrfs_set_stack_block_group_used(&item, block_group->used);
2024de0dc456SDavid Sterba 		btrfs_set_stack_block_group_chunk_objectid(&item,
20253d976388SDavid Sterba 				BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2026de0dc456SDavid Sterba 		btrfs_set_stack_block_group_flags(&item, block_group->flags);
2027b3470b5dSDavid Sterba 		key.objectid = block_group->start;
2028b3470b5dSDavid Sterba 		key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2029b3470b5dSDavid Sterba 		key.offset = block_group->length;
20304358d963SJosef Bacik 		spin_unlock(&block_group->lock);
20314358d963SJosef Bacik 
20324358d963SJosef Bacik 		ret = btrfs_insert_item(trans, extent_root, &key, &item,
20334358d963SJosef Bacik 					sizeof(item));
20344358d963SJosef Bacik 		if (ret)
20354358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
20364358d963SJosef Bacik 		ret = btrfs_finish_chunk_alloc(trans, key.objectid, key.offset);
20374358d963SJosef Bacik 		if (ret)
20384358d963SJosef Bacik 			btrfs_abort_transaction(trans, ret);
20394358d963SJosef Bacik 		add_block_group_free_space(trans, block_group);
20404358d963SJosef Bacik 		/* Already aborted the transaction if it failed. */
20414358d963SJosef Bacik next:
20424358d963SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
20434358d963SJosef Bacik 		list_del_init(&block_group->bg_list);
20444358d963SJosef Bacik 	}
20454358d963SJosef Bacik 	btrfs_trans_release_chunk_metadata(trans);
20464358d963SJosef Bacik }
20474358d963SJosef Bacik 
20484358d963SJosef Bacik int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
20494358d963SJosef Bacik 			   u64 type, u64 chunk_offset, u64 size)
20504358d963SJosef Bacik {
20514358d963SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
205232da5386SDavid Sterba 	struct btrfs_block_group *cache;
20534358d963SJosef Bacik 	int ret;
20544358d963SJosef Bacik 
20554358d963SJosef Bacik 	btrfs_set_log_full_commit(trans);
20564358d963SJosef Bacik 
20574358d963SJosef Bacik 	cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
20584358d963SJosef Bacik 	if (!cache)
20594358d963SJosef Bacik 		return -ENOMEM;
20604358d963SJosef Bacik 
2061bf38be65SDavid Sterba 	cache->used = bytes_used;
20624358d963SJosef Bacik 	cache->flags = type;
20634358d963SJosef Bacik 	cache->last_byte_to_unpin = (u64)-1;
20644358d963SJosef Bacik 	cache->cached = BTRFS_CACHE_FINISHED;
20654358d963SJosef Bacik 	cache->needs_free_space = 1;
20664358d963SJosef Bacik 	ret = exclude_super_stripes(cache);
20674358d963SJosef Bacik 	if (ret) {
20684358d963SJosef Bacik 		/* We may have excluded something, so call this just in case */
20694358d963SJosef Bacik 		btrfs_free_excluded_extents(cache);
20704358d963SJosef Bacik 		btrfs_put_block_group(cache);
20714358d963SJosef Bacik 		return ret;
20724358d963SJosef Bacik 	}
20734358d963SJosef Bacik 
20744358d963SJosef Bacik 	add_new_free_space(cache, chunk_offset, chunk_offset + size);
20754358d963SJosef Bacik 
20764358d963SJosef Bacik 	btrfs_free_excluded_extents(cache);
20774358d963SJosef Bacik 
20784358d963SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
20794358d963SJosef Bacik 	if (btrfs_should_fragment_free_space(cache)) {
20804358d963SJosef Bacik 		u64 new_bytes_used = size - bytes_used;
20814358d963SJosef Bacik 
20824358d963SJosef Bacik 		bytes_used += new_bytes_used >> 1;
2083e11c0406SJosef Bacik 		fragment_free_space(cache);
20844358d963SJosef Bacik 	}
20854358d963SJosef Bacik #endif
20864358d963SJosef Bacik 	/*
20874358d963SJosef Bacik 	 * Ensure the corresponding space_info object is created and
20884358d963SJosef Bacik 	 * assigned to our block group. We want our bg to be added to the rbtree
20894358d963SJosef Bacik 	 * with its ->space_info set.
20904358d963SJosef Bacik 	 */
20914358d963SJosef Bacik 	cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
20924358d963SJosef Bacik 	ASSERT(cache->space_info);
20934358d963SJosef Bacik 
20944358d963SJosef Bacik 	ret = btrfs_add_block_group_cache(fs_info, cache);
20954358d963SJosef Bacik 	if (ret) {
20964358d963SJosef Bacik 		btrfs_remove_free_space_cache(cache);
20974358d963SJosef Bacik 		btrfs_put_block_group(cache);
20984358d963SJosef Bacik 		return ret;
20994358d963SJosef Bacik 	}
21004358d963SJosef Bacik 
21014358d963SJosef Bacik 	/*
21024358d963SJosef Bacik 	 * Now that our block group has its ->space_info set and is inserted in
21034358d963SJosef Bacik 	 * the rbtree, update the space info's counters.
21044358d963SJosef Bacik 	 */
21054358d963SJosef Bacik 	trace_btrfs_add_block_group(fs_info, cache, 1);
21064358d963SJosef Bacik 	btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
21074358d963SJosef Bacik 				cache->bytes_super, &cache->space_info);
21084358d963SJosef Bacik 	btrfs_update_global_block_rsv(fs_info);
21094358d963SJosef Bacik 
21104358d963SJosef Bacik 	link_block_group(cache);
21114358d963SJosef Bacik 
21124358d963SJosef Bacik 	list_add_tail(&cache->bg_list, &trans->new_bgs);
21134358d963SJosef Bacik 	trans->delayed_ref_updates++;
21144358d963SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
21154358d963SJosef Bacik 
21164358d963SJosef Bacik 	set_avail_alloc_bits(fs_info, type);
21174358d963SJosef Bacik 	return 0;
21184358d963SJosef Bacik }
211926ce2095SJosef Bacik 
212026ce2095SJosef Bacik static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
212126ce2095SJosef Bacik {
212226ce2095SJosef Bacik 	u64 num_devices;
212326ce2095SJosef Bacik 	u64 stripped;
212426ce2095SJosef Bacik 
212526ce2095SJosef Bacik 	/*
212626ce2095SJosef Bacik 	 * if restripe for this chunk_type is on pick target profile and
212726ce2095SJosef Bacik 	 * return, otherwise do the usual balance
212826ce2095SJosef Bacik 	 */
2129e11c0406SJosef Bacik 	stripped = get_restripe_target(fs_info, flags);
213026ce2095SJosef Bacik 	if (stripped)
213126ce2095SJosef Bacik 		return extended_to_chunk(stripped);
213226ce2095SJosef Bacik 
213326ce2095SJosef Bacik 	num_devices = fs_info->fs_devices->rw_devices;
213426ce2095SJosef Bacik 
213526ce2095SJosef Bacik 	stripped = BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID56_MASK |
213626ce2095SJosef Bacik 		BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10;
213726ce2095SJosef Bacik 
213826ce2095SJosef Bacik 	if (num_devices == 1) {
213926ce2095SJosef Bacik 		stripped |= BTRFS_BLOCK_GROUP_DUP;
214026ce2095SJosef Bacik 		stripped = flags & ~stripped;
214126ce2095SJosef Bacik 
214226ce2095SJosef Bacik 		/* turn raid0 into single device chunks */
214326ce2095SJosef Bacik 		if (flags & BTRFS_BLOCK_GROUP_RAID0)
214426ce2095SJosef Bacik 			return stripped;
214526ce2095SJosef Bacik 
214626ce2095SJosef Bacik 		/* turn mirroring into duplication */
214726ce2095SJosef Bacik 		if (flags & (BTRFS_BLOCK_GROUP_RAID1_MASK |
214826ce2095SJosef Bacik 			     BTRFS_BLOCK_GROUP_RAID10))
214926ce2095SJosef Bacik 			return stripped | BTRFS_BLOCK_GROUP_DUP;
215026ce2095SJosef Bacik 	} else {
215126ce2095SJosef Bacik 		/* they already had raid on here, just return */
215226ce2095SJosef Bacik 		if (flags & stripped)
215326ce2095SJosef Bacik 			return flags;
215426ce2095SJosef Bacik 
215526ce2095SJosef Bacik 		stripped |= BTRFS_BLOCK_GROUP_DUP;
215626ce2095SJosef Bacik 		stripped = flags & ~stripped;
215726ce2095SJosef Bacik 
215826ce2095SJosef Bacik 		/* switch duplicated blocks with raid1 */
215926ce2095SJosef Bacik 		if (flags & BTRFS_BLOCK_GROUP_DUP)
216026ce2095SJosef Bacik 			return stripped | BTRFS_BLOCK_GROUP_RAID1;
216126ce2095SJosef Bacik 
216226ce2095SJosef Bacik 		/* this is drive concat, leave it alone */
216326ce2095SJosef Bacik 	}
216426ce2095SJosef Bacik 
216526ce2095SJosef Bacik 	return flags;
216626ce2095SJosef Bacik }
216726ce2095SJosef Bacik 
2168b12de528SQu Wenruo /*
2169b12de528SQu Wenruo  * Mark one block group RO, can be called several times for the same block
2170b12de528SQu Wenruo  * group.
2171b12de528SQu Wenruo  *
2172b12de528SQu Wenruo  * @cache:		the destination block group
2173b12de528SQu Wenruo  * @do_chunk_alloc:	whether need to do chunk pre-allocation, this is to
2174b12de528SQu Wenruo  * 			ensure we still have some free space after marking this
2175b12de528SQu Wenruo  * 			block group RO.
2176b12de528SQu Wenruo  */
2177b12de528SQu Wenruo int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2178b12de528SQu Wenruo 			     bool do_chunk_alloc)
217926ce2095SJosef Bacik {
218026ce2095SJosef Bacik 	struct btrfs_fs_info *fs_info = cache->fs_info;
218126ce2095SJosef Bacik 	struct btrfs_trans_handle *trans;
218226ce2095SJosef Bacik 	u64 alloc_flags;
218326ce2095SJosef Bacik 	int ret;
218426ce2095SJosef Bacik 
218526ce2095SJosef Bacik again:
218626ce2095SJosef Bacik 	trans = btrfs_join_transaction(fs_info->extent_root);
218726ce2095SJosef Bacik 	if (IS_ERR(trans))
218826ce2095SJosef Bacik 		return PTR_ERR(trans);
218926ce2095SJosef Bacik 
219026ce2095SJosef Bacik 	/*
219126ce2095SJosef Bacik 	 * we're not allowed to set block groups readonly after the dirty
219226ce2095SJosef Bacik 	 * block groups cache has started writing.  If it already started,
219326ce2095SJosef Bacik 	 * back off and let this transaction commit
219426ce2095SJosef Bacik 	 */
219526ce2095SJosef Bacik 	mutex_lock(&fs_info->ro_block_group_mutex);
219626ce2095SJosef Bacik 	if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
219726ce2095SJosef Bacik 		u64 transid = trans->transid;
219826ce2095SJosef Bacik 
219926ce2095SJosef Bacik 		mutex_unlock(&fs_info->ro_block_group_mutex);
220026ce2095SJosef Bacik 		btrfs_end_transaction(trans);
220126ce2095SJosef Bacik 
220226ce2095SJosef Bacik 		ret = btrfs_wait_for_commit(fs_info, transid);
220326ce2095SJosef Bacik 		if (ret)
220426ce2095SJosef Bacik 			return ret;
220526ce2095SJosef Bacik 		goto again;
220626ce2095SJosef Bacik 	}
220726ce2095SJosef Bacik 
2208b12de528SQu Wenruo 	if (do_chunk_alloc) {
220926ce2095SJosef Bacik 		/*
2210b12de528SQu Wenruo 		 * If we are changing raid levels, try to allocate a
2211b12de528SQu Wenruo 		 * corresponding block group with the new raid level.
221226ce2095SJosef Bacik 		 */
221326ce2095SJosef Bacik 		alloc_flags = update_block_group_flags(fs_info, cache->flags);
221426ce2095SJosef Bacik 		if (alloc_flags != cache->flags) {
2215b12de528SQu Wenruo 			ret = btrfs_chunk_alloc(trans, alloc_flags,
2216b12de528SQu Wenruo 						CHUNK_ALLOC_FORCE);
221726ce2095SJosef Bacik 			/*
221826ce2095SJosef Bacik 			 * ENOSPC is allowed here, we may have enough space
2219b12de528SQu Wenruo 			 * already allocated at the new raid level to carry on
222026ce2095SJosef Bacik 			 */
222126ce2095SJosef Bacik 			if (ret == -ENOSPC)
222226ce2095SJosef Bacik 				ret = 0;
222326ce2095SJosef Bacik 			if (ret < 0)
222426ce2095SJosef Bacik 				goto out;
222526ce2095SJosef Bacik 		}
2226b12de528SQu Wenruo 	}
222726ce2095SJosef Bacik 
2228*a7a63accSJosef Bacik 	ret = inc_block_group_ro(cache, 0);
2229b12de528SQu Wenruo 	if (!do_chunk_alloc)
2230b12de528SQu Wenruo 		goto unlock_out;
223126ce2095SJosef Bacik 	if (!ret)
223226ce2095SJosef Bacik 		goto out;
223326ce2095SJosef Bacik 	alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
223426ce2095SJosef Bacik 	ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
223526ce2095SJosef Bacik 	if (ret < 0)
223626ce2095SJosef Bacik 		goto out;
2237e11c0406SJosef Bacik 	ret = inc_block_group_ro(cache, 0);
223826ce2095SJosef Bacik out:
223926ce2095SJosef Bacik 	if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
224026ce2095SJosef Bacik 		alloc_flags = update_block_group_flags(fs_info, cache->flags);
224126ce2095SJosef Bacik 		mutex_lock(&fs_info->chunk_mutex);
224226ce2095SJosef Bacik 		check_system_chunk(trans, alloc_flags);
224326ce2095SJosef Bacik 		mutex_unlock(&fs_info->chunk_mutex);
224426ce2095SJosef Bacik 	}
2245b12de528SQu Wenruo unlock_out:
224626ce2095SJosef Bacik 	mutex_unlock(&fs_info->ro_block_group_mutex);
224726ce2095SJosef Bacik 
224826ce2095SJosef Bacik 	btrfs_end_transaction(trans);
224926ce2095SJosef Bacik 	return ret;
225026ce2095SJosef Bacik }
225126ce2095SJosef Bacik 
225232da5386SDavid Sterba void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
225326ce2095SJosef Bacik {
225426ce2095SJosef Bacik 	struct btrfs_space_info *sinfo = cache->space_info;
225526ce2095SJosef Bacik 	u64 num_bytes;
225626ce2095SJosef Bacik 
225726ce2095SJosef Bacik 	BUG_ON(!cache->ro);
225826ce2095SJosef Bacik 
225926ce2095SJosef Bacik 	spin_lock(&sinfo->lock);
226026ce2095SJosef Bacik 	spin_lock(&cache->lock);
226126ce2095SJosef Bacik 	if (!--cache->ro) {
2262b3470b5dSDavid Sterba 		num_bytes = cache->length - cache->reserved -
2263bf38be65SDavid Sterba 			    cache->pinned - cache->bytes_super - cache->used;
226426ce2095SJosef Bacik 		sinfo->bytes_readonly -= num_bytes;
226526ce2095SJosef Bacik 		list_del_init(&cache->ro_list);
226626ce2095SJosef Bacik 	}
226726ce2095SJosef Bacik 	spin_unlock(&cache->lock);
226826ce2095SJosef Bacik 	spin_unlock(&sinfo->lock);
226926ce2095SJosef Bacik }
227077745c05SJosef Bacik 
227177745c05SJosef Bacik static int write_one_cache_group(struct btrfs_trans_handle *trans,
227277745c05SJosef Bacik 				 struct btrfs_path *path,
227332da5386SDavid Sterba 				 struct btrfs_block_group *cache)
227477745c05SJosef Bacik {
227577745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
227677745c05SJosef Bacik 	int ret;
227777745c05SJosef Bacik 	struct btrfs_root *extent_root = fs_info->extent_root;
227877745c05SJosef Bacik 	unsigned long bi;
227977745c05SJosef Bacik 	struct extent_buffer *leaf;
2280bf38be65SDavid Sterba 	struct btrfs_block_group_item bgi;
2281b3470b5dSDavid Sterba 	struct btrfs_key key;
228277745c05SJosef Bacik 
2283b3470b5dSDavid Sterba 	key.objectid = cache->start;
2284b3470b5dSDavid Sterba 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2285b3470b5dSDavid Sterba 	key.offset = cache->length;
2286b3470b5dSDavid Sterba 
2287b3470b5dSDavid Sterba 	ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 1);
228877745c05SJosef Bacik 	if (ret) {
228977745c05SJosef Bacik 		if (ret > 0)
229077745c05SJosef Bacik 			ret = -ENOENT;
229177745c05SJosef Bacik 		goto fail;
229277745c05SJosef Bacik 	}
229377745c05SJosef Bacik 
229477745c05SJosef Bacik 	leaf = path->nodes[0];
229577745c05SJosef Bacik 	bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2296de0dc456SDavid Sterba 	btrfs_set_stack_block_group_used(&bgi, cache->used);
2297de0dc456SDavid Sterba 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
22983d976388SDavid Sterba 			BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2299de0dc456SDavid Sterba 	btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2300bf38be65SDavid Sterba 	write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
230177745c05SJosef Bacik 	btrfs_mark_buffer_dirty(leaf);
230277745c05SJosef Bacik fail:
230377745c05SJosef Bacik 	btrfs_release_path(path);
230477745c05SJosef Bacik 	return ret;
230577745c05SJosef Bacik 
230677745c05SJosef Bacik }
230777745c05SJosef Bacik 
230832da5386SDavid Sterba static int cache_save_setup(struct btrfs_block_group *block_group,
230977745c05SJosef Bacik 			    struct btrfs_trans_handle *trans,
231077745c05SJosef Bacik 			    struct btrfs_path *path)
231177745c05SJosef Bacik {
231277745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = block_group->fs_info;
231377745c05SJosef Bacik 	struct btrfs_root *root = fs_info->tree_root;
231477745c05SJosef Bacik 	struct inode *inode = NULL;
231577745c05SJosef Bacik 	struct extent_changeset *data_reserved = NULL;
231677745c05SJosef Bacik 	u64 alloc_hint = 0;
231777745c05SJosef Bacik 	int dcs = BTRFS_DC_ERROR;
231877745c05SJosef Bacik 	u64 num_pages = 0;
231977745c05SJosef Bacik 	int retries = 0;
232077745c05SJosef Bacik 	int ret = 0;
232177745c05SJosef Bacik 
232277745c05SJosef Bacik 	/*
232377745c05SJosef Bacik 	 * If this block group is smaller than 100 megs don't bother caching the
232477745c05SJosef Bacik 	 * block group.
232577745c05SJosef Bacik 	 */
2326b3470b5dSDavid Sterba 	if (block_group->length < (100 * SZ_1M)) {
232777745c05SJosef Bacik 		spin_lock(&block_group->lock);
232877745c05SJosef Bacik 		block_group->disk_cache_state = BTRFS_DC_WRITTEN;
232977745c05SJosef Bacik 		spin_unlock(&block_group->lock);
233077745c05SJosef Bacik 		return 0;
233177745c05SJosef Bacik 	}
233277745c05SJosef Bacik 
233377745c05SJosef Bacik 	if (trans->aborted)
233477745c05SJosef Bacik 		return 0;
233577745c05SJosef Bacik again:
233677745c05SJosef Bacik 	inode = lookup_free_space_inode(block_group, path);
233777745c05SJosef Bacik 	if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
233877745c05SJosef Bacik 		ret = PTR_ERR(inode);
233977745c05SJosef Bacik 		btrfs_release_path(path);
234077745c05SJosef Bacik 		goto out;
234177745c05SJosef Bacik 	}
234277745c05SJosef Bacik 
234377745c05SJosef Bacik 	if (IS_ERR(inode)) {
234477745c05SJosef Bacik 		BUG_ON(retries);
234577745c05SJosef Bacik 		retries++;
234677745c05SJosef Bacik 
234777745c05SJosef Bacik 		if (block_group->ro)
234877745c05SJosef Bacik 			goto out_free;
234977745c05SJosef Bacik 
235077745c05SJosef Bacik 		ret = create_free_space_inode(trans, block_group, path);
235177745c05SJosef Bacik 		if (ret)
235277745c05SJosef Bacik 			goto out_free;
235377745c05SJosef Bacik 		goto again;
235477745c05SJosef Bacik 	}
235577745c05SJosef Bacik 
235677745c05SJosef Bacik 	/*
235777745c05SJosef Bacik 	 * We want to set the generation to 0, that way if anything goes wrong
235877745c05SJosef Bacik 	 * from here on out we know not to trust this cache when we load up next
235977745c05SJosef Bacik 	 * time.
236077745c05SJosef Bacik 	 */
236177745c05SJosef Bacik 	BTRFS_I(inode)->generation = 0;
236277745c05SJosef Bacik 	ret = btrfs_update_inode(trans, root, inode);
236377745c05SJosef Bacik 	if (ret) {
236477745c05SJosef Bacik 		/*
236577745c05SJosef Bacik 		 * So theoretically we could recover from this, simply set the
236677745c05SJosef Bacik 		 * super cache generation to 0 so we know to invalidate the
236777745c05SJosef Bacik 		 * cache, but then we'd have to keep track of the block groups
236877745c05SJosef Bacik 		 * that fail this way so we know we _have_ to reset this cache
236977745c05SJosef Bacik 		 * before the next commit or risk reading stale cache.  So to
237077745c05SJosef Bacik 		 * limit our exposure to horrible edge cases lets just abort the
237177745c05SJosef Bacik 		 * transaction, this only happens in really bad situations
237277745c05SJosef Bacik 		 * anyway.
237377745c05SJosef Bacik 		 */
237477745c05SJosef Bacik 		btrfs_abort_transaction(trans, ret);
237577745c05SJosef Bacik 		goto out_put;
237677745c05SJosef Bacik 	}
237777745c05SJosef Bacik 	WARN_ON(ret);
237877745c05SJosef Bacik 
237977745c05SJosef Bacik 	/* We've already setup this transaction, go ahead and exit */
238077745c05SJosef Bacik 	if (block_group->cache_generation == trans->transid &&
238177745c05SJosef Bacik 	    i_size_read(inode)) {
238277745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
238377745c05SJosef Bacik 		goto out_put;
238477745c05SJosef Bacik 	}
238577745c05SJosef Bacik 
238677745c05SJosef Bacik 	if (i_size_read(inode) > 0) {
238777745c05SJosef Bacik 		ret = btrfs_check_trunc_cache_free_space(fs_info,
238877745c05SJosef Bacik 					&fs_info->global_block_rsv);
238977745c05SJosef Bacik 		if (ret)
239077745c05SJosef Bacik 			goto out_put;
239177745c05SJosef Bacik 
239277745c05SJosef Bacik 		ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
239377745c05SJosef Bacik 		if (ret)
239477745c05SJosef Bacik 			goto out_put;
239577745c05SJosef Bacik 	}
239677745c05SJosef Bacik 
239777745c05SJosef Bacik 	spin_lock(&block_group->lock);
239877745c05SJosef Bacik 	if (block_group->cached != BTRFS_CACHE_FINISHED ||
239977745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE)) {
240077745c05SJosef Bacik 		/*
240177745c05SJosef Bacik 		 * don't bother trying to write stuff out _if_
240277745c05SJosef Bacik 		 * a) we're not cached,
240377745c05SJosef Bacik 		 * b) we're with nospace_cache mount option,
240477745c05SJosef Bacik 		 * c) we're with v2 space_cache (FREE_SPACE_TREE).
240577745c05SJosef Bacik 		 */
240677745c05SJosef Bacik 		dcs = BTRFS_DC_WRITTEN;
240777745c05SJosef Bacik 		spin_unlock(&block_group->lock);
240877745c05SJosef Bacik 		goto out_put;
240977745c05SJosef Bacik 	}
241077745c05SJosef Bacik 	spin_unlock(&block_group->lock);
241177745c05SJosef Bacik 
241277745c05SJosef Bacik 	/*
241377745c05SJosef Bacik 	 * We hit an ENOSPC when setting up the cache in this transaction, just
241477745c05SJosef Bacik 	 * skip doing the setup, we've already cleared the cache so we're safe.
241577745c05SJosef Bacik 	 */
241677745c05SJosef Bacik 	if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
241777745c05SJosef Bacik 		ret = -ENOSPC;
241877745c05SJosef Bacik 		goto out_put;
241977745c05SJosef Bacik 	}
242077745c05SJosef Bacik 
242177745c05SJosef Bacik 	/*
242277745c05SJosef Bacik 	 * Try to preallocate enough space based on how big the block group is.
242377745c05SJosef Bacik 	 * Keep in mind this has to include any pinned space which could end up
242477745c05SJosef Bacik 	 * taking up quite a bit since it's not folded into the other space
242577745c05SJosef Bacik 	 * cache.
242677745c05SJosef Bacik 	 */
2427b3470b5dSDavid Sterba 	num_pages = div_u64(block_group->length, SZ_256M);
242877745c05SJosef Bacik 	if (!num_pages)
242977745c05SJosef Bacik 		num_pages = 1;
243077745c05SJosef Bacik 
243177745c05SJosef Bacik 	num_pages *= 16;
243277745c05SJosef Bacik 	num_pages *= PAGE_SIZE;
243377745c05SJosef Bacik 
243477745c05SJosef Bacik 	ret = btrfs_check_data_free_space(inode, &data_reserved, 0, num_pages);
243577745c05SJosef Bacik 	if (ret)
243677745c05SJosef Bacik 		goto out_put;
243777745c05SJosef Bacik 
243877745c05SJosef Bacik 	ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
243977745c05SJosef Bacik 					      num_pages, num_pages,
244077745c05SJosef Bacik 					      &alloc_hint);
244177745c05SJosef Bacik 	/*
244277745c05SJosef Bacik 	 * Our cache requires contiguous chunks so that we don't modify a bunch
244377745c05SJosef Bacik 	 * of metadata or split extents when writing the cache out, which means
244477745c05SJosef Bacik 	 * we can enospc if we are heavily fragmented in addition to just normal
244577745c05SJosef Bacik 	 * out of space conditions.  So if we hit this just skip setting up any
244677745c05SJosef Bacik 	 * other block groups for this transaction, maybe we'll unpin enough
244777745c05SJosef Bacik 	 * space the next time around.
244877745c05SJosef Bacik 	 */
244977745c05SJosef Bacik 	if (!ret)
245077745c05SJosef Bacik 		dcs = BTRFS_DC_SETUP;
245177745c05SJosef Bacik 	else if (ret == -ENOSPC)
245277745c05SJosef Bacik 		set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
245377745c05SJosef Bacik 
245477745c05SJosef Bacik out_put:
245577745c05SJosef Bacik 	iput(inode);
245677745c05SJosef Bacik out_free:
245777745c05SJosef Bacik 	btrfs_release_path(path);
245877745c05SJosef Bacik out:
245977745c05SJosef Bacik 	spin_lock(&block_group->lock);
246077745c05SJosef Bacik 	if (!ret && dcs == BTRFS_DC_SETUP)
246177745c05SJosef Bacik 		block_group->cache_generation = trans->transid;
246277745c05SJosef Bacik 	block_group->disk_cache_state = dcs;
246377745c05SJosef Bacik 	spin_unlock(&block_group->lock);
246477745c05SJosef Bacik 
246577745c05SJosef Bacik 	extent_changeset_free(data_reserved);
246677745c05SJosef Bacik 	return ret;
246777745c05SJosef Bacik }
246877745c05SJosef Bacik 
246977745c05SJosef Bacik int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
247077745c05SJosef Bacik {
247177745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
247232da5386SDavid Sterba 	struct btrfs_block_group *cache, *tmp;
247377745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
247477745c05SJosef Bacik 	struct btrfs_path *path;
247577745c05SJosef Bacik 
247677745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs) ||
247777745c05SJosef Bacik 	    !btrfs_test_opt(fs_info, SPACE_CACHE))
247877745c05SJosef Bacik 		return 0;
247977745c05SJosef Bacik 
248077745c05SJosef Bacik 	path = btrfs_alloc_path();
248177745c05SJosef Bacik 	if (!path)
248277745c05SJosef Bacik 		return -ENOMEM;
248377745c05SJosef Bacik 
248477745c05SJosef Bacik 	/* Could add new block groups, use _safe just in case */
248577745c05SJosef Bacik 	list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
248677745c05SJosef Bacik 				 dirty_list) {
248777745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_CLEAR)
248877745c05SJosef Bacik 			cache_save_setup(cache, trans, path);
248977745c05SJosef Bacik 	}
249077745c05SJosef Bacik 
249177745c05SJosef Bacik 	btrfs_free_path(path);
249277745c05SJosef Bacik 	return 0;
249377745c05SJosef Bacik }
249477745c05SJosef Bacik 
249577745c05SJosef Bacik /*
249677745c05SJosef Bacik  * Transaction commit does final block group cache writeback during a critical
249777745c05SJosef Bacik  * section where nothing is allowed to change the FS.  This is required in
249877745c05SJosef Bacik  * order for the cache to actually match the block group, but can introduce a
249977745c05SJosef Bacik  * lot of latency into the commit.
250077745c05SJosef Bacik  *
250177745c05SJosef Bacik  * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
250277745c05SJosef Bacik  * There's a chance we'll have to redo some of it if the block group changes
250377745c05SJosef Bacik  * again during the commit, but it greatly reduces the commit latency by
250477745c05SJosef Bacik  * getting rid of the easy block groups while we're still allowing others to
250577745c05SJosef Bacik  * join the commit.
250677745c05SJosef Bacik  */
250777745c05SJosef Bacik int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
250877745c05SJosef Bacik {
250977745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
251032da5386SDavid Sterba 	struct btrfs_block_group *cache;
251177745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
251277745c05SJosef Bacik 	int ret = 0;
251377745c05SJosef Bacik 	int should_put;
251477745c05SJosef Bacik 	struct btrfs_path *path = NULL;
251577745c05SJosef Bacik 	LIST_HEAD(dirty);
251677745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
251777745c05SJosef Bacik 	int num_started = 0;
251877745c05SJosef Bacik 	int loops = 0;
251977745c05SJosef Bacik 
252077745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
252177745c05SJosef Bacik 	if (list_empty(&cur_trans->dirty_bgs)) {
252277745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
252377745c05SJosef Bacik 		return 0;
252477745c05SJosef Bacik 	}
252577745c05SJosef Bacik 	list_splice_init(&cur_trans->dirty_bgs, &dirty);
252677745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
252777745c05SJosef Bacik 
252877745c05SJosef Bacik again:
252977745c05SJosef Bacik 	/* Make sure all the block groups on our dirty list actually exist */
253077745c05SJosef Bacik 	btrfs_create_pending_block_groups(trans);
253177745c05SJosef Bacik 
253277745c05SJosef Bacik 	if (!path) {
253377745c05SJosef Bacik 		path = btrfs_alloc_path();
253477745c05SJosef Bacik 		if (!path)
253577745c05SJosef Bacik 			return -ENOMEM;
253677745c05SJosef Bacik 	}
253777745c05SJosef Bacik 
253877745c05SJosef Bacik 	/*
253977745c05SJosef Bacik 	 * cache_write_mutex is here only to save us from balance or automatic
254077745c05SJosef Bacik 	 * removal of empty block groups deleting this block group while we are
254177745c05SJosef Bacik 	 * writing out the cache
254277745c05SJosef Bacik 	 */
254377745c05SJosef Bacik 	mutex_lock(&trans->transaction->cache_write_mutex);
254477745c05SJosef Bacik 	while (!list_empty(&dirty)) {
254577745c05SJosef Bacik 		bool drop_reserve = true;
254677745c05SJosef Bacik 
254732da5386SDavid Sterba 		cache = list_first_entry(&dirty, struct btrfs_block_group,
254877745c05SJosef Bacik 					 dirty_list);
254977745c05SJosef Bacik 		/*
255077745c05SJosef Bacik 		 * This can happen if something re-dirties a block group that
255177745c05SJosef Bacik 		 * is already under IO.  Just wait for it to finish and then do
255277745c05SJosef Bacik 		 * it all again
255377745c05SJosef Bacik 		 */
255477745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
255577745c05SJosef Bacik 			list_del_init(&cache->io_list);
255677745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
255777745c05SJosef Bacik 			btrfs_put_block_group(cache);
255877745c05SJosef Bacik 		}
255977745c05SJosef Bacik 
256077745c05SJosef Bacik 
256177745c05SJosef Bacik 		/*
256277745c05SJosef Bacik 		 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
256377745c05SJosef Bacik 		 * it should update the cache_state.  Don't delete until after
256477745c05SJosef Bacik 		 * we wait.
256577745c05SJosef Bacik 		 *
256677745c05SJosef Bacik 		 * Since we're not running in the commit critical section
256777745c05SJosef Bacik 		 * we need the dirty_bgs_lock to protect from update_block_group
256877745c05SJosef Bacik 		 */
256977745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
257077745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
257177745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
257277745c05SJosef Bacik 
257377745c05SJosef Bacik 		should_put = 1;
257477745c05SJosef Bacik 
257577745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
257677745c05SJosef Bacik 
257777745c05SJosef Bacik 		if (cache->disk_cache_state == BTRFS_DC_SETUP) {
257877745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
257977745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
258077745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
258177745c05SJosef Bacik 				num_started++;
258277745c05SJosef Bacik 				should_put = 0;
258377745c05SJosef Bacik 
258477745c05SJosef Bacik 				/*
258577745c05SJosef Bacik 				 * The cache_write_mutex is protecting the
258677745c05SJosef Bacik 				 * io_list, also refer to the definition of
258777745c05SJosef Bacik 				 * btrfs_transaction::io_bgs for more details
258877745c05SJosef Bacik 				 */
258977745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
259077745c05SJosef Bacik 			} else {
259177745c05SJosef Bacik 				/*
259277745c05SJosef Bacik 				 * If we failed to write the cache, the
259377745c05SJosef Bacik 				 * generation will be bad and life goes on
259477745c05SJosef Bacik 				 */
259577745c05SJosef Bacik 				ret = 0;
259677745c05SJosef Bacik 			}
259777745c05SJosef Bacik 		}
259877745c05SJosef Bacik 		if (!ret) {
259977745c05SJosef Bacik 			ret = write_one_cache_group(trans, path, cache);
260077745c05SJosef Bacik 			/*
260177745c05SJosef Bacik 			 * Our block group might still be attached to the list
260277745c05SJosef Bacik 			 * of new block groups in the transaction handle of some
260377745c05SJosef Bacik 			 * other task (struct btrfs_trans_handle->new_bgs). This
260477745c05SJosef Bacik 			 * means its block group item isn't yet in the extent
260577745c05SJosef Bacik 			 * tree. If this happens ignore the error, as we will
260677745c05SJosef Bacik 			 * try again later in the critical section of the
260777745c05SJosef Bacik 			 * transaction commit.
260877745c05SJosef Bacik 			 */
260977745c05SJosef Bacik 			if (ret == -ENOENT) {
261077745c05SJosef Bacik 				ret = 0;
261177745c05SJosef Bacik 				spin_lock(&cur_trans->dirty_bgs_lock);
261277745c05SJosef Bacik 				if (list_empty(&cache->dirty_list)) {
261377745c05SJosef Bacik 					list_add_tail(&cache->dirty_list,
261477745c05SJosef Bacik 						      &cur_trans->dirty_bgs);
261577745c05SJosef Bacik 					btrfs_get_block_group(cache);
261677745c05SJosef Bacik 					drop_reserve = false;
261777745c05SJosef Bacik 				}
261877745c05SJosef Bacik 				spin_unlock(&cur_trans->dirty_bgs_lock);
261977745c05SJosef Bacik 			} else if (ret) {
262077745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
262177745c05SJosef Bacik 			}
262277745c05SJosef Bacik 		}
262377745c05SJosef Bacik 
262477745c05SJosef Bacik 		/* If it's not on the io list, we need to put the block group */
262577745c05SJosef Bacik 		if (should_put)
262677745c05SJosef Bacik 			btrfs_put_block_group(cache);
262777745c05SJosef Bacik 		if (drop_reserve)
262877745c05SJosef Bacik 			btrfs_delayed_refs_rsv_release(fs_info, 1);
262977745c05SJosef Bacik 
263077745c05SJosef Bacik 		if (ret)
263177745c05SJosef Bacik 			break;
263277745c05SJosef Bacik 
263377745c05SJosef Bacik 		/*
263477745c05SJosef Bacik 		 * Avoid blocking other tasks for too long. It might even save
263577745c05SJosef Bacik 		 * us from writing caches for block groups that are going to be
263677745c05SJosef Bacik 		 * removed.
263777745c05SJosef Bacik 		 */
263877745c05SJosef Bacik 		mutex_unlock(&trans->transaction->cache_write_mutex);
263977745c05SJosef Bacik 		mutex_lock(&trans->transaction->cache_write_mutex);
264077745c05SJosef Bacik 	}
264177745c05SJosef Bacik 	mutex_unlock(&trans->transaction->cache_write_mutex);
264277745c05SJosef Bacik 
264377745c05SJosef Bacik 	/*
264477745c05SJosef Bacik 	 * Go through delayed refs for all the stuff we've just kicked off
264577745c05SJosef Bacik 	 * and then loop back (just once)
264677745c05SJosef Bacik 	 */
264777745c05SJosef Bacik 	ret = btrfs_run_delayed_refs(trans, 0);
264877745c05SJosef Bacik 	if (!ret && loops == 0) {
264977745c05SJosef Bacik 		loops++;
265077745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
265177745c05SJosef Bacik 		list_splice_init(&cur_trans->dirty_bgs, &dirty);
265277745c05SJosef Bacik 		/*
265377745c05SJosef Bacik 		 * dirty_bgs_lock protects us from concurrent block group
265477745c05SJosef Bacik 		 * deletes too (not just cache_write_mutex).
265577745c05SJosef Bacik 		 */
265677745c05SJosef Bacik 		if (!list_empty(&dirty)) {
265777745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
265877745c05SJosef Bacik 			goto again;
265977745c05SJosef Bacik 		}
266077745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
266177745c05SJosef Bacik 	} else if (ret < 0) {
266277745c05SJosef Bacik 		btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
266377745c05SJosef Bacik 	}
266477745c05SJosef Bacik 
266577745c05SJosef Bacik 	btrfs_free_path(path);
266677745c05SJosef Bacik 	return ret;
266777745c05SJosef Bacik }
266877745c05SJosef Bacik 
266977745c05SJosef Bacik int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
267077745c05SJosef Bacik {
267177745c05SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
267232da5386SDavid Sterba 	struct btrfs_block_group *cache;
267377745c05SJosef Bacik 	struct btrfs_transaction *cur_trans = trans->transaction;
267477745c05SJosef Bacik 	int ret = 0;
267577745c05SJosef Bacik 	int should_put;
267677745c05SJosef Bacik 	struct btrfs_path *path;
267777745c05SJosef Bacik 	struct list_head *io = &cur_trans->io_bgs;
267877745c05SJosef Bacik 	int num_started = 0;
267977745c05SJosef Bacik 
268077745c05SJosef Bacik 	path = btrfs_alloc_path();
268177745c05SJosef Bacik 	if (!path)
268277745c05SJosef Bacik 		return -ENOMEM;
268377745c05SJosef Bacik 
268477745c05SJosef Bacik 	/*
268577745c05SJosef Bacik 	 * Even though we are in the critical section of the transaction commit,
268677745c05SJosef Bacik 	 * we can still have concurrent tasks adding elements to this
268777745c05SJosef Bacik 	 * transaction's list of dirty block groups. These tasks correspond to
268877745c05SJosef Bacik 	 * endio free space workers started when writeback finishes for a
268977745c05SJosef Bacik 	 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
269077745c05SJosef Bacik 	 * allocate new block groups as a result of COWing nodes of the root
269177745c05SJosef Bacik 	 * tree when updating the free space inode. The writeback for the space
269277745c05SJosef Bacik 	 * caches is triggered by an earlier call to
269377745c05SJosef Bacik 	 * btrfs_start_dirty_block_groups() and iterations of the following
269477745c05SJosef Bacik 	 * loop.
269577745c05SJosef Bacik 	 * Also we want to do the cache_save_setup first and then run the
269677745c05SJosef Bacik 	 * delayed refs to make sure we have the best chance at doing this all
269777745c05SJosef Bacik 	 * in one shot.
269877745c05SJosef Bacik 	 */
269977745c05SJosef Bacik 	spin_lock(&cur_trans->dirty_bgs_lock);
270077745c05SJosef Bacik 	while (!list_empty(&cur_trans->dirty_bgs)) {
270177745c05SJosef Bacik 		cache = list_first_entry(&cur_trans->dirty_bgs,
270232da5386SDavid Sterba 					 struct btrfs_block_group,
270377745c05SJosef Bacik 					 dirty_list);
270477745c05SJosef Bacik 
270577745c05SJosef Bacik 		/*
270677745c05SJosef Bacik 		 * This can happen if cache_save_setup re-dirties a block group
270777745c05SJosef Bacik 		 * that is already under IO.  Just wait for it to finish and
270877745c05SJosef Bacik 		 * then do it all again
270977745c05SJosef Bacik 		 */
271077745c05SJosef Bacik 		if (!list_empty(&cache->io_list)) {
271177745c05SJosef Bacik 			spin_unlock(&cur_trans->dirty_bgs_lock);
271277745c05SJosef Bacik 			list_del_init(&cache->io_list);
271377745c05SJosef Bacik 			btrfs_wait_cache_io(trans, cache, path);
271477745c05SJosef Bacik 			btrfs_put_block_group(cache);
271577745c05SJosef Bacik 			spin_lock(&cur_trans->dirty_bgs_lock);
271677745c05SJosef Bacik 		}
271777745c05SJosef Bacik 
271877745c05SJosef Bacik 		/*
271977745c05SJosef Bacik 		 * Don't remove from the dirty list until after we've waited on
272077745c05SJosef Bacik 		 * any pending IO
272177745c05SJosef Bacik 		 */
272277745c05SJosef Bacik 		list_del_init(&cache->dirty_list);
272377745c05SJosef Bacik 		spin_unlock(&cur_trans->dirty_bgs_lock);
272477745c05SJosef Bacik 		should_put = 1;
272577745c05SJosef Bacik 
272677745c05SJosef Bacik 		cache_save_setup(cache, trans, path);
272777745c05SJosef Bacik 
272877745c05SJosef Bacik 		if (!ret)
272977745c05SJosef Bacik 			ret = btrfs_run_delayed_refs(trans,
273077745c05SJosef Bacik 						     (unsigned long) -1);
273177745c05SJosef Bacik 
273277745c05SJosef Bacik 		if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
273377745c05SJosef Bacik 			cache->io_ctl.inode = NULL;
273477745c05SJosef Bacik 			ret = btrfs_write_out_cache(trans, cache, path);
273577745c05SJosef Bacik 			if (ret == 0 && cache->io_ctl.inode) {
273677745c05SJosef Bacik 				num_started++;
273777745c05SJosef Bacik 				should_put = 0;
273877745c05SJosef Bacik 				list_add_tail(&cache->io_list, io);
273977745c05SJosef Bacik 			} else {
274077745c05SJosef Bacik 				/*
274177745c05SJosef Bacik 				 * If we failed to write the cache, the
274277745c05SJosef Bacik 				 * generation will be bad and life goes on
274377745c05SJosef Bacik 				 */
274477745c05SJosef Bacik 				ret = 0;
274577745c05SJosef Bacik 			}
274677745c05SJosef Bacik 		}
274777745c05SJosef Bacik 		if (!ret) {
274877745c05SJosef Bacik 			ret = write_one_cache_group(trans, path, cache);
274977745c05SJosef Bacik 			/*
275077745c05SJosef Bacik 			 * One of the free space endio workers might have
275177745c05SJosef Bacik 			 * created a new block group while updating a free space
275277745c05SJosef Bacik 			 * cache's inode (at inode.c:btrfs_finish_ordered_io())
275377745c05SJosef Bacik 			 * and hasn't released its transaction handle yet, in
275477745c05SJosef Bacik 			 * which case the new block group is still attached to
275577745c05SJosef Bacik 			 * its transaction handle and its creation has not
275677745c05SJosef Bacik 			 * finished yet (no block group item in the extent tree
275777745c05SJosef Bacik 			 * yet, etc). If this is the case, wait for all free
275877745c05SJosef Bacik 			 * space endio workers to finish and retry. This is a
275977745c05SJosef Bacik 			 * a very rare case so no need for a more efficient and
276077745c05SJosef Bacik 			 * complex approach.
276177745c05SJosef Bacik 			 */
276277745c05SJosef Bacik 			if (ret == -ENOENT) {
276377745c05SJosef Bacik 				wait_event(cur_trans->writer_wait,
276477745c05SJosef Bacik 				   atomic_read(&cur_trans->num_writers) == 1);
276577745c05SJosef Bacik 				ret = write_one_cache_group(trans, path, cache);
276677745c05SJosef Bacik 			}
276777745c05SJosef Bacik 			if (ret)
276877745c05SJosef Bacik 				btrfs_abort_transaction(trans, ret);
276977745c05SJosef Bacik 		}
277077745c05SJosef Bacik 
277177745c05SJosef Bacik 		/* If its not on the io list, we need to put the block group */
277277745c05SJosef Bacik 		if (should_put)
277377745c05SJosef Bacik 			btrfs_put_block_group(cache);
277477745c05SJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
277577745c05SJosef Bacik 		spin_lock(&cur_trans->dirty_bgs_lock);
277677745c05SJosef Bacik 	}
277777745c05SJosef Bacik 	spin_unlock(&cur_trans->dirty_bgs_lock);
277877745c05SJosef Bacik 
277977745c05SJosef Bacik 	/*
278077745c05SJosef Bacik 	 * Refer to the definition of io_bgs member for details why it's safe
278177745c05SJosef Bacik 	 * to use it without any locking
278277745c05SJosef Bacik 	 */
278377745c05SJosef Bacik 	while (!list_empty(io)) {
278432da5386SDavid Sterba 		cache = list_first_entry(io, struct btrfs_block_group,
278577745c05SJosef Bacik 					 io_list);
278677745c05SJosef Bacik 		list_del_init(&cache->io_list);
278777745c05SJosef Bacik 		btrfs_wait_cache_io(trans, cache, path);
278877745c05SJosef Bacik 		btrfs_put_block_group(cache);
278977745c05SJosef Bacik 	}
279077745c05SJosef Bacik 
279177745c05SJosef Bacik 	btrfs_free_path(path);
279277745c05SJosef Bacik 	return ret;
279377745c05SJosef Bacik }
2794606d1bf1SJosef Bacik 
2795606d1bf1SJosef Bacik int btrfs_update_block_group(struct btrfs_trans_handle *trans,
2796606d1bf1SJosef Bacik 			     u64 bytenr, u64 num_bytes, int alloc)
2797606d1bf1SJosef Bacik {
2798606d1bf1SJosef Bacik 	struct btrfs_fs_info *info = trans->fs_info;
279932da5386SDavid Sterba 	struct btrfs_block_group *cache = NULL;
2800606d1bf1SJosef Bacik 	u64 total = num_bytes;
2801606d1bf1SJosef Bacik 	u64 old_val;
2802606d1bf1SJosef Bacik 	u64 byte_in_group;
2803606d1bf1SJosef Bacik 	int factor;
2804606d1bf1SJosef Bacik 	int ret = 0;
2805606d1bf1SJosef Bacik 
2806606d1bf1SJosef Bacik 	/* Block accounting for super block */
2807606d1bf1SJosef Bacik 	spin_lock(&info->delalloc_root_lock);
2808606d1bf1SJosef Bacik 	old_val = btrfs_super_bytes_used(info->super_copy);
2809606d1bf1SJosef Bacik 	if (alloc)
2810606d1bf1SJosef Bacik 		old_val += num_bytes;
2811606d1bf1SJosef Bacik 	else
2812606d1bf1SJosef Bacik 		old_val -= num_bytes;
2813606d1bf1SJosef Bacik 	btrfs_set_super_bytes_used(info->super_copy, old_val);
2814606d1bf1SJosef Bacik 	spin_unlock(&info->delalloc_root_lock);
2815606d1bf1SJosef Bacik 
2816606d1bf1SJosef Bacik 	while (total) {
2817606d1bf1SJosef Bacik 		cache = btrfs_lookup_block_group(info, bytenr);
2818606d1bf1SJosef Bacik 		if (!cache) {
2819606d1bf1SJosef Bacik 			ret = -ENOENT;
2820606d1bf1SJosef Bacik 			break;
2821606d1bf1SJosef Bacik 		}
2822606d1bf1SJosef Bacik 		factor = btrfs_bg_type_to_factor(cache->flags);
2823606d1bf1SJosef Bacik 
2824606d1bf1SJosef Bacik 		/*
2825606d1bf1SJosef Bacik 		 * If this block group has free space cache written out, we
2826606d1bf1SJosef Bacik 		 * need to make sure to load it if we are removing space.  This
2827606d1bf1SJosef Bacik 		 * is because we need the unpinning stage to actually add the
2828606d1bf1SJosef Bacik 		 * space back to the block group, otherwise we will leak space.
2829606d1bf1SJosef Bacik 		 */
283032da5386SDavid Sterba 		if (!alloc && !btrfs_block_group_done(cache))
2831606d1bf1SJosef Bacik 			btrfs_cache_block_group(cache, 1);
2832606d1bf1SJosef Bacik 
2833b3470b5dSDavid Sterba 		byte_in_group = bytenr - cache->start;
2834b3470b5dSDavid Sterba 		WARN_ON(byte_in_group > cache->length);
2835606d1bf1SJosef Bacik 
2836606d1bf1SJosef Bacik 		spin_lock(&cache->space_info->lock);
2837606d1bf1SJosef Bacik 		spin_lock(&cache->lock);
2838606d1bf1SJosef Bacik 
2839606d1bf1SJosef Bacik 		if (btrfs_test_opt(info, SPACE_CACHE) &&
2840606d1bf1SJosef Bacik 		    cache->disk_cache_state < BTRFS_DC_CLEAR)
2841606d1bf1SJosef Bacik 			cache->disk_cache_state = BTRFS_DC_CLEAR;
2842606d1bf1SJosef Bacik 
2843bf38be65SDavid Sterba 		old_val = cache->used;
2844b3470b5dSDavid Sterba 		num_bytes = min(total, cache->length - byte_in_group);
2845606d1bf1SJosef Bacik 		if (alloc) {
2846606d1bf1SJosef Bacik 			old_val += num_bytes;
2847bf38be65SDavid Sterba 			cache->used = old_val;
2848606d1bf1SJosef Bacik 			cache->reserved -= num_bytes;
2849606d1bf1SJosef Bacik 			cache->space_info->bytes_reserved -= num_bytes;
2850606d1bf1SJosef Bacik 			cache->space_info->bytes_used += num_bytes;
2851606d1bf1SJosef Bacik 			cache->space_info->disk_used += num_bytes * factor;
2852606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
2853606d1bf1SJosef Bacik 			spin_unlock(&cache->space_info->lock);
2854606d1bf1SJosef Bacik 		} else {
2855606d1bf1SJosef Bacik 			old_val -= num_bytes;
2856bf38be65SDavid Sterba 			cache->used = old_val;
2857606d1bf1SJosef Bacik 			cache->pinned += num_bytes;
2858606d1bf1SJosef Bacik 			btrfs_space_info_update_bytes_pinned(info,
2859606d1bf1SJosef Bacik 					cache->space_info, num_bytes);
2860606d1bf1SJosef Bacik 			cache->space_info->bytes_used -= num_bytes;
2861606d1bf1SJosef Bacik 			cache->space_info->disk_used -= num_bytes * factor;
2862606d1bf1SJosef Bacik 			spin_unlock(&cache->lock);
2863606d1bf1SJosef Bacik 			spin_unlock(&cache->space_info->lock);
2864606d1bf1SJosef Bacik 
2865606d1bf1SJosef Bacik 			percpu_counter_add_batch(
2866606d1bf1SJosef Bacik 					&cache->space_info->total_bytes_pinned,
2867606d1bf1SJosef Bacik 					num_bytes,
2868606d1bf1SJosef Bacik 					BTRFS_TOTAL_BYTES_PINNED_BATCH);
2869606d1bf1SJosef Bacik 			set_extent_dirty(info->pinned_extents,
2870606d1bf1SJosef Bacik 					 bytenr, bytenr + num_bytes - 1,
2871606d1bf1SJosef Bacik 					 GFP_NOFS | __GFP_NOFAIL);
2872606d1bf1SJosef Bacik 		}
2873606d1bf1SJosef Bacik 
2874606d1bf1SJosef Bacik 		spin_lock(&trans->transaction->dirty_bgs_lock);
2875606d1bf1SJosef Bacik 		if (list_empty(&cache->dirty_list)) {
2876606d1bf1SJosef Bacik 			list_add_tail(&cache->dirty_list,
2877606d1bf1SJosef Bacik 				      &trans->transaction->dirty_bgs);
2878606d1bf1SJosef Bacik 			trans->delayed_ref_updates++;
2879606d1bf1SJosef Bacik 			btrfs_get_block_group(cache);
2880606d1bf1SJosef Bacik 		}
2881606d1bf1SJosef Bacik 		spin_unlock(&trans->transaction->dirty_bgs_lock);
2882606d1bf1SJosef Bacik 
2883606d1bf1SJosef Bacik 		/*
2884606d1bf1SJosef Bacik 		 * No longer have used bytes in this block group, queue it for
2885606d1bf1SJosef Bacik 		 * deletion. We do this after adding the block group to the
2886606d1bf1SJosef Bacik 		 * dirty list to avoid races between cleaner kthread and space
2887606d1bf1SJosef Bacik 		 * cache writeout.
2888606d1bf1SJosef Bacik 		 */
28896e80d4f8SDennis Zhou 		if (!alloc && old_val == 0) {
28906e80d4f8SDennis Zhou 			if (!btrfs_test_opt(info, DISCARD_ASYNC))
2891606d1bf1SJosef Bacik 				btrfs_mark_bg_unused(cache);
28926e80d4f8SDennis Zhou 		}
2893606d1bf1SJosef Bacik 
2894606d1bf1SJosef Bacik 		btrfs_put_block_group(cache);
2895606d1bf1SJosef Bacik 		total -= num_bytes;
2896606d1bf1SJosef Bacik 		bytenr += num_bytes;
2897606d1bf1SJosef Bacik 	}
2898606d1bf1SJosef Bacik 
2899606d1bf1SJosef Bacik 	/* Modified block groups are accounted for in the delayed_refs_rsv. */
2900606d1bf1SJosef Bacik 	btrfs_update_delayed_refs_rsv(trans);
2901606d1bf1SJosef Bacik 	return ret;
2902606d1bf1SJosef Bacik }
2903606d1bf1SJosef Bacik 
2904606d1bf1SJosef Bacik /**
2905606d1bf1SJosef Bacik  * btrfs_add_reserved_bytes - update the block_group and space info counters
2906606d1bf1SJosef Bacik  * @cache:	The cache we are manipulating
2907606d1bf1SJosef Bacik  * @ram_bytes:  The number of bytes of file content, and will be same to
2908606d1bf1SJosef Bacik  *              @num_bytes except for the compress path.
2909606d1bf1SJosef Bacik  * @num_bytes:	The number of bytes in question
2910606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
2911606d1bf1SJosef Bacik  *
2912606d1bf1SJosef Bacik  * This is called by the allocator when it reserves space. If this is a
2913606d1bf1SJosef Bacik  * reservation and the block group has become read only we cannot make the
2914606d1bf1SJosef Bacik  * reservation and return -EAGAIN, otherwise this function always succeeds.
2915606d1bf1SJosef Bacik  */
291632da5386SDavid Sterba int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
2917606d1bf1SJosef Bacik 			     u64 ram_bytes, u64 num_bytes, int delalloc)
2918606d1bf1SJosef Bacik {
2919606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
2920606d1bf1SJosef Bacik 	int ret = 0;
2921606d1bf1SJosef Bacik 
2922606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
2923606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
2924606d1bf1SJosef Bacik 	if (cache->ro) {
2925606d1bf1SJosef Bacik 		ret = -EAGAIN;
2926606d1bf1SJosef Bacik 	} else {
2927606d1bf1SJosef Bacik 		cache->reserved += num_bytes;
2928606d1bf1SJosef Bacik 		space_info->bytes_reserved += num_bytes;
2929a43c3835SJosef Bacik 		trace_btrfs_space_reservation(cache->fs_info, "space_info",
2930a43c3835SJosef Bacik 					      space_info->flags, num_bytes, 1);
2931606d1bf1SJosef Bacik 		btrfs_space_info_update_bytes_may_use(cache->fs_info,
2932606d1bf1SJosef Bacik 						      space_info, -ram_bytes);
2933606d1bf1SJosef Bacik 		if (delalloc)
2934606d1bf1SJosef Bacik 			cache->delalloc_bytes += num_bytes;
2935606d1bf1SJosef Bacik 	}
2936606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
2937606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
2938606d1bf1SJosef Bacik 	return ret;
2939606d1bf1SJosef Bacik }
2940606d1bf1SJosef Bacik 
2941606d1bf1SJosef Bacik /**
2942606d1bf1SJosef Bacik  * btrfs_free_reserved_bytes - update the block_group and space info counters
2943606d1bf1SJosef Bacik  * @cache:      The cache we are manipulating
2944606d1bf1SJosef Bacik  * @num_bytes:  The number of bytes in question
2945606d1bf1SJosef Bacik  * @delalloc:   The blocks are allocated for the delalloc write
2946606d1bf1SJosef Bacik  *
2947606d1bf1SJosef Bacik  * This is called by somebody who is freeing space that was never actually used
2948606d1bf1SJosef Bacik  * on disk.  For example if you reserve some space for a new leaf in transaction
2949606d1bf1SJosef Bacik  * A and before transaction A commits you free that leaf, you call this with
2950606d1bf1SJosef Bacik  * reserve set to 0 in order to clear the reservation.
2951606d1bf1SJosef Bacik  */
295232da5386SDavid Sterba void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
2953606d1bf1SJosef Bacik 			       u64 num_bytes, int delalloc)
2954606d1bf1SJosef Bacik {
2955606d1bf1SJosef Bacik 	struct btrfs_space_info *space_info = cache->space_info;
2956606d1bf1SJosef Bacik 
2957606d1bf1SJosef Bacik 	spin_lock(&space_info->lock);
2958606d1bf1SJosef Bacik 	spin_lock(&cache->lock);
2959606d1bf1SJosef Bacik 	if (cache->ro)
2960606d1bf1SJosef Bacik 		space_info->bytes_readonly += num_bytes;
2961606d1bf1SJosef Bacik 	cache->reserved -= num_bytes;
2962606d1bf1SJosef Bacik 	space_info->bytes_reserved -= num_bytes;
2963606d1bf1SJosef Bacik 	space_info->max_extent_size = 0;
2964606d1bf1SJosef Bacik 
2965606d1bf1SJosef Bacik 	if (delalloc)
2966606d1bf1SJosef Bacik 		cache->delalloc_bytes -= num_bytes;
2967606d1bf1SJosef Bacik 	spin_unlock(&cache->lock);
2968606d1bf1SJosef Bacik 	spin_unlock(&space_info->lock);
2969606d1bf1SJosef Bacik }
297007730d87SJosef Bacik 
297107730d87SJosef Bacik static void force_metadata_allocation(struct btrfs_fs_info *info)
297207730d87SJosef Bacik {
297307730d87SJosef Bacik 	struct list_head *head = &info->space_info;
297407730d87SJosef Bacik 	struct btrfs_space_info *found;
297507730d87SJosef Bacik 
297607730d87SJosef Bacik 	rcu_read_lock();
297707730d87SJosef Bacik 	list_for_each_entry_rcu(found, head, list) {
297807730d87SJosef Bacik 		if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
297907730d87SJosef Bacik 			found->force_alloc = CHUNK_ALLOC_FORCE;
298007730d87SJosef Bacik 	}
298107730d87SJosef Bacik 	rcu_read_unlock();
298207730d87SJosef Bacik }
298307730d87SJosef Bacik 
298407730d87SJosef Bacik static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
298507730d87SJosef Bacik 			      struct btrfs_space_info *sinfo, int force)
298607730d87SJosef Bacik {
298707730d87SJosef Bacik 	u64 bytes_used = btrfs_space_info_used(sinfo, false);
298807730d87SJosef Bacik 	u64 thresh;
298907730d87SJosef Bacik 
299007730d87SJosef Bacik 	if (force == CHUNK_ALLOC_FORCE)
299107730d87SJosef Bacik 		return 1;
299207730d87SJosef Bacik 
299307730d87SJosef Bacik 	/*
299407730d87SJosef Bacik 	 * in limited mode, we want to have some free space up to
299507730d87SJosef Bacik 	 * about 1% of the FS size.
299607730d87SJosef Bacik 	 */
299707730d87SJosef Bacik 	if (force == CHUNK_ALLOC_LIMITED) {
299807730d87SJosef Bacik 		thresh = btrfs_super_total_bytes(fs_info->super_copy);
299907730d87SJosef Bacik 		thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
300007730d87SJosef Bacik 
300107730d87SJosef Bacik 		if (sinfo->total_bytes - bytes_used < thresh)
300207730d87SJosef Bacik 			return 1;
300307730d87SJosef Bacik 	}
300407730d87SJosef Bacik 
300507730d87SJosef Bacik 	if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
300607730d87SJosef Bacik 		return 0;
300707730d87SJosef Bacik 	return 1;
300807730d87SJosef Bacik }
300907730d87SJosef Bacik 
301007730d87SJosef Bacik int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
301107730d87SJosef Bacik {
301207730d87SJosef Bacik 	u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
301307730d87SJosef Bacik 
301407730d87SJosef Bacik 	return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
301507730d87SJosef Bacik }
301607730d87SJosef Bacik 
301707730d87SJosef Bacik /*
301807730d87SJosef Bacik  * If force is CHUNK_ALLOC_FORCE:
301907730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
302007730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
302107730d87SJosef Bacik  * If force is NOT CHUNK_ALLOC_FORCE:
302207730d87SJosef Bacik  *    - return 0 if it doesn't need to allocate a new chunk,
302307730d87SJosef Bacik  *    - return 1 if it successfully allocates a chunk,
302407730d87SJosef Bacik  *    - return errors including -ENOSPC otherwise.
302507730d87SJosef Bacik  */
302607730d87SJosef Bacik int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
302707730d87SJosef Bacik 		      enum btrfs_chunk_alloc_enum force)
302807730d87SJosef Bacik {
302907730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
303007730d87SJosef Bacik 	struct btrfs_space_info *space_info;
303107730d87SJosef Bacik 	bool wait_for_alloc = false;
303207730d87SJosef Bacik 	bool should_alloc = false;
303307730d87SJosef Bacik 	int ret = 0;
303407730d87SJosef Bacik 
303507730d87SJosef Bacik 	/* Don't re-enter if we're already allocating a chunk */
303607730d87SJosef Bacik 	if (trans->allocating_chunk)
303707730d87SJosef Bacik 		return -ENOSPC;
303807730d87SJosef Bacik 
303907730d87SJosef Bacik 	space_info = btrfs_find_space_info(fs_info, flags);
304007730d87SJosef Bacik 	ASSERT(space_info);
304107730d87SJosef Bacik 
304207730d87SJosef Bacik 	do {
304307730d87SJosef Bacik 		spin_lock(&space_info->lock);
304407730d87SJosef Bacik 		if (force < space_info->force_alloc)
304507730d87SJosef Bacik 			force = space_info->force_alloc;
304607730d87SJosef Bacik 		should_alloc = should_alloc_chunk(fs_info, space_info, force);
304707730d87SJosef Bacik 		if (space_info->full) {
304807730d87SJosef Bacik 			/* No more free physical space */
304907730d87SJosef Bacik 			if (should_alloc)
305007730d87SJosef Bacik 				ret = -ENOSPC;
305107730d87SJosef Bacik 			else
305207730d87SJosef Bacik 				ret = 0;
305307730d87SJosef Bacik 			spin_unlock(&space_info->lock);
305407730d87SJosef Bacik 			return ret;
305507730d87SJosef Bacik 		} else if (!should_alloc) {
305607730d87SJosef Bacik 			spin_unlock(&space_info->lock);
305707730d87SJosef Bacik 			return 0;
305807730d87SJosef Bacik 		} else if (space_info->chunk_alloc) {
305907730d87SJosef Bacik 			/*
306007730d87SJosef Bacik 			 * Someone is already allocating, so we need to block
306107730d87SJosef Bacik 			 * until this someone is finished and then loop to
306207730d87SJosef Bacik 			 * recheck if we should continue with our allocation
306307730d87SJosef Bacik 			 * attempt.
306407730d87SJosef Bacik 			 */
306507730d87SJosef Bacik 			wait_for_alloc = true;
306607730d87SJosef Bacik 			spin_unlock(&space_info->lock);
306707730d87SJosef Bacik 			mutex_lock(&fs_info->chunk_mutex);
306807730d87SJosef Bacik 			mutex_unlock(&fs_info->chunk_mutex);
306907730d87SJosef Bacik 		} else {
307007730d87SJosef Bacik 			/* Proceed with allocation */
307107730d87SJosef Bacik 			space_info->chunk_alloc = 1;
307207730d87SJosef Bacik 			wait_for_alloc = false;
307307730d87SJosef Bacik 			spin_unlock(&space_info->lock);
307407730d87SJosef Bacik 		}
307507730d87SJosef Bacik 
307607730d87SJosef Bacik 		cond_resched();
307707730d87SJosef Bacik 	} while (wait_for_alloc);
307807730d87SJosef Bacik 
307907730d87SJosef Bacik 	mutex_lock(&fs_info->chunk_mutex);
308007730d87SJosef Bacik 	trans->allocating_chunk = true;
308107730d87SJosef Bacik 
308207730d87SJosef Bacik 	/*
308307730d87SJosef Bacik 	 * If we have mixed data/metadata chunks we want to make sure we keep
308407730d87SJosef Bacik 	 * allocating mixed chunks instead of individual chunks.
308507730d87SJosef Bacik 	 */
308607730d87SJosef Bacik 	if (btrfs_mixed_space_info(space_info))
308707730d87SJosef Bacik 		flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
308807730d87SJosef Bacik 
308907730d87SJosef Bacik 	/*
309007730d87SJosef Bacik 	 * if we're doing a data chunk, go ahead and make sure that
309107730d87SJosef Bacik 	 * we keep a reasonable number of metadata chunks allocated in the
309207730d87SJosef Bacik 	 * FS as well.
309307730d87SJosef Bacik 	 */
309407730d87SJosef Bacik 	if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
309507730d87SJosef Bacik 		fs_info->data_chunk_allocations++;
309607730d87SJosef Bacik 		if (!(fs_info->data_chunk_allocations %
309707730d87SJosef Bacik 		      fs_info->metadata_ratio))
309807730d87SJosef Bacik 			force_metadata_allocation(fs_info);
309907730d87SJosef Bacik 	}
310007730d87SJosef Bacik 
310107730d87SJosef Bacik 	/*
310207730d87SJosef Bacik 	 * Check if we have enough space in SYSTEM chunk because we may need
310307730d87SJosef Bacik 	 * to update devices.
310407730d87SJosef Bacik 	 */
310507730d87SJosef Bacik 	check_system_chunk(trans, flags);
310607730d87SJosef Bacik 
310707730d87SJosef Bacik 	ret = btrfs_alloc_chunk(trans, flags);
310807730d87SJosef Bacik 	trans->allocating_chunk = false;
310907730d87SJosef Bacik 
311007730d87SJosef Bacik 	spin_lock(&space_info->lock);
311107730d87SJosef Bacik 	if (ret < 0) {
311207730d87SJosef Bacik 		if (ret == -ENOSPC)
311307730d87SJosef Bacik 			space_info->full = 1;
311407730d87SJosef Bacik 		else
311507730d87SJosef Bacik 			goto out;
311607730d87SJosef Bacik 	} else {
311707730d87SJosef Bacik 		ret = 1;
311807730d87SJosef Bacik 		space_info->max_extent_size = 0;
311907730d87SJosef Bacik 	}
312007730d87SJosef Bacik 
312107730d87SJosef Bacik 	space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
312207730d87SJosef Bacik out:
312307730d87SJosef Bacik 	space_info->chunk_alloc = 0;
312407730d87SJosef Bacik 	spin_unlock(&space_info->lock);
312507730d87SJosef Bacik 	mutex_unlock(&fs_info->chunk_mutex);
312607730d87SJosef Bacik 	/*
312707730d87SJosef Bacik 	 * When we allocate a new chunk we reserve space in the chunk block
312807730d87SJosef Bacik 	 * reserve to make sure we can COW nodes/leafs in the chunk tree or
312907730d87SJosef Bacik 	 * add new nodes/leafs to it if we end up needing to do it when
313007730d87SJosef Bacik 	 * inserting the chunk item and updating device items as part of the
313107730d87SJosef Bacik 	 * second phase of chunk allocation, performed by
313207730d87SJosef Bacik 	 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
313307730d87SJosef Bacik 	 * large number of new block groups to create in our transaction
313407730d87SJosef Bacik 	 * handle's new_bgs list to avoid exhausting the chunk block reserve
313507730d87SJosef Bacik 	 * in extreme cases - like having a single transaction create many new
313607730d87SJosef Bacik 	 * block groups when starting to write out the free space caches of all
313707730d87SJosef Bacik 	 * the block groups that were made dirty during the lifetime of the
313807730d87SJosef Bacik 	 * transaction.
313907730d87SJosef Bacik 	 */
314007730d87SJosef Bacik 	if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
314107730d87SJosef Bacik 		btrfs_create_pending_block_groups(trans);
314207730d87SJosef Bacik 
314307730d87SJosef Bacik 	return ret;
314407730d87SJosef Bacik }
314507730d87SJosef Bacik 
314607730d87SJosef Bacik static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
314707730d87SJosef Bacik {
314807730d87SJosef Bacik 	u64 num_dev;
314907730d87SJosef Bacik 
315007730d87SJosef Bacik 	num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
315107730d87SJosef Bacik 	if (!num_dev)
315207730d87SJosef Bacik 		num_dev = fs_info->fs_devices->rw_devices;
315307730d87SJosef Bacik 
315407730d87SJosef Bacik 	return num_dev;
315507730d87SJosef Bacik }
315607730d87SJosef Bacik 
315707730d87SJosef Bacik /*
3158a9143bd3SMarcos Paulo de Souza  * Reserve space in the system space for allocating or removing a chunk
315907730d87SJosef Bacik  */
316007730d87SJosef Bacik void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
316107730d87SJosef Bacik {
316207730d87SJosef Bacik 	struct btrfs_fs_info *fs_info = trans->fs_info;
316307730d87SJosef Bacik 	struct btrfs_space_info *info;
316407730d87SJosef Bacik 	u64 left;
316507730d87SJosef Bacik 	u64 thresh;
316607730d87SJosef Bacik 	int ret = 0;
316707730d87SJosef Bacik 	u64 num_devs;
316807730d87SJosef Bacik 
316907730d87SJosef Bacik 	/*
317007730d87SJosef Bacik 	 * Needed because we can end up allocating a system chunk and for an
317107730d87SJosef Bacik 	 * atomic and race free space reservation in the chunk block reserve.
317207730d87SJosef Bacik 	 */
317307730d87SJosef Bacik 	lockdep_assert_held(&fs_info->chunk_mutex);
317407730d87SJosef Bacik 
317507730d87SJosef Bacik 	info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
317607730d87SJosef Bacik 	spin_lock(&info->lock);
317707730d87SJosef Bacik 	left = info->total_bytes - btrfs_space_info_used(info, true);
317807730d87SJosef Bacik 	spin_unlock(&info->lock);
317907730d87SJosef Bacik 
318007730d87SJosef Bacik 	num_devs = get_profile_num_devs(fs_info, type);
318107730d87SJosef Bacik 
318207730d87SJosef Bacik 	/* num_devs device items to update and 1 chunk item to add or remove */
31832bd36e7bSJosef Bacik 	thresh = btrfs_calc_metadata_size(fs_info, num_devs) +
31842bd36e7bSJosef Bacik 		btrfs_calc_insert_metadata_size(fs_info, 1);
318507730d87SJosef Bacik 
318607730d87SJosef Bacik 	if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
318707730d87SJosef Bacik 		btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
318807730d87SJosef Bacik 			   left, thresh, type);
318907730d87SJosef Bacik 		btrfs_dump_space_info(fs_info, info, 0, 0);
319007730d87SJosef Bacik 	}
319107730d87SJosef Bacik 
319207730d87SJosef Bacik 	if (left < thresh) {
319307730d87SJosef Bacik 		u64 flags = btrfs_system_alloc_profile(fs_info);
319407730d87SJosef Bacik 
319507730d87SJosef Bacik 		/*
319607730d87SJosef Bacik 		 * Ignore failure to create system chunk. We might end up not
319707730d87SJosef Bacik 		 * needing it, as we might not need to COW all nodes/leafs from
319807730d87SJosef Bacik 		 * the paths we visit in the chunk tree (they were already COWed
319907730d87SJosef Bacik 		 * or created in the current transaction for example).
320007730d87SJosef Bacik 		 */
320107730d87SJosef Bacik 		ret = btrfs_alloc_chunk(trans, flags);
320207730d87SJosef Bacik 	}
320307730d87SJosef Bacik 
320407730d87SJosef Bacik 	if (!ret) {
320507730d87SJosef Bacik 		ret = btrfs_block_rsv_add(fs_info->chunk_root,
320607730d87SJosef Bacik 					  &fs_info->chunk_block_rsv,
320707730d87SJosef Bacik 					  thresh, BTRFS_RESERVE_NO_FLUSH);
320807730d87SJosef Bacik 		if (!ret)
320907730d87SJosef Bacik 			trans->chunk_bytes_reserved += thresh;
321007730d87SJosef Bacik 	}
321107730d87SJosef Bacik }
321207730d87SJosef Bacik 
32133e43c279SJosef Bacik void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
32143e43c279SJosef Bacik {
321532da5386SDavid Sterba 	struct btrfs_block_group *block_group;
32163e43c279SJosef Bacik 	u64 last = 0;
32173e43c279SJosef Bacik 
32183e43c279SJosef Bacik 	while (1) {
32193e43c279SJosef Bacik 		struct inode *inode;
32203e43c279SJosef Bacik 
32213e43c279SJosef Bacik 		block_group = btrfs_lookup_first_block_group(info, last);
32223e43c279SJosef Bacik 		while (block_group) {
32233e43c279SJosef Bacik 			btrfs_wait_block_group_cache_done(block_group);
32243e43c279SJosef Bacik 			spin_lock(&block_group->lock);
32253e43c279SJosef Bacik 			if (block_group->iref)
32263e43c279SJosef Bacik 				break;
32273e43c279SJosef Bacik 			spin_unlock(&block_group->lock);
32283e43c279SJosef Bacik 			block_group = btrfs_next_block_group(block_group);
32293e43c279SJosef Bacik 		}
32303e43c279SJosef Bacik 		if (!block_group) {
32313e43c279SJosef Bacik 			if (last == 0)
32323e43c279SJosef Bacik 				break;
32333e43c279SJosef Bacik 			last = 0;
32343e43c279SJosef Bacik 			continue;
32353e43c279SJosef Bacik 		}
32363e43c279SJosef Bacik 
32373e43c279SJosef Bacik 		inode = block_group->inode;
32383e43c279SJosef Bacik 		block_group->iref = 0;
32393e43c279SJosef Bacik 		block_group->inode = NULL;
32403e43c279SJosef Bacik 		spin_unlock(&block_group->lock);
32413e43c279SJosef Bacik 		ASSERT(block_group->io_ctl.inode == NULL);
32423e43c279SJosef Bacik 		iput(inode);
3243b3470b5dSDavid Sterba 		last = block_group->start + block_group->length;
32443e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
32453e43c279SJosef Bacik 	}
32463e43c279SJosef Bacik }
32473e43c279SJosef Bacik 
32483e43c279SJosef Bacik /*
32493e43c279SJosef Bacik  * Must be called only after stopping all workers, since we could have block
32503e43c279SJosef Bacik  * group caching kthreads running, and therefore they could race with us if we
32513e43c279SJosef Bacik  * freed the block groups before stopping them.
32523e43c279SJosef Bacik  */
32533e43c279SJosef Bacik int btrfs_free_block_groups(struct btrfs_fs_info *info)
32543e43c279SJosef Bacik {
325532da5386SDavid Sterba 	struct btrfs_block_group *block_group;
32563e43c279SJosef Bacik 	struct btrfs_space_info *space_info;
32573e43c279SJosef Bacik 	struct btrfs_caching_control *caching_ctl;
32583e43c279SJosef Bacik 	struct rb_node *n;
32593e43c279SJosef Bacik 
32603e43c279SJosef Bacik 	down_write(&info->commit_root_sem);
32613e43c279SJosef Bacik 	while (!list_empty(&info->caching_block_groups)) {
32623e43c279SJosef Bacik 		caching_ctl = list_entry(info->caching_block_groups.next,
32633e43c279SJosef Bacik 					 struct btrfs_caching_control, list);
32643e43c279SJosef Bacik 		list_del(&caching_ctl->list);
32653e43c279SJosef Bacik 		btrfs_put_caching_control(caching_ctl);
32663e43c279SJosef Bacik 	}
32673e43c279SJosef Bacik 	up_write(&info->commit_root_sem);
32683e43c279SJosef Bacik 
32693e43c279SJosef Bacik 	spin_lock(&info->unused_bgs_lock);
32703e43c279SJosef Bacik 	while (!list_empty(&info->unused_bgs)) {
32713e43c279SJosef Bacik 		block_group = list_first_entry(&info->unused_bgs,
327232da5386SDavid Sterba 					       struct btrfs_block_group,
32733e43c279SJosef Bacik 					       bg_list);
32743e43c279SJosef Bacik 		list_del_init(&block_group->bg_list);
32753e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
32763e43c279SJosef Bacik 	}
32773e43c279SJosef Bacik 	spin_unlock(&info->unused_bgs_lock);
32783e43c279SJosef Bacik 
32793e43c279SJosef Bacik 	spin_lock(&info->block_group_cache_lock);
32803e43c279SJosef Bacik 	while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
328132da5386SDavid Sterba 		block_group = rb_entry(n, struct btrfs_block_group,
32823e43c279SJosef Bacik 				       cache_node);
32833e43c279SJosef Bacik 		rb_erase(&block_group->cache_node,
32843e43c279SJosef Bacik 			 &info->block_group_cache_tree);
32853e43c279SJosef Bacik 		RB_CLEAR_NODE(&block_group->cache_node);
32863e43c279SJosef Bacik 		spin_unlock(&info->block_group_cache_lock);
32873e43c279SJosef Bacik 
32883e43c279SJosef Bacik 		down_write(&block_group->space_info->groups_sem);
32893e43c279SJosef Bacik 		list_del(&block_group->list);
32903e43c279SJosef Bacik 		up_write(&block_group->space_info->groups_sem);
32913e43c279SJosef Bacik 
32923e43c279SJosef Bacik 		/*
32933e43c279SJosef Bacik 		 * We haven't cached this block group, which means we could
32943e43c279SJosef Bacik 		 * possibly have excluded extents on this block group.
32953e43c279SJosef Bacik 		 */
32963e43c279SJosef Bacik 		if (block_group->cached == BTRFS_CACHE_NO ||
32973e43c279SJosef Bacik 		    block_group->cached == BTRFS_CACHE_ERROR)
32983e43c279SJosef Bacik 			btrfs_free_excluded_extents(block_group);
32993e43c279SJosef Bacik 
33003e43c279SJosef Bacik 		btrfs_remove_free_space_cache(block_group);
33013e43c279SJosef Bacik 		ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
33023e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->dirty_list));
33033e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->io_list));
33043e43c279SJosef Bacik 		ASSERT(list_empty(&block_group->bg_list));
33053e43c279SJosef Bacik 		ASSERT(atomic_read(&block_group->count) == 1);
33063e43c279SJosef Bacik 		btrfs_put_block_group(block_group);
33073e43c279SJosef Bacik 
33083e43c279SJosef Bacik 		spin_lock(&info->block_group_cache_lock);
33093e43c279SJosef Bacik 	}
33103e43c279SJosef Bacik 	spin_unlock(&info->block_group_cache_lock);
33113e43c279SJosef Bacik 
33123e43c279SJosef Bacik 	/*
33133e43c279SJosef Bacik 	 * Now that all the block groups are freed, go through and free all the
33143e43c279SJosef Bacik 	 * space_info structs.  This is only called during the final stages of
33153e43c279SJosef Bacik 	 * unmount, and so we know nobody is using them.  We call
33163e43c279SJosef Bacik 	 * synchronize_rcu() once before we start, just to be on the safe side.
33173e43c279SJosef Bacik 	 */
33183e43c279SJosef Bacik 	synchronize_rcu();
33193e43c279SJosef Bacik 
33203e43c279SJosef Bacik 	btrfs_release_global_block_rsv(info);
33213e43c279SJosef Bacik 
33223e43c279SJosef Bacik 	while (!list_empty(&info->space_info)) {
33233e43c279SJosef Bacik 		space_info = list_entry(info->space_info.next,
33243e43c279SJosef Bacik 					struct btrfs_space_info,
33253e43c279SJosef Bacik 					list);
33263e43c279SJosef Bacik 
33273e43c279SJosef Bacik 		/*
33283e43c279SJosef Bacik 		 * Do not hide this behind enospc_debug, this is actually
33293e43c279SJosef Bacik 		 * important and indicates a real bug if this happens.
33303e43c279SJosef Bacik 		 */
33313e43c279SJosef Bacik 		if (WARN_ON(space_info->bytes_pinned > 0 ||
33323e43c279SJosef Bacik 			    space_info->bytes_reserved > 0 ||
33333e43c279SJosef Bacik 			    space_info->bytes_may_use > 0))
33343e43c279SJosef Bacik 			btrfs_dump_space_info(info, space_info, 0, 0);
33353e43c279SJosef Bacik 		list_del(&space_info->list);
33363e43c279SJosef Bacik 		btrfs_sysfs_remove_space_info(space_info);
33373e43c279SJosef Bacik 	}
33383e43c279SJosef Bacik 	return 0;
33393e43c279SJosef Bacik }
3340