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