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