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