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