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_err(fs_info, "error relocating chunk %llu",
1648 btrfs_put_block_group(bg);
1649 spin_lock(&fs_info->unused_bgs_lock);
1651 spin_unlock(&fs_info->unused_bgs_lock);
1652 mutex_unlock(&fs_info->reclaim_bgs_lock);
1653 btrfs_exclop_finish(fs_info);
1654 sb_end_write(fs_info->sb);
1657 void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
1659 spin_lock(&fs_info->unused_bgs_lock);
1660 if (!list_empty(&fs_info->reclaim_bgs))
1661 queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
1662 spin_unlock(&fs_info->unused_bgs_lock);
1665 void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
1667 struct btrfs_fs_info *fs_info = bg->fs_info;
1669 spin_lock(&fs_info->unused_bgs_lock);
1670 if (list_empty(&bg->bg_list)) {
1671 btrfs_get_block_group(bg);
1672 trace_btrfs_add_reclaim_block_group(bg);
1673 list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
1675 spin_unlock(&fs_info->unused_bgs_lock);
1678 static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1679 struct btrfs_path *path)
1681 struct extent_map_tree *em_tree;
1682 struct extent_map *em;
1683 struct btrfs_block_group_item bg;
1684 struct extent_buffer *leaf;
1689 slot = path->slots[0];
1690 leaf = path->nodes[0];
1692 em_tree = &fs_info->mapping_tree;
1693 read_lock(&em_tree->lock);
1694 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1695 read_unlock(&em_tree->lock);
1698 "logical %llu len %llu found bg but no related chunk",
1699 key->objectid, key->offset);
1703 if (em->start != key->objectid || em->len != key->offset) {
1705 "block group %llu len %llu mismatch with chunk %llu len %llu",
1706 key->objectid, key->offset, em->start, em->len);
1711 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1713 flags = btrfs_stack_block_group_flags(&bg) &
1714 BTRFS_BLOCK_GROUP_TYPE_MASK;
1716 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1718 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1719 key->objectid, key->offset, flags,
1720 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1725 free_extent_map(em);
1729 static int find_first_block_group(struct btrfs_fs_info *fs_info,
1730 struct btrfs_path *path,
1731 struct btrfs_key *key)
1733 struct btrfs_root *root = btrfs_block_group_root(fs_info);
1735 struct btrfs_key found_key;
1737 btrfs_for_each_slot(root, key, &found_key, path, ret) {
1738 if (found_key.objectid >= key->objectid &&
1739 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1740 return read_bg_from_eb(fs_info, &found_key, path);
1746 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1748 u64 extra_flags = chunk_to_extended(flags) &
1749 BTRFS_EXTENDED_PROFILE_MASK;
1751 write_seqlock(&fs_info->profiles_lock);
1752 if (flags & BTRFS_BLOCK_GROUP_DATA)
1753 fs_info->avail_data_alloc_bits |= extra_flags;
1754 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1755 fs_info->avail_metadata_alloc_bits |= extra_flags;
1756 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1757 fs_info->avail_system_alloc_bits |= extra_flags;
1758 write_sequnlock(&fs_info->profiles_lock);
1762 * Map a physical disk address to a list of logical addresses
1764 * @fs_info: the filesystem
1765 * @chunk_start: logical address of block group
1766 * @bdev: physical device to resolve, can be NULL to indicate any device
1767 * @physical: physical address to map to logical addresses
1768 * @logical: return array of logical addresses which map to @physical
1769 * @naddrs: length of @logical
1770 * @stripe_len: size of IO stripe for the given block group
1772 * Maps a particular @physical disk address to a list of @logical addresses.
1773 * Used primarily to exclude those portions of a block group that contain super
1776 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1777 struct block_device *bdev, u64 physical, u64 **logical,
1778 int *naddrs, int *stripe_len)
1780 struct extent_map *em;
1781 struct map_lookup *map;
1784 u64 data_stripe_length;
1789 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1793 map = em->map_lookup;
1794 data_stripe_length = em->orig_block_len;
1795 io_stripe_size = map->stripe_len;
1796 chunk_start = em->start;
1798 /* For RAID5/6 adjust to a full IO stripe length */
1799 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
1800 io_stripe_size = map->stripe_len * nr_data_stripes(map);
1802 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
1808 for (i = 0; i < map->num_stripes; i++) {
1809 bool already_inserted = false;
1814 if (!in_range(physical, map->stripes[i].physical,
1815 data_stripe_length))
1818 if (bdev && map->stripes[i].dev->bdev != bdev)
1821 stripe_nr = physical - map->stripes[i].physical;
1822 stripe_nr = div64_u64_rem(stripe_nr, map->stripe_len, &offset);
1824 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
1825 BTRFS_BLOCK_GROUP_RAID10)) {
1826 stripe_nr = stripe_nr * map->num_stripes + i;
1827 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1830 * The remaining case would be for RAID56, multiply by
1831 * nr_data_stripes(). Alternatively, just use rmap_len below
1832 * instead of map->stripe_len
1835 bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
1837 /* Ensure we don't add duplicate addresses */
1838 for (j = 0; j < nr; j++) {
1839 if (buf[j] == bytenr) {
1840 already_inserted = true;
1845 if (!already_inserted)
1851 *stripe_len = io_stripe_size;
1853 free_extent_map(em);
1857 static int exclude_super_stripes(struct btrfs_block_group *cache)
1859 struct btrfs_fs_info *fs_info = cache->fs_info;
1860 const bool zoned = btrfs_is_zoned(fs_info);
1866 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1867 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
1868 cache->bytes_super += stripe_len;
1869 ret = btrfs_add_excluded_extent(fs_info, cache->start,
1875 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1876 bytenr = btrfs_sb_offset(i);
1877 ret = btrfs_rmap_block(fs_info, cache->start, NULL,
1878 bytenr, &logical, &nr, &stripe_len);
1882 /* Shouldn't have super stripes in sequential zones */
1885 "zoned: block group %llu must not contain super block",
1891 u64 len = min_t(u64, stripe_len,
1892 cache->start + cache->length - logical[nr]);
1894 cache->bytes_super += len;
1895 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
1908 static void link_block_group(struct btrfs_block_group *cache)
1910 struct btrfs_space_info *space_info = cache->space_info;
1911 int index = btrfs_bg_flags_to_raid_index(cache->flags);
1913 down_write(&space_info->groups_sem);
1914 list_add_tail(&cache->list, &space_info->block_groups[index]);
1915 up_write(&space_info->groups_sem);
1918 static struct btrfs_block_group *btrfs_create_block_group_cache(
1919 struct btrfs_fs_info *fs_info, u64 start)
1921 struct btrfs_block_group *cache;
1923 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1927 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1929 if (!cache->free_space_ctl) {
1934 cache->start = start;
1936 cache->fs_info = fs_info;
1937 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
1939 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1941 refcount_set(&cache->refs, 1);
1942 spin_lock_init(&cache->lock);
1943 init_rwsem(&cache->data_rwsem);
1944 INIT_LIST_HEAD(&cache->list);
1945 INIT_LIST_HEAD(&cache->cluster_list);
1946 INIT_LIST_HEAD(&cache->bg_list);
1947 INIT_LIST_HEAD(&cache->ro_list);
1948 INIT_LIST_HEAD(&cache->discard_list);
1949 INIT_LIST_HEAD(&cache->dirty_list);
1950 INIT_LIST_HEAD(&cache->io_list);
1951 INIT_LIST_HEAD(&cache->active_bg_list);
1952 btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
1953 atomic_set(&cache->frozen, 0);
1954 mutex_init(&cache->free_space_lock);
1955 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1961 * Iterate all chunks and verify that each of them has the corresponding block
1964 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1966 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1967 struct extent_map *em;
1968 struct btrfs_block_group *bg;
1973 read_lock(&map_tree->lock);
1975 * lookup_extent_mapping will return the first extent map
1976 * intersecting the range, so setting @len to 1 is enough to
1977 * get the first chunk.
1979 em = lookup_extent_mapping(map_tree, start, 1);
1980 read_unlock(&map_tree->lock);
1984 bg = btrfs_lookup_block_group(fs_info, em->start);
1987 "chunk start=%llu len=%llu doesn't have corresponding block group",
1988 em->start, em->len);
1990 free_extent_map(em);
1993 if (bg->start != em->start || bg->length != em->len ||
1994 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1995 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1997 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
1999 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
2000 bg->start, bg->length,
2001 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
2003 free_extent_map(em);
2004 btrfs_put_block_group(bg);
2007 start = em->start + em->len;
2008 free_extent_map(em);
2009 btrfs_put_block_group(bg);
2014 static int read_one_block_group(struct btrfs_fs_info *info,
2015 struct btrfs_block_group_item *bgi,
2016 const struct btrfs_key *key,
2019 struct btrfs_block_group *cache;
2020 struct btrfs_space_info *space_info;
2021 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
2024 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
2026 cache = btrfs_create_block_group_cache(info, key->objectid);
2030 cache->length = key->offset;
2031 cache->used = btrfs_stack_block_group_used(bgi);
2032 cache->flags = btrfs_stack_block_group_flags(bgi);
2033 cache->global_root_id = btrfs_stack_block_group_chunk_objectid(bgi);
2035 set_free_space_tree_thresholds(cache);
2039 * When we mount with old space cache, we need to
2040 * set BTRFS_DC_CLEAR and set dirty flag.
2042 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
2043 * truncate the old free space cache inode and
2045 * b) Setting 'dirty flag' makes sure that we flush
2046 * the new space cache info onto disk.
2048 if (btrfs_test_opt(info, SPACE_CACHE))
2049 cache->disk_cache_state = BTRFS_DC_CLEAR;
2051 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
2052 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
2054 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2060 ret = btrfs_load_block_group_zone_info(cache, false);
2062 btrfs_err(info, "zoned: failed to load zone info of bg %llu",
2068 * We need to exclude the super stripes now so that the space info has
2069 * super bytes accounted for, otherwise we'll think we have more space
2070 * than we actually do.
2072 ret = exclude_super_stripes(cache);
2074 /* We may have excluded something, so call this just in case. */
2075 btrfs_free_excluded_extents(cache);
2080 * For zoned filesystem, space after the allocation offset is the only
2081 * free space for a block group. So, we don't need any caching work.
2082 * btrfs_calc_zone_unusable() will set the amount of free space and
2083 * zone_unusable space.
2085 * For regular filesystem, check for two cases, either we are full, and
2086 * therefore don't need to bother with the caching work since we won't
2087 * find any space, or we are empty, and we can just add all the space
2088 * in and be done with it. This saves us _a_lot_ of time, particularly
2091 if (btrfs_is_zoned(info)) {
2092 btrfs_calc_zone_unusable(cache);
2093 /* Should not have any excluded extents. Just in case, though. */
2094 btrfs_free_excluded_extents(cache);
2095 } else if (cache->length == cache->used) {
2096 cache->last_byte_to_unpin = (u64)-1;
2097 cache->cached = BTRFS_CACHE_FINISHED;
2098 btrfs_free_excluded_extents(cache);
2099 } else if (cache->used == 0) {
2100 cache->last_byte_to_unpin = (u64)-1;
2101 cache->cached = BTRFS_CACHE_FINISHED;
2102 add_new_free_space(cache, cache->start,
2103 cache->start + cache->length);
2104 btrfs_free_excluded_extents(cache);
2107 ret = btrfs_add_block_group_cache(info, cache);
2109 btrfs_remove_free_space_cache(cache);
2112 trace_btrfs_add_block_group(info, cache, 0);
2113 btrfs_update_space_info(info, cache->flags, cache->length,
2114 cache->used, cache->bytes_super,
2115 cache->zone_unusable, cache->zone_is_active,
2118 cache->space_info = space_info;
2120 link_block_group(cache);
2122 set_avail_alloc_bits(info, cache->flags);
2123 if (btrfs_chunk_writeable(info, cache->start)) {
2124 if (cache->used == 0) {
2125 ASSERT(list_empty(&cache->bg_list));
2126 if (btrfs_test_opt(info, DISCARD_ASYNC))
2127 btrfs_discard_queue_work(&info->discard_ctl, cache);
2129 btrfs_mark_bg_unused(cache);
2132 inc_block_group_ro(cache, 1);
2137 btrfs_put_block_group(cache);
2141 static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
2143 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
2144 struct btrfs_space_info *space_info;
2145 struct rb_node *node;
2148 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
2149 struct extent_map *em;
2150 struct map_lookup *map;
2151 struct btrfs_block_group *bg;
2153 em = rb_entry(node, struct extent_map, rb_node);
2154 map = em->map_lookup;
2155 bg = btrfs_create_block_group_cache(fs_info, em->start);
2161 /* Fill dummy cache as FULL */
2162 bg->length = em->len;
2163 bg->flags = map->type;
2164 bg->last_byte_to_unpin = (u64)-1;
2165 bg->cached = BTRFS_CACHE_FINISHED;
2167 bg->flags = map->type;
2168 ret = btrfs_add_block_group_cache(fs_info, bg);
2170 * We may have some valid block group cache added already, in
2171 * that case we skip to the next one.
2173 if (ret == -EEXIST) {
2175 btrfs_put_block_group(bg);
2180 btrfs_remove_free_space_cache(bg);
2181 btrfs_put_block_group(bg);
2185 btrfs_update_space_info(fs_info, bg->flags, em->len, em->len,
2186 0, 0, false, &space_info);
2187 bg->space_info = space_info;
2188 link_block_group(bg);
2190 set_avail_alloc_bits(fs_info, bg->flags);
2193 btrfs_init_global_block_rsv(fs_info);
2197 int btrfs_read_block_groups(struct btrfs_fs_info *info)
2199 struct btrfs_root *root = btrfs_block_group_root(info);
2200 struct btrfs_path *path;
2202 struct btrfs_block_group *cache;
2203 struct btrfs_space_info *space_info;
2204 struct btrfs_key key;
2209 return fill_dummy_bgs(info);
2213 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2214 path = btrfs_alloc_path();
2218 cache_gen = btrfs_super_cache_generation(info->super_copy);
2219 if (btrfs_test_opt(info, SPACE_CACHE) &&
2220 btrfs_super_generation(info->super_copy) != cache_gen)
2222 if (btrfs_test_opt(info, CLEAR_CACHE))
2226 struct btrfs_block_group_item bgi;
2227 struct extent_buffer *leaf;
2230 ret = find_first_block_group(info, path, &key);
2236 leaf = path->nodes[0];
2237 slot = path->slots[0];
2239 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
2242 btrfs_item_key_to_cpu(leaf, &key, slot);
2243 btrfs_release_path(path);
2244 ret = read_one_block_group(info, &bgi, &key, need_clear);
2247 key.objectid += key.offset;
2250 btrfs_release_path(path);
2252 list_for_each_entry(space_info, &info->space_info, list) {
2255 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2256 if (list_empty(&space_info->block_groups[i]))
2258 cache = list_first_entry(&space_info->block_groups[i],
2259 struct btrfs_block_group,
2261 btrfs_sysfs_add_block_group_type(cache);
2264 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2265 (BTRFS_BLOCK_GROUP_RAID10 |
2266 BTRFS_BLOCK_GROUP_RAID1_MASK |
2267 BTRFS_BLOCK_GROUP_RAID56_MASK |
2268 BTRFS_BLOCK_GROUP_DUP)))
2271 * Avoid allocating from un-mirrored block group if there are
2272 * mirrored block groups.
2274 list_for_each_entry(cache,
2275 &space_info->block_groups[BTRFS_RAID_RAID0],
2277 inc_block_group_ro(cache, 1);
2278 list_for_each_entry(cache,
2279 &space_info->block_groups[BTRFS_RAID_SINGLE],
2281 inc_block_group_ro(cache, 1);
2284 btrfs_init_global_block_rsv(info);
2285 ret = check_chunk_block_group_mappings(info);
2287 btrfs_free_path(path);
2289 * We've hit some error while reading the extent tree, and have
2290 * rescue=ibadroots mount option.
2291 * Try to fill the tree using dummy block groups so that the user can
2292 * continue to mount and grab their data.
2294 if (ret && btrfs_test_opt(info, IGNOREBADROOTS))
2295 ret = fill_dummy_bgs(info);
2300 * This function, insert_block_group_item(), belongs to the phase 2 of chunk
2303 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2306 static int insert_block_group_item(struct btrfs_trans_handle *trans,
2307 struct btrfs_block_group *block_group)
2309 struct btrfs_fs_info *fs_info = trans->fs_info;
2310 struct btrfs_block_group_item bgi;
2311 struct btrfs_root *root = btrfs_block_group_root(fs_info);
2312 struct btrfs_key key;
2314 spin_lock(&block_group->lock);
2315 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2316 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2317 block_group->global_root_id);
2318 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2319 key.objectid = block_group->start;
2320 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2321 key.offset = block_group->length;
2322 spin_unlock(&block_group->lock);
2324 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2327 static int insert_dev_extent(struct btrfs_trans_handle *trans,
2328 struct btrfs_device *device, u64 chunk_offset,
2329 u64 start, u64 num_bytes)
2331 struct btrfs_fs_info *fs_info = device->fs_info;
2332 struct btrfs_root *root = fs_info->dev_root;
2333 struct btrfs_path *path;
2334 struct btrfs_dev_extent *extent;
2335 struct extent_buffer *leaf;
2336 struct btrfs_key key;
2339 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
2340 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
2341 path = btrfs_alloc_path();
2345 key.objectid = device->devid;
2346 key.type = BTRFS_DEV_EXTENT_KEY;
2348 ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent));
2352 leaf = path->nodes[0];
2353 extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
2354 btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID);
2355 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
2356 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2357 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
2359 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
2360 btrfs_mark_buffer_dirty(leaf);
2362 btrfs_free_path(path);
2367 * This function belongs to phase 2.
2369 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2372 static int insert_dev_extents(struct btrfs_trans_handle *trans,
2373 u64 chunk_offset, u64 chunk_size)
2375 struct btrfs_fs_info *fs_info = trans->fs_info;
2376 struct btrfs_device *device;
2377 struct extent_map *em;
2378 struct map_lookup *map;
2384 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
2388 map = em->map_lookup;
2389 stripe_size = em->orig_block_len;
2392 * Take the device list mutex to prevent races with the final phase of
2393 * a device replace operation that replaces the device object associated
2394 * with the map's stripes, because the device object's id can change
2395 * at any time during that final phase of the device replace operation
2396 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
2397 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
2398 * resulting in persisting a device extent item with such ID.
2400 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2401 for (i = 0; i < map->num_stripes; i++) {
2402 device = map->stripes[i].dev;
2403 dev_offset = map->stripes[i].physical;
2405 ret = insert_dev_extent(trans, device, chunk_offset, dev_offset,
2410 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2412 free_extent_map(em);
2417 * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
2420 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2423 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2425 struct btrfs_fs_info *fs_info = trans->fs_info;
2426 struct btrfs_block_group *block_group;
2429 while (!list_empty(&trans->new_bgs)) {
2432 block_group = list_first_entry(&trans->new_bgs,
2433 struct btrfs_block_group,
2438 index = btrfs_bg_flags_to_raid_index(block_group->flags);
2440 ret = insert_block_group_item(trans, block_group);
2442 btrfs_abort_transaction(trans, ret);
2443 if (!block_group->chunk_item_inserted) {
2444 mutex_lock(&fs_info->chunk_mutex);
2445 ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group);
2446 mutex_unlock(&fs_info->chunk_mutex);
2448 btrfs_abort_transaction(trans, ret);
2450 ret = insert_dev_extents(trans, block_group->start,
2451 block_group->length);
2453 btrfs_abort_transaction(trans, ret);
2454 add_block_group_free_space(trans, block_group);
2457 * If we restriped during balance, we may have added a new raid
2458 * type, so now add the sysfs entries when it is safe to do so.
2459 * We don't have to worry about locking here as it's handled in
2460 * btrfs_sysfs_add_block_group_type.
2462 if (block_group->space_info->block_group_kobjs[index] == NULL)
2463 btrfs_sysfs_add_block_group_type(block_group);
2465 /* Already aborted the transaction if it failed. */
2467 btrfs_delayed_refs_rsv_release(fs_info, 1);
2468 list_del_init(&block_group->bg_list);
2470 btrfs_trans_release_chunk_metadata(trans);
2474 * For extent tree v2 we use the block_group_item->chunk_offset to point at our
2475 * global root id. For v1 it's always set to BTRFS_FIRST_CHUNK_TREE_OBJECTID.
2477 static u64 calculate_global_root_id(struct btrfs_fs_info *fs_info, u64 offset)
2482 if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2483 return BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2485 /* If we have a smaller fs index based on 128MiB. */
2486 if (btrfs_super_total_bytes(fs_info->super_copy) <= (SZ_1G * 10ULL))
2489 offset = div64_u64(offset, div);
2490 div64_u64_rem(offset, fs_info->nr_global_roots, &index);
2494 struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
2495 u64 bytes_used, u64 type,
2496 u64 chunk_offset, u64 size)
2498 struct btrfs_fs_info *fs_info = trans->fs_info;
2499 struct btrfs_block_group *cache;
2502 btrfs_set_log_full_commit(trans);
2504 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
2506 return ERR_PTR(-ENOMEM);
2508 cache->length = size;
2509 set_free_space_tree_thresholds(cache);
2510 cache->used = bytes_used;
2511 cache->flags = type;
2512 cache->last_byte_to_unpin = (u64)-1;
2513 cache->cached = BTRFS_CACHE_FINISHED;
2514 cache->global_root_id = calculate_global_root_id(fs_info, cache->start);
2516 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
2517 cache->needs_free_space = 1;
2519 ret = btrfs_load_block_group_zone_info(cache, true);
2521 btrfs_put_block_group(cache);
2522 return ERR_PTR(ret);
2525 ret = exclude_super_stripes(cache);
2527 /* We may have excluded something, so call this just in case */
2528 btrfs_free_excluded_extents(cache);
2529 btrfs_put_block_group(cache);
2530 return ERR_PTR(ret);
2533 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2535 btrfs_free_excluded_extents(cache);
2537 #ifdef CONFIG_BTRFS_DEBUG
2538 if (btrfs_should_fragment_free_space(cache)) {
2539 u64 new_bytes_used = size - bytes_used;
2541 bytes_used += new_bytes_used >> 1;
2542 fragment_free_space(cache);
2546 * Ensure the corresponding space_info object is created and
2547 * assigned to our block group. We want our bg to be added to the rbtree
2548 * with its ->space_info set.
2550 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2551 ASSERT(cache->space_info);
2553 ret = btrfs_add_block_group_cache(fs_info, cache);
2555 btrfs_remove_free_space_cache(cache);
2556 btrfs_put_block_group(cache);
2557 return ERR_PTR(ret);
2561 * Now that our block group has its ->space_info set and is inserted in
2562 * the rbtree, update the space info's counters.
2564 trace_btrfs_add_block_group(fs_info, cache, 1);
2565 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
2566 cache->bytes_super, cache->zone_unusable,
2567 cache->zone_is_active, &cache->space_info);
2568 btrfs_update_global_block_rsv(fs_info);
2570 link_block_group(cache);
2572 list_add_tail(&cache->bg_list, &trans->new_bgs);
2573 trans->delayed_ref_updates++;
2574 btrfs_update_delayed_refs_rsv(trans);
2576 set_avail_alloc_bits(fs_info, type);
2581 * Mark one block group RO, can be called several times for the same block
2584 * @cache: the destination block group
2585 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2586 * ensure we still have some free space after marking this
2589 int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2590 bool do_chunk_alloc)
2592 struct btrfs_fs_info *fs_info = cache->fs_info;
2593 struct btrfs_trans_handle *trans;
2594 struct btrfs_root *root = btrfs_block_group_root(fs_info);
2597 bool dirty_bg_running;
2600 * This can only happen when we are doing read-only scrub on read-only
2602 * In that case we should not start a new transaction on read-only fs.
2603 * Thus here we skip all chunk allocations.
2605 if (sb_rdonly(fs_info->sb)) {
2606 mutex_lock(&fs_info->ro_block_group_mutex);
2607 ret = inc_block_group_ro(cache, 0);
2608 mutex_unlock(&fs_info->ro_block_group_mutex);
2613 trans = btrfs_join_transaction(root);
2615 return PTR_ERR(trans);
2617 dirty_bg_running = false;
2620 * We're not allowed to set block groups readonly after the dirty
2621 * block group cache has started writing. If it already started,
2622 * back off and let this transaction commit.
2624 mutex_lock(&fs_info->ro_block_group_mutex);
2625 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2626 u64 transid = trans->transid;
2628 mutex_unlock(&fs_info->ro_block_group_mutex);
2629 btrfs_end_transaction(trans);
2631 ret = btrfs_wait_for_commit(fs_info, transid);
2634 dirty_bg_running = true;
2636 } while (dirty_bg_running);
2638 if (do_chunk_alloc) {
2640 * If we are changing raid levels, try to allocate a
2641 * corresponding block group with the new raid level.
2643 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2644 if (alloc_flags != cache->flags) {
2645 ret = btrfs_chunk_alloc(trans, alloc_flags,
2648 * ENOSPC is allowed here, we may have enough space
2649 * already allocated at the new raid level to carry on
2658 ret = inc_block_group_ro(cache, 0);
2659 if (!do_chunk_alloc || ret == -ETXTBSY)
2663 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2664 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2668 * We have allocated a new chunk. We also need to activate that chunk to
2669 * grant metadata tickets for zoned filesystem.
2671 ret = btrfs_zoned_activate_one_bg(fs_info, cache->space_info, true);
2675 ret = inc_block_group_ro(cache, 0);
2676 if (ret == -ETXTBSY)
2679 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2680 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2681 mutex_lock(&fs_info->chunk_mutex);
2682 check_system_chunk(trans, alloc_flags);
2683 mutex_unlock(&fs_info->chunk_mutex);
2686 mutex_unlock(&fs_info->ro_block_group_mutex);
2688 btrfs_end_transaction(trans);
2692 void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
2694 struct btrfs_space_info *sinfo = cache->space_info;
2699 spin_lock(&sinfo->lock);
2700 spin_lock(&cache->lock);
2702 if (btrfs_is_zoned(cache->fs_info)) {
2703 /* Migrate zone_unusable bytes back */
2704 cache->zone_unusable =
2705 (cache->alloc_offset - cache->used) +
2706 (cache->length - cache->zone_capacity);
2707 sinfo->bytes_zone_unusable += cache->zone_unusable;
2708 sinfo->bytes_readonly -= cache->zone_unusable;
2710 num_bytes = cache->length - cache->reserved -
2711 cache->pinned - cache->bytes_super -
2712 cache->zone_unusable - cache->used;
2713 sinfo->bytes_readonly -= num_bytes;
2714 list_del_init(&cache->ro_list);
2716 spin_unlock(&cache->lock);
2717 spin_unlock(&sinfo->lock);
2720 static int update_block_group_item(struct btrfs_trans_handle *trans,
2721 struct btrfs_path *path,
2722 struct btrfs_block_group *cache)
2724 struct btrfs_fs_info *fs_info = trans->fs_info;
2726 struct btrfs_root *root = btrfs_block_group_root(fs_info);
2728 struct extent_buffer *leaf;
2729 struct btrfs_block_group_item bgi;
2730 struct btrfs_key key;
2732 key.objectid = cache->start;
2733 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2734 key.offset = cache->length;
2736 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2743 leaf = path->nodes[0];
2744 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2745 btrfs_set_stack_block_group_used(&bgi, cache->used);
2746 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2747 cache->global_root_id);
2748 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2749 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
2750 btrfs_mark_buffer_dirty(leaf);
2752 btrfs_release_path(path);
2757 static int cache_save_setup(struct btrfs_block_group *block_group,
2758 struct btrfs_trans_handle *trans,
2759 struct btrfs_path *path)
2761 struct btrfs_fs_info *fs_info = block_group->fs_info;
2762 struct btrfs_root *root = fs_info->tree_root;
2763 struct inode *inode = NULL;
2764 struct extent_changeset *data_reserved = NULL;
2766 int dcs = BTRFS_DC_ERROR;
2771 if (!btrfs_test_opt(fs_info, SPACE_CACHE))
2775 * If this block group is smaller than 100 megs don't bother caching the
2778 if (block_group->length < (100 * SZ_1M)) {
2779 spin_lock(&block_group->lock);
2780 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2781 spin_unlock(&block_group->lock);
2785 if (TRANS_ABORTED(trans))
2788 inode = lookup_free_space_inode(block_group, path);
2789 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2790 ret = PTR_ERR(inode);
2791 btrfs_release_path(path);
2795 if (IS_ERR(inode)) {
2799 if (block_group->ro)
2802 ret = create_free_space_inode(trans, block_group, path);
2809 * We want to set the generation to 0, that way if anything goes wrong
2810 * from here on out we know not to trust this cache when we load up next
2813 BTRFS_I(inode)->generation = 0;
2814 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
2817 * So theoretically we could recover from this, simply set the
2818 * super cache generation to 0 so we know to invalidate the
2819 * cache, but then we'd have to keep track of the block groups
2820 * that fail this way so we know we _have_ to reset this cache
2821 * before the next commit or risk reading stale cache. So to
2822 * limit our exposure to horrible edge cases lets just abort the
2823 * transaction, this only happens in really bad situations
2826 btrfs_abort_transaction(trans, ret);
2831 /* We've already setup this transaction, go ahead and exit */
2832 if (block_group->cache_generation == trans->transid &&
2833 i_size_read(inode)) {
2834 dcs = BTRFS_DC_SETUP;
2838 if (i_size_read(inode) > 0) {
2839 ret = btrfs_check_trunc_cache_free_space(fs_info,
2840 &fs_info->global_block_rsv);
2844 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2849 spin_lock(&block_group->lock);
2850 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2851 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2853 * don't bother trying to write stuff out _if_
2854 * a) we're not cached,
2855 * b) we're with nospace_cache mount option,
2856 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2858 dcs = BTRFS_DC_WRITTEN;
2859 spin_unlock(&block_group->lock);
2862 spin_unlock(&block_group->lock);
2865 * We hit an ENOSPC when setting up the cache in this transaction, just
2866 * skip doing the setup, we've already cleared the cache so we're safe.
2868 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2874 * Try to preallocate enough space based on how big the block group is.
2875 * Keep in mind this has to include any pinned space which could end up
2876 * taking up quite a bit since it's not folded into the other space
2879 cache_size = div_u64(block_group->length, SZ_256M);
2884 cache_size *= fs_info->sectorsize;
2886 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
2891 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
2892 cache_size, cache_size,
2895 * Our cache requires contiguous chunks so that we don't modify a bunch
2896 * of metadata or split extents when writing the cache out, which means
2897 * we can enospc if we are heavily fragmented in addition to just normal
2898 * out of space conditions. So if we hit this just skip setting up any
2899 * other block groups for this transaction, maybe we'll unpin enough
2900 * space the next time around.
2903 dcs = BTRFS_DC_SETUP;
2904 else if (ret == -ENOSPC)
2905 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2910 btrfs_release_path(path);
2912 spin_lock(&block_group->lock);
2913 if (!ret && dcs == BTRFS_DC_SETUP)
2914 block_group->cache_generation = trans->transid;
2915 block_group->disk_cache_state = dcs;
2916 spin_unlock(&block_group->lock);
2918 extent_changeset_free(data_reserved);
2922 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2924 struct btrfs_fs_info *fs_info = trans->fs_info;
2925 struct btrfs_block_group *cache, *tmp;
2926 struct btrfs_transaction *cur_trans = trans->transaction;
2927 struct btrfs_path *path;
2929 if (list_empty(&cur_trans->dirty_bgs) ||
2930 !btrfs_test_opt(fs_info, SPACE_CACHE))
2933 path = btrfs_alloc_path();
2937 /* Could add new block groups, use _safe just in case */
2938 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2940 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2941 cache_save_setup(cache, trans, path);
2944 btrfs_free_path(path);
2949 * Transaction commit does final block group cache writeback during a critical
2950 * section where nothing is allowed to change the FS. This is required in
2951 * order for the cache to actually match the block group, but can introduce a
2952 * lot of latency into the commit.
2954 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2955 * There's a chance we'll have to redo some of it if the block group changes
2956 * again during the commit, but it greatly reduces the commit latency by
2957 * getting rid of the easy block groups while we're still allowing others to
2960 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2962 struct btrfs_fs_info *fs_info = trans->fs_info;
2963 struct btrfs_block_group *cache;
2964 struct btrfs_transaction *cur_trans = trans->transaction;
2967 struct btrfs_path *path = NULL;
2969 struct list_head *io = &cur_trans->io_bgs;
2972 spin_lock(&cur_trans->dirty_bgs_lock);
2973 if (list_empty(&cur_trans->dirty_bgs)) {
2974 spin_unlock(&cur_trans->dirty_bgs_lock);
2977 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2978 spin_unlock(&cur_trans->dirty_bgs_lock);
2981 /* Make sure all the block groups on our dirty list actually exist */
2982 btrfs_create_pending_block_groups(trans);
2985 path = btrfs_alloc_path();
2993 * cache_write_mutex is here only to save us from balance or automatic
2994 * removal of empty block groups deleting this block group while we are
2995 * writing out the cache
2997 mutex_lock(&trans->transaction->cache_write_mutex);
2998 while (!list_empty(&dirty)) {
2999 bool drop_reserve = true;
3001 cache = list_first_entry(&dirty, struct btrfs_block_group,
3004 * This can happen if something re-dirties a block group that
3005 * is already under IO. Just wait for it to finish and then do
3008 if (!list_empty(&cache->io_list)) {
3009 list_del_init(&cache->io_list);
3010 btrfs_wait_cache_io(trans, cache, path);
3011 btrfs_put_block_group(cache);
3016 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
3017 * it should update the cache_state. Don't delete until after
3020 * Since we're not running in the commit critical section
3021 * we need the dirty_bgs_lock to protect from update_block_group
3023 spin_lock(&cur_trans->dirty_bgs_lock);
3024 list_del_init(&cache->dirty_list);
3025 spin_unlock(&cur_trans->dirty_bgs_lock);
3029 cache_save_setup(cache, trans, path);
3031 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3032 cache->io_ctl.inode = NULL;
3033 ret = btrfs_write_out_cache(trans, cache, path);
3034 if (ret == 0 && cache->io_ctl.inode) {
3038 * The cache_write_mutex is protecting the
3039 * io_list, also refer to the definition of
3040 * btrfs_transaction::io_bgs for more details
3042 list_add_tail(&cache->io_list, io);
3045 * If we failed to write the cache, the
3046 * generation will be bad and life goes on
3052 ret = update_block_group_item(trans, path, cache);
3054 * Our block group might still be attached to the list
3055 * of new block groups in the transaction handle of some
3056 * other task (struct btrfs_trans_handle->new_bgs). This
3057 * means its block group item isn't yet in the extent
3058 * tree. If this happens ignore the error, as we will
3059 * try again later in the critical section of the
3060 * transaction commit.
3062 if (ret == -ENOENT) {
3064 spin_lock(&cur_trans->dirty_bgs_lock);
3065 if (list_empty(&cache->dirty_list)) {
3066 list_add_tail(&cache->dirty_list,
3067 &cur_trans->dirty_bgs);
3068 btrfs_get_block_group(cache);
3069 drop_reserve = false;
3071 spin_unlock(&cur_trans->dirty_bgs_lock);
3073 btrfs_abort_transaction(trans, ret);
3077 /* If it's not on the io list, we need to put the block group */
3079 btrfs_put_block_group(cache);
3081 btrfs_delayed_refs_rsv_release(fs_info, 1);
3083 * Avoid blocking other tasks for too long. It might even save
3084 * us from writing caches for block groups that are going to be
3087 mutex_unlock(&trans->transaction->cache_write_mutex);
3090 mutex_lock(&trans->transaction->cache_write_mutex);
3092 mutex_unlock(&trans->transaction->cache_write_mutex);
3095 * Go through delayed refs for all the stuff we've just kicked off
3096 * and then loop back (just once)
3099 ret = btrfs_run_delayed_refs(trans, 0);
3100 if (!ret && loops == 0) {
3102 spin_lock(&cur_trans->dirty_bgs_lock);
3103 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3105 * dirty_bgs_lock protects us from concurrent block group
3106 * deletes too (not just cache_write_mutex).
3108 if (!list_empty(&dirty)) {
3109 spin_unlock(&cur_trans->dirty_bgs_lock);
3112 spin_unlock(&cur_trans->dirty_bgs_lock);
3116 spin_lock(&cur_trans->dirty_bgs_lock);
3117 list_splice_init(&dirty, &cur_trans->dirty_bgs);
3118 spin_unlock(&cur_trans->dirty_bgs_lock);
3119 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3122 btrfs_free_path(path);
3126 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
3128 struct btrfs_fs_info *fs_info = trans->fs_info;
3129 struct btrfs_block_group *cache;
3130 struct btrfs_transaction *cur_trans = trans->transaction;
3133 struct btrfs_path *path;
3134 struct list_head *io = &cur_trans->io_bgs;
3136 path = btrfs_alloc_path();
3141 * Even though we are in the critical section of the transaction commit,
3142 * we can still have concurrent tasks adding elements to this
3143 * transaction's list of dirty block groups. These tasks correspond to
3144 * endio free space workers started when writeback finishes for a
3145 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3146 * allocate new block groups as a result of COWing nodes of the root
3147 * tree when updating the free space inode. The writeback for the space
3148 * caches is triggered by an earlier call to
3149 * btrfs_start_dirty_block_groups() and iterations of the following
3151 * Also we want to do the cache_save_setup first and then run the
3152 * delayed refs to make sure we have the best chance at doing this all
3155 spin_lock(&cur_trans->dirty_bgs_lock);
3156 while (!list_empty(&cur_trans->dirty_bgs)) {
3157 cache = list_first_entry(&cur_trans->dirty_bgs,
3158 struct btrfs_block_group,
3162 * This can happen if cache_save_setup re-dirties a block group
3163 * that is already under IO. Just wait for it to finish and
3164 * then do it all again
3166 if (!list_empty(&cache->io_list)) {
3167 spin_unlock(&cur_trans->dirty_bgs_lock);
3168 list_del_init(&cache->io_list);
3169 btrfs_wait_cache_io(trans, cache, path);
3170 btrfs_put_block_group(cache);
3171 spin_lock(&cur_trans->dirty_bgs_lock);
3175 * Don't remove from the dirty list until after we've waited on
3178 list_del_init(&cache->dirty_list);
3179 spin_unlock(&cur_trans->dirty_bgs_lock);
3182 cache_save_setup(cache, trans, path);
3185 ret = btrfs_run_delayed_refs(trans,
3186 (unsigned long) -1);
3188 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3189 cache->io_ctl.inode = NULL;
3190 ret = btrfs_write_out_cache(trans, cache, path);
3191 if (ret == 0 && cache->io_ctl.inode) {
3193 list_add_tail(&cache->io_list, io);
3196 * If we failed to write the cache, the
3197 * generation will be bad and life goes on
3203 ret = update_block_group_item(trans, path, cache);
3205 * One of the free space endio workers might have
3206 * created a new block group while updating a free space
3207 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3208 * and hasn't released its transaction handle yet, in
3209 * which case the new block group is still attached to
3210 * its transaction handle and its creation has not
3211 * finished yet (no block group item in the extent tree
3212 * yet, etc). If this is the case, wait for all free
3213 * space endio workers to finish and retry. This is a
3214 * very rare case so no need for a more efficient and
3217 if (ret == -ENOENT) {
3218 wait_event(cur_trans->writer_wait,
3219 atomic_read(&cur_trans->num_writers) == 1);
3220 ret = update_block_group_item(trans, path, cache);
3223 btrfs_abort_transaction(trans, ret);
3226 /* If its not on the io list, we need to put the block group */
3228 btrfs_put_block_group(cache);
3229 btrfs_delayed_refs_rsv_release(fs_info, 1);
3230 spin_lock(&cur_trans->dirty_bgs_lock);
3232 spin_unlock(&cur_trans->dirty_bgs_lock);
3235 * Refer to the definition of io_bgs member for details why it's safe
3236 * to use it without any locking
3238 while (!list_empty(io)) {
3239 cache = list_first_entry(io, struct btrfs_block_group,
3241 list_del_init(&cache->io_list);
3242 btrfs_wait_cache_io(trans, cache, path);
3243 btrfs_put_block_group(cache);
3246 btrfs_free_path(path);
3250 static inline bool should_reclaim_block_group(struct btrfs_block_group *bg,
3253 const struct btrfs_space_info *space_info = bg->space_info;
3254 const int reclaim_thresh = READ_ONCE(space_info->bg_reclaim_threshold);
3255 const u64 new_val = bg->used;
3256 const u64 old_val = new_val + bytes_freed;
3259 if (reclaim_thresh == 0)
3262 thresh = div_factor_fine(bg->length, reclaim_thresh);
3265 * If we were below the threshold before don't reclaim, we are likely a
3266 * brand new block group and we don't want to relocate new block groups.
3268 if (old_val < thresh)
3270 if (new_val >= thresh)
3275 int btrfs_update_block_group(struct btrfs_trans_handle *trans,
3276 u64 bytenr, u64 num_bytes, bool alloc)
3278 struct btrfs_fs_info *info = trans->fs_info;
3279 struct btrfs_block_group *cache = NULL;
3280 u64 total = num_bytes;
3286 /* Block accounting for super block */
3287 spin_lock(&info->delalloc_root_lock);
3288 old_val = btrfs_super_bytes_used(info->super_copy);
3290 old_val += num_bytes;
3292 old_val -= num_bytes;
3293 btrfs_set_super_bytes_used(info->super_copy, old_val);
3294 spin_unlock(&info->delalloc_root_lock);
3299 cache = btrfs_lookup_block_group(info, bytenr);
3304 factor = btrfs_bg_type_to_factor(cache->flags);
3307 * If this block group has free space cache written out, we
3308 * need to make sure to load it if we are removing space. This
3309 * is because we need the unpinning stage to actually add the
3310 * space back to the block group, otherwise we will leak space.
3312 if (!alloc && !btrfs_block_group_done(cache))
3313 btrfs_cache_block_group(cache, 1);
3315 byte_in_group = bytenr - cache->start;
3316 WARN_ON(byte_in_group > cache->length);
3318 spin_lock(&cache->space_info->lock);
3319 spin_lock(&cache->lock);
3321 if (btrfs_test_opt(info, SPACE_CACHE) &&
3322 cache->disk_cache_state < BTRFS_DC_CLEAR)
3323 cache->disk_cache_state = BTRFS_DC_CLEAR;
3325 old_val = cache->used;
3326 num_bytes = min(total, cache->length - byte_in_group);
3328 old_val += num_bytes;
3329 cache->used = old_val;
3330 cache->reserved -= num_bytes;
3331 cache->space_info->bytes_reserved -= num_bytes;
3332 cache->space_info->bytes_used += num_bytes;
3333 cache->space_info->disk_used += num_bytes * factor;
3334 spin_unlock(&cache->lock);
3335 spin_unlock(&cache->space_info->lock);
3337 old_val -= num_bytes;
3338 cache->used = old_val;
3339 cache->pinned += num_bytes;
3340 btrfs_space_info_update_bytes_pinned(info,
3341 cache->space_info, num_bytes);
3342 cache->space_info->bytes_used -= num_bytes;
3343 cache->space_info->disk_used -= num_bytes * factor;
3345 reclaim = should_reclaim_block_group(cache, num_bytes);
3346 spin_unlock(&cache->lock);
3347 spin_unlock(&cache->space_info->lock);
3349 set_extent_dirty(&trans->transaction->pinned_extents,
3350 bytenr, bytenr + num_bytes - 1,
3351 GFP_NOFS | __GFP_NOFAIL);
3354 spin_lock(&trans->transaction->dirty_bgs_lock);
3355 if (list_empty(&cache->dirty_list)) {
3356 list_add_tail(&cache->dirty_list,
3357 &trans->transaction->dirty_bgs);
3358 trans->delayed_ref_updates++;
3359 btrfs_get_block_group(cache);
3361 spin_unlock(&trans->transaction->dirty_bgs_lock);
3364 * No longer have used bytes in this block group, queue it for
3365 * deletion. We do this after adding the block group to the
3366 * dirty list to avoid races between cleaner kthread and space
3369 if (!alloc && old_val == 0) {
3370 if (!btrfs_test_opt(info, DISCARD_ASYNC))
3371 btrfs_mark_bg_unused(cache);
3372 } else if (!alloc && reclaim) {
3373 btrfs_mark_bg_to_reclaim(cache);
3376 btrfs_put_block_group(cache);
3378 bytenr += num_bytes;
3381 /* Modified block groups are accounted for in the delayed_refs_rsv. */
3382 btrfs_update_delayed_refs_rsv(trans);
3387 * btrfs_add_reserved_bytes - update the block_group and space info counters
3388 * @cache: The cache we are manipulating
3389 * @ram_bytes: The number of bytes of file content, and will be same to
3390 * @num_bytes except for the compress path.
3391 * @num_bytes: The number of bytes in question
3392 * @delalloc: The blocks are allocated for the delalloc write
3394 * This is called by the allocator when it reserves space. If this is a
3395 * reservation and the block group has become read only we cannot make the
3396 * reservation and return -EAGAIN, otherwise this function always succeeds.
3398 int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
3399 u64 ram_bytes, u64 num_bytes, int delalloc)
3401 struct btrfs_space_info *space_info = cache->space_info;
3404 spin_lock(&space_info->lock);
3405 spin_lock(&cache->lock);
3409 cache->reserved += num_bytes;
3410 space_info->bytes_reserved += num_bytes;
3411 trace_btrfs_space_reservation(cache->fs_info, "space_info",
3412 space_info->flags, num_bytes, 1);
3413 btrfs_space_info_update_bytes_may_use(cache->fs_info,
3414 space_info, -ram_bytes);
3416 cache->delalloc_bytes += num_bytes;
3419 * Compression can use less space than we reserved, so wake
3420 * tickets if that happens
3422 if (num_bytes < ram_bytes)
3423 btrfs_try_granting_tickets(cache->fs_info, space_info);
3425 spin_unlock(&cache->lock);
3426 spin_unlock(&space_info->lock);
3431 * btrfs_free_reserved_bytes - update the block_group and space info counters
3432 * @cache: The cache we are manipulating
3433 * @num_bytes: The number of bytes in question
3434 * @delalloc: The blocks are allocated for the delalloc write
3436 * This is called by somebody who is freeing space that was never actually used
3437 * on disk. For example if you reserve some space for a new leaf in transaction
3438 * A and before transaction A commits you free that leaf, you call this with
3439 * reserve set to 0 in order to clear the reservation.
3441 void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3442 u64 num_bytes, int delalloc)
3444 struct btrfs_space_info *space_info = cache->space_info;
3446 spin_lock(&space_info->lock);
3447 spin_lock(&cache->lock);
3449 space_info->bytes_readonly += num_bytes;
3450 cache->reserved -= num_bytes;
3451 space_info->bytes_reserved -= num_bytes;
3452 space_info->max_extent_size = 0;
3455 cache->delalloc_bytes -= num_bytes;
3456 spin_unlock(&cache->lock);
3458 btrfs_try_granting_tickets(cache->fs_info, space_info);
3459 spin_unlock(&space_info->lock);
3462 static void force_metadata_allocation(struct btrfs_fs_info *info)
3464 struct list_head *head = &info->space_info;
3465 struct btrfs_space_info *found;
3467 list_for_each_entry(found, head, list) {
3468 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3469 found->force_alloc = CHUNK_ALLOC_FORCE;
3473 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3474 struct btrfs_space_info *sinfo, int force)
3476 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3479 if (force == CHUNK_ALLOC_FORCE)
3483 * in limited mode, we want to have some free space up to
3484 * about 1% of the FS size.
3486 if (force == CHUNK_ALLOC_LIMITED) {
3487 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3488 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3490 if (sinfo->total_bytes - bytes_used < thresh)
3494 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3499 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3501 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3503 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3506 static struct btrfs_block_group *do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags)
3508 struct btrfs_block_group *bg;
3512 * Check if we have enough space in the system space info because we
3513 * will need to update device items in the chunk btree and insert a new
3514 * chunk item in the chunk btree as well. This will allocate a new
3515 * system block group if needed.
3517 check_system_chunk(trans, flags);
3519 bg = btrfs_create_chunk(trans, flags);
3525 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
3527 * Normally we are not expected to fail with -ENOSPC here, since we have
3528 * previously reserved space in the system space_info and allocated one
3529 * new system chunk if necessary. However there are three exceptions:
3531 * 1) We may have enough free space in the system space_info but all the
3532 * existing system block groups have a profile which can not be used
3533 * for extent allocation.
3535 * This happens when mounting in degraded mode. For example we have a
3536 * RAID1 filesystem with 2 devices, lose one device and mount the fs
3537 * using the other device in degraded mode. If we then allocate a chunk,
3538 * we may have enough free space in the existing system space_info, but
3539 * none of the block groups can be used for extent allocation since they
3540 * have a RAID1 profile, and because we are in degraded mode with a
3541 * single device, we are forced to allocate a new system chunk with a
3542 * SINGLE profile. Making check_system_chunk() iterate over all system
3543 * block groups and check if they have a usable profile and enough space
3544 * can be slow on very large filesystems, so we tolerate the -ENOSPC and
3545 * try again after forcing allocation of a new system chunk. Like this
3546 * we avoid paying the cost of that search in normal circumstances, when
3547 * we were not mounted in degraded mode;
3549 * 2) We had enough free space info the system space_info, and one suitable
3550 * block group to allocate from when we called check_system_chunk()
3551 * above. However right after we called it, the only system block group
3552 * with enough free space got turned into RO mode by a running scrub,
3553 * and in this case we have to allocate a new one and retry. We only
3554 * need do this allocate and retry once, since we have a transaction
3555 * handle and scrub uses the commit root to search for block groups;
3557 * 3) We had one system block group with enough free space when we called
3558 * check_system_chunk(), but after that, right before we tried to
3559 * allocate the last extent buffer we needed, a discard operation came
3560 * in and it temporarily removed the last free space entry from the
3561 * block group (discard removes a free space entry, discards it, and
3562 * then adds back the entry to the block group cache).
3564 if (ret == -ENOSPC) {
3565 const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info);
3566 struct btrfs_block_group *sys_bg;
3568 sys_bg = btrfs_create_chunk(trans, sys_flags);
3569 if (IS_ERR(sys_bg)) {
3570 ret = PTR_ERR(sys_bg);
3571 btrfs_abort_transaction(trans, ret);
3575 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3577 btrfs_abort_transaction(trans, ret);
3581 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
3583 btrfs_abort_transaction(trans, ret);
3587 btrfs_abort_transaction(trans, ret);
3591 btrfs_trans_release_chunk_metadata(trans);
3594 return ERR_PTR(ret);
3596 btrfs_get_block_group(bg);
3601 * Chunk allocation is done in 2 phases:
3603 * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
3604 * the chunk, the chunk mapping, create its block group and add the items
3605 * that belong in the chunk btree to it - more specifically, we need to
3606 * update device items in the chunk btree and add a new chunk item to it.
3608 * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
3609 * group item to the extent btree and the device extent items to the devices
3612 * This is done to prevent deadlocks. For example when COWing a node from the
3613 * extent btree we are holding a write lock on the node's parent and if we
3614 * trigger chunk allocation and attempted to insert the new block group item
3615 * in the extent btree right way, we could deadlock because the path for the
3616 * insertion can include that parent node. At first glance it seems impossible
3617 * to trigger chunk allocation after starting a transaction since tasks should
3618 * reserve enough transaction units (metadata space), however while that is true
3619 * most of the time, chunk allocation may still be triggered for several reasons:
3621 * 1) When reserving metadata, we check if there is enough free space in the
3622 * metadata space_info and therefore don't trigger allocation of a new chunk.
3623 * However later when the task actually tries to COW an extent buffer from
3624 * the extent btree or from the device btree for example, it is forced to
3625 * allocate a new block group (chunk) because the only one that had enough
3626 * free space was just turned to RO mode by a running scrub for example (or
3627 * device replace, block group reclaim thread, etc), so we can not use it
3628 * for allocating an extent and end up being forced to allocate a new one;
3630 * 2) Because we only check that the metadata space_info has enough free bytes,
3631 * we end up not allocating a new metadata chunk in that case. However if
3632 * the filesystem was mounted in degraded mode, none of the existing block
3633 * groups might be suitable for extent allocation due to their incompatible
3634 * profile (for e.g. mounting a 2 devices filesystem, where all block groups
3635 * use a RAID1 profile, in degraded mode using a single device). In this case
3636 * when the task attempts to COW some extent buffer of the extent btree for
3637 * example, it will trigger allocation of a new metadata block group with a
3638 * suitable profile (SINGLE profile in the example of the degraded mount of
3639 * the RAID1 filesystem);
3641 * 3) The task has reserved enough transaction units / metadata space, but when
3642 * it attempts to COW an extent buffer from the extent or device btree for
3643 * example, it does not find any free extent in any metadata block group,
3644 * therefore forced to try to allocate a new metadata block group.
3645 * This is because some other task allocated all available extents in the
3646 * meanwhile - this typically happens with tasks that don't reserve space
3647 * properly, either intentionally or as a bug. One example where this is
3648 * done intentionally is fsync, as it does not reserve any transaction units
3649 * and ends up allocating a variable number of metadata extents for log
3650 * tree extent buffers;
3652 * 4) The task has reserved enough transaction units / metadata space, but right
3653 * before it tries to allocate the last extent buffer it needs, a discard
3654 * operation comes in and, temporarily, removes the last free space entry from
3655 * the only metadata block group that had free space (discard starts by
3656 * removing a free space entry from a block group, then does the discard
3657 * operation and, once it's done, it adds back the free space entry to the
3660 * We also need this 2 phases setup when adding a device to a filesystem with
3661 * a seed device - we must create new metadata and system chunks without adding
3662 * any of the block group items to the chunk, extent and device btrees. If we
3663 * did not do it this way, we would get ENOSPC when attempting to update those
3664 * btrees, since all the chunks from the seed device are read-only.
3666 * Phase 1 does the updates and insertions to the chunk btree because if we had
3667 * it done in phase 2 and have a thundering herd of tasks allocating chunks in
3668 * parallel, we risk having too many system chunks allocated by many tasks if
3669 * many tasks reach phase 1 without the previous ones completing phase 2. In the
3670 * extreme case this leads to exhaustion of the system chunk array in the
3671 * superblock. This is easier to trigger if using a btree node/leaf size of 64K
3672 * and with RAID filesystems (so we have more device items in the chunk btree).
3673 * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
3674 * the system chunk array due to concurrent allocations") provides more details.
3676 * Allocation of system chunks does not happen through this function. A task that
3677 * needs to update the chunk btree (the only btree that uses system chunks), must
3678 * preallocate chunk space by calling either check_system_chunk() or
3679 * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or
3680 * metadata chunk or when removing a chunk, while the later is used before doing
3681 * a modification to the chunk btree - use cases for the later are adding,
3682 * removing and resizing a device as well as relocation of a system chunk.
3683 * See the comment below for more details.
3685 * The reservation of system space, done through check_system_chunk(), as well
3686 * as all the updates and insertions into the chunk btree must be done while
3687 * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
3688 * an extent buffer from the chunks btree we never trigger allocation of a new
3689 * system chunk, which would result in a deadlock (trying to lock twice an
3690 * extent buffer of the chunk btree, first time before triggering the chunk
3691 * allocation and the second time during chunk allocation while attempting to
3692 * update the chunks btree). The system chunk array is also updated while holding
3693 * that mutex. The same logic applies to removing chunks - we must reserve system
3694 * space, update the chunk btree and the system chunk array in the superblock
3695 * while holding fs_info->chunk_mutex.
3697 * This function, btrfs_chunk_alloc(), belongs to phase 1.
3699 * If @force is CHUNK_ALLOC_FORCE:
3700 * - return 1 if it successfully allocates a chunk,
3701 * - return errors including -ENOSPC otherwise.
3702 * If @force is NOT CHUNK_ALLOC_FORCE:
3703 * - return 0 if it doesn't need to allocate a new chunk,
3704 * - return 1 if it successfully allocates a chunk,
3705 * - return errors including -ENOSPC otherwise.
3707 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3708 enum btrfs_chunk_alloc_enum force)
3710 struct btrfs_fs_info *fs_info = trans->fs_info;
3711 struct btrfs_space_info *space_info;
3712 struct btrfs_block_group *ret_bg;
3713 bool wait_for_alloc = false;
3714 bool should_alloc = false;
3715 bool from_extent_allocation = false;
3718 if (force == CHUNK_ALLOC_FORCE_FOR_EXTENT) {
3719 from_extent_allocation = true;
3720 force = CHUNK_ALLOC_FORCE;
3723 /* Don't re-enter if we're already allocating a chunk */
3724 if (trans->allocating_chunk)
3727 * Allocation of system chunks can not happen through this path, as we
3728 * could end up in a deadlock if we are allocating a data or metadata
3729 * chunk and there is another task modifying the chunk btree.
3731 * This is because while we are holding the chunk mutex, we will attempt
3732 * to add the new chunk item to the chunk btree or update an existing
3733 * device item in the chunk btree, while the other task that is modifying
3734 * the chunk btree is attempting to COW an extent buffer while holding a
3735 * lock on it and on its parent - if the COW operation triggers a system
3736 * chunk allocation, then we can deadlock because we are holding the
3737 * chunk mutex and we may need to access that extent buffer or its parent
3738 * in order to add the chunk item or update a device item.
3740 * Tasks that want to modify the chunk tree should reserve system space
3741 * before updating the chunk btree, by calling either
3742 * btrfs_reserve_chunk_metadata() or check_system_chunk().
3743 * It's possible that after a task reserves the space, it still ends up
3744 * here - this happens in the cases described above at do_chunk_alloc().
3745 * The task will have to either retry or fail.
3747 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3750 space_info = btrfs_find_space_info(fs_info, flags);
3754 spin_lock(&space_info->lock);
3755 if (force < space_info->force_alloc)
3756 force = space_info->force_alloc;
3757 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3758 if (space_info->full) {
3759 /* No more free physical space */
3764 spin_unlock(&space_info->lock);
3766 } else if (!should_alloc) {
3767 spin_unlock(&space_info->lock);
3769 } else if (space_info->chunk_alloc) {
3771 * Someone is already allocating, so we need to block
3772 * until this someone is finished and then loop to
3773 * recheck if we should continue with our allocation
3776 wait_for_alloc = true;
3777 force = CHUNK_ALLOC_NO_FORCE;
3778 spin_unlock(&space_info->lock);
3779 mutex_lock(&fs_info->chunk_mutex);
3780 mutex_unlock(&fs_info->chunk_mutex);
3782 /* Proceed with allocation */
3783 space_info->chunk_alloc = 1;
3784 wait_for_alloc = false;
3785 spin_unlock(&space_info->lock);
3789 } while (wait_for_alloc);
3791 mutex_lock(&fs_info->chunk_mutex);
3792 trans->allocating_chunk = true;
3795 * If we have mixed data/metadata chunks we want to make sure we keep
3796 * allocating mixed chunks instead of individual chunks.
3798 if (btrfs_mixed_space_info(space_info))
3799 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3802 * if we're doing a data chunk, go ahead and make sure that
3803 * we keep a reasonable number of metadata chunks allocated in the
3806 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3807 fs_info->data_chunk_allocations++;
3808 if (!(fs_info->data_chunk_allocations %
3809 fs_info->metadata_ratio))
3810 force_metadata_allocation(fs_info);
3813 ret_bg = do_chunk_alloc(trans, flags);
3814 trans->allocating_chunk = false;
3816 if (IS_ERR(ret_bg)) {
3817 ret = PTR_ERR(ret_bg);
3818 } else if (from_extent_allocation) {
3820 * New block group is likely to be used soon. Try to activate
3821 * it now. Failure is OK for now.
3823 btrfs_zone_activate(ret_bg);
3827 btrfs_put_block_group(ret_bg);
3829 spin_lock(&space_info->lock);
3832 space_info->full = 1;
3837 space_info->max_extent_size = 0;
3840 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3842 space_info->chunk_alloc = 0;
3843 spin_unlock(&space_info->lock);
3844 mutex_unlock(&fs_info->chunk_mutex);
3849 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3853 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3855 num_dev = fs_info->fs_devices->rw_devices;
3860 static void reserve_chunk_space(struct btrfs_trans_handle *trans,
3864 struct btrfs_fs_info *fs_info = trans->fs_info;
3865 struct btrfs_space_info *info;
3870 * Needed because we can end up allocating a system chunk and for an
3871 * atomic and race free space reservation in the chunk block reserve.
3873 lockdep_assert_held(&fs_info->chunk_mutex);
3875 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3876 spin_lock(&info->lock);
3877 left = info->total_bytes - btrfs_space_info_used(info, true);
3878 spin_unlock(&info->lock);
3880 if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3881 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3883 btrfs_dump_space_info(fs_info, info, 0, 0);
3887 u64 flags = btrfs_system_alloc_profile(fs_info);
3888 struct btrfs_block_group *bg;
3891 * Ignore failure to create system chunk. We might end up not
3892 * needing it, as we might not need to COW all nodes/leafs from
3893 * the paths we visit in the chunk tree (they were already COWed
3894 * or created in the current transaction for example).
3896 bg = btrfs_create_chunk(trans, flags);
3901 * We have a new chunk. We also need to activate it for
3904 ret = btrfs_zoned_activate_one_bg(fs_info, info, true);
3909 * If we fail to add the chunk item here, we end up
3910 * trying again at phase 2 of chunk allocation, at
3911 * btrfs_create_pending_block_groups(). So ignore
3912 * any error here. An ENOSPC here could happen, due to
3913 * the cases described at do_chunk_alloc() - the system
3914 * block group we just created was just turned into RO
3915 * mode by a scrub for example, or a running discard
3916 * temporarily removed its free space entries, etc.
3918 btrfs_chunk_alloc_add_chunk_item(trans, bg);
3923 ret = btrfs_block_rsv_add(fs_info,
3924 &fs_info->chunk_block_rsv,
3925 bytes, BTRFS_RESERVE_NO_FLUSH);
3927 trans->chunk_bytes_reserved += bytes;
3932 * Reserve space in the system space for allocating or removing a chunk.
3933 * The caller must be holding fs_info->chunk_mutex.
3935 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3937 struct btrfs_fs_info *fs_info = trans->fs_info;
3938 const u64 num_devs = get_profile_num_devs(fs_info, type);
3941 /* num_devs device items to update and 1 chunk item to add or remove. */
3942 bytes = btrfs_calc_metadata_size(fs_info, num_devs) +
3943 btrfs_calc_insert_metadata_size(fs_info, 1);
3945 reserve_chunk_space(trans, bytes, type);
3949 * Reserve space in the system space, if needed, for doing a modification to the
3952 * @trans: A transaction handle.
3953 * @is_item_insertion: Indicate if the modification is for inserting a new item
3954 * in the chunk btree or if it's for the deletion or update
3955 * of an existing item.
3957 * This is used in a context where we need to update the chunk btree outside
3958 * block group allocation and removal, to avoid a deadlock with a concurrent
3959 * task that is allocating a metadata or data block group and therefore needs to
3960 * update the chunk btree while holding the chunk mutex. After the update to the
3961 * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called.
3964 void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans,
3965 bool is_item_insertion)
3967 struct btrfs_fs_info *fs_info = trans->fs_info;
3970 if (is_item_insertion)
3971 bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
3973 bytes = btrfs_calc_metadata_size(fs_info, 1);
3975 mutex_lock(&fs_info->chunk_mutex);
3976 reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM);
3977 mutex_unlock(&fs_info->chunk_mutex);
3980 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3982 struct btrfs_block_group *block_group;
3986 struct inode *inode;
3988 block_group = btrfs_lookup_first_block_group(info, last);
3989 while (block_group) {
3990 btrfs_wait_block_group_cache_done(block_group);
3991 spin_lock(&block_group->lock);
3992 if (block_group->iref)
3994 spin_unlock(&block_group->lock);
3995 block_group = btrfs_next_block_group(block_group);
4004 inode = block_group->inode;
4005 block_group->iref = 0;
4006 block_group->inode = NULL;
4007 spin_unlock(&block_group->lock);
4008 ASSERT(block_group->io_ctl.inode == NULL);
4010 last = block_group->start + block_group->length;
4011 btrfs_put_block_group(block_group);
4016 * Must be called only after stopping all workers, since we could have block
4017 * group caching kthreads running, and therefore they could race with us if we
4018 * freed the block groups before stopping them.
4020 int btrfs_free_block_groups(struct btrfs_fs_info *info)
4022 struct btrfs_block_group *block_group;
4023 struct btrfs_space_info *space_info;
4024 struct btrfs_caching_control *caching_ctl;
4027 write_lock(&info->block_group_cache_lock);
4028 while (!list_empty(&info->caching_block_groups)) {
4029 caching_ctl = list_entry(info->caching_block_groups.next,
4030 struct btrfs_caching_control, list);
4031 list_del(&caching_ctl->list);
4032 btrfs_put_caching_control(caching_ctl);
4034 write_unlock(&info->block_group_cache_lock);
4036 spin_lock(&info->unused_bgs_lock);
4037 while (!list_empty(&info->unused_bgs)) {
4038 block_group = list_first_entry(&info->unused_bgs,
4039 struct btrfs_block_group,
4041 list_del_init(&block_group->bg_list);
4042 btrfs_put_block_group(block_group);
4045 while (!list_empty(&info->reclaim_bgs)) {
4046 block_group = list_first_entry(&info->reclaim_bgs,
4047 struct btrfs_block_group,
4049 list_del_init(&block_group->bg_list);
4050 btrfs_put_block_group(block_group);
4052 spin_unlock(&info->unused_bgs_lock);
4054 spin_lock(&info->zone_active_bgs_lock);
4055 while (!list_empty(&info->zone_active_bgs)) {
4056 block_group = list_first_entry(&info->zone_active_bgs,
4057 struct btrfs_block_group,
4059 list_del_init(&block_group->active_bg_list);
4060 btrfs_put_block_group(block_group);
4062 spin_unlock(&info->zone_active_bgs_lock);
4064 write_lock(&info->block_group_cache_lock);
4065 while ((n = rb_last(&info->block_group_cache_tree.rb_root)) != NULL) {
4066 block_group = rb_entry(n, struct btrfs_block_group,
4068 rb_erase_cached(&block_group->cache_node,
4069 &info->block_group_cache_tree);
4070 RB_CLEAR_NODE(&block_group->cache_node);
4071 write_unlock(&info->block_group_cache_lock);
4073 down_write(&block_group->space_info->groups_sem);
4074 list_del(&block_group->list);
4075 up_write(&block_group->space_info->groups_sem);
4078 * We haven't cached this block group, which means we could
4079 * possibly have excluded extents on this block group.
4081 if (block_group->cached == BTRFS_CACHE_NO ||
4082 block_group->cached == BTRFS_CACHE_ERROR)
4083 btrfs_free_excluded_extents(block_group);
4085 btrfs_remove_free_space_cache(block_group);
4086 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
4087 ASSERT(list_empty(&block_group->dirty_list));
4088 ASSERT(list_empty(&block_group->io_list));
4089 ASSERT(list_empty(&block_group->bg_list));
4090 ASSERT(refcount_read(&block_group->refs) == 1);
4091 ASSERT(block_group->swap_extents == 0);
4092 btrfs_put_block_group(block_group);
4094 write_lock(&info->block_group_cache_lock);
4096 write_unlock(&info->block_group_cache_lock);
4098 btrfs_release_global_block_rsv(info);
4100 while (!list_empty(&info->space_info)) {
4101 space_info = list_entry(info->space_info.next,
4102 struct btrfs_space_info,
4106 * Do not hide this behind enospc_debug, this is actually
4107 * important and indicates a real bug if this happens.
4109 if (WARN_ON(space_info->bytes_pinned > 0 ||
4110 space_info->bytes_may_use > 0))
4111 btrfs_dump_space_info(info, space_info, 0, 0);
4114 * If there was a failure to cleanup a log tree, very likely due
4115 * to an IO failure on a writeback attempt of one or more of its
4116 * extent buffers, we could not do proper (and cheap) unaccounting
4117 * of their reserved space, so don't warn on bytes_reserved > 0 in
4120 if (!(space_info->flags & BTRFS_BLOCK_GROUP_METADATA) ||
4121 !BTRFS_FS_LOG_CLEANUP_ERROR(info)) {
4122 if (WARN_ON(space_info->bytes_reserved > 0))
4123 btrfs_dump_space_info(info, space_info, 0, 0);
4126 WARN_ON(space_info->reclaim_size > 0);
4127 list_del(&space_info->list);
4128 btrfs_sysfs_remove_space_info(space_info);
4133 void btrfs_freeze_block_group(struct btrfs_block_group *cache)
4135 atomic_inc(&cache->frozen);
4138 void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
4140 struct btrfs_fs_info *fs_info = block_group->fs_info;
4141 struct extent_map_tree *em_tree;
4142 struct extent_map *em;
4145 spin_lock(&block_group->lock);
4146 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
4147 block_group->removed);
4148 spin_unlock(&block_group->lock);
4151 em_tree = &fs_info->mapping_tree;
4152 write_lock(&em_tree->lock);
4153 em = lookup_extent_mapping(em_tree, block_group->start,
4155 BUG_ON(!em); /* logic error, can't happen */
4156 remove_extent_mapping(em_tree, em);
4157 write_unlock(&em_tree->lock);
4159 /* once for us and once for the tree */
4160 free_extent_map(em);
4161 free_extent_map(em);
4164 * We may have left one free space entry and other possible
4165 * tasks trimming this block group have left 1 entry each one.
4168 __btrfs_remove_free_space_cache(block_group->free_space_ctl);
4172 bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
4176 spin_lock(&bg->lock);
4181 spin_unlock(&bg->lock);
4186 void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
4188 spin_lock(&bg->lock);
4190 ASSERT(bg->swap_extents >= amount);
4191 bg->swap_extents -= amount;
4192 spin_unlock(&bg->lock);