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