1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/sizes.h>
4 #include <linux/list_sort.h>
7 #include "block-group.h"
8 #include "space-info.h"
10 #include "free-space-cache.h"
11 #include "free-space-tree.h"
13 #include "transaction.h"
14 #include "ref-verify.h"
17 #include "delalloc-space.h"
22 #include "accessors.h"
23 #include "extent-tree.h"
25 #ifdef CONFIG_BTRFS_DEBUG
26 int btrfs_should_fragment_free_space(struct btrfs_block_group *block_group)
28 struct btrfs_fs_info *fs_info = block_group->fs_info;
30 return (btrfs_test_opt(fs_info, FRAGMENT_METADATA) &&
31 block_group->flags & BTRFS_BLOCK_GROUP_METADATA) ||
32 (btrfs_test_opt(fs_info, FRAGMENT_DATA) &&
33 block_group->flags & BTRFS_BLOCK_GROUP_DATA);
38 * Return target flags in extended format or 0 if restripe for this chunk_type
41 * Should be called with balance_lock held
43 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
45 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
51 if (flags & BTRFS_BLOCK_GROUP_DATA &&
52 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
53 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
54 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
55 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
56 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
57 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
58 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
59 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
66 * @flags: available profiles in extended format (see ctree.h)
68 * Return reduced profile in chunk format. If profile changing is in progress
69 * (either running or paused) picks the target profile (if it's already
70 * available), otherwise falls back to plain reducing.
72 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
74 u64 num_devices = fs_info->fs_devices->rw_devices;
80 * See if restripe for this chunk_type is in progress, if so try to
81 * reduce to the target profile
83 spin_lock(&fs_info->balance_lock);
84 target = get_restripe_target(fs_info, flags);
86 spin_unlock(&fs_info->balance_lock);
87 return extended_to_chunk(target);
89 spin_unlock(&fs_info->balance_lock);
91 /* First, mask out the RAID levels which aren't possible */
92 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
93 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
94 allowed |= btrfs_raid_array[raid_type].bg_flag;
98 /* Select the highest-redundancy RAID level. */
99 if (allowed & BTRFS_BLOCK_GROUP_RAID1C4)
100 allowed = BTRFS_BLOCK_GROUP_RAID1C4;
101 else if (allowed & BTRFS_BLOCK_GROUP_RAID6)
102 allowed = BTRFS_BLOCK_GROUP_RAID6;
103 else if (allowed & BTRFS_BLOCK_GROUP_RAID1C3)
104 allowed = BTRFS_BLOCK_GROUP_RAID1C3;
105 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
106 allowed = BTRFS_BLOCK_GROUP_RAID5;
107 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
108 allowed = BTRFS_BLOCK_GROUP_RAID10;
109 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
110 allowed = BTRFS_BLOCK_GROUP_RAID1;
111 else if (allowed & BTRFS_BLOCK_GROUP_DUP)
112 allowed = BTRFS_BLOCK_GROUP_DUP;
113 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
114 allowed = BTRFS_BLOCK_GROUP_RAID0;
116 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
118 return extended_to_chunk(flags | allowed);
121 u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
128 seq = read_seqbegin(&fs_info->profiles_lock);
130 if (flags & BTRFS_BLOCK_GROUP_DATA)
131 flags |= fs_info->avail_data_alloc_bits;
132 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
133 flags |= fs_info->avail_system_alloc_bits;
134 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
135 flags |= fs_info->avail_metadata_alloc_bits;
136 } while (read_seqretry(&fs_info->profiles_lock, seq));
138 return btrfs_reduce_alloc_profile(fs_info, flags);
141 void btrfs_get_block_group(struct btrfs_block_group *cache)
143 refcount_inc(&cache->refs);
146 void btrfs_put_block_group(struct btrfs_block_group *cache)
148 if (refcount_dec_and_test(&cache->refs)) {
149 WARN_ON(cache->pinned > 0);
151 * If there was a failure to cleanup a log tree, very likely due
152 * to an IO failure on a writeback attempt of one or more of its
153 * extent buffers, we could not do proper (and cheap) unaccounting
154 * of their reserved space, so don't warn on reserved > 0 in that
157 if (!(cache->flags & BTRFS_BLOCK_GROUP_METADATA) ||
158 !BTRFS_FS_LOG_CLEANUP_ERROR(cache->fs_info))
159 WARN_ON(cache->reserved > 0);
162 * A block_group shouldn't be on the discard_list anymore.
163 * Remove the block_group from the discard_list to prevent us
164 * from causing a panic due to NULL pointer dereference.
166 if (WARN_ON(!list_empty(&cache->discard_list)))
167 btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
170 kfree(cache->free_space_ctl);
171 kfree(cache->physical_map);
177 * This adds the block group to the fs_info rb tree for the block group cache
179 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
180 struct btrfs_block_group *block_group)
183 struct rb_node *parent = NULL;
184 struct btrfs_block_group *cache;
185 bool leftmost = true;
187 ASSERT(block_group->length != 0);
189 write_lock(&info->block_group_cache_lock);
190 p = &info->block_group_cache_tree.rb_root.rb_node;
194 cache = rb_entry(parent, struct btrfs_block_group, cache_node);
195 if (block_group->start < cache->start) {
197 } else if (block_group->start > cache->start) {
201 write_unlock(&info->block_group_cache_lock);
206 rb_link_node(&block_group->cache_node, parent, p);
207 rb_insert_color_cached(&block_group->cache_node,
208 &info->block_group_cache_tree, leftmost);
210 write_unlock(&info->block_group_cache_lock);
216 * This will return the block group at or after bytenr if contains is 0, else
217 * it will return the block group that contains the bytenr
219 static struct btrfs_block_group *block_group_cache_tree_search(
220 struct btrfs_fs_info *info, u64 bytenr, int contains)
222 struct btrfs_block_group *cache, *ret = NULL;
226 read_lock(&info->block_group_cache_lock);
227 n = info->block_group_cache_tree.rb_root.rb_node;
230 cache = rb_entry(n, struct btrfs_block_group, cache_node);
231 end = cache->start + cache->length - 1;
232 start = cache->start;
234 if (bytenr < start) {
235 if (!contains && (!ret || start < ret->start))
238 } else if (bytenr > start) {
239 if (contains && bytenr <= end) {
250 btrfs_get_block_group(ret);
251 read_unlock(&info->block_group_cache_lock);
257 * Return the block group that starts at or after bytenr
259 struct btrfs_block_group *btrfs_lookup_first_block_group(
260 struct btrfs_fs_info *info, u64 bytenr)
262 return block_group_cache_tree_search(info, bytenr, 0);
266 * Return the block group that contains the given bytenr
268 struct btrfs_block_group *btrfs_lookup_block_group(
269 struct btrfs_fs_info *info, u64 bytenr)
271 return block_group_cache_tree_search(info, bytenr, 1);
274 struct btrfs_block_group *btrfs_next_block_group(
275 struct btrfs_block_group *cache)
277 struct btrfs_fs_info *fs_info = cache->fs_info;
278 struct rb_node *node;
280 read_lock(&fs_info->block_group_cache_lock);
282 /* If our block group was removed, we need a full search. */
283 if (RB_EMPTY_NODE(&cache->cache_node)) {
284 const u64 next_bytenr = cache->start + cache->length;
286 read_unlock(&fs_info->block_group_cache_lock);
287 btrfs_put_block_group(cache);
288 return btrfs_lookup_first_block_group(fs_info, next_bytenr);
290 node = rb_next(&cache->cache_node);
291 btrfs_put_block_group(cache);
293 cache = rb_entry(node, struct btrfs_block_group, cache_node);
294 btrfs_get_block_group(cache);
297 read_unlock(&fs_info->block_group_cache_lock);
302 * Check if we can do a NOCOW write for a given extent.
304 * @fs_info: The filesystem information object.
305 * @bytenr: Logical start address of the extent.
307 * Check if we can do a NOCOW write for the given extent, and increments the
308 * number of NOCOW writers in the block group that contains the extent, as long
309 * as the block group exists and it's currently not in read-only mode.
311 * Returns: A non-NULL block group pointer if we can do a NOCOW write, the caller
312 * is responsible for calling btrfs_dec_nocow_writers() later.
314 * Or NULL if we can not do a NOCOW write
316 struct btrfs_block_group *btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info,
319 struct btrfs_block_group *bg;
320 bool can_nocow = true;
322 bg = btrfs_lookup_block_group(fs_info, bytenr);
326 spin_lock(&bg->lock);
330 atomic_inc(&bg->nocow_writers);
331 spin_unlock(&bg->lock);
334 btrfs_put_block_group(bg);
338 /* No put on block group, done by btrfs_dec_nocow_writers(). */
343 * Decrement the number of NOCOW writers in a block group.
345 * This is meant to be called after a previous call to btrfs_inc_nocow_writers(),
346 * and on the block group returned by that call. Typically this is called after
347 * creating an ordered extent for a NOCOW write, to prevent races with scrub and
350 * After this call, the caller should not use the block group anymore. It it wants
351 * to use it, then it should get a reference on it before calling this function.
353 void btrfs_dec_nocow_writers(struct btrfs_block_group *bg)
355 if (atomic_dec_and_test(&bg->nocow_writers))
356 wake_up_var(&bg->nocow_writers);
358 /* For the lookup done by a previous call to btrfs_inc_nocow_writers(). */
359 btrfs_put_block_group(bg);
362 void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
364 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
367 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
370 struct btrfs_block_group *bg;
372 bg = btrfs_lookup_block_group(fs_info, start);
374 if (atomic_dec_and_test(&bg->reservations))
375 wake_up_var(&bg->reservations);
376 btrfs_put_block_group(bg);
379 void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
381 struct btrfs_space_info *space_info = bg->space_info;
385 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
389 * Our block group is read only but before we set it to read only,
390 * some task might have had allocated an extent from it already, but it
391 * has not yet created a respective ordered extent (and added it to a
392 * root's list of ordered extents).
393 * Therefore wait for any task currently allocating extents, since the
394 * block group's reservations counter is incremented while a read lock
395 * on the groups' semaphore is held and decremented after releasing
396 * the read access on that semaphore and creating the ordered extent.
398 down_write(&space_info->groups_sem);
399 up_write(&space_info->groups_sem);
401 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
404 struct btrfs_caching_control *btrfs_get_caching_control(
405 struct btrfs_block_group *cache)
407 struct btrfs_caching_control *ctl;
409 spin_lock(&cache->lock);
410 if (!cache->caching_ctl) {
411 spin_unlock(&cache->lock);
415 ctl = cache->caching_ctl;
416 refcount_inc(&ctl->count);
417 spin_unlock(&cache->lock);
421 void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
423 if (refcount_dec_and_test(&ctl->count))
428 * When we wait for progress in the block group caching, its because our
429 * allocation attempt failed at least once. So, we must sleep and let some
430 * progress happen before we try again.
432 * This function will sleep at least once waiting for new free space to show
433 * up, and then it will check the block group free space numbers for our min
434 * num_bytes. Another option is to have it go ahead and look in the rbtree for
435 * a free extent of a given size, but this is a good start.
437 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
438 * any of the information in this block group.
440 void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
443 struct btrfs_caching_control *caching_ctl;
445 caching_ctl = btrfs_get_caching_control(cache);
449 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
450 (cache->free_space_ctl->free_space >= num_bytes));
452 btrfs_put_caching_control(caching_ctl);
455 static int btrfs_caching_ctl_wait_done(struct btrfs_block_group *cache,
456 struct btrfs_caching_control *caching_ctl)
458 wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
459 return cache->cached == BTRFS_CACHE_ERROR ? -EIO : 0;
462 static int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
464 struct btrfs_caching_control *caching_ctl;
467 caching_ctl = btrfs_get_caching_control(cache);
469 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
470 ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
471 btrfs_put_caching_control(caching_ctl);
475 #ifdef CONFIG_BTRFS_DEBUG
476 static void fragment_free_space(struct btrfs_block_group *block_group)
478 struct btrfs_fs_info *fs_info = block_group->fs_info;
479 u64 start = block_group->start;
480 u64 len = block_group->length;
481 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
482 fs_info->nodesize : fs_info->sectorsize;
483 u64 step = chunk << 1;
485 while (len > chunk) {
486 btrfs_remove_free_space(block_group, start, chunk);
497 * This is only called by btrfs_cache_block_group, since we could have freed
498 * extents we need to check the pinned_extents for any extents that can't be
499 * used yet since their free space will be released as soon as the transaction
502 u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
504 struct btrfs_fs_info *info = block_group->fs_info;
505 u64 extent_start, extent_end, size, total_added = 0;
508 while (start < end) {
509 ret = find_first_extent_bit(&info->excluded_extents, start,
510 &extent_start, &extent_end,
511 EXTENT_DIRTY | EXTENT_UPTODATE,
516 if (extent_start <= start) {
517 start = extent_end + 1;
518 } else if (extent_start > start && extent_start < end) {
519 size = extent_start - start;
521 ret = btrfs_add_free_space_async_trimmed(block_group,
523 BUG_ON(ret); /* -ENOMEM or logic error */
524 start = extent_end + 1;
533 ret = btrfs_add_free_space_async_trimmed(block_group, start,
535 BUG_ON(ret); /* -ENOMEM or logic error */
542 * Get an arbitrary extent item index / max_index through the block group
544 * @block_group the block group to sample from
545 * @index: the integral step through the block group to grab from
546 * @max_index: the granularity of the sampling
547 * @key: return value parameter for the item we find
549 * Pre-conditions on indices:
550 * 0 <= index <= max_index
553 * Returns: 0 on success, 1 if the search didn't yield a useful item, negative
554 * error code on error.
556 static int sample_block_group_extent_item(struct btrfs_caching_control *caching_ctl,
557 struct btrfs_block_group *block_group,
558 int index, int max_index,
559 struct btrfs_key *found_key)
561 struct btrfs_fs_info *fs_info = block_group->fs_info;
562 struct btrfs_root *extent_root;
564 u64 search_end = block_group->start + block_group->length;
565 struct btrfs_path *path;
566 struct btrfs_key search_key;
570 ASSERT(index <= max_index);
571 ASSERT(max_index > 0);
572 lockdep_assert_held(&caching_ctl->mutex);
573 lockdep_assert_held_read(&fs_info->commit_root_sem);
575 path = btrfs_alloc_path();
579 extent_root = btrfs_extent_root(fs_info, max_t(u64, block_group->start,
580 BTRFS_SUPER_INFO_OFFSET));
582 path->skip_locking = 1;
583 path->search_commit_root = 1;
584 path->reada = READA_FORWARD;
586 search_offset = index * div_u64(block_group->length, max_index);
587 search_key.objectid = block_group->start + search_offset;
588 search_key.type = BTRFS_EXTENT_ITEM_KEY;
589 search_key.offset = 0;
591 btrfs_for_each_slot(extent_root, &search_key, found_key, path, ret) {
592 /* Success; sampled an extent item in the block group */
593 if (found_key->type == BTRFS_EXTENT_ITEM_KEY &&
594 found_key->objectid >= block_group->start &&
595 found_key->objectid + found_key->offset <= search_end)
598 /* We can't possibly find a valid extent item anymore */
599 if (found_key->objectid >= search_end) {
605 lockdep_assert_held(&caching_ctl->mutex);
606 lockdep_assert_held_read(&fs_info->commit_root_sem);
607 btrfs_free_path(path);
612 * Best effort attempt to compute a block group's size class while caching it.
614 * @block_group: the block group we are caching
616 * We cannot infer the size class while adding free space extents, because that
617 * logic doesn't care about contiguous file extents (it doesn't differentiate
618 * between a 100M extent and 100 contiguous 1M extents). So we need to read the
619 * file extent items. Reading all of them is quite wasteful, because usually
620 * only a handful are enough to give a good answer. Therefore, we just grab 5 of
621 * them at even steps through the block group and pick the smallest size class
622 * we see. Since size class is best effort, and not guaranteed in general,
623 * inaccuracy is acceptable.
625 * To be more explicit about why this algorithm makes sense:
627 * If we are caching in a block group from disk, then there are three major cases
629 * 1. the block group is well behaved and all extents in it are the same size
631 * 2. the block group is mostly one size class with rare exceptions for last
633 * 3. the block group was populated before size classes and can have a totally
634 * arbitrary mix of size classes.
636 * In case 1, looking at any extent in the block group will yield the correct
637 * result. For the mixed cases, taking the minimum size class seems like a good
638 * approximation, since gaps from frees will be usable to the size class. For
639 * 2., a small handful of file extents is likely to yield the right answer. For
640 * 3, we can either read every file extent, or admit that this is best effort
641 * anyway and try to stay fast.
643 * Returns: 0 on success, negative error code on error.
645 static int load_block_group_size_class(struct btrfs_caching_control *caching_ctl,
646 struct btrfs_block_group *block_group)
648 struct btrfs_fs_info *fs_info = block_group->fs_info;
649 struct btrfs_key key;
651 u64 min_size = block_group->length;
652 enum btrfs_block_group_size_class size_class = BTRFS_BG_SZ_NONE;
655 if (!btrfs_block_group_should_use_size_class(block_group))
658 lockdep_assert_held(&caching_ctl->mutex);
659 lockdep_assert_held_read(&fs_info->commit_root_sem);
660 for (i = 0; i < 5; ++i) {
661 ret = sample_block_group_extent_item(caching_ctl, block_group, i, 5, &key);
666 min_size = min_t(u64, min_size, key.offset);
667 size_class = btrfs_calc_block_group_size_class(min_size);
669 if (size_class != BTRFS_BG_SZ_NONE) {
670 spin_lock(&block_group->lock);
671 block_group->size_class = size_class;
672 spin_unlock(&block_group->lock);
678 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
680 struct btrfs_block_group *block_group = caching_ctl->block_group;
681 struct btrfs_fs_info *fs_info = block_group->fs_info;
682 struct btrfs_root *extent_root;
683 struct btrfs_path *path;
684 struct extent_buffer *leaf;
685 struct btrfs_key key;
692 path = btrfs_alloc_path();
696 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
697 extent_root = btrfs_extent_root(fs_info, last);
699 #ifdef CONFIG_BTRFS_DEBUG
701 * If we're fragmenting we don't want to make anybody think we can
702 * allocate from this block group until we've had a chance to fragment
705 if (btrfs_should_fragment_free_space(block_group))
709 * We don't want to deadlock with somebody trying to allocate a new
710 * extent for the extent root while also trying to search the extent
711 * root to add free space. So we skip locking and search the commit
712 * root, since its read-only
714 path->skip_locking = 1;
715 path->search_commit_root = 1;
716 path->reada = READA_FORWARD;
720 key.type = BTRFS_EXTENT_ITEM_KEY;
723 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
727 leaf = path->nodes[0];
728 nritems = btrfs_header_nritems(leaf);
731 if (btrfs_fs_closing(fs_info) > 1) {
736 if (path->slots[0] < nritems) {
737 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
739 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
743 if (need_resched() ||
744 rwsem_is_contended(&fs_info->commit_root_sem)) {
745 btrfs_release_path(path);
746 up_read(&fs_info->commit_root_sem);
747 mutex_unlock(&caching_ctl->mutex);
749 mutex_lock(&caching_ctl->mutex);
750 down_read(&fs_info->commit_root_sem);
754 ret = btrfs_next_leaf(extent_root, path);
759 leaf = path->nodes[0];
760 nritems = btrfs_header_nritems(leaf);
764 if (key.objectid < last) {
767 key.type = BTRFS_EXTENT_ITEM_KEY;
768 btrfs_release_path(path);
772 if (key.objectid < block_group->start) {
777 if (key.objectid >= block_group->start + block_group->length)
780 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
781 key.type == BTRFS_METADATA_ITEM_KEY) {
782 total_found += add_new_free_space(block_group, last,
784 if (key.type == BTRFS_METADATA_ITEM_KEY)
785 last = key.objectid +
788 last = key.objectid + key.offset;
790 if (total_found > CACHING_CTL_WAKE_UP) {
793 wake_up(&caching_ctl->wait);
800 total_found += add_new_free_space(block_group, last,
801 block_group->start + block_group->length);
804 btrfs_free_path(path);
808 static noinline void caching_thread(struct btrfs_work *work)
810 struct btrfs_block_group *block_group;
811 struct btrfs_fs_info *fs_info;
812 struct btrfs_caching_control *caching_ctl;
815 caching_ctl = container_of(work, struct btrfs_caching_control, work);
816 block_group = caching_ctl->block_group;
817 fs_info = block_group->fs_info;
819 mutex_lock(&caching_ctl->mutex);
820 down_read(&fs_info->commit_root_sem);
822 load_block_group_size_class(caching_ctl, block_group);
823 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
824 ret = load_free_space_cache(block_group);
831 * We failed to load the space cache, set ourselves to
832 * CACHE_STARTED and carry on.
834 spin_lock(&block_group->lock);
835 block_group->cached = BTRFS_CACHE_STARTED;
836 spin_unlock(&block_group->lock);
837 wake_up(&caching_ctl->wait);
841 * If we are in the transaction that populated the free space tree we
842 * can't actually cache from the free space tree as our commit root and
843 * real root are the same, so we could change the contents of the blocks
844 * while caching. Instead do the slow caching in this case, and after
845 * the transaction has committed we will be safe.
847 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
848 !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
849 ret = load_free_space_tree(caching_ctl);
851 ret = load_extent_tree_free(caching_ctl);
853 spin_lock(&block_group->lock);
854 block_group->caching_ctl = NULL;
855 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
856 spin_unlock(&block_group->lock);
858 #ifdef CONFIG_BTRFS_DEBUG
859 if (btrfs_should_fragment_free_space(block_group)) {
862 spin_lock(&block_group->space_info->lock);
863 spin_lock(&block_group->lock);
864 bytes_used = block_group->length - block_group->used;
865 block_group->space_info->bytes_used += bytes_used >> 1;
866 spin_unlock(&block_group->lock);
867 spin_unlock(&block_group->space_info->lock);
868 fragment_free_space(block_group);
872 up_read(&fs_info->commit_root_sem);
873 btrfs_free_excluded_extents(block_group);
874 mutex_unlock(&caching_ctl->mutex);
876 wake_up(&caching_ctl->wait);
878 btrfs_put_caching_control(caching_ctl);
879 btrfs_put_block_group(block_group);
882 int btrfs_cache_block_group(struct btrfs_block_group *cache, bool wait)
884 struct btrfs_fs_info *fs_info = cache->fs_info;
885 struct btrfs_caching_control *caching_ctl = NULL;
888 /* Allocator for zoned filesystems does not use the cache at all */
889 if (btrfs_is_zoned(fs_info))
892 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
896 INIT_LIST_HEAD(&caching_ctl->list);
897 mutex_init(&caching_ctl->mutex);
898 init_waitqueue_head(&caching_ctl->wait);
899 caching_ctl->block_group = cache;
900 refcount_set(&caching_ctl->count, 2);
901 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
903 spin_lock(&cache->lock);
904 if (cache->cached != BTRFS_CACHE_NO) {
907 caching_ctl = cache->caching_ctl;
909 refcount_inc(&caching_ctl->count);
910 spin_unlock(&cache->lock);
913 WARN_ON(cache->caching_ctl);
914 cache->caching_ctl = caching_ctl;
915 cache->cached = BTRFS_CACHE_STARTED;
916 spin_unlock(&cache->lock);
918 write_lock(&fs_info->block_group_cache_lock);
919 refcount_inc(&caching_ctl->count);
920 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
921 write_unlock(&fs_info->block_group_cache_lock);
923 btrfs_get_block_group(cache);
925 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
927 if (wait && caching_ctl)
928 ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
930 btrfs_put_caching_control(caching_ctl);
935 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
937 u64 extra_flags = chunk_to_extended(flags) &
938 BTRFS_EXTENDED_PROFILE_MASK;
940 write_seqlock(&fs_info->profiles_lock);
941 if (flags & BTRFS_BLOCK_GROUP_DATA)
942 fs_info->avail_data_alloc_bits &= ~extra_flags;
943 if (flags & BTRFS_BLOCK_GROUP_METADATA)
944 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
945 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
946 fs_info->avail_system_alloc_bits &= ~extra_flags;
947 write_sequnlock(&fs_info->profiles_lock);
951 * Clear incompat bits for the following feature(s):
953 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
954 * in the whole filesystem
956 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
958 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
960 bool found_raid56 = false;
961 bool found_raid1c34 = false;
963 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
964 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
965 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
966 struct list_head *head = &fs_info->space_info;
967 struct btrfs_space_info *sinfo;
969 list_for_each_entry_rcu(sinfo, head, list) {
970 down_read(&sinfo->groups_sem);
971 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
973 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
975 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
976 found_raid1c34 = true;
977 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
978 found_raid1c34 = true;
979 up_read(&sinfo->groups_sem);
982 btrfs_clear_fs_incompat(fs_info, RAID56);
984 btrfs_clear_fs_incompat(fs_info, RAID1C34);
988 static int remove_block_group_item(struct btrfs_trans_handle *trans,
989 struct btrfs_path *path,
990 struct btrfs_block_group *block_group)
992 struct btrfs_fs_info *fs_info = trans->fs_info;
993 struct btrfs_root *root;
994 struct btrfs_key key;
997 root = btrfs_block_group_root(fs_info);
998 key.objectid = block_group->start;
999 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
1000 key.offset = block_group->length;
1002 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1008 ret = btrfs_del_item(trans, root, path);
1012 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
1013 u64 group_start, struct extent_map *em)
1015 struct btrfs_fs_info *fs_info = trans->fs_info;
1016 struct btrfs_path *path;
1017 struct btrfs_block_group *block_group;
1018 struct btrfs_free_cluster *cluster;
1019 struct inode *inode;
1020 struct kobject *kobj = NULL;
1024 struct btrfs_caching_control *caching_ctl = NULL;
1026 bool remove_rsv = false;
1028 block_group = btrfs_lookup_block_group(fs_info, group_start);
1029 BUG_ON(!block_group);
1030 BUG_ON(!block_group->ro);
1032 trace_btrfs_remove_block_group(block_group);
1034 * Free the reserved super bytes from this block group before
1037 btrfs_free_excluded_extents(block_group);
1038 btrfs_free_ref_tree_range(fs_info, block_group->start,
1039 block_group->length);
1041 index = btrfs_bg_flags_to_raid_index(block_group->flags);
1042 factor = btrfs_bg_type_to_factor(block_group->flags);
1044 /* make sure this block group isn't part of an allocation cluster */
1045 cluster = &fs_info->data_alloc_cluster;
1046 spin_lock(&cluster->refill_lock);
1047 btrfs_return_cluster_to_free_space(block_group, cluster);
1048 spin_unlock(&cluster->refill_lock);
1051 * make sure this block group isn't part of a metadata
1052 * allocation cluster
1054 cluster = &fs_info->meta_alloc_cluster;
1055 spin_lock(&cluster->refill_lock);
1056 btrfs_return_cluster_to_free_space(block_group, cluster);
1057 spin_unlock(&cluster->refill_lock);
1059 btrfs_clear_treelog_bg(block_group);
1060 btrfs_clear_data_reloc_bg(block_group);
1062 path = btrfs_alloc_path();
1069 * get the inode first so any iput calls done for the io_list
1070 * aren't the final iput (no unlinks allowed now)
1072 inode = lookup_free_space_inode(block_group, path);
1074 mutex_lock(&trans->transaction->cache_write_mutex);
1076 * Make sure our free space cache IO is done before removing the
1079 spin_lock(&trans->transaction->dirty_bgs_lock);
1080 if (!list_empty(&block_group->io_list)) {
1081 list_del_init(&block_group->io_list);
1083 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
1085 spin_unlock(&trans->transaction->dirty_bgs_lock);
1086 btrfs_wait_cache_io(trans, block_group, path);
1087 btrfs_put_block_group(block_group);
1088 spin_lock(&trans->transaction->dirty_bgs_lock);
1091 if (!list_empty(&block_group->dirty_list)) {
1092 list_del_init(&block_group->dirty_list);
1094 btrfs_put_block_group(block_group);
1096 spin_unlock(&trans->transaction->dirty_bgs_lock);
1097 mutex_unlock(&trans->transaction->cache_write_mutex);
1099 ret = btrfs_remove_free_space_inode(trans, inode, block_group);
1103 write_lock(&fs_info->block_group_cache_lock);
1104 rb_erase_cached(&block_group->cache_node,
1105 &fs_info->block_group_cache_tree);
1106 RB_CLEAR_NODE(&block_group->cache_node);
1108 /* Once for the block groups rbtree */
1109 btrfs_put_block_group(block_group);
1111 write_unlock(&fs_info->block_group_cache_lock);
1113 down_write(&block_group->space_info->groups_sem);
1115 * we must use list_del_init so people can check to see if they
1116 * are still on the list after taking the semaphore
1118 list_del_init(&block_group->list);
1119 if (list_empty(&block_group->space_info->block_groups[index])) {
1120 kobj = block_group->space_info->block_group_kobjs[index];
1121 block_group->space_info->block_group_kobjs[index] = NULL;
1122 clear_avail_alloc_bits(fs_info, block_group->flags);
1124 up_write(&block_group->space_info->groups_sem);
1125 clear_incompat_bg_bits(fs_info, block_group->flags);
1131 if (block_group->cached == BTRFS_CACHE_STARTED)
1132 btrfs_wait_block_group_cache_done(block_group);
1134 write_lock(&fs_info->block_group_cache_lock);
1135 caching_ctl = btrfs_get_caching_control(block_group);
1137 struct btrfs_caching_control *ctl;
1139 list_for_each_entry(ctl, &fs_info->caching_block_groups, list) {
1140 if (ctl->block_group == block_group) {
1142 refcount_inc(&caching_ctl->count);
1148 list_del_init(&caching_ctl->list);
1149 write_unlock(&fs_info->block_group_cache_lock);
1152 /* Once for the caching bgs list and once for us. */
1153 btrfs_put_caching_control(caching_ctl);
1154 btrfs_put_caching_control(caching_ctl);
1157 spin_lock(&trans->transaction->dirty_bgs_lock);
1158 WARN_ON(!list_empty(&block_group->dirty_list));
1159 WARN_ON(!list_empty(&block_group->io_list));
1160 spin_unlock(&trans->transaction->dirty_bgs_lock);
1162 btrfs_remove_free_space_cache(block_group);
1164 spin_lock(&block_group->space_info->lock);
1165 list_del_init(&block_group->ro_list);
1167 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1168 WARN_ON(block_group->space_info->total_bytes
1169 < block_group->length);
1170 WARN_ON(block_group->space_info->bytes_readonly
1171 < block_group->length - block_group->zone_unusable);
1172 WARN_ON(block_group->space_info->bytes_zone_unusable
1173 < block_group->zone_unusable);
1174 WARN_ON(block_group->space_info->disk_total
1175 < block_group->length * factor);
1177 block_group->space_info->total_bytes -= block_group->length;
1178 block_group->space_info->bytes_readonly -=
1179 (block_group->length - block_group->zone_unusable);
1180 block_group->space_info->bytes_zone_unusable -=
1181 block_group->zone_unusable;
1182 block_group->space_info->disk_total -= block_group->length * factor;
1184 spin_unlock(&block_group->space_info->lock);
1187 * Remove the free space for the block group from the free space tree
1188 * and the block group's item from the extent tree before marking the
1189 * block group as removed. This is to prevent races with tasks that
1190 * freeze and unfreeze a block group, this task and another task
1191 * allocating a new block group - the unfreeze task ends up removing
1192 * the block group's extent map before the task calling this function
1193 * deletes the block group item from the extent tree, allowing for
1194 * another task to attempt to create another block group with the same
1195 * item key (and failing with -EEXIST and a transaction abort).
1197 ret = remove_block_group_free_space(trans, block_group);
1201 ret = remove_block_group_item(trans, path, block_group);
1205 spin_lock(&block_group->lock);
1206 set_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags);
1209 * At this point trimming or scrub can't start on this block group,
1210 * because we removed the block group from the rbtree
1211 * fs_info->block_group_cache_tree so no one can't find it anymore and
1212 * even if someone already got this block group before we removed it
1213 * from the rbtree, they have already incremented block_group->frozen -
1214 * if they didn't, for the trimming case they won't find any free space
1215 * entries because we already removed them all when we called
1216 * btrfs_remove_free_space_cache().
1218 * And we must not remove the extent map from the fs_info->mapping_tree
1219 * to prevent the same logical address range and physical device space
1220 * ranges from being reused for a new block group. This is needed to
1221 * avoid races with trimming and scrub.
1223 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1224 * completely transactionless, so while it is trimming a range the
1225 * currently running transaction might finish and a new one start,
1226 * allowing for new block groups to be created that can reuse the same
1227 * physical device locations unless we take this special care.
1229 * There may also be an implicit trim operation if the file system
1230 * is mounted with -odiscard. The same protections must remain
1231 * in place until the extents have been discarded completely when
1232 * the transaction commit has completed.
1234 remove_em = (atomic_read(&block_group->frozen) == 0);
1235 spin_unlock(&block_group->lock);
1238 struct extent_map_tree *em_tree;
1240 em_tree = &fs_info->mapping_tree;
1241 write_lock(&em_tree->lock);
1242 remove_extent_mapping(em_tree, em);
1243 write_unlock(&em_tree->lock);
1244 /* once for the tree */
1245 free_extent_map(em);
1249 /* Once for the lookup reference */
1250 btrfs_put_block_group(block_group);
1252 btrfs_delayed_refs_rsv_release(fs_info, 1);
1253 btrfs_free_path(path);
1257 struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1258 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1260 struct btrfs_root *root = btrfs_block_group_root(fs_info);
1261 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1262 struct extent_map *em;
1263 struct map_lookup *map;
1264 unsigned int num_items;
1266 read_lock(&em_tree->lock);
1267 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1268 read_unlock(&em_tree->lock);
1269 ASSERT(em && em->start == chunk_offset);
1272 * We need to reserve 3 + N units from the metadata space info in order
1273 * to remove a block group (done at btrfs_remove_chunk() and at
1274 * btrfs_remove_block_group()), which are used for:
1276 * 1 unit for adding the free space inode's orphan (located in the tree
1278 * 1 unit for deleting the block group item (located in the extent
1280 * 1 unit for deleting the free space item (located in tree of tree
1282 * N units for deleting N device extent items corresponding to each
1283 * stripe (located in the device tree).
1285 * In order to remove a block group we also need to reserve units in the
1286 * system space info in order to update the chunk tree (update one or
1287 * more device items and remove one chunk item), but this is done at
1288 * btrfs_remove_chunk() through a call to check_system_chunk().
1290 map = em->map_lookup;
1291 num_items = 3 + map->num_stripes;
1292 free_extent_map(em);
1294 return btrfs_start_transaction_fallback_global_rsv(root, num_items);
1298 * Mark block group @cache read-only, so later write won't happen to block
1301 * If @force is not set, this function will only mark the block group readonly
1302 * if we have enough free space (1M) in other metadata/system block groups.
1303 * If @force is not set, this function will mark the block group readonly
1304 * without checking free space.
1306 * NOTE: This function doesn't care if other block groups can contain all the
1307 * data in this block group. That check should be done by relocation routine,
1308 * not this function.
1310 static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
1312 struct btrfs_space_info *sinfo = cache->space_info;
1316 spin_lock(&sinfo->lock);
1317 spin_lock(&cache->lock);
1319 if (cache->swap_extents) {
1330 num_bytes = cache->length - cache->reserved - cache->pinned -
1331 cache->bytes_super - cache->zone_unusable - cache->used;
1334 * Data never overcommits, even in mixed mode, so do just the straight
1335 * check of left over space in how much we have allocated.
1339 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1340 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1343 * Here we make sure if we mark this bg RO, we still have enough
1344 * free space as buffer.
1346 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1350 * We overcommit metadata, so we need to do the
1351 * btrfs_can_overcommit check here, and we need to pass in
1352 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1353 * leeway to allow us to mark this block group as read only.
1355 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1356 BTRFS_RESERVE_NO_FLUSH))
1361 sinfo->bytes_readonly += num_bytes;
1362 if (btrfs_is_zoned(cache->fs_info)) {
1363 /* Migrate zone_unusable bytes to readonly */
1364 sinfo->bytes_readonly += cache->zone_unusable;
1365 sinfo->bytes_zone_unusable -= cache->zone_unusable;
1366 cache->zone_unusable = 0;
1369 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
1372 spin_unlock(&cache->lock);
1373 spin_unlock(&sinfo->lock);
1374 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1375 btrfs_info(cache->fs_info,
1376 "unable to make block group %llu ro", cache->start);
1377 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1382 static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1383 struct btrfs_block_group *bg)
1385 struct btrfs_fs_info *fs_info = bg->fs_info;
1386 struct btrfs_transaction *prev_trans = NULL;
1387 const u64 start = bg->start;
1388 const u64 end = start + bg->length - 1;
1391 spin_lock(&fs_info->trans_lock);
1392 if (trans->transaction->list.prev != &fs_info->trans_list) {
1393 prev_trans = list_last_entry(&trans->transaction->list,
1394 struct btrfs_transaction, list);
1395 refcount_inc(&prev_trans->use_count);
1397 spin_unlock(&fs_info->trans_lock);
1400 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1401 * btrfs_finish_extent_commit(). If we are at transaction N, another
1402 * task might be running finish_extent_commit() for the previous
1403 * transaction N - 1, and have seen a range belonging to the block
1404 * group in pinned_extents before we were able to clear the whole block
1405 * group range from pinned_extents. This means that task can lookup for
1406 * the block group after we unpinned it from pinned_extents and removed
1407 * it, leading to a BUG_ON() at unpin_extent_range().
1409 mutex_lock(&fs_info->unused_bg_unpin_mutex);
1411 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1417 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
1420 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1422 btrfs_put_transaction(prev_trans);
1428 * Process the unused_bgs list and remove any that don't have any allocated
1429 * space inside of them.
1431 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1433 struct btrfs_block_group *block_group;
1434 struct btrfs_space_info *space_info;
1435 struct btrfs_trans_handle *trans;
1436 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1439 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1442 if (btrfs_fs_closing(fs_info))
1446 * Long running balances can keep us blocked here for eternity, so
1447 * simply skip deletion if we're unable to get the mutex.
1449 if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
1452 spin_lock(&fs_info->unused_bgs_lock);
1453 while (!list_empty(&fs_info->unused_bgs)) {
1456 block_group = list_first_entry(&fs_info->unused_bgs,
1457 struct btrfs_block_group,
1459 list_del_init(&block_group->bg_list);
1461 space_info = block_group->space_info;
1463 if (ret || btrfs_mixed_space_info(space_info)) {
1464 btrfs_put_block_group(block_group);
1467 spin_unlock(&fs_info->unused_bgs_lock);
1469 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1471 /* Don't want to race with allocators so take the groups_sem */
1472 down_write(&space_info->groups_sem);
1475 * Async discard moves the final block group discard to be prior
1476 * to the unused_bgs code path. Therefore, if it's not fully
1477 * trimmed, punt it back to the async discard lists.
1479 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1480 !btrfs_is_free_space_trimmed(block_group)) {
1481 trace_btrfs_skip_unused_block_group(block_group);
1482 up_write(&space_info->groups_sem);
1483 /* Requeue if we failed because of async discard */
1484 btrfs_discard_queue_work(&fs_info->discard_ctl,
1489 spin_lock(&block_group->lock);
1490 if (block_group->reserved || block_group->pinned ||
1491 block_group->used || block_group->ro ||
1492 list_is_singular(&block_group->list)) {
1494 * We want to bail if we made new allocations or have
1495 * outstanding allocations in this block group. We do
1496 * the ro check in case balance is currently acting on
1499 trace_btrfs_skip_unused_block_group(block_group);
1500 spin_unlock(&block_group->lock);
1501 up_write(&space_info->groups_sem);
1504 spin_unlock(&block_group->lock);
1506 /* We don't want to force the issue, only flip if it's ok. */
1507 ret = inc_block_group_ro(block_group, 0);
1508 up_write(&space_info->groups_sem);
1514 ret = btrfs_zone_finish(block_group);
1516 btrfs_dec_block_group_ro(block_group);
1523 * Want to do this before we do anything else so we can recover
1524 * properly if we fail to join the transaction.
1526 trans = btrfs_start_trans_remove_block_group(fs_info,
1527 block_group->start);
1528 if (IS_ERR(trans)) {
1529 btrfs_dec_block_group_ro(block_group);
1530 ret = PTR_ERR(trans);
1535 * We could have pending pinned extents for this block group,
1536 * just delete them, we don't care about them anymore.
1538 if (!clean_pinned_extents(trans, block_group)) {
1539 btrfs_dec_block_group_ro(block_group);
1544 * At this point, the block_group is read only and should fail
1545 * new allocations. However, btrfs_finish_extent_commit() can
1546 * cause this block_group to be placed back on the discard
1547 * lists because now the block_group isn't fully discarded.
1548 * Bail here and try again later after discarding everything.
1550 spin_lock(&fs_info->discard_ctl.lock);
1551 if (!list_empty(&block_group->discard_list)) {
1552 spin_unlock(&fs_info->discard_ctl.lock);
1553 btrfs_dec_block_group_ro(block_group);
1554 btrfs_discard_queue_work(&fs_info->discard_ctl,
1558 spin_unlock(&fs_info->discard_ctl.lock);
1560 /* Reset pinned so btrfs_put_block_group doesn't complain */
1561 spin_lock(&space_info->lock);
1562 spin_lock(&block_group->lock);
1564 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1565 -block_group->pinned);
1566 space_info->bytes_readonly += block_group->pinned;
1567 block_group->pinned = 0;
1569 spin_unlock(&block_group->lock);
1570 spin_unlock(&space_info->lock);
1573 * The normal path here is an unused block group is passed here,
1574 * then trimming is handled in the transaction commit path.
1575 * Async discard interposes before this to do the trimming
1576 * before coming down the unused block group path as trimming
1577 * will no longer be done later in the transaction commit path.
1579 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1583 * DISCARD can flip during remount. On zoned filesystems, we
1584 * need to reset sequential-required zones.
1586 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) ||
1587 btrfs_is_zoned(fs_info);
1589 /* Implicit trim during transaction commit. */
1591 btrfs_freeze_block_group(block_group);
1594 * Btrfs_remove_chunk will abort the transaction if things go
1597 ret = btrfs_remove_chunk(trans, block_group->start);
1601 btrfs_unfreeze_block_group(block_group);
1606 * If we're not mounted with -odiscard, we can just forget
1607 * about this block group. Otherwise we'll need to wait
1608 * until transaction commit to do the actual discard.
1611 spin_lock(&fs_info->unused_bgs_lock);
1613 * A concurrent scrub might have added us to the list
1614 * fs_info->unused_bgs, so use a list_move operation
1615 * to add the block group to the deleted_bgs list.
1617 list_move(&block_group->bg_list,
1618 &trans->transaction->deleted_bgs);
1619 spin_unlock(&fs_info->unused_bgs_lock);
1620 btrfs_get_block_group(block_group);
1623 btrfs_end_transaction(trans);
1625 btrfs_put_block_group(block_group);
1626 spin_lock(&fs_info->unused_bgs_lock);
1628 spin_unlock(&fs_info->unused_bgs_lock);
1629 mutex_unlock(&fs_info->reclaim_bgs_lock);
1633 btrfs_end_transaction(trans);
1634 mutex_unlock(&fs_info->reclaim_bgs_lock);
1635 btrfs_put_block_group(block_group);
1636 btrfs_discard_punt_unused_bgs_list(fs_info);
1639 void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1641 struct btrfs_fs_info *fs_info = bg->fs_info;
1643 trace_btrfs_add_unused_block_group(bg);
1644 spin_lock(&fs_info->unused_bgs_lock);
1645 if (list_empty(&bg->bg_list)) {
1646 btrfs_get_block_group(bg);
1647 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1649 /* Pull out the block group from the reclaim_bgs list. */
1650 list_move_tail(&bg->bg_list, &fs_info->unused_bgs);
1652 spin_unlock(&fs_info->unused_bgs_lock);
1656 * We want block groups with a low number of used bytes to be in the beginning
1657 * of the list, so they will get reclaimed first.
1659 static int reclaim_bgs_cmp(void *unused, const struct list_head *a,
1660 const struct list_head *b)
1662 const struct btrfs_block_group *bg1, *bg2;
1664 bg1 = list_entry(a, struct btrfs_block_group, bg_list);
1665 bg2 = list_entry(b, struct btrfs_block_group, bg_list);
1667 return bg1->used > bg2->used;
1670 static inline bool btrfs_should_reclaim(struct btrfs_fs_info *fs_info)
1672 if (btrfs_is_zoned(fs_info))
1673 return btrfs_zoned_should_reclaim(fs_info);
1677 static bool should_reclaim_block_group(struct btrfs_block_group *bg, u64 bytes_freed)
1679 const struct btrfs_space_info *space_info = bg->space_info;
1680 const int reclaim_thresh = READ_ONCE(space_info->bg_reclaim_threshold);
1681 const u64 new_val = bg->used;
1682 const u64 old_val = new_val + bytes_freed;
1685 if (reclaim_thresh == 0)
1688 thresh = mult_perc(bg->length, reclaim_thresh);
1691 * If we were below the threshold before don't reclaim, we are likely a
1692 * brand new block group and we don't want to relocate new block groups.
1694 if (old_val < thresh)
1696 if (new_val >= thresh)
1701 void btrfs_reclaim_bgs_work(struct work_struct *work)
1703 struct btrfs_fs_info *fs_info =
1704 container_of(work, struct btrfs_fs_info, reclaim_bgs_work);
1705 struct btrfs_block_group *bg;
1706 struct btrfs_space_info *space_info;
1708 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1711 if (btrfs_fs_closing(fs_info))
1714 if (!btrfs_should_reclaim(fs_info))
1717 sb_start_write(fs_info->sb);
1719 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
1720 sb_end_write(fs_info->sb);
1725 * Long running balances can keep us blocked here for eternity, so
1726 * simply skip reclaim if we're unable to get the mutex.
1728 if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) {
1729 btrfs_exclop_finish(fs_info);
1730 sb_end_write(fs_info->sb);
1734 spin_lock(&fs_info->unused_bgs_lock);
1736 * Sort happens under lock because we can't simply splice it and sort.
1737 * The block groups might still be in use and reachable via bg_list,
1738 * and their presence in the reclaim_bgs list must be preserved.
1740 list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp);
1741 while (!list_empty(&fs_info->reclaim_bgs)) {
1745 bg = list_first_entry(&fs_info->reclaim_bgs,
1746 struct btrfs_block_group,
1748 list_del_init(&bg->bg_list);
1750 space_info = bg->space_info;
1751 spin_unlock(&fs_info->unused_bgs_lock);
1753 /* Don't race with allocators so take the groups_sem */
1754 down_write(&space_info->groups_sem);
1756 spin_lock(&bg->lock);
1757 if (bg->reserved || bg->pinned || bg->ro) {
1759 * We want to bail if we made new allocations or have
1760 * outstanding allocations in this block group. We do
1761 * the ro check in case balance is currently acting on
1764 spin_unlock(&bg->lock);
1765 up_write(&space_info->groups_sem);
1768 if (bg->used == 0) {
1770 * It is possible that we trigger relocation on a block
1771 * group as its extents are deleted and it first goes
1772 * below the threshold, then shortly after goes empty.
1774 * In this case, relocating it does delete it, but has
1775 * some overhead in relocation specific metadata, looking
1776 * for the non-existent extents and running some extra
1777 * transactions, which we can avoid by using one of the
1778 * other mechanisms for dealing with empty block groups.
1780 if (!btrfs_test_opt(fs_info, DISCARD_ASYNC))
1781 btrfs_mark_bg_unused(bg);
1782 spin_unlock(&bg->lock);
1783 up_write(&space_info->groups_sem);
1788 * The block group might no longer meet the reclaim condition by
1789 * the time we get around to reclaiming it, so to avoid
1790 * reclaiming overly full block_groups, skip reclaiming them.
1792 * Since the decision making process also depends on the amount
1793 * being freed, pass in a fake giant value to skip that extra
1794 * check, which is more meaningful when adding to the list in
1797 if (!should_reclaim_block_group(bg, bg->length)) {
1798 spin_unlock(&bg->lock);
1799 up_write(&space_info->groups_sem);
1802 spin_unlock(&bg->lock);
1805 * Get out fast, in case we're read-only or unmounting the
1806 * filesystem. It is OK to drop block groups from the list even
1807 * for the read-only case. As we did sb_start_write(),
1808 * "mount -o remount,ro" won't happen and read-only filesystem
1809 * means it is forced read-only due to a fatal error. So, it
1810 * never gets back to read-write to let us reclaim again.
1812 if (btrfs_need_cleaner_sleep(fs_info)) {
1813 up_write(&space_info->groups_sem);
1818 * Cache the zone_unusable value before turning the block group
1819 * to read only. As soon as the blog group is read only it's
1820 * zone_unusable value gets moved to the block group's read-only
1821 * bytes and isn't available for calculations anymore.
1823 zone_unusable = bg->zone_unusable;
1824 ret = inc_block_group_ro(bg, 0);
1825 up_write(&space_info->groups_sem);
1830 "reclaiming chunk %llu with %llu%% used %llu%% unusable",
1832 div64_u64(bg->used * 100, bg->length),
1833 div64_u64(zone_unusable * 100, bg->length));
1834 trace_btrfs_reclaim_block_group(bg);
1835 ret = btrfs_relocate_chunk(fs_info, bg->start);
1837 btrfs_dec_block_group_ro(bg);
1838 btrfs_err(fs_info, "error relocating chunk %llu",
1844 btrfs_mark_bg_to_reclaim(bg);
1845 btrfs_put_block_group(bg);
1847 mutex_unlock(&fs_info->reclaim_bgs_lock);
1849 * Reclaiming all the block groups in the list can take really
1850 * long. Prioritize cleaning up unused block groups.
1852 btrfs_delete_unused_bgs(fs_info);
1854 * If we are interrupted by a balance, we can just bail out. The
1855 * cleaner thread restart again if necessary.
1857 if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
1859 spin_lock(&fs_info->unused_bgs_lock);
1861 spin_unlock(&fs_info->unused_bgs_lock);
1862 mutex_unlock(&fs_info->reclaim_bgs_lock);
1864 btrfs_exclop_finish(fs_info);
1865 sb_end_write(fs_info->sb);
1868 void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
1870 spin_lock(&fs_info->unused_bgs_lock);
1871 if (!list_empty(&fs_info->reclaim_bgs))
1872 queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
1873 spin_unlock(&fs_info->unused_bgs_lock);
1876 void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
1878 struct btrfs_fs_info *fs_info = bg->fs_info;
1880 spin_lock(&fs_info->unused_bgs_lock);
1881 if (list_empty(&bg->bg_list)) {
1882 btrfs_get_block_group(bg);
1883 trace_btrfs_add_reclaim_block_group(bg);
1884 list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
1886 spin_unlock(&fs_info->unused_bgs_lock);
1889 static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1890 struct btrfs_path *path)
1892 struct extent_map_tree *em_tree;
1893 struct extent_map *em;
1894 struct btrfs_block_group_item bg;
1895 struct extent_buffer *leaf;
1900 slot = path->slots[0];
1901 leaf = path->nodes[0];
1903 em_tree = &fs_info->mapping_tree;
1904 read_lock(&em_tree->lock);
1905 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1906 read_unlock(&em_tree->lock);
1909 "logical %llu len %llu found bg but no related chunk",
1910 key->objectid, key->offset);
1914 if (em->start != key->objectid || em->len != key->offset) {
1916 "block group %llu len %llu mismatch with chunk %llu len %llu",
1917 key->objectid, key->offset, em->start, em->len);
1922 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1924 flags = btrfs_stack_block_group_flags(&bg) &
1925 BTRFS_BLOCK_GROUP_TYPE_MASK;
1927 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1929 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1930 key->objectid, key->offset, flags,
1931 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1936 free_extent_map(em);
1940 static int find_first_block_group(struct btrfs_fs_info *fs_info,
1941 struct btrfs_path *path,
1942 struct btrfs_key *key)
1944 struct btrfs_root *root = btrfs_block_group_root(fs_info);
1946 struct btrfs_key found_key;
1948 btrfs_for_each_slot(root, key, &found_key, path, ret) {
1949 if (found_key.objectid >= key->objectid &&
1950 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1951 return read_bg_from_eb(fs_info, &found_key, path);
1957 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1959 u64 extra_flags = chunk_to_extended(flags) &
1960 BTRFS_EXTENDED_PROFILE_MASK;
1962 write_seqlock(&fs_info->profiles_lock);
1963 if (flags & BTRFS_BLOCK_GROUP_DATA)
1964 fs_info->avail_data_alloc_bits |= extra_flags;
1965 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1966 fs_info->avail_metadata_alloc_bits |= extra_flags;
1967 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1968 fs_info->avail_system_alloc_bits |= extra_flags;
1969 write_sequnlock(&fs_info->profiles_lock);
1973 * Map a physical disk address to a list of logical addresses.
1975 * @fs_info: the filesystem
1976 * @chunk_start: logical address of block group
1977 * @physical: physical address to map to logical addresses
1978 * @logical: return array of logical addresses which map to @physical
1979 * @naddrs: length of @logical
1980 * @stripe_len: size of IO stripe for the given block group
1982 * Maps a particular @physical disk address to a list of @logical addresses.
1983 * Used primarily to exclude those portions of a block group that contain super
1986 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1987 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
1989 struct extent_map *em;
1990 struct map_lookup *map;
1993 u64 data_stripe_length;
1998 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
2002 map = em->map_lookup;
2003 data_stripe_length = em->orig_block_len;
2004 io_stripe_size = BTRFS_STRIPE_LEN;
2005 chunk_start = em->start;
2007 /* For RAID5/6 adjust to a full IO stripe length */
2008 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
2009 io_stripe_size = btrfs_stripe_nr_to_offset(nr_data_stripes(map));
2011 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
2017 for (i = 0; i < map->num_stripes; i++) {
2018 bool already_inserted = false;
2023 if (!in_range(physical, map->stripes[i].physical,
2024 data_stripe_length))
2027 stripe_nr = (physical - map->stripes[i].physical) >>
2028 BTRFS_STRIPE_LEN_SHIFT;
2029 offset = (physical - map->stripes[i].physical) &
2030 BTRFS_STRIPE_LEN_MASK;
2032 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
2033 BTRFS_BLOCK_GROUP_RAID10))
2034 stripe_nr = div_u64(stripe_nr * map->num_stripes + i,
2037 * The remaining case would be for RAID56, multiply by
2038 * nr_data_stripes(). Alternatively, just use rmap_len below
2039 * instead of map->stripe_len
2041 bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
2043 /* Ensure we don't add duplicate addresses */
2044 for (j = 0; j < nr; j++) {
2045 if (buf[j] == bytenr) {
2046 already_inserted = true;
2051 if (!already_inserted)
2057 *stripe_len = io_stripe_size;
2059 free_extent_map(em);
2063 static int exclude_super_stripes(struct btrfs_block_group *cache)
2065 struct btrfs_fs_info *fs_info = cache->fs_info;
2066 const bool zoned = btrfs_is_zoned(fs_info);
2072 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
2073 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
2074 cache->bytes_super += stripe_len;
2075 ret = btrfs_add_excluded_extent(fs_info, cache->start,
2081 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2082 bytenr = btrfs_sb_offset(i);
2083 ret = btrfs_rmap_block(fs_info, cache->start,
2084 bytenr, &logical, &nr, &stripe_len);
2088 /* Shouldn't have super stripes in sequential zones */
2091 "zoned: block group %llu must not contain super block",
2097 u64 len = min_t(u64, stripe_len,
2098 cache->start + cache->length - logical[nr]);
2100 cache->bytes_super += len;
2101 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
2114 static struct btrfs_block_group *btrfs_create_block_group_cache(
2115 struct btrfs_fs_info *fs_info, u64 start)
2117 struct btrfs_block_group *cache;
2119 cache = kzalloc(sizeof(*cache), GFP_NOFS);
2123 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
2125 if (!cache->free_space_ctl) {
2130 cache->start = start;
2132 cache->fs_info = fs_info;
2133 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
2135 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
2137 refcount_set(&cache->refs, 1);
2138 spin_lock_init(&cache->lock);
2139 init_rwsem(&cache->data_rwsem);
2140 INIT_LIST_HEAD(&cache->list);
2141 INIT_LIST_HEAD(&cache->cluster_list);
2142 INIT_LIST_HEAD(&cache->bg_list);
2143 INIT_LIST_HEAD(&cache->ro_list);
2144 INIT_LIST_HEAD(&cache->discard_list);
2145 INIT_LIST_HEAD(&cache->dirty_list);
2146 INIT_LIST_HEAD(&cache->io_list);
2147 INIT_LIST_HEAD(&cache->active_bg_list);
2148 btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
2149 atomic_set(&cache->frozen, 0);
2150 mutex_init(&cache->free_space_lock);
2156 * Iterate all chunks and verify that each of them has the corresponding block
2159 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
2161 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
2162 struct extent_map *em;
2163 struct btrfs_block_group *bg;
2168 read_lock(&map_tree->lock);
2170 * lookup_extent_mapping will return the first extent map
2171 * intersecting the range, so setting @len to 1 is enough to
2172 * get the first chunk.
2174 em = lookup_extent_mapping(map_tree, start, 1);
2175 read_unlock(&map_tree->lock);
2179 bg = btrfs_lookup_block_group(fs_info, em->start);
2182 "chunk start=%llu len=%llu doesn't have corresponding block group",
2183 em->start, em->len);
2185 free_extent_map(em);
2188 if (bg->start != em->start || bg->length != em->len ||
2189 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
2190 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
2192 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
2194 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
2195 bg->start, bg->length,
2196 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
2198 free_extent_map(em);
2199 btrfs_put_block_group(bg);
2202 start = em->start + em->len;
2203 free_extent_map(em);
2204 btrfs_put_block_group(bg);
2209 static int read_one_block_group(struct btrfs_fs_info *info,
2210 struct btrfs_block_group_item *bgi,
2211 const struct btrfs_key *key,
2214 struct btrfs_block_group *cache;
2215 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
2218 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
2220 cache = btrfs_create_block_group_cache(info, key->objectid);
2224 cache->length = key->offset;
2225 cache->used = btrfs_stack_block_group_used(bgi);
2226 cache->commit_used = cache->used;
2227 cache->flags = btrfs_stack_block_group_flags(bgi);
2228 cache->global_root_id = btrfs_stack_block_group_chunk_objectid(bgi);
2230 set_free_space_tree_thresholds(cache);
2234 * When we mount with old space cache, we need to
2235 * set BTRFS_DC_CLEAR and set dirty flag.
2237 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
2238 * truncate the old free space cache inode and
2240 * b) Setting 'dirty flag' makes sure that we flush
2241 * the new space cache info onto disk.
2243 if (btrfs_test_opt(info, SPACE_CACHE))
2244 cache->disk_cache_state = BTRFS_DC_CLEAR;
2246 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
2247 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
2249 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2255 ret = btrfs_load_block_group_zone_info(cache, false);
2257 btrfs_err(info, "zoned: failed to load zone info of bg %llu",
2263 * We need to exclude the super stripes now so that the space info has
2264 * super bytes accounted for, otherwise we'll think we have more space
2265 * than we actually do.
2267 ret = exclude_super_stripes(cache);
2269 /* We may have excluded something, so call this just in case. */
2270 btrfs_free_excluded_extents(cache);
2275 * For zoned filesystem, space after the allocation offset is the only
2276 * free space for a block group. So, we don't need any caching work.
2277 * btrfs_calc_zone_unusable() will set the amount of free space and
2278 * zone_unusable space.
2280 * For regular filesystem, check for two cases, either we are full, and
2281 * therefore don't need to bother with the caching work since we won't
2282 * find any space, or we are empty, and we can just add all the space
2283 * in and be done with it. This saves us _a_lot_ of time, particularly
2286 if (btrfs_is_zoned(info)) {
2287 btrfs_calc_zone_unusable(cache);
2288 /* Should not have any excluded extents. Just in case, though. */
2289 btrfs_free_excluded_extents(cache);
2290 } else if (cache->length == cache->used) {
2291 cache->cached = BTRFS_CACHE_FINISHED;
2292 btrfs_free_excluded_extents(cache);
2293 } else if (cache->used == 0) {
2294 cache->cached = BTRFS_CACHE_FINISHED;
2295 add_new_free_space(cache, cache->start,
2296 cache->start + cache->length);
2297 btrfs_free_excluded_extents(cache);
2300 ret = btrfs_add_block_group_cache(info, cache);
2302 btrfs_remove_free_space_cache(cache);
2305 trace_btrfs_add_block_group(info, cache, 0);
2306 btrfs_add_bg_to_space_info(info, cache);
2308 set_avail_alloc_bits(info, cache->flags);
2309 if (btrfs_chunk_writeable(info, cache->start)) {
2310 if (cache->used == 0) {
2311 ASSERT(list_empty(&cache->bg_list));
2312 if (btrfs_test_opt(info, DISCARD_ASYNC))
2313 btrfs_discard_queue_work(&info->discard_ctl, cache);
2315 btrfs_mark_bg_unused(cache);
2318 inc_block_group_ro(cache, 1);
2323 btrfs_put_block_group(cache);
2327 static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
2329 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
2330 struct rb_node *node;
2333 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
2334 struct extent_map *em;
2335 struct map_lookup *map;
2336 struct btrfs_block_group *bg;
2338 em = rb_entry(node, struct extent_map, rb_node);
2339 map = em->map_lookup;
2340 bg = btrfs_create_block_group_cache(fs_info, em->start);
2346 /* Fill dummy cache as FULL */
2347 bg->length = em->len;
2348 bg->flags = map->type;
2349 bg->cached = BTRFS_CACHE_FINISHED;
2351 bg->flags = map->type;
2352 ret = btrfs_add_block_group_cache(fs_info, bg);
2354 * We may have some valid block group cache added already, in
2355 * that case we skip to the next one.
2357 if (ret == -EEXIST) {
2359 btrfs_put_block_group(bg);
2364 btrfs_remove_free_space_cache(bg);
2365 btrfs_put_block_group(bg);
2369 btrfs_add_bg_to_space_info(fs_info, bg);
2371 set_avail_alloc_bits(fs_info, bg->flags);
2374 btrfs_init_global_block_rsv(fs_info);
2378 int btrfs_read_block_groups(struct btrfs_fs_info *info)
2380 struct btrfs_root *root = btrfs_block_group_root(info);
2381 struct btrfs_path *path;
2383 struct btrfs_block_group *cache;
2384 struct btrfs_space_info *space_info;
2385 struct btrfs_key key;
2390 * Either no extent root (with ibadroots rescue option) or we have
2391 * unsupported RO options. The fs can never be mounted read-write, so no
2392 * need to waste time searching block group items.
2394 * This also allows new extent tree related changes to be RO compat,
2395 * no need for a full incompat flag.
2397 if (!root || (btrfs_super_compat_ro_flags(info->super_copy) &
2398 ~BTRFS_FEATURE_COMPAT_RO_SUPP))
2399 return fill_dummy_bgs(info);
2403 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2404 path = btrfs_alloc_path();
2408 cache_gen = btrfs_super_cache_generation(info->super_copy);
2409 if (btrfs_test_opt(info, SPACE_CACHE) &&
2410 btrfs_super_generation(info->super_copy) != cache_gen)
2412 if (btrfs_test_opt(info, CLEAR_CACHE))
2416 struct btrfs_block_group_item bgi;
2417 struct extent_buffer *leaf;
2420 ret = find_first_block_group(info, path, &key);
2426 leaf = path->nodes[0];
2427 slot = path->slots[0];
2429 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
2432 btrfs_item_key_to_cpu(leaf, &key, slot);
2433 btrfs_release_path(path);
2434 ret = read_one_block_group(info, &bgi, &key, need_clear);
2437 key.objectid += key.offset;
2440 btrfs_release_path(path);
2442 list_for_each_entry(space_info, &info->space_info, list) {
2445 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2446 if (list_empty(&space_info->block_groups[i]))
2448 cache = list_first_entry(&space_info->block_groups[i],
2449 struct btrfs_block_group,
2451 btrfs_sysfs_add_block_group_type(cache);
2454 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2455 (BTRFS_BLOCK_GROUP_RAID10 |
2456 BTRFS_BLOCK_GROUP_RAID1_MASK |
2457 BTRFS_BLOCK_GROUP_RAID56_MASK |
2458 BTRFS_BLOCK_GROUP_DUP)))
2461 * Avoid allocating from un-mirrored block group if there are
2462 * mirrored block groups.
2464 list_for_each_entry(cache,
2465 &space_info->block_groups[BTRFS_RAID_RAID0],
2467 inc_block_group_ro(cache, 1);
2468 list_for_each_entry(cache,
2469 &space_info->block_groups[BTRFS_RAID_SINGLE],
2471 inc_block_group_ro(cache, 1);
2474 btrfs_init_global_block_rsv(info);
2475 ret = check_chunk_block_group_mappings(info);
2477 btrfs_free_path(path);
2479 * We've hit some error while reading the extent tree, and have
2480 * rescue=ibadroots mount option.
2481 * Try to fill the tree using dummy block groups so that the user can
2482 * continue to mount and grab their data.
2484 if (ret && btrfs_test_opt(info, IGNOREBADROOTS))
2485 ret = fill_dummy_bgs(info);
2490 * This function, insert_block_group_item(), belongs to the phase 2 of chunk
2493 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2496 static int insert_block_group_item(struct btrfs_trans_handle *trans,
2497 struct btrfs_block_group *block_group)
2499 struct btrfs_fs_info *fs_info = trans->fs_info;
2500 struct btrfs_block_group_item bgi;
2501 struct btrfs_root *root = btrfs_block_group_root(fs_info);
2502 struct btrfs_key key;
2503 u64 old_commit_used;
2506 spin_lock(&block_group->lock);
2507 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2508 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2509 block_group->global_root_id);
2510 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2511 old_commit_used = block_group->commit_used;
2512 block_group->commit_used = block_group->used;
2513 key.objectid = block_group->start;
2514 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2515 key.offset = block_group->length;
2516 spin_unlock(&block_group->lock);
2518 ret = btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2520 spin_lock(&block_group->lock);
2521 block_group->commit_used = old_commit_used;
2522 spin_unlock(&block_group->lock);
2528 static int insert_dev_extent(struct btrfs_trans_handle *trans,
2529 struct btrfs_device *device, u64 chunk_offset,
2530 u64 start, u64 num_bytes)
2532 struct btrfs_fs_info *fs_info = device->fs_info;
2533 struct btrfs_root *root = fs_info->dev_root;
2534 struct btrfs_path *path;
2535 struct btrfs_dev_extent *extent;
2536 struct extent_buffer *leaf;
2537 struct btrfs_key key;
2540 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
2541 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
2542 path = btrfs_alloc_path();
2546 key.objectid = device->devid;
2547 key.type = BTRFS_DEV_EXTENT_KEY;
2549 ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent));
2553 leaf = path->nodes[0];
2554 extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
2555 btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID);
2556 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
2557 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2558 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
2560 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
2561 btrfs_mark_buffer_dirty(leaf);
2563 btrfs_free_path(path);
2568 * This function belongs to phase 2.
2570 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2573 static int insert_dev_extents(struct btrfs_trans_handle *trans,
2574 u64 chunk_offset, u64 chunk_size)
2576 struct btrfs_fs_info *fs_info = trans->fs_info;
2577 struct btrfs_device *device;
2578 struct extent_map *em;
2579 struct map_lookup *map;
2585 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
2589 map = em->map_lookup;
2590 stripe_size = em->orig_block_len;
2593 * Take the device list mutex to prevent races with the final phase of
2594 * a device replace operation that replaces the device object associated
2595 * with the map's stripes, because the device object's id can change
2596 * at any time during that final phase of the device replace operation
2597 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
2598 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
2599 * resulting in persisting a device extent item with such ID.
2601 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2602 for (i = 0; i < map->num_stripes; i++) {
2603 device = map->stripes[i].dev;
2604 dev_offset = map->stripes[i].physical;
2606 ret = insert_dev_extent(trans, device, chunk_offset, dev_offset,
2611 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2613 free_extent_map(em);
2618 * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
2621 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2624 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2626 struct btrfs_fs_info *fs_info = trans->fs_info;
2627 struct btrfs_block_group *block_group;
2630 while (!list_empty(&trans->new_bgs)) {
2633 block_group = list_first_entry(&trans->new_bgs,
2634 struct btrfs_block_group,
2639 index = btrfs_bg_flags_to_raid_index(block_group->flags);
2641 ret = insert_block_group_item(trans, block_group);
2643 btrfs_abort_transaction(trans, ret);
2644 if (!test_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED,
2645 &block_group->runtime_flags)) {
2646 mutex_lock(&fs_info->chunk_mutex);
2647 ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group);
2648 mutex_unlock(&fs_info->chunk_mutex);
2650 btrfs_abort_transaction(trans, ret);
2652 ret = insert_dev_extents(trans, block_group->start,
2653 block_group->length);
2655 btrfs_abort_transaction(trans, ret);
2656 add_block_group_free_space(trans, block_group);
2659 * If we restriped during balance, we may have added a new raid
2660 * type, so now add the sysfs entries when it is safe to do so.
2661 * We don't have to worry about locking here as it's handled in
2662 * btrfs_sysfs_add_block_group_type.
2664 if (block_group->space_info->block_group_kobjs[index] == NULL)
2665 btrfs_sysfs_add_block_group_type(block_group);
2667 /* Already aborted the transaction if it failed. */
2669 btrfs_delayed_refs_rsv_release(fs_info, 1);
2670 list_del_init(&block_group->bg_list);
2672 btrfs_trans_release_chunk_metadata(trans);
2676 * For extent tree v2 we use the block_group_item->chunk_offset to point at our
2677 * global root id. For v1 it's always set to BTRFS_FIRST_CHUNK_TREE_OBJECTID.
2679 static u64 calculate_global_root_id(struct btrfs_fs_info *fs_info, u64 offset)
2684 if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2685 return BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2687 /* If we have a smaller fs index based on 128MiB. */
2688 if (btrfs_super_total_bytes(fs_info->super_copy) <= (SZ_1G * 10ULL))
2691 offset = div64_u64(offset, div);
2692 div64_u64_rem(offset, fs_info->nr_global_roots, &index);
2696 struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
2698 u64 chunk_offset, u64 size)
2700 struct btrfs_fs_info *fs_info = trans->fs_info;
2701 struct btrfs_block_group *cache;
2704 btrfs_set_log_full_commit(trans);
2706 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
2708 return ERR_PTR(-ENOMEM);
2710 cache->length = size;
2711 set_free_space_tree_thresholds(cache);
2712 cache->flags = type;
2713 cache->cached = BTRFS_CACHE_FINISHED;
2714 cache->global_root_id = calculate_global_root_id(fs_info, cache->start);
2716 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
2717 set_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE, &cache->runtime_flags);
2719 ret = btrfs_load_block_group_zone_info(cache, true);
2721 btrfs_put_block_group(cache);
2722 return ERR_PTR(ret);
2725 ret = exclude_super_stripes(cache);
2727 /* We may have excluded something, so call this just in case */
2728 btrfs_free_excluded_extents(cache);
2729 btrfs_put_block_group(cache);
2730 return ERR_PTR(ret);
2733 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2735 btrfs_free_excluded_extents(cache);
2738 * Ensure the corresponding space_info object is created and
2739 * assigned to our block group. We want our bg to be added to the rbtree
2740 * with its ->space_info set.
2742 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2743 ASSERT(cache->space_info);
2745 ret = btrfs_add_block_group_cache(fs_info, cache);
2747 btrfs_remove_free_space_cache(cache);
2748 btrfs_put_block_group(cache);
2749 return ERR_PTR(ret);
2753 * Now that our block group has its ->space_info set and is inserted in
2754 * the rbtree, update the space info's counters.
2756 trace_btrfs_add_block_group(fs_info, cache, 1);
2757 btrfs_add_bg_to_space_info(fs_info, cache);
2758 btrfs_update_global_block_rsv(fs_info);
2760 #ifdef CONFIG_BTRFS_DEBUG
2761 if (btrfs_should_fragment_free_space(cache)) {
2762 cache->space_info->bytes_used += size >> 1;
2763 fragment_free_space(cache);
2767 list_add_tail(&cache->bg_list, &trans->new_bgs);
2768 trans->delayed_ref_updates++;
2769 btrfs_update_delayed_refs_rsv(trans);
2771 set_avail_alloc_bits(fs_info, type);
2776 * Mark one block group RO, can be called several times for the same block
2779 * @cache: the destination block group
2780 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2781 * ensure we still have some free space after marking this
2784 int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2785 bool do_chunk_alloc)
2787 struct btrfs_fs_info *fs_info = cache->fs_info;
2788 struct btrfs_trans_handle *trans;
2789 struct btrfs_root *root = btrfs_block_group_root(fs_info);
2792 bool dirty_bg_running;
2795 * This can only happen when we are doing read-only scrub on read-only
2797 * In that case we should not start a new transaction on read-only fs.
2798 * Thus here we skip all chunk allocations.
2800 if (sb_rdonly(fs_info->sb)) {
2801 mutex_lock(&fs_info->ro_block_group_mutex);
2802 ret = inc_block_group_ro(cache, 0);
2803 mutex_unlock(&fs_info->ro_block_group_mutex);
2808 trans = btrfs_join_transaction(root);
2810 return PTR_ERR(trans);
2812 dirty_bg_running = false;
2815 * We're not allowed to set block groups readonly after the dirty
2816 * block group cache has started writing. If it already started,
2817 * back off and let this transaction commit.
2819 mutex_lock(&fs_info->ro_block_group_mutex);
2820 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2821 u64 transid = trans->transid;
2823 mutex_unlock(&fs_info->ro_block_group_mutex);
2824 btrfs_end_transaction(trans);
2826 ret = btrfs_wait_for_commit(fs_info, transid);
2829 dirty_bg_running = true;
2831 } while (dirty_bg_running);
2833 if (do_chunk_alloc) {
2835 * If we are changing raid levels, try to allocate a
2836 * corresponding block group with the new raid level.
2838 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2839 if (alloc_flags != cache->flags) {
2840 ret = btrfs_chunk_alloc(trans, alloc_flags,
2843 * ENOSPC is allowed here, we may have enough space
2844 * already allocated at the new raid level to carry on
2853 ret = inc_block_group_ro(cache, 0);
2856 if (ret == -ETXTBSY)
2860 * Skip chunk alloction if the bg is SYSTEM, this is to avoid system
2861 * chunk allocation storm to exhaust the system chunk array. Otherwise
2862 * we still want to try our best to mark the block group read-only.
2864 if (!do_chunk_alloc && ret == -ENOSPC &&
2865 (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM))
2868 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2869 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2873 * We have allocated a new chunk. We also need to activate that chunk to
2874 * grant metadata tickets for zoned filesystem.
2876 ret = btrfs_zoned_activate_one_bg(fs_info, cache->space_info, true);
2880 ret = inc_block_group_ro(cache, 0);
2881 if (ret == -ETXTBSY)
2884 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2885 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2886 mutex_lock(&fs_info->chunk_mutex);
2887 check_system_chunk(trans, alloc_flags);
2888 mutex_unlock(&fs_info->chunk_mutex);
2891 mutex_unlock(&fs_info->ro_block_group_mutex);
2893 btrfs_end_transaction(trans);
2897 void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
2899 struct btrfs_space_info *sinfo = cache->space_info;
2904 spin_lock(&sinfo->lock);
2905 spin_lock(&cache->lock);
2907 if (btrfs_is_zoned(cache->fs_info)) {
2908 /* Migrate zone_unusable bytes back */
2909 cache->zone_unusable =
2910 (cache->alloc_offset - cache->used) +
2911 (cache->length - cache->zone_capacity);
2912 sinfo->bytes_zone_unusable += cache->zone_unusable;
2913 sinfo->bytes_readonly -= cache->zone_unusable;
2915 num_bytes = cache->length - cache->reserved -
2916 cache->pinned - cache->bytes_super -
2917 cache->zone_unusable - cache->used;
2918 sinfo->bytes_readonly -= num_bytes;
2919 list_del_init(&cache->ro_list);
2921 spin_unlock(&cache->lock);
2922 spin_unlock(&sinfo->lock);
2925 static int update_block_group_item(struct btrfs_trans_handle *trans,
2926 struct btrfs_path *path,
2927 struct btrfs_block_group *cache)
2929 struct btrfs_fs_info *fs_info = trans->fs_info;
2931 struct btrfs_root *root = btrfs_block_group_root(fs_info);
2933 struct extent_buffer *leaf;
2934 struct btrfs_block_group_item bgi;
2935 struct btrfs_key key;
2936 u64 old_commit_used;
2940 * Block group items update can be triggered out of commit transaction
2941 * critical section, thus we need a consistent view of used bytes.
2942 * We cannot use cache->used directly outside of the spin lock, as it
2945 spin_lock(&cache->lock);
2946 old_commit_used = cache->commit_used;
2948 /* No change in used bytes, can safely skip it. */
2949 if (cache->commit_used == used) {
2950 spin_unlock(&cache->lock);
2953 cache->commit_used = used;
2954 spin_unlock(&cache->lock);
2956 key.objectid = cache->start;
2957 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2958 key.offset = cache->length;
2960 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2967 leaf = path->nodes[0];
2968 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2969 btrfs_set_stack_block_group_used(&bgi, used);
2970 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2971 cache->global_root_id);
2972 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2973 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
2974 btrfs_mark_buffer_dirty(leaf);
2976 btrfs_release_path(path);
2977 /* We didn't update the block group item, need to revert @commit_used. */
2979 spin_lock(&cache->lock);
2980 cache->commit_used = old_commit_used;
2981 spin_unlock(&cache->lock);
2987 static int cache_save_setup(struct btrfs_block_group *block_group,
2988 struct btrfs_trans_handle *trans,
2989 struct btrfs_path *path)
2991 struct btrfs_fs_info *fs_info = block_group->fs_info;
2992 struct btrfs_root *root = fs_info->tree_root;
2993 struct inode *inode = NULL;
2994 struct extent_changeset *data_reserved = NULL;
2996 int dcs = BTRFS_DC_ERROR;
3001 if (!btrfs_test_opt(fs_info, SPACE_CACHE))
3005 * If this block group is smaller than 100 megs don't bother caching the
3008 if (block_group->length < (100 * SZ_1M)) {
3009 spin_lock(&block_group->lock);
3010 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3011 spin_unlock(&block_group->lock);
3015 if (TRANS_ABORTED(trans))
3018 inode = lookup_free_space_inode(block_group, path);
3019 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3020 ret = PTR_ERR(inode);
3021 btrfs_release_path(path);
3025 if (IS_ERR(inode)) {
3029 if (block_group->ro)
3032 ret = create_free_space_inode(trans, block_group, path);
3039 * We want to set the generation to 0, that way if anything goes wrong
3040 * from here on out we know not to trust this cache when we load up next
3043 BTRFS_I(inode)->generation = 0;
3044 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
3047 * So theoretically we could recover from this, simply set the
3048 * super cache generation to 0 so we know to invalidate the
3049 * cache, but then we'd have to keep track of the block groups
3050 * that fail this way so we know we _have_ to reset this cache
3051 * before the next commit or risk reading stale cache. So to
3052 * limit our exposure to horrible edge cases lets just abort the
3053 * transaction, this only happens in really bad situations
3056 btrfs_abort_transaction(trans, ret);
3061 /* We've already setup this transaction, go ahead and exit */
3062 if (block_group->cache_generation == trans->transid &&
3063 i_size_read(inode)) {
3064 dcs = BTRFS_DC_SETUP;
3068 if (i_size_read(inode) > 0) {
3069 ret = btrfs_check_trunc_cache_free_space(fs_info,
3070 &fs_info->global_block_rsv);
3074 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
3079 spin_lock(&block_group->lock);
3080 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3081 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3083 * don't bother trying to write stuff out _if_
3084 * a) we're not cached,
3085 * b) we're with nospace_cache mount option,
3086 * c) we're with v2 space_cache (FREE_SPACE_TREE).
3088 dcs = BTRFS_DC_WRITTEN;
3089 spin_unlock(&block_group->lock);
3092 spin_unlock(&block_group->lock);
3095 * We hit an ENOSPC when setting up the cache in this transaction, just
3096 * skip doing the setup, we've already cleared the cache so we're safe.
3098 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3104 * Try to preallocate enough space based on how big the block group is.
3105 * Keep in mind this has to include any pinned space which could end up
3106 * taking up quite a bit since it's not folded into the other space
3109 cache_size = div_u64(block_group->length, SZ_256M);
3114 cache_size *= fs_info->sectorsize;
3116 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
3121 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
3122 cache_size, cache_size,
3125 * Our cache requires contiguous chunks so that we don't modify a bunch
3126 * of metadata or split extents when writing the cache out, which means
3127 * we can enospc if we are heavily fragmented in addition to just normal
3128 * out of space conditions. So if we hit this just skip setting up any
3129 * other block groups for this transaction, maybe we'll unpin enough
3130 * space the next time around.
3133 dcs = BTRFS_DC_SETUP;
3134 else if (ret == -ENOSPC)
3135 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3140 btrfs_release_path(path);
3142 spin_lock(&block_group->lock);
3143 if (!ret && dcs == BTRFS_DC_SETUP)
3144 block_group->cache_generation = trans->transid;
3145 block_group->disk_cache_state = dcs;
3146 spin_unlock(&block_group->lock);
3148 extent_changeset_free(data_reserved);
3152 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
3154 struct btrfs_fs_info *fs_info = trans->fs_info;
3155 struct btrfs_block_group *cache, *tmp;
3156 struct btrfs_transaction *cur_trans = trans->transaction;
3157 struct btrfs_path *path;
3159 if (list_empty(&cur_trans->dirty_bgs) ||
3160 !btrfs_test_opt(fs_info, SPACE_CACHE))
3163 path = btrfs_alloc_path();
3167 /* Could add new block groups, use _safe just in case */
3168 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3170 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3171 cache_save_setup(cache, trans, path);
3174 btrfs_free_path(path);
3179 * Transaction commit does final block group cache writeback during a critical
3180 * section where nothing is allowed to change the FS. This is required in
3181 * order for the cache to actually match the block group, but can introduce a
3182 * lot of latency into the commit.
3184 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
3185 * There's a chance we'll have to redo some of it if the block group changes
3186 * again during the commit, but it greatly reduces the commit latency by
3187 * getting rid of the easy block groups while we're still allowing others to
3190 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
3192 struct btrfs_fs_info *fs_info = trans->fs_info;
3193 struct btrfs_block_group *cache;
3194 struct btrfs_transaction *cur_trans = trans->transaction;
3197 struct btrfs_path *path = NULL;
3199 struct list_head *io = &cur_trans->io_bgs;
3202 spin_lock(&cur_trans->dirty_bgs_lock);
3203 if (list_empty(&cur_trans->dirty_bgs)) {
3204 spin_unlock(&cur_trans->dirty_bgs_lock);
3207 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3208 spin_unlock(&cur_trans->dirty_bgs_lock);
3211 /* Make sure all the block groups on our dirty list actually exist */
3212 btrfs_create_pending_block_groups(trans);
3215 path = btrfs_alloc_path();
3223 * cache_write_mutex is here only to save us from balance or automatic
3224 * removal of empty block groups deleting this block group while we are
3225 * writing out the cache
3227 mutex_lock(&trans->transaction->cache_write_mutex);
3228 while (!list_empty(&dirty)) {
3229 bool drop_reserve = true;
3231 cache = list_first_entry(&dirty, struct btrfs_block_group,
3234 * This can happen if something re-dirties a block group that
3235 * is already under IO. Just wait for it to finish and then do
3238 if (!list_empty(&cache->io_list)) {
3239 list_del_init(&cache->io_list);
3240 btrfs_wait_cache_io(trans, cache, path);
3241 btrfs_put_block_group(cache);
3246 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
3247 * it should update the cache_state. Don't delete until after
3250 * Since we're not running in the commit critical section
3251 * we need the dirty_bgs_lock to protect from update_block_group
3253 spin_lock(&cur_trans->dirty_bgs_lock);
3254 list_del_init(&cache->dirty_list);
3255 spin_unlock(&cur_trans->dirty_bgs_lock);
3259 cache_save_setup(cache, trans, path);
3261 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3262 cache->io_ctl.inode = NULL;
3263 ret = btrfs_write_out_cache(trans, cache, path);
3264 if (ret == 0 && cache->io_ctl.inode) {
3268 * The cache_write_mutex is protecting the
3269 * io_list, also refer to the definition of
3270 * btrfs_transaction::io_bgs for more details
3272 list_add_tail(&cache->io_list, io);
3275 * If we failed to write the cache, the
3276 * generation will be bad and life goes on
3282 ret = update_block_group_item(trans, path, cache);
3284 * Our block group might still be attached to the list
3285 * of new block groups in the transaction handle of some
3286 * other task (struct btrfs_trans_handle->new_bgs). This
3287 * means its block group item isn't yet in the extent
3288 * tree. If this happens ignore the error, as we will
3289 * try again later in the critical section of the
3290 * transaction commit.
3292 if (ret == -ENOENT) {
3294 spin_lock(&cur_trans->dirty_bgs_lock);
3295 if (list_empty(&cache->dirty_list)) {
3296 list_add_tail(&cache->dirty_list,
3297 &cur_trans->dirty_bgs);
3298 btrfs_get_block_group(cache);
3299 drop_reserve = false;
3301 spin_unlock(&cur_trans->dirty_bgs_lock);
3303 btrfs_abort_transaction(trans, ret);
3307 /* If it's not on the io list, we need to put the block group */
3309 btrfs_put_block_group(cache);
3311 btrfs_delayed_refs_rsv_release(fs_info, 1);
3313 * Avoid blocking other tasks for too long. It might even save
3314 * us from writing caches for block groups that are going to be
3317 mutex_unlock(&trans->transaction->cache_write_mutex);
3320 mutex_lock(&trans->transaction->cache_write_mutex);
3322 mutex_unlock(&trans->transaction->cache_write_mutex);
3325 * Go through delayed refs for all the stuff we've just kicked off
3326 * and then loop back (just once)
3329 ret = btrfs_run_delayed_refs(trans, 0);
3330 if (!ret && loops == 0) {
3332 spin_lock(&cur_trans->dirty_bgs_lock);
3333 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3335 * dirty_bgs_lock protects us from concurrent block group
3336 * deletes too (not just cache_write_mutex).
3338 if (!list_empty(&dirty)) {
3339 spin_unlock(&cur_trans->dirty_bgs_lock);
3342 spin_unlock(&cur_trans->dirty_bgs_lock);
3346 spin_lock(&cur_trans->dirty_bgs_lock);
3347 list_splice_init(&dirty, &cur_trans->dirty_bgs);
3348 spin_unlock(&cur_trans->dirty_bgs_lock);
3349 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3352 btrfs_free_path(path);
3356 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
3358 struct btrfs_fs_info *fs_info = trans->fs_info;
3359 struct btrfs_block_group *cache;
3360 struct btrfs_transaction *cur_trans = trans->transaction;
3363 struct btrfs_path *path;
3364 struct list_head *io = &cur_trans->io_bgs;
3366 path = btrfs_alloc_path();
3371 * Even though we are in the critical section of the transaction commit,
3372 * we can still have concurrent tasks adding elements to this
3373 * transaction's list of dirty block groups. These tasks correspond to
3374 * endio free space workers started when writeback finishes for a
3375 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3376 * allocate new block groups as a result of COWing nodes of the root
3377 * tree when updating the free space inode. The writeback for the space
3378 * caches is triggered by an earlier call to
3379 * btrfs_start_dirty_block_groups() and iterations of the following
3381 * Also we want to do the cache_save_setup first and then run the
3382 * delayed refs to make sure we have the best chance at doing this all
3385 spin_lock(&cur_trans->dirty_bgs_lock);
3386 while (!list_empty(&cur_trans->dirty_bgs)) {
3387 cache = list_first_entry(&cur_trans->dirty_bgs,
3388 struct btrfs_block_group,
3392 * This can happen if cache_save_setup re-dirties a block group
3393 * that is already under IO. Just wait for it to finish and
3394 * then do it all again
3396 if (!list_empty(&cache->io_list)) {
3397 spin_unlock(&cur_trans->dirty_bgs_lock);
3398 list_del_init(&cache->io_list);
3399 btrfs_wait_cache_io(trans, cache, path);
3400 btrfs_put_block_group(cache);
3401 spin_lock(&cur_trans->dirty_bgs_lock);
3405 * Don't remove from the dirty list until after we've waited on
3408 list_del_init(&cache->dirty_list);
3409 spin_unlock(&cur_trans->dirty_bgs_lock);
3412 cache_save_setup(cache, trans, path);
3415 ret = btrfs_run_delayed_refs(trans,
3416 (unsigned long) -1);
3418 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3419 cache->io_ctl.inode = NULL;
3420 ret = btrfs_write_out_cache(trans, cache, path);
3421 if (ret == 0 && cache->io_ctl.inode) {
3423 list_add_tail(&cache->io_list, io);
3426 * If we failed to write the cache, the
3427 * generation will be bad and life goes on
3433 ret = update_block_group_item(trans, path, cache);
3435 * One of the free space endio workers might have
3436 * created a new block group while updating a free space
3437 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3438 * and hasn't released its transaction handle yet, in
3439 * which case the new block group is still attached to
3440 * its transaction handle and its creation has not
3441 * finished yet (no block group item in the extent tree
3442 * yet, etc). If this is the case, wait for all free
3443 * space endio workers to finish and retry. This is a
3444 * very rare case so no need for a more efficient and
3447 if (ret == -ENOENT) {
3448 wait_event(cur_trans->writer_wait,
3449 atomic_read(&cur_trans->num_writers) == 1);
3450 ret = update_block_group_item(trans, path, cache);
3453 btrfs_abort_transaction(trans, ret);
3456 /* If its not on the io list, we need to put the block group */
3458 btrfs_put_block_group(cache);
3459 btrfs_delayed_refs_rsv_release(fs_info, 1);
3460 spin_lock(&cur_trans->dirty_bgs_lock);
3462 spin_unlock(&cur_trans->dirty_bgs_lock);
3465 * Refer to the definition of io_bgs member for details why it's safe
3466 * to use it without any locking
3468 while (!list_empty(io)) {
3469 cache = list_first_entry(io, struct btrfs_block_group,
3471 list_del_init(&cache->io_list);
3472 btrfs_wait_cache_io(trans, cache, path);
3473 btrfs_put_block_group(cache);
3476 btrfs_free_path(path);
3480 int btrfs_update_block_group(struct btrfs_trans_handle *trans,
3481 u64 bytenr, u64 num_bytes, bool alloc)
3483 struct btrfs_fs_info *info = trans->fs_info;
3484 struct btrfs_block_group *cache = NULL;
3485 u64 total = num_bytes;
3491 /* Block accounting for super block */
3492 spin_lock(&info->delalloc_root_lock);
3493 old_val = btrfs_super_bytes_used(info->super_copy);
3495 old_val += num_bytes;
3497 old_val -= num_bytes;
3498 btrfs_set_super_bytes_used(info->super_copy, old_val);
3499 spin_unlock(&info->delalloc_root_lock);
3502 struct btrfs_space_info *space_info;
3503 bool reclaim = false;
3505 cache = btrfs_lookup_block_group(info, bytenr);
3510 space_info = cache->space_info;
3511 factor = btrfs_bg_type_to_factor(cache->flags);
3514 * If this block group has free space cache written out, we
3515 * need to make sure to load it if we are removing space. This
3516 * is because we need the unpinning stage to actually add the
3517 * space back to the block group, otherwise we will leak space.
3519 if (!alloc && !btrfs_block_group_done(cache))
3520 btrfs_cache_block_group(cache, true);
3522 byte_in_group = bytenr - cache->start;
3523 WARN_ON(byte_in_group > cache->length);
3525 spin_lock(&space_info->lock);
3526 spin_lock(&cache->lock);
3528 if (btrfs_test_opt(info, SPACE_CACHE) &&
3529 cache->disk_cache_state < BTRFS_DC_CLEAR)
3530 cache->disk_cache_state = BTRFS_DC_CLEAR;
3532 old_val = cache->used;
3533 num_bytes = min(total, cache->length - byte_in_group);
3535 old_val += num_bytes;
3536 cache->used = old_val;
3537 cache->reserved -= num_bytes;
3538 space_info->bytes_reserved -= num_bytes;
3539 space_info->bytes_used += num_bytes;
3540 space_info->disk_used += num_bytes * factor;
3541 spin_unlock(&cache->lock);
3542 spin_unlock(&space_info->lock);
3544 old_val -= num_bytes;
3545 cache->used = old_val;
3546 cache->pinned += num_bytes;
3547 btrfs_space_info_update_bytes_pinned(info, space_info,
3549 space_info->bytes_used -= num_bytes;
3550 space_info->disk_used -= num_bytes * factor;
3552 reclaim = should_reclaim_block_group(cache, num_bytes);
3554 spin_unlock(&cache->lock);
3555 spin_unlock(&space_info->lock);
3557 set_extent_bit(&trans->transaction->pinned_extents,
3558 bytenr, bytenr + num_bytes - 1,
3559 EXTENT_DIRTY, NULL);
3562 spin_lock(&trans->transaction->dirty_bgs_lock);
3563 if (list_empty(&cache->dirty_list)) {
3564 list_add_tail(&cache->dirty_list,
3565 &trans->transaction->dirty_bgs);
3566 trans->delayed_ref_updates++;
3567 btrfs_get_block_group(cache);
3569 spin_unlock(&trans->transaction->dirty_bgs_lock);
3572 * No longer have used bytes in this block group, queue it for
3573 * deletion. We do this after adding the block group to the
3574 * dirty list to avoid races between cleaner kthread and space
3577 if (!alloc && old_val == 0) {
3578 if (!btrfs_test_opt(info, DISCARD_ASYNC))
3579 btrfs_mark_bg_unused(cache);
3580 } else if (!alloc && reclaim) {
3581 btrfs_mark_bg_to_reclaim(cache);
3584 btrfs_put_block_group(cache);
3586 bytenr += num_bytes;
3589 /* Modified block groups are accounted for in the delayed_refs_rsv. */
3590 btrfs_update_delayed_refs_rsv(trans);
3595 * Update the block_group and space info counters.
3597 * @cache: The cache we are manipulating
3598 * @ram_bytes: The number of bytes of file content, and will be same to
3599 * @num_bytes except for the compress path.
3600 * @num_bytes: The number of bytes in question
3601 * @delalloc: The blocks are allocated for the delalloc write
3603 * This is called by the allocator when it reserves space. If this is a
3604 * reservation and the block group has become read only we cannot make the
3605 * reservation and return -EAGAIN, otherwise this function always succeeds.
3607 int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
3608 u64 ram_bytes, u64 num_bytes, int delalloc,
3609 bool force_wrong_size_class)
3611 struct btrfs_space_info *space_info = cache->space_info;
3612 enum btrfs_block_group_size_class size_class;
3615 spin_lock(&space_info->lock);
3616 spin_lock(&cache->lock);
3622 if (btrfs_block_group_should_use_size_class(cache)) {
3623 size_class = btrfs_calc_block_group_size_class(num_bytes);
3624 ret = btrfs_use_block_group_size_class(cache, size_class, force_wrong_size_class);
3628 cache->reserved += num_bytes;
3629 space_info->bytes_reserved += num_bytes;
3630 trace_btrfs_space_reservation(cache->fs_info, "space_info",
3631 space_info->flags, num_bytes, 1);
3632 btrfs_space_info_update_bytes_may_use(cache->fs_info,
3633 space_info, -ram_bytes);
3635 cache->delalloc_bytes += num_bytes;
3638 * Compression can use less space than we reserved, so wake tickets if
3641 if (num_bytes < ram_bytes)
3642 btrfs_try_granting_tickets(cache->fs_info, space_info);
3644 spin_unlock(&cache->lock);
3645 spin_unlock(&space_info->lock);
3650 * Update the block_group and space info counters.
3652 * @cache: The cache we are manipulating
3653 * @num_bytes: The number of bytes in question
3654 * @delalloc: The blocks are allocated for the delalloc write
3656 * This is called by somebody who is freeing space that was never actually used
3657 * on disk. For example if you reserve some space for a new leaf in transaction
3658 * A and before transaction A commits you free that leaf, you call this with
3659 * reserve set to 0 in order to clear the reservation.
3661 void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3662 u64 num_bytes, int delalloc)
3664 struct btrfs_space_info *space_info = cache->space_info;
3666 spin_lock(&space_info->lock);
3667 spin_lock(&cache->lock);
3669 space_info->bytes_readonly += num_bytes;
3670 cache->reserved -= num_bytes;
3671 space_info->bytes_reserved -= num_bytes;
3672 space_info->max_extent_size = 0;
3675 cache->delalloc_bytes -= num_bytes;
3676 spin_unlock(&cache->lock);
3678 btrfs_try_granting_tickets(cache->fs_info, space_info);
3679 spin_unlock(&space_info->lock);
3682 static void force_metadata_allocation(struct btrfs_fs_info *info)
3684 struct list_head *head = &info->space_info;
3685 struct btrfs_space_info *found;
3687 list_for_each_entry(found, head, list) {
3688 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3689 found->force_alloc = CHUNK_ALLOC_FORCE;
3693 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3694 struct btrfs_space_info *sinfo, int force)
3696 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3699 if (force == CHUNK_ALLOC_FORCE)
3703 * in limited mode, we want to have some free space up to
3704 * about 1% of the FS size.
3706 if (force == CHUNK_ALLOC_LIMITED) {
3707 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3708 thresh = max_t(u64, SZ_64M, mult_perc(thresh, 1));
3710 if (sinfo->total_bytes - bytes_used < thresh)
3714 if (bytes_used + SZ_2M < mult_perc(sinfo->total_bytes, 80))
3719 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3721 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3723 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3726 static struct btrfs_block_group *do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags)
3728 struct btrfs_block_group *bg;
3732 * Check if we have enough space in the system space info because we
3733 * will need to update device items in the chunk btree and insert a new
3734 * chunk item in the chunk btree as well. This will allocate a new
3735 * system block group if needed.
3737 check_system_chunk(trans, flags);
3739 bg = btrfs_create_chunk(trans, flags);
3745 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
3747 * Normally we are not expected to fail with -ENOSPC here, since we have
3748 * previously reserved space in the system space_info and allocated one
3749 * new system chunk if necessary. However there are three exceptions:
3751 * 1) We may have enough free space in the system space_info but all the
3752 * existing system block groups have a profile which can not be used
3753 * for extent allocation.
3755 * This happens when mounting in degraded mode. For example we have a
3756 * RAID1 filesystem with 2 devices, lose one device and mount the fs
3757 * using the other device in degraded mode. If we then allocate a chunk,
3758 * we may have enough free space in the existing system space_info, but
3759 * none of the block groups can be used for extent allocation since they
3760 * have a RAID1 profile, and because we are in degraded mode with a
3761 * single device, we are forced to allocate a new system chunk with a
3762 * SINGLE profile. Making check_system_chunk() iterate over all system
3763 * block groups and check if they have a usable profile and enough space
3764 * can be slow on very large filesystems, so we tolerate the -ENOSPC and
3765 * try again after forcing allocation of a new system chunk. Like this
3766 * we avoid paying the cost of that search in normal circumstances, when
3767 * we were not mounted in degraded mode;
3769 * 2) We had enough free space info the system space_info, and one suitable
3770 * block group to allocate from when we called check_system_chunk()
3771 * above. However right after we called it, the only system block group
3772 * with enough free space got turned into RO mode by a running scrub,
3773 * and in this case we have to allocate a new one and retry. We only
3774 * need do this allocate and retry once, since we have a transaction
3775 * handle and scrub uses the commit root to search for block groups;
3777 * 3) We had one system block group with enough free space when we called
3778 * check_system_chunk(), but after that, right before we tried to
3779 * allocate the last extent buffer we needed, a discard operation came
3780 * in and it temporarily removed the last free space entry from the
3781 * block group (discard removes a free space entry, discards it, and
3782 * then adds back the entry to the block group cache).
3784 if (ret == -ENOSPC) {
3785 const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info);
3786 struct btrfs_block_group *sys_bg;
3788 sys_bg = btrfs_create_chunk(trans, sys_flags);
3789 if (IS_ERR(sys_bg)) {
3790 ret = PTR_ERR(sys_bg);
3791 btrfs_abort_transaction(trans, ret);
3795 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3797 btrfs_abort_transaction(trans, ret);
3801 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
3803 btrfs_abort_transaction(trans, ret);
3807 btrfs_abort_transaction(trans, ret);
3811 btrfs_trans_release_chunk_metadata(trans);
3814 return ERR_PTR(ret);
3816 btrfs_get_block_group(bg);
3821 * Chunk allocation is done in 2 phases:
3823 * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
3824 * the chunk, the chunk mapping, create its block group and add the items
3825 * that belong in the chunk btree to it - more specifically, we need to
3826 * update device items in the chunk btree and add a new chunk item to it.
3828 * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
3829 * group item to the extent btree and the device extent items to the devices
3832 * This is done to prevent deadlocks. For example when COWing a node from the
3833 * extent btree we are holding a write lock on the node's parent and if we
3834 * trigger chunk allocation and attempted to insert the new block group item
3835 * in the extent btree right way, we could deadlock because the path for the
3836 * insertion can include that parent node. At first glance it seems impossible
3837 * to trigger chunk allocation after starting a transaction since tasks should
3838 * reserve enough transaction units (metadata space), however while that is true
3839 * most of the time, chunk allocation may still be triggered for several reasons:
3841 * 1) When reserving metadata, we check if there is enough free space in the
3842 * metadata space_info and therefore don't trigger allocation of a new chunk.
3843 * However later when the task actually tries to COW an extent buffer from
3844 * the extent btree or from the device btree for example, it is forced to
3845 * allocate a new block group (chunk) because the only one that had enough
3846 * free space was just turned to RO mode by a running scrub for example (or
3847 * device replace, block group reclaim thread, etc), so we can not use it
3848 * for allocating an extent and end up being forced to allocate a new one;
3850 * 2) Because we only check that the metadata space_info has enough free bytes,
3851 * we end up not allocating a new metadata chunk in that case. However if
3852 * the filesystem was mounted in degraded mode, none of the existing block
3853 * groups might be suitable for extent allocation due to their incompatible
3854 * profile (for e.g. mounting a 2 devices filesystem, where all block groups
3855 * use a RAID1 profile, in degraded mode using a single device). In this case
3856 * when the task attempts to COW some extent buffer of the extent btree for
3857 * example, it will trigger allocation of a new metadata block group with a
3858 * suitable profile (SINGLE profile in the example of the degraded mount of
3859 * the RAID1 filesystem);
3861 * 3) The task has reserved enough transaction units / metadata space, but when
3862 * it attempts to COW an extent buffer from the extent or device btree for
3863 * example, it does not find any free extent in any metadata block group,
3864 * therefore forced to try to allocate a new metadata block group.
3865 * This is because some other task allocated all available extents in the
3866 * meanwhile - this typically happens with tasks that don't reserve space
3867 * properly, either intentionally or as a bug. One example where this is
3868 * done intentionally is fsync, as it does not reserve any transaction units
3869 * and ends up allocating a variable number of metadata extents for log
3870 * tree extent buffers;
3872 * 4) The task has reserved enough transaction units / metadata space, but right
3873 * before it tries to allocate the last extent buffer it needs, a discard
3874 * operation comes in and, temporarily, removes the last free space entry from
3875 * the only metadata block group that had free space (discard starts by
3876 * removing a free space entry from a block group, then does the discard
3877 * operation and, once it's done, it adds back the free space entry to the
3880 * We also need this 2 phases setup when adding a device to a filesystem with
3881 * a seed device - we must create new metadata and system chunks without adding
3882 * any of the block group items to the chunk, extent and device btrees. If we
3883 * did not do it this way, we would get ENOSPC when attempting to update those
3884 * btrees, since all the chunks from the seed device are read-only.
3886 * Phase 1 does the updates and insertions to the chunk btree because if we had
3887 * it done in phase 2 and have a thundering herd of tasks allocating chunks in
3888 * parallel, we risk having too many system chunks allocated by many tasks if
3889 * many tasks reach phase 1 without the previous ones completing phase 2. In the
3890 * extreme case this leads to exhaustion of the system chunk array in the
3891 * superblock. This is easier to trigger if using a btree node/leaf size of 64K
3892 * and with RAID filesystems (so we have more device items in the chunk btree).
3893 * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
3894 * the system chunk array due to concurrent allocations") provides more details.
3896 * Allocation of system chunks does not happen through this function. A task that
3897 * needs to update the chunk btree (the only btree that uses system chunks), must
3898 * preallocate chunk space by calling either check_system_chunk() or
3899 * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or
3900 * metadata chunk or when removing a chunk, while the later is used before doing
3901 * a modification to the chunk btree - use cases for the later are adding,
3902 * removing and resizing a device as well as relocation of a system chunk.
3903 * See the comment below for more details.
3905 * The reservation of system space, done through check_system_chunk(), as well
3906 * as all the updates and insertions into the chunk btree must be done while
3907 * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
3908 * an extent buffer from the chunks btree we never trigger allocation of a new
3909 * system chunk, which would result in a deadlock (trying to lock twice an
3910 * extent buffer of the chunk btree, first time before triggering the chunk
3911 * allocation and the second time during chunk allocation while attempting to
3912 * update the chunks btree). The system chunk array is also updated while holding
3913 * that mutex. The same logic applies to removing chunks - we must reserve system
3914 * space, update the chunk btree and the system chunk array in the superblock
3915 * while holding fs_info->chunk_mutex.
3917 * This function, btrfs_chunk_alloc(), belongs to phase 1.
3919 * If @force is CHUNK_ALLOC_FORCE:
3920 * - return 1 if it successfully allocates a chunk,
3921 * - return errors including -ENOSPC otherwise.
3922 * If @force is NOT CHUNK_ALLOC_FORCE:
3923 * - return 0 if it doesn't need to allocate a new chunk,
3924 * - return 1 if it successfully allocates a chunk,
3925 * - return errors including -ENOSPC otherwise.
3927 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3928 enum btrfs_chunk_alloc_enum force)
3930 struct btrfs_fs_info *fs_info = trans->fs_info;
3931 struct btrfs_space_info *space_info;
3932 struct btrfs_block_group *ret_bg;
3933 bool wait_for_alloc = false;
3934 bool should_alloc = false;
3935 bool from_extent_allocation = false;
3938 if (force == CHUNK_ALLOC_FORCE_FOR_EXTENT) {
3939 from_extent_allocation = true;
3940 force = CHUNK_ALLOC_FORCE;
3943 /* Don't re-enter if we're already allocating a chunk */
3944 if (trans->allocating_chunk)
3947 * Allocation of system chunks can not happen through this path, as we
3948 * could end up in a deadlock if we are allocating a data or metadata
3949 * chunk and there is another task modifying the chunk btree.
3951 * This is because while we are holding the chunk mutex, we will attempt
3952 * to add the new chunk item to the chunk btree or update an existing
3953 * device item in the chunk btree, while the other task that is modifying
3954 * the chunk btree is attempting to COW an extent buffer while holding a
3955 * lock on it and on its parent - if the COW operation triggers a system
3956 * chunk allocation, then we can deadlock because we are holding the
3957 * chunk mutex and we may need to access that extent buffer or its parent
3958 * in order to add the chunk item or update a device item.
3960 * Tasks that want to modify the chunk tree should reserve system space
3961 * before updating the chunk btree, by calling either
3962 * btrfs_reserve_chunk_metadata() or check_system_chunk().
3963 * It's possible that after a task reserves the space, it still ends up
3964 * here - this happens in the cases described above at do_chunk_alloc().
3965 * The task will have to either retry or fail.
3967 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3970 space_info = btrfs_find_space_info(fs_info, flags);
3974 spin_lock(&space_info->lock);
3975 if (force < space_info->force_alloc)
3976 force = space_info->force_alloc;
3977 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3978 if (space_info->full) {
3979 /* No more free physical space */
3984 spin_unlock(&space_info->lock);
3986 } else if (!should_alloc) {
3987 spin_unlock(&space_info->lock);
3989 } else if (space_info->chunk_alloc) {
3991 * Someone is already allocating, so we need to block
3992 * until this someone is finished and then loop to
3993 * recheck if we should continue with our allocation
3996 wait_for_alloc = true;
3997 force = CHUNK_ALLOC_NO_FORCE;
3998 spin_unlock(&space_info->lock);
3999 mutex_lock(&fs_info->chunk_mutex);
4000 mutex_unlock(&fs_info->chunk_mutex);
4002 /* Proceed with allocation */
4003 space_info->chunk_alloc = 1;
4004 wait_for_alloc = false;
4005 spin_unlock(&space_info->lock);
4009 } while (wait_for_alloc);
4011 mutex_lock(&fs_info->chunk_mutex);
4012 trans->allocating_chunk = true;
4015 * If we have mixed data/metadata chunks we want to make sure we keep
4016 * allocating mixed chunks instead of individual chunks.
4018 if (btrfs_mixed_space_info(space_info))
4019 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4022 * if we're doing a data chunk, go ahead and make sure that
4023 * we keep a reasonable number of metadata chunks allocated in the
4026 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4027 fs_info->data_chunk_allocations++;
4028 if (!(fs_info->data_chunk_allocations %
4029 fs_info->metadata_ratio))
4030 force_metadata_allocation(fs_info);
4033 ret_bg = do_chunk_alloc(trans, flags);
4034 trans->allocating_chunk = false;
4036 if (IS_ERR(ret_bg)) {
4037 ret = PTR_ERR(ret_bg);
4038 } else if (from_extent_allocation) {
4040 * New block group is likely to be used soon. Try to activate
4041 * it now. Failure is OK for now.
4043 btrfs_zone_activate(ret_bg);
4047 btrfs_put_block_group(ret_bg);
4049 spin_lock(&space_info->lock);
4052 space_info->full = 1;
4057 space_info->max_extent_size = 0;
4060 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4062 space_info->chunk_alloc = 0;
4063 spin_unlock(&space_info->lock);
4064 mutex_unlock(&fs_info->chunk_mutex);
4069 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
4073 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
4075 num_dev = fs_info->fs_devices->rw_devices;
4080 static void reserve_chunk_space(struct btrfs_trans_handle *trans,
4084 struct btrfs_fs_info *fs_info = trans->fs_info;
4085 struct btrfs_space_info *info;
4090 * Needed because we can end up allocating a system chunk and for an
4091 * atomic and race free space reservation in the chunk block reserve.
4093 lockdep_assert_held(&fs_info->chunk_mutex);
4095 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4096 spin_lock(&info->lock);
4097 left = info->total_bytes - btrfs_space_info_used(info, true);
4098 spin_unlock(&info->lock);
4100 if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4101 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
4103 btrfs_dump_space_info(fs_info, info, 0, 0);
4107 u64 flags = btrfs_system_alloc_profile(fs_info);
4108 struct btrfs_block_group *bg;
4111 * Ignore failure to create system chunk. We might end up not
4112 * needing it, as we might not need to COW all nodes/leafs from
4113 * the paths we visit in the chunk tree (they were already COWed
4114 * or created in the current transaction for example).
4116 bg = btrfs_create_chunk(trans, flags);
4121 * We have a new chunk. We also need to activate it for
4124 ret = btrfs_zoned_activate_one_bg(fs_info, info, true);
4129 * If we fail to add the chunk item here, we end up
4130 * trying again at phase 2 of chunk allocation, at
4131 * btrfs_create_pending_block_groups(). So ignore
4132 * any error here. An ENOSPC here could happen, due to
4133 * the cases described at do_chunk_alloc() - the system
4134 * block group we just created was just turned into RO
4135 * mode by a scrub for example, or a running discard
4136 * temporarily removed its free space entries, etc.
4138 btrfs_chunk_alloc_add_chunk_item(trans, bg);
4143 ret = btrfs_block_rsv_add(fs_info,
4144 &fs_info->chunk_block_rsv,
4145 bytes, BTRFS_RESERVE_NO_FLUSH);
4147 trans->chunk_bytes_reserved += bytes;
4152 * Reserve space in the system space for allocating or removing a chunk.
4153 * The caller must be holding fs_info->chunk_mutex.
4155 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
4157 struct btrfs_fs_info *fs_info = trans->fs_info;
4158 const u64 num_devs = get_profile_num_devs(fs_info, type);
4161 /* num_devs device items to update and 1 chunk item to add or remove. */
4162 bytes = btrfs_calc_metadata_size(fs_info, num_devs) +
4163 btrfs_calc_insert_metadata_size(fs_info, 1);
4165 reserve_chunk_space(trans, bytes, type);
4169 * Reserve space in the system space, if needed, for doing a modification to the
4172 * @trans: A transaction handle.
4173 * @is_item_insertion: Indicate if the modification is for inserting a new item
4174 * in the chunk btree or if it's for the deletion or update
4175 * of an existing item.
4177 * This is used in a context where we need to update the chunk btree outside
4178 * block group allocation and removal, to avoid a deadlock with a concurrent
4179 * task that is allocating a metadata or data block group and therefore needs to
4180 * update the chunk btree while holding the chunk mutex. After the update to the
4181 * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called.
4184 void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans,
4185 bool is_item_insertion)
4187 struct btrfs_fs_info *fs_info = trans->fs_info;
4190 if (is_item_insertion)
4191 bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
4193 bytes = btrfs_calc_metadata_size(fs_info, 1);
4195 mutex_lock(&fs_info->chunk_mutex);
4196 reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM);
4197 mutex_unlock(&fs_info->chunk_mutex);
4200 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
4202 struct btrfs_block_group *block_group;
4204 block_group = btrfs_lookup_first_block_group(info, 0);
4205 while (block_group) {
4206 btrfs_wait_block_group_cache_done(block_group);
4207 spin_lock(&block_group->lock);
4208 if (test_and_clear_bit(BLOCK_GROUP_FLAG_IREF,
4209 &block_group->runtime_flags)) {
4210 struct inode *inode = block_group->inode;
4212 block_group->inode = NULL;
4213 spin_unlock(&block_group->lock);
4215 ASSERT(block_group->io_ctl.inode == NULL);
4218 spin_unlock(&block_group->lock);
4220 block_group = btrfs_next_block_group(block_group);
4225 * Must be called only after stopping all workers, since we could have block
4226 * group caching kthreads running, and therefore they could race with us if we
4227 * freed the block groups before stopping them.
4229 int btrfs_free_block_groups(struct btrfs_fs_info *info)
4231 struct btrfs_block_group *block_group;
4232 struct btrfs_space_info *space_info;
4233 struct btrfs_caching_control *caching_ctl;
4236 write_lock(&info->block_group_cache_lock);
4237 while (!list_empty(&info->caching_block_groups)) {
4238 caching_ctl = list_entry(info->caching_block_groups.next,
4239 struct btrfs_caching_control, list);
4240 list_del(&caching_ctl->list);
4241 btrfs_put_caching_control(caching_ctl);
4243 write_unlock(&info->block_group_cache_lock);
4245 spin_lock(&info->unused_bgs_lock);
4246 while (!list_empty(&info->unused_bgs)) {
4247 block_group = list_first_entry(&info->unused_bgs,
4248 struct btrfs_block_group,
4250 list_del_init(&block_group->bg_list);
4251 btrfs_put_block_group(block_group);
4254 while (!list_empty(&info->reclaim_bgs)) {
4255 block_group = list_first_entry(&info->reclaim_bgs,
4256 struct btrfs_block_group,
4258 list_del_init(&block_group->bg_list);
4259 btrfs_put_block_group(block_group);
4261 spin_unlock(&info->unused_bgs_lock);
4263 spin_lock(&info->zone_active_bgs_lock);
4264 while (!list_empty(&info->zone_active_bgs)) {
4265 block_group = list_first_entry(&info->zone_active_bgs,
4266 struct btrfs_block_group,
4268 list_del_init(&block_group->active_bg_list);
4269 btrfs_put_block_group(block_group);
4271 spin_unlock(&info->zone_active_bgs_lock);
4273 write_lock(&info->block_group_cache_lock);
4274 while ((n = rb_last(&info->block_group_cache_tree.rb_root)) != NULL) {
4275 block_group = rb_entry(n, struct btrfs_block_group,
4277 rb_erase_cached(&block_group->cache_node,
4278 &info->block_group_cache_tree);
4279 RB_CLEAR_NODE(&block_group->cache_node);
4280 write_unlock(&info->block_group_cache_lock);
4282 down_write(&block_group->space_info->groups_sem);
4283 list_del(&block_group->list);
4284 up_write(&block_group->space_info->groups_sem);
4287 * We haven't cached this block group, which means we could
4288 * possibly have excluded extents on this block group.
4290 if (block_group->cached == BTRFS_CACHE_NO ||
4291 block_group->cached == BTRFS_CACHE_ERROR)
4292 btrfs_free_excluded_extents(block_group);
4294 btrfs_remove_free_space_cache(block_group);
4295 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
4296 ASSERT(list_empty(&block_group->dirty_list));
4297 ASSERT(list_empty(&block_group->io_list));
4298 ASSERT(list_empty(&block_group->bg_list));
4299 ASSERT(refcount_read(&block_group->refs) == 1);
4300 ASSERT(block_group->swap_extents == 0);
4301 btrfs_put_block_group(block_group);
4303 write_lock(&info->block_group_cache_lock);
4305 write_unlock(&info->block_group_cache_lock);
4307 btrfs_release_global_block_rsv(info);
4309 while (!list_empty(&info->space_info)) {
4310 space_info = list_entry(info->space_info.next,
4311 struct btrfs_space_info,
4315 * Do not hide this behind enospc_debug, this is actually
4316 * important and indicates a real bug if this happens.
4318 if (WARN_ON(space_info->bytes_pinned > 0 ||
4319 space_info->bytes_may_use > 0))
4320 btrfs_dump_space_info(info, space_info, 0, 0);
4323 * If there was a failure to cleanup a log tree, very likely due
4324 * to an IO failure on a writeback attempt of one or more of its
4325 * extent buffers, we could not do proper (and cheap) unaccounting
4326 * of their reserved space, so don't warn on bytes_reserved > 0 in
4329 if (!(space_info->flags & BTRFS_BLOCK_GROUP_METADATA) ||
4330 !BTRFS_FS_LOG_CLEANUP_ERROR(info)) {
4331 if (WARN_ON(space_info->bytes_reserved > 0))
4332 btrfs_dump_space_info(info, space_info, 0, 0);
4335 WARN_ON(space_info->reclaim_size > 0);
4336 list_del(&space_info->list);
4337 btrfs_sysfs_remove_space_info(space_info);
4342 void btrfs_freeze_block_group(struct btrfs_block_group *cache)
4344 atomic_inc(&cache->frozen);
4347 void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
4349 struct btrfs_fs_info *fs_info = block_group->fs_info;
4350 struct extent_map_tree *em_tree;
4351 struct extent_map *em;
4354 spin_lock(&block_group->lock);
4355 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
4356 test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags));
4357 spin_unlock(&block_group->lock);
4360 em_tree = &fs_info->mapping_tree;
4361 write_lock(&em_tree->lock);
4362 em = lookup_extent_mapping(em_tree, block_group->start,
4364 BUG_ON(!em); /* logic error, can't happen */
4365 remove_extent_mapping(em_tree, em);
4366 write_unlock(&em_tree->lock);
4368 /* once for us and once for the tree */
4369 free_extent_map(em);
4370 free_extent_map(em);
4373 * We may have left one free space entry and other possible
4374 * tasks trimming this block group have left 1 entry each one.
4377 btrfs_remove_free_space_cache(block_group);
4381 bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
4385 spin_lock(&bg->lock);
4390 spin_unlock(&bg->lock);
4395 void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
4397 spin_lock(&bg->lock);
4399 ASSERT(bg->swap_extents >= amount);
4400 bg->swap_extents -= amount;
4401 spin_unlock(&bg->lock);
4404 enum btrfs_block_group_size_class btrfs_calc_block_group_size_class(u64 size)
4406 if (size <= SZ_128K)
4407 return BTRFS_BG_SZ_SMALL;
4409 return BTRFS_BG_SZ_MEDIUM;
4410 return BTRFS_BG_SZ_LARGE;
4414 * Handle a block group allocating an extent in a size class
4416 * @bg: The block group we allocated in.
4417 * @size_class: The size class of the allocation.
4418 * @force_wrong_size_class: Whether we are desperate enough to allow
4419 * mismatched size classes.
4421 * Returns: 0 if the size class was valid for this block_group, -EAGAIN in the
4422 * case of a race that leads to the wrong size class without
4423 * force_wrong_size_class set.
4425 * find_free_extent will skip block groups with a mismatched size class until
4426 * it really needs to avoid ENOSPC. In that case it will set
4427 * force_wrong_size_class. However, if a block group is newly allocated and
4428 * doesn't yet have a size class, then it is possible for two allocations of
4429 * different sizes to race and both try to use it. The loser is caught here and
4432 int btrfs_use_block_group_size_class(struct btrfs_block_group *bg,
4433 enum btrfs_block_group_size_class size_class,
4434 bool force_wrong_size_class)
4436 ASSERT(size_class != BTRFS_BG_SZ_NONE);
4438 /* The new allocation is in the right size class, do nothing */
4439 if (bg->size_class == size_class)
4442 * The new allocation is in a mismatched size class.
4443 * This means one of two things:
4445 * 1. Two tasks in find_free_extent for different size_classes raced
4446 * and hit the same empty block_group. Make the loser try again.
4447 * 2. A call to find_free_extent got desperate enough to set
4448 * 'force_wrong_slab'. Don't change the size_class, but allow the
4451 if (bg->size_class != BTRFS_BG_SZ_NONE) {
4452 if (force_wrong_size_class)
4457 * The happy new block group case: the new allocation is the first
4458 * one in the block_group so we set size_class.
4460 bg->size_class = size_class;
4465 bool btrfs_block_group_should_use_size_class(struct btrfs_block_group *bg)
4467 if (btrfs_is_zoned(bg->fs_info))
4469 if (!btrfs_is_block_group_data_only(bg))