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