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