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