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