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