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