1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/list_sort.h>
6 #include "block-group.h"
7 #include "space-info.h"
9 #include "free-space-cache.h"
10 #include "free-space-tree.h"
12 #include "transaction.h"
13 #include "ref-verify.h"
16 #include "delalloc-space.h"
22 * Return target flags in extended format or 0 if restripe for this chunk_type
25 * Should be called with balance_lock held
27 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
29 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
35 if (flags & BTRFS_BLOCK_GROUP_DATA &&
36 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
37 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
38 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
39 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
40 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
41 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
42 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
43 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
50 * @flags: available profiles in extended format (see ctree.h)
52 * Return reduced profile in chunk format. If profile changing is in progress
53 * (either running or paused) picks the target profile (if it's already
54 * available), otherwise falls back to plain reducing.
56 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
58 u64 num_devices = fs_info->fs_devices->rw_devices;
64 * See if restripe for this chunk_type is in progress, if so try to
65 * reduce to the target profile
67 spin_lock(&fs_info->balance_lock);
68 target = get_restripe_target(fs_info, flags);
70 spin_unlock(&fs_info->balance_lock);
71 return extended_to_chunk(target);
73 spin_unlock(&fs_info->balance_lock);
75 /* First, mask out the RAID levels which aren't possible */
76 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
77 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
78 allowed |= btrfs_raid_array[raid_type].bg_flag;
82 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
83 allowed = BTRFS_BLOCK_GROUP_RAID6;
84 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
85 allowed = BTRFS_BLOCK_GROUP_RAID5;
86 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
87 allowed = BTRFS_BLOCK_GROUP_RAID10;
88 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
89 allowed = BTRFS_BLOCK_GROUP_RAID1;
90 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
91 allowed = BTRFS_BLOCK_GROUP_RAID0;
93 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
95 return extended_to_chunk(flags | allowed);
98 u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
105 seq = read_seqbegin(&fs_info->profiles_lock);
107 if (flags & BTRFS_BLOCK_GROUP_DATA)
108 flags |= fs_info->avail_data_alloc_bits;
109 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
110 flags |= fs_info->avail_system_alloc_bits;
111 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
112 flags |= fs_info->avail_metadata_alloc_bits;
113 } while (read_seqretry(&fs_info->profiles_lock, seq));
115 return btrfs_reduce_alloc_profile(fs_info, flags);
118 void btrfs_get_block_group(struct btrfs_block_group *cache)
120 refcount_inc(&cache->refs);
123 void btrfs_put_block_group(struct btrfs_block_group *cache)
125 if (refcount_dec_and_test(&cache->refs)) {
126 WARN_ON(cache->pinned > 0);
128 * If there was a failure to cleanup a log tree, very likely due
129 * to an IO failure on a writeback attempt of one or more of its
130 * extent buffers, we could not do proper (and cheap) unaccounting
131 * of their reserved space, so don't warn on reserved > 0 in that
134 if (!(cache->flags & BTRFS_BLOCK_GROUP_METADATA) ||
135 !BTRFS_FS_LOG_CLEANUP_ERROR(cache->fs_info))
136 WARN_ON(cache->reserved > 0);
139 * A block_group shouldn't be on the discard_list anymore.
140 * Remove the block_group from the discard_list to prevent us
141 * from causing a panic due to NULL pointer dereference.
143 if (WARN_ON(!list_empty(&cache->discard_list)))
144 btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
148 * If not empty, someone is still holding mutex of
149 * full_stripe_lock, which can only be released by caller.
150 * And it will definitely cause use-after-free when caller
151 * tries to release full stripe lock.
153 * No better way to resolve, but only to warn.
155 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
156 kfree(cache->free_space_ctl);
157 kfree(cache->physical_map);
163 * This adds the block group to the fs_info rb tree for the block group cache
165 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
166 struct btrfs_block_group *block_group)
169 struct rb_node *parent = NULL;
170 struct btrfs_block_group *cache;
171 bool leftmost = true;
173 ASSERT(block_group->length != 0);
175 write_lock(&info->block_group_cache_lock);
176 p = &info->block_group_cache_tree.rb_root.rb_node;
180 cache = rb_entry(parent, struct btrfs_block_group, cache_node);
181 if (block_group->start < cache->start) {
183 } else if (block_group->start > cache->start) {
187 write_unlock(&info->block_group_cache_lock);
192 rb_link_node(&block_group->cache_node, parent, p);
193 rb_insert_color_cached(&block_group->cache_node,
194 &info->block_group_cache_tree, leftmost);
196 write_unlock(&info->block_group_cache_lock);
202 * This will return the block group at or after bytenr if contains is 0, else
203 * it will return the block group that contains the bytenr
205 static struct btrfs_block_group *block_group_cache_tree_search(
206 struct btrfs_fs_info *info, u64 bytenr, int contains)
208 struct btrfs_block_group *cache, *ret = NULL;
212 read_lock(&info->block_group_cache_lock);
213 n = info->block_group_cache_tree.rb_root.rb_node;
216 cache = rb_entry(n, struct btrfs_block_group, cache_node);
217 end = cache->start + cache->length - 1;
218 start = cache->start;
220 if (bytenr < start) {
221 if (!contains && (!ret || start < ret->start))
224 } else if (bytenr > start) {
225 if (contains && bytenr <= end) {
236 btrfs_get_block_group(ret);
237 read_unlock(&info->block_group_cache_lock);
243 * Return the block group that starts at or after bytenr
245 struct btrfs_block_group *btrfs_lookup_first_block_group(
246 struct btrfs_fs_info *info, u64 bytenr)
248 return block_group_cache_tree_search(info, bytenr, 0);
252 * Return the block group that contains the given bytenr
254 struct btrfs_block_group *btrfs_lookup_block_group(
255 struct btrfs_fs_info *info, u64 bytenr)
257 return block_group_cache_tree_search(info, bytenr, 1);
260 struct btrfs_block_group *btrfs_next_block_group(
261 struct btrfs_block_group *cache)
263 struct btrfs_fs_info *fs_info = cache->fs_info;
264 struct rb_node *node;
266 read_lock(&fs_info->block_group_cache_lock);
268 /* If our block group was removed, we need a full search. */
269 if (RB_EMPTY_NODE(&cache->cache_node)) {
270 const u64 next_bytenr = cache->start + cache->length;
272 read_unlock(&fs_info->block_group_cache_lock);
273 btrfs_put_block_group(cache);
274 return btrfs_lookup_first_block_group(fs_info, next_bytenr);
276 node = rb_next(&cache->cache_node);
277 btrfs_put_block_group(cache);
279 cache = rb_entry(node, struct btrfs_block_group, cache_node);
280 btrfs_get_block_group(cache);
283 read_unlock(&fs_info->block_group_cache_lock);
288 * Check if we can do a NOCOW write for a given extent.
290 * @fs_info: The filesystem information object.
291 * @bytenr: Logical start address of the extent.
293 * Check if we can do a NOCOW write for the given extent, and increments the
294 * number of NOCOW writers in the block group that contains the extent, as long
295 * as the block group exists and it's currently not in read-only mode.
297 * Returns: A non-NULL block group pointer if we can do a NOCOW write, the caller
298 * is responsible for calling btrfs_dec_nocow_writers() later.
300 * Or NULL if we can not do a NOCOW write
302 struct btrfs_block_group *btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info,
305 struct btrfs_block_group *bg;
306 bool can_nocow = true;
308 bg = btrfs_lookup_block_group(fs_info, bytenr);
312 spin_lock(&bg->lock);
316 atomic_inc(&bg->nocow_writers);
317 spin_unlock(&bg->lock);
320 btrfs_put_block_group(bg);
324 /* No put on block group, done by btrfs_dec_nocow_writers(). */
329 * Decrement the number of NOCOW writers in a block group.
331 * @bg: The block group.
333 * This is meant to be called after a previous call to btrfs_inc_nocow_writers(),
334 * and on the block group returned by that call. Typically this is called after
335 * creating an ordered extent for a NOCOW write, to prevent races with scrub and
338 * After this call, the caller should not use the block group anymore. It it wants
339 * to use it, then it should get a reference on it before calling this function.
341 void btrfs_dec_nocow_writers(struct btrfs_block_group *bg)
343 if (atomic_dec_and_test(&bg->nocow_writers))
344 wake_up_var(&bg->nocow_writers);
346 /* For the lookup done by a previous call to btrfs_inc_nocow_writers(). */
347 btrfs_put_block_group(bg);
350 void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
352 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
355 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
358 struct btrfs_block_group *bg;
360 bg = btrfs_lookup_block_group(fs_info, start);
362 if (atomic_dec_and_test(&bg->reservations))
363 wake_up_var(&bg->reservations);
364 btrfs_put_block_group(bg);
367 void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
369 struct btrfs_space_info *space_info = bg->space_info;
373 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
377 * Our block group is read only but before we set it to read only,
378 * some task might have had allocated an extent from it already, but it
379 * has not yet created a respective ordered extent (and added it to a
380 * root's list of ordered extents).
381 * Therefore wait for any task currently allocating extents, since the
382 * block group's reservations counter is incremented while a read lock
383 * on the groups' semaphore is held and decremented after releasing
384 * the read access on that semaphore and creating the ordered extent.
386 down_write(&space_info->groups_sem);
387 up_write(&space_info->groups_sem);
389 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
392 struct btrfs_caching_control *btrfs_get_caching_control(
393 struct btrfs_block_group *cache)
395 struct btrfs_caching_control *ctl;
397 spin_lock(&cache->lock);
398 if (!cache->caching_ctl) {
399 spin_unlock(&cache->lock);
403 ctl = cache->caching_ctl;
404 refcount_inc(&ctl->count);
405 spin_unlock(&cache->lock);
409 void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
411 if (refcount_dec_and_test(&ctl->count))
416 * When we wait for progress in the block group caching, its because our
417 * allocation attempt failed at least once. So, we must sleep and let some
418 * progress happen before we try again.
420 * This function will sleep at least once waiting for new free space to show
421 * up, and then it will check the block group free space numbers for our min
422 * num_bytes. Another option is to have it go ahead and look in the rbtree for
423 * a free extent of a given size, but this is a good start.
425 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
426 * any of the information in this block group.
428 void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
431 struct btrfs_caching_control *caching_ctl;
433 caching_ctl = btrfs_get_caching_control(cache);
437 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
438 (cache->free_space_ctl->free_space >= num_bytes));
440 btrfs_put_caching_control(caching_ctl);
443 int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
445 struct btrfs_caching_control *caching_ctl;
448 caching_ctl = btrfs_get_caching_control(cache);
450 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
452 wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
453 if (cache->cached == BTRFS_CACHE_ERROR)
455 btrfs_put_caching_control(caching_ctl);
459 static bool space_cache_v1_done(struct btrfs_block_group *cache)
463 spin_lock(&cache->lock);
464 ret = cache->cached != BTRFS_CACHE_FAST;
465 spin_unlock(&cache->lock);
470 void btrfs_wait_space_cache_v1_finished(struct btrfs_block_group *cache,
471 struct btrfs_caching_control *caching_ctl)
473 wait_event(caching_ctl->wait, space_cache_v1_done(cache));
476 #ifdef CONFIG_BTRFS_DEBUG
477 static void fragment_free_space(struct btrfs_block_group *block_group)
479 struct btrfs_fs_info *fs_info = block_group->fs_info;
480 u64 start = block_group->start;
481 u64 len = block_group->length;
482 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
483 fs_info->nodesize : fs_info->sectorsize;
484 u64 step = chunk << 1;
486 while (len > chunk) {
487 btrfs_remove_free_space(block_group, start, chunk);
498 * This is only called by btrfs_cache_block_group, since we could have freed
499 * extents we need to check the pinned_extents for any extents that can't be
500 * used yet since their free space will be released as soon as the transaction
503 u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
505 struct btrfs_fs_info *info = block_group->fs_info;
506 u64 extent_start, extent_end, size, total_added = 0;
509 while (start < end) {
510 ret = find_first_extent_bit(&info->excluded_extents, start,
511 &extent_start, &extent_end,
512 EXTENT_DIRTY | EXTENT_UPTODATE,
517 if (extent_start <= start) {
518 start = extent_end + 1;
519 } else if (extent_start > start && extent_start < end) {
520 size = extent_start - start;
522 ret = btrfs_add_free_space_async_trimmed(block_group,
524 BUG_ON(ret); /* -ENOMEM or logic error */
525 start = extent_end + 1;
534 ret = btrfs_add_free_space_async_trimmed(block_group, start,
536 BUG_ON(ret); /* -ENOMEM or logic error */
542 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
544 struct btrfs_block_group *block_group = caching_ctl->block_group;
545 struct btrfs_fs_info *fs_info = block_group->fs_info;
546 struct btrfs_root *extent_root;
547 struct btrfs_path *path;
548 struct extent_buffer *leaf;
549 struct btrfs_key key;
556 path = btrfs_alloc_path();
560 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
561 extent_root = btrfs_extent_root(fs_info, last);
563 #ifdef CONFIG_BTRFS_DEBUG
565 * If we're fragmenting we don't want to make anybody think we can
566 * allocate from this block group until we've had a chance to fragment
569 if (btrfs_should_fragment_free_space(block_group))
573 * We don't want to deadlock with somebody trying to allocate a new
574 * extent for the extent root while also trying to search the extent
575 * root to add free space. So we skip locking and search the commit
576 * root, since its read-only
578 path->skip_locking = 1;
579 path->search_commit_root = 1;
580 path->reada = READA_FORWARD;
584 key.type = BTRFS_EXTENT_ITEM_KEY;
587 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
591 leaf = path->nodes[0];
592 nritems = btrfs_header_nritems(leaf);
595 if (btrfs_fs_closing(fs_info) > 1) {
600 if (path->slots[0] < nritems) {
601 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
603 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
607 if (need_resched() ||
608 rwsem_is_contended(&fs_info->commit_root_sem)) {
610 caching_ctl->progress = last;
611 btrfs_release_path(path);
612 up_read(&fs_info->commit_root_sem);
613 mutex_unlock(&caching_ctl->mutex);
615 mutex_lock(&caching_ctl->mutex);
616 down_read(&fs_info->commit_root_sem);
620 ret = btrfs_next_leaf(extent_root, path);
625 leaf = path->nodes[0];
626 nritems = btrfs_header_nritems(leaf);
630 if (key.objectid < last) {
633 key.type = BTRFS_EXTENT_ITEM_KEY;
636 caching_ctl->progress = last;
637 btrfs_release_path(path);
641 if (key.objectid < block_group->start) {
646 if (key.objectid >= block_group->start + block_group->length)
649 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
650 key.type == BTRFS_METADATA_ITEM_KEY) {
651 total_found += add_new_free_space(block_group, last,
653 if (key.type == BTRFS_METADATA_ITEM_KEY)
654 last = key.objectid +
657 last = key.objectid + key.offset;
659 if (total_found > CACHING_CTL_WAKE_UP) {
662 wake_up(&caching_ctl->wait);
669 total_found += add_new_free_space(block_group, last,
670 block_group->start + block_group->length);
671 caching_ctl->progress = (u64)-1;
674 btrfs_free_path(path);
678 static noinline void caching_thread(struct btrfs_work *work)
680 struct btrfs_block_group *block_group;
681 struct btrfs_fs_info *fs_info;
682 struct btrfs_caching_control *caching_ctl;
685 caching_ctl = container_of(work, struct btrfs_caching_control, work);
686 block_group = caching_ctl->block_group;
687 fs_info = block_group->fs_info;
689 mutex_lock(&caching_ctl->mutex);
690 down_read(&fs_info->commit_root_sem);
692 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
693 ret = load_free_space_cache(block_group);
700 * We failed to load the space cache, set ourselves to
701 * CACHE_STARTED and carry on.
703 spin_lock(&block_group->lock);
704 block_group->cached = BTRFS_CACHE_STARTED;
705 spin_unlock(&block_group->lock);
706 wake_up(&caching_ctl->wait);
710 * If we are in the transaction that populated the free space tree we
711 * can't actually cache from the free space tree as our commit root and
712 * real root are the same, so we could change the contents of the blocks
713 * while caching. Instead do the slow caching in this case, and after
714 * the transaction has committed we will be safe.
716 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
717 !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
718 ret = load_free_space_tree(caching_ctl);
720 ret = load_extent_tree_free(caching_ctl);
722 spin_lock(&block_group->lock);
723 block_group->caching_ctl = NULL;
724 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
725 spin_unlock(&block_group->lock);
727 #ifdef CONFIG_BTRFS_DEBUG
728 if (btrfs_should_fragment_free_space(block_group)) {
731 spin_lock(&block_group->space_info->lock);
732 spin_lock(&block_group->lock);
733 bytes_used = block_group->length - block_group->used;
734 block_group->space_info->bytes_used += bytes_used >> 1;
735 spin_unlock(&block_group->lock);
736 spin_unlock(&block_group->space_info->lock);
737 fragment_free_space(block_group);
741 caching_ctl->progress = (u64)-1;
743 up_read(&fs_info->commit_root_sem);
744 btrfs_free_excluded_extents(block_group);
745 mutex_unlock(&caching_ctl->mutex);
747 wake_up(&caching_ctl->wait);
749 btrfs_put_caching_control(caching_ctl);
750 btrfs_put_block_group(block_group);
753 int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
756 struct btrfs_fs_info *fs_info = cache->fs_info;
757 struct btrfs_caching_control *caching_ctl = NULL;
760 /* Allocator for zoned filesystems does not use the cache at all */
761 if (btrfs_is_zoned(fs_info))
764 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
768 INIT_LIST_HEAD(&caching_ctl->list);
769 mutex_init(&caching_ctl->mutex);
770 init_waitqueue_head(&caching_ctl->wait);
771 caching_ctl->block_group = cache;
772 caching_ctl->progress = cache->start;
773 refcount_set(&caching_ctl->count, 2);
774 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
776 spin_lock(&cache->lock);
777 if (cache->cached != BTRFS_CACHE_NO) {
780 caching_ctl = cache->caching_ctl;
782 refcount_inc(&caching_ctl->count);
783 spin_unlock(&cache->lock);
786 WARN_ON(cache->caching_ctl);
787 cache->caching_ctl = caching_ctl;
788 if (btrfs_test_opt(fs_info, SPACE_CACHE))
789 cache->cached = BTRFS_CACHE_FAST;
791 cache->cached = BTRFS_CACHE_STARTED;
792 cache->has_caching_ctl = 1;
793 spin_unlock(&cache->lock);
795 write_lock(&fs_info->block_group_cache_lock);
796 refcount_inc(&caching_ctl->count);
797 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
798 write_unlock(&fs_info->block_group_cache_lock);
800 btrfs_get_block_group(cache);
802 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
804 if (load_cache_only && caching_ctl)
805 btrfs_wait_space_cache_v1_finished(cache, caching_ctl);
807 btrfs_put_caching_control(caching_ctl);
812 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
814 u64 extra_flags = chunk_to_extended(flags) &
815 BTRFS_EXTENDED_PROFILE_MASK;
817 write_seqlock(&fs_info->profiles_lock);
818 if (flags & BTRFS_BLOCK_GROUP_DATA)
819 fs_info->avail_data_alloc_bits &= ~extra_flags;
820 if (flags & BTRFS_BLOCK_GROUP_METADATA)
821 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
822 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
823 fs_info->avail_system_alloc_bits &= ~extra_flags;
824 write_sequnlock(&fs_info->profiles_lock);
828 * Clear incompat bits for the following feature(s):
830 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
831 * in the whole filesystem
833 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
835 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
837 bool found_raid56 = false;
838 bool found_raid1c34 = false;
840 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
841 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
842 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
843 struct list_head *head = &fs_info->space_info;
844 struct btrfs_space_info *sinfo;
846 list_for_each_entry_rcu(sinfo, head, list) {
847 down_read(&sinfo->groups_sem);
848 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
850 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
852 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
853 found_raid1c34 = true;
854 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
855 found_raid1c34 = true;
856 up_read(&sinfo->groups_sem);
859 btrfs_clear_fs_incompat(fs_info, RAID56);
861 btrfs_clear_fs_incompat(fs_info, RAID1C34);
865 static int remove_block_group_item(struct btrfs_trans_handle *trans,
866 struct btrfs_path *path,
867 struct btrfs_block_group *block_group)
869 struct btrfs_fs_info *fs_info = trans->fs_info;
870 struct btrfs_root *root;
871 struct btrfs_key key;
874 root = btrfs_block_group_root(fs_info);
875 key.objectid = block_group->start;
876 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
877 key.offset = block_group->length;
879 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
885 ret = btrfs_del_item(trans, root, path);
889 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
890 u64 group_start, struct extent_map *em)
892 struct btrfs_fs_info *fs_info = trans->fs_info;
893 struct btrfs_path *path;
894 struct btrfs_block_group *block_group;
895 struct btrfs_free_cluster *cluster;
897 struct kobject *kobj = NULL;
901 struct btrfs_caching_control *caching_ctl = NULL;
903 bool remove_rsv = false;
905 block_group = btrfs_lookup_block_group(fs_info, group_start);
906 BUG_ON(!block_group);
907 BUG_ON(!block_group->ro);
909 trace_btrfs_remove_block_group(block_group);
911 * Free the reserved super bytes from this block group before
914 btrfs_free_excluded_extents(block_group);
915 btrfs_free_ref_tree_range(fs_info, block_group->start,
916 block_group->length);
918 index = btrfs_bg_flags_to_raid_index(block_group->flags);
919 factor = btrfs_bg_type_to_factor(block_group->flags);
921 /* make sure this block group isn't part of an allocation cluster */
922 cluster = &fs_info->data_alloc_cluster;
923 spin_lock(&cluster->refill_lock);
924 btrfs_return_cluster_to_free_space(block_group, cluster);
925 spin_unlock(&cluster->refill_lock);
928 * make sure this block group isn't part of a metadata
931 cluster = &fs_info->meta_alloc_cluster;
932 spin_lock(&cluster->refill_lock);
933 btrfs_return_cluster_to_free_space(block_group, cluster);
934 spin_unlock(&cluster->refill_lock);
936 btrfs_clear_treelog_bg(block_group);
937 btrfs_clear_data_reloc_bg(block_group);
939 path = btrfs_alloc_path();
946 * get the inode first so any iput calls done for the io_list
947 * aren't the final iput (no unlinks allowed now)
949 inode = lookup_free_space_inode(block_group, path);
951 mutex_lock(&trans->transaction->cache_write_mutex);
953 * Make sure our free space cache IO is done before removing the
956 spin_lock(&trans->transaction->dirty_bgs_lock);
957 if (!list_empty(&block_group->io_list)) {
958 list_del_init(&block_group->io_list);
960 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
962 spin_unlock(&trans->transaction->dirty_bgs_lock);
963 btrfs_wait_cache_io(trans, block_group, path);
964 btrfs_put_block_group(block_group);
965 spin_lock(&trans->transaction->dirty_bgs_lock);
968 if (!list_empty(&block_group->dirty_list)) {
969 list_del_init(&block_group->dirty_list);
971 btrfs_put_block_group(block_group);
973 spin_unlock(&trans->transaction->dirty_bgs_lock);
974 mutex_unlock(&trans->transaction->cache_write_mutex);
976 ret = btrfs_remove_free_space_inode(trans, inode, block_group);
980 write_lock(&fs_info->block_group_cache_lock);
981 rb_erase_cached(&block_group->cache_node,
982 &fs_info->block_group_cache_tree);
983 RB_CLEAR_NODE(&block_group->cache_node);
985 /* Once for the block groups rbtree */
986 btrfs_put_block_group(block_group);
988 write_unlock(&fs_info->block_group_cache_lock);
990 down_write(&block_group->space_info->groups_sem);
992 * we must use list_del_init so people can check to see if they
993 * are still on the list after taking the semaphore
995 list_del_init(&block_group->list);
996 if (list_empty(&block_group->space_info->block_groups[index])) {
997 kobj = block_group->space_info->block_group_kobjs[index];
998 block_group->space_info->block_group_kobjs[index] = NULL;
999 clear_avail_alloc_bits(fs_info, block_group->flags);
1001 up_write(&block_group->space_info->groups_sem);
1002 clear_incompat_bg_bits(fs_info, block_group->flags);
1008 if (block_group->has_caching_ctl)
1009 caching_ctl = btrfs_get_caching_control(block_group);
1010 if (block_group->cached == BTRFS_CACHE_STARTED)
1011 btrfs_wait_block_group_cache_done(block_group);
1012 if (block_group->has_caching_ctl) {
1013 write_lock(&fs_info->block_group_cache_lock);
1015 struct btrfs_caching_control *ctl;
1017 list_for_each_entry(ctl,
1018 &fs_info->caching_block_groups, list)
1019 if (ctl->block_group == block_group) {
1021 refcount_inc(&caching_ctl->count);
1026 list_del_init(&caching_ctl->list);
1027 write_unlock(&fs_info->block_group_cache_lock);
1029 /* Once for the caching bgs list and once for us. */
1030 btrfs_put_caching_control(caching_ctl);
1031 btrfs_put_caching_control(caching_ctl);
1035 spin_lock(&trans->transaction->dirty_bgs_lock);
1036 WARN_ON(!list_empty(&block_group->dirty_list));
1037 WARN_ON(!list_empty(&block_group->io_list));
1038 spin_unlock(&trans->transaction->dirty_bgs_lock);
1040 btrfs_remove_free_space_cache(block_group);
1042 spin_lock(&block_group->space_info->lock);
1043 list_del_init(&block_group->ro_list);
1045 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1046 WARN_ON(block_group->space_info->total_bytes
1047 < block_group->length);
1048 WARN_ON(block_group->space_info->bytes_readonly
1049 < block_group->length - block_group->zone_unusable);
1050 WARN_ON(block_group->space_info->bytes_zone_unusable
1051 < block_group->zone_unusable);
1052 WARN_ON(block_group->space_info->disk_total
1053 < block_group->length * factor);
1054 WARN_ON(block_group->zone_is_active &&
1055 block_group->space_info->active_total_bytes
1056 < block_group->length);
1058 block_group->space_info->total_bytes -= block_group->length;
1059 if (block_group->zone_is_active)
1060 block_group->space_info->active_total_bytes -= block_group->length;
1061 block_group->space_info->bytes_readonly -=
1062 (block_group->length - block_group->zone_unusable);
1063 block_group->space_info->bytes_zone_unusable -=
1064 block_group->zone_unusable;
1065 block_group->space_info->disk_total -= block_group->length * factor;
1067 spin_unlock(&block_group->space_info->lock);
1070 * Remove the free space for the block group from the free space tree
1071 * and the block group's item from the extent tree before marking the
1072 * block group as removed. This is to prevent races with tasks that
1073 * freeze and unfreeze a block group, this task and another task
1074 * allocating a new block group - the unfreeze task ends up removing
1075 * the block group's extent map before the task calling this function
1076 * deletes the block group item from the extent tree, allowing for
1077 * another task to attempt to create another block group with the same
1078 * item key (and failing with -EEXIST and a transaction abort).
1080 ret = remove_block_group_free_space(trans, block_group);
1084 ret = remove_block_group_item(trans, path, block_group);
1088 spin_lock(&block_group->lock);
1089 block_group->removed = 1;
1091 * At this point trimming or scrub can't start on this block group,
1092 * because we removed the block group from the rbtree
1093 * fs_info->block_group_cache_tree so no one can't find it anymore and
1094 * even if someone already got this block group before we removed it
1095 * from the rbtree, they have already incremented block_group->frozen -
1096 * if they didn't, for the trimming case they won't find any free space
1097 * entries because we already removed them all when we called
1098 * btrfs_remove_free_space_cache().
1100 * And we must not remove the extent map from the fs_info->mapping_tree
1101 * to prevent the same logical address range and physical device space
1102 * ranges from being reused for a new block group. This is needed to
1103 * avoid races with trimming and scrub.
1105 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1106 * completely transactionless, so while it is trimming a range the
1107 * currently running transaction might finish and a new one start,
1108 * allowing for new block groups to be created that can reuse the same
1109 * physical device locations unless we take this special care.
1111 * There may also be an implicit trim operation if the file system
1112 * is mounted with -odiscard. The same protections must remain
1113 * in place until the extents have been discarded completely when
1114 * the transaction commit has completed.
1116 remove_em = (atomic_read(&block_group->frozen) == 0);
1117 spin_unlock(&block_group->lock);
1120 struct extent_map_tree *em_tree;
1122 em_tree = &fs_info->mapping_tree;
1123 write_lock(&em_tree->lock);
1124 remove_extent_mapping(em_tree, em);
1125 write_unlock(&em_tree->lock);
1126 /* once for the tree */
1127 free_extent_map(em);
1131 /* Once for the lookup reference */
1132 btrfs_put_block_group(block_group);
1134 btrfs_delayed_refs_rsv_release(fs_info, 1);
1135 btrfs_free_path(path);
1139 struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1140 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1142 struct btrfs_root *root = btrfs_block_group_root(fs_info);
1143 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1144 struct extent_map *em;
1145 struct map_lookup *map;
1146 unsigned int num_items;
1148 read_lock(&em_tree->lock);
1149 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1150 read_unlock(&em_tree->lock);
1151 ASSERT(em && em->start == chunk_offset);
1154 * We need to reserve 3 + N units from the metadata space info in order
1155 * to remove a block group (done at btrfs_remove_chunk() and at
1156 * btrfs_remove_block_group()), which are used for:
1158 * 1 unit for adding the free space inode's orphan (located in the tree
1160 * 1 unit for deleting the block group item (located in the extent
1162 * 1 unit for deleting the free space item (located in tree of tree
1164 * N units for deleting N device extent items corresponding to each
1165 * stripe (located in the device tree).
1167 * In order to remove a block group we also need to reserve units in the
1168 * system space info in order to update the chunk tree (update one or
1169 * more device items and remove one chunk item), but this is done at
1170 * btrfs_remove_chunk() through a call to check_system_chunk().
1172 map = em->map_lookup;
1173 num_items = 3 + map->num_stripes;
1174 free_extent_map(em);
1176 return btrfs_start_transaction_fallback_global_rsv(root, num_items);
1180 * Mark block group @cache read-only, so later write won't happen to block
1183 * If @force is not set, this function will only mark the block group readonly
1184 * if we have enough free space (1M) in other metadata/system block groups.
1185 * If @force is not set, this function will mark the block group readonly
1186 * without checking free space.
1188 * NOTE: This function doesn't care if other block groups can contain all the
1189 * data in this block group. That check should be done by relocation routine,
1190 * not this function.
1192 static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
1194 struct btrfs_space_info *sinfo = cache->space_info;
1198 spin_lock(&sinfo->lock);
1199 spin_lock(&cache->lock);
1201 if (cache->swap_extents) {
1212 num_bytes = cache->length - cache->reserved - cache->pinned -
1213 cache->bytes_super - cache->zone_unusable - cache->used;
1216 * Data never overcommits, even in mixed mode, so do just the straight
1217 * check of left over space in how much we have allocated.
1221 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1222 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1225 * Here we make sure if we mark this bg RO, we still have enough
1226 * free space as buffer.
1228 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1232 * We overcommit metadata, so we need to do the
1233 * btrfs_can_overcommit check here, and we need to pass in
1234 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1235 * leeway to allow us to mark this block group as read only.
1237 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1238 BTRFS_RESERVE_NO_FLUSH))
1243 sinfo->bytes_readonly += num_bytes;
1244 if (btrfs_is_zoned(cache->fs_info)) {
1245 /* Migrate zone_unusable bytes to readonly */
1246 sinfo->bytes_readonly += cache->zone_unusable;
1247 sinfo->bytes_zone_unusable -= cache->zone_unusable;
1248 cache->zone_unusable = 0;
1251 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
1254 spin_unlock(&cache->lock);
1255 spin_unlock(&sinfo->lock);
1256 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1257 btrfs_info(cache->fs_info,
1258 "unable to make block group %llu ro", cache->start);
1259 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1264 static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1265 struct btrfs_block_group *bg)
1267 struct btrfs_fs_info *fs_info = bg->fs_info;
1268 struct btrfs_transaction *prev_trans = NULL;
1269 const u64 start = bg->start;
1270 const u64 end = start + bg->length - 1;
1273 spin_lock(&fs_info->trans_lock);
1274 if (trans->transaction->list.prev != &fs_info->trans_list) {
1275 prev_trans = list_last_entry(&trans->transaction->list,
1276 struct btrfs_transaction, list);
1277 refcount_inc(&prev_trans->use_count);
1279 spin_unlock(&fs_info->trans_lock);
1282 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1283 * btrfs_finish_extent_commit(). If we are at transaction N, another
1284 * task might be running finish_extent_commit() for the previous
1285 * transaction N - 1, and have seen a range belonging to the block
1286 * group in pinned_extents before we were able to clear the whole block
1287 * group range from pinned_extents. This means that task can lookup for
1288 * the block group after we unpinned it from pinned_extents and removed
1289 * it, leading to a BUG_ON() at unpin_extent_range().
1291 mutex_lock(&fs_info->unused_bg_unpin_mutex);
1293 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1299 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
1302 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1304 btrfs_put_transaction(prev_trans);
1310 * Process the unused_bgs list and remove any that don't have any allocated
1311 * space inside of them.
1313 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1315 struct btrfs_block_group *block_group;
1316 struct btrfs_space_info *space_info;
1317 struct btrfs_trans_handle *trans;
1318 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1321 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1325 * Long running balances can keep us blocked here for eternity, so
1326 * simply skip deletion if we're unable to get the mutex.
1328 if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
1331 spin_lock(&fs_info->unused_bgs_lock);
1332 while (!list_empty(&fs_info->unused_bgs)) {
1335 block_group = list_first_entry(&fs_info->unused_bgs,
1336 struct btrfs_block_group,
1338 list_del_init(&block_group->bg_list);
1340 space_info = block_group->space_info;
1342 if (ret || btrfs_mixed_space_info(space_info)) {
1343 btrfs_put_block_group(block_group);
1346 spin_unlock(&fs_info->unused_bgs_lock);
1348 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1350 /* Don't want to race with allocators so take the groups_sem */
1351 down_write(&space_info->groups_sem);
1354 * Async discard moves the final block group discard to be prior
1355 * to the unused_bgs code path. Therefore, if it's not fully
1356 * trimmed, punt it back to the async discard lists.
1358 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1359 !btrfs_is_free_space_trimmed(block_group)) {
1360 trace_btrfs_skip_unused_block_group(block_group);
1361 up_write(&space_info->groups_sem);
1362 /* Requeue if we failed because of async discard */
1363 btrfs_discard_queue_work(&fs_info->discard_ctl,
1368 spin_lock(&block_group->lock);
1369 if (block_group->reserved || block_group->pinned ||
1370 block_group->used || block_group->ro ||
1371 list_is_singular(&block_group->list)) {
1373 * We want to bail if we made new allocations or have
1374 * outstanding allocations in this block group. We do
1375 * the ro check in case balance is currently acting on
1378 trace_btrfs_skip_unused_block_group(block_group);
1379 spin_unlock(&block_group->lock);
1380 up_write(&space_info->groups_sem);
1383 spin_unlock(&block_group->lock);
1385 /* We don't want to force the issue, only flip if it's ok. */
1386 ret = inc_block_group_ro(block_group, 0);
1387 up_write(&space_info->groups_sem);
1393 ret = btrfs_zone_finish(block_group);
1395 btrfs_dec_block_group_ro(block_group);
1402 * Want to do this before we do anything else so we can recover
1403 * properly if we fail to join the transaction.
1405 trans = btrfs_start_trans_remove_block_group(fs_info,
1406 block_group->start);
1407 if (IS_ERR(trans)) {
1408 btrfs_dec_block_group_ro(block_group);
1409 ret = PTR_ERR(trans);
1414 * We could have pending pinned extents for this block group,
1415 * just delete them, we don't care about them anymore.
1417 if (!clean_pinned_extents(trans, block_group)) {
1418 btrfs_dec_block_group_ro(block_group);
1423 * At this point, the block_group is read only and should fail
1424 * new allocations. However, btrfs_finish_extent_commit() can
1425 * cause this block_group to be placed back on the discard
1426 * lists because now the block_group isn't fully discarded.
1427 * Bail here and try again later after discarding everything.
1429 spin_lock(&fs_info->discard_ctl.lock);
1430 if (!list_empty(&block_group->discard_list)) {
1431 spin_unlock(&fs_info->discard_ctl.lock);
1432 btrfs_dec_block_group_ro(block_group);
1433 btrfs_discard_queue_work(&fs_info->discard_ctl,
1437 spin_unlock(&fs_info->discard_ctl.lock);
1439 /* Reset pinned so btrfs_put_block_group doesn't complain */
1440 spin_lock(&space_info->lock);
1441 spin_lock(&block_group->lock);
1443 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1444 -block_group->pinned);
1445 space_info->bytes_readonly += block_group->pinned;
1446 block_group->pinned = 0;
1448 spin_unlock(&block_group->lock);
1449 spin_unlock(&space_info->lock);
1452 * The normal path here is an unused block group is passed here,
1453 * then trimming is handled in the transaction commit path.
1454 * Async discard interposes before this to do the trimming
1455 * before coming down the unused block group path as trimming
1456 * will no longer be done later in the transaction commit path.
1458 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1462 * DISCARD can flip during remount. On zoned filesystems, we
1463 * need to reset sequential-required zones.
1465 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) ||
1466 btrfs_is_zoned(fs_info);
1468 /* Implicit trim during transaction commit. */
1470 btrfs_freeze_block_group(block_group);
1473 * Btrfs_remove_chunk will abort the transaction if things go
1476 ret = btrfs_remove_chunk(trans, block_group->start);
1480 btrfs_unfreeze_block_group(block_group);
1485 * If we're not mounted with -odiscard, we can just forget
1486 * about this block group. Otherwise we'll need to wait
1487 * until transaction commit to do the actual discard.
1490 spin_lock(&fs_info->unused_bgs_lock);
1492 * A concurrent scrub might have added us to the list
1493 * fs_info->unused_bgs, so use a list_move operation
1494 * to add the block group to the deleted_bgs list.
1496 list_move(&block_group->bg_list,
1497 &trans->transaction->deleted_bgs);
1498 spin_unlock(&fs_info->unused_bgs_lock);
1499 btrfs_get_block_group(block_group);
1502 btrfs_end_transaction(trans);
1504 btrfs_put_block_group(block_group);
1505 spin_lock(&fs_info->unused_bgs_lock);
1507 spin_unlock(&fs_info->unused_bgs_lock);
1508 mutex_unlock(&fs_info->reclaim_bgs_lock);
1512 btrfs_end_transaction(trans);
1513 mutex_unlock(&fs_info->reclaim_bgs_lock);
1514 btrfs_put_block_group(block_group);
1515 btrfs_discard_punt_unused_bgs_list(fs_info);
1518 void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1520 struct btrfs_fs_info *fs_info = bg->fs_info;
1522 spin_lock(&fs_info->unused_bgs_lock);
1523 if (list_empty(&bg->bg_list)) {
1524 btrfs_get_block_group(bg);
1525 trace_btrfs_add_unused_block_group(bg);
1526 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1528 spin_unlock(&fs_info->unused_bgs_lock);
1532 * We want block groups with a low number of used bytes to be in the beginning
1533 * of the list, so they will get reclaimed first.
1535 static int reclaim_bgs_cmp(void *unused, const struct list_head *a,
1536 const struct list_head *b)
1538 const struct btrfs_block_group *bg1, *bg2;
1540 bg1 = list_entry(a, struct btrfs_block_group, bg_list);
1541 bg2 = list_entry(b, struct btrfs_block_group, bg_list);
1543 return bg1->used > bg2->used;
1546 static inline bool btrfs_should_reclaim(struct btrfs_fs_info *fs_info)
1548 if (btrfs_is_zoned(fs_info))
1549 return btrfs_zoned_should_reclaim(fs_info);
1553 void btrfs_reclaim_bgs_work(struct work_struct *work)
1555 struct btrfs_fs_info *fs_info =
1556 container_of(work, struct btrfs_fs_info, reclaim_bgs_work);
1557 struct btrfs_block_group *bg;
1558 struct btrfs_space_info *space_info;
1560 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1563 if (!btrfs_should_reclaim(fs_info))
1566 sb_start_write(fs_info->sb);
1568 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
1569 sb_end_write(fs_info->sb);
1574 * Long running balances can keep us blocked here for eternity, so
1575 * simply skip reclaim if we're unable to get the mutex.
1577 if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) {
1578 btrfs_exclop_finish(fs_info);
1579 sb_end_write(fs_info->sb);
1583 spin_lock(&fs_info->unused_bgs_lock);
1585 * Sort happens under lock because we can't simply splice it and sort.
1586 * The block groups might still be in use and reachable via bg_list,
1587 * and their presence in the reclaim_bgs list must be preserved.
1589 list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp);
1590 while (!list_empty(&fs_info->reclaim_bgs)) {
1594 bg = list_first_entry(&fs_info->reclaim_bgs,
1595 struct btrfs_block_group,
1597 list_del_init(&bg->bg_list);
1599 space_info = bg->space_info;
1600 spin_unlock(&fs_info->unused_bgs_lock);
1602 /* Don't race with allocators so take the groups_sem */
1603 down_write(&space_info->groups_sem);
1605 spin_lock(&bg->lock);
1606 if (bg->reserved || bg->pinned || bg->ro) {
1608 * We want to bail if we made new allocations or have
1609 * outstanding allocations in this block group. We do
1610 * the ro check in case balance is currently acting on
1613 spin_unlock(&bg->lock);
1614 up_write(&space_info->groups_sem);
1617 spin_unlock(&bg->lock);
1619 /* Get out fast, in case we're unmounting the filesystem */
1620 if (btrfs_fs_closing(fs_info)) {
1621 up_write(&space_info->groups_sem);
1626 * Cache the zone_unusable value before turning the block group
1627 * to read only. As soon as the blog group is read only it's
1628 * zone_unusable value gets moved to the block group's read-only
1629 * bytes and isn't available for calculations anymore.
1631 zone_unusable = bg->zone_unusable;
1632 ret = inc_block_group_ro(bg, 0);
1633 up_write(&space_info->groups_sem);
1638 "reclaiming chunk %llu with %llu%% used %llu%% unusable",
1639 bg->start, div_u64(bg->used * 100, bg->length),
1640 div64_u64(zone_unusable * 100, bg->length));
1641 trace_btrfs_reclaim_block_group(bg);
1642 ret = btrfs_relocate_chunk(fs_info, bg->start);
1644 btrfs_dec_block_group_ro(bg);
1645 btrfs_err(fs_info, "error relocating chunk %llu",
1650 btrfs_put_block_group(bg);
1651 spin_lock(&fs_info->unused_bgs_lock);
1653 spin_unlock(&fs_info->unused_bgs_lock);
1654 mutex_unlock(&fs_info->reclaim_bgs_lock);
1655 btrfs_exclop_finish(fs_info);
1656 sb_end_write(fs_info->sb);
1659 void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
1661 spin_lock(&fs_info->unused_bgs_lock);
1662 if (!list_empty(&fs_info->reclaim_bgs))
1663 queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
1664 spin_unlock(&fs_info->unused_bgs_lock);
1667 void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
1669 struct btrfs_fs_info *fs_info = bg->fs_info;
1671 spin_lock(&fs_info->unused_bgs_lock);
1672 if (list_empty(&bg->bg_list)) {
1673 btrfs_get_block_group(bg);
1674 trace_btrfs_add_reclaim_block_group(bg);
1675 list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
1677 spin_unlock(&fs_info->unused_bgs_lock);
1680 static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1681 struct btrfs_path *path)
1683 struct extent_map_tree *em_tree;
1684 struct extent_map *em;
1685 struct btrfs_block_group_item bg;
1686 struct extent_buffer *leaf;
1691 slot = path->slots[0];
1692 leaf = path->nodes[0];
1694 em_tree = &fs_info->mapping_tree;
1695 read_lock(&em_tree->lock);
1696 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1697 read_unlock(&em_tree->lock);
1700 "logical %llu len %llu found bg but no related chunk",
1701 key->objectid, key->offset);
1705 if (em->start != key->objectid || em->len != key->offset) {
1707 "block group %llu len %llu mismatch with chunk %llu len %llu",
1708 key->objectid, key->offset, em->start, em->len);
1713 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1715 flags = btrfs_stack_block_group_flags(&bg) &
1716 BTRFS_BLOCK_GROUP_TYPE_MASK;
1718 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1720 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1721 key->objectid, key->offset, flags,
1722 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1727 free_extent_map(em);
1731 static int find_first_block_group(struct btrfs_fs_info *fs_info,
1732 struct btrfs_path *path,
1733 struct btrfs_key *key)
1735 struct btrfs_root *root = btrfs_block_group_root(fs_info);
1737 struct btrfs_key found_key;
1739 btrfs_for_each_slot(root, key, &found_key, path, ret) {
1740 if (found_key.objectid >= key->objectid &&
1741 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1742 return read_bg_from_eb(fs_info, &found_key, path);
1748 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1750 u64 extra_flags = chunk_to_extended(flags) &
1751 BTRFS_EXTENDED_PROFILE_MASK;
1753 write_seqlock(&fs_info->profiles_lock);
1754 if (flags & BTRFS_BLOCK_GROUP_DATA)
1755 fs_info->avail_data_alloc_bits |= extra_flags;
1756 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1757 fs_info->avail_metadata_alloc_bits |= extra_flags;
1758 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1759 fs_info->avail_system_alloc_bits |= extra_flags;
1760 write_sequnlock(&fs_info->profiles_lock);
1764 * Map a physical disk address to a list of logical addresses
1766 * @fs_info: the filesystem
1767 * @chunk_start: logical address of block group
1768 * @bdev: physical device to resolve, can be NULL to indicate any device
1769 * @physical: physical address to map to logical addresses
1770 * @logical: return array of logical addresses which map to @physical
1771 * @naddrs: length of @logical
1772 * @stripe_len: size of IO stripe for the given block group
1774 * Maps a particular @physical disk address to a list of @logical addresses.
1775 * Used primarily to exclude those portions of a block group that contain super
1778 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1779 struct block_device *bdev, u64 physical, u64 **logical,
1780 int *naddrs, int *stripe_len)
1782 struct extent_map *em;
1783 struct map_lookup *map;
1786 u64 data_stripe_length;
1791 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1795 map = em->map_lookup;
1796 data_stripe_length = em->orig_block_len;
1797 io_stripe_size = map->stripe_len;
1798 chunk_start = em->start;
1800 /* For RAID5/6 adjust to a full IO stripe length */
1801 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
1802 io_stripe_size = map->stripe_len * nr_data_stripes(map);
1804 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
1810 for (i = 0; i < map->num_stripes; i++) {
1811 bool already_inserted = false;
1816 if (!in_range(physical, map->stripes[i].physical,
1817 data_stripe_length))
1820 if (bdev && map->stripes[i].dev->bdev != bdev)
1823 stripe_nr = physical - map->stripes[i].physical;
1824 stripe_nr = div64_u64_rem(stripe_nr, map->stripe_len, &offset);
1826 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
1827 BTRFS_BLOCK_GROUP_RAID10)) {
1828 stripe_nr = stripe_nr * map->num_stripes + i;
1829 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1832 * The remaining case would be for RAID56, multiply by
1833 * nr_data_stripes(). Alternatively, just use rmap_len below
1834 * instead of map->stripe_len
1837 bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
1839 /* Ensure we don't add duplicate addresses */
1840 for (j = 0; j < nr; j++) {
1841 if (buf[j] == bytenr) {
1842 already_inserted = true;
1847 if (!already_inserted)
1853 *stripe_len = io_stripe_size;
1855 free_extent_map(em);
1859 static int exclude_super_stripes(struct btrfs_block_group *cache)
1861 struct btrfs_fs_info *fs_info = cache->fs_info;
1862 const bool zoned = btrfs_is_zoned(fs_info);
1868 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1869 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
1870 cache->bytes_super += stripe_len;
1871 ret = btrfs_add_excluded_extent(fs_info, cache->start,
1877 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1878 bytenr = btrfs_sb_offset(i);
1879 ret = btrfs_rmap_block(fs_info, cache->start, NULL,
1880 bytenr, &logical, &nr, &stripe_len);
1884 /* Shouldn't have super stripes in sequential zones */
1887 "zoned: block group %llu must not contain super block",
1893 u64 len = min_t(u64, stripe_len,
1894 cache->start + cache->length - logical[nr]);
1896 cache->bytes_super += len;
1897 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
1910 static void link_block_group(struct btrfs_block_group *cache)
1912 struct btrfs_space_info *space_info = cache->space_info;
1913 int index = btrfs_bg_flags_to_raid_index(cache->flags);
1915 down_write(&space_info->groups_sem);
1916 list_add_tail(&cache->list, &space_info->block_groups[index]);
1917 up_write(&space_info->groups_sem);
1920 static struct btrfs_block_group *btrfs_create_block_group_cache(
1921 struct btrfs_fs_info *fs_info, u64 start)
1923 struct btrfs_block_group *cache;
1925 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1929 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1931 if (!cache->free_space_ctl) {
1936 cache->start = start;
1938 cache->fs_info = fs_info;
1939 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
1941 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1943 refcount_set(&cache->refs, 1);
1944 spin_lock_init(&cache->lock);
1945 init_rwsem(&cache->data_rwsem);
1946 INIT_LIST_HEAD(&cache->list);
1947 INIT_LIST_HEAD(&cache->cluster_list);
1948 INIT_LIST_HEAD(&cache->bg_list);
1949 INIT_LIST_HEAD(&cache->ro_list);
1950 INIT_LIST_HEAD(&cache->discard_list);
1951 INIT_LIST_HEAD(&cache->dirty_list);
1952 INIT_LIST_HEAD(&cache->io_list);
1953 INIT_LIST_HEAD(&cache->active_bg_list);
1954 btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
1955 atomic_set(&cache->frozen, 0);
1956 mutex_init(&cache->free_space_lock);
1957 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1963 * Iterate all chunks and verify that each of them has the corresponding block
1966 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1968 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1969 struct extent_map *em;
1970 struct btrfs_block_group *bg;
1975 read_lock(&map_tree->lock);
1977 * lookup_extent_mapping will return the first extent map
1978 * intersecting the range, so setting @len to 1 is enough to
1979 * get the first chunk.
1981 em = lookup_extent_mapping(map_tree, start, 1);
1982 read_unlock(&map_tree->lock);
1986 bg = btrfs_lookup_block_group(fs_info, em->start);
1989 "chunk start=%llu len=%llu doesn't have corresponding block group",
1990 em->start, em->len);
1992 free_extent_map(em);
1995 if (bg->start != em->start || bg->length != em->len ||
1996 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1997 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1999 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
2001 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
2002 bg->start, bg->length,
2003 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
2005 free_extent_map(em);
2006 btrfs_put_block_group(bg);
2009 start = em->start + em->len;
2010 free_extent_map(em);
2011 btrfs_put_block_group(bg);
2016 static int read_one_block_group(struct btrfs_fs_info *info,
2017 struct btrfs_block_group_item *bgi,
2018 const struct btrfs_key *key,
2021 struct btrfs_block_group *cache;
2022 struct btrfs_space_info *space_info;
2023 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
2026 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
2028 cache = btrfs_create_block_group_cache(info, key->objectid);
2032 cache->length = key->offset;
2033 cache->used = btrfs_stack_block_group_used(bgi);
2034 cache->flags = btrfs_stack_block_group_flags(bgi);
2035 cache->global_root_id = btrfs_stack_block_group_chunk_objectid(bgi);
2037 set_free_space_tree_thresholds(cache);
2041 * When we mount with old space cache, we need to
2042 * set BTRFS_DC_CLEAR and set dirty flag.
2044 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
2045 * truncate the old free space cache inode and
2047 * b) Setting 'dirty flag' makes sure that we flush
2048 * the new space cache info onto disk.
2050 if (btrfs_test_opt(info, SPACE_CACHE))
2051 cache->disk_cache_state = BTRFS_DC_CLEAR;
2053 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
2054 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
2056 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2062 ret = btrfs_load_block_group_zone_info(cache, false);
2064 btrfs_err(info, "zoned: failed to load zone info of bg %llu",
2070 * We need to exclude the super stripes now so that the space info has
2071 * super bytes accounted for, otherwise we'll think we have more space
2072 * than we actually do.
2074 ret = exclude_super_stripes(cache);
2076 /* We may have excluded something, so call this just in case. */
2077 btrfs_free_excluded_extents(cache);
2082 * For zoned filesystem, space after the allocation offset is the only
2083 * free space for a block group. So, we don't need any caching work.
2084 * btrfs_calc_zone_unusable() will set the amount of free space and
2085 * zone_unusable space.
2087 * For regular filesystem, check for two cases, either we are full, and
2088 * therefore don't need to bother with the caching work since we won't
2089 * find any space, or we are empty, and we can just add all the space
2090 * in and be done with it. This saves us _a_lot_ of time, particularly
2093 if (btrfs_is_zoned(info)) {
2094 btrfs_calc_zone_unusable(cache);
2095 /* Should not have any excluded extents. Just in case, though. */
2096 btrfs_free_excluded_extents(cache);
2097 } else if (cache->length == cache->used) {
2098 cache->last_byte_to_unpin = (u64)-1;
2099 cache->cached = BTRFS_CACHE_FINISHED;
2100 btrfs_free_excluded_extents(cache);
2101 } else if (cache->used == 0) {
2102 cache->last_byte_to_unpin = (u64)-1;
2103 cache->cached = BTRFS_CACHE_FINISHED;
2104 add_new_free_space(cache, cache->start,
2105 cache->start + cache->length);
2106 btrfs_free_excluded_extents(cache);
2109 ret = btrfs_add_block_group_cache(info, cache);
2111 btrfs_remove_free_space_cache(cache);
2114 trace_btrfs_add_block_group(info, cache, 0);
2115 btrfs_update_space_info(info, cache->flags, cache->length,
2116 cache->used, cache->bytes_super,
2117 cache->zone_unusable, cache->zone_is_active,
2120 cache->space_info = space_info;
2122 link_block_group(cache);
2124 set_avail_alloc_bits(info, cache->flags);
2125 if (btrfs_chunk_writeable(info, cache->start)) {
2126 if (cache->used == 0) {
2127 ASSERT(list_empty(&cache->bg_list));
2128 if (btrfs_test_opt(info, DISCARD_ASYNC))
2129 btrfs_discard_queue_work(&info->discard_ctl, cache);
2131 btrfs_mark_bg_unused(cache);
2134 inc_block_group_ro(cache, 1);
2139 btrfs_put_block_group(cache);
2143 static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
2145 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
2146 struct btrfs_space_info *space_info;
2147 struct rb_node *node;
2150 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
2151 struct extent_map *em;
2152 struct map_lookup *map;
2153 struct btrfs_block_group *bg;
2155 em = rb_entry(node, struct extent_map, rb_node);
2156 map = em->map_lookup;
2157 bg = btrfs_create_block_group_cache(fs_info, em->start);
2163 /* Fill dummy cache as FULL */
2164 bg->length = em->len;
2165 bg->flags = map->type;
2166 bg->last_byte_to_unpin = (u64)-1;
2167 bg->cached = BTRFS_CACHE_FINISHED;
2169 bg->flags = map->type;
2170 ret = btrfs_add_block_group_cache(fs_info, bg);
2172 * We may have some valid block group cache added already, in
2173 * that case we skip to the next one.
2175 if (ret == -EEXIST) {
2177 btrfs_put_block_group(bg);
2182 btrfs_remove_free_space_cache(bg);
2183 btrfs_put_block_group(bg);
2187 btrfs_update_space_info(fs_info, bg->flags, em->len, em->len,
2188 0, 0, false, &space_info);
2189 bg->space_info = space_info;
2190 link_block_group(bg);
2192 set_avail_alloc_bits(fs_info, bg->flags);
2195 btrfs_init_global_block_rsv(fs_info);
2199 int btrfs_read_block_groups(struct btrfs_fs_info *info)
2201 struct btrfs_root *root = btrfs_block_group_root(info);
2202 struct btrfs_path *path;
2204 struct btrfs_block_group *cache;
2205 struct btrfs_space_info *space_info;
2206 struct btrfs_key key;
2211 return fill_dummy_bgs(info);
2215 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2216 path = btrfs_alloc_path();
2220 cache_gen = btrfs_super_cache_generation(info->super_copy);
2221 if (btrfs_test_opt(info, SPACE_CACHE) &&
2222 btrfs_super_generation(info->super_copy) != cache_gen)
2224 if (btrfs_test_opt(info, CLEAR_CACHE))
2228 struct btrfs_block_group_item bgi;
2229 struct extent_buffer *leaf;
2232 ret = find_first_block_group(info, path, &key);
2238 leaf = path->nodes[0];
2239 slot = path->slots[0];
2241 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
2244 btrfs_item_key_to_cpu(leaf, &key, slot);
2245 btrfs_release_path(path);
2246 ret = read_one_block_group(info, &bgi, &key, need_clear);
2249 key.objectid += key.offset;
2252 btrfs_release_path(path);
2254 list_for_each_entry(space_info, &info->space_info, list) {
2257 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2258 if (list_empty(&space_info->block_groups[i]))
2260 cache = list_first_entry(&space_info->block_groups[i],
2261 struct btrfs_block_group,
2263 btrfs_sysfs_add_block_group_type(cache);
2266 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2267 (BTRFS_BLOCK_GROUP_RAID10 |
2268 BTRFS_BLOCK_GROUP_RAID1_MASK |
2269 BTRFS_BLOCK_GROUP_RAID56_MASK |
2270 BTRFS_BLOCK_GROUP_DUP)))
2273 * Avoid allocating from un-mirrored block group if there are
2274 * mirrored block groups.
2276 list_for_each_entry(cache,
2277 &space_info->block_groups[BTRFS_RAID_RAID0],
2279 inc_block_group_ro(cache, 1);
2280 list_for_each_entry(cache,
2281 &space_info->block_groups[BTRFS_RAID_SINGLE],
2283 inc_block_group_ro(cache, 1);
2286 btrfs_init_global_block_rsv(info);
2287 ret = check_chunk_block_group_mappings(info);
2289 btrfs_free_path(path);
2291 * We've hit some error while reading the extent tree, and have
2292 * rescue=ibadroots mount option.
2293 * Try to fill the tree using dummy block groups so that the user can
2294 * continue to mount and grab their data.
2296 if (ret && btrfs_test_opt(info, IGNOREBADROOTS))
2297 ret = fill_dummy_bgs(info);
2302 * This function, insert_block_group_item(), belongs to the phase 2 of chunk
2305 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2308 static int insert_block_group_item(struct btrfs_trans_handle *trans,
2309 struct btrfs_block_group *block_group)
2311 struct btrfs_fs_info *fs_info = trans->fs_info;
2312 struct btrfs_block_group_item bgi;
2313 struct btrfs_root *root = btrfs_block_group_root(fs_info);
2314 struct btrfs_key key;
2316 spin_lock(&block_group->lock);
2317 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2318 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2319 block_group->global_root_id);
2320 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2321 key.objectid = block_group->start;
2322 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2323 key.offset = block_group->length;
2324 spin_unlock(&block_group->lock);
2326 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2329 static int insert_dev_extent(struct btrfs_trans_handle *trans,
2330 struct btrfs_device *device, u64 chunk_offset,
2331 u64 start, u64 num_bytes)
2333 struct btrfs_fs_info *fs_info = device->fs_info;
2334 struct btrfs_root *root = fs_info->dev_root;
2335 struct btrfs_path *path;
2336 struct btrfs_dev_extent *extent;
2337 struct extent_buffer *leaf;
2338 struct btrfs_key key;
2341 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
2342 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
2343 path = btrfs_alloc_path();
2347 key.objectid = device->devid;
2348 key.type = BTRFS_DEV_EXTENT_KEY;
2350 ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent));
2354 leaf = path->nodes[0];
2355 extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
2356 btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID);
2357 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
2358 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2359 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
2361 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
2362 btrfs_mark_buffer_dirty(leaf);
2364 btrfs_free_path(path);
2369 * This function belongs to phase 2.
2371 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2374 static int insert_dev_extents(struct btrfs_trans_handle *trans,
2375 u64 chunk_offset, u64 chunk_size)
2377 struct btrfs_fs_info *fs_info = trans->fs_info;
2378 struct btrfs_device *device;
2379 struct extent_map *em;
2380 struct map_lookup *map;
2386 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
2390 map = em->map_lookup;
2391 stripe_size = em->orig_block_len;
2394 * Take the device list mutex to prevent races with the final phase of
2395 * a device replace operation that replaces the device object associated
2396 * with the map's stripes, because the device object's id can change
2397 * at any time during that final phase of the device replace operation
2398 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
2399 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
2400 * resulting in persisting a device extent item with such ID.
2402 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2403 for (i = 0; i < map->num_stripes; i++) {
2404 device = map->stripes[i].dev;
2405 dev_offset = map->stripes[i].physical;
2407 ret = insert_dev_extent(trans, device, chunk_offset, dev_offset,
2412 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2414 free_extent_map(em);
2419 * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
2422 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2425 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2427 struct btrfs_fs_info *fs_info = trans->fs_info;
2428 struct btrfs_block_group *block_group;
2431 while (!list_empty(&trans->new_bgs)) {
2434 block_group = list_first_entry(&trans->new_bgs,
2435 struct btrfs_block_group,
2440 index = btrfs_bg_flags_to_raid_index(block_group->flags);
2442 ret = insert_block_group_item(trans, block_group);
2444 btrfs_abort_transaction(trans, ret);
2445 if (!block_group->chunk_item_inserted) {
2446 mutex_lock(&fs_info->chunk_mutex);
2447 ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group);
2448 mutex_unlock(&fs_info->chunk_mutex);
2450 btrfs_abort_transaction(trans, ret);
2452 ret = insert_dev_extents(trans, block_group->start,
2453 block_group->length);
2455 btrfs_abort_transaction(trans, ret);
2456 add_block_group_free_space(trans, block_group);
2459 * If we restriped during balance, we may have added a new raid
2460 * type, so now add the sysfs entries when it is safe to do so.
2461 * We don't have to worry about locking here as it's handled in
2462 * btrfs_sysfs_add_block_group_type.
2464 if (block_group->space_info->block_group_kobjs[index] == NULL)
2465 btrfs_sysfs_add_block_group_type(block_group);
2467 /* Already aborted the transaction if it failed. */
2469 btrfs_delayed_refs_rsv_release(fs_info, 1);
2470 list_del_init(&block_group->bg_list);
2472 btrfs_trans_release_chunk_metadata(trans);
2476 * For extent tree v2 we use the block_group_item->chunk_offset to point at our
2477 * global root id. For v1 it's always set to BTRFS_FIRST_CHUNK_TREE_OBJECTID.
2479 static u64 calculate_global_root_id(struct btrfs_fs_info *fs_info, u64 offset)
2484 if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2485 return BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2487 /* If we have a smaller fs index based on 128MiB. */
2488 if (btrfs_super_total_bytes(fs_info->super_copy) <= (SZ_1G * 10ULL))
2491 offset = div64_u64(offset, div);
2492 div64_u64_rem(offset, fs_info->nr_global_roots, &index);
2496 struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
2497 u64 bytes_used, u64 type,
2498 u64 chunk_offset, u64 size)
2500 struct btrfs_fs_info *fs_info = trans->fs_info;
2501 struct btrfs_block_group *cache;
2504 btrfs_set_log_full_commit(trans);
2506 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
2508 return ERR_PTR(-ENOMEM);
2510 cache->length = size;
2511 set_free_space_tree_thresholds(cache);
2512 cache->used = bytes_used;
2513 cache->flags = type;
2514 cache->last_byte_to_unpin = (u64)-1;
2515 cache->cached = BTRFS_CACHE_FINISHED;
2516 cache->global_root_id = calculate_global_root_id(fs_info, cache->start);
2518 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
2519 cache->needs_free_space = 1;
2521 ret = btrfs_load_block_group_zone_info(cache, true);
2523 btrfs_put_block_group(cache);
2524 return ERR_PTR(ret);
2527 ret = exclude_super_stripes(cache);
2529 /* We may have excluded something, so call this just in case */
2530 btrfs_free_excluded_extents(cache);
2531 btrfs_put_block_group(cache);
2532 return ERR_PTR(ret);
2535 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2537 btrfs_free_excluded_extents(cache);
2539 #ifdef CONFIG_BTRFS_DEBUG
2540 if (btrfs_should_fragment_free_space(cache)) {
2541 u64 new_bytes_used = size - bytes_used;
2543 bytes_used += new_bytes_used >> 1;
2544 fragment_free_space(cache);
2548 * Ensure the corresponding space_info object is created and
2549 * assigned to our block group. We want our bg to be added to the rbtree
2550 * with its ->space_info set.
2552 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2553 ASSERT(cache->space_info);
2555 ret = btrfs_add_block_group_cache(fs_info, cache);
2557 btrfs_remove_free_space_cache(cache);
2558 btrfs_put_block_group(cache);
2559 return ERR_PTR(ret);
2563 * Now that our block group has its ->space_info set and is inserted in
2564 * the rbtree, update the space info's counters.
2566 trace_btrfs_add_block_group(fs_info, cache, 1);
2567 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
2568 cache->bytes_super, cache->zone_unusable,
2569 cache->zone_is_active, &cache->space_info);
2570 btrfs_update_global_block_rsv(fs_info);
2572 link_block_group(cache);
2574 list_add_tail(&cache->bg_list, &trans->new_bgs);
2575 trans->delayed_ref_updates++;
2576 btrfs_update_delayed_refs_rsv(trans);
2578 set_avail_alloc_bits(fs_info, type);
2583 * Mark one block group RO, can be called several times for the same block
2586 * @cache: the destination block group
2587 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2588 * ensure we still have some free space after marking this
2591 int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2592 bool do_chunk_alloc)
2594 struct btrfs_fs_info *fs_info = cache->fs_info;
2595 struct btrfs_trans_handle *trans;
2596 struct btrfs_root *root = btrfs_block_group_root(fs_info);
2599 bool dirty_bg_running;
2602 * This can only happen when we are doing read-only scrub on read-only
2604 * In that case we should not start a new transaction on read-only fs.
2605 * Thus here we skip all chunk allocations.
2607 if (sb_rdonly(fs_info->sb)) {
2608 mutex_lock(&fs_info->ro_block_group_mutex);
2609 ret = inc_block_group_ro(cache, 0);
2610 mutex_unlock(&fs_info->ro_block_group_mutex);
2615 trans = btrfs_join_transaction(root);
2617 return PTR_ERR(trans);
2619 dirty_bg_running = false;
2622 * We're not allowed to set block groups readonly after the dirty
2623 * block group cache has started writing. If it already started,
2624 * back off and let this transaction commit.
2626 mutex_lock(&fs_info->ro_block_group_mutex);
2627 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2628 u64 transid = trans->transid;
2630 mutex_unlock(&fs_info->ro_block_group_mutex);
2631 btrfs_end_transaction(trans);
2633 ret = btrfs_wait_for_commit(fs_info, transid);
2636 dirty_bg_running = true;
2638 } while (dirty_bg_running);
2640 if (do_chunk_alloc) {
2642 * If we are changing raid levels, try to allocate a
2643 * corresponding block group with the new raid level.
2645 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2646 if (alloc_flags != cache->flags) {
2647 ret = btrfs_chunk_alloc(trans, alloc_flags,
2650 * ENOSPC is allowed here, we may have enough space
2651 * already allocated at the new raid level to carry on
2660 ret = inc_block_group_ro(cache, 0);
2661 if (!do_chunk_alloc || ret == -ETXTBSY)
2665 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2666 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2670 * We have allocated a new chunk. We also need to activate that chunk to
2671 * grant metadata tickets for zoned filesystem.
2673 ret = btrfs_zoned_activate_one_bg(fs_info, cache->space_info, true);
2677 ret = inc_block_group_ro(cache, 0);
2678 if (ret == -ETXTBSY)
2681 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2682 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2683 mutex_lock(&fs_info->chunk_mutex);
2684 check_system_chunk(trans, alloc_flags);
2685 mutex_unlock(&fs_info->chunk_mutex);
2688 mutex_unlock(&fs_info->ro_block_group_mutex);
2690 btrfs_end_transaction(trans);
2694 void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
2696 struct btrfs_space_info *sinfo = cache->space_info;
2701 spin_lock(&sinfo->lock);
2702 spin_lock(&cache->lock);
2704 if (btrfs_is_zoned(cache->fs_info)) {
2705 /* Migrate zone_unusable bytes back */
2706 cache->zone_unusable =
2707 (cache->alloc_offset - cache->used) +
2708 (cache->length - cache->zone_capacity);
2709 sinfo->bytes_zone_unusable += cache->zone_unusable;
2710 sinfo->bytes_readonly -= cache->zone_unusable;
2712 num_bytes = cache->length - cache->reserved -
2713 cache->pinned - cache->bytes_super -
2714 cache->zone_unusable - cache->used;
2715 sinfo->bytes_readonly -= num_bytes;
2716 list_del_init(&cache->ro_list);
2718 spin_unlock(&cache->lock);
2719 spin_unlock(&sinfo->lock);
2722 static int update_block_group_item(struct btrfs_trans_handle *trans,
2723 struct btrfs_path *path,
2724 struct btrfs_block_group *cache)
2726 struct btrfs_fs_info *fs_info = trans->fs_info;
2728 struct btrfs_root *root = btrfs_block_group_root(fs_info);
2730 struct extent_buffer *leaf;
2731 struct btrfs_block_group_item bgi;
2732 struct btrfs_key key;
2734 key.objectid = cache->start;
2735 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2736 key.offset = cache->length;
2738 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2745 leaf = path->nodes[0];
2746 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2747 btrfs_set_stack_block_group_used(&bgi, cache->used);
2748 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2749 cache->global_root_id);
2750 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2751 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
2752 btrfs_mark_buffer_dirty(leaf);
2754 btrfs_release_path(path);
2759 static int cache_save_setup(struct btrfs_block_group *block_group,
2760 struct btrfs_trans_handle *trans,
2761 struct btrfs_path *path)
2763 struct btrfs_fs_info *fs_info = block_group->fs_info;
2764 struct btrfs_root *root = fs_info->tree_root;
2765 struct inode *inode = NULL;
2766 struct extent_changeset *data_reserved = NULL;
2768 int dcs = BTRFS_DC_ERROR;
2773 if (!btrfs_test_opt(fs_info, SPACE_CACHE))
2777 * If this block group is smaller than 100 megs don't bother caching the
2780 if (block_group->length < (100 * SZ_1M)) {
2781 spin_lock(&block_group->lock);
2782 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2783 spin_unlock(&block_group->lock);
2787 if (TRANS_ABORTED(trans))
2790 inode = lookup_free_space_inode(block_group, path);
2791 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2792 ret = PTR_ERR(inode);
2793 btrfs_release_path(path);
2797 if (IS_ERR(inode)) {
2801 if (block_group->ro)
2804 ret = create_free_space_inode(trans, block_group, path);
2811 * We want to set the generation to 0, that way if anything goes wrong
2812 * from here on out we know not to trust this cache when we load up next
2815 BTRFS_I(inode)->generation = 0;
2816 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
2819 * So theoretically we could recover from this, simply set the
2820 * super cache generation to 0 so we know to invalidate the
2821 * cache, but then we'd have to keep track of the block groups
2822 * that fail this way so we know we _have_ to reset this cache
2823 * before the next commit or risk reading stale cache. So to
2824 * limit our exposure to horrible edge cases lets just abort the
2825 * transaction, this only happens in really bad situations
2828 btrfs_abort_transaction(trans, ret);
2833 /* We've already setup this transaction, go ahead and exit */
2834 if (block_group->cache_generation == trans->transid &&
2835 i_size_read(inode)) {
2836 dcs = BTRFS_DC_SETUP;
2840 if (i_size_read(inode) > 0) {
2841 ret = btrfs_check_trunc_cache_free_space(fs_info,
2842 &fs_info->global_block_rsv);
2846 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2851 spin_lock(&block_group->lock);
2852 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2853 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2855 * don't bother trying to write stuff out _if_
2856 * a) we're not cached,
2857 * b) we're with nospace_cache mount option,
2858 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2860 dcs = BTRFS_DC_WRITTEN;
2861 spin_unlock(&block_group->lock);
2864 spin_unlock(&block_group->lock);
2867 * We hit an ENOSPC when setting up the cache in this transaction, just
2868 * skip doing the setup, we've already cleared the cache so we're safe.
2870 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2876 * Try to preallocate enough space based on how big the block group is.
2877 * Keep in mind this has to include any pinned space which could end up
2878 * taking up quite a bit since it's not folded into the other space
2881 cache_size = div_u64(block_group->length, SZ_256M);
2886 cache_size *= fs_info->sectorsize;
2888 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
2893 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
2894 cache_size, cache_size,
2897 * Our cache requires contiguous chunks so that we don't modify a bunch
2898 * of metadata or split extents when writing the cache out, which means
2899 * we can enospc if we are heavily fragmented in addition to just normal
2900 * out of space conditions. So if we hit this just skip setting up any
2901 * other block groups for this transaction, maybe we'll unpin enough
2902 * space the next time around.
2905 dcs = BTRFS_DC_SETUP;
2906 else if (ret == -ENOSPC)
2907 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2912 btrfs_release_path(path);
2914 spin_lock(&block_group->lock);
2915 if (!ret && dcs == BTRFS_DC_SETUP)
2916 block_group->cache_generation = trans->transid;
2917 block_group->disk_cache_state = dcs;
2918 spin_unlock(&block_group->lock);
2920 extent_changeset_free(data_reserved);
2924 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2926 struct btrfs_fs_info *fs_info = trans->fs_info;
2927 struct btrfs_block_group *cache, *tmp;
2928 struct btrfs_transaction *cur_trans = trans->transaction;
2929 struct btrfs_path *path;
2931 if (list_empty(&cur_trans->dirty_bgs) ||
2932 !btrfs_test_opt(fs_info, SPACE_CACHE))
2935 path = btrfs_alloc_path();
2939 /* Could add new block groups, use _safe just in case */
2940 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2942 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2943 cache_save_setup(cache, trans, path);
2946 btrfs_free_path(path);
2951 * Transaction commit does final block group cache writeback during a critical
2952 * section where nothing is allowed to change the FS. This is required in
2953 * order for the cache to actually match the block group, but can introduce a
2954 * lot of latency into the commit.
2956 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2957 * There's a chance we'll have to redo some of it if the block group changes
2958 * again during the commit, but it greatly reduces the commit latency by
2959 * getting rid of the easy block groups while we're still allowing others to
2962 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2964 struct btrfs_fs_info *fs_info = trans->fs_info;
2965 struct btrfs_block_group *cache;
2966 struct btrfs_transaction *cur_trans = trans->transaction;
2969 struct btrfs_path *path = NULL;
2971 struct list_head *io = &cur_trans->io_bgs;
2974 spin_lock(&cur_trans->dirty_bgs_lock);
2975 if (list_empty(&cur_trans->dirty_bgs)) {
2976 spin_unlock(&cur_trans->dirty_bgs_lock);
2979 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2980 spin_unlock(&cur_trans->dirty_bgs_lock);
2983 /* Make sure all the block groups on our dirty list actually exist */
2984 btrfs_create_pending_block_groups(trans);
2987 path = btrfs_alloc_path();
2995 * cache_write_mutex is here only to save us from balance or automatic
2996 * removal of empty block groups deleting this block group while we are
2997 * writing out the cache
2999 mutex_lock(&trans->transaction->cache_write_mutex);
3000 while (!list_empty(&dirty)) {
3001 bool drop_reserve = true;
3003 cache = list_first_entry(&dirty, struct btrfs_block_group,
3006 * This can happen if something re-dirties a block group that
3007 * is already under IO. Just wait for it to finish and then do
3010 if (!list_empty(&cache->io_list)) {
3011 list_del_init(&cache->io_list);
3012 btrfs_wait_cache_io(trans, cache, path);
3013 btrfs_put_block_group(cache);
3018 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
3019 * it should update the cache_state. Don't delete until after
3022 * Since we're not running in the commit critical section
3023 * we need the dirty_bgs_lock to protect from update_block_group
3025 spin_lock(&cur_trans->dirty_bgs_lock);
3026 list_del_init(&cache->dirty_list);
3027 spin_unlock(&cur_trans->dirty_bgs_lock);
3031 cache_save_setup(cache, trans, path);
3033 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3034 cache->io_ctl.inode = NULL;
3035 ret = btrfs_write_out_cache(trans, cache, path);
3036 if (ret == 0 && cache->io_ctl.inode) {
3040 * The cache_write_mutex is protecting the
3041 * io_list, also refer to the definition of
3042 * btrfs_transaction::io_bgs for more details
3044 list_add_tail(&cache->io_list, io);
3047 * If we failed to write the cache, the
3048 * generation will be bad and life goes on
3054 ret = update_block_group_item(trans, path, cache);
3056 * Our block group might still be attached to the list
3057 * of new block groups in the transaction handle of some
3058 * other task (struct btrfs_trans_handle->new_bgs). This
3059 * means its block group item isn't yet in the extent
3060 * tree. If this happens ignore the error, as we will
3061 * try again later in the critical section of the
3062 * transaction commit.
3064 if (ret == -ENOENT) {
3066 spin_lock(&cur_trans->dirty_bgs_lock);
3067 if (list_empty(&cache->dirty_list)) {
3068 list_add_tail(&cache->dirty_list,
3069 &cur_trans->dirty_bgs);
3070 btrfs_get_block_group(cache);
3071 drop_reserve = false;
3073 spin_unlock(&cur_trans->dirty_bgs_lock);
3075 btrfs_abort_transaction(trans, ret);
3079 /* If it's not on the io list, we need to put the block group */
3081 btrfs_put_block_group(cache);
3083 btrfs_delayed_refs_rsv_release(fs_info, 1);
3085 * Avoid blocking other tasks for too long. It might even save
3086 * us from writing caches for block groups that are going to be
3089 mutex_unlock(&trans->transaction->cache_write_mutex);
3092 mutex_lock(&trans->transaction->cache_write_mutex);
3094 mutex_unlock(&trans->transaction->cache_write_mutex);
3097 * Go through delayed refs for all the stuff we've just kicked off
3098 * and then loop back (just once)
3101 ret = btrfs_run_delayed_refs(trans, 0);
3102 if (!ret && loops == 0) {
3104 spin_lock(&cur_trans->dirty_bgs_lock);
3105 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3107 * dirty_bgs_lock protects us from concurrent block group
3108 * deletes too (not just cache_write_mutex).
3110 if (!list_empty(&dirty)) {
3111 spin_unlock(&cur_trans->dirty_bgs_lock);
3114 spin_unlock(&cur_trans->dirty_bgs_lock);
3118 spin_lock(&cur_trans->dirty_bgs_lock);
3119 list_splice_init(&dirty, &cur_trans->dirty_bgs);
3120 spin_unlock(&cur_trans->dirty_bgs_lock);
3121 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3124 btrfs_free_path(path);
3128 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
3130 struct btrfs_fs_info *fs_info = trans->fs_info;
3131 struct btrfs_block_group *cache;
3132 struct btrfs_transaction *cur_trans = trans->transaction;
3135 struct btrfs_path *path;
3136 struct list_head *io = &cur_trans->io_bgs;
3138 path = btrfs_alloc_path();
3143 * Even though we are in the critical section of the transaction commit,
3144 * we can still have concurrent tasks adding elements to this
3145 * transaction's list of dirty block groups. These tasks correspond to
3146 * endio free space workers started when writeback finishes for a
3147 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3148 * allocate new block groups as a result of COWing nodes of the root
3149 * tree when updating the free space inode. The writeback for the space
3150 * caches is triggered by an earlier call to
3151 * btrfs_start_dirty_block_groups() and iterations of the following
3153 * Also we want to do the cache_save_setup first and then run the
3154 * delayed refs to make sure we have the best chance at doing this all
3157 spin_lock(&cur_trans->dirty_bgs_lock);
3158 while (!list_empty(&cur_trans->dirty_bgs)) {
3159 cache = list_first_entry(&cur_trans->dirty_bgs,
3160 struct btrfs_block_group,
3164 * This can happen if cache_save_setup re-dirties a block group
3165 * that is already under IO. Just wait for it to finish and
3166 * then do it all again
3168 if (!list_empty(&cache->io_list)) {
3169 spin_unlock(&cur_trans->dirty_bgs_lock);
3170 list_del_init(&cache->io_list);
3171 btrfs_wait_cache_io(trans, cache, path);
3172 btrfs_put_block_group(cache);
3173 spin_lock(&cur_trans->dirty_bgs_lock);
3177 * Don't remove from the dirty list until after we've waited on
3180 list_del_init(&cache->dirty_list);
3181 spin_unlock(&cur_trans->dirty_bgs_lock);
3184 cache_save_setup(cache, trans, path);
3187 ret = btrfs_run_delayed_refs(trans,
3188 (unsigned long) -1);
3190 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3191 cache->io_ctl.inode = NULL;
3192 ret = btrfs_write_out_cache(trans, cache, path);
3193 if (ret == 0 && cache->io_ctl.inode) {
3195 list_add_tail(&cache->io_list, io);
3198 * If we failed to write the cache, the
3199 * generation will be bad and life goes on
3205 ret = update_block_group_item(trans, path, cache);
3207 * One of the free space endio workers might have
3208 * created a new block group while updating a free space
3209 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3210 * and hasn't released its transaction handle yet, in
3211 * which case the new block group is still attached to
3212 * its transaction handle and its creation has not
3213 * finished yet (no block group item in the extent tree
3214 * yet, etc). If this is the case, wait for all free
3215 * space endio workers to finish and retry. This is a
3216 * very rare case so no need for a more efficient and
3219 if (ret == -ENOENT) {
3220 wait_event(cur_trans->writer_wait,
3221 atomic_read(&cur_trans->num_writers) == 1);
3222 ret = update_block_group_item(trans, path, cache);
3225 btrfs_abort_transaction(trans, ret);
3228 /* If its not on the io list, we need to put the block group */
3230 btrfs_put_block_group(cache);
3231 btrfs_delayed_refs_rsv_release(fs_info, 1);
3232 spin_lock(&cur_trans->dirty_bgs_lock);
3234 spin_unlock(&cur_trans->dirty_bgs_lock);
3237 * Refer to the definition of io_bgs member for details why it's safe
3238 * to use it without any locking
3240 while (!list_empty(io)) {
3241 cache = list_first_entry(io, struct btrfs_block_group,
3243 list_del_init(&cache->io_list);
3244 btrfs_wait_cache_io(trans, cache, path);
3245 btrfs_put_block_group(cache);
3248 btrfs_free_path(path);
3252 static inline bool should_reclaim_block_group(struct btrfs_block_group *bg,
3255 const struct btrfs_space_info *space_info = bg->space_info;
3256 const int reclaim_thresh = READ_ONCE(space_info->bg_reclaim_threshold);
3257 const u64 new_val = bg->used;
3258 const u64 old_val = new_val + bytes_freed;
3261 if (reclaim_thresh == 0)
3264 thresh = div_factor_fine(bg->length, reclaim_thresh);
3267 * If we were below the threshold before don't reclaim, we are likely a
3268 * brand new block group and we don't want to relocate new block groups.
3270 if (old_val < thresh)
3272 if (new_val >= thresh)
3277 int btrfs_update_block_group(struct btrfs_trans_handle *trans,
3278 u64 bytenr, u64 num_bytes, bool alloc)
3280 struct btrfs_fs_info *info = trans->fs_info;
3281 struct btrfs_block_group *cache = NULL;
3282 u64 total = num_bytes;
3288 /* Block accounting for super block */
3289 spin_lock(&info->delalloc_root_lock);
3290 old_val = btrfs_super_bytes_used(info->super_copy);
3292 old_val += num_bytes;
3294 old_val -= num_bytes;
3295 btrfs_set_super_bytes_used(info->super_copy, old_val);
3296 spin_unlock(&info->delalloc_root_lock);
3301 cache = btrfs_lookup_block_group(info, bytenr);
3306 factor = btrfs_bg_type_to_factor(cache->flags);
3309 * If this block group has free space cache written out, we
3310 * need to make sure to load it if we are removing space. This
3311 * is because we need the unpinning stage to actually add the
3312 * space back to the block group, otherwise we will leak space.
3314 if (!alloc && !btrfs_block_group_done(cache))
3315 btrfs_cache_block_group(cache, 1);
3317 byte_in_group = bytenr - cache->start;
3318 WARN_ON(byte_in_group > cache->length);
3320 spin_lock(&cache->space_info->lock);
3321 spin_lock(&cache->lock);
3323 if (btrfs_test_opt(info, SPACE_CACHE) &&
3324 cache->disk_cache_state < BTRFS_DC_CLEAR)
3325 cache->disk_cache_state = BTRFS_DC_CLEAR;
3327 old_val = cache->used;
3328 num_bytes = min(total, cache->length - byte_in_group);
3330 old_val += num_bytes;
3331 cache->used = old_val;
3332 cache->reserved -= num_bytes;
3333 cache->space_info->bytes_reserved -= num_bytes;
3334 cache->space_info->bytes_used += num_bytes;
3335 cache->space_info->disk_used += num_bytes * factor;
3336 spin_unlock(&cache->lock);
3337 spin_unlock(&cache->space_info->lock);
3339 old_val -= num_bytes;
3340 cache->used = old_val;
3341 cache->pinned += num_bytes;
3342 btrfs_space_info_update_bytes_pinned(info,
3343 cache->space_info, num_bytes);
3344 cache->space_info->bytes_used -= num_bytes;
3345 cache->space_info->disk_used -= num_bytes * factor;
3347 reclaim = should_reclaim_block_group(cache, num_bytes);
3348 spin_unlock(&cache->lock);
3349 spin_unlock(&cache->space_info->lock);
3351 set_extent_dirty(&trans->transaction->pinned_extents,
3352 bytenr, bytenr + num_bytes - 1,
3353 GFP_NOFS | __GFP_NOFAIL);
3356 spin_lock(&trans->transaction->dirty_bgs_lock);
3357 if (list_empty(&cache->dirty_list)) {
3358 list_add_tail(&cache->dirty_list,
3359 &trans->transaction->dirty_bgs);
3360 trans->delayed_ref_updates++;
3361 btrfs_get_block_group(cache);
3363 spin_unlock(&trans->transaction->dirty_bgs_lock);
3366 * No longer have used bytes in this block group, queue it for
3367 * deletion. We do this after adding the block group to the
3368 * dirty list to avoid races between cleaner kthread and space
3371 if (!alloc && old_val == 0) {
3372 if (!btrfs_test_opt(info, DISCARD_ASYNC))
3373 btrfs_mark_bg_unused(cache);
3374 } else if (!alloc && reclaim) {
3375 btrfs_mark_bg_to_reclaim(cache);
3378 btrfs_put_block_group(cache);
3380 bytenr += num_bytes;
3383 /* Modified block groups are accounted for in the delayed_refs_rsv. */
3384 btrfs_update_delayed_refs_rsv(trans);
3389 * btrfs_add_reserved_bytes - update the block_group and space info counters
3390 * @cache: The cache we are manipulating
3391 * @ram_bytes: The number of bytes of file content, and will be same to
3392 * @num_bytes except for the compress path.
3393 * @num_bytes: The number of bytes in question
3394 * @delalloc: The blocks are allocated for the delalloc write
3396 * This is called by the allocator when it reserves space. If this is a
3397 * reservation and the block group has become read only we cannot make the
3398 * reservation and return -EAGAIN, otherwise this function always succeeds.
3400 int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
3401 u64 ram_bytes, u64 num_bytes, int delalloc)
3403 struct btrfs_space_info *space_info = cache->space_info;
3406 spin_lock(&space_info->lock);
3407 spin_lock(&cache->lock);
3411 cache->reserved += num_bytes;
3412 space_info->bytes_reserved += num_bytes;
3413 trace_btrfs_space_reservation(cache->fs_info, "space_info",
3414 space_info->flags, num_bytes, 1);
3415 btrfs_space_info_update_bytes_may_use(cache->fs_info,
3416 space_info, -ram_bytes);
3418 cache->delalloc_bytes += num_bytes;
3421 * Compression can use less space than we reserved, so wake
3422 * tickets if that happens
3424 if (num_bytes < ram_bytes)
3425 btrfs_try_granting_tickets(cache->fs_info, space_info);
3427 spin_unlock(&cache->lock);
3428 spin_unlock(&space_info->lock);
3433 * btrfs_free_reserved_bytes - update the block_group and space info counters
3434 * @cache: The cache we are manipulating
3435 * @num_bytes: The number of bytes in question
3436 * @delalloc: The blocks are allocated for the delalloc write
3438 * This is called by somebody who is freeing space that was never actually used
3439 * on disk. For example if you reserve some space for a new leaf in transaction
3440 * A and before transaction A commits you free that leaf, you call this with
3441 * reserve set to 0 in order to clear the reservation.
3443 void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3444 u64 num_bytes, int delalloc)
3446 struct btrfs_space_info *space_info = cache->space_info;
3448 spin_lock(&space_info->lock);
3449 spin_lock(&cache->lock);
3451 space_info->bytes_readonly += num_bytes;
3452 cache->reserved -= num_bytes;
3453 space_info->bytes_reserved -= num_bytes;
3454 space_info->max_extent_size = 0;
3457 cache->delalloc_bytes -= num_bytes;
3458 spin_unlock(&cache->lock);
3460 btrfs_try_granting_tickets(cache->fs_info, space_info);
3461 spin_unlock(&space_info->lock);
3464 static void force_metadata_allocation(struct btrfs_fs_info *info)
3466 struct list_head *head = &info->space_info;
3467 struct btrfs_space_info *found;
3469 list_for_each_entry(found, head, list) {
3470 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3471 found->force_alloc = CHUNK_ALLOC_FORCE;
3475 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3476 struct btrfs_space_info *sinfo, int force)
3478 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3481 if (force == CHUNK_ALLOC_FORCE)
3485 * in limited mode, we want to have some free space up to
3486 * about 1% of the FS size.
3488 if (force == CHUNK_ALLOC_LIMITED) {
3489 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3490 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3492 if (sinfo->total_bytes - bytes_used < thresh)
3496 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3501 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3503 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3505 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3508 static struct btrfs_block_group *do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags)
3510 struct btrfs_block_group *bg;
3514 * Check if we have enough space in the system space info because we
3515 * will need to update device items in the chunk btree and insert a new
3516 * chunk item in the chunk btree as well. This will allocate a new
3517 * system block group if needed.
3519 check_system_chunk(trans, flags);
3521 bg = btrfs_create_chunk(trans, flags);
3527 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
3529 * Normally we are not expected to fail with -ENOSPC here, since we have
3530 * previously reserved space in the system space_info and allocated one
3531 * new system chunk if necessary. However there are three exceptions:
3533 * 1) We may have enough free space in the system space_info but all the
3534 * existing system block groups have a profile which can not be used
3535 * for extent allocation.
3537 * This happens when mounting in degraded mode. For example we have a
3538 * RAID1 filesystem with 2 devices, lose one device and mount the fs
3539 * using the other device in degraded mode. If we then allocate a chunk,
3540 * we may have enough free space in the existing system space_info, but
3541 * none of the block groups can be used for extent allocation since they
3542 * have a RAID1 profile, and because we are in degraded mode with a
3543 * single device, we are forced to allocate a new system chunk with a
3544 * SINGLE profile. Making check_system_chunk() iterate over all system
3545 * block groups and check if they have a usable profile and enough space
3546 * can be slow on very large filesystems, so we tolerate the -ENOSPC and
3547 * try again after forcing allocation of a new system chunk. Like this
3548 * we avoid paying the cost of that search in normal circumstances, when
3549 * we were not mounted in degraded mode;
3551 * 2) We had enough free space info the system space_info, and one suitable
3552 * block group to allocate from when we called check_system_chunk()
3553 * above. However right after we called it, the only system block group
3554 * with enough free space got turned into RO mode by a running scrub,
3555 * and in this case we have to allocate a new one and retry. We only
3556 * need do this allocate and retry once, since we have a transaction
3557 * handle and scrub uses the commit root to search for block groups;
3559 * 3) We had one system block group with enough free space when we called
3560 * check_system_chunk(), but after that, right before we tried to
3561 * allocate the last extent buffer we needed, a discard operation came
3562 * in and it temporarily removed the last free space entry from the
3563 * block group (discard removes a free space entry, discards it, and
3564 * then adds back the entry to the block group cache).
3566 if (ret == -ENOSPC) {
3567 const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info);
3568 struct btrfs_block_group *sys_bg;
3570 sys_bg = btrfs_create_chunk(trans, sys_flags);
3571 if (IS_ERR(sys_bg)) {
3572 ret = PTR_ERR(sys_bg);
3573 btrfs_abort_transaction(trans, ret);
3577 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3579 btrfs_abort_transaction(trans, ret);
3583 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
3585 btrfs_abort_transaction(trans, ret);
3589 btrfs_abort_transaction(trans, ret);
3593 btrfs_trans_release_chunk_metadata(trans);
3596 return ERR_PTR(ret);
3598 btrfs_get_block_group(bg);
3603 * Chunk allocation is done in 2 phases:
3605 * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
3606 * the chunk, the chunk mapping, create its block group and add the items
3607 * that belong in the chunk btree to it - more specifically, we need to
3608 * update device items in the chunk btree and add a new chunk item to it.
3610 * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
3611 * group item to the extent btree and the device extent items to the devices
3614 * This is done to prevent deadlocks. For example when COWing a node from the
3615 * extent btree we are holding a write lock on the node's parent and if we
3616 * trigger chunk allocation and attempted to insert the new block group item
3617 * in the extent btree right way, we could deadlock because the path for the
3618 * insertion can include that parent node. At first glance it seems impossible
3619 * to trigger chunk allocation after starting a transaction since tasks should
3620 * reserve enough transaction units (metadata space), however while that is true
3621 * most of the time, chunk allocation may still be triggered for several reasons:
3623 * 1) When reserving metadata, we check if there is enough free space in the
3624 * metadata space_info and therefore don't trigger allocation of a new chunk.
3625 * However later when the task actually tries to COW an extent buffer from
3626 * the extent btree or from the device btree for example, it is forced to
3627 * allocate a new block group (chunk) because the only one that had enough
3628 * free space was just turned to RO mode by a running scrub for example (or
3629 * device replace, block group reclaim thread, etc), so we can not use it
3630 * for allocating an extent and end up being forced to allocate a new one;
3632 * 2) Because we only check that the metadata space_info has enough free bytes,
3633 * we end up not allocating a new metadata chunk in that case. However if
3634 * the filesystem was mounted in degraded mode, none of the existing block
3635 * groups might be suitable for extent allocation due to their incompatible
3636 * profile (for e.g. mounting a 2 devices filesystem, where all block groups
3637 * use a RAID1 profile, in degraded mode using a single device). In this case
3638 * when the task attempts to COW some extent buffer of the extent btree for
3639 * example, it will trigger allocation of a new metadata block group with a
3640 * suitable profile (SINGLE profile in the example of the degraded mount of
3641 * the RAID1 filesystem);
3643 * 3) The task has reserved enough transaction units / metadata space, but when
3644 * it attempts to COW an extent buffer from the extent or device btree for
3645 * example, it does not find any free extent in any metadata block group,
3646 * therefore forced to try to allocate a new metadata block group.
3647 * This is because some other task allocated all available extents in the
3648 * meanwhile - this typically happens with tasks that don't reserve space
3649 * properly, either intentionally or as a bug. One example where this is
3650 * done intentionally is fsync, as it does not reserve any transaction units
3651 * and ends up allocating a variable number of metadata extents for log
3652 * tree extent buffers;
3654 * 4) The task has reserved enough transaction units / metadata space, but right
3655 * before it tries to allocate the last extent buffer it needs, a discard
3656 * operation comes in and, temporarily, removes the last free space entry from
3657 * the only metadata block group that had free space (discard starts by
3658 * removing a free space entry from a block group, then does the discard
3659 * operation and, once it's done, it adds back the free space entry to the
3662 * We also need this 2 phases setup when adding a device to a filesystem with
3663 * a seed device - we must create new metadata and system chunks without adding
3664 * any of the block group items to the chunk, extent and device btrees. If we
3665 * did not do it this way, we would get ENOSPC when attempting to update those
3666 * btrees, since all the chunks from the seed device are read-only.
3668 * Phase 1 does the updates and insertions to the chunk btree because if we had
3669 * it done in phase 2 and have a thundering herd of tasks allocating chunks in
3670 * parallel, we risk having too many system chunks allocated by many tasks if
3671 * many tasks reach phase 1 without the previous ones completing phase 2. In the
3672 * extreme case this leads to exhaustion of the system chunk array in the
3673 * superblock. This is easier to trigger if using a btree node/leaf size of 64K
3674 * and with RAID filesystems (so we have more device items in the chunk btree).
3675 * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
3676 * the system chunk array due to concurrent allocations") provides more details.
3678 * Allocation of system chunks does not happen through this function. A task that
3679 * needs to update the chunk btree (the only btree that uses system chunks), must
3680 * preallocate chunk space by calling either check_system_chunk() or
3681 * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or
3682 * metadata chunk or when removing a chunk, while the later is used before doing
3683 * a modification to the chunk btree - use cases for the later are adding,
3684 * removing and resizing a device as well as relocation of a system chunk.
3685 * See the comment below for more details.
3687 * The reservation of system space, done through check_system_chunk(), as well
3688 * as all the updates and insertions into the chunk btree must be done while
3689 * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
3690 * an extent buffer from the chunks btree we never trigger allocation of a new
3691 * system chunk, which would result in a deadlock (trying to lock twice an
3692 * extent buffer of the chunk btree, first time before triggering the chunk
3693 * allocation and the second time during chunk allocation while attempting to
3694 * update the chunks btree). The system chunk array is also updated while holding
3695 * that mutex. The same logic applies to removing chunks - we must reserve system
3696 * space, update the chunk btree and the system chunk array in the superblock
3697 * while holding fs_info->chunk_mutex.
3699 * This function, btrfs_chunk_alloc(), belongs to phase 1.
3701 * If @force is CHUNK_ALLOC_FORCE:
3702 * - return 1 if it successfully allocates a chunk,
3703 * - return errors including -ENOSPC otherwise.
3704 * If @force is NOT CHUNK_ALLOC_FORCE:
3705 * - return 0 if it doesn't need to allocate a new chunk,
3706 * - return 1 if it successfully allocates a chunk,
3707 * - return errors including -ENOSPC otherwise.
3709 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3710 enum btrfs_chunk_alloc_enum force)
3712 struct btrfs_fs_info *fs_info = trans->fs_info;
3713 struct btrfs_space_info *space_info;
3714 struct btrfs_block_group *ret_bg;
3715 bool wait_for_alloc = false;
3716 bool should_alloc = false;
3717 bool from_extent_allocation = false;
3720 if (force == CHUNK_ALLOC_FORCE_FOR_EXTENT) {
3721 from_extent_allocation = true;
3722 force = CHUNK_ALLOC_FORCE;
3725 /* Don't re-enter if we're already allocating a chunk */
3726 if (trans->allocating_chunk)
3729 * Allocation of system chunks can not happen through this path, as we
3730 * could end up in a deadlock if we are allocating a data or metadata
3731 * chunk and there is another task modifying the chunk btree.
3733 * This is because while we are holding the chunk mutex, we will attempt
3734 * to add the new chunk item to the chunk btree or update an existing
3735 * device item in the chunk btree, while the other task that is modifying
3736 * the chunk btree is attempting to COW an extent buffer while holding a
3737 * lock on it and on its parent - if the COW operation triggers a system
3738 * chunk allocation, then we can deadlock because we are holding the
3739 * chunk mutex and we may need to access that extent buffer or its parent
3740 * in order to add the chunk item or update a device item.
3742 * Tasks that want to modify the chunk tree should reserve system space
3743 * before updating the chunk btree, by calling either
3744 * btrfs_reserve_chunk_metadata() or check_system_chunk().
3745 * It's possible that after a task reserves the space, it still ends up
3746 * here - this happens in the cases described above at do_chunk_alloc().
3747 * The task will have to either retry or fail.
3749 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3752 space_info = btrfs_find_space_info(fs_info, flags);
3756 spin_lock(&space_info->lock);
3757 if (force < space_info->force_alloc)
3758 force = space_info->force_alloc;
3759 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3760 if (space_info->full) {
3761 /* No more free physical space */
3766 spin_unlock(&space_info->lock);
3768 } else if (!should_alloc) {
3769 spin_unlock(&space_info->lock);
3771 } else if (space_info->chunk_alloc) {
3773 * Someone is already allocating, so we need to block
3774 * until this someone is finished and then loop to
3775 * recheck if we should continue with our allocation
3778 wait_for_alloc = true;
3779 force = CHUNK_ALLOC_NO_FORCE;
3780 spin_unlock(&space_info->lock);
3781 mutex_lock(&fs_info->chunk_mutex);
3782 mutex_unlock(&fs_info->chunk_mutex);
3784 /* Proceed with allocation */
3785 space_info->chunk_alloc = 1;
3786 wait_for_alloc = false;
3787 spin_unlock(&space_info->lock);
3791 } while (wait_for_alloc);
3793 mutex_lock(&fs_info->chunk_mutex);
3794 trans->allocating_chunk = true;
3797 * If we have mixed data/metadata chunks we want to make sure we keep
3798 * allocating mixed chunks instead of individual chunks.
3800 if (btrfs_mixed_space_info(space_info))
3801 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3804 * if we're doing a data chunk, go ahead and make sure that
3805 * we keep a reasonable number of metadata chunks allocated in the
3808 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3809 fs_info->data_chunk_allocations++;
3810 if (!(fs_info->data_chunk_allocations %
3811 fs_info->metadata_ratio))
3812 force_metadata_allocation(fs_info);
3815 ret_bg = do_chunk_alloc(trans, flags);
3816 trans->allocating_chunk = false;
3818 if (IS_ERR(ret_bg)) {
3819 ret = PTR_ERR(ret_bg);
3820 } else if (from_extent_allocation) {
3822 * New block group is likely to be used soon. Try to activate
3823 * it now. Failure is OK for now.
3825 btrfs_zone_activate(ret_bg);
3829 btrfs_put_block_group(ret_bg);
3831 spin_lock(&space_info->lock);
3834 space_info->full = 1;
3839 space_info->max_extent_size = 0;
3842 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3844 space_info->chunk_alloc = 0;
3845 spin_unlock(&space_info->lock);
3846 mutex_unlock(&fs_info->chunk_mutex);
3851 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3855 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3857 num_dev = fs_info->fs_devices->rw_devices;
3862 static void reserve_chunk_space(struct btrfs_trans_handle *trans,
3866 struct btrfs_fs_info *fs_info = trans->fs_info;
3867 struct btrfs_space_info *info;
3872 * Needed because we can end up allocating a system chunk and for an
3873 * atomic and race free space reservation in the chunk block reserve.
3875 lockdep_assert_held(&fs_info->chunk_mutex);
3877 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3878 spin_lock(&info->lock);
3879 left = info->total_bytes - btrfs_space_info_used(info, true);
3880 spin_unlock(&info->lock);
3882 if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3883 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3885 btrfs_dump_space_info(fs_info, info, 0, 0);
3889 u64 flags = btrfs_system_alloc_profile(fs_info);
3890 struct btrfs_block_group *bg;
3893 * Ignore failure to create system chunk. We might end up not
3894 * needing it, as we might not need to COW all nodes/leafs from
3895 * the paths we visit in the chunk tree (they were already COWed
3896 * or created in the current transaction for example).
3898 bg = btrfs_create_chunk(trans, flags);
3903 * We have a new chunk. We also need to activate it for
3906 ret = btrfs_zoned_activate_one_bg(fs_info, info, true);
3911 * If we fail to add the chunk item here, we end up
3912 * trying again at phase 2 of chunk allocation, at
3913 * btrfs_create_pending_block_groups(). So ignore
3914 * any error here. An ENOSPC here could happen, due to
3915 * the cases described at do_chunk_alloc() - the system
3916 * block group we just created was just turned into RO
3917 * mode by a scrub for example, or a running discard
3918 * temporarily removed its free space entries, etc.
3920 btrfs_chunk_alloc_add_chunk_item(trans, bg);
3925 ret = btrfs_block_rsv_add(fs_info,
3926 &fs_info->chunk_block_rsv,
3927 bytes, BTRFS_RESERVE_NO_FLUSH);
3929 trans->chunk_bytes_reserved += bytes;
3934 * Reserve space in the system space for allocating or removing a chunk.
3935 * The caller must be holding fs_info->chunk_mutex.
3937 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3939 struct btrfs_fs_info *fs_info = trans->fs_info;
3940 const u64 num_devs = get_profile_num_devs(fs_info, type);
3943 /* num_devs device items to update and 1 chunk item to add or remove. */
3944 bytes = btrfs_calc_metadata_size(fs_info, num_devs) +
3945 btrfs_calc_insert_metadata_size(fs_info, 1);
3947 reserve_chunk_space(trans, bytes, type);
3951 * Reserve space in the system space, if needed, for doing a modification to the
3954 * @trans: A transaction handle.
3955 * @is_item_insertion: Indicate if the modification is for inserting a new item
3956 * in the chunk btree or if it's for the deletion or update
3957 * of an existing item.
3959 * This is used in a context where we need to update the chunk btree outside
3960 * block group allocation and removal, to avoid a deadlock with a concurrent
3961 * task that is allocating a metadata or data block group and therefore needs to
3962 * update the chunk btree while holding the chunk mutex. After the update to the
3963 * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called.
3966 void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans,
3967 bool is_item_insertion)
3969 struct btrfs_fs_info *fs_info = trans->fs_info;
3972 if (is_item_insertion)
3973 bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
3975 bytes = btrfs_calc_metadata_size(fs_info, 1);
3977 mutex_lock(&fs_info->chunk_mutex);
3978 reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM);
3979 mutex_unlock(&fs_info->chunk_mutex);
3982 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3984 struct btrfs_block_group *block_group;
3988 struct inode *inode;
3990 block_group = btrfs_lookup_first_block_group(info, last);
3991 while (block_group) {
3992 btrfs_wait_block_group_cache_done(block_group);
3993 spin_lock(&block_group->lock);
3994 if (block_group->iref)
3996 spin_unlock(&block_group->lock);
3997 block_group = btrfs_next_block_group(block_group);
4006 inode = block_group->inode;
4007 block_group->iref = 0;
4008 block_group->inode = NULL;
4009 spin_unlock(&block_group->lock);
4010 ASSERT(block_group->io_ctl.inode == NULL);
4012 last = block_group->start + block_group->length;
4013 btrfs_put_block_group(block_group);
4018 * Must be called only after stopping all workers, since we could have block
4019 * group caching kthreads running, and therefore they could race with us if we
4020 * freed the block groups before stopping them.
4022 int btrfs_free_block_groups(struct btrfs_fs_info *info)
4024 struct btrfs_block_group *block_group;
4025 struct btrfs_space_info *space_info;
4026 struct btrfs_caching_control *caching_ctl;
4029 write_lock(&info->block_group_cache_lock);
4030 while (!list_empty(&info->caching_block_groups)) {
4031 caching_ctl = list_entry(info->caching_block_groups.next,
4032 struct btrfs_caching_control, list);
4033 list_del(&caching_ctl->list);
4034 btrfs_put_caching_control(caching_ctl);
4036 write_unlock(&info->block_group_cache_lock);
4038 spin_lock(&info->unused_bgs_lock);
4039 while (!list_empty(&info->unused_bgs)) {
4040 block_group = list_first_entry(&info->unused_bgs,
4041 struct btrfs_block_group,
4043 list_del_init(&block_group->bg_list);
4044 btrfs_put_block_group(block_group);
4047 while (!list_empty(&info->reclaim_bgs)) {
4048 block_group = list_first_entry(&info->reclaim_bgs,
4049 struct btrfs_block_group,
4051 list_del_init(&block_group->bg_list);
4052 btrfs_put_block_group(block_group);
4054 spin_unlock(&info->unused_bgs_lock);
4056 spin_lock(&info->zone_active_bgs_lock);
4057 while (!list_empty(&info->zone_active_bgs)) {
4058 block_group = list_first_entry(&info->zone_active_bgs,
4059 struct btrfs_block_group,
4061 list_del_init(&block_group->active_bg_list);
4062 btrfs_put_block_group(block_group);
4064 spin_unlock(&info->zone_active_bgs_lock);
4066 write_lock(&info->block_group_cache_lock);
4067 while ((n = rb_last(&info->block_group_cache_tree.rb_root)) != NULL) {
4068 block_group = rb_entry(n, struct btrfs_block_group,
4070 rb_erase_cached(&block_group->cache_node,
4071 &info->block_group_cache_tree);
4072 RB_CLEAR_NODE(&block_group->cache_node);
4073 write_unlock(&info->block_group_cache_lock);
4075 down_write(&block_group->space_info->groups_sem);
4076 list_del(&block_group->list);
4077 up_write(&block_group->space_info->groups_sem);
4080 * We haven't cached this block group, which means we could
4081 * possibly have excluded extents on this block group.
4083 if (block_group->cached == BTRFS_CACHE_NO ||
4084 block_group->cached == BTRFS_CACHE_ERROR)
4085 btrfs_free_excluded_extents(block_group);
4087 btrfs_remove_free_space_cache(block_group);
4088 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
4089 ASSERT(list_empty(&block_group->dirty_list));
4090 ASSERT(list_empty(&block_group->io_list));
4091 ASSERT(list_empty(&block_group->bg_list));
4092 ASSERT(refcount_read(&block_group->refs) == 1);
4093 ASSERT(block_group->swap_extents == 0);
4094 btrfs_put_block_group(block_group);
4096 write_lock(&info->block_group_cache_lock);
4098 write_unlock(&info->block_group_cache_lock);
4100 btrfs_release_global_block_rsv(info);
4102 while (!list_empty(&info->space_info)) {
4103 space_info = list_entry(info->space_info.next,
4104 struct btrfs_space_info,
4108 * Do not hide this behind enospc_debug, this is actually
4109 * important and indicates a real bug if this happens.
4111 if (WARN_ON(space_info->bytes_pinned > 0 ||
4112 space_info->bytes_may_use > 0))
4113 btrfs_dump_space_info(info, space_info, 0, 0);
4116 * If there was a failure to cleanup a log tree, very likely due
4117 * to an IO failure on a writeback attempt of one or more of its
4118 * extent buffers, we could not do proper (and cheap) unaccounting
4119 * of their reserved space, so don't warn on bytes_reserved > 0 in
4122 if (!(space_info->flags & BTRFS_BLOCK_GROUP_METADATA) ||
4123 !BTRFS_FS_LOG_CLEANUP_ERROR(info)) {
4124 if (WARN_ON(space_info->bytes_reserved > 0))
4125 btrfs_dump_space_info(info, space_info, 0, 0);
4128 WARN_ON(space_info->reclaim_size > 0);
4129 list_del(&space_info->list);
4130 btrfs_sysfs_remove_space_info(space_info);
4135 void btrfs_freeze_block_group(struct btrfs_block_group *cache)
4137 atomic_inc(&cache->frozen);
4140 void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
4142 struct btrfs_fs_info *fs_info = block_group->fs_info;
4143 struct extent_map_tree *em_tree;
4144 struct extent_map *em;
4147 spin_lock(&block_group->lock);
4148 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
4149 block_group->removed);
4150 spin_unlock(&block_group->lock);
4153 em_tree = &fs_info->mapping_tree;
4154 write_lock(&em_tree->lock);
4155 em = lookup_extent_mapping(em_tree, block_group->start,
4157 BUG_ON(!em); /* logic error, can't happen */
4158 remove_extent_mapping(em_tree, em);
4159 write_unlock(&em_tree->lock);
4161 /* once for us and once for the tree */
4162 free_extent_map(em);
4163 free_extent_map(em);
4166 * We may have left one free space entry and other possible
4167 * tasks trimming this block group have left 1 entry each one.
4170 __btrfs_remove_free_space_cache(block_group->free_space_ctl);
4174 bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
4178 spin_lock(&bg->lock);
4183 spin_unlock(&bg->lock);
4188 void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
4190 spin_lock(&bg->lock);
4192 ASSERT(bg->swap_extents >= amount);
4193 bg->swap_extents -= amount;
4194 spin_unlock(&bg->lock);