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