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