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