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