xref: /linux/fs/btrfs/block-group.c (revision 0eb4aaa230d725fa9b1cd758c0f17abca5597af6)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include <linux/sizes.h>
4 #include <linux/list_sort.h>
5 #include "misc.h"
6 #include "ctree.h"
7 #include "block-group.h"
8 #include "space-info.h"
9 #include "disk-io.h"
10 #include "free-space-cache.h"
11 #include "free-space-tree.h"
12 #include "volumes.h"
13 #include "transaction.h"
14 #include "ref-verify.h"
15 #include "sysfs.h"
16 #include "tree-log.h"
17 #include "delalloc-space.h"
18 #include "discard.h"
19 #include "raid56.h"
20 #include "zoned.h"
21 #include "fs.h"
22 #include "accessors.h"
23 #include "extent-tree.h"
24 
25 #ifdef CONFIG_BTRFS_DEBUG
btrfs_should_fragment_free_space(const struct btrfs_block_group * block_group)26 int btrfs_should_fragment_free_space(const struct btrfs_block_group *block_group)
27 {
28 	struct btrfs_fs_info *fs_info = block_group->fs_info;
29 
30 	return (btrfs_test_opt(fs_info, FRAGMENT_METADATA) &&
31 		block_group->flags & BTRFS_BLOCK_GROUP_METADATA) ||
32 	       (btrfs_test_opt(fs_info, FRAGMENT_DATA) &&
33 		block_group->flags &  BTRFS_BLOCK_GROUP_DATA);
34 }
35 #endif
36 
37 /*
38  * Return target flags in extended format or 0 if restripe for this chunk_type
39  * is not in progress
40  *
41  * Should be called with balance_lock held
42  */
get_restripe_target(const struct btrfs_fs_info * fs_info,u64 flags)43 static u64 get_restripe_target(const struct btrfs_fs_info *fs_info, u64 flags)
44 {
45 	const struct btrfs_balance_control *bctl = fs_info->balance_ctl;
46 	u64 target = 0;
47 
48 	if (!bctl)
49 		return 0;
50 
51 	if (flags & BTRFS_BLOCK_GROUP_DATA &&
52 	    bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
53 		target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
54 	} else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
55 		   bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
56 		target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
57 	} else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
58 		   bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
59 		target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
60 	}
61 
62 	return target;
63 }
64 
65 /*
66  * @flags: available profiles in extended format (see ctree.h)
67  *
68  * Return reduced profile in chunk format.  If profile changing is in progress
69  * (either running or paused) picks the target profile (if it's already
70  * available), otherwise falls back to plain reducing.
71  */
btrfs_reduce_alloc_profile(struct btrfs_fs_info * fs_info,u64 flags)72 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
73 {
74 	u64 num_devices = fs_info->fs_devices->rw_devices;
75 	u64 target;
76 	u64 raid_type;
77 	u64 allowed = 0;
78 
79 	/*
80 	 * See if restripe for this chunk_type is in progress, if so try to
81 	 * reduce to the target profile
82 	 */
83 	spin_lock(&fs_info->balance_lock);
84 	target = get_restripe_target(fs_info, flags);
85 	if (target) {
86 		spin_unlock(&fs_info->balance_lock);
87 		return extended_to_chunk(target);
88 	}
89 	spin_unlock(&fs_info->balance_lock);
90 
91 	/* First, mask out the RAID levels which aren't possible */
92 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
93 		if (num_devices >= btrfs_raid_array[raid_type].devs_min)
94 			allowed |= btrfs_raid_array[raid_type].bg_flag;
95 	}
96 	allowed &= flags;
97 
98 	/* Select the highest-redundancy RAID level. */
99 	if (allowed & BTRFS_BLOCK_GROUP_RAID1C4)
100 		allowed = BTRFS_BLOCK_GROUP_RAID1C4;
101 	else if (allowed & BTRFS_BLOCK_GROUP_RAID6)
102 		allowed = BTRFS_BLOCK_GROUP_RAID6;
103 	else if (allowed & BTRFS_BLOCK_GROUP_RAID1C3)
104 		allowed = BTRFS_BLOCK_GROUP_RAID1C3;
105 	else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
106 		allowed = BTRFS_BLOCK_GROUP_RAID5;
107 	else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
108 		allowed = BTRFS_BLOCK_GROUP_RAID10;
109 	else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
110 		allowed = BTRFS_BLOCK_GROUP_RAID1;
111 	else if (allowed & BTRFS_BLOCK_GROUP_DUP)
112 		allowed = BTRFS_BLOCK_GROUP_DUP;
113 	else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
114 		allowed = BTRFS_BLOCK_GROUP_RAID0;
115 
116 	flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
117 
118 	return extended_to_chunk(flags | allowed);
119 }
120 
btrfs_get_alloc_profile(struct btrfs_fs_info * fs_info,u64 orig_flags)121 u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
122 {
123 	unsigned seq;
124 	u64 flags;
125 
126 	do {
127 		flags = orig_flags;
128 		seq = read_seqbegin(&fs_info->profiles_lock);
129 
130 		if (flags & BTRFS_BLOCK_GROUP_DATA)
131 			flags |= fs_info->avail_data_alloc_bits;
132 		else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
133 			flags |= fs_info->avail_system_alloc_bits;
134 		else if (flags & BTRFS_BLOCK_GROUP_METADATA)
135 			flags |= fs_info->avail_metadata_alloc_bits;
136 	} while (read_seqretry(&fs_info->profiles_lock, seq));
137 
138 	return btrfs_reduce_alloc_profile(fs_info, flags);
139 }
140 
btrfs_get_block_group(struct btrfs_block_group * cache)141 void btrfs_get_block_group(struct btrfs_block_group *cache)
142 {
143 	refcount_inc(&cache->refs);
144 }
145 
btrfs_put_block_group(struct btrfs_block_group * cache)146 void btrfs_put_block_group(struct btrfs_block_group *cache)
147 {
148 	if (refcount_dec_and_test(&cache->refs)) {
149 		WARN_ON(cache->pinned > 0);
150 		/*
151 		 * If there was a failure to cleanup a log tree, very likely due
152 		 * to an IO failure on a writeback attempt of one or more of its
153 		 * extent buffers, we could not do proper (and cheap) unaccounting
154 		 * of their reserved space, so don't warn on reserved > 0 in that
155 		 * case.
156 		 */
157 		if (!(cache->flags & BTRFS_BLOCK_GROUP_METADATA) ||
158 		    !BTRFS_FS_LOG_CLEANUP_ERROR(cache->fs_info))
159 			WARN_ON(cache->reserved > 0);
160 
161 		/*
162 		 * A block_group shouldn't be on the discard_list anymore.
163 		 * Remove the block_group from the discard_list to prevent us
164 		 * from causing a panic due to NULL pointer dereference.
165 		 */
166 		if (WARN_ON(!list_empty(&cache->discard_list)))
167 			btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
168 						  cache);
169 
170 		kfree(cache->free_space_ctl);
171 		btrfs_free_chunk_map(cache->physical_map);
172 		kfree(cache);
173 	}
174 }
175 
btrfs_bg_start_cmp(const struct rb_node * new,const struct rb_node * exist)176 static int btrfs_bg_start_cmp(const struct rb_node *new,
177 			      const struct rb_node *exist)
178 {
179 	const struct btrfs_block_group *new_bg =
180 		rb_entry(new, struct btrfs_block_group, cache_node);
181 	const struct btrfs_block_group *exist_bg =
182 		rb_entry(exist, struct btrfs_block_group, cache_node);
183 
184 	if (new_bg->start < exist_bg->start)
185 		return -1;
186 	if (new_bg->start > exist_bg->start)
187 		return 1;
188 	return 0;
189 }
190 
191 /*
192  * This adds the block group to the fs_info rb tree for the block group cache
193  */
btrfs_add_block_group_cache(struct btrfs_fs_info * info,struct btrfs_block_group * block_group)194 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
195 				       struct btrfs_block_group *block_group)
196 {
197 	struct rb_node *exist;
198 	int ret = 0;
199 
200 	ASSERT(block_group->length != 0);
201 
202 	write_lock(&info->block_group_cache_lock);
203 
204 	exist = rb_find_add_cached(&block_group->cache_node,
205 			&info->block_group_cache_tree, btrfs_bg_start_cmp);
206 	if (exist)
207 		ret = -EEXIST;
208 	write_unlock(&info->block_group_cache_lock);
209 
210 	return ret;
211 }
212 
213 /*
214  * This will return the block group at or after bytenr if contains is 0, else
215  * it will return the block group that contains the bytenr
216  */
block_group_cache_tree_search(struct btrfs_fs_info * info,u64 bytenr,int contains)217 static struct btrfs_block_group *block_group_cache_tree_search(
218 		struct btrfs_fs_info *info, u64 bytenr, int contains)
219 {
220 	struct btrfs_block_group *cache, *ret = NULL;
221 	struct rb_node *n;
222 	u64 end, start;
223 
224 	read_lock(&info->block_group_cache_lock);
225 	n = info->block_group_cache_tree.rb_root.rb_node;
226 
227 	while (n) {
228 		cache = rb_entry(n, struct btrfs_block_group, cache_node);
229 		end = cache->start + cache->length - 1;
230 		start = cache->start;
231 
232 		if (bytenr < start) {
233 			if (!contains && (!ret || start < ret->start))
234 				ret = cache;
235 			n = n->rb_left;
236 		} else if (bytenr > start) {
237 			if (contains && bytenr <= end) {
238 				ret = cache;
239 				break;
240 			}
241 			n = n->rb_right;
242 		} else {
243 			ret = cache;
244 			break;
245 		}
246 	}
247 	if (ret)
248 		btrfs_get_block_group(ret);
249 	read_unlock(&info->block_group_cache_lock);
250 
251 	return ret;
252 }
253 
254 /*
255  * Return the block group that starts at or after bytenr
256  */
btrfs_lookup_first_block_group(struct btrfs_fs_info * info,u64 bytenr)257 struct btrfs_block_group *btrfs_lookup_first_block_group(
258 		struct btrfs_fs_info *info, u64 bytenr)
259 {
260 	return block_group_cache_tree_search(info, bytenr, 0);
261 }
262 
263 /*
264  * Return the block group that contains the given bytenr
265  */
btrfs_lookup_block_group(struct btrfs_fs_info * info,u64 bytenr)266 struct btrfs_block_group *btrfs_lookup_block_group(
267 		struct btrfs_fs_info *info, u64 bytenr)
268 {
269 	return block_group_cache_tree_search(info, bytenr, 1);
270 }
271 
btrfs_next_block_group(struct btrfs_block_group * cache)272 struct btrfs_block_group *btrfs_next_block_group(
273 		struct btrfs_block_group *cache)
274 {
275 	struct btrfs_fs_info *fs_info = cache->fs_info;
276 	struct rb_node *node;
277 
278 	read_lock(&fs_info->block_group_cache_lock);
279 
280 	/* If our block group was removed, we need a full search. */
281 	if (RB_EMPTY_NODE(&cache->cache_node)) {
282 		const u64 next_bytenr = cache->start + cache->length;
283 
284 		read_unlock(&fs_info->block_group_cache_lock);
285 		btrfs_put_block_group(cache);
286 		return btrfs_lookup_first_block_group(fs_info, next_bytenr);
287 	}
288 	node = rb_next(&cache->cache_node);
289 	btrfs_put_block_group(cache);
290 	if (node) {
291 		cache = rb_entry(node, struct btrfs_block_group, cache_node);
292 		btrfs_get_block_group(cache);
293 	} else
294 		cache = NULL;
295 	read_unlock(&fs_info->block_group_cache_lock);
296 	return cache;
297 }
298 
299 /*
300  * Check if we can do a NOCOW write for a given extent.
301  *
302  * @fs_info:       The filesystem information object.
303  * @bytenr:        Logical start address of the extent.
304  *
305  * Check if we can do a NOCOW write for the given extent, and increments the
306  * number of NOCOW writers in the block group that contains the extent, as long
307  * as the block group exists and it's currently not in read-only mode.
308  *
309  * Returns: A non-NULL block group pointer if we can do a NOCOW write, the caller
310  *          is responsible for calling btrfs_dec_nocow_writers() later.
311  *
312  *          Or NULL if we can not do a NOCOW write
313  */
btrfs_inc_nocow_writers(struct btrfs_fs_info * fs_info,u64 bytenr)314 struct btrfs_block_group *btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info,
315 						  u64 bytenr)
316 {
317 	struct btrfs_block_group *bg;
318 	bool can_nocow = true;
319 
320 	bg = btrfs_lookup_block_group(fs_info, bytenr);
321 	if (!bg)
322 		return NULL;
323 
324 	spin_lock(&bg->lock);
325 	if (bg->ro)
326 		can_nocow = false;
327 	else
328 		atomic_inc(&bg->nocow_writers);
329 	spin_unlock(&bg->lock);
330 
331 	if (!can_nocow) {
332 		btrfs_put_block_group(bg);
333 		return NULL;
334 	}
335 
336 	/* No put on block group, done by btrfs_dec_nocow_writers(). */
337 	return bg;
338 }
339 
340 /*
341  * Decrement the number of NOCOW writers in a block group.
342  *
343  * This is meant to be called after a previous call to btrfs_inc_nocow_writers(),
344  * and on the block group returned by that call. Typically this is called after
345  * creating an ordered extent for a NOCOW write, to prevent races with scrub and
346  * relocation.
347  *
348  * After this call, the caller should not use the block group anymore. It it wants
349  * to use it, then it should get a reference on it before calling this function.
350  */
btrfs_dec_nocow_writers(struct btrfs_block_group * bg)351 void btrfs_dec_nocow_writers(struct btrfs_block_group *bg)
352 {
353 	if (atomic_dec_and_test(&bg->nocow_writers))
354 		wake_up_var(&bg->nocow_writers);
355 
356 	/* For the lookup done by a previous call to btrfs_inc_nocow_writers(). */
357 	btrfs_put_block_group(bg);
358 }
359 
btrfs_wait_nocow_writers(struct btrfs_block_group * bg)360 void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
361 {
362 	wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
363 }
364 
btrfs_dec_block_group_reservations(struct btrfs_fs_info * fs_info,const u64 start)365 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
366 					const u64 start)
367 {
368 	struct btrfs_block_group *bg;
369 
370 	bg = btrfs_lookup_block_group(fs_info, start);
371 	ASSERT(bg);
372 	if (atomic_dec_and_test(&bg->reservations))
373 		wake_up_var(&bg->reservations);
374 	btrfs_put_block_group(bg);
375 }
376 
btrfs_wait_block_group_reservations(struct btrfs_block_group * bg)377 void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
378 {
379 	struct btrfs_space_info *space_info = bg->space_info;
380 
381 	ASSERT(bg->ro);
382 
383 	if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
384 		return;
385 
386 	/*
387 	 * Our block group is read only but before we set it to read only,
388 	 * some task might have had allocated an extent from it already, but it
389 	 * has not yet created a respective ordered extent (and added it to a
390 	 * root's list of ordered extents).
391 	 * Therefore wait for any task currently allocating extents, since the
392 	 * block group's reservations counter is incremented while a read lock
393 	 * on the groups' semaphore is held and decremented after releasing
394 	 * the read access on that semaphore and creating the ordered extent.
395 	 */
396 	down_write(&space_info->groups_sem);
397 	up_write(&space_info->groups_sem);
398 
399 	wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
400 }
401 
btrfs_get_caching_control(struct btrfs_block_group * cache)402 struct btrfs_caching_control *btrfs_get_caching_control(
403 		struct btrfs_block_group *cache)
404 {
405 	struct btrfs_caching_control *ctl;
406 
407 	spin_lock(&cache->lock);
408 	if (!cache->caching_ctl) {
409 		spin_unlock(&cache->lock);
410 		return NULL;
411 	}
412 
413 	ctl = cache->caching_ctl;
414 	refcount_inc(&ctl->count);
415 	spin_unlock(&cache->lock);
416 	return ctl;
417 }
418 
btrfs_put_caching_control(struct btrfs_caching_control * ctl)419 static void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
420 {
421 	if (refcount_dec_and_test(&ctl->count))
422 		kfree(ctl);
423 }
424 
425 /*
426  * When we wait for progress in the block group caching, its because our
427  * allocation attempt failed at least once.  So, we must sleep and let some
428  * progress happen before we try again.
429  *
430  * This function will sleep at least once waiting for new free space to show
431  * up, and then it will check the block group free space numbers for our min
432  * num_bytes.  Another option is to have it go ahead and look in the rbtree for
433  * a free extent of a given size, but this is a good start.
434  *
435  * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
436  * any of the information in this block group.
437  */
btrfs_wait_block_group_cache_progress(struct btrfs_block_group * cache,u64 num_bytes)438 void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
439 					   u64 num_bytes)
440 {
441 	struct btrfs_caching_control *caching_ctl;
442 	int progress;
443 
444 	caching_ctl = btrfs_get_caching_control(cache);
445 	if (!caching_ctl)
446 		return;
447 
448 	/*
449 	 * We've already failed to allocate from this block group, so even if
450 	 * there's enough space in the block group it isn't contiguous enough to
451 	 * allow for an allocation, so wait for at least the next wakeup tick,
452 	 * or for the thing to be done.
453 	 */
454 	progress = atomic_read(&caching_ctl->progress);
455 
456 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
457 		   (progress != atomic_read(&caching_ctl->progress) &&
458 		    (cache->free_space_ctl->free_space >= num_bytes)));
459 
460 	btrfs_put_caching_control(caching_ctl);
461 }
462 
btrfs_caching_ctl_wait_done(struct btrfs_block_group * cache,struct btrfs_caching_control * caching_ctl)463 static int btrfs_caching_ctl_wait_done(struct btrfs_block_group *cache,
464 				       struct btrfs_caching_control *caching_ctl)
465 {
466 	wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
467 	return cache->cached == BTRFS_CACHE_ERROR ? -EIO : 0;
468 }
469 
btrfs_wait_block_group_cache_done(struct btrfs_block_group * cache)470 static int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
471 {
472 	struct btrfs_caching_control *caching_ctl;
473 	int ret;
474 
475 	caching_ctl = btrfs_get_caching_control(cache);
476 	if (!caching_ctl)
477 		return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
478 	ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
479 	btrfs_put_caching_control(caching_ctl);
480 	return ret;
481 }
482 
483 #ifdef CONFIG_BTRFS_DEBUG
fragment_free_space(struct btrfs_block_group * block_group)484 static void fragment_free_space(struct btrfs_block_group *block_group)
485 {
486 	struct btrfs_fs_info *fs_info = block_group->fs_info;
487 	u64 start = block_group->start;
488 	u64 len = block_group->length;
489 	u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
490 		fs_info->nodesize : fs_info->sectorsize;
491 	u64 step = chunk << 1;
492 
493 	while (len > chunk) {
494 		btrfs_remove_free_space(block_group, start, chunk);
495 		start += step;
496 		if (len < step)
497 			len = 0;
498 		else
499 			len -= step;
500 	}
501 }
502 #endif
503 
504 /*
505  * Add a free space range to the in memory free space cache of a block group.
506  * This checks if the range contains super block locations and any such
507  * locations are not added to the free space cache.
508  *
509  * @block_group:      The target block group.
510  * @start:            Start offset of the range.
511  * @end:              End offset of the range (exclusive).
512  * @total_added_ret:  Optional pointer to return the total amount of space
513  *                    added to the block group's free space cache.
514  *
515  * Returns 0 on success or < 0 on error.
516  */
btrfs_add_new_free_space(struct btrfs_block_group * block_group,u64 start,u64 end,u64 * total_added_ret)517 int btrfs_add_new_free_space(struct btrfs_block_group *block_group, u64 start,
518 			     u64 end, u64 *total_added_ret)
519 {
520 	struct btrfs_fs_info *info = block_group->fs_info;
521 	u64 extent_start, extent_end, size;
522 	int ret;
523 
524 	if (total_added_ret)
525 		*total_added_ret = 0;
526 
527 	while (start < end) {
528 		if (!find_first_extent_bit(&info->excluded_extents, start,
529 					   &extent_start, &extent_end,
530 					   EXTENT_DIRTY | EXTENT_UPTODATE,
531 					   NULL))
532 			break;
533 
534 		if (extent_start <= start) {
535 			start = extent_end + 1;
536 		} else if (extent_start > start && extent_start < end) {
537 			size = extent_start - start;
538 			ret = btrfs_add_free_space_async_trimmed(block_group,
539 								 start, size);
540 			if (ret)
541 				return ret;
542 			if (total_added_ret)
543 				*total_added_ret += size;
544 			start = extent_end + 1;
545 		} else {
546 			break;
547 		}
548 	}
549 
550 	if (start < end) {
551 		size = end - start;
552 		ret = btrfs_add_free_space_async_trimmed(block_group, start,
553 							 size);
554 		if (ret)
555 			return ret;
556 		if (total_added_ret)
557 			*total_added_ret += size;
558 	}
559 
560 	return 0;
561 }
562 
563 /*
564  * Get an arbitrary extent item index / max_index through the block group
565  *
566  * @block_group   the block group to sample from
567  * @index:        the integral step through the block group to grab from
568  * @max_index:    the granularity of the sampling
569  * @key:          return value parameter for the item we find
570  *
571  * Pre-conditions on indices:
572  * 0 <= index <= max_index
573  * 0 < max_index
574  *
575  * Returns: 0 on success, 1 if the search didn't yield a useful item, negative
576  * error code on error.
577  */
sample_block_group_extent_item(struct btrfs_caching_control * caching_ctl,struct btrfs_block_group * block_group,int index,int max_index,struct btrfs_key * found_key)578 static int sample_block_group_extent_item(struct btrfs_caching_control *caching_ctl,
579 					  struct btrfs_block_group *block_group,
580 					  int index, int max_index,
581 					  struct btrfs_key *found_key)
582 {
583 	struct btrfs_fs_info *fs_info = block_group->fs_info;
584 	struct btrfs_root *extent_root;
585 	u64 search_offset;
586 	u64 search_end = block_group->start + block_group->length;
587 	struct btrfs_path *path;
588 	struct btrfs_key search_key;
589 	int ret = 0;
590 
591 	ASSERT(index >= 0);
592 	ASSERT(index <= max_index);
593 	ASSERT(max_index > 0);
594 	lockdep_assert_held(&caching_ctl->mutex);
595 	lockdep_assert_held_read(&fs_info->commit_root_sem);
596 
597 	path = btrfs_alloc_path();
598 	if (!path)
599 		return -ENOMEM;
600 
601 	extent_root = btrfs_extent_root(fs_info, max_t(u64, block_group->start,
602 						       BTRFS_SUPER_INFO_OFFSET));
603 
604 	path->skip_locking = 1;
605 	path->search_commit_root = 1;
606 	path->reada = READA_FORWARD;
607 
608 	search_offset = index * div_u64(block_group->length, max_index);
609 	search_key.objectid = block_group->start + search_offset;
610 	search_key.type = BTRFS_EXTENT_ITEM_KEY;
611 	search_key.offset = 0;
612 
613 	btrfs_for_each_slot(extent_root, &search_key, found_key, path, ret) {
614 		/* Success; sampled an extent item in the block group */
615 		if (found_key->type == BTRFS_EXTENT_ITEM_KEY &&
616 		    found_key->objectid >= block_group->start &&
617 		    found_key->objectid + found_key->offset <= search_end)
618 			break;
619 
620 		/* We can't possibly find a valid extent item anymore */
621 		if (found_key->objectid >= search_end) {
622 			ret = 1;
623 			break;
624 		}
625 	}
626 
627 	lockdep_assert_held(&caching_ctl->mutex);
628 	lockdep_assert_held_read(&fs_info->commit_root_sem);
629 	btrfs_free_path(path);
630 	return ret;
631 }
632 
633 /*
634  * Best effort attempt to compute a block group's size class while caching it.
635  *
636  * @block_group: the block group we are caching
637  *
638  * We cannot infer the size class while adding free space extents, because that
639  * logic doesn't care about contiguous file extents (it doesn't differentiate
640  * between a 100M extent and 100 contiguous 1M extents). So we need to read the
641  * file extent items. Reading all of them is quite wasteful, because usually
642  * only a handful are enough to give a good answer. Therefore, we just grab 5 of
643  * them at even steps through the block group and pick the smallest size class
644  * we see. Since size class is best effort, and not guaranteed in general,
645  * inaccuracy is acceptable.
646  *
647  * To be more explicit about why this algorithm makes sense:
648  *
649  * If we are caching in a block group from disk, then there are three major cases
650  * to consider:
651  * 1. the block group is well behaved and all extents in it are the same size
652  *    class.
653  * 2. the block group is mostly one size class with rare exceptions for last
654  *    ditch allocations
655  * 3. the block group was populated before size classes and can have a totally
656  *    arbitrary mix of size classes.
657  *
658  * In case 1, looking at any extent in the block group will yield the correct
659  * result. For the mixed cases, taking the minimum size class seems like a good
660  * approximation, since gaps from frees will be usable to the size class. For
661  * 2., a small handful of file extents is likely to yield the right answer. For
662  * 3, we can either read every file extent, or admit that this is best effort
663  * anyway and try to stay fast.
664  *
665  * Returns: 0 on success, negative error code on error.
666  */
load_block_group_size_class(struct btrfs_caching_control * caching_ctl,struct btrfs_block_group * block_group)667 static int load_block_group_size_class(struct btrfs_caching_control *caching_ctl,
668 				       struct btrfs_block_group *block_group)
669 {
670 	struct btrfs_fs_info *fs_info = block_group->fs_info;
671 	struct btrfs_key key;
672 	int i;
673 	u64 min_size = block_group->length;
674 	enum btrfs_block_group_size_class size_class = BTRFS_BG_SZ_NONE;
675 	int ret;
676 
677 	if (!btrfs_block_group_should_use_size_class(block_group))
678 		return 0;
679 
680 	lockdep_assert_held(&caching_ctl->mutex);
681 	lockdep_assert_held_read(&fs_info->commit_root_sem);
682 	for (i = 0; i < 5; ++i) {
683 		ret = sample_block_group_extent_item(caching_ctl, block_group, i, 5, &key);
684 		if (ret < 0)
685 			goto out;
686 		if (ret > 0)
687 			continue;
688 		min_size = min_t(u64, min_size, key.offset);
689 		size_class = btrfs_calc_block_group_size_class(min_size);
690 	}
691 	if (size_class != BTRFS_BG_SZ_NONE) {
692 		spin_lock(&block_group->lock);
693 		block_group->size_class = size_class;
694 		spin_unlock(&block_group->lock);
695 	}
696 out:
697 	return ret;
698 }
699 
load_extent_tree_free(struct btrfs_caching_control * caching_ctl)700 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
701 {
702 	struct btrfs_block_group *block_group = caching_ctl->block_group;
703 	struct btrfs_fs_info *fs_info = block_group->fs_info;
704 	struct btrfs_root *extent_root;
705 	struct btrfs_path *path;
706 	struct extent_buffer *leaf;
707 	struct btrfs_key key;
708 	u64 total_found = 0;
709 	u64 last = 0;
710 	u32 nritems;
711 	int ret;
712 	bool wakeup = true;
713 
714 	path = btrfs_alloc_path();
715 	if (!path)
716 		return -ENOMEM;
717 
718 	last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
719 	extent_root = btrfs_extent_root(fs_info, last);
720 
721 #ifdef CONFIG_BTRFS_DEBUG
722 	/*
723 	 * If we're fragmenting we don't want to make anybody think we can
724 	 * allocate from this block group until we've had a chance to fragment
725 	 * the free space.
726 	 */
727 	if (btrfs_should_fragment_free_space(block_group))
728 		wakeup = false;
729 #endif
730 	/*
731 	 * We don't want to deadlock with somebody trying to allocate a new
732 	 * extent for the extent root while also trying to search the extent
733 	 * root to add free space.  So we skip locking and search the commit
734 	 * root, since its read-only
735 	 */
736 	path->skip_locking = 1;
737 	path->search_commit_root = 1;
738 	path->reada = READA_FORWARD;
739 
740 	key.objectid = last;
741 	key.offset = 0;
742 	key.type = BTRFS_EXTENT_ITEM_KEY;
743 
744 next:
745 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
746 	if (ret < 0)
747 		goto out;
748 
749 	leaf = path->nodes[0];
750 	nritems = btrfs_header_nritems(leaf);
751 
752 	while (1) {
753 		if (btrfs_fs_closing(fs_info) > 1) {
754 			last = (u64)-1;
755 			break;
756 		}
757 
758 		if (path->slots[0] < nritems) {
759 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
760 		} else {
761 			ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
762 			if (ret)
763 				break;
764 
765 			if (need_resched() ||
766 			    rwsem_is_contended(&fs_info->commit_root_sem)) {
767 				btrfs_release_path(path);
768 				up_read(&fs_info->commit_root_sem);
769 				mutex_unlock(&caching_ctl->mutex);
770 				cond_resched();
771 				mutex_lock(&caching_ctl->mutex);
772 				down_read(&fs_info->commit_root_sem);
773 				goto next;
774 			}
775 
776 			ret = btrfs_next_leaf(extent_root, path);
777 			if (ret < 0)
778 				goto out;
779 			if (ret)
780 				break;
781 			leaf = path->nodes[0];
782 			nritems = btrfs_header_nritems(leaf);
783 			continue;
784 		}
785 
786 		if (key.objectid < last) {
787 			key.objectid = last;
788 			key.offset = 0;
789 			key.type = BTRFS_EXTENT_ITEM_KEY;
790 			btrfs_release_path(path);
791 			goto next;
792 		}
793 
794 		if (key.objectid < block_group->start) {
795 			path->slots[0]++;
796 			continue;
797 		}
798 
799 		if (key.objectid >= block_group->start + block_group->length)
800 			break;
801 
802 		if (key.type == BTRFS_EXTENT_ITEM_KEY ||
803 		    key.type == BTRFS_METADATA_ITEM_KEY) {
804 			u64 space_added;
805 
806 			ret = btrfs_add_new_free_space(block_group, last,
807 						       key.objectid, &space_added);
808 			if (ret)
809 				goto out;
810 			total_found += space_added;
811 			if (key.type == BTRFS_METADATA_ITEM_KEY)
812 				last = key.objectid +
813 					fs_info->nodesize;
814 			else
815 				last = key.objectid + key.offset;
816 
817 			if (total_found > CACHING_CTL_WAKE_UP) {
818 				total_found = 0;
819 				if (wakeup) {
820 					atomic_inc(&caching_ctl->progress);
821 					wake_up(&caching_ctl->wait);
822 				}
823 			}
824 		}
825 		path->slots[0]++;
826 	}
827 
828 	ret = btrfs_add_new_free_space(block_group, last,
829 				       block_group->start + block_group->length,
830 				       NULL);
831 out:
832 	btrfs_free_path(path);
833 	return ret;
834 }
835 
btrfs_free_excluded_extents(const struct btrfs_block_group * bg)836 static inline void btrfs_free_excluded_extents(const struct btrfs_block_group *bg)
837 {
838 	clear_extent_bits(&bg->fs_info->excluded_extents, bg->start,
839 			  bg->start + bg->length - 1, EXTENT_UPTODATE);
840 }
841 
caching_thread(struct btrfs_work * work)842 static noinline void caching_thread(struct btrfs_work *work)
843 {
844 	struct btrfs_block_group *block_group;
845 	struct btrfs_fs_info *fs_info;
846 	struct btrfs_caching_control *caching_ctl;
847 	int ret;
848 
849 	caching_ctl = container_of(work, struct btrfs_caching_control, work);
850 	block_group = caching_ctl->block_group;
851 	fs_info = block_group->fs_info;
852 
853 	mutex_lock(&caching_ctl->mutex);
854 	down_read(&fs_info->commit_root_sem);
855 
856 	load_block_group_size_class(caching_ctl, block_group);
857 	if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
858 		ret = load_free_space_cache(block_group);
859 		if (ret == 1) {
860 			ret = 0;
861 			goto done;
862 		}
863 
864 		/*
865 		 * We failed to load the space cache, set ourselves to
866 		 * CACHE_STARTED and carry on.
867 		 */
868 		spin_lock(&block_group->lock);
869 		block_group->cached = BTRFS_CACHE_STARTED;
870 		spin_unlock(&block_group->lock);
871 		wake_up(&caching_ctl->wait);
872 	}
873 
874 	/*
875 	 * If we are in the transaction that populated the free space tree we
876 	 * can't actually cache from the free space tree as our commit root and
877 	 * real root are the same, so we could change the contents of the blocks
878 	 * while caching.  Instead do the slow caching in this case, and after
879 	 * the transaction has committed we will be safe.
880 	 */
881 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
882 	    !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
883 		ret = load_free_space_tree(caching_ctl);
884 	else
885 		ret = load_extent_tree_free(caching_ctl);
886 done:
887 	spin_lock(&block_group->lock);
888 	block_group->caching_ctl = NULL;
889 	block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
890 	spin_unlock(&block_group->lock);
891 
892 #ifdef CONFIG_BTRFS_DEBUG
893 	if (btrfs_should_fragment_free_space(block_group)) {
894 		u64 bytes_used;
895 
896 		spin_lock(&block_group->space_info->lock);
897 		spin_lock(&block_group->lock);
898 		bytes_used = block_group->length - block_group->used;
899 		block_group->space_info->bytes_used += bytes_used >> 1;
900 		spin_unlock(&block_group->lock);
901 		spin_unlock(&block_group->space_info->lock);
902 		fragment_free_space(block_group);
903 	}
904 #endif
905 
906 	up_read(&fs_info->commit_root_sem);
907 	btrfs_free_excluded_extents(block_group);
908 	mutex_unlock(&caching_ctl->mutex);
909 
910 	wake_up(&caching_ctl->wait);
911 
912 	btrfs_put_caching_control(caching_ctl);
913 	btrfs_put_block_group(block_group);
914 }
915 
btrfs_cache_block_group(struct btrfs_block_group * cache,bool wait)916 int btrfs_cache_block_group(struct btrfs_block_group *cache, bool wait)
917 {
918 	struct btrfs_fs_info *fs_info = cache->fs_info;
919 	struct btrfs_caching_control *caching_ctl = NULL;
920 	int ret = 0;
921 
922 	/* Allocator for zoned filesystems does not use the cache at all */
923 	if (btrfs_is_zoned(fs_info))
924 		return 0;
925 
926 	caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
927 	if (!caching_ctl)
928 		return -ENOMEM;
929 
930 	INIT_LIST_HEAD(&caching_ctl->list);
931 	mutex_init(&caching_ctl->mutex);
932 	init_waitqueue_head(&caching_ctl->wait);
933 	caching_ctl->block_group = cache;
934 	refcount_set(&caching_ctl->count, 2);
935 	atomic_set(&caching_ctl->progress, 0);
936 	btrfs_init_work(&caching_ctl->work, caching_thread, NULL);
937 
938 	spin_lock(&cache->lock);
939 	if (cache->cached != BTRFS_CACHE_NO) {
940 		kfree(caching_ctl);
941 
942 		caching_ctl = cache->caching_ctl;
943 		if (caching_ctl)
944 			refcount_inc(&caching_ctl->count);
945 		spin_unlock(&cache->lock);
946 		goto out;
947 	}
948 	WARN_ON(cache->caching_ctl);
949 	cache->caching_ctl = caching_ctl;
950 	cache->cached = BTRFS_CACHE_STARTED;
951 	spin_unlock(&cache->lock);
952 
953 	write_lock(&fs_info->block_group_cache_lock);
954 	refcount_inc(&caching_ctl->count);
955 	list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
956 	write_unlock(&fs_info->block_group_cache_lock);
957 
958 	btrfs_get_block_group(cache);
959 
960 	btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
961 out:
962 	if (wait && caching_ctl)
963 		ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
964 	if (caching_ctl)
965 		btrfs_put_caching_control(caching_ctl);
966 
967 	return ret;
968 }
969 
clear_avail_alloc_bits(struct btrfs_fs_info * fs_info,u64 flags)970 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
971 {
972 	u64 extra_flags = chunk_to_extended(flags) &
973 				BTRFS_EXTENDED_PROFILE_MASK;
974 
975 	write_seqlock(&fs_info->profiles_lock);
976 	if (flags & BTRFS_BLOCK_GROUP_DATA)
977 		fs_info->avail_data_alloc_bits &= ~extra_flags;
978 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
979 		fs_info->avail_metadata_alloc_bits &= ~extra_flags;
980 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
981 		fs_info->avail_system_alloc_bits &= ~extra_flags;
982 	write_sequnlock(&fs_info->profiles_lock);
983 }
984 
985 /*
986  * Clear incompat bits for the following feature(s):
987  *
988  * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
989  *            in the whole filesystem
990  *
991  * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
992  */
clear_incompat_bg_bits(struct btrfs_fs_info * fs_info,u64 flags)993 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
994 {
995 	bool found_raid56 = false;
996 	bool found_raid1c34 = false;
997 
998 	if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
999 	    (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
1000 	    (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
1001 		struct list_head *head = &fs_info->space_info;
1002 		struct btrfs_space_info *sinfo;
1003 
1004 		list_for_each_entry_rcu(sinfo, head, list) {
1005 			down_read(&sinfo->groups_sem);
1006 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
1007 				found_raid56 = true;
1008 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
1009 				found_raid56 = true;
1010 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
1011 				found_raid1c34 = true;
1012 			if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
1013 				found_raid1c34 = true;
1014 			up_read(&sinfo->groups_sem);
1015 		}
1016 		if (!found_raid56)
1017 			btrfs_clear_fs_incompat(fs_info, RAID56);
1018 		if (!found_raid1c34)
1019 			btrfs_clear_fs_incompat(fs_info, RAID1C34);
1020 	}
1021 }
1022 
btrfs_block_group_root(struct btrfs_fs_info * fs_info)1023 static struct btrfs_root *btrfs_block_group_root(struct btrfs_fs_info *fs_info)
1024 {
1025 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE))
1026 		return fs_info->block_group_root;
1027 	return btrfs_extent_root(fs_info, 0);
1028 }
1029 
remove_block_group_item(struct btrfs_trans_handle * trans,struct btrfs_path * path,struct btrfs_block_group * block_group)1030 static int remove_block_group_item(struct btrfs_trans_handle *trans,
1031 				   struct btrfs_path *path,
1032 				   struct btrfs_block_group *block_group)
1033 {
1034 	struct btrfs_fs_info *fs_info = trans->fs_info;
1035 	struct btrfs_root *root;
1036 	struct btrfs_key key;
1037 	int ret;
1038 
1039 	root = btrfs_block_group_root(fs_info);
1040 	key.objectid = block_group->start;
1041 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
1042 	key.offset = block_group->length;
1043 
1044 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1045 	if (ret > 0)
1046 		ret = -ENOENT;
1047 	if (ret < 0)
1048 		return ret;
1049 
1050 	ret = btrfs_del_item(trans, root, path);
1051 	return ret;
1052 }
1053 
btrfs_remove_block_group(struct btrfs_trans_handle * trans,struct btrfs_chunk_map * map)1054 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
1055 			     struct btrfs_chunk_map *map)
1056 {
1057 	struct btrfs_fs_info *fs_info = trans->fs_info;
1058 	struct btrfs_path *path;
1059 	struct btrfs_block_group *block_group;
1060 	struct btrfs_free_cluster *cluster;
1061 	struct inode *inode;
1062 	struct kobject *kobj = NULL;
1063 	int ret;
1064 	int index;
1065 	int factor;
1066 	struct btrfs_caching_control *caching_ctl = NULL;
1067 	bool remove_map;
1068 	bool remove_rsv = false;
1069 
1070 	block_group = btrfs_lookup_block_group(fs_info, map->start);
1071 	if (!block_group)
1072 		return -ENOENT;
1073 
1074 	BUG_ON(!block_group->ro);
1075 
1076 	trace_btrfs_remove_block_group(block_group);
1077 	/*
1078 	 * Free the reserved super bytes from this block group before
1079 	 * remove it.
1080 	 */
1081 	btrfs_free_excluded_extents(block_group);
1082 	btrfs_free_ref_tree_range(fs_info, block_group->start,
1083 				  block_group->length);
1084 
1085 	index = btrfs_bg_flags_to_raid_index(block_group->flags);
1086 	factor = btrfs_bg_type_to_factor(block_group->flags);
1087 
1088 	/* make sure this block group isn't part of an allocation cluster */
1089 	cluster = &fs_info->data_alloc_cluster;
1090 	spin_lock(&cluster->refill_lock);
1091 	btrfs_return_cluster_to_free_space(block_group, cluster);
1092 	spin_unlock(&cluster->refill_lock);
1093 
1094 	/*
1095 	 * make sure this block group isn't part of a metadata
1096 	 * allocation cluster
1097 	 */
1098 	cluster = &fs_info->meta_alloc_cluster;
1099 	spin_lock(&cluster->refill_lock);
1100 	btrfs_return_cluster_to_free_space(block_group, cluster);
1101 	spin_unlock(&cluster->refill_lock);
1102 
1103 	btrfs_clear_treelog_bg(block_group);
1104 	btrfs_clear_data_reloc_bg(block_group);
1105 
1106 	path = btrfs_alloc_path();
1107 	if (!path) {
1108 		ret = -ENOMEM;
1109 		goto out;
1110 	}
1111 
1112 	/*
1113 	 * get the inode first so any iput calls done for the io_list
1114 	 * aren't the final iput (no unlinks allowed now)
1115 	 */
1116 	inode = lookup_free_space_inode(block_group, path);
1117 
1118 	mutex_lock(&trans->transaction->cache_write_mutex);
1119 	/*
1120 	 * Make sure our free space cache IO is done before removing the
1121 	 * free space inode
1122 	 */
1123 	spin_lock(&trans->transaction->dirty_bgs_lock);
1124 	if (!list_empty(&block_group->io_list)) {
1125 		list_del_init(&block_group->io_list);
1126 
1127 		WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
1128 
1129 		spin_unlock(&trans->transaction->dirty_bgs_lock);
1130 		btrfs_wait_cache_io(trans, block_group, path);
1131 		btrfs_put_block_group(block_group);
1132 		spin_lock(&trans->transaction->dirty_bgs_lock);
1133 	}
1134 
1135 	if (!list_empty(&block_group->dirty_list)) {
1136 		list_del_init(&block_group->dirty_list);
1137 		remove_rsv = true;
1138 		btrfs_put_block_group(block_group);
1139 	}
1140 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1141 	mutex_unlock(&trans->transaction->cache_write_mutex);
1142 
1143 	ret = btrfs_remove_free_space_inode(trans, inode, block_group);
1144 	if (ret)
1145 		goto out;
1146 
1147 	write_lock(&fs_info->block_group_cache_lock);
1148 	rb_erase_cached(&block_group->cache_node,
1149 			&fs_info->block_group_cache_tree);
1150 	RB_CLEAR_NODE(&block_group->cache_node);
1151 
1152 	/* Once for the block groups rbtree */
1153 	btrfs_put_block_group(block_group);
1154 
1155 	write_unlock(&fs_info->block_group_cache_lock);
1156 
1157 	down_write(&block_group->space_info->groups_sem);
1158 	/*
1159 	 * we must use list_del_init so people can check to see if they
1160 	 * are still on the list after taking the semaphore
1161 	 */
1162 	list_del_init(&block_group->list);
1163 	if (list_empty(&block_group->space_info->block_groups[index])) {
1164 		kobj = block_group->space_info->block_group_kobjs[index];
1165 		block_group->space_info->block_group_kobjs[index] = NULL;
1166 		clear_avail_alloc_bits(fs_info, block_group->flags);
1167 	}
1168 	up_write(&block_group->space_info->groups_sem);
1169 	clear_incompat_bg_bits(fs_info, block_group->flags);
1170 	if (kobj) {
1171 		kobject_del(kobj);
1172 		kobject_put(kobj);
1173 	}
1174 
1175 	if (block_group->cached == BTRFS_CACHE_STARTED)
1176 		btrfs_wait_block_group_cache_done(block_group);
1177 
1178 	write_lock(&fs_info->block_group_cache_lock);
1179 	caching_ctl = btrfs_get_caching_control(block_group);
1180 	if (!caching_ctl) {
1181 		struct btrfs_caching_control *ctl;
1182 
1183 		list_for_each_entry(ctl, &fs_info->caching_block_groups, list) {
1184 			if (ctl->block_group == block_group) {
1185 				caching_ctl = ctl;
1186 				refcount_inc(&caching_ctl->count);
1187 				break;
1188 			}
1189 		}
1190 	}
1191 	if (caching_ctl)
1192 		list_del_init(&caching_ctl->list);
1193 	write_unlock(&fs_info->block_group_cache_lock);
1194 
1195 	if (caching_ctl) {
1196 		/* Once for the caching bgs list and once for us. */
1197 		btrfs_put_caching_control(caching_ctl);
1198 		btrfs_put_caching_control(caching_ctl);
1199 	}
1200 
1201 	spin_lock(&trans->transaction->dirty_bgs_lock);
1202 	WARN_ON(!list_empty(&block_group->dirty_list));
1203 	WARN_ON(!list_empty(&block_group->io_list));
1204 	spin_unlock(&trans->transaction->dirty_bgs_lock);
1205 
1206 	btrfs_remove_free_space_cache(block_group);
1207 
1208 	spin_lock(&block_group->space_info->lock);
1209 	list_del_init(&block_group->ro_list);
1210 
1211 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1212 		WARN_ON(block_group->space_info->total_bytes
1213 			< block_group->length);
1214 		WARN_ON(block_group->space_info->bytes_readonly
1215 			< block_group->length - block_group->zone_unusable);
1216 		WARN_ON(block_group->space_info->bytes_zone_unusable
1217 			< block_group->zone_unusable);
1218 		WARN_ON(block_group->space_info->disk_total
1219 			< block_group->length * factor);
1220 	}
1221 	block_group->space_info->total_bytes -= block_group->length;
1222 	block_group->space_info->bytes_readonly -=
1223 		(block_group->length - block_group->zone_unusable);
1224 	btrfs_space_info_update_bytes_zone_unusable(block_group->space_info,
1225 						    -block_group->zone_unusable);
1226 	block_group->space_info->disk_total -= block_group->length * factor;
1227 
1228 	spin_unlock(&block_group->space_info->lock);
1229 
1230 	/*
1231 	 * Remove the free space for the block group from the free space tree
1232 	 * and the block group's item from the extent tree before marking the
1233 	 * block group as removed. This is to prevent races with tasks that
1234 	 * freeze and unfreeze a block group, this task and another task
1235 	 * allocating a new block group - the unfreeze task ends up removing
1236 	 * the block group's extent map before the task calling this function
1237 	 * deletes the block group item from the extent tree, allowing for
1238 	 * another task to attempt to create another block group with the same
1239 	 * item key (and failing with -EEXIST and a transaction abort).
1240 	 */
1241 	ret = remove_block_group_free_space(trans, block_group);
1242 	if (ret)
1243 		goto out;
1244 
1245 	ret = remove_block_group_item(trans, path, block_group);
1246 	if (ret < 0)
1247 		goto out;
1248 
1249 	spin_lock(&block_group->lock);
1250 	set_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags);
1251 
1252 	/*
1253 	 * At this point trimming or scrub can't start on this block group,
1254 	 * because we removed the block group from the rbtree
1255 	 * fs_info->block_group_cache_tree so no one can't find it anymore and
1256 	 * even if someone already got this block group before we removed it
1257 	 * from the rbtree, they have already incremented block_group->frozen -
1258 	 * if they didn't, for the trimming case they won't find any free space
1259 	 * entries because we already removed them all when we called
1260 	 * btrfs_remove_free_space_cache().
1261 	 *
1262 	 * And we must not remove the chunk map from the fs_info->mapping_tree
1263 	 * to prevent the same logical address range and physical device space
1264 	 * ranges from being reused for a new block group. This is needed to
1265 	 * avoid races with trimming and scrub.
1266 	 *
1267 	 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1268 	 * completely transactionless, so while it is trimming a range the
1269 	 * currently running transaction might finish and a new one start,
1270 	 * allowing for new block groups to be created that can reuse the same
1271 	 * physical device locations unless we take this special care.
1272 	 *
1273 	 * There may also be an implicit trim operation if the file system
1274 	 * is mounted with -odiscard. The same protections must remain
1275 	 * in place until the extents have been discarded completely when
1276 	 * the transaction commit has completed.
1277 	 */
1278 	remove_map = (atomic_read(&block_group->frozen) == 0);
1279 	spin_unlock(&block_group->lock);
1280 
1281 	if (remove_map)
1282 		btrfs_remove_chunk_map(fs_info, map);
1283 
1284 out:
1285 	/* Once for the lookup reference */
1286 	btrfs_put_block_group(block_group);
1287 	if (remove_rsv)
1288 		btrfs_dec_delayed_refs_rsv_bg_updates(fs_info);
1289 	btrfs_free_path(path);
1290 	return ret;
1291 }
1292 
btrfs_start_trans_remove_block_group(struct btrfs_fs_info * fs_info,const u64 chunk_offset)1293 struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1294 		struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1295 {
1296 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
1297 	struct btrfs_chunk_map *map;
1298 	unsigned int num_items;
1299 
1300 	map = btrfs_find_chunk_map(fs_info, chunk_offset, 1);
1301 	ASSERT(map != NULL);
1302 	ASSERT(map->start == chunk_offset);
1303 
1304 	/*
1305 	 * We need to reserve 3 + N units from the metadata space info in order
1306 	 * to remove a block group (done at btrfs_remove_chunk() and at
1307 	 * btrfs_remove_block_group()), which are used for:
1308 	 *
1309 	 * 1 unit for adding the free space inode's orphan (located in the tree
1310 	 * of tree roots).
1311 	 * 1 unit for deleting the block group item (located in the extent
1312 	 * tree).
1313 	 * 1 unit for deleting the free space item (located in tree of tree
1314 	 * roots).
1315 	 * N units for deleting N device extent items corresponding to each
1316 	 * stripe (located in the device tree).
1317 	 *
1318 	 * In order to remove a block group we also need to reserve units in the
1319 	 * system space info in order to update the chunk tree (update one or
1320 	 * more device items and remove one chunk item), but this is done at
1321 	 * btrfs_remove_chunk() through a call to check_system_chunk().
1322 	 */
1323 	num_items = 3 + map->num_stripes;
1324 	btrfs_free_chunk_map(map);
1325 
1326 	return btrfs_start_transaction_fallback_global_rsv(root, num_items);
1327 }
1328 
1329 /*
1330  * Mark block group @cache read-only, so later write won't happen to block
1331  * group @cache.
1332  *
1333  * If @force is not set, this function will only mark the block group readonly
1334  * if we have enough free space (1M) in other metadata/system block groups.
1335  * If @force is not set, this function will mark the block group readonly
1336  * without checking free space.
1337  *
1338  * NOTE: This function doesn't care if other block groups can contain all the
1339  * data in this block group. That check should be done by relocation routine,
1340  * not this function.
1341  */
inc_block_group_ro(struct btrfs_block_group * cache,int force)1342 static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
1343 {
1344 	struct btrfs_space_info *sinfo = cache->space_info;
1345 	u64 num_bytes;
1346 	int ret = -ENOSPC;
1347 
1348 	spin_lock(&sinfo->lock);
1349 	spin_lock(&cache->lock);
1350 
1351 	if (cache->swap_extents) {
1352 		ret = -ETXTBSY;
1353 		goto out;
1354 	}
1355 
1356 	if (cache->ro) {
1357 		cache->ro++;
1358 		ret = 0;
1359 		goto out;
1360 	}
1361 
1362 	num_bytes = cache->length - cache->reserved - cache->pinned -
1363 		    cache->bytes_super - cache->zone_unusable - cache->used;
1364 
1365 	/*
1366 	 * Data never overcommits, even in mixed mode, so do just the straight
1367 	 * check of left over space in how much we have allocated.
1368 	 */
1369 	if (force) {
1370 		ret = 0;
1371 	} else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1372 		u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1373 
1374 		/*
1375 		 * Here we make sure if we mark this bg RO, we still have enough
1376 		 * free space as buffer.
1377 		 */
1378 		if (sinfo_used + num_bytes <= sinfo->total_bytes)
1379 			ret = 0;
1380 	} else {
1381 		/*
1382 		 * We overcommit metadata, so we need to do the
1383 		 * btrfs_can_overcommit check here, and we need to pass in
1384 		 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1385 		 * leeway to allow us to mark this block group as read only.
1386 		 */
1387 		if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1388 					 BTRFS_RESERVE_NO_FLUSH))
1389 			ret = 0;
1390 	}
1391 
1392 	if (!ret) {
1393 		sinfo->bytes_readonly += num_bytes;
1394 		if (btrfs_is_zoned(cache->fs_info)) {
1395 			/* Migrate zone_unusable bytes to readonly */
1396 			sinfo->bytes_readonly += cache->zone_unusable;
1397 			btrfs_space_info_update_bytes_zone_unusable(sinfo, -cache->zone_unusable);
1398 			cache->zone_unusable = 0;
1399 		}
1400 		cache->ro++;
1401 		list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
1402 	}
1403 out:
1404 	spin_unlock(&cache->lock);
1405 	spin_unlock(&sinfo->lock);
1406 	if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1407 		btrfs_info(cache->fs_info,
1408 			"unable to make block group %llu ro", cache->start);
1409 		btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1410 	}
1411 	return ret;
1412 }
1413 
clean_pinned_extents(struct btrfs_trans_handle * trans,const struct btrfs_block_group * bg)1414 static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1415 				 const struct btrfs_block_group *bg)
1416 {
1417 	struct btrfs_fs_info *fs_info = trans->fs_info;
1418 	struct btrfs_transaction *prev_trans = NULL;
1419 	const u64 start = bg->start;
1420 	const u64 end = start + bg->length - 1;
1421 	int ret;
1422 
1423 	spin_lock(&fs_info->trans_lock);
1424 	if (trans->transaction->list.prev != &fs_info->trans_list) {
1425 		prev_trans = list_last_entry(&trans->transaction->list,
1426 					     struct btrfs_transaction, list);
1427 		refcount_inc(&prev_trans->use_count);
1428 	}
1429 	spin_unlock(&fs_info->trans_lock);
1430 
1431 	/*
1432 	 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1433 	 * btrfs_finish_extent_commit(). If we are at transaction N, another
1434 	 * task might be running finish_extent_commit() for the previous
1435 	 * transaction N - 1, and have seen a range belonging to the block
1436 	 * group in pinned_extents before we were able to clear the whole block
1437 	 * group range from pinned_extents. This means that task can lookup for
1438 	 * the block group after we unpinned it from pinned_extents and removed
1439 	 * it, leading to an error at unpin_extent_range().
1440 	 */
1441 	mutex_lock(&fs_info->unused_bg_unpin_mutex);
1442 	if (prev_trans) {
1443 		ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1444 					EXTENT_DIRTY);
1445 		if (ret)
1446 			goto out;
1447 	}
1448 
1449 	ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
1450 				EXTENT_DIRTY);
1451 out:
1452 	mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1453 	if (prev_trans)
1454 		btrfs_put_transaction(prev_trans);
1455 
1456 	return ret == 0;
1457 }
1458 
1459 /*
1460  * Process the unused_bgs list and remove any that don't have any allocated
1461  * space inside of them.
1462  */
btrfs_delete_unused_bgs(struct btrfs_fs_info * fs_info)1463 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1464 {
1465 	LIST_HEAD(retry_list);
1466 	struct btrfs_block_group *block_group;
1467 	struct btrfs_space_info *space_info;
1468 	struct btrfs_trans_handle *trans;
1469 	const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1470 	int ret = 0;
1471 
1472 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1473 		return;
1474 
1475 	if (btrfs_fs_closing(fs_info))
1476 		return;
1477 
1478 	/*
1479 	 * Long running balances can keep us blocked here for eternity, so
1480 	 * simply skip deletion if we're unable to get the mutex.
1481 	 */
1482 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
1483 		return;
1484 
1485 	spin_lock(&fs_info->unused_bgs_lock);
1486 	while (!list_empty(&fs_info->unused_bgs)) {
1487 		u64 used;
1488 		int trimming;
1489 
1490 		block_group = list_first_entry(&fs_info->unused_bgs,
1491 					       struct btrfs_block_group,
1492 					       bg_list);
1493 		list_del_init(&block_group->bg_list);
1494 
1495 		space_info = block_group->space_info;
1496 
1497 		if (ret || btrfs_mixed_space_info(space_info)) {
1498 			btrfs_put_block_group(block_group);
1499 			continue;
1500 		}
1501 		spin_unlock(&fs_info->unused_bgs_lock);
1502 
1503 		btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1504 
1505 		/* Don't want to race with allocators so take the groups_sem */
1506 		down_write(&space_info->groups_sem);
1507 
1508 		/*
1509 		 * Async discard moves the final block group discard to be prior
1510 		 * to the unused_bgs code path.  Therefore, if it's not fully
1511 		 * trimmed, punt it back to the async discard lists.
1512 		 */
1513 		if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1514 		    !btrfs_is_free_space_trimmed(block_group)) {
1515 			trace_btrfs_skip_unused_block_group(block_group);
1516 			up_write(&space_info->groups_sem);
1517 			/* Requeue if we failed because of async discard */
1518 			btrfs_discard_queue_work(&fs_info->discard_ctl,
1519 						 block_group);
1520 			goto next;
1521 		}
1522 
1523 		spin_lock(&space_info->lock);
1524 		spin_lock(&block_group->lock);
1525 		if (btrfs_is_block_group_used(block_group) || block_group->ro ||
1526 		    list_is_singular(&block_group->list)) {
1527 			/*
1528 			 * We want to bail if we made new allocations or have
1529 			 * outstanding allocations in this block group.  We do
1530 			 * the ro check in case balance is currently acting on
1531 			 * this block group.
1532 			 *
1533 			 * Also bail out if this is the only block group for its
1534 			 * type, because otherwise we would lose profile
1535 			 * information from fs_info->avail_*_alloc_bits and the
1536 			 * next block group of this type would be created with a
1537 			 * "single" profile (even if we're in a raid fs) because
1538 			 * fs_info->avail_*_alloc_bits would be 0.
1539 			 */
1540 			trace_btrfs_skip_unused_block_group(block_group);
1541 			spin_unlock(&block_group->lock);
1542 			spin_unlock(&space_info->lock);
1543 			up_write(&space_info->groups_sem);
1544 			goto next;
1545 		}
1546 
1547 		/*
1548 		 * The block group may be unused but there may be space reserved
1549 		 * accounting with the existence of that block group, that is,
1550 		 * space_info->bytes_may_use was incremented by a task but no
1551 		 * space was yet allocated from the block group by the task.
1552 		 * That space may or may not be allocated, as we are generally
1553 		 * pessimistic about space reservation for metadata as well as
1554 		 * for data when using compression (as we reserve space based on
1555 		 * the worst case, when data can't be compressed, and before
1556 		 * actually attempting compression, before starting writeback).
1557 		 *
1558 		 * So check if the total space of the space_info minus the size
1559 		 * of this block group is less than the used space of the
1560 		 * space_info - if that's the case, then it means we have tasks
1561 		 * that might be relying on the block group in order to allocate
1562 		 * extents, and add back the block group to the unused list when
1563 		 * we finish, so that we retry later in case no tasks ended up
1564 		 * needing to allocate extents from the block group.
1565 		 */
1566 		used = btrfs_space_info_used(space_info, true);
1567 		if (space_info->total_bytes - block_group->length < used &&
1568 		    block_group->zone_unusable < block_group->length) {
1569 			/*
1570 			 * Add a reference for the list, compensate for the ref
1571 			 * drop under the "next" label for the
1572 			 * fs_info->unused_bgs list.
1573 			 */
1574 			btrfs_get_block_group(block_group);
1575 			list_add_tail(&block_group->bg_list, &retry_list);
1576 
1577 			trace_btrfs_skip_unused_block_group(block_group);
1578 			spin_unlock(&block_group->lock);
1579 			spin_unlock(&space_info->lock);
1580 			up_write(&space_info->groups_sem);
1581 			goto next;
1582 		}
1583 
1584 		spin_unlock(&block_group->lock);
1585 		spin_unlock(&space_info->lock);
1586 
1587 		/* We don't want to force the issue, only flip if it's ok. */
1588 		ret = inc_block_group_ro(block_group, 0);
1589 		up_write(&space_info->groups_sem);
1590 		if (ret < 0) {
1591 			ret = 0;
1592 			goto next;
1593 		}
1594 
1595 		ret = btrfs_zone_finish(block_group);
1596 		if (ret < 0) {
1597 			btrfs_dec_block_group_ro(block_group);
1598 			if (ret == -EAGAIN)
1599 				ret = 0;
1600 			goto next;
1601 		}
1602 
1603 		/*
1604 		 * Want to do this before we do anything else so we can recover
1605 		 * properly if we fail to join the transaction.
1606 		 */
1607 		trans = btrfs_start_trans_remove_block_group(fs_info,
1608 						     block_group->start);
1609 		if (IS_ERR(trans)) {
1610 			btrfs_dec_block_group_ro(block_group);
1611 			ret = PTR_ERR(trans);
1612 			goto next;
1613 		}
1614 
1615 		/*
1616 		 * We could have pending pinned extents for this block group,
1617 		 * just delete them, we don't care about them anymore.
1618 		 */
1619 		if (!clean_pinned_extents(trans, block_group)) {
1620 			btrfs_dec_block_group_ro(block_group);
1621 			goto end_trans;
1622 		}
1623 
1624 		/*
1625 		 * At this point, the block_group is read only and should fail
1626 		 * new allocations.  However, btrfs_finish_extent_commit() can
1627 		 * cause this block_group to be placed back on the discard
1628 		 * lists because now the block_group isn't fully discarded.
1629 		 * Bail here and try again later after discarding everything.
1630 		 */
1631 		spin_lock(&fs_info->discard_ctl.lock);
1632 		if (!list_empty(&block_group->discard_list)) {
1633 			spin_unlock(&fs_info->discard_ctl.lock);
1634 			btrfs_dec_block_group_ro(block_group);
1635 			btrfs_discard_queue_work(&fs_info->discard_ctl,
1636 						 block_group);
1637 			goto end_trans;
1638 		}
1639 		spin_unlock(&fs_info->discard_ctl.lock);
1640 
1641 		/* Reset pinned so btrfs_put_block_group doesn't complain */
1642 		spin_lock(&space_info->lock);
1643 		spin_lock(&block_group->lock);
1644 
1645 		btrfs_space_info_update_bytes_pinned(space_info, -block_group->pinned);
1646 		space_info->bytes_readonly += block_group->pinned;
1647 		block_group->pinned = 0;
1648 
1649 		spin_unlock(&block_group->lock);
1650 		spin_unlock(&space_info->lock);
1651 
1652 		/*
1653 		 * The normal path here is an unused block group is passed here,
1654 		 * then trimming is handled in the transaction commit path.
1655 		 * Async discard interposes before this to do the trimming
1656 		 * before coming down the unused block group path as trimming
1657 		 * will no longer be done later in the transaction commit path.
1658 		 */
1659 		if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1660 			goto flip_async;
1661 
1662 		/*
1663 		 * DISCARD can flip during remount. On zoned filesystems, we
1664 		 * need to reset sequential-required zones.
1665 		 */
1666 		trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) ||
1667 				btrfs_is_zoned(fs_info);
1668 
1669 		/* Implicit trim during transaction commit. */
1670 		if (trimming)
1671 			btrfs_freeze_block_group(block_group);
1672 
1673 		/*
1674 		 * Btrfs_remove_chunk will abort the transaction if things go
1675 		 * horribly wrong.
1676 		 */
1677 		ret = btrfs_remove_chunk(trans, block_group->start);
1678 
1679 		if (ret) {
1680 			if (trimming)
1681 				btrfs_unfreeze_block_group(block_group);
1682 			goto end_trans;
1683 		}
1684 
1685 		/*
1686 		 * If we're not mounted with -odiscard, we can just forget
1687 		 * about this block group. Otherwise we'll need to wait
1688 		 * until transaction commit to do the actual discard.
1689 		 */
1690 		if (trimming) {
1691 			spin_lock(&fs_info->unused_bgs_lock);
1692 			/*
1693 			 * A concurrent scrub might have added us to the list
1694 			 * fs_info->unused_bgs, so use a list_move operation
1695 			 * to add the block group to the deleted_bgs list.
1696 			 */
1697 			list_move(&block_group->bg_list,
1698 				  &trans->transaction->deleted_bgs);
1699 			spin_unlock(&fs_info->unused_bgs_lock);
1700 			btrfs_get_block_group(block_group);
1701 		}
1702 end_trans:
1703 		btrfs_end_transaction(trans);
1704 next:
1705 		btrfs_put_block_group(block_group);
1706 		spin_lock(&fs_info->unused_bgs_lock);
1707 	}
1708 	list_splice_tail(&retry_list, &fs_info->unused_bgs);
1709 	spin_unlock(&fs_info->unused_bgs_lock);
1710 	mutex_unlock(&fs_info->reclaim_bgs_lock);
1711 	return;
1712 
1713 flip_async:
1714 	btrfs_end_transaction(trans);
1715 	spin_lock(&fs_info->unused_bgs_lock);
1716 	list_splice_tail(&retry_list, &fs_info->unused_bgs);
1717 	spin_unlock(&fs_info->unused_bgs_lock);
1718 	mutex_unlock(&fs_info->reclaim_bgs_lock);
1719 	btrfs_put_block_group(block_group);
1720 	btrfs_discard_punt_unused_bgs_list(fs_info);
1721 }
1722 
btrfs_mark_bg_unused(struct btrfs_block_group * bg)1723 void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1724 {
1725 	struct btrfs_fs_info *fs_info = bg->fs_info;
1726 
1727 	spin_lock(&fs_info->unused_bgs_lock);
1728 	if (list_empty(&bg->bg_list)) {
1729 		btrfs_get_block_group(bg);
1730 		trace_btrfs_add_unused_block_group(bg);
1731 		list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1732 	} else if (!test_bit(BLOCK_GROUP_FLAG_NEW, &bg->runtime_flags)) {
1733 		/* Pull out the block group from the reclaim_bgs list. */
1734 		trace_btrfs_add_unused_block_group(bg);
1735 		list_move_tail(&bg->bg_list, &fs_info->unused_bgs);
1736 	}
1737 	spin_unlock(&fs_info->unused_bgs_lock);
1738 }
1739 
1740 /*
1741  * We want block groups with a low number of used bytes to be in the beginning
1742  * of the list, so they will get reclaimed first.
1743  */
reclaim_bgs_cmp(void * unused,const struct list_head * a,const struct list_head * b)1744 static int reclaim_bgs_cmp(void *unused, const struct list_head *a,
1745 			   const struct list_head *b)
1746 {
1747 	const struct btrfs_block_group *bg1, *bg2;
1748 
1749 	bg1 = list_entry(a, struct btrfs_block_group, bg_list);
1750 	bg2 = list_entry(b, struct btrfs_block_group, bg_list);
1751 
1752 	return bg1->used > bg2->used;
1753 }
1754 
btrfs_should_reclaim(const struct btrfs_fs_info * fs_info)1755 static inline bool btrfs_should_reclaim(const struct btrfs_fs_info *fs_info)
1756 {
1757 	if (btrfs_is_zoned(fs_info))
1758 		return btrfs_zoned_should_reclaim(fs_info);
1759 	return true;
1760 }
1761 
should_reclaim_block_group(const struct btrfs_block_group * bg,u64 bytes_freed)1762 static bool should_reclaim_block_group(const struct btrfs_block_group *bg, u64 bytes_freed)
1763 {
1764 	const int thresh_pct = btrfs_calc_reclaim_threshold(bg->space_info);
1765 	u64 thresh_bytes = mult_perc(bg->length, thresh_pct);
1766 	const u64 new_val = bg->used;
1767 	const u64 old_val = new_val + bytes_freed;
1768 
1769 	if (thresh_bytes == 0)
1770 		return false;
1771 
1772 	/*
1773 	 * If we were below the threshold before don't reclaim, we are likely a
1774 	 * brand new block group and we don't want to relocate new block groups.
1775 	 */
1776 	if (old_val < thresh_bytes)
1777 		return false;
1778 	if (new_val >= thresh_bytes)
1779 		return false;
1780 	return true;
1781 }
1782 
btrfs_reclaim_bgs_work(struct work_struct * work)1783 void btrfs_reclaim_bgs_work(struct work_struct *work)
1784 {
1785 	struct btrfs_fs_info *fs_info =
1786 		container_of(work, struct btrfs_fs_info, reclaim_bgs_work);
1787 	struct btrfs_block_group *bg;
1788 	struct btrfs_space_info *space_info;
1789 	LIST_HEAD(retry_list);
1790 
1791 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1792 		return;
1793 
1794 	if (btrfs_fs_closing(fs_info))
1795 		return;
1796 
1797 	if (!btrfs_should_reclaim(fs_info))
1798 		return;
1799 
1800 	sb_start_write(fs_info->sb);
1801 
1802 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
1803 		sb_end_write(fs_info->sb);
1804 		return;
1805 	}
1806 
1807 	/*
1808 	 * Long running balances can keep us blocked here for eternity, so
1809 	 * simply skip reclaim if we're unable to get the mutex.
1810 	 */
1811 	if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) {
1812 		btrfs_exclop_finish(fs_info);
1813 		sb_end_write(fs_info->sb);
1814 		return;
1815 	}
1816 
1817 	spin_lock(&fs_info->unused_bgs_lock);
1818 	/*
1819 	 * Sort happens under lock because we can't simply splice it and sort.
1820 	 * The block groups might still be in use and reachable via bg_list,
1821 	 * and their presence in the reclaim_bgs list must be preserved.
1822 	 */
1823 	list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp);
1824 	while (!list_empty(&fs_info->reclaim_bgs)) {
1825 		u64 zone_unusable;
1826 		u64 reclaimed;
1827 		int ret = 0;
1828 
1829 		bg = list_first_entry(&fs_info->reclaim_bgs,
1830 				      struct btrfs_block_group,
1831 				      bg_list);
1832 		list_del_init(&bg->bg_list);
1833 
1834 		space_info = bg->space_info;
1835 		spin_unlock(&fs_info->unused_bgs_lock);
1836 
1837 		/* Don't race with allocators so take the groups_sem */
1838 		down_write(&space_info->groups_sem);
1839 
1840 		spin_lock(&space_info->lock);
1841 		spin_lock(&bg->lock);
1842 		if (bg->reserved || bg->pinned || bg->ro) {
1843 			/*
1844 			 * We want to bail if we made new allocations or have
1845 			 * outstanding allocations in this block group.  We do
1846 			 * the ro check in case balance is currently acting on
1847 			 * this block group.
1848 			 */
1849 			spin_unlock(&bg->lock);
1850 			spin_unlock(&space_info->lock);
1851 			up_write(&space_info->groups_sem);
1852 			goto next;
1853 		}
1854 		if (bg->used == 0) {
1855 			/*
1856 			 * It is possible that we trigger relocation on a block
1857 			 * group as its extents are deleted and it first goes
1858 			 * below the threshold, then shortly after goes empty.
1859 			 *
1860 			 * In this case, relocating it does delete it, but has
1861 			 * some overhead in relocation specific metadata, looking
1862 			 * for the non-existent extents and running some extra
1863 			 * transactions, which we can avoid by using one of the
1864 			 * other mechanisms for dealing with empty block groups.
1865 			 */
1866 			if (!btrfs_test_opt(fs_info, DISCARD_ASYNC))
1867 				btrfs_mark_bg_unused(bg);
1868 			spin_unlock(&bg->lock);
1869 			spin_unlock(&space_info->lock);
1870 			up_write(&space_info->groups_sem);
1871 			goto next;
1872 
1873 		}
1874 		/*
1875 		 * The block group might no longer meet the reclaim condition by
1876 		 * the time we get around to reclaiming it, so to avoid
1877 		 * reclaiming overly full block_groups, skip reclaiming them.
1878 		 *
1879 		 * Since the decision making process also depends on the amount
1880 		 * being freed, pass in a fake giant value to skip that extra
1881 		 * check, which is more meaningful when adding to the list in
1882 		 * the first place.
1883 		 */
1884 		if (!should_reclaim_block_group(bg, bg->length)) {
1885 			spin_unlock(&bg->lock);
1886 			spin_unlock(&space_info->lock);
1887 			up_write(&space_info->groups_sem);
1888 			goto next;
1889 		}
1890 		spin_unlock(&bg->lock);
1891 		spin_unlock(&space_info->lock);
1892 
1893 		/*
1894 		 * Get out fast, in case we're read-only or unmounting the
1895 		 * filesystem. It is OK to drop block groups from the list even
1896 		 * for the read-only case. As we did sb_start_write(),
1897 		 * "mount -o remount,ro" won't happen and read-only filesystem
1898 		 * means it is forced read-only due to a fatal error. So, it
1899 		 * never gets back to read-write to let us reclaim again.
1900 		 */
1901 		if (btrfs_need_cleaner_sleep(fs_info)) {
1902 			up_write(&space_info->groups_sem);
1903 			goto next;
1904 		}
1905 
1906 		/*
1907 		 * Cache the zone_unusable value before turning the block group
1908 		 * to read only. As soon as the blog group is read only it's
1909 		 * zone_unusable value gets moved to the block group's read-only
1910 		 * bytes and isn't available for calculations anymore.
1911 		 */
1912 		zone_unusable = bg->zone_unusable;
1913 		ret = inc_block_group_ro(bg, 0);
1914 		up_write(&space_info->groups_sem);
1915 		if (ret < 0)
1916 			goto next;
1917 
1918 		btrfs_info(fs_info,
1919 			"reclaiming chunk %llu with %llu%% used %llu%% unusable",
1920 				bg->start,
1921 				div64_u64(bg->used * 100, bg->length),
1922 				div64_u64(zone_unusable * 100, bg->length));
1923 		trace_btrfs_reclaim_block_group(bg);
1924 		reclaimed = bg->used;
1925 		ret = btrfs_relocate_chunk(fs_info, bg->start);
1926 		if (ret) {
1927 			btrfs_dec_block_group_ro(bg);
1928 			btrfs_err(fs_info, "error relocating chunk %llu",
1929 				  bg->start);
1930 			reclaimed = 0;
1931 			spin_lock(&space_info->lock);
1932 			space_info->reclaim_errors++;
1933 			if (READ_ONCE(space_info->periodic_reclaim))
1934 				space_info->periodic_reclaim_ready = false;
1935 			spin_unlock(&space_info->lock);
1936 		}
1937 		spin_lock(&space_info->lock);
1938 		space_info->reclaim_count++;
1939 		space_info->reclaim_bytes += reclaimed;
1940 		spin_unlock(&space_info->lock);
1941 
1942 next:
1943 		if (ret && !READ_ONCE(space_info->periodic_reclaim)) {
1944 			/* Refcount held by the reclaim_bgs list after splice. */
1945 			spin_lock(&fs_info->unused_bgs_lock);
1946 			/*
1947 			 * This block group might be added to the unused list
1948 			 * during the above process. Move it back to the
1949 			 * reclaim list otherwise.
1950 			 */
1951 			if (list_empty(&bg->bg_list)) {
1952 				btrfs_get_block_group(bg);
1953 				list_add_tail(&bg->bg_list, &retry_list);
1954 			}
1955 			spin_unlock(&fs_info->unused_bgs_lock);
1956 		}
1957 		btrfs_put_block_group(bg);
1958 
1959 		mutex_unlock(&fs_info->reclaim_bgs_lock);
1960 		/*
1961 		 * Reclaiming all the block groups in the list can take really
1962 		 * long.  Prioritize cleaning up unused block groups.
1963 		 */
1964 		btrfs_delete_unused_bgs(fs_info);
1965 		/*
1966 		 * If we are interrupted by a balance, we can just bail out. The
1967 		 * cleaner thread restart again if necessary.
1968 		 */
1969 		if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
1970 			goto end;
1971 		spin_lock(&fs_info->unused_bgs_lock);
1972 	}
1973 	spin_unlock(&fs_info->unused_bgs_lock);
1974 	mutex_unlock(&fs_info->reclaim_bgs_lock);
1975 end:
1976 	spin_lock(&fs_info->unused_bgs_lock);
1977 	list_splice_tail(&retry_list, &fs_info->reclaim_bgs);
1978 	spin_unlock(&fs_info->unused_bgs_lock);
1979 	btrfs_exclop_finish(fs_info);
1980 	sb_end_write(fs_info->sb);
1981 }
1982 
btrfs_reclaim_bgs(struct btrfs_fs_info * fs_info)1983 void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
1984 {
1985 	btrfs_reclaim_sweep(fs_info);
1986 	spin_lock(&fs_info->unused_bgs_lock);
1987 	if (!list_empty(&fs_info->reclaim_bgs))
1988 		queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
1989 	spin_unlock(&fs_info->unused_bgs_lock);
1990 }
1991 
btrfs_mark_bg_to_reclaim(struct btrfs_block_group * bg)1992 void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
1993 {
1994 	struct btrfs_fs_info *fs_info = bg->fs_info;
1995 
1996 	spin_lock(&fs_info->unused_bgs_lock);
1997 	if (list_empty(&bg->bg_list)) {
1998 		btrfs_get_block_group(bg);
1999 		trace_btrfs_add_reclaim_block_group(bg);
2000 		list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
2001 	}
2002 	spin_unlock(&fs_info->unused_bgs_lock);
2003 }
2004 
read_bg_from_eb(struct btrfs_fs_info * fs_info,const struct btrfs_key * key,const struct btrfs_path * path)2005 static int read_bg_from_eb(struct btrfs_fs_info *fs_info, const struct btrfs_key *key,
2006 			   const struct btrfs_path *path)
2007 {
2008 	struct btrfs_chunk_map *map;
2009 	struct btrfs_block_group_item bg;
2010 	struct extent_buffer *leaf;
2011 	int slot;
2012 	u64 flags;
2013 	int ret = 0;
2014 
2015 	slot = path->slots[0];
2016 	leaf = path->nodes[0];
2017 
2018 	map = btrfs_find_chunk_map(fs_info, key->objectid, key->offset);
2019 	if (!map) {
2020 		btrfs_err(fs_info,
2021 			  "logical %llu len %llu found bg but no related chunk",
2022 			  key->objectid, key->offset);
2023 		return -ENOENT;
2024 	}
2025 
2026 	if (map->start != key->objectid || map->chunk_len != key->offset) {
2027 		btrfs_err(fs_info,
2028 			"block group %llu len %llu mismatch with chunk %llu len %llu",
2029 			  key->objectid, key->offset, map->start, map->chunk_len);
2030 		ret = -EUCLEAN;
2031 		goto out_free_map;
2032 	}
2033 
2034 	read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
2035 			   sizeof(bg));
2036 	flags = btrfs_stack_block_group_flags(&bg) &
2037 		BTRFS_BLOCK_GROUP_TYPE_MASK;
2038 
2039 	if (flags != (map->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
2040 		btrfs_err(fs_info,
2041 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
2042 			  key->objectid, key->offset, flags,
2043 			  (BTRFS_BLOCK_GROUP_TYPE_MASK & map->type));
2044 		ret = -EUCLEAN;
2045 	}
2046 
2047 out_free_map:
2048 	btrfs_free_chunk_map(map);
2049 	return ret;
2050 }
2051 
find_first_block_group(struct btrfs_fs_info * fs_info,struct btrfs_path * path,const struct btrfs_key * key)2052 static int find_first_block_group(struct btrfs_fs_info *fs_info,
2053 				  struct btrfs_path *path,
2054 				  const struct btrfs_key *key)
2055 {
2056 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
2057 	int ret;
2058 	struct btrfs_key found_key;
2059 
2060 	btrfs_for_each_slot(root, key, &found_key, path, ret) {
2061 		if (found_key.objectid >= key->objectid &&
2062 		    found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
2063 			return read_bg_from_eb(fs_info, &found_key, path);
2064 		}
2065 	}
2066 	return ret;
2067 }
2068 
set_avail_alloc_bits(struct btrfs_fs_info * fs_info,u64 flags)2069 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
2070 {
2071 	u64 extra_flags = chunk_to_extended(flags) &
2072 				BTRFS_EXTENDED_PROFILE_MASK;
2073 
2074 	write_seqlock(&fs_info->profiles_lock);
2075 	if (flags & BTRFS_BLOCK_GROUP_DATA)
2076 		fs_info->avail_data_alloc_bits |= extra_flags;
2077 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
2078 		fs_info->avail_metadata_alloc_bits |= extra_flags;
2079 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
2080 		fs_info->avail_system_alloc_bits |= extra_flags;
2081 	write_sequnlock(&fs_info->profiles_lock);
2082 }
2083 
2084 /*
2085  * Map a physical disk address to a list of logical addresses.
2086  *
2087  * @fs_info:       the filesystem
2088  * @chunk_start:   logical address of block group
2089  * @physical:	   physical address to map to logical addresses
2090  * @logical:	   return array of logical addresses which map to @physical
2091  * @naddrs:	   length of @logical
2092  * @stripe_len:    size of IO stripe for the given block group
2093  *
2094  * Maps a particular @physical disk address to a list of @logical addresses.
2095  * Used primarily to exclude those portions of a block group that contain super
2096  * block copies.
2097  */
btrfs_rmap_block(struct btrfs_fs_info * fs_info,u64 chunk_start,u64 physical,u64 ** logical,int * naddrs,int * stripe_len)2098 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
2099 		     u64 physical, u64 **logical, int *naddrs, int *stripe_len)
2100 {
2101 	struct btrfs_chunk_map *map;
2102 	u64 *buf;
2103 	u64 bytenr;
2104 	u64 data_stripe_length;
2105 	u64 io_stripe_size;
2106 	int i, nr = 0;
2107 	int ret = 0;
2108 
2109 	map = btrfs_get_chunk_map(fs_info, chunk_start, 1);
2110 	if (IS_ERR(map))
2111 		return -EIO;
2112 
2113 	data_stripe_length = map->stripe_size;
2114 	io_stripe_size = BTRFS_STRIPE_LEN;
2115 	chunk_start = map->start;
2116 
2117 	/* For RAID5/6 adjust to a full IO stripe length */
2118 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
2119 		io_stripe_size = btrfs_stripe_nr_to_offset(nr_data_stripes(map));
2120 
2121 	buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
2122 	if (!buf) {
2123 		ret = -ENOMEM;
2124 		goto out;
2125 	}
2126 
2127 	for (i = 0; i < map->num_stripes; i++) {
2128 		bool already_inserted = false;
2129 		u32 stripe_nr;
2130 		u32 offset;
2131 		int j;
2132 
2133 		if (!in_range(physical, map->stripes[i].physical,
2134 			      data_stripe_length))
2135 			continue;
2136 
2137 		stripe_nr = (physical - map->stripes[i].physical) >>
2138 			    BTRFS_STRIPE_LEN_SHIFT;
2139 		offset = (physical - map->stripes[i].physical) &
2140 			 BTRFS_STRIPE_LEN_MASK;
2141 
2142 		if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
2143 				 BTRFS_BLOCK_GROUP_RAID10))
2144 			stripe_nr = div_u64(stripe_nr * map->num_stripes + i,
2145 					    map->sub_stripes);
2146 		/*
2147 		 * The remaining case would be for RAID56, multiply by
2148 		 * nr_data_stripes().  Alternatively, just use rmap_len below
2149 		 * instead of map->stripe_len
2150 		 */
2151 		bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
2152 
2153 		/* Ensure we don't add duplicate addresses */
2154 		for (j = 0; j < nr; j++) {
2155 			if (buf[j] == bytenr) {
2156 				already_inserted = true;
2157 				break;
2158 			}
2159 		}
2160 
2161 		if (!already_inserted)
2162 			buf[nr++] = bytenr;
2163 	}
2164 
2165 	*logical = buf;
2166 	*naddrs = nr;
2167 	*stripe_len = io_stripe_size;
2168 out:
2169 	btrfs_free_chunk_map(map);
2170 	return ret;
2171 }
2172 
exclude_super_stripes(struct btrfs_block_group * cache)2173 static int exclude_super_stripes(struct btrfs_block_group *cache)
2174 {
2175 	struct btrfs_fs_info *fs_info = cache->fs_info;
2176 	const bool zoned = btrfs_is_zoned(fs_info);
2177 	u64 bytenr;
2178 	u64 *logical;
2179 	int stripe_len;
2180 	int i, nr, ret;
2181 
2182 	if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
2183 		stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
2184 		cache->bytes_super += stripe_len;
2185 		ret = set_extent_bit(&fs_info->excluded_extents, cache->start,
2186 				     cache->start + stripe_len - 1,
2187 				     EXTENT_UPTODATE, NULL);
2188 		if (ret)
2189 			return ret;
2190 	}
2191 
2192 	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2193 		bytenr = btrfs_sb_offset(i);
2194 		ret = btrfs_rmap_block(fs_info, cache->start,
2195 				       bytenr, &logical, &nr, &stripe_len);
2196 		if (ret)
2197 			return ret;
2198 
2199 		/* Shouldn't have super stripes in sequential zones */
2200 		if (zoned && nr) {
2201 			kfree(logical);
2202 			btrfs_err(fs_info,
2203 			"zoned: block group %llu must not contain super block",
2204 				  cache->start);
2205 			return -EUCLEAN;
2206 		}
2207 
2208 		while (nr--) {
2209 			u64 len = min_t(u64, stripe_len,
2210 				cache->start + cache->length - logical[nr]);
2211 
2212 			cache->bytes_super += len;
2213 			ret = set_extent_bit(&fs_info->excluded_extents, logical[nr],
2214 					     logical[nr] + len - 1,
2215 					     EXTENT_UPTODATE, NULL);
2216 			if (ret) {
2217 				kfree(logical);
2218 				return ret;
2219 			}
2220 		}
2221 
2222 		kfree(logical);
2223 	}
2224 	return 0;
2225 }
2226 
btrfs_create_block_group_cache(struct btrfs_fs_info * fs_info,u64 start)2227 static struct btrfs_block_group *btrfs_create_block_group_cache(
2228 		struct btrfs_fs_info *fs_info, u64 start)
2229 {
2230 	struct btrfs_block_group *cache;
2231 
2232 	cache = kzalloc(sizeof(*cache), GFP_NOFS);
2233 	if (!cache)
2234 		return NULL;
2235 
2236 	cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
2237 					GFP_NOFS);
2238 	if (!cache->free_space_ctl) {
2239 		kfree(cache);
2240 		return NULL;
2241 	}
2242 
2243 	cache->start = start;
2244 
2245 	cache->fs_info = fs_info;
2246 	cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
2247 
2248 	cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
2249 
2250 	refcount_set(&cache->refs, 1);
2251 	spin_lock_init(&cache->lock);
2252 	init_rwsem(&cache->data_rwsem);
2253 	INIT_LIST_HEAD(&cache->list);
2254 	INIT_LIST_HEAD(&cache->cluster_list);
2255 	INIT_LIST_HEAD(&cache->bg_list);
2256 	INIT_LIST_HEAD(&cache->ro_list);
2257 	INIT_LIST_HEAD(&cache->discard_list);
2258 	INIT_LIST_HEAD(&cache->dirty_list);
2259 	INIT_LIST_HEAD(&cache->io_list);
2260 	INIT_LIST_HEAD(&cache->active_bg_list);
2261 	btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
2262 	atomic_set(&cache->frozen, 0);
2263 	mutex_init(&cache->free_space_lock);
2264 
2265 	return cache;
2266 }
2267 
2268 /*
2269  * Iterate all chunks and verify that each of them has the corresponding block
2270  * group
2271  */
check_chunk_block_group_mappings(struct btrfs_fs_info * fs_info)2272 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
2273 {
2274 	u64 start = 0;
2275 	int ret = 0;
2276 
2277 	while (1) {
2278 		struct btrfs_chunk_map *map;
2279 		struct btrfs_block_group *bg;
2280 
2281 		/*
2282 		 * btrfs_find_chunk_map() will return the first chunk map
2283 		 * intersecting the range, so setting @length to 1 is enough to
2284 		 * get the first chunk.
2285 		 */
2286 		map = btrfs_find_chunk_map(fs_info, start, 1);
2287 		if (!map)
2288 			break;
2289 
2290 		bg = btrfs_lookup_block_group(fs_info, map->start);
2291 		if (!bg) {
2292 			btrfs_err(fs_info,
2293 	"chunk start=%llu len=%llu doesn't have corresponding block group",
2294 				     map->start, map->chunk_len);
2295 			ret = -EUCLEAN;
2296 			btrfs_free_chunk_map(map);
2297 			break;
2298 		}
2299 		if (bg->start != map->start || bg->length != map->chunk_len ||
2300 		    (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
2301 		    (map->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
2302 			btrfs_err(fs_info,
2303 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
2304 				map->start, map->chunk_len,
2305 				map->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
2306 				bg->start, bg->length,
2307 				bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
2308 			ret = -EUCLEAN;
2309 			btrfs_free_chunk_map(map);
2310 			btrfs_put_block_group(bg);
2311 			break;
2312 		}
2313 		start = map->start + map->chunk_len;
2314 		btrfs_free_chunk_map(map);
2315 		btrfs_put_block_group(bg);
2316 	}
2317 	return ret;
2318 }
2319 
read_one_block_group(struct btrfs_fs_info * info,struct btrfs_block_group_item * bgi,const struct btrfs_key * key,int need_clear)2320 static int read_one_block_group(struct btrfs_fs_info *info,
2321 				struct btrfs_block_group_item *bgi,
2322 				const struct btrfs_key *key,
2323 				int need_clear)
2324 {
2325 	struct btrfs_block_group *cache;
2326 	const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
2327 	int ret;
2328 
2329 	ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
2330 
2331 	cache = btrfs_create_block_group_cache(info, key->objectid);
2332 	if (!cache)
2333 		return -ENOMEM;
2334 
2335 	cache->length = key->offset;
2336 	cache->used = btrfs_stack_block_group_used(bgi);
2337 	cache->commit_used = cache->used;
2338 	cache->flags = btrfs_stack_block_group_flags(bgi);
2339 	cache->global_root_id = btrfs_stack_block_group_chunk_objectid(bgi);
2340 
2341 	set_free_space_tree_thresholds(cache);
2342 
2343 	if (need_clear) {
2344 		/*
2345 		 * When we mount with old space cache, we need to
2346 		 * set BTRFS_DC_CLEAR and set dirty flag.
2347 		 *
2348 		 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
2349 		 *    truncate the old free space cache inode and
2350 		 *    setup a new one.
2351 		 * b) Setting 'dirty flag' makes sure that we flush
2352 		 *    the new space cache info onto disk.
2353 		 */
2354 		if (btrfs_test_opt(info, SPACE_CACHE))
2355 			cache->disk_cache_state = BTRFS_DC_CLEAR;
2356 	}
2357 	if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
2358 	    (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
2359 			btrfs_err(info,
2360 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2361 				  cache->start);
2362 			ret = -EINVAL;
2363 			goto error;
2364 	}
2365 
2366 	ret = btrfs_load_block_group_zone_info(cache, false);
2367 	if (ret) {
2368 		btrfs_err(info, "zoned: failed to load zone info of bg %llu",
2369 			  cache->start);
2370 		goto error;
2371 	}
2372 
2373 	/*
2374 	 * We need to exclude the super stripes now so that the space info has
2375 	 * super bytes accounted for, otherwise we'll think we have more space
2376 	 * than we actually do.
2377 	 */
2378 	ret = exclude_super_stripes(cache);
2379 	if (ret) {
2380 		/* We may have excluded something, so call this just in case. */
2381 		btrfs_free_excluded_extents(cache);
2382 		goto error;
2383 	}
2384 
2385 	/*
2386 	 * For zoned filesystem, space after the allocation offset is the only
2387 	 * free space for a block group. So, we don't need any caching work.
2388 	 * btrfs_calc_zone_unusable() will set the amount of free space and
2389 	 * zone_unusable space.
2390 	 *
2391 	 * For regular filesystem, check for two cases, either we are full, and
2392 	 * therefore don't need to bother with the caching work since we won't
2393 	 * find any space, or we are empty, and we can just add all the space
2394 	 * in and be done with it.  This saves us _a_lot_ of time, particularly
2395 	 * in the full case.
2396 	 */
2397 	if (btrfs_is_zoned(info)) {
2398 		btrfs_calc_zone_unusable(cache);
2399 		/* Should not have any excluded extents. Just in case, though. */
2400 		btrfs_free_excluded_extents(cache);
2401 	} else if (cache->length == cache->used) {
2402 		cache->cached = BTRFS_CACHE_FINISHED;
2403 		btrfs_free_excluded_extents(cache);
2404 	} else if (cache->used == 0) {
2405 		cache->cached = BTRFS_CACHE_FINISHED;
2406 		ret = btrfs_add_new_free_space(cache, cache->start,
2407 					       cache->start + cache->length, NULL);
2408 		btrfs_free_excluded_extents(cache);
2409 		if (ret)
2410 			goto error;
2411 	}
2412 
2413 	ret = btrfs_add_block_group_cache(info, cache);
2414 	if (ret) {
2415 		btrfs_remove_free_space_cache(cache);
2416 		goto error;
2417 	}
2418 	trace_btrfs_add_block_group(info, cache, 0);
2419 	btrfs_add_bg_to_space_info(info, cache);
2420 
2421 	set_avail_alloc_bits(info, cache->flags);
2422 	if (btrfs_chunk_writeable(info, cache->start)) {
2423 		if (cache->used == 0) {
2424 			ASSERT(list_empty(&cache->bg_list));
2425 			if (btrfs_test_opt(info, DISCARD_ASYNC))
2426 				btrfs_discard_queue_work(&info->discard_ctl, cache);
2427 			else
2428 				btrfs_mark_bg_unused(cache);
2429 		}
2430 	} else {
2431 		inc_block_group_ro(cache, 1);
2432 	}
2433 
2434 	return 0;
2435 error:
2436 	btrfs_put_block_group(cache);
2437 	return ret;
2438 }
2439 
fill_dummy_bgs(struct btrfs_fs_info * fs_info)2440 static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
2441 {
2442 	struct rb_node *node;
2443 	int ret = 0;
2444 
2445 	for (node = rb_first_cached(&fs_info->mapping_tree); node; node = rb_next(node)) {
2446 		struct btrfs_chunk_map *map;
2447 		struct btrfs_block_group *bg;
2448 
2449 		map = rb_entry(node, struct btrfs_chunk_map, rb_node);
2450 		bg = btrfs_create_block_group_cache(fs_info, map->start);
2451 		if (!bg) {
2452 			ret = -ENOMEM;
2453 			break;
2454 		}
2455 
2456 		/* Fill dummy cache as FULL */
2457 		bg->length = map->chunk_len;
2458 		bg->flags = map->type;
2459 		bg->cached = BTRFS_CACHE_FINISHED;
2460 		bg->used = map->chunk_len;
2461 		bg->flags = map->type;
2462 		ret = btrfs_add_block_group_cache(fs_info, bg);
2463 		/*
2464 		 * We may have some valid block group cache added already, in
2465 		 * that case we skip to the next one.
2466 		 */
2467 		if (ret == -EEXIST) {
2468 			ret = 0;
2469 			btrfs_put_block_group(bg);
2470 			continue;
2471 		}
2472 
2473 		if (ret) {
2474 			btrfs_remove_free_space_cache(bg);
2475 			btrfs_put_block_group(bg);
2476 			break;
2477 		}
2478 
2479 		btrfs_add_bg_to_space_info(fs_info, bg);
2480 
2481 		set_avail_alloc_bits(fs_info, bg->flags);
2482 	}
2483 	if (!ret)
2484 		btrfs_init_global_block_rsv(fs_info);
2485 	return ret;
2486 }
2487 
btrfs_read_block_groups(struct btrfs_fs_info * info)2488 int btrfs_read_block_groups(struct btrfs_fs_info *info)
2489 {
2490 	struct btrfs_root *root = btrfs_block_group_root(info);
2491 	struct btrfs_path *path;
2492 	int ret;
2493 	struct btrfs_block_group *cache;
2494 	struct btrfs_space_info *space_info;
2495 	struct btrfs_key key;
2496 	int need_clear = 0;
2497 	u64 cache_gen;
2498 
2499 	/*
2500 	 * Either no extent root (with ibadroots rescue option) or we have
2501 	 * unsupported RO options. The fs can never be mounted read-write, so no
2502 	 * need to waste time searching block group items.
2503 	 *
2504 	 * This also allows new extent tree related changes to be RO compat,
2505 	 * no need for a full incompat flag.
2506 	 */
2507 	if (!root || (btrfs_super_compat_ro_flags(info->super_copy) &
2508 		      ~BTRFS_FEATURE_COMPAT_RO_SUPP))
2509 		return fill_dummy_bgs(info);
2510 
2511 	key.objectid = 0;
2512 	key.offset = 0;
2513 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2514 	path = btrfs_alloc_path();
2515 	if (!path)
2516 		return -ENOMEM;
2517 
2518 	cache_gen = btrfs_super_cache_generation(info->super_copy);
2519 	if (btrfs_test_opt(info, SPACE_CACHE) &&
2520 	    btrfs_super_generation(info->super_copy) != cache_gen)
2521 		need_clear = 1;
2522 	if (btrfs_test_opt(info, CLEAR_CACHE))
2523 		need_clear = 1;
2524 
2525 	while (1) {
2526 		struct btrfs_block_group_item bgi;
2527 		struct extent_buffer *leaf;
2528 		int slot;
2529 
2530 		ret = find_first_block_group(info, path, &key);
2531 		if (ret > 0)
2532 			break;
2533 		if (ret != 0)
2534 			goto error;
2535 
2536 		leaf = path->nodes[0];
2537 		slot = path->slots[0];
2538 
2539 		read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
2540 				   sizeof(bgi));
2541 
2542 		btrfs_item_key_to_cpu(leaf, &key, slot);
2543 		btrfs_release_path(path);
2544 		ret = read_one_block_group(info, &bgi, &key, need_clear);
2545 		if (ret < 0)
2546 			goto error;
2547 		key.objectid += key.offset;
2548 		key.offset = 0;
2549 	}
2550 	btrfs_release_path(path);
2551 
2552 	list_for_each_entry(space_info, &info->space_info, list) {
2553 		int i;
2554 
2555 		for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2556 			if (list_empty(&space_info->block_groups[i]))
2557 				continue;
2558 			cache = list_first_entry(&space_info->block_groups[i],
2559 						 struct btrfs_block_group,
2560 						 list);
2561 			btrfs_sysfs_add_block_group_type(cache);
2562 		}
2563 
2564 		if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2565 		      (BTRFS_BLOCK_GROUP_RAID10 |
2566 		       BTRFS_BLOCK_GROUP_RAID1_MASK |
2567 		       BTRFS_BLOCK_GROUP_RAID56_MASK |
2568 		       BTRFS_BLOCK_GROUP_DUP)))
2569 			continue;
2570 		/*
2571 		 * Avoid allocating from un-mirrored block group if there are
2572 		 * mirrored block groups.
2573 		 */
2574 		list_for_each_entry(cache,
2575 				&space_info->block_groups[BTRFS_RAID_RAID0],
2576 				list)
2577 			inc_block_group_ro(cache, 1);
2578 		list_for_each_entry(cache,
2579 				&space_info->block_groups[BTRFS_RAID_SINGLE],
2580 				list)
2581 			inc_block_group_ro(cache, 1);
2582 	}
2583 
2584 	btrfs_init_global_block_rsv(info);
2585 	ret = check_chunk_block_group_mappings(info);
2586 error:
2587 	btrfs_free_path(path);
2588 	/*
2589 	 * We've hit some error while reading the extent tree, and have
2590 	 * rescue=ibadroots mount option.
2591 	 * Try to fill the tree using dummy block groups so that the user can
2592 	 * continue to mount and grab their data.
2593 	 */
2594 	if (ret && btrfs_test_opt(info, IGNOREBADROOTS))
2595 		ret = fill_dummy_bgs(info);
2596 	return ret;
2597 }
2598 
2599 /*
2600  * This function, insert_block_group_item(), belongs to the phase 2 of chunk
2601  * allocation.
2602  *
2603  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2604  * phases.
2605  */
insert_block_group_item(struct btrfs_trans_handle * trans,struct btrfs_block_group * block_group)2606 static int insert_block_group_item(struct btrfs_trans_handle *trans,
2607 				   struct btrfs_block_group *block_group)
2608 {
2609 	struct btrfs_fs_info *fs_info = trans->fs_info;
2610 	struct btrfs_block_group_item bgi;
2611 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
2612 	struct btrfs_key key;
2613 	u64 old_commit_used;
2614 	int ret;
2615 
2616 	spin_lock(&block_group->lock);
2617 	btrfs_set_stack_block_group_used(&bgi, block_group->used);
2618 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
2619 						   block_group->global_root_id);
2620 	btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2621 	old_commit_used = block_group->commit_used;
2622 	block_group->commit_used = block_group->used;
2623 	key.objectid = block_group->start;
2624 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2625 	key.offset = block_group->length;
2626 	spin_unlock(&block_group->lock);
2627 
2628 	ret = btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2629 	if (ret < 0) {
2630 		spin_lock(&block_group->lock);
2631 		block_group->commit_used = old_commit_used;
2632 		spin_unlock(&block_group->lock);
2633 	}
2634 
2635 	return ret;
2636 }
2637 
insert_dev_extent(struct btrfs_trans_handle * trans,const struct btrfs_device * device,u64 chunk_offset,u64 start,u64 num_bytes)2638 static int insert_dev_extent(struct btrfs_trans_handle *trans,
2639 			     const struct btrfs_device *device, u64 chunk_offset,
2640 			     u64 start, u64 num_bytes)
2641 {
2642 	struct btrfs_fs_info *fs_info = device->fs_info;
2643 	struct btrfs_root *root = fs_info->dev_root;
2644 	struct btrfs_path *path;
2645 	struct btrfs_dev_extent *extent;
2646 	struct extent_buffer *leaf;
2647 	struct btrfs_key key;
2648 	int ret;
2649 
2650 	WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
2651 	WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
2652 	path = btrfs_alloc_path();
2653 	if (!path)
2654 		return -ENOMEM;
2655 
2656 	key.objectid = device->devid;
2657 	key.type = BTRFS_DEV_EXTENT_KEY;
2658 	key.offset = start;
2659 	ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent));
2660 	if (ret)
2661 		goto out;
2662 
2663 	leaf = path->nodes[0];
2664 	extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
2665 	btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID);
2666 	btrfs_set_dev_extent_chunk_objectid(leaf, extent,
2667 					    BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2668 	btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
2669 
2670 	btrfs_set_dev_extent_length(leaf, extent, num_bytes);
2671 out:
2672 	btrfs_free_path(path);
2673 	return ret;
2674 }
2675 
2676 /*
2677  * This function belongs to phase 2.
2678  *
2679  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2680  * phases.
2681  */
insert_dev_extents(struct btrfs_trans_handle * trans,u64 chunk_offset,u64 chunk_size)2682 static int insert_dev_extents(struct btrfs_trans_handle *trans,
2683 				   u64 chunk_offset, u64 chunk_size)
2684 {
2685 	struct btrfs_fs_info *fs_info = trans->fs_info;
2686 	struct btrfs_device *device;
2687 	struct btrfs_chunk_map *map;
2688 	u64 dev_offset;
2689 	int i;
2690 	int ret = 0;
2691 
2692 	map = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
2693 	if (IS_ERR(map))
2694 		return PTR_ERR(map);
2695 
2696 	/*
2697 	 * Take the device list mutex to prevent races with the final phase of
2698 	 * a device replace operation that replaces the device object associated
2699 	 * with the map's stripes, because the device object's id can change
2700 	 * at any time during that final phase of the device replace operation
2701 	 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
2702 	 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
2703 	 * resulting in persisting a device extent item with such ID.
2704 	 */
2705 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
2706 	for (i = 0; i < map->num_stripes; i++) {
2707 		device = map->stripes[i].dev;
2708 		dev_offset = map->stripes[i].physical;
2709 
2710 		ret = insert_dev_extent(trans, device, chunk_offset, dev_offset,
2711 					map->stripe_size);
2712 		if (ret)
2713 			break;
2714 	}
2715 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2716 
2717 	btrfs_free_chunk_map(map);
2718 	return ret;
2719 }
2720 
2721 /*
2722  * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
2723  * chunk allocation.
2724  *
2725  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2726  * phases.
2727  */
btrfs_create_pending_block_groups(struct btrfs_trans_handle * trans)2728 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2729 {
2730 	struct btrfs_fs_info *fs_info = trans->fs_info;
2731 	struct btrfs_block_group *block_group;
2732 	int ret = 0;
2733 
2734 	while (!list_empty(&trans->new_bgs)) {
2735 		int index;
2736 
2737 		block_group = list_first_entry(&trans->new_bgs,
2738 					       struct btrfs_block_group,
2739 					       bg_list);
2740 		if (ret)
2741 			goto next;
2742 
2743 		index = btrfs_bg_flags_to_raid_index(block_group->flags);
2744 
2745 		ret = insert_block_group_item(trans, block_group);
2746 		if (ret)
2747 			btrfs_abort_transaction(trans, ret);
2748 		if (!test_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED,
2749 			      &block_group->runtime_flags)) {
2750 			mutex_lock(&fs_info->chunk_mutex);
2751 			ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group);
2752 			mutex_unlock(&fs_info->chunk_mutex);
2753 			if (ret)
2754 				btrfs_abort_transaction(trans, ret);
2755 		}
2756 		ret = insert_dev_extents(trans, block_group->start,
2757 					 block_group->length);
2758 		if (ret)
2759 			btrfs_abort_transaction(trans, ret);
2760 		add_block_group_free_space(trans, block_group);
2761 
2762 		/*
2763 		 * If we restriped during balance, we may have added a new raid
2764 		 * type, so now add the sysfs entries when it is safe to do so.
2765 		 * We don't have to worry about locking here as it's handled in
2766 		 * btrfs_sysfs_add_block_group_type.
2767 		 */
2768 		if (block_group->space_info->block_group_kobjs[index] == NULL)
2769 			btrfs_sysfs_add_block_group_type(block_group);
2770 
2771 		/* Already aborted the transaction if it failed. */
2772 next:
2773 		btrfs_dec_delayed_refs_rsv_bg_inserts(fs_info);
2774 		list_del_init(&block_group->bg_list);
2775 		clear_bit(BLOCK_GROUP_FLAG_NEW, &block_group->runtime_flags);
2776 
2777 		/*
2778 		 * If the block group is still unused, add it to the list of
2779 		 * unused block groups. The block group may have been created in
2780 		 * order to satisfy a space reservation, in which case the
2781 		 * extent allocation only happens later. But often we don't
2782 		 * actually need to allocate space that we previously reserved,
2783 		 * so the block group may become unused for a long time. For
2784 		 * example for metadata we generally reserve space for a worst
2785 		 * possible scenario, but then don't end up allocating all that
2786 		 * space or none at all (due to no need to COW, extent buffers
2787 		 * were already COWed in the current transaction and still
2788 		 * unwritten, tree heights lower than the maximum possible
2789 		 * height, etc). For data we generally reserve the axact amount
2790 		 * of space we are going to allocate later, the exception is
2791 		 * when using compression, as we must reserve space based on the
2792 		 * uncompressed data size, because the compression is only done
2793 		 * when writeback triggered and we don't know how much space we
2794 		 * are actually going to need, so we reserve the uncompressed
2795 		 * size because the data may be incompressible in the worst case.
2796 		 */
2797 		if (ret == 0) {
2798 			bool used;
2799 
2800 			spin_lock(&block_group->lock);
2801 			used = btrfs_is_block_group_used(block_group);
2802 			spin_unlock(&block_group->lock);
2803 
2804 			if (!used)
2805 				btrfs_mark_bg_unused(block_group);
2806 		}
2807 	}
2808 	btrfs_trans_release_chunk_metadata(trans);
2809 }
2810 
2811 /*
2812  * For extent tree v2 we use the block_group_item->chunk_offset to point at our
2813  * global root id.  For v1 it's always set to BTRFS_FIRST_CHUNK_TREE_OBJECTID.
2814  */
calculate_global_root_id(const struct btrfs_fs_info * fs_info,u64 offset)2815 static u64 calculate_global_root_id(const struct btrfs_fs_info *fs_info, u64 offset)
2816 {
2817 	u64 div = SZ_1G;
2818 	u64 index;
2819 
2820 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2821 		return BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2822 
2823 	/* If we have a smaller fs index based on 128MiB. */
2824 	if (btrfs_super_total_bytes(fs_info->super_copy) <= (SZ_1G * 10ULL))
2825 		div = SZ_128M;
2826 
2827 	offset = div64_u64(offset, div);
2828 	div64_u64_rem(offset, fs_info->nr_global_roots, &index);
2829 	return index;
2830 }
2831 
btrfs_make_block_group(struct btrfs_trans_handle * trans,u64 type,u64 chunk_offset,u64 size)2832 struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
2833 						 u64 type,
2834 						 u64 chunk_offset, u64 size)
2835 {
2836 	struct btrfs_fs_info *fs_info = trans->fs_info;
2837 	struct btrfs_block_group *cache;
2838 	int ret;
2839 
2840 	btrfs_set_log_full_commit(trans);
2841 
2842 	cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
2843 	if (!cache)
2844 		return ERR_PTR(-ENOMEM);
2845 
2846 	/*
2847 	 * Mark it as new before adding it to the rbtree of block groups or any
2848 	 * list, so that no other task finds it and calls btrfs_mark_bg_unused()
2849 	 * before the new flag is set.
2850 	 */
2851 	set_bit(BLOCK_GROUP_FLAG_NEW, &cache->runtime_flags);
2852 
2853 	cache->length = size;
2854 	set_free_space_tree_thresholds(cache);
2855 	cache->flags = type;
2856 	cache->cached = BTRFS_CACHE_FINISHED;
2857 	cache->global_root_id = calculate_global_root_id(fs_info, cache->start);
2858 
2859 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
2860 		set_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE, &cache->runtime_flags);
2861 
2862 	ret = btrfs_load_block_group_zone_info(cache, true);
2863 	if (ret) {
2864 		btrfs_put_block_group(cache);
2865 		return ERR_PTR(ret);
2866 	}
2867 
2868 	ret = exclude_super_stripes(cache);
2869 	if (ret) {
2870 		/* We may have excluded something, so call this just in case */
2871 		btrfs_free_excluded_extents(cache);
2872 		btrfs_put_block_group(cache);
2873 		return ERR_PTR(ret);
2874 	}
2875 
2876 	ret = btrfs_add_new_free_space(cache, chunk_offset, chunk_offset + size, NULL);
2877 	btrfs_free_excluded_extents(cache);
2878 	if (ret) {
2879 		btrfs_put_block_group(cache);
2880 		return ERR_PTR(ret);
2881 	}
2882 
2883 	/*
2884 	 * Ensure the corresponding space_info object is created and
2885 	 * assigned to our block group. We want our bg to be added to the rbtree
2886 	 * with its ->space_info set.
2887 	 */
2888 	cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2889 	ASSERT(cache->space_info);
2890 
2891 	ret = btrfs_add_block_group_cache(fs_info, cache);
2892 	if (ret) {
2893 		btrfs_remove_free_space_cache(cache);
2894 		btrfs_put_block_group(cache);
2895 		return ERR_PTR(ret);
2896 	}
2897 
2898 	/*
2899 	 * Now that our block group has its ->space_info set and is inserted in
2900 	 * the rbtree, update the space info's counters.
2901 	 */
2902 	trace_btrfs_add_block_group(fs_info, cache, 1);
2903 	btrfs_add_bg_to_space_info(fs_info, cache);
2904 	btrfs_update_global_block_rsv(fs_info);
2905 
2906 #ifdef CONFIG_BTRFS_DEBUG
2907 	if (btrfs_should_fragment_free_space(cache)) {
2908 		cache->space_info->bytes_used += size >> 1;
2909 		fragment_free_space(cache);
2910 	}
2911 #endif
2912 
2913 	list_add_tail(&cache->bg_list, &trans->new_bgs);
2914 	btrfs_inc_delayed_refs_rsv_bg_inserts(fs_info);
2915 
2916 	set_avail_alloc_bits(fs_info, type);
2917 	return cache;
2918 }
2919 
2920 /*
2921  * Mark one block group RO, can be called several times for the same block
2922  * group.
2923  *
2924  * @cache:		the destination block group
2925  * @do_chunk_alloc:	whether need to do chunk pre-allocation, this is to
2926  * 			ensure we still have some free space after marking this
2927  * 			block group RO.
2928  */
btrfs_inc_block_group_ro(struct btrfs_block_group * cache,bool do_chunk_alloc)2929 int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2930 			     bool do_chunk_alloc)
2931 {
2932 	struct btrfs_fs_info *fs_info = cache->fs_info;
2933 	struct btrfs_trans_handle *trans;
2934 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
2935 	u64 alloc_flags;
2936 	int ret;
2937 	bool dirty_bg_running;
2938 
2939 	/*
2940 	 * This can only happen when we are doing read-only scrub on read-only
2941 	 * mount.
2942 	 * In that case we should not start a new transaction on read-only fs.
2943 	 * Thus here we skip all chunk allocations.
2944 	 */
2945 	if (sb_rdonly(fs_info->sb)) {
2946 		mutex_lock(&fs_info->ro_block_group_mutex);
2947 		ret = inc_block_group_ro(cache, 0);
2948 		mutex_unlock(&fs_info->ro_block_group_mutex);
2949 		return ret;
2950 	}
2951 
2952 	do {
2953 		trans = btrfs_join_transaction(root);
2954 		if (IS_ERR(trans))
2955 			return PTR_ERR(trans);
2956 
2957 		dirty_bg_running = false;
2958 
2959 		/*
2960 		 * We're not allowed to set block groups readonly after the dirty
2961 		 * block group cache has started writing.  If it already started,
2962 		 * back off and let this transaction commit.
2963 		 */
2964 		mutex_lock(&fs_info->ro_block_group_mutex);
2965 		if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2966 			u64 transid = trans->transid;
2967 
2968 			mutex_unlock(&fs_info->ro_block_group_mutex);
2969 			btrfs_end_transaction(trans);
2970 
2971 			ret = btrfs_wait_for_commit(fs_info, transid);
2972 			if (ret)
2973 				return ret;
2974 			dirty_bg_running = true;
2975 		}
2976 	} while (dirty_bg_running);
2977 
2978 	if (do_chunk_alloc) {
2979 		/*
2980 		 * If we are changing raid levels, try to allocate a
2981 		 * corresponding block group with the new raid level.
2982 		 */
2983 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2984 		if (alloc_flags != cache->flags) {
2985 			ret = btrfs_chunk_alloc(trans, alloc_flags,
2986 						CHUNK_ALLOC_FORCE);
2987 			/*
2988 			 * ENOSPC is allowed here, we may have enough space
2989 			 * already allocated at the new raid level to carry on
2990 			 */
2991 			if (ret == -ENOSPC)
2992 				ret = 0;
2993 			if (ret < 0)
2994 				goto out;
2995 		}
2996 	}
2997 
2998 	ret = inc_block_group_ro(cache, 0);
2999 	if (!ret)
3000 		goto out;
3001 	if (ret == -ETXTBSY)
3002 		goto unlock_out;
3003 
3004 	/*
3005 	 * Skip chunk allocation if the bg is SYSTEM, this is to avoid system
3006 	 * chunk allocation storm to exhaust the system chunk array.  Otherwise
3007 	 * we still want to try our best to mark the block group read-only.
3008 	 */
3009 	if (!do_chunk_alloc && ret == -ENOSPC &&
3010 	    (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM))
3011 		goto unlock_out;
3012 
3013 	alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
3014 	ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3015 	if (ret < 0)
3016 		goto out;
3017 	/*
3018 	 * We have allocated a new chunk. We also need to activate that chunk to
3019 	 * grant metadata tickets for zoned filesystem.
3020 	 */
3021 	ret = btrfs_zoned_activate_one_bg(fs_info, cache->space_info, true);
3022 	if (ret < 0)
3023 		goto out;
3024 
3025 	ret = inc_block_group_ro(cache, 0);
3026 	if (ret == -ETXTBSY)
3027 		goto unlock_out;
3028 out:
3029 	if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
3030 		alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
3031 		mutex_lock(&fs_info->chunk_mutex);
3032 		check_system_chunk(trans, alloc_flags);
3033 		mutex_unlock(&fs_info->chunk_mutex);
3034 	}
3035 unlock_out:
3036 	mutex_unlock(&fs_info->ro_block_group_mutex);
3037 
3038 	btrfs_end_transaction(trans);
3039 	return ret;
3040 }
3041 
btrfs_dec_block_group_ro(struct btrfs_block_group * cache)3042 void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
3043 {
3044 	struct btrfs_space_info *sinfo = cache->space_info;
3045 	u64 num_bytes;
3046 
3047 	BUG_ON(!cache->ro);
3048 
3049 	spin_lock(&sinfo->lock);
3050 	spin_lock(&cache->lock);
3051 	if (!--cache->ro) {
3052 		if (btrfs_is_zoned(cache->fs_info)) {
3053 			/* Migrate zone_unusable bytes back */
3054 			cache->zone_unusable =
3055 				(cache->alloc_offset - cache->used - cache->pinned -
3056 				 cache->reserved) +
3057 				(cache->length - cache->zone_capacity);
3058 			btrfs_space_info_update_bytes_zone_unusable(sinfo, cache->zone_unusable);
3059 			sinfo->bytes_readonly -= cache->zone_unusable;
3060 		}
3061 		num_bytes = cache->length - cache->reserved -
3062 			    cache->pinned - cache->bytes_super -
3063 			    cache->zone_unusable - cache->used;
3064 		sinfo->bytes_readonly -= num_bytes;
3065 		list_del_init(&cache->ro_list);
3066 	}
3067 	spin_unlock(&cache->lock);
3068 	spin_unlock(&sinfo->lock);
3069 }
3070 
update_block_group_item(struct btrfs_trans_handle * trans,struct btrfs_path * path,struct btrfs_block_group * cache)3071 static int update_block_group_item(struct btrfs_trans_handle *trans,
3072 				   struct btrfs_path *path,
3073 				   struct btrfs_block_group *cache)
3074 {
3075 	struct btrfs_fs_info *fs_info = trans->fs_info;
3076 	int ret;
3077 	struct btrfs_root *root = btrfs_block_group_root(fs_info);
3078 	unsigned long bi;
3079 	struct extent_buffer *leaf;
3080 	struct btrfs_block_group_item bgi;
3081 	struct btrfs_key key;
3082 	u64 old_commit_used;
3083 	u64 used;
3084 
3085 	/*
3086 	 * Block group items update can be triggered out of commit transaction
3087 	 * critical section, thus we need a consistent view of used bytes.
3088 	 * We cannot use cache->used directly outside of the spin lock, as it
3089 	 * may be changed.
3090 	 */
3091 	spin_lock(&cache->lock);
3092 	old_commit_used = cache->commit_used;
3093 	used = cache->used;
3094 	/* No change in used bytes, can safely skip it. */
3095 	if (cache->commit_used == used) {
3096 		spin_unlock(&cache->lock);
3097 		return 0;
3098 	}
3099 	cache->commit_used = used;
3100 	spin_unlock(&cache->lock);
3101 
3102 	key.objectid = cache->start;
3103 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
3104 	key.offset = cache->length;
3105 
3106 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3107 	if (ret) {
3108 		if (ret > 0)
3109 			ret = -ENOENT;
3110 		goto fail;
3111 	}
3112 
3113 	leaf = path->nodes[0];
3114 	bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3115 	btrfs_set_stack_block_group_used(&bgi, used);
3116 	btrfs_set_stack_block_group_chunk_objectid(&bgi,
3117 						   cache->global_root_id);
3118 	btrfs_set_stack_block_group_flags(&bgi, cache->flags);
3119 	write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
3120 fail:
3121 	btrfs_release_path(path);
3122 	/*
3123 	 * We didn't update the block group item, need to revert commit_used
3124 	 * unless the block group item didn't exist yet - this is to prevent a
3125 	 * race with a concurrent insertion of the block group item, with
3126 	 * insert_block_group_item(), that happened just after we attempted to
3127 	 * update. In that case we would reset commit_used to 0 just after the
3128 	 * insertion set it to a value greater than 0 - if the block group later
3129 	 * becomes with 0 used bytes, we would incorrectly skip its update.
3130 	 */
3131 	if (ret < 0 && ret != -ENOENT) {
3132 		spin_lock(&cache->lock);
3133 		cache->commit_used = old_commit_used;
3134 		spin_unlock(&cache->lock);
3135 	}
3136 	return ret;
3137 
3138 }
3139 
cache_save_setup(struct btrfs_block_group * block_group,struct btrfs_trans_handle * trans,struct btrfs_path * path)3140 static int cache_save_setup(struct btrfs_block_group *block_group,
3141 			    struct btrfs_trans_handle *trans,
3142 			    struct btrfs_path *path)
3143 {
3144 	struct btrfs_fs_info *fs_info = block_group->fs_info;
3145 	struct inode *inode = NULL;
3146 	struct extent_changeset *data_reserved = NULL;
3147 	u64 alloc_hint = 0;
3148 	int dcs = BTRFS_DC_ERROR;
3149 	u64 cache_size = 0;
3150 	int retries = 0;
3151 	int ret = 0;
3152 
3153 	if (!btrfs_test_opt(fs_info, SPACE_CACHE))
3154 		return 0;
3155 
3156 	/*
3157 	 * If this block group is smaller than 100 megs don't bother caching the
3158 	 * block group.
3159 	 */
3160 	if (block_group->length < (100 * SZ_1M)) {
3161 		spin_lock(&block_group->lock);
3162 		block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3163 		spin_unlock(&block_group->lock);
3164 		return 0;
3165 	}
3166 
3167 	if (TRANS_ABORTED(trans))
3168 		return 0;
3169 again:
3170 	inode = lookup_free_space_inode(block_group, path);
3171 	if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3172 		ret = PTR_ERR(inode);
3173 		btrfs_release_path(path);
3174 		goto out;
3175 	}
3176 
3177 	if (IS_ERR(inode)) {
3178 		BUG_ON(retries);
3179 		retries++;
3180 
3181 		if (block_group->ro)
3182 			goto out_free;
3183 
3184 		ret = create_free_space_inode(trans, block_group, path);
3185 		if (ret)
3186 			goto out_free;
3187 		goto again;
3188 	}
3189 
3190 	/*
3191 	 * We want to set the generation to 0, that way if anything goes wrong
3192 	 * from here on out we know not to trust this cache when we load up next
3193 	 * time.
3194 	 */
3195 	BTRFS_I(inode)->generation = 0;
3196 	ret = btrfs_update_inode(trans, BTRFS_I(inode));
3197 	if (ret) {
3198 		/*
3199 		 * So theoretically we could recover from this, simply set the
3200 		 * super cache generation to 0 so we know to invalidate the
3201 		 * cache, but then we'd have to keep track of the block groups
3202 		 * that fail this way so we know we _have_ to reset this cache
3203 		 * before the next commit or risk reading stale cache.  So to
3204 		 * limit our exposure to horrible edge cases lets just abort the
3205 		 * transaction, this only happens in really bad situations
3206 		 * anyway.
3207 		 */
3208 		btrfs_abort_transaction(trans, ret);
3209 		goto out_put;
3210 	}
3211 	WARN_ON(ret);
3212 
3213 	/* We've already setup this transaction, go ahead and exit */
3214 	if (block_group->cache_generation == trans->transid &&
3215 	    i_size_read(inode)) {
3216 		dcs = BTRFS_DC_SETUP;
3217 		goto out_put;
3218 	}
3219 
3220 	if (i_size_read(inode) > 0) {
3221 		ret = btrfs_check_trunc_cache_free_space(fs_info,
3222 					&fs_info->global_block_rsv);
3223 		if (ret)
3224 			goto out_put;
3225 
3226 		ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
3227 		if (ret)
3228 			goto out_put;
3229 	}
3230 
3231 	spin_lock(&block_group->lock);
3232 	if (block_group->cached != BTRFS_CACHE_FINISHED ||
3233 	    !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3234 		/*
3235 		 * don't bother trying to write stuff out _if_
3236 		 * a) we're not cached,
3237 		 * b) we're with nospace_cache mount option,
3238 		 * c) we're with v2 space_cache (FREE_SPACE_TREE).
3239 		 */
3240 		dcs = BTRFS_DC_WRITTEN;
3241 		spin_unlock(&block_group->lock);
3242 		goto out_put;
3243 	}
3244 	spin_unlock(&block_group->lock);
3245 
3246 	/*
3247 	 * We hit an ENOSPC when setting up the cache in this transaction, just
3248 	 * skip doing the setup, we've already cleared the cache so we're safe.
3249 	 */
3250 	if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3251 		ret = -ENOSPC;
3252 		goto out_put;
3253 	}
3254 
3255 	/*
3256 	 * Try to preallocate enough space based on how big the block group is.
3257 	 * Keep in mind this has to include any pinned space which could end up
3258 	 * taking up quite a bit since it's not folded into the other space
3259 	 * cache.
3260 	 */
3261 	cache_size = div_u64(block_group->length, SZ_256M);
3262 	if (!cache_size)
3263 		cache_size = 1;
3264 
3265 	cache_size *= 16;
3266 	cache_size *= fs_info->sectorsize;
3267 
3268 	ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
3269 					  cache_size, false);
3270 	if (ret)
3271 		goto out_put;
3272 
3273 	ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
3274 					      cache_size, cache_size,
3275 					      &alloc_hint);
3276 	/*
3277 	 * Our cache requires contiguous chunks so that we don't modify a bunch
3278 	 * of metadata or split extents when writing the cache out, which means
3279 	 * we can enospc if we are heavily fragmented in addition to just normal
3280 	 * out of space conditions.  So if we hit this just skip setting up any
3281 	 * other block groups for this transaction, maybe we'll unpin enough
3282 	 * space the next time around.
3283 	 */
3284 	if (!ret)
3285 		dcs = BTRFS_DC_SETUP;
3286 	else if (ret == -ENOSPC)
3287 		set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3288 
3289 out_put:
3290 	iput(inode);
3291 out_free:
3292 	btrfs_release_path(path);
3293 out:
3294 	spin_lock(&block_group->lock);
3295 	if (!ret && dcs == BTRFS_DC_SETUP)
3296 		block_group->cache_generation = trans->transid;
3297 	block_group->disk_cache_state = dcs;
3298 	spin_unlock(&block_group->lock);
3299 
3300 	extent_changeset_free(data_reserved);
3301 	return ret;
3302 }
3303 
btrfs_setup_space_cache(struct btrfs_trans_handle * trans)3304 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
3305 {
3306 	struct btrfs_fs_info *fs_info = trans->fs_info;
3307 	struct btrfs_block_group *cache, *tmp;
3308 	struct btrfs_transaction *cur_trans = trans->transaction;
3309 	struct btrfs_path *path;
3310 
3311 	if (list_empty(&cur_trans->dirty_bgs) ||
3312 	    !btrfs_test_opt(fs_info, SPACE_CACHE))
3313 		return 0;
3314 
3315 	path = btrfs_alloc_path();
3316 	if (!path)
3317 		return -ENOMEM;
3318 
3319 	/* Could add new block groups, use _safe just in case */
3320 	list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3321 				 dirty_list) {
3322 		if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3323 			cache_save_setup(cache, trans, path);
3324 	}
3325 
3326 	btrfs_free_path(path);
3327 	return 0;
3328 }
3329 
3330 /*
3331  * Transaction commit does final block group cache writeback during a critical
3332  * section where nothing is allowed to change the FS.  This is required in
3333  * order for the cache to actually match the block group, but can introduce a
3334  * lot of latency into the commit.
3335  *
3336  * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
3337  * There's a chance we'll have to redo some of it if the block group changes
3338  * again during the commit, but it greatly reduces the commit latency by
3339  * getting rid of the easy block groups while we're still allowing others to
3340  * join the commit.
3341  */
btrfs_start_dirty_block_groups(struct btrfs_trans_handle * trans)3342 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
3343 {
3344 	struct btrfs_fs_info *fs_info = trans->fs_info;
3345 	struct btrfs_block_group *cache;
3346 	struct btrfs_transaction *cur_trans = trans->transaction;
3347 	int ret = 0;
3348 	int should_put;
3349 	struct btrfs_path *path = NULL;
3350 	LIST_HEAD(dirty);
3351 	struct list_head *io = &cur_trans->io_bgs;
3352 	int loops = 0;
3353 
3354 	spin_lock(&cur_trans->dirty_bgs_lock);
3355 	if (list_empty(&cur_trans->dirty_bgs)) {
3356 		spin_unlock(&cur_trans->dirty_bgs_lock);
3357 		return 0;
3358 	}
3359 	list_splice_init(&cur_trans->dirty_bgs, &dirty);
3360 	spin_unlock(&cur_trans->dirty_bgs_lock);
3361 
3362 again:
3363 	/* Make sure all the block groups on our dirty list actually exist */
3364 	btrfs_create_pending_block_groups(trans);
3365 
3366 	if (!path) {
3367 		path = btrfs_alloc_path();
3368 		if (!path) {
3369 			ret = -ENOMEM;
3370 			goto out;
3371 		}
3372 	}
3373 
3374 	/*
3375 	 * cache_write_mutex is here only to save us from balance or automatic
3376 	 * removal of empty block groups deleting this block group while we are
3377 	 * writing out the cache
3378 	 */
3379 	mutex_lock(&trans->transaction->cache_write_mutex);
3380 	while (!list_empty(&dirty)) {
3381 		bool drop_reserve = true;
3382 
3383 		cache = list_first_entry(&dirty, struct btrfs_block_group,
3384 					 dirty_list);
3385 		/*
3386 		 * This can happen if something re-dirties a block group that
3387 		 * is already under IO.  Just wait for it to finish and then do
3388 		 * it all again
3389 		 */
3390 		if (!list_empty(&cache->io_list)) {
3391 			list_del_init(&cache->io_list);
3392 			btrfs_wait_cache_io(trans, cache, path);
3393 			btrfs_put_block_group(cache);
3394 		}
3395 
3396 
3397 		/*
3398 		 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
3399 		 * it should update the cache_state.  Don't delete until after
3400 		 * we wait.
3401 		 *
3402 		 * Since we're not running in the commit critical section
3403 		 * we need the dirty_bgs_lock to protect from update_block_group
3404 		 */
3405 		spin_lock(&cur_trans->dirty_bgs_lock);
3406 		list_del_init(&cache->dirty_list);
3407 		spin_unlock(&cur_trans->dirty_bgs_lock);
3408 
3409 		should_put = 1;
3410 
3411 		cache_save_setup(cache, trans, path);
3412 
3413 		if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3414 			cache->io_ctl.inode = NULL;
3415 			ret = btrfs_write_out_cache(trans, cache, path);
3416 			if (ret == 0 && cache->io_ctl.inode) {
3417 				should_put = 0;
3418 
3419 				/*
3420 				 * The cache_write_mutex is protecting the
3421 				 * io_list, also refer to the definition of
3422 				 * btrfs_transaction::io_bgs for more details
3423 				 */
3424 				list_add_tail(&cache->io_list, io);
3425 			} else {
3426 				/*
3427 				 * If we failed to write the cache, the
3428 				 * generation will be bad and life goes on
3429 				 */
3430 				ret = 0;
3431 			}
3432 		}
3433 		if (!ret) {
3434 			ret = update_block_group_item(trans, path, cache);
3435 			/*
3436 			 * Our block group might still be attached to the list
3437 			 * of new block groups in the transaction handle of some
3438 			 * other task (struct btrfs_trans_handle->new_bgs). This
3439 			 * means its block group item isn't yet in the extent
3440 			 * tree. If this happens ignore the error, as we will
3441 			 * try again later in the critical section of the
3442 			 * transaction commit.
3443 			 */
3444 			if (ret == -ENOENT) {
3445 				ret = 0;
3446 				spin_lock(&cur_trans->dirty_bgs_lock);
3447 				if (list_empty(&cache->dirty_list)) {
3448 					list_add_tail(&cache->dirty_list,
3449 						      &cur_trans->dirty_bgs);
3450 					btrfs_get_block_group(cache);
3451 					drop_reserve = false;
3452 				}
3453 				spin_unlock(&cur_trans->dirty_bgs_lock);
3454 			} else if (ret) {
3455 				btrfs_abort_transaction(trans, ret);
3456 			}
3457 		}
3458 
3459 		/* If it's not on the io list, we need to put the block group */
3460 		if (should_put)
3461 			btrfs_put_block_group(cache);
3462 		if (drop_reserve)
3463 			btrfs_dec_delayed_refs_rsv_bg_updates(fs_info);
3464 		/*
3465 		 * Avoid blocking other tasks for too long. It might even save
3466 		 * us from writing caches for block groups that are going to be
3467 		 * removed.
3468 		 */
3469 		mutex_unlock(&trans->transaction->cache_write_mutex);
3470 		if (ret)
3471 			goto out;
3472 		mutex_lock(&trans->transaction->cache_write_mutex);
3473 	}
3474 	mutex_unlock(&trans->transaction->cache_write_mutex);
3475 
3476 	/*
3477 	 * Go through delayed refs for all the stuff we've just kicked off
3478 	 * and then loop back (just once)
3479 	 */
3480 	if (!ret)
3481 		ret = btrfs_run_delayed_refs(trans, 0);
3482 	if (!ret && loops == 0) {
3483 		loops++;
3484 		spin_lock(&cur_trans->dirty_bgs_lock);
3485 		list_splice_init(&cur_trans->dirty_bgs, &dirty);
3486 		/*
3487 		 * dirty_bgs_lock protects us from concurrent block group
3488 		 * deletes too (not just cache_write_mutex).
3489 		 */
3490 		if (!list_empty(&dirty)) {
3491 			spin_unlock(&cur_trans->dirty_bgs_lock);
3492 			goto again;
3493 		}
3494 		spin_unlock(&cur_trans->dirty_bgs_lock);
3495 	}
3496 out:
3497 	if (ret < 0) {
3498 		spin_lock(&cur_trans->dirty_bgs_lock);
3499 		list_splice_init(&dirty, &cur_trans->dirty_bgs);
3500 		spin_unlock(&cur_trans->dirty_bgs_lock);
3501 		btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3502 	}
3503 
3504 	btrfs_free_path(path);
3505 	return ret;
3506 }
3507 
btrfs_write_dirty_block_groups(struct btrfs_trans_handle * trans)3508 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
3509 {
3510 	struct btrfs_fs_info *fs_info = trans->fs_info;
3511 	struct btrfs_block_group *cache;
3512 	struct btrfs_transaction *cur_trans = trans->transaction;
3513 	int ret = 0;
3514 	int should_put;
3515 	struct btrfs_path *path;
3516 	struct list_head *io = &cur_trans->io_bgs;
3517 
3518 	path = btrfs_alloc_path();
3519 	if (!path)
3520 		return -ENOMEM;
3521 
3522 	/*
3523 	 * Even though we are in the critical section of the transaction commit,
3524 	 * we can still have concurrent tasks adding elements to this
3525 	 * transaction's list of dirty block groups. These tasks correspond to
3526 	 * endio free space workers started when writeback finishes for a
3527 	 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3528 	 * allocate new block groups as a result of COWing nodes of the root
3529 	 * tree when updating the free space inode. The writeback for the space
3530 	 * caches is triggered by an earlier call to
3531 	 * btrfs_start_dirty_block_groups() and iterations of the following
3532 	 * loop.
3533 	 * Also we want to do the cache_save_setup first and then run the
3534 	 * delayed refs to make sure we have the best chance at doing this all
3535 	 * in one shot.
3536 	 */
3537 	spin_lock(&cur_trans->dirty_bgs_lock);
3538 	while (!list_empty(&cur_trans->dirty_bgs)) {
3539 		cache = list_first_entry(&cur_trans->dirty_bgs,
3540 					 struct btrfs_block_group,
3541 					 dirty_list);
3542 
3543 		/*
3544 		 * This can happen if cache_save_setup re-dirties a block group
3545 		 * that is already under IO.  Just wait for it to finish and
3546 		 * then do it all again
3547 		 */
3548 		if (!list_empty(&cache->io_list)) {
3549 			spin_unlock(&cur_trans->dirty_bgs_lock);
3550 			list_del_init(&cache->io_list);
3551 			btrfs_wait_cache_io(trans, cache, path);
3552 			btrfs_put_block_group(cache);
3553 			spin_lock(&cur_trans->dirty_bgs_lock);
3554 		}
3555 
3556 		/*
3557 		 * Don't remove from the dirty list until after we've waited on
3558 		 * any pending IO
3559 		 */
3560 		list_del_init(&cache->dirty_list);
3561 		spin_unlock(&cur_trans->dirty_bgs_lock);
3562 		should_put = 1;
3563 
3564 		cache_save_setup(cache, trans, path);
3565 
3566 		if (!ret)
3567 			ret = btrfs_run_delayed_refs(trans, U64_MAX);
3568 
3569 		if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3570 			cache->io_ctl.inode = NULL;
3571 			ret = btrfs_write_out_cache(trans, cache, path);
3572 			if (ret == 0 && cache->io_ctl.inode) {
3573 				should_put = 0;
3574 				list_add_tail(&cache->io_list, io);
3575 			} else {
3576 				/*
3577 				 * If we failed to write the cache, the
3578 				 * generation will be bad and life goes on
3579 				 */
3580 				ret = 0;
3581 			}
3582 		}
3583 		if (!ret) {
3584 			ret = update_block_group_item(trans, path, cache);
3585 			/*
3586 			 * One of the free space endio workers might have
3587 			 * created a new block group while updating a free space
3588 			 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3589 			 * and hasn't released its transaction handle yet, in
3590 			 * which case the new block group is still attached to
3591 			 * its transaction handle and its creation has not
3592 			 * finished yet (no block group item in the extent tree
3593 			 * yet, etc). If this is the case, wait for all free
3594 			 * space endio workers to finish and retry. This is a
3595 			 * very rare case so no need for a more efficient and
3596 			 * complex approach.
3597 			 */
3598 			if (ret == -ENOENT) {
3599 				wait_event(cur_trans->writer_wait,
3600 				   atomic_read(&cur_trans->num_writers) == 1);
3601 				ret = update_block_group_item(trans, path, cache);
3602 			}
3603 			if (ret)
3604 				btrfs_abort_transaction(trans, ret);
3605 		}
3606 
3607 		/* If its not on the io list, we need to put the block group */
3608 		if (should_put)
3609 			btrfs_put_block_group(cache);
3610 		btrfs_dec_delayed_refs_rsv_bg_updates(fs_info);
3611 		spin_lock(&cur_trans->dirty_bgs_lock);
3612 	}
3613 	spin_unlock(&cur_trans->dirty_bgs_lock);
3614 
3615 	/*
3616 	 * Refer to the definition of io_bgs member for details why it's safe
3617 	 * to use it without any locking
3618 	 */
3619 	while (!list_empty(io)) {
3620 		cache = list_first_entry(io, struct btrfs_block_group,
3621 					 io_list);
3622 		list_del_init(&cache->io_list);
3623 		btrfs_wait_cache_io(trans, cache, path);
3624 		btrfs_put_block_group(cache);
3625 	}
3626 
3627 	btrfs_free_path(path);
3628 	return ret;
3629 }
3630 
btrfs_update_block_group(struct btrfs_trans_handle * trans,u64 bytenr,u64 num_bytes,bool alloc)3631 int btrfs_update_block_group(struct btrfs_trans_handle *trans,
3632 			     u64 bytenr, u64 num_bytes, bool alloc)
3633 {
3634 	struct btrfs_fs_info *info = trans->fs_info;
3635 	struct btrfs_space_info *space_info;
3636 	struct btrfs_block_group *cache;
3637 	u64 old_val;
3638 	bool reclaim = false;
3639 	bool bg_already_dirty = true;
3640 	int factor;
3641 
3642 	/* Block accounting for super block */
3643 	spin_lock(&info->delalloc_root_lock);
3644 	old_val = btrfs_super_bytes_used(info->super_copy);
3645 	if (alloc)
3646 		old_val += num_bytes;
3647 	else
3648 		old_val -= num_bytes;
3649 	btrfs_set_super_bytes_used(info->super_copy, old_val);
3650 	spin_unlock(&info->delalloc_root_lock);
3651 
3652 	cache = btrfs_lookup_block_group(info, bytenr);
3653 	if (!cache)
3654 		return -ENOENT;
3655 
3656 	/* An extent can not span multiple block groups. */
3657 	ASSERT(bytenr + num_bytes <= cache->start + cache->length);
3658 
3659 	space_info = cache->space_info;
3660 	factor = btrfs_bg_type_to_factor(cache->flags);
3661 
3662 	/*
3663 	 * If this block group has free space cache written out, we need to make
3664 	 * sure to load it if we are removing space.  This is because we need
3665 	 * the unpinning stage to actually add the space back to the block group,
3666 	 * otherwise we will leak space.
3667 	 */
3668 	if (!alloc && !btrfs_block_group_done(cache))
3669 		btrfs_cache_block_group(cache, true);
3670 
3671 	spin_lock(&space_info->lock);
3672 	spin_lock(&cache->lock);
3673 
3674 	if (btrfs_test_opt(info, SPACE_CACHE) &&
3675 	    cache->disk_cache_state < BTRFS_DC_CLEAR)
3676 		cache->disk_cache_state = BTRFS_DC_CLEAR;
3677 
3678 	old_val = cache->used;
3679 	if (alloc) {
3680 		old_val += num_bytes;
3681 		cache->used = old_val;
3682 		cache->reserved -= num_bytes;
3683 		cache->reclaim_mark = 0;
3684 		space_info->bytes_reserved -= num_bytes;
3685 		space_info->bytes_used += num_bytes;
3686 		space_info->disk_used += num_bytes * factor;
3687 		if (READ_ONCE(space_info->periodic_reclaim))
3688 			btrfs_space_info_update_reclaimable(space_info, -num_bytes);
3689 		spin_unlock(&cache->lock);
3690 		spin_unlock(&space_info->lock);
3691 	} else {
3692 		old_val -= num_bytes;
3693 		cache->used = old_val;
3694 		cache->pinned += num_bytes;
3695 		btrfs_space_info_update_bytes_pinned(space_info, num_bytes);
3696 		space_info->bytes_used -= num_bytes;
3697 		space_info->disk_used -= num_bytes * factor;
3698 		if (READ_ONCE(space_info->periodic_reclaim))
3699 			btrfs_space_info_update_reclaimable(space_info, num_bytes);
3700 		else
3701 			reclaim = should_reclaim_block_group(cache, num_bytes);
3702 
3703 		spin_unlock(&cache->lock);
3704 		spin_unlock(&space_info->lock);
3705 
3706 		set_extent_bit(&trans->transaction->pinned_extents, bytenr,
3707 			       bytenr + num_bytes - 1, EXTENT_DIRTY, NULL);
3708 	}
3709 
3710 	spin_lock(&trans->transaction->dirty_bgs_lock);
3711 	if (list_empty(&cache->dirty_list)) {
3712 		list_add_tail(&cache->dirty_list, &trans->transaction->dirty_bgs);
3713 		bg_already_dirty = false;
3714 		btrfs_get_block_group(cache);
3715 	}
3716 	spin_unlock(&trans->transaction->dirty_bgs_lock);
3717 
3718 	/*
3719 	 * No longer have used bytes in this block group, queue it for deletion.
3720 	 * We do this after adding the block group to the dirty list to avoid
3721 	 * races between cleaner kthread and space cache writeout.
3722 	 */
3723 	if (!alloc && old_val == 0) {
3724 		if (!btrfs_test_opt(info, DISCARD_ASYNC))
3725 			btrfs_mark_bg_unused(cache);
3726 	} else if (!alloc && reclaim) {
3727 		btrfs_mark_bg_to_reclaim(cache);
3728 	}
3729 
3730 	btrfs_put_block_group(cache);
3731 
3732 	/* Modified block groups are accounted for in the delayed_refs_rsv. */
3733 	if (!bg_already_dirty)
3734 		btrfs_inc_delayed_refs_rsv_bg_updates(info);
3735 
3736 	return 0;
3737 }
3738 
3739 /*
3740  * Update the block_group and space info counters.
3741  *
3742  * @cache:	The cache we are manipulating
3743  * @ram_bytes:  The number of bytes of file content, and will be same to
3744  *              @num_bytes except for the compress path.
3745  * @num_bytes:	The number of bytes in question
3746  * @delalloc:   The blocks are allocated for the delalloc write
3747  *
3748  * This is called by the allocator when it reserves space. If this is a
3749  * reservation and the block group has become read only we cannot make the
3750  * reservation and return -EAGAIN, otherwise this function always succeeds.
3751  */
btrfs_add_reserved_bytes(struct btrfs_block_group * cache,u64 ram_bytes,u64 num_bytes,int delalloc,bool force_wrong_size_class)3752 int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
3753 			     u64 ram_bytes, u64 num_bytes, int delalloc,
3754 			     bool force_wrong_size_class)
3755 {
3756 	struct btrfs_space_info *space_info = cache->space_info;
3757 	enum btrfs_block_group_size_class size_class;
3758 	int ret = 0;
3759 
3760 	spin_lock(&space_info->lock);
3761 	spin_lock(&cache->lock);
3762 	if (cache->ro) {
3763 		ret = -EAGAIN;
3764 		goto out;
3765 	}
3766 
3767 	if (btrfs_block_group_should_use_size_class(cache)) {
3768 		size_class = btrfs_calc_block_group_size_class(num_bytes);
3769 		ret = btrfs_use_block_group_size_class(cache, size_class, force_wrong_size_class);
3770 		if (ret)
3771 			goto out;
3772 	}
3773 	cache->reserved += num_bytes;
3774 	space_info->bytes_reserved += num_bytes;
3775 	trace_btrfs_space_reservation(cache->fs_info, "space_info",
3776 				      space_info->flags, num_bytes, 1);
3777 	btrfs_space_info_update_bytes_may_use(space_info, -ram_bytes);
3778 	if (delalloc)
3779 		cache->delalloc_bytes += num_bytes;
3780 
3781 	/*
3782 	 * Compression can use less space than we reserved, so wake tickets if
3783 	 * that happens.
3784 	 */
3785 	if (num_bytes < ram_bytes)
3786 		btrfs_try_granting_tickets(cache->fs_info, space_info);
3787 out:
3788 	spin_unlock(&cache->lock);
3789 	spin_unlock(&space_info->lock);
3790 	return ret;
3791 }
3792 
3793 /*
3794  * Update the block_group and space info counters.
3795  *
3796  * @cache:      The cache we are manipulating
3797  * @num_bytes:  The number of bytes in question
3798  * @delalloc:   The blocks are allocated for the delalloc write
3799  *
3800  * This is called by somebody who is freeing space that was never actually used
3801  * on disk.  For example if you reserve some space for a new leaf in transaction
3802  * A and before transaction A commits you free that leaf, you call this with
3803  * reserve set to 0 in order to clear the reservation.
3804  */
btrfs_free_reserved_bytes(struct btrfs_block_group * cache,u64 num_bytes,int delalloc)3805 void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3806 			       u64 num_bytes, int delalloc)
3807 {
3808 	struct btrfs_space_info *space_info = cache->space_info;
3809 
3810 	spin_lock(&space_info->lock);
3811 	spin_lock(&cache->lock);
3812 	if (cache->ro)
3813 		space_info->bytes_readonly += num_bytes;
3814 	else if (btrfs_is_zoned(cache->fs_info))
3815 		space_info->bytes_zone_unusable += num_bytes;
3816 	cache->reserved -= num_bytes;
3817 	space_info->bytes_reserved -= num_bytes;
3818 	space_info->max_extent_size = 0;
3819 
3820 	if (delalloc)
3821 		cache->delalloc_bytes -= num_bytes;
3822 	spin_unlock(&cache->lock);
3823 
3824 	btrfs_try_granting_tickets(cache->fs_info, space_info);
3825 	spin_unlock(&space_info->lock);
3826 }
3827 
force_metadata_allocation(struct btrfs_fs_info * info)3828 static void force_metadata_allocation(struct btrfs_fs_info *info)
3829 {
3830 	struct list_head *head = &info->space_info;
3831 	struct btrfs_space_info *found;
3832 
3833 	list_for_each_entry(found, head, list) {
3834 		if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3835 			found->force_alloc = CHUNK_ALLOC_FORCE;
3836 	}
3837 }
3838 
should_alloc_chunk(const struct btrfs_fs_info * fs_info,const struct btrfs_space_info * sinfo,int force)3839 static int should_alloc_chunk(const struct btrfs_fs_info *fs_info,
3840 			      const struct btrfs_space_info *sinfo, int force)
3841 {
3842 	u64 bytes_used = btrfs_space_info_used(sinfo, false);
3843 	u64 thresh;
3844 
3845 	if (force == CHUNK_ALLOC_FORCE)
3846 		return 1;
3847 
3848 	/*
3849 	 * in limited mode, we want to have some free space up to
3850 	 * about 1% of the FS size.
3851 	 */
3852 	if (force == CHUNK_ALLOC_LIMITED) {
3853 		thresh = btrfs_super_total_bytes(fs_info->super_copy);
3854 		thresh = max_t(u64, SZ_64M, mult_perc(thresh, 1));
3855 
3856 		if (sinfo->total_bytes - bytes_used < thresh)
3857 			return 1;
3858 	}
3859 
3860 	if (bytes_used + SZ_2M < mult_perc(sinfo->total_bytes, 80))
3861 		return 0;
3862 	return 1;
3863 }
3864 
btrfs_force_chunk_alloc(struct btrfs_trans_handle * trans,u64 type)3865 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3866 {
3867 	u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3868 
3869 	return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3870 }
3871 
do_chunk_alloc(struct btrfs_trans_handle * trans,u64 flags)3872 static struct btrfs_block_group *do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags)
3873 {
3874 	struct btrfs_block_group *bg;
3875 	int ret;
3876 
3877 	/*
3878 	 * Check if we have enough space in the system space info because we
3879 	 * will need to update device items in the chunk btree and insert a new
3880 	 * chunk item in the chunk btree as well. This will allocate a new
3881 	 * system block group if needed.
3882 	 */
3883 	check_system_chunk(trans, flags);
3884 
3885 	bg = btrfs_create_chunk(trans, flags);
3886 	if (IS_ERR(bg)) {
3887 		ret = PTR_ERR(bg);
3888 		goto out;
3889 	}
3890 
3891 	ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
3892 	/*
3893 	 * Normally we are not expected to fail with -ENOSPC here, since we have
3894 	 * previously reserved space in the system space_info and allocated one
3895 	 * new system chunk if necessary. However there are three exceptions:
3896 	 *
3897 	 * 1) We may have enough free space in the system space_info but all the
3898 	 *    existing system block groups have a profile which can not be used
3899 	 *    for extent allocation.
3900 	 *
3901 	 *    This happens when mounting in degraded mode. For example we have a
3902 	 *    RAID1 filesystem with 2 devices, lose one device and mount the fs
3903 	 *    using the other device in degraded mode. If we then allocate a chunk,
3904 	 *    we may have enough free space in the existing system space_info, but
3905 	 *    none of the block groups can be used for extent allocation since they
3906 	 *    have a RAID1 profile, and because we are in degraded mode with a
3907 	 *    single device, we are forced to allocate a new system chunk with a
3908 	 *    SINGLE profile. Making check_system_chunk() iterate over all system
3909 	 *    block groups and check if they have a usable profile and enough space
3910 	 *    can be slow on very large filesystems, so we tolerate the -ENOSPC and
3911 	 *    try again after forcing allocation of a new system chunk. Like this
3912 	 *    we avoid paying the cost of that search in normal circumstances, when
3913 	 *    we were not mounted in degraded mode;
3914 	 *
3915 	 * 2) We had enough free space info the system space_info, and one suitable
3916 	 *    block group to allocate from when we called check_system_chunk()
3917 	 *    above. However right after we called it, the only system block group
3918 	 *    with enough free space got turned into RO mode by a running scrub,
3919 	 *    and in this case we have to allocate a new one and retry. We only
3920 	 *    need do this allocate and retry once, since we have a transaction
3921 	 *    handle and scrub uses the commit root to search for block groups;
3922 	 *
3923 	 * 3) We had one system block group with enough free space when we called
3924 	 *    check_system_chunk(), but after that, right before we tried to
3925 	 *    allocate the last extent buffer we needed, a discard operation came
3926 	 *    in and it temporarily removed the last free space entry from the
3927 	 *    block group (discard removes a free space entry, discards it, and
3928 	 *    then adds back the entry to the block group cache).
3929 	 */
3930 	if (ret == -ENOSPC) {
3931 		const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info);
3932 		struct btrfs_block_group *sys_bg;
3933 
3934 		sys_bg = btrfs_create_chunk(trans, sys_flags);
3935 		if (IS_ERR(sys_bg)) {
3936 			ret = PTR_ERR(sys_bg);
3937 			btrfs_abort_transaction(trans, ret);
3938 			goto out;
3939 		}
3940 
3941 		ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3942 		if (ret) {
3943 			btrfs_abort_transaction(trans, ret);
3944 			goto out;
3945 		}
3946 
3947 		ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
3948 		if (ret) {
3949 			btrfs_abort_transaction(trans, ret);
3950 			goto out;
3951 		}
3952 	} else if (ret) {
3953 		btrfs_abort_transaction(trans, ret);
3954 		goto out;
3955 	}
3956 out:
3957 	btrfs_trans_release_chunk_metadata(trans);
3958 
3959 	if (ret)
3960 		return ERR_PTR(ret);
3961 
3962 	btrfs_get_block_group(bg);
3963 	return bg;
3964 }
3965 
3966 /*
3967  * Chunk allocation is done in 2 phases:
3968  *
3969  * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
3970  *    the chunk, the chunk mapping, create its block group and add the items
3971  *    that belong in the chunk btree to it - more specifically, we need to
3972  *    update device items in the chunk btree and add a new chunk item to it.
3973  *
3974  * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
3975  *    group item to the extent btree and the device extent items to the devices
3976  *    btree.
3977  *
3978  * This is done to prevent deadlocks. For example when COWing a node from the
3979  * extent btree we are holding a write lock on the node's parent and if we
3980  * trigger chunk allocation and attempted to insert the new block group item
3981  * in the extent btree right way, we could deadlock because the path for the
3982  * insertion can include that parent node. At first glance it seems impossible
3983  * to trigger chunk allocation after starting a transaction since tasks should
3984  * reserve enough transaction units (metadata space), however while that is true
3985  * most of the time, chunk allocation may still be triggered for several reasons:
3986  *
3987  * 1) When reserving metadata, we check if there is enough free space in the
3988  *    metadata space_info and therefore don't trigger allocation of a new chunk.
3989  *    However later when the task actually tries to COW an extent buffer from
3990  *    the extent btree or from the device btree for example, it is forced to
3991  *    allocate a new block group (chunk) because the only one that had enough
3992  *    free space was just turned to RO mode by a running scrub for example (or
3993  *    device replace, block group reclaim thread, etc), so we can not use it
3994  *    for allocating an extent and end up being forced to allocate a new one;
3995  *
3996  * 2) Because we only check that the metadata space_info has enough free bytes,
3997  *    we end up not allocating a new metadata chunk in that case. However if
3998  *    the filesystem was mounted in degraded mode, none of the existing block
3999  *    groups might be suitable for extent allocation due to their incompatible
4000  *    profile (for e.g. mounting a 2 devices filesystem, where all block groups
4001  *    use a RAID1 profile, in degraded mode using a single device). In this case
4002  *    when the task attempts to COW some extent buffer of the extent btree for
4003  *    example, it will trigger allocation of a new metadata block group with a
4004  *    suitable profile (SINGLE profile in the example of the degraded mount of
4005  *    the RAID1 filesystem);
4006  *
4007  * 3) The task has reserved enough transaction units / metadata space, but when
4008  *    it attempts to COW an extent buffer from the extent or device btree for
4009  *    example, it does not find any free extent in any metadata block group,
4010  *    therefore forced to try to allocate a new metadata block group.
4011  *    This is because some other task allocated all available extents in the
4012  *    meanwhile - this typically happens with tasks that don't reserve space
4013  *    properly, either intentionally or as a bug. One example where this is
4014  *    done intentionally is fsync, as it does not reserve any transaction units
4015  *    and ends up allocating a variable number of metadata extents for log
4016  *    tree extent buffers;
4017  *
4018  * 4) The task has reserved enough transaction units / metadata space, but right
4019  *    before it tries to allocate the last extent buffer it needs, a discard
4020  *    operation comes in and, temporarily, removes the last free space entry from
4021  *    the only metadata block group that had free space (discard starts by
4022  *    removing a free space entry from a block group, then does the discard
4023  *    operation and, once it's done, it adds back the free space entry to the
4024  *    block group).
4025  *
4026  * We also need this 2 phases setup when adding a device to a filesystem with
4027  * a seed device - we must create new metadata and system chunks without adding
4028  * any of the block group items to the chunk, extent and device btrees. If we
4029  * did not do it this way, we would get ENOSPC when attempting to update those
4030  * btrees, since all the chunks from the seed device are read-only.
4031  *
4032  * Phase 1 does the updates and insertions to the chunk btree because if we had
4033  * it done in phase 2 and have a thundering herd of tasks allocating chunks in
4034  * parallel, we risk having too many system chunks allocated by many tasks if
4035  * many tasks reach phase 1 without the previous ones completing phase 2. In the
4036  * extreme case this leads to exhaustion of the system chunk array in the
4037  * superblock. This is easier to trigger if using a btree node/leaf size of 64K
4038  * and with RAID filesystems (so we have more device items in the chunk btree).
4039  * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
4040  * the system chunk array due to concurrent allocations") provides more details.
4041  *
4042  * Allocation of system chunks does not happen through this function. A task that
4043  * needs to update the chunk btree (the only btree that uses system chunks), must
4044  * preallocate chunk space by calling either check_system_chunk() or
4045  * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or
4046  * metadata chunk or when removing a chunk, while the later is used before doing
4047  * a modification to the chunk btree - use cases for the later are adding,
4048  * removing and resizing a device as well as relocation of a system chunk.
4049  * See the comment below for more details.
4050  *
4051  * The reservation of system space, done through check_system_chunk(), as well
4052  * as all the updates and insertions into the chunk btree must be done while
4053  * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
4054  * an extent buffer from the chunks btree we never trigger allocation of a new
4055  * system chunk, which would result in a deadlock (trying to lock twice an
4056  * extent buffer of the chunk btree, first time before triggering the chunk
4057  * allocation and the second time during chunk allocation while attempting to
4058  * update the chunks btree). The system chunk array is also updated while holding
4059  * that mutex. The same logic applies to removing chunks - we must reserve system
4060  * space, update the chunk btree and the system chunk array in the superblock
4061  * while holding fs_info->chunk_mutex.
4062  *
4063  * This function, btrfs_chunk_alloc(), belongs to phase 1.
4064  *
4065  * If @force is CHUNK_ALLOC_FORCE:
4066  *    - return 1 if it successfully allocates a chunk,
4067  *    - return errors including -ENOSPC otherwise.
4068  * If @force is NOT CHUNK_ALLOC_FORCE:
4069  *    - return 0 if it doesn't need to allocate a new chunk,
4070  *    - return 1 if it successfully allocates a chunk,
4071  *    - return errors including -ENOSPC otherwise.
4072  */
btrfs_chunk_alloc(struct btrfs_trans_handle * trans,u64 flags,enum btrfs_chunk_alloc_enum force)4073 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
4074 		      enum btrfs_chunk_alloc_enum force)
4075 {
4076 	struct btrfs_fs_info *fs_info = trans->fs_info;
4077 	struct btrfs_space_info *space_info;
4078 	struct btrfs_block_group *ret_bg;
4079 	bool wait_for_alloc = false;
4080 	bool should_alloc = false;
4081 	bool from_extent_allocation = false;
4082 	int ret = 0;
4083 
4084 	if (force == CHUNK_ALLOC_FORCE_FOR_EXTENT) {
4085 		from_extent_allocation = true;
4086 		force = CHUNK_ALLOC_FORCE;
4087 	}
4088 
4089 	/* Don't re-enter if we're already allocating a chunk */
4090 	if (trans->allocating_chunk)
4091 		return -ENOSPC;
4092 	/*
4093 	 * Allocation of system chunks can not happen through this path, as we
4094 	 * could end up in a deadlock if we are allocating a data or metadata
4095 	 * chunk and there is another task modifying the chunk btree.
4096 	 *
4097 	 * This is because while we are holding the chunk mutex, we will attempt
4098 	 * to add the new chunk item to the chunk btree or update an existing
4099 	 * device item in the chunk btree, while the other task that is modifying
4100 	 * the chunk btree is attempting to COW an extent buffer while holding a
4101 	 * lock on it and on its parent - if the COW operation triggers a system
4102 	 * chunk allocation, then we can deadlock because we are holding the
4103 	 * chunk mutex and we may need to access that extent buffer or its parent
4104 	 * in order to add the chunk item or update a device item.
4105 	 *
4106 	 * Tasks that want to modify the chunk tree should reserve system space
4107 	 * before updating the chunk btree, by calling either
4108 	 * btrfs_reserve_chunk_metadata() or check_system_chunk().
4109 	 * It's possible that after a task reserves the space, it still ends up
4110 	 * here - this happens in the cases described above at do_chunk_alloc().
4111 	 * The task will have to either retry or fail.
4112 	 */
4113 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4114 		return -ENOSPC;
4115 
4116 	space_info = btrfs_find_space_info(fs_info, flags);
4117 	ASSERT(space_info);
4118 
4119 	do {
4120 		spin_lock(&space_info->lock);
4121 		if (force < space_info->force_alloc)
4122 			force = space_info->force_alloc;
4123 		should_alloc = should_alloc_chunk(fs_info, space_info, force);
4124 		if (space_info->full) {
4125 			/* No more free physical space */
4126 			if (should_alloc)
4127 				ret = -ENOSPC;
4128 			else
4129 				ret = 0;
4130 			spin_unlock(&space_info->lock);
4131 			return ret;
4132 		} else if (!should_alloc) {
4133 			spin_unlock(&space_info->lock);
4134 			return 0;
4135 		} else if (space_info->chunk_alloc) {
4136 			/*
4137 			 * Someone is already allocating, so we need to block
4138 			 * until this someone is finished and then loop to
4139 			 * recheck if we should continue with our allocation
4140 			 * attempt.
4141 			 */
4142 			wait_for_alloc = true;
4143 			force = CHUNK_ALLOC_NO_FORCE;
4144 			spin_unlock(&space_info->lock);
4145 			mutex_lock(&fs_info->chunk_mutex);
4146 			mutex_unlock(&fs_info->chunk_mutex);
4147 		} else {
4148 			/* Proceed with allocation */
4149 			space_info->chunk_alloc = 1;
4150 			wait_for_alloc = false;
4151 			spin_unlock(&space_info->lock);
4152 		}
4153 
4154 		cond_resched();
4155 	} while (wait_for_alloc);
4156 
4157 	mutex_lock(&fs_info->chunk_mutex);
4158 	trans->allocating_chunk = true;
4159 
4160 	/*
4161 	 * If we have mixed data/metadata chunks we want to make sure we keep
4162 	 * allocating mixed chunks instead of individual chunks.
4163 	 */
4164 	if (btrfs_mixed_space_info(space_info))
4165 		flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4166 
4167 	/*
4168 	 * if we're doing a data chunk, go ahead and make sure that
4169 	 * we keep a reasonable number of metadata chunks allocated in the
4170 	 * FS as well.
4171 	 */
4172 	if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4173 		fs_info->data_chunk_allocations++;
4174 		if (!(fs_info->data_chunk_allocations %
4175 		      fs_info->metadata_ratio))
4176 			force_metadata_allocation(fs_info);
4177 	}
4178 
4179 	ret_bg = do_chunk_alloc(trans, flags);
4180 	trans->allocating_chunk = false;
4181 
4182 	if (IS_ERR(ret_bg)) {
4183 		ret = PTR_ERR(ret_bg);
4184 	} else if (from_extent_allocation && (flags & BTRFS_BLOCK_GROUP_DATA)) {
4185 		/*
4186 		 * New block group is likely to be used soon. Try to activate
4187 		 * it now. Failure is OK for now.
4188 		 */
4189 		btrfs_zone_activate(ret_bg);
4190 	}
4191 
4192 	if (!ret)
4193 		btrfs_put_block_group(ret_bg);
4194 
4195 	spin_lock(&space_info->lock);
4196 	if (ret < 0) {
4197 		if (ret == -ENOSPC)
4198 			space_info->full = 1;
4199 		else
4200 			goto out;
4201 	} else {
4202 		ret = 1;
4203 		space_info->max_extent_size = 0;
4204 	}
4205 
4206 	space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4207 out:
4208 	space_info->chunk_alloc = 0;
4209 	spin_unlock(&space_info->lock);
4210 	mutex_unlock(&fs_info->chunk_mutex);
4211 
4212 	return ret;
4213 }
4214 
get_profile_num_devs(const struct btrfs_fs_info * fs_info,u64 type)4215 static u64 get_profile_num_devs(const struct btrfs_fs_info *fs_info, u64 type)
4216 {
4217 	u64 num_dev;
4218 
4219 	num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
4220 	if (!num_dev)
4221 		num_dev = fs_info->fs_devices->rw_devices;
4222 
4223 	return num_dev;
4224 }
4225 
reserve_chunk_space(struct btrfs_trans_handle * trans,u64 bytes,u64 type)4226 static void reserve_chunk_space(struct btrfs_trans_handle *trans,
4227 				u64 bytes,
4228 				u64 type)
4229 {
4230 	struct btrfs_fs_info *fs_info = trans->fs_info;
4231 	struct btrfs_space_info *info;
4232 	u64 left;
4233 	int ret = 0;
4234 
4235 	/*
4236 	 * Needed because we can end up allocating a system chunk and for an
4237 	 * atomic and race free space reservation in the chunk block reserve.
4238 	 */
4239 	lockdep_assert_held(&fs_info->chunk_mutex);
4240 
4241 	info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4242 	spin_lock(&info->lock);
4243 	left = info->total_bytes - btrfs_space_info_used(info, true);
4244 	spin_unlock(&info->lock);
4245 
4246 	if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4247 		btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
4248 			   left, bytes, type);
4249 		btrfs_dump_space_info(fs_info, info, 0, 0);
4250 	}
4251 
4252 	if (left < bytes) {
4253 		u64 flags = btrfs_system_alloc_profile(fs_info);
4254 		struct btrfs_block_group *bg;
4255 
4256 		/*
4257 		 * Ignore failure to create system chunk. We might end up not
4258 		 * needing it, as we might not need to COW all nodes/leafs from
4259 		 * the paths we visit in the chunk tree (they were already COWed
4260 		 * or created in the current transaction for example).
4261 		 */
4262 		bg = btrfs_create_chunk(trans, flags);
4263 		if (IS_ERR(bg)) {
4264 			ret = PTR_ERR(bg);
4265 		} else {
4266 			/*
4267 			 * We have a new chunk. We also need to activate it for
4268 			 * zoned filesystem.
4269 			 */
4270 			ret = btrfs_zoned_activate_one_bg(fs_info, info, true);
4271 			if (ret < 0)
4272 				return;
4273 
4274 			/*
4275 			 * If we fail to add the chunk item here, we end up
4276 			 * trying again at phase 2 of chunk allocation, at
4277 			 * btrfs_create_pending_block_groups(). So ignore
4278 			 * any error here. An ENOSPC here could happen, due to
4279 			 * the cases described at do_chunk_alloc() - the system
4280 			 * block group we just created was just turned into RO
4281 			 * mode by a scrub for example, or a running discard
4282 			 * temporarily removed its free space entries, etc.
4283 			 */
4284 			btrfs_chunk_alloc_add_chunk_item(trans, bg);
4285 		}
4286 	}
4287 
4288 	if (!ret) {
4289 		ret = btrfs_block_rsv_add(fs_info,
4290 					  &fs_info->chunk_block_rsv,
4291 					  bytes, BTRFS_RESERVE_NO_FLUSH);
4292 		if (!ret)
4293 			trans->chunk_bytes_reserved += bytes;
4294 	}
4295 }
4296 
4297 /*
4298  * Reserve space in the system space for allocating or removing a chunk.
4299  * The caller must be holding fs_info->chunk_mutex.
4300  */
check_system_chunk(struct btrfs_trans_handle * trans,u64 type)4301 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
4302 {
4303 	struct btrfs_fs_info *fs_info = trans->fs_info;
4304 	const u64 num_devs = get_profile_num_devs(fs_info, type);
4305 	u64 bytes;
4306 
4307 	/* num_devs device items to update and 1 chunk item to add or remove. */
4308 	bytes = btrfs_calc_metadata_size(fs_info, num_devs) +
4309 		btrfs_calc_insert_metadata_size(fs_info, 1);
4310 
4311 	reserve_chunk_space(trans, bytes, type);
4312 }
4313 
4314 /*
4315  * Reserve space in the system space, if needed, for doing a modification to the
4316  * chunk btree.
4317  *
4318  * @trans:		A transaction handle.
4319  * @is_item_insertion:	Indicate if the modification is for inserting a new item
4320  *			in the chunk btree or if it's for the deletion or update
4321  *			of an existing item.
4322  *
4323  * This is used in a context where we need to update the chunk btree outside
4324  * block group allocation and removal, to avoid a deadlock with a concurrent
4325  * task that is allocating a metadata or data block group and therefore needs to
4326  * update the chunk btree while holding the chunk mutex. After the update to the
4327  * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called.
4328  *
4329  */
btrfs_reserve_chunk_metadata(struct btrfs_trans_handle * trans,bool is_item_insertion)4330 void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans,
4331 				  bool is_item_insertion)
4332 {
4333 	struct btrfs_fs_info *fs_info = trans->fs_info;
4334 	u64 bytes;
4335 
4336 	if (is_item_insertion)
4337 		bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
4338 	else
4339 		bytes = btrfs_calc_metadata_size(fs_info, 1);
4340 
4341 	mutex_lock(&fs_info->chunk_mutex);
4342 	reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM);
4343 	mutex_unlock(&fs_info->chunk_mutex);
4344 }
4345 
btrfs_put_block_group_cache(struct btrfs_fs_info * info)4346 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
4347 {
4348 	struct btrfs_block_group *block_group;
4349 
4350 	block_group = btrfs_lookup_first_block_group(info, 0);
4351 	while (block_group) {
4352 		btrfs_wait_block_group_cache_done(block_group);
4353 		spin_lock(&block_group->lock);
4354 		if (test_and_clear_bit(BLOCK_GROUP_FLAG_IREF,
4355 				       &block_group->runtime_flags)) {
4356 			struct btrfs_inode *inode = block_group->inode;
4357 
4358 			block_group->inode = NULL;
4359 			spin_unlock(&block_group->lock);
4360 
4361 			ASSERT(block_group->io_ctl.inode == NULL);
4362 			iput(&inode->vfs_inode);
4363 		} else {
4364 			spin_unlock(&block_group->lock);
4365 		}
4366 		block_group = btrfs_next_block_group(block_group);
4367 	}
4368 }
4369 
4370 /*
4371  * Must be called only after stopping all workers, since we could have block
4372  * group caching kthreads running, and therefore they could race with us if we
4373  * freed the block groups before stopping them.
4374  */
btrfs_free_block_groups(struct btrfs_fs_info * info)4375 int btrfs_free_block_groups(struct btrfs_fs_info *info)
4376 {
4377 	struct btrfs_block_group *block_group;
4378 	struct btrfs_space_info *space_info;
4379 	struct btrfs_caching_control *caching_ctl;
4380 	struct rb_node *n;
4381 
4382 	if (btrfs_is_zoned(info)) {
4383 		if (info->active_meta_bg) {
4384 			btrfs_put_block_group(info->active_meta_bg);
4385 			info->active_meta_bg = NULL;
4386 		}
4387 		if (info->active_system_bg) {
4388 			btrfs_put_block_group(info->active_system_bg);
4389 			info->active_system_bg = NULL;
4390 		}
4391 	}
4392 
4393 	write_lock(&info->block_group_cache_lock);
4394 	while (!list_empty(&info->caching_block_groups)) {
4395 		caching_ctl = list_entry(info->caching_block_groups.next,
4396 					 struct btrfs_caching_control, list);
4397 		list_del(&caching_ctl->list);
4398 		btrfs_put_caching_control(caching_ctl);
4399 	}
4400 	write_unlock(&info->block_group_cache_lock);
4401 
4402 	spin_lock(&info->unused_bgs_lock);
4403 	while (!list_empty(&info->unused_bgs)) {
4404 		block_group = list_first_entry(&info->unused_bgs,
4405 					       struct btrfs_block_group,
4406 					       bg_list);
4407 		list_del_init(&block_group->bg_list);
4408 		btrfs_put_block_group(block_group);
4409 	}
4410 
4411 	while (!list_empty(&info->reclaim_bgs)) {
4412 		block_group = list_first_entry(&info->reclaim_bgs,
4413 					       struct btrfs_block_group,
4414 					       bg_list);
4415 		list_del_init(&block_group->bg_list);
4416 		btrfs_put_block_group(block_group);
4417 	}
4418 	spin_unlock(&info->unused_bgs_lock);
4419 
4420 	spin_lock(&info->zone_active_bgs_lock);
4421 	while (!list_empty(&info->zone_active_bgs)) {
4422 		block_group = list_first_entry(&info->zone_active_bgs,
4423 					       struct btrfs_block_group,
4424 					       active_bg_list);
4425 		list_del_init(&block_group->active_bg_list);
4426 		btrfs_put_block_group(block_group);
4427 	}
4428 	spin_unlock(&info->zone_active_bgs_lock);
4429 
4430 	write_lock(&info->block_group_cache_lock);
4431 	while ((n = rb_last(&info->block_group_cache_tree.rb_root)) != NULL) {
4432 		block_group = rb_entry(n, struct btrfs_block_group,
4433 				       cache_node);
4434 		rb_erase_cached(&block_group->cache_node,
4435 				&info->block_group_cache_tree);
4436 		RB_CLEAR_NODE(&block_group->cache_node);
4437 		write_unlock(&info->block_group_cache_lock);
4438 
4439 		down_write(&block_group->space_info->groups_sem);
4440 		list_del(&block_group->list);
4441 		up_write(&block_group->space_info->groups_sem);
4442 
4443 		/*
4444 		 * We haven't cached this block group, which means we could
4445 		 * possibly have excluded extents on this block group.
4446 		 */
4447 		if (block_group->cached == BTRFS_CACHE_NO ||
4448 		    block_group->cached == BTRFS_CACHE_ERROR)
4449 			btrfs_free_excluded_extents(block_group);
4450 
4451 		btrfs_remove_free_space_cache(block_group);
4452 		ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
4453 		ASSERT(list_empty(&block_group->dirty_list));
4454 		ASSERT(list_empty(&block_group->io_list));
4455 		ASSERT(list_empty(&block_group->bg_list));
4456 		ASSERT(refcount_read(&block_group->refs) == 1);
4457 		ASSERT(block_group->swap_extents == 0);
4458 		btrfs_put_block_group(block_group);
4459 
4460 		write_lock(&info->block_group_cache_lock);
4461 	}
4462 	write_unlock(&info->block_group_cache_lock);
4463 
4464 	btrfs_release_global_block_rsv(info);
4465 
4466 	while (!list_empty(&info->space_info)) {
4467 		space_info = list_entry(info->space_info.next,
4468 					struct btrfs_space_info,
4469 					list);
4470 
4471 		/*
4472 		 * Do not hide this behind enospc_debug, this is actually
4473 		 * important and indicates a real bug if this happens.
4474 		 */
4475 		if (WARN_ON(space_info->bytes_pinned > 0 ||
4476 			    space_info->bytes_may_use > 0))
4477 			btrfs_dump_space_info(info, space_info, 0, 0);
4478 
4479 		/*
4480 		 * If there was a failure to cleanup a log tree, very likely due
4481 		 * to an IO failure on a writeback attempt of one or more of its
4482 		 * extent buffers, we could not do proper (and cheap) unaccounting
4483 		 * of their reserved space, so don't warn on bytes_reserved > 0 in
4484 		 * that case.
4485 		 */
4486 		if (!(space_info->flags & BTRFS_BLOCK_GROUP_METADATA) ||
4487 		    !BTRFS_FS_LOG_CLEANUP_ERROR(info)) {
4488 			if (WARN_ON(space_info->bytes_reserved > 0))
4489 				btrfs_dump_space_info(info, space_info, 0, 0);
4490 		}
4491 
4492 		WARN_ON(space_info->reclaim_size > 0);
4493 		list_del(&space_info->list);
4494 		btrfs_sysfs_remove_space_info(space_info);
4495 	}
4496 	return 0;
4497 }
4498 
btrfs_freeze_block_group(struct btrfs_block_group * cache)4499 void btrfs_freeze_block_group(struct btrfs_block_group *cache)
4500 {
4501 	atomic_inc(&cache->frozen);
4502 }
4503 
btrfs_unfreeze_block_group(struct btrfs_block_group * block_group)4504 void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
4505 {
4506 	struct btrfs_fs_info *fs_info = block_group->fs_info;
4507 	bool cleanup;
4508 
4509 	spin_lock(&block_group->lock);
4510 	cleanup = (atomic_dec_and_test(&block_group->frozen) &&
4511 		   test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags));
4512 	spin_unlock(&block_group->lock);
4513 
4514 	if (cleanup) {
4515 		struct btrfs_chunk_map *map;
4516 
4517 		map = btrfs_find_chunk_map(fs_info, block_group->start, 1);
4518 		/* Logic error, can't happen. */
4519 		ASSERT(map);
4520 
4521 		btrfs_remove_chunk_map(fs_info, map);
4522 
4523 		/* Once for our lookup reference. */
4524 		btrfs_free_chunk_map(map);
4525 
4526 		/*
4527 		 * We may have left one free space entry and other possible
4528 		 * tasks trimming this block group have left 1 entry each one.
4529 		 * Free them if any.
4530 		 */
4531 		btrfs_remove_free_space_cache(block_group);
4532 	}
4533 }
4534 
btrfs_inc_block_group_swap_extents(struct btrfs_block_group * bg)4535 bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
4536 {
4537 	bool ret = true;
4538 
4539 	spin_lock(&bg->lock);
4540 	if (bg->ro)
4541 		ret = false;
4542 	else
4543 		bg->swap_extents++;
4544 	spin_unlock(&bg->lock);
4545 
4546 	return ret;
4547 }
4548 
btrfs_dec_block_group_swap_extents(struct btrfs_block_group * bg,int amount)4549 void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
4550 {
4551 	spin_lock(&bg->lock);
4552 	ASSERT(!bg->ro);
4553 	ASSERT(bg->swap_extents >= amount);
4554 	bg->swap_extents -= amount;
4555 	spin_unlock(&bg->lock);
4556 }
4557 
btrfs_calc_block_group_size_class(u64 size)4558 enum btrfs_block_group_size_class btrfs_calc_block_group_size_class(u64 size)
4559 {
4560 	if (size <= SZ_128K)
4561 		return BTRFS_BG_SZ_SMALL;
4562 	if (size <= SZ_8M)
4563 		return BTRFS_BG_SZ_MEDIUM;
4564 	return BTRFS_BG_SZ_LARGE;
4565 }
4566 
4567 /*
4568  * Handle a block group allocating an extent in a size class
4569  *
4570  * @bg:				The block group we allocated in.
4571  * @size_class:			The size class of the allocation.
4572  * @force_wrong_size_class:	Whether we are desperate enough to allow
4573  *				mismatched size classes.
4574  *
4575  * Returns: 0 if the size class was valid for this block_group, -EAGAIN in the
4576  * case of a race that leads to the wrong size class without
4577  * force_wrong_size_class set.
4578  *
4579  * find_free_extent will skip block groups with a mismatched size class until
4580  * it really needs to avoid ENOSPC. In that case it will set
4581  * force_wrong_size_class. However, if a block group is newly allocated and
4582  * doesn't yet have a size class, then it is possible for two allocations of
4583  * different sizes to race and both try to use it. The loser is caught here and
4584  * has to retry.
4585  */
btrfs_use_block_group_size_class(struct btrfs_block_group * bg,enum btrfs_block_group_size_class size_class,bool force_wrong_size_class)4586 int btrfs_use_block_group_size_class(struct btrfs_block_group *bg,
4587 				     enum btrfs_block_group_size_class size_class,
4588 				     bool force_wrong_size_class)
4589 {
4590 	ASSERT(size_class != BTRFS_BG_SZ_NONE);
4591 
4592 	/* The new allocation is in the right size class, do nothing */
4593 	if (bg->size_class == size_class)
4594 		return 0;
4595 	/*
4596 	 * The new allocation is in a mismatched size class.
4597 	 * This means one of two things:
4598 	 *
4599 	 * 1. Two tasks in find_free_extent for different size_classes raced
4600 	 *    and hit the same empty block_group. Make the loser try again.
4601 	 * 2. A call to find_free_extent got desperate enough to set
4602 	 *    'force_wrong_slab'. Don't change the size_class, but allow the
4603 	 *    allocation.
4604 	 */
4605 	if (bg->size_class != BTRFS_BG_SZ_NONE) {
4606 		if (force_wrong_size_class)
4607 			return 0;
4608 		return -EAGAIN;
4609 	}
4610 	/*
4611 	 * The happy new block group case: the new allocation is the first
4612 	 * one in the block_group so we set size_class.
4613 	 */
4614 	bg->size_class = size_class;
4615 
4616 	return 0;
4617 }
4618 
btrfs_block_group_should_use_size_class(const struct btrfs_block_group * bg)4619 bool btrfs_block_group_should_use_size_class(const struct btrfs_block_group *bg)
4620 {
4621 	if (btrfs_is_zoned(bg->fs_info))
4622 		return false;
4623 	if (!btrfs_is_block_group_data_only(bg))
4624 		return false;
4625 	return true;
4626 }
4627