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