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