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