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