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);
127 WARN_ON(cache->reserved > 0);
130 * A block_group shouldn't be on the discard_list anymore.
131 * Remove the block_group from the discard_list to prevent us
132 * from causing a panic due to NULL pointer dereference.
134 if (WARN_ON(!list_empty(&cache->discard_list)))
135 btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
139 * If not empty, someone is still holding mutex of
140 * full_stripe_lock, which can only be released by caller.
141 * And it will definitely cause use-after-free when caller
142 * tries to release full stripe lock.
144 * No better way to resolve, but only to warn.
146 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
147 kfree(cache->free_space_ctl);
148 kfree(cache->physical_map);
154 * This adds the block group to the fs_info rb tree for the block group cache
156 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
157 struct btrfs_block_group *block_group)
160 struct rb_node *parent = NULL;
161 struct btrfs_block_group *cache;
163 ASSERT(block_group->length != 0);
165 spin_lock(&info->block_group_cache_lock);
166 p = &info->block_group_cache_tree.rb_node;
170 cache = rb_entry(parent, struct btrfs_block_group, cache_node);
171 if (block_group->start < cache->start) {
173 } else if (block_group->start > cache->start) {
176 spin_unlock(&info->block_group_cache_lock);
181 rb_link_node(&block_group->cache_node, parent, p);
182 rb_insert_color(&block_group->cache_node,
183 &info->block_group_cache_tree);
185 if (info->first_logical_byte > block_group->start)
186 info->first_logical_byte = block_group->start;
188 spin_unlock(&info->block_group_cache_lock);
194 * This will return the block group at or after bytenr if contains is 0, else
195 * it will return the block group that contains the bytenr
197 static struct btrfs_block_group *block_group_cache_tree_search(
198 struct btrfs_fs_info *info, u64 bytenr, int contains)
200 struct btrfs_block_group *cache, *ret = NULL;
204 spin_lock(&info->block_group_cache_lock);
205 n = info->block_group_cache_tree.rb_node;
208 cache = rb_entry(n, struct btrfs_block_group, cache_node);
209 end = cache->start + cache->length - 1;
210 start = cache->start;
212 if (bytenr < start) {
213 if (!contains && (!ret || start < ret->start))
216 } else if (bytenr > start) {
217 if (contains && bytenr <= end) {
228 btrfs_get_block_group(ret);
229 if (bytenr == 0 && info->first_logical_byte > ret->start)
230 info->first_logical_byte = ret->start;
232 spin_unlock(&info->block_group_cache_lock);
238 * Return the block group that starts at or after bytenr
240 struct btrfs_block_group *btrfs_lookup_first_block_group(
241 struct btrfs_fs_info *info, u64 bytenr)
243 return block_group_cache_tree_search(info, bytenr, 0);
247 * Return the block group that contains the given bytenr
249 struct btrfs_block_group *btrfs_lookup_block_group(
250 struct btrfs_fs_info *info, u64 bytenr)
252 return block_group_cache_tree_search(info, bytenr, 1);
255 struct btrfs_block_group *btrfs_next_block_group(
256 struct btrfs_block_group *cache)
258 struct btrfs_fs_info *fs_info = cache->fs_info;
259 struct rb_node *node;
261 spin_lock(&fs_info->block_group_cache_lock);
263 /* If our block group was removed, we need a full search. */
264 if (RB_EMPTY_NODE(&cache->cache_node)) {
265 const u64 next_bytenr = cache->start + cache->length;
267 spin_unlock(&fs_info->block_group_cache_lock);
268 btrfs_put_block_group(cache);
269 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
271 node = rb_next(&cache->cache_node);
272 btrfs_put_block_group(cache);
274 cache = rb_entry(node, struct btrfs_block_group, cache_node);
275 btrfs_get_block_group(cache);
278 spin_unlock(&fs_info->block_group_cache_lock);
282 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
284 struct btrfs_block_group *bg;
287 bg = btrfs_lookup_block_group(fs_info, bytenr);
291 spin_lock(&bg->lock);
295 atomic_inc(&bg->nocow_writers);
296 spin_unlock(&bg->lock);
298 /* No put on block group, done by btrfs_dec_nocow_writers */
300 btrfs_put_block_group(bg);
305 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
307 struct btrfs_block_group *bg;
309 bg = btrfs_lookup_block_group(fs_info, bytenr);
311 if (atomic_dec_and_test(&bg->nocow_writers))
312 wake_up_var(&bg->nocow_writers);
314 * Once for our lookup and once for the lookup done by a previous call
315 * to btrfs_inc_nocow_writers()
317 btrfs_put_block_group(bg);
318 btrfs_put_block_group(bg);
321 void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
323 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
326 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
329 struct btrfs_block_group *bg;
331 bg = btrfs_lookup_block_group(fs_info, start);
333 if (atomic_dec_and_test(&bg->reservations))
334 wake_up_var(&bg->reservations);
335 btrfs_put_block_group(bg);
338 void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
340 struct btrfs_space_info *space_info = bg->space_info;
344 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
348 * Our block group is read only but before we set it to read only,
349 * some task might have had allocated an extent from it already, but it
350 * has not yet created a respective ordered extent (and added it to a
351 * root's list of ordered extents).
352 * Therefore wait for any task currently allocating extents, since the
353 * block group's reservations counter is incremented while a read lock
354 * on the groups' semaphore is held and decremented after releasing
355 * the read access on that semaphore and creating the ordered extent.
357 down_write(&space_info->groups_sem);
358 up_write(&space_info->groups_sem);
360 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
363 struct btrfs_caching_control *btrfs_get_caching_control(
364 struct btrfs_block_group *cache)
366 struct btrfs_caching_control *ctl;
368 spin_lock(&cache->lock);
369 if (!cache->caching_ctl) {
370 spin_unlock(&cache->lock);
374 ctl = cache->caching_ctl;
375 refcount_inc(&ctl->count);
376 spin_unlock(&cache->lock);
380 void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
382 if (refcount_dec_and_test(&ctl->count))
387 * When we wait for progress in the block group caching, its because our
388 * allocation attempt failed at least once. So, we must sleep and let some
389 * progress happen before we try again.
391 * This function will sleep at least once waiting for new free space to show
392 * up, and then it will check the block group free space numbers for our min
393 * num_bytes. Another option is to have it go ahead and look in the rbtree for
394 * a free extent of a given size, but this is a good start.
396 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
397 * any of the information in this block group.
399 void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
402 struct btrfs_caching_control *caching_ctl;
404 caching_ctl = btrfs_get_caching_control(cache);
408 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
409 (cache->free_space_ctl->free_space >= num_bytes));
411 btrfs_put_caching_control(caching_ctl);
414 int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
416 struct btrfs_caching_control *caching_ctl;
419 caching_ctl = btrfs_get_caching_control(cache);
421 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
423 wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
424 if (cache->cached == BTRFS_CACHE_ERROR)
426 btrfs_put_caching_control(caching_ctl);
430 static bool space_cache_v1_done(struct btrfs_block_group *cache)
434 spin_lock(&cache->lock);
435 ret = cache->cached != BTRFS_CACHE_FAST;
436 spin_unlock(&cache->lock);
441 void btrfs_wait_space_cache_v1_finished(struct btrfs_block_group *cache,
442 struct btrfs_caching_control *caching_ctl)
444 wait_event(caching_ctl->wait, space_cache_v1_done(cache));
447 #ifdef CONFIG_BTRFS_DEBUG
448 static void fragment_free_space(struct btrfs_block_group *block_group)
450 struct btrfs_fs_info *fs_info = block_group->fs_info;
451 u64 start = block_group->start;
452 u64 len = block_group->length;
453 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
454 fs_info->nodesize : fs_info->sectorsize;
455 u64 step = chunk << 1;
457 while (len > chunk) {
458 btrfs_remove_free_space(block_group, start, chunk);
469 * This is only called by btrfs_cache_block_group, since we could have freed
470 * extents we need to check the pinned_extents for any extents that can't be
471 * used yet since their free space will be released as soon as the transaction
474 u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
476 struct btrfs_fs_info *info = block_group->fs_info;
477 u64 extent_start, extent_end, size, total_added = 0;
480 while (start < end) {
481 ret = find_first_extent_bit(&info->excluded_extents, start,
482 &extent_start, &extent_end,
483 EXTENT_DIRTY | EXTENT_UPTODATE,
488 if (extent_start <= start) {
489 start = extent_end + 1;
490 } else if (extent_start > start && extent_start < end) {
491 size = extent_start - start;
493 ret = btrfs_add_free_space_async_trimmed(block_group,
495 BUG_ON(ret); /* -ENOMEM or logic error */
496 start = extent_end + 1;
505 ret = btrfs_add_free_space_async_trimmed(block_group, start,
507 BUG_ON(ret); /* -ENOMEM or logic error */
513 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
515 struct btrfs_block_group *block_group = caching_ctl->block_group;
516 struct btrfs_fs_info *fs_info = block_group->fs_info;
517 struct btrfs_root *extent_root = fs_info->extent_root;
518 struct btrfs_path *path;
519 struct extent_buffer *leaf;
520 struct btrfs_key key;
527 path = btrfs_alloc_path();
531 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
533 #ifdef CONFIG_BTRFS_DEBUG
535 * If we're fragmenting we don't want to make anybody think we can
536 * allocate from this block group until we've had a chance to fragment
539 if (btrfs_should_fragment_free_space(block_group))
543 * We don't want to deadlock with somebody trying to allocate a new
544 * extent for the extent root while also trying to search the extent
545 * root to add free space. So we skip locking and search the commit
546 * root, since its read-only
548 path->skip_locking = 1;
549 path->search_commit_root = 1;
550 path->reada = READA_FORWARD;
554 key.type = BTRFS_EXTENT_ITEM_KEY;
557 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
561 leaf = path->nodes[0];
562 nritems = btrfs_header_nritems(leaf);
565 if (btrfs_fs_closing(fs_info) > 1) {
570 if (path->slots[0] < nritems) {
571 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
573 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
577 if (need_resched() ||
578 rwsem_is_contended(&fs_info->commit_root_sem)) {
580 caching_ctl->progress = last;
581 btrfs_release_path(path);
582 up_read(&fs_info->commit_root_sem);
583 mutex_unlock(&caching_ctl->mutex);
585 mutex_lock(&caching_ctl->mutex);
586 down_read(&fs_info->commit_root_sem);
590 ret = btrfs_next_leaf(extent_root, path);
595 leaf = path->nodes[0];
596 nritems = btrfs_header_nritems(leaf);
600 if (key.objectid < last) {
603 key.type = BTRFS_EXTENT_ITEM_KEY;
606 caching_ctl->progress = last;
607 btrfs_release_path(path);
611 if (key.objectid < block_group->start) {
616 if (key.objectid >= block_group->start + block_group->length)
619 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
620 key.type == BTRFS_METADATA_ITEM_KEY) {
621 total_found += add_new_free_space(block_group, last,
623 if (key.type == BTRFS_METADATA_ITEM_KEY)
624 last = key.objectid +
627 last = key.objectid + key.offset;
629 if (total_found > CACHING_CTL_WAKE_UP) {
632 wake_up(&caching_ctl->wait);
639 total_found += add_new_free_space(block_group, last,
640 block_group->start + block_group->length);
641 caching_ctl->progress = (u64)-1;
644 btrfs_free_path(path);
648 static noinline void caching_thread(struct btrfs_work *work)
650 struct btrfs_block_group *block_group;
651 struct btrfs_fs_info *fs_info;
652 struct btrfs_caching_control *caching_ctl;
655 caching_ctl = container_of(work, struct btrfs_caching_control, work);
656 block_group = caching_ctl->block_group;
657 fs_info = block_group->fs_info;
659 mutex_lock(&caching_ctl->mutex);
660 down_read(&fs_info->commit_root_sem);
662 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
663 ret = load_free_space_cache(block_group);
670 * We failed to load the space cache, set ourselves to
671 * CACHE_STARTED and carry on.
673 spin_lock(&block_group->lock);
674 block_group->cached = BTRFS_CACHE_STARTED;
675 spin_unlock(&block_group->lock);
676 wake_up(&caching_ctl->wait);
680 * If we are in the transaction that populated the free space tree we
681 * can't actually cache from the free space tree as our commit root and
682 * real root are the same, so we could change the contents of the blocks
683 * while caching. Instead do the slow caching in this case, and after
684 * the transaction has committed we will be safe.
686 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
687 !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
688 ret = load_free_space_tree(caching_ctl);
690 ret = load_extent_tree_free(caching_ctl);
692 spin_lock(&block_group->lock);
693 block_group->caching_ctl = NULL;
694 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
695 spin_unlock(&block_group->lock);
697 #ifdef CONFIG_BTRFS_DEBUG
698 if (btrfs_should_fragment_free_space(block_group)) {
701 spin_lock(&block_group->space_info->lock);
702 spin_lock(&block_group->lock);
703 bytes_used = block_group->length - block_group->used;
704 block_group->space_info->bytes_used += bytes_used >> 1;
705 spin_unlock(&block_group->lock);
706 spin_unlock(&block_group->space_info->lock);
707 fragment_free_space(block_group);
711 caching_ctl->progress = (u64)-1;
713 up_read(&fs_info->commit_root_sem);
714 btrfs_free_excluded_extents(block_group);
715 mutex_unlock(&caching_ctl->mutex);
717 wake_up(&caching_ctl->wait);
719 btrfs_put_caching_control(caching_ctl);
720 btrfs_put_block_group(block_group);
723 int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
726 struct btrfs_fs_info *fs_info = cache->fs_info;
727 struct btrfs_caching_control *caching_ctl = NULL;
730 /* Allocator for zoned filesystems does not use the cache at all */
731 if (btrfs_is_zoned(fs_info))
734 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
738 INIT_LIST_HEAD(&caching_ctl->list);
739 mutex_init(&caching_ctl->mutex);
740 init_waitqueue_head(&caching_ctl->wait);
741 caching_ctl->block_group = cache;
742 caching_ctl->progress = cache->start;
743 refcount_set(&caching_ctl->count, 2);
744 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
746 spin_lock(&cache->lock);
747 if (cache->cached != BTRFS_CACHE_NO) {
750 caching_ctl = cache->caching_ctl;
752 refcount_inc(&caching_ctl->count);
753 spin_unlock(&cache->lock);
756 WARN_ON(cache->caching_ctl);
757 cache->caching_ctl = caching_ctl;
758 if (btrfs_test_opt(fs_info, SPACE_CACHE))
759 cache->cached = BTRFS_CACHE_FAST;
761 cache->cached = BTRFS_CACHE_STARTED;
762 cache->has_caching_ctl = 1;
763 spin_unlock(&cache->lock);
765 spin_lock(&fs_info->block_group_cache_lock);
766 refcount_inc(&caching_ctl->count);
767 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
768 spin_unlock(&fs_info->block_group_cache_lock);
770 btrfs_get_block_group(cache);
772 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
774 if (load_cache_only && caching_ctl)
775 btrfs_wait_space_cache_v1_finished(cache, caching_ctl);
777 btrfs_put_caching_control(caching_ctl);
782 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
784 u64 extra_flags = chunk_to_extended(flags) &
785 BTRFS_EXTENDED_PROFILE_MASK;
787 write_seqlock(&fs_info->profiles_lock);
788 if (flags & BTRFS_BLOCK_GROUP_DATA)
789 fs_info->avail_data_alloc_bits &= ~extra_flags;
790 if (flags & BTRFS_BLOCK_GROUP_METADATA)
791 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
792 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
793 fs_info->avail_system_alloc_bits &= ~extra_flags;
794 write_sequnlock(&fs_info->profiles_lock);
798 * Clear incompat bits for the following feature(s):
800 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
801 * in the whole filesystem
803 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
805 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
807 bool found_raid56 = false;
808 bool found_raid1c34 = false;
810 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
811 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
812 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
813 struct list_head *head = &fs_info->space_info;
814 struct btrfs_space_info *sinfo;
816 list_for_each_entry_rcu(sinfo, head, list) {
817 down_read(&sinfo->groups_sem);
818 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
820 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
822 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
823 found_raid1c34 = true;
824 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
825 found_raid1c34 = true;
826 up_read(&sinfo->groups_sem);
829 btrfs_clear_fs_incompat(fs_info, RAID56);
831 btrfs_clear_fs_incompat(fs_info, RAID1C34);
835 static int remove_block_group_item(struct btrfs_trans_handle *trans,
836 struct btrfs_path *path,
837 struct btrfs_block_group *block_group)
839 struct btrfs_fs_info *fs_info = trans->fs_info;
840 struct btrfs_root *root;
841 struct btrfs_key key;
844 root = fs_info->extent_root;
845 key.objectid = block_group->start;
846 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
847 key.offset = block_group->length;
849 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
855 ret = btrfs_del_item(trans, root, path);
859 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
860 u64 group_start, struct extent_map *em)
862 struct btrfs_fs_info *fs_info = trans->fs_info;
863 struct btrfs_path *path;
864 struct btrfs_block_group *block_group;
865 struct btrfs_free_cluster *cluster;
867 struct kobject *kobj = NULL;
871 struct btrfs_caching_control *caching_ctl = NULL;
873 bool remove_rsv = false;
875 block_group = btrfs_lookup_block_group(fs_info, group_start);
876 BUG_ON(!block_group);
877 BUG_ON(!block_group->ro);
879 trace_btrfs_remove_block_group(block_group);
881 * Free the reserved super bytes from this block group before
884 btrfs_free_excluded_extents(block_group);
885 btrfs_free_ref_tree_range(fs_info, block_group->start,
886 block_group->length);
888 index = btrfs_bg_flags_to_raid_index(block_group->flags);
889 factor = btrfs_bg_type_to_factor(block_group->flags);
891 /* make sure this block group isn't part of an allocation cluster */
892 cluster = &fs_info->data_alloc_cluster;
893 spin_lock(&cluster->refill_lock);
894 btrfs_return_cluster_to_free_space(block_group, cluster);
895 spin_unlock(&cluster->refill_lock);
898 * make sure this block group isn't part of a metadata
901 cluster = &fs_info->meta_alloc_cluster;
902 spin_lock(&cluster->refill_lock);
903 btrfs_return_cluster_to_free_space(block_group, cluster);
904 spin_unlock(&cluster->refill_lock);
906 btrfs_clear_treelog_bg(block_group);
907 btrfs_clear_data_reloc_bg(block_group);
909 path = btrfs_alloc_path();
916 * get the inode first so any iput calls done for the io_list
917 * aren't the final iput (no unlinks allowed now)
919 inode = lookup_free_space_inode(block_group, path);
921 mutex_lock(&trans->transaction->cache_write_mutex);
923 * Make sure our free space cache IO is done before removing the
926 spin_lock(&trans->transaction->dirty_bgs_lock);
927 if (!list_empty(&block_group->io_list)) {
928 list_del_init(&block_group->io_list);
930 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
932 spin_unlock(&trans->transaction->dirty_bgs_lock);
933 btrfs_wait_cache_io(trans, block_group, path);
934 btrfs_put_block_group(block_group);
935 spin_lock(&trans->transaction->dirty_bgs_lock);
938 if (!list_empty(&block_group->dirty_list)) {
939 list_del_init(&block_group->dirty_list);
941 btrfs_put_block_group(block_group);
943 spin_unlock(&trans->transaction->dirty_bgs_lock);
944 mutex_unlock(&trans->transaction->cache_write_mutex);
946 ret = btrfs_remove_free_space_inode(trans, inode, block_group);
950 spin_lock(&fs_info->block_group_cache_lock);
951 rb_erase(&block_group->cache_node,
952 &fs_info->block_group_cache_tree);
953 RB_CLEAR_NODE(&block_group->cache_node);
955 /* Once for the block groups rbtree */
956 btrfs_put_block_group(block_group);
958 if (fs_info->first_logical_byte == block_group->start)
959 fs_info->first_logical_byte = (u64)-1;
960 spin_unlock(&fs_info->block_group_cache_lock);
962 down_write(&block_group->space_info->groups_sem);
964 * we must use list_del_init so people can check to see if they
965 * are still on the list after taking the semaphore
967 list_del_init(&block_group->list);
968 if (list_empty(&block_group->space_info->block_groups[index])) {
969 kobj = block_group->space_info->block_group_kobjs[index];
970 block_group->space_info->block_group_kobjs[index] = NULL;
971 clear_avail_alloc_bits(fs_info, block_group->flags);
973 up_write(&block_group->space_info->groups_sem);
974 clear_incompat_bg_bits(fs_info, block_group->flags);
980 if (block_group->has_caching_ctl)
981 caching_ctl = btrfs_get_caching_control(block_group);
982 if (block_group->cached == BTRFS_CACHE_STARTED)
983 btrfs_wait_block_group_cache_done(block_group);
984 if (block_group->has_caching_ctl) {
985 spin_lock(&fs_info->block_group_cache_lock);
987 struct btrfs_caching_control *ctl;
989 list_for_each_entry(ctl,
990 &fs_info->caching_block_groups, list)
991 if (ctl->block_group == block_group) {
993 refcount_inc(&caching_ctl->count);
998 list_del_init(&caching_ctl->list);
999 spin_unlock(&fs_info->block_group_cache_lock);
1001 /* Once for the caching bgs list and once for us. */
1002 btrfs_put_caching_control(caching_ctl);
1003 btrfs_put_caching_control(caching_ctl);
1007 spin_lock(&trans->transaction->dirty_bgs_lock);
1008 WARN_ON(!list_empty(&block_group->dirty_list));
1009 WARN_ON(!list_empty(&block_group->io_list));
1010 spin_unlock(&trans->transaction->dirty_bgs_lock);
1012 btrfs_remove_free_space_cache(block_group);
1014 spin_lock(&block_group->space_info->lock);
1015 list_del_init(&block_group->ro_list);
1017 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1018 WARN_ON(block_group->space_info->total_bytes
1019 < block_group->length);
1020 WARN_ON(block_group->space_info->bytes_readonly
1021 < block_group->length - block_group->zone_unusable);
1022 WARN_ON(block_group->space_info->bytes_zone_unusable
1023 < block_group->zone_unusable);
1024 WARN_ON(block_group->space_info->disk_total
1025 < block_group->length * factor);
1027 block_group->space_info->total_bytes -= block_group->length;
1028 block_group->space_info->bytes_readonly -=
1029 (block_group->length - block_group->zone_unusable);
1030 block_group->space_info->bytes_zone_unusable -=
1031 block_group->zone_unusable;
1032 block_group->space_info->disk_total -= block_group->length * factor;
1034 spin_unlock(&block_group->space_info->lock);
1037 * Remove the free space for the block group from the free space tree
1038 * and the block group's item from the extent tree before marking the
1039 * block group as removed. This is to prevent races with tasks that
1040 * freeze and unfreeze a block group, this task and another task
1041 * allocating a new block group - the unfreeze task ends up removing
1042 * the block group's extent map before the task calling this function
1043 * deletes the block group item from the extent tree, allowing for
1044 * another task to attempt to create another block group with the same
1045 * item key (and failing with -EEXIST and a transaction abort).
1047 ret = remove_block_group_free_space(trans, block_group);
1051 ret = remove_block_group_item(trans, path, block_group);
1055 spin_lock(&block_group->lock);
1056 block_group->removed = 1;
1058 * At this point trimming or scrub can't start on this block group,
1059 * because we removed the block group from the rbtree
1060 * fs_info->block_group_cache_tree so no one can't find it anymore and
1061 * even if someone already got this block group before we removed it
1062 * from the rbtree, they have already incremented block_group->frozen -
1063 * if they didn't, for the trimming case they won't find any free space
1064 * entries because we already removed them all when we called
1065 * btrfs_remove_free_space_cache().
1067 * And we must not remove the extent map from the fs_info->mapping_tree
1068 * to prevent the same logical address range and physical device space
1069 * ranges from being reused for a new block group. This is needed to
1070 * avoid races with trimming and scrub.
1072 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1073 * completely transactionless, so while it is trimming a range the
1074 * currently running transaction might finish and a new one start,
1075 * allowing for new block groups to be created that can reuse the same
1076 * physical device locations unless we take this special care.
1078 * There may also be an implicit trim operation if the file system
1079 * is mounted with -odiscard. The same protections must remain
1080 * in place until the extents have been discarded completely when
1081 * the transaction commit has completed.
1083 remove_em = (atomic_read(&block_group->frozen) == 0);
1084 spin_unlock(&block_group->lock);
1087 struct extent_map_tree *em_tree;
1089 em_tree = &fs_info->mapping_tree;
1090 write_lock(&em_tree->lock);
1091 remove_extent_mapping(em_tree, em);
1092 write_unlock(&em_tree->lock);
1093 /* once for the tree */
1094 free_extent_map(em);
1098 /* Once for the lookup reference */
1099 btrfs_put_block_group(block_group);
1101 btrfs_delayed_refs_rsv_release(fs_info, 1);
1102 btrfs_free_path(path);
1106 struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1107 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1109 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1110 struct extent_map *em;
1111 struct map_lookup *map;
1112 unsigned int num_items;
1114 read_lock(&em_tree->lock);
1115 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1116 read_unlock(&em_tree->lock);
1117 ASSERT(em && em->start == chunk_offset);
1120 * We need to reserve 3 + N units from the metadata space info in order
1121 * to remove a block group (done at btrfs_remove_chunk() and at
1122 * btrfs_remove_block_group()), which are used for:
1124 * 1 unit for adding the free space inode's orphan (located in the tree
1126 * 1 unit for deleting the block group item (located in the extent
1128 * 1 unit for deleting the free space item (located in tree of tree
1130 * N units for deleting N device extent items corresponding to each
1131 * stripe (located in the device tree).
1133 * In order to remove a block group we also need to reserve units in the
1134 * system space info in order to update the chunk tree (update one or
1135 * more device items and remove one chunk item), but this is done at
1136 * btrfs_remove_chunk() through a call to check_system_chunk().
1138 map = em->map_lookup;
1139 num_items = 3 + map->num_stripes;
1140 free_extent_map(em);
1142 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
1147 * Mark block group @cache read-only, so later write won't happen to block
1150 * If @force is not set, this function will only mark the block group readonly
1151 * if we have enough free space (1M) in other metadata/system block groups.
1152 * If @force is not set, this function will mark the block group readonly
1153 * without checking free space.
1155 * NOTE: This function doesn't care if other block groups can contain all the
1156 * data in this block group. That check should be done by relocation routine,
1157 * not this function.
1159 static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
1161 struct btrfs_space_info *sinfo = cache->space_info;
1165 spin_lock(&sinfo->lock);
1166 spin_lock(&cache->lock);
1168 if (cache->swap_extents) {
1179 num_bytes = cache->length - cache->reserved - cache->pinned -
1180 cache->bytes_super - cache->zone_unusable - cache->used;
1183 * Data never overcommits, even in mixed mode, so do just the straight
1184 * check of left over space in how much we have allocated.
1188 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1189 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1192 * Here we make sure if we mark this bg RO, we still have enough
1193 * free space as buffer.
1195 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1199 * We overcommit metadata, so we need to do the
1200 * btrfs_can_overcommit check here, and we need to pass in
1201 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1202 * leeway to allow us to mark this block group as read only.
1204 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1205 BTRFS_RESERVE_NO_FLUSH))
1210 sinfo->bytes_readonly += num_bytes;
1211 if (btrfs_is_zoned(cache->fs_info)) {
1212 /* Migrate zone_unusable bytes to readonly */
1213 sinfo->bytes_readonly += cache->zone_unusable;
1214 sinfo->bytes_zone_unusable -= cache->zone_unusable;
1215 cache->zone_unusable = 0;
1218 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
1221 spin_unlock(&cache->lock);
1222 spin_unlock(&sinfo->lock);
1223 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1224 btrfs_info(cache->fs_info,
1225 "unable to make block group %llu ro", cache->start);
1226 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1231 static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1232 struct btrfs_block_group *bg)
1234 struct btrfs_fs_info *fs_info = bg->fs_info;
1235 struct btrfs_transaction *prev_trans = NULL;
1236 const u64 start = bg->start;
1237 const u64 end = start + bg->length - 1;
1240 spin_lock(&fs_info->trans_lock);
1241 if (trans->transaction->list.prev != &fs_info->trans_list) {
1242 prev_trans = list_last_entry(&trans->transaction->list,
1243 struct btrfs_transaction, list);
1244 refcount_inc(&prev_trans->use_count);
1246 spin_unlock(&fs_info->trans_lock);
1249 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1250 * btrfs_finish_extent_commit(). If we are at transaction N, another
1251 * task might be running finish_extent_commit() for the previous
1252 * transaction N - 1, and have seen a range belonging to the block
1253 * group in pinned_extents before we were able to clear the whole block
1254 * group range from pinned_extents. This means that task can lookup for
1255 * the block group after we unpinned it from pinned_extents and removed
1256 * it, leading to a BUG_ON() at unpin_extent_range().
1258 mutex_lock(&fs_info->unused_bg_unpin_mutex);
1260 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1266 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
1269 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1271 btrfs_put_transaction(prev_trans);
1277 * Process the unused_bgs list and remove any that don't have any allocated
1278 * space inside of them.
1280 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1282 struct btrfs_block_group *block_group;
1283 struct btrfs_space_info *space_info;
1284 struct btrfs_trans_handle *trans;
1285 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1288 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1292 * Long running balances can keep us blocked here for eternity, so
1293 * simply skip deletion if we're unable to get the mutex.
1295 if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
1298 spin_lock(&fs_info->unused_bgs_lock);
1299 while (!list_empty(&fs_info->unused_bgs)) {
1302 block_group = list_first_entry(&fs_info->unused_bgs,
1303 struct btrfs_block_group,
1305 list_del_init(&block_group->bg_list);
1307 space_info = block_group->space_info;
1309 if (ret || btrfs_mixed_space_info(space_info)) {
1310 btrfs_put_block_group(block_group);
1313 spin_unlock(&fs_info->unused_bgs_lock);
1315 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1317 /* Don't want to race with allocators so take the groups_sem */
1318 down_write(&space_info->groups_sem);
1321 * Async discard moves the final block group discard to be prior
1322 * to the unused_bgs code path. Therefore, if it's not fully
1323 * trimmed, punt it back to the async discard lists.
1325 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1326 !btrfs_is_free_space_trimmed(block_group)) {
1327 trace_btrfs_skip_unused_block_group(block_group);
1328 up_write(&space_info->groups_sem);
1329 /* Requeue if we failed because of async discard */
1330 btrfs_discard_queue_work(&fs_info->discard_ctl,
1335 spin_lock(&block_group->lock);
1336 if (block_group->reserved || block_group->pinned ||
1337 block_group->used || block_group->ro ||
1338 list_is_singular(&block_group->list)) {
1340 * We want to bail if we made new allocations or have
1341 * outstanding allocations in this block group. We do
1342 * the ro check in case balance is currently acting on
1345 trace_btrfs_skip_unused_block_group(block_group);
1346 spin_unlock(&block_group->lock);
1347 up_write(&space_info->groups_sem);
1350 spin_unlock(&block_group->lock);
1352 /* We don't want to force the issue, only flip if it's ok. */
1353 ret = inc_block_group_ro(block_group, 0);
1354 up_write(&space_info->groups_sem);
1361 * Want to do this before we do anything else so we can recover
1362 * properly if we fail to join the transaction.
1364 trans = btrfs_start_trans_remove_block_group(fs_info,
1365 block_group->start);
1366 if (IS_ERR(trans)) {
1367 btrfs_dec_block_group_ro(block_group);
1368 ret = PTR_ERR(trans);
1373 * We could have pending pinned extents for this block group,
1374 * just delete them, we don't care about them anymore.
1376 if (!clean_pinned_extents(trans, block_group)) {
1377 btrfs_dec_block_group_ro(block_group);
1382 * At this point, the block_group is read only and should fail
1383 * new allocations. However, btrfs_finish_extent_commit() can
1384 * cause this block_group to be placed back on the discard
1385 * lists because now the block_group isn't fully discarded.
1386 * Bail here and try again later after discarding everything.
1388 spin_lock(&fs_info->discard_ctl.lock);
1389 if (!list_empty(&block_group->discard_list)) {
1390 spin_unlock(&fs_info->discard_ctl.lock);
1391 btrfs_dec_block_group_ro(block_group);
1392 btrfs_discard_queue_work(&fs_info->discard_ctl,
1396 spin_unlock(&fs_info->discard_ctl.lock);
1398 /* Reset pinned so btrfs_put_block_group doesn't complain */
1399 spin_lock(&space_info->lock);
1400 spin_lock(&block_group->lock);
1402 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1403 -block_group->pinned);
1404 space_info->bytes_readonly += block_group->pinned;
1405 block_group->pinned = 0;
1407 spin_unlock(&block_group->lock);
1408 spin_unlock(&space_info->lock);
1411 * The normal path here is an unused block group is passed here,
1412 * then trimming is handled in the transaction commit path.
1413 * Async discard interposes before this to do the trimming
1414 * before coming down the unused block group path as trimming
1415 * will no longer be done later in the transaction commit path.
1417 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1421 * DISCARD can flip during remount. On zoned filesystems, we
1422 * need to reset sequential-required zones.
1424 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) ||
1425 btrfs_is_zoned(fs_info);
1427 /* Implicit trim during transaction commit. */
1429 btrfs_freeze_block_group(block_group);
1432 * Btrfs_remove_chunk will abort the transaction if things go
1435 ret = btrfs_remove_chunk(trans, block_group->start);
1439 btrfs_unfreeze_block_group(block_group);
1444 * If we're not mounted with -odiscard, we can just forget
1445 * about this block group. Otherwise we'll need to wait
1446 * until transaction commit to do the actual discard.
1449 spin_lock(&fs_info->unused_bgs_lock);
1451 * A concurrent scrub might have added us to the list
1452 * fs_info->unused_bgs, so use a list_move operation
1453 * to add the block group to the deleted_bgs list.
1455 list_move(&block_group->bg_list,
1456 &trans->transaction->deleted_bgs);
1457 spin_unlock(&fs_info->unused_bgs_lock);
1458 btrfs_get_block_group(block_group);
1461 btrfs_end_transaction(trans);
1463 btrfs_put_block_group(block_group);
1464 spin_lock(&fs_info->unused_bgs_lock);
1466 spin_unlock(&fs_info->unused_bgs_lock);
1467 mutex_unlock(&fs_info->reclaim_bgs_lock);
1471 btrfs_end_transaction(trans);
1472 mutex_unlock(&fs_info->reclaim_bgs_lock);
1473 btrfs_put_block_group(block_group);
1474 btrfs_discard_punt_unused_bgs_list(fs_info);
1477 void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1479 struct btrfs_fs_info *fs_info = bg->fs_info;
1481 spin_lock(&fs_info->unused_bgs_lock);
1482 if (list_empty(&bg->bg_list)) {
1483 btrfs_get_block_group(bg);
1484 trace_btrfs_add_unused_block_group(bg);
1485 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1487 spin_unlock(&fs_info->unused_bgs_lock);
1491 * We want block groups with a low number of used bytes to be in the beginning
1492 * of the list, so they will get reclaimed first.
1494 static int reclaim_bgs_cmp(void *unused, const struct list_head *a,
1495 const struct list_head *b)
1497 const struct btrfs_block_group *bg1, *bg2;
1499 bg1 = list_entry(a, struct btrfs_block_group, bg_list);
1500 bg2 = list_entry(b, struct btrfs_block_group, bg_list);
1502 return bg1->used > bg2->used;
1505 void btrfs_reclaim_bgs_work(struct work_struct *work)
1507 struct btrfs_fs_info *fs_info =
1508 container_of(work, struct btrfs_fs_info, reclaim_bgs_work);
1509 struct btrfs_block_group *bg;
1510 struct btrfs_space_info *space_info;
1511 LIST_HEAD(again_list);
1513 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1516 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE))
1520 * Long running balances can keep us blocked here for eternity, so
1521 * simply skip reclaim if we're unable to get the mutex.
1523 if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) {
1524 btrfs_exclop_finish(fs_info);
1528 spin_lock(&fs_info->unused_bgs_lock);
1530 * Sort happens under lock because we can't simply splice it and sort.
1531 * The block groups might still be in use and reachable via bg_list,
1532 * and their presence in the reclaim_bgs list must be preserved.
1534 list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp);
1535 while (!list_empty(&fs_info->reclaim_bgs)) {
1539 bg = list_first_entry(&fs_info->reclaim_bgs,
1540 struct btrfs_block_group,
1542 list_del_init(&bg->bg_list);
1544 space_info = bg->space_info;
1545 spin_unlock(&fs_info->unused_bgs_lock);
1547 /* Don't race with allocators so take the groups_sem */
1548 down_write(&space_info->groups_sem);
1550 spin_lock(&bg->lock);
1551 if (bg->reserved || bg->pinned || bg->ro) {
1553 * We want to bail if we made new allocations or have
1554 * outstanding allocations in this block group. We do
1555 * the ro check in case balance is currently acting on
1558 spin_unlock(&bg->lock);
1559 up_write(&space_info->groups_sem);
1562 spin_unlock(&bg->lock);
1564 /* Get out fast, in case we're unmounting the filesystem */
1565 if (btrfs_fs_closing(fs_info)) {
1566 up_write(&space_info->groups_sem);
1571 * Cache the zone_unusable value before turning the block group
1572 * to read only. As soon as the blog group is read only it's
1573 * zone_unusable value gets moved to the block group's read-only
1574 * bytes and isn't available for calculations anymore.
1576 zone_unusable = bg->zone_unusable;
1577 ret = inc_block_group_ro(bg, 0);
1578 up_write(&space_info->groups_sem);
1583 "reclaiming chunk %llu with %llu%% used %llu%% unusable",
1584 bg->start, div_u64(bg->used * 100, bg->length),
1585 div64_u64(zone_unusable * 100, bg->length));
1586 trace_btrfs_reclaim_block_group(bg);
1587 ret = btrfs_relocate_chunk(fs_info, bg->start);
1588 if (ret && ret != -EAGAIN)
1589 btrfs_err(fs_info, "error relocating chunk %llu",
1593 spin_lock(&fs_info->unused_bgs_lock);
1594 if (ret == -EAGAIN && list_empty(&bg->bg_list))
1595 list_add_tail(&bg->bg_list, &again_list);
1597 btrfs_put_block_group(bg);
1599 list_splice_tail(&again_list, &fs_info->reclaim_bgs);
1600 spin_unlock(&fs_info->unused_bgs_lock);
1601 mutex_unlock(&fs_info->reclaim_bgs_lock);
1602 btrfs_exclop_finish(fs_info);
1605 void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
1607 spin_lock(&fs_info->unused_bgs_lock);
1608 if (!list_empty(&fs_info->reclaim_bgs))
1609 queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
1610 spin_unlock(&fs_info->unused_bgs_lock);
1613 void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
1615 struct btrfs_fs_info *fs_info = bg->fs_info;
1617 spin_lock(&fs_info->unused_bgs_lock);
1618 if (list_empty(&bg->bg_list)) {
1619 btrfs_get_block_group(bg);
1620 trace_btrfs_add_reclaim_block_group(bg);
1621 list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
1623 spin_unlock(&fs_info->unused_bgs_lock);
1626 static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1627 struct btrfs_path *path)
1629 struct extent_map_tree *em_tree;
1630 struct extent_map *em;
1631 struct btrfs_block_group_item bg;
1632 struct extent_buffer *leaf;
1637 slot = path->slots[0];
1638 leaf = path->nodes[0];
1640 em_tree = &fs_info->mapping_tree;
1641 read_lock(&em_tree->lock);
1642 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1643 read_unlock(&em_tree->lock);
1646 "logical %llu len %llu found bg but no related chunk",
1647 key->objectid, key->offset);
1651 if (em->start != key->objectid || em->len != key->offset) {
1653 "block group %llu len %llu mismatch with chunk %llu len %llu",
1654 key->objectid, key->offset, em->start, em->len);
1659 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1661 flags = btrfs_stack_block_group_flags(&bg) &
1662 BTRFS_BLOCK_GROUP_TYPE_MASK;
1664 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1666 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1667 key->objectid, key->offset, flags,
1668 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1673 free_extent_map(em);
1677 static int find_first_block_group(struct btrfs_fs_info *fs_info,
1678 struct btrfs_path *path,
1679 struct btrfs_key *key)
1681 struct btrfs_root *root = fs_info->extent_root;
1683 struct btrfs_key found_key;
1684 struct extent_buffer *leaf;
1687 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1692 slot = path->slots[0];
1693 leaf = path->nodes[0];
1694 if (slot >= btrfs_header_nritems(leaf)) {
1695 ret = btrfs_next_leaf(root, path);
1702 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1704 if (found_key.objectid >= key->objectid &&
1705 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1706 ret = read_bg_from_eb(fs_info, &found_key, path);
1716 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1718 u64 extra_flags = chunk_to_extended(flags) &
1719 BTRFS_EXTENDED_PROFILE_MASK;
1721 write_seqlock(&fs_info->profiles_lock);
1722 if (flags & BTRFS_BLOCK_GROUP_DATA)
1723 fs_info->avail_data_alloc_bits |= extra_flags;
1724 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1725 fs_info->avail_metadata_alloc_bits |= extra_flags;
1726 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1727 fs_info->avail_system_alloc_bits |= extra_flags;
1728 write_sequnlock(&fs_info->profiles_lock);
1732 * Map a physical disk address to a list of logical addresses
1734 * @fs_info: the filesystem
1735 * @chunk_start: logical address of block group
1736 * @bdev: physical device to resolve, can be NULL to indicate any device
1737 * @physical: physical address to map to logical addresses
1738 * @logical: return array of logical addresses which map to @physical
1739 * @naddrs: length of @logical
1740 * @stripe_len: size of IO stripe for the given block group
1742 * Maps a particular @physical disk address to a list of @logical addresses.
1743 * Used primarily to exclude those portions of a block group that contain super
1746 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1747 struct block_device *bdev, u64 physical, u64 **logical,
1748 int *naddrs, int *stripe_len)
1750 struct extent_map *em;
1751 struct map_lookup *map;
1754 u64 data_stripe_length;
1759 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1763 map = em->map_lookup;
1764 data_stripe_length = em->orig_block_len;
1765 io_stripe_size = map->stripe_len;
1766 chunk_start = em->start;
1768 /* For RAID5/6 adjust to a full IO stripe length */
1769 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
1770 io_stripe_size = map->stripe_len * nr_data_stripes(map);
1772 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
1778 for (i = 0; i < map->num_stripes; i++) {
1779 bool already_inserted = false;
1784 if (!in_range(physical, map->stripes[i].physical,
1785 data_stripe_length))
1788 if (bdev && map->stripes[i].dev->bdev != bdev)
1791 stripe_nr = physical - map->stripes[i].physical;
1792 stripe_nr = div64_u64_rem(stripe_nr, map->stripe_len, &offset);
1794 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1795 stripe_nr = stripe_nr * map->num_stripes + i;
1796 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1797 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1798 stripe_nr = stripe_nr * map->num_stripes + i;
1801 * The remaining case would be for RAID56, multiply by
1802 * nr_data_stripes(). Alternatively, just use rmap_len below
1803 * instead of map->stripe_len
1806 bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
1808 /* Ensure we don't add duplicate addresses */
1809 for (j = 0; j < nr; j++) {
1810 if (buf[j] == bytenr) {
1811 already_inserted = true;
1816 if (!already_inserted)
1822 *stripe_len = io_stripe_size;
1824 free_extent_map(em);
1828 static int exclude_super_stripes(struct btrfs_block_group *cache)
1830 struct btrfs_fs_info *fs_info = cache->fs_info;
1831 const bool zoned = btrfs_is_zoned(fs_info);
1837 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1838 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
1839 cache->bytes_super += stripe_len;
1840 ret = btrfs_add_excluded_extent(fs_info, cache->start,
1846 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1847 bytenr = btrfs_sb_offset(i);
1848 ret = btrfs_rmap_block(fs_info, cache->start, NULL,
1849 bytenr, &logical, &nr, &stripe_len);
1853 /* Shouldn't have super stripes in sequential zones */
1856 "zoned: block group %llu must not contain super block",
1862 u64 len = min_t(u64, stripe_len,
1863 cache->start + cache->length - logical[nr]);
1865 cache->bytes_super += len;
1866 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
1879 static void link_block_group(struct btrfs_block_group *cache)
1881 struct btrfs_space_info *space_info = cache->space_info;
1882 int index = btrfs_bg_flags_to_raid_index(cache->flags);
1884 down_write(&space_info->groups_sem);
1885 list_add_tail(&cache->list, &space_info->block_groups[index]);
1886 up_write(&space_info->groups_sem);
1889 static struct btrfs_block_group *btrfs_create_block_group_cache(
1890 struct btrfs_fs_info *fs_info, u64 start)
1892 struct btrfs_block_group *cache;
1894 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1898 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1900 if (!cache->free_space_ctl) {
1905 cache->start = start;
1907 cache->fs_info = fs_info;
1908 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
1910 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1912 refcount_set(&cache->refs, 1);
1913 spin_lock_init(&cache->lock);
1914 init_rwsem(&cache->data_rwsem);
1915 INIT_LIST_HEAD(&cache->list);
1916 INIT_LIST_HEAD(&cache->cluster_list);
1917 INIT_LIST_HEAD(&cache->bg_list);
1918 INIT_LIST_HEAD(&cache->ro_list);
1919 INIT_LIST_HEAD(&cache->discard_list);
1920 INIT_LIST_HEAD(&cache->dirty_list);
1921 INIT_LIST_HEAD(&cache->io_list);
1922 INIT_LIST_HEAD(&cache->active_bg_list);
1923 btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
1924 atomic_set(&cache->frozen, 0);
1925 mutex_init(&cache->free_space_lock);
1926 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1932 * Iterate all chunks and verify that each of them has the corresponding block
1935 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1937 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1938 struct extent_map *em;
1939 struct btrfs_block_group *bg;
1944 read_lock(&map_tree->lock);
1946 * lookup_extent_mapping will return the first extent map
1947 * intersecting the range, so setting @len to 1 is enough to
1948 * get the first chunk.
1950 em = lookup_extent_mapping(map_tree, start, 1);
1951 read_unlock(&map_tree->lock);
1955 bg = btrfs_lookup_block_group(fs_info, em->start);
1958 "chunk start=%llu len=%llu doesn't have corresponding block group",
1959 em->start, em->len);
1961 free_extent_map(em);
1964 if (bg->start != em->start || bg->length != em->len ||
1965 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1966 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1968 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
1970 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
1971 bg->start, bg->length,
1972 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
1974 free_extent_map(em);
1975 btrfs_put_block_group(bg);
1978 start = em->start + em->len;
1979 free_extent_map(em);
1980 btrfs_put_block_group(bg);
1985 static int read_one_block_group(struct btrfs_fs_info *info,
1986 struct btrfs_block_group_item *bgi,
1987 const struct btrfs_key *key,
1990 struct btrfs_block_group *cache;
1991 struct btrfs_space_info *space_info;
1992 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
1995 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
1997 cache = btrfs_create_block_group_cache(info, key->objectid);
2001 cache->length = key->offset;
2002 cache->used = btrfs_stack_block_group_used(bgi);
2003 cache->flags = btrfs_stack_block_group_flags(bgi);
2005 set_free_space_tree_thresholds(cache);
2009 * When we mount with old space cache, we need to
2010 * set BTRFS_DC_CLEAR and set dirty flag.
2012 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
2013 * truncate the old free space cache inode and
2015 * b) Setting 'dirty flag' makes sure that we flush
2016 * the new space cache info onto disk.
2018 if (btrfs_test_opt(info, SPACE_CACHE))
2019 cache->disk_cache_state = BTRFS_DC_CLEAR;
2021 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
2022 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
2024 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2030 ret = btrfs_load_block_group_zone_info(cache, false);
2032 btrfs_err(info, "zoned: failed to load zone info of bg %llu",
2038 * We need to exclude the super stripes now so that the space info has
2039 * super bytes accounted for, otherwise we'll think we have more space
2040 * than we actually do.
2042 ret = exclude_super_stripes(cache);
2044 /* We may have excluded something, so call this just in case. */
2045 btrfs_free_excluded_extents(cache);
2050 * For zoned filesystem, space after the allocation offset is the only
2051 * free space for a block group. So, we don't need any caching work.
2052 * btrfs_calc_zone_unusable() will set the amount of free space and
2053 * zone_unusable space.
2055 * For regular filesystem, check for two cases, either we are full, and
2056 * therefore don't need to bother with the caching work since we won't
2057 * find any space, or we are empty, and we can just add all the space
2058 * in and be done with it. This saves us _a_lot_ of time, particularly
2061 if (btrfs_is_zoned(info)) {
2062 btrfs_calc_zone_unusable(cache);
2063 /* Should not have any excluded extents. Just in case, though. */
2064 btrfs_free_excluded_extents(cache);
2065 } else if (cache->length == cache->used) {
2066 cache->last_byte_to_unpin = (u64)-1;
2067 cache->cached = BTRFS_CACHE_FINISHED;
2068 btrfs_free_excluded_extents(cache);
2069 } else if (cache->used == 0) {
2070 cache->last_byte_to_unpin = (u64)-1;
2071 cache->cached = BTRFS_CACHE_FINISHED;
2072 add_new_free_space(cache, cache->start,
2073 cache->start + cache->length);
2074 btrfs_free_excluded_extents(cache);
2077 ret = btrfs_add_block_group_cache(info, cache);
2079 btrfs_remove_free_space_cache(cache);
2082 trace_btrfs_add_block_group(info, cache, 0);
2083 btrfs_update_space_info(info, cache->flags, cache->length,
2084 cache->used, cache->bytes_super,
2085 cache->zone_unusable, &space_info);
2087 cache->space_info = space_info;
2089 link_block_group(cache);
2091 set_avail_alloc_bits(info, cache->flags);
2092 if (btrfs_chunk_writeable(info, cache->start)) {
2093 if (cache->used == 0) {
2094 ASSERT(list_empty(&cache->bg_list));
2095 if (btrfs_test_opt(info, DISCARD_ASYNC))
2096 btrfs_discard_queue_work(&info->discard_ctl, cache);
2098 btrfs_mark_bg_unused(cache);
2101 inc_block_group_ro(cache, 1);
2106 btrfs_put_block_group(cache);
2110 static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
2112 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
2113 struct btrfs_space_info *space_info;
2114 struct rb_node *node;
2117 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
2118 struct extent_map *em;
2119 struct map_lookup *map;
2120 struct btrfs_block_group *bg;
2122 em = rb_entry(node, struct extent_map, rb_node);
2123 map = em->map_lookup;
2124 bg = btrfs_create_block_group_cache(fs_info, em->start);
2130 /* Fill dummy cache as FULL */
2131 bg->length = em->len;
2132 bg->flags = map->type;
2133 bg->last_byte_to_unpin = (u64)-1;
2134 bg->cached = BTRFS_CACHE_FINISHED;
2136 bg->flags = map->type;
2137 ret = btrfs_add_block_group_cache(fs_info, bg);
2139 * We may have some valid block group cache added already, in
2140 * that case we skip to the next one.
2142 if (ret == -EEXIST) {
2144 btrfs_put_block_group(bg);
2149 btrfs_remove_free_space_cache(bg);
2150 btrfs_put_block_group(bg);
2154 btrfs_update_space_info(fs_info, bg->flags, em->len, em->len,
2156 bg->space_info = space_info;
2157 link_block_group(bg);
2159 set_avail_alloc_bits(fs_info, bg->flags);
2162 btrfs_init_global_block_rsv(fs_info);
2166 int btrfs_read_block_groups(struct btrfs_fs_info *info)
2168 struct btrfs_path *path;
2170 struct btrfs_block_group *cache;
2171 struct btrfs_space_info *space_info;
2172 struct btrfs_key key;
2176 if (!info->extent_root)
2177 return fill_dummy_bgs(info);
2181 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2182 path = btrfs_alloc_path();
2186 cache_gen = btrfs_super_cache_generation(info->super_copy);
2187 if (btrfs_test_opt(info, SPACE_CACHE) &&
2188 btrfs_super_generation(info->super_copy) != cache_gen)
2190 if (btrfs_test_opt(info, CLEAR_CACHE))
2194 struct btrfs_block_group_item bgi;
2195 struct extent_buffer *leaf;
2198 ret = find_first_block_group(info, path, &key);
2204 leaf = path->nodes[0];
2205 slot = path->slots[0];
2207 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
2210 btrfs_item_key_to_cpu(leaf, &key, slot);
2211 btrfs_release_path(path);
2212 ret = read_one_block_group(info, &bgi, &key, need_clear);
2215 key.objectid += key.offset;
2218 btrfs_release_path(path);
2220 list_for_each_entry(space_info, &info->space_info, list) {
2223 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2224 if (list_empty(&space_info->block_groups[i]))
2226 cache = list_first_entry(&space_info->block_groups[i],
2227 struct btrfs_block_group,
2229 btrfs_sysfs_add_block_group_type(cache);
2232 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2233 (BTRFS_BLOCK_GROUP_RAID10 |
2234 BTRFS_BLOCK_GROUP_RAID1_MASK |
2235 BTRFS_BLOCK_GROUP_RAID56_MASK |
2236 BTRFS_BLOCK_GROUP_DUP)))
2239 * Avoid allocating from un-mirrored block group if there are
2240 * mirrored block groups.
2242 list_for_each_entry(cache,
2243 &space_info->block_groups[BTRFS_RAID_RAID0],
2245 inc_block_group_ro(cache, 1);
2246 list_for_each_entry(cache,
2247 &space_info->block_groups[BTRFS_RAID_SINGLE],
2249 inc_block_group_ro(cache, 1);
2252 btrfs_init_global_block_rsv(info);
2253 ret = check_chunk_block_group_mappings(info);
2255 btrfs_free_path(path);
2257 * We've hit some error while reading the extent tree, and have
2258 * rescue=ibadroots mount option.
2259 * Try to fill the tree using dummy block groups so that the user can
2260 * continue to mount and grab their data.
2262 if (ret && btrfs_test_opt(info, IGNOREBADROOTS))
2263 ret = fill_dummy_bgs(info);
2268 * This function, insert_block_group_item(), belongs to the phase 2 of chunk
2271 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2274 static int insert_block_group_item(struct btrfs_trans_handle *trans,
2275 struct btrfs_block_group *block_group)
2277 struct btrfs_fs_info *fs_info = trans->fs_info;
2278 struct btrfs_block_group_item bgi;
2279 struct btrfs_root *root;
2280 struct btrfs_key key;
2282 spin_lock(&block_group->lock);
2283 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2284 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2285 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2286 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2287 key.objectid = block_group->start;
2288 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2289 key.offset = block_group->length;
2290 spin_unlock(&block_group->lock);
2292 root = fs_info->extent_root;
2293 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2296 static int insert_dev_extent(struct btrfs_trans_handle *trans,
2297 struct btrfs_device *device, u64 chunk_offset,
2298 u64 start, u64 num_bytes)
2300 struct btrfs_fs_info *fs_info = device->fs_info;
2301 struct btrfs_root *root = fs_info->dev_root;
2302 struct btrfs_path *path;
2303 struct btrfs_dev_extent *extent;
2304 struct extent_buffer *leaf;
2305 struct btrfs_key key;
2308 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
2309 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
2310 path = btrfs_alloc_path();
2314 key.objectid = device->devid;
2315 key.type = BTRFS_DEV_EXTENT_KEY;
2317 ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent));
2321 leaf = path->nodes[0];
2322 extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
2323 btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID);
2324 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
2325 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2326 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
2328 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
2329 btrfs_mark_buffer_dirty(leaf);
2331 btrfs_free_path(path);
2336 * This function belongs to phase 2.
2338 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2341 static int insert_dev_extents(struct btrfs_trans_handle *trans,
2342 u64 chunk_offset, u64 chunk_size)
2344 struct btrfs_fs_info *fs_info = trans->fs_info;
2345 struct btrfs_device *device;
2346 struct extent_map *em;
2347 struct map_lookup *map;
2353 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
2357 map = em->map_lookup;
2358 stripe_size = em->orig_block_len;
2361 * Take the device list mutex to prevent races with the final phase of
2362 * a device replace operation that replaces the device object associated
2363 * with the map's stripes, because the device object's id can change
2364 * at any time during that final phase of the device replace operation
2365 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
2366 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
2367 * resulting in persisting a device extent item with such ID.
2369 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2370 for (i = 0; i < map->num_stripes; i++) {
2371 device = map->stripes[i].dev;
2372 dev_offset = map->stripes[i].physical;
2374 ret = insert_dev_extent(trans, device, chunk_offset, dev_offset,
2379 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2381 free_extent_map(em);
2386 * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
2389 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2392 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2394 struct btrfs_fs_info *fs_info = trans->fs_info;
2395 struct btrfs_block_group *block_group;
2398 while (!list_empty(&trans->new_bgs)) {
2401 block_group = list_first_entry(&trans->new_bgs,
2402 struct btrfs_block_group,
2407 index = btrfs_bg_flags_to_raid_index(block_group->flags);
2409 ret = insert_block_group_item(trans, block_group);
2411 btrfs_abort_transaction(trans, ret);
2412 if (!block_group->chunk_item_inserted) {
2413 mutex_lock(&fs_info->chunk_mutex);
2414 ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group);
2415 mutex_unlock(&fs_info->chunk_mutex);
2417 btrfs_abort_transaction(trans, ret);
2419 ret = insert_dev_extents(trans, block_group->start,
2420 block_group->length);
2422 btrfs_abort_transaction(trans, ret);
2423 add_block_group_free_space(trans, block_group);
2426 * If we restriped during balance, we may have added a new raid
2427 * type, so now add the sysfs entries when it is safe to do so.
2428 * We don't have to worry about locking here as it's handled in
2429 * btrfs_sysfs_add_block_group_type.
2431 if (block_group->space_info->block_group_kobjs[index] == NULL)
2432 btrfs_sysfs_add_block_group_type(block_group);
2434 /* Already aborted the transaction if it failed. */
2436 btrfs_delayed_refs_rsv_release(fs_info, 1);
2437 list_del_init(&block_group->bg_list);
2439 btrfs_trans_release_chunk_metadata(trans);
2442 struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
2443 u64 bytes_used, u64 type,
2444 u64 chunk_offset, u64 size)
2446 struct btrfs_fs_info *fs_info = trans->fs_info;
2447 struct btrfs_block_group *cache;
2450 btrfs_set_log_full_commit(trans);
2452 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
2454 return ERR_PTR(-ENOMEM);
2456 cache->length = size;
2457 set_free_space_tree_thresholds(cache);
2458 cache->used = bytes_used;
2459 cache->flags = type;
2460 cache->last_byte_to_unpin = (u64)-1;
2461 cache->cached = BTRFS_CACHE_FINISHED;
2462 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
2463 cache->needs_free_space = 1;
2465 ret = btrfs_load_block_group_zone_info(cache, true);
2467 btrfs_put_block_group(cache);
2468 return ERR_PTR(ret);
2472 * New block group is likely to be used soon. Try to activate it now.
2473 * Failure is OK for now.
2475 btrfs_zone_activate(cache);
2477 ret = exclude_super_stripes(cache);
2479 /* We may have excluded something, so call this just in case */
2480 btrfs_free_excluded_extents(cache);
2481 btrfs_put_block_group(cache);
2482 return ERR_PTR(ret);
2485 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2487 btrfs_free_excluded_extents(cache);
2489 #ifdef CONFIG_BTRFS_DEBUG
2490 if (btrfs_should_fragment_free_space(cache)) {
2491 u64 new_bytes_used = size - bytes_used;
2493 bytes_used += new_bytes_used >> 1;
2494 fragment_free_space(cache);
2498 * Ensure the corresponding space_info object is created and
2499 * assigned to our block group. We want our bg to be added to the rbtree
2500 * with its ->space_info set.
2502 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2503 ASSERT(cache->space_info);
2505 ret = btrfs_add_block_group_cache(fs_info, cache);
2507 btrfs_remove_free_space_cache(cache);
2508 btrfs_put_block_group(cache);
2509 return ERR_PTR(ret);
2513 * Now that our block group has its ->space_info set and is inserted in
2514 * the rbtree, update the space info's counters.
2516 trace_btrfs_add_block_group(fs_info, cache, 1);
2517 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
2518 cache->bytes_super, cache->zone_unusable,
2519 &cache->space_info);
2520 btrfs_update_global_block_rsv(fs_info);
2522 link_block_group(cache);
2524 list_add_tail(&cache->bg_list, &trans->new_bgs);
2525 trans->delayed_ref_updates++;
2526 btrfs_update_delayed_refs_rsv(trans);
2528 set_avail_alloc_bits(fs_info, type);
2533 * Mark one block group RO, can be called several times for the same block
2536 * @cache: the destination block group
2537 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2538 * ensure we still have some free space after marking this
2541 int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2542 bool do_chunk_alloc)
2544 struct btrfs_fs_info *fs_info = cache->fs_info;
2545 struct btrfs_trans_handle *trans;
2548 bool dirty_bg_running;
2551 trans = btrfs_join_transaction(fs_info->extent_root);
2553 return PTR_ERR(trans);
2555 dirty_bg_running = false;
2558 * We're not allowed to set block groups readonly after the dirty
2559 * block group cache has started writing. If it already started,
2560 * back off and let this transaction commit.
2562 mutex_lock(&fs_info->ro_block_group_mutex);
2563 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2564 u64 transid = trans->transid;
2566 mutex_unlock(&fs_info->ro_block_group_mutex);
2567 btrfs_end_transaction(trans);
2569 ret = btrfs_wait_for_commit(fs_info, transid);
2572 dirty_bg_running = true;
2574 } while (dirty_bg_running);
2576 if (do_chunk_alloc) {
2578 * If we are changing raid levels, try to allocate a
2579 * corresponding block group with the new raid level.
2581 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2582 if (alloc_flags != cache->flags) {
2583 ret = btrfs_chunk_alloc(trans, alloc_flags,
2586 * ENOSPC is allowed here, we may have enough space
2587 * already allocated at the new raid level to carry on
2596 ret = inc_block_group_ro(cache, 0);
2597 if (!do_chunk_alloc || ret == -ETXTBSY)
2601 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2602 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2605 ret = inc_block_group_ro(cache, 0);
2606 if (ret == -ETXTBSY)
2609 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2610 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2611 mutex_lock(&fs_info->chunk_mutex);
2612 check_system_chunk(trans, alloc_flags);
2613 mutex_unlock(&fs_info->chunk_mutex);
2616 mutex_unlock(&fs_info->ro_block_group_mutex);
2618 btrfs_end_transaction(trans);
2622 void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
2624 struct btrfs_space_info *sinfo = cache->space_info;
2629 spin_lock(&sinfo->lock);
2630 spin_lock(&cache->lock);
2632 if (btrfs_is_zoned(cache->fs_info)) {
2633 /* Migrate zone_unusable bytes back */
2634 cache->zone_unusable =
2635 (cache->alloc_offset - cache->used) +
2636 (cache->length - cache->zone_capacity);
2637 sinfo->bytes_zone_unusable += cache->zone_unusable;
2638 sinfo->bytes_readonly -= cache->zone_unusable;
2640 num_bytes = cache->length - cache->reserved -
2641 cache->pinned - cache->bytes_super -
2642 cache->zone_unusable - cache->used;
2643 sinfo->bytes_readonly -= num_bytes;
2644 list_del_init(&cache->ro_list);
2646 spin_unlock(&cache->lock);
2647 spin_unlock(&sinfo->lock);
2650 static int update_block_group_item(struct btrfs_trans_handle *trans,
2651 struct btrfs_path *path,
2652 struct btrfs_block_group *cache)
2654 struct btrfs_fs_info *fs_info = trans->fs_info;
2656 struct btrfs_root *root = fs_info->extent_root;
2658 struct extent_buffer *leaf;
2659 struct btrfs_block_group_item bgi;
2660 struct btrfs_key key;
2662 key.objectid = cache->start;
2663 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2664 key.offset = cache->length;
2666 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2673 leaf = path->nodes[0];
2674 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2675 btrfs_set_stack_block_group_used(&bgi, cache->used);
2676 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2677 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2678 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2679 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
2680 btrfs_mark_buffer_dirty(leaf);
2682 btrfs_release_path(path);
2687 static int cache_save_setup(struct btrfs_block_group *block_group,
2688 struct btrfs_trans_handle *trans,
2689 struct btrfs_path *path)
2691 struct btrfs_fs_info *fs_info = block_group->fs_info;
2692 struct btrfs_root *root = fs_info->tree_root;
2693 struct inode *inode = NULL;
2694 struct extent_changeset *data_reserved = NULL;
2696 int dcs = BTRFS_DC_ERROR;
2701 if (!btrfs_test_opt(fs_info, SPACE_CACHE))
2705 * If this block group is smaller than 100 megs don't bother caching the
2708 if (block_group->length < (100 * SZ_1M)) {
2709 spin_lock(&block_group->lock);
2710 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2711 spin_unlock(&block_group->lock);
2715 if (TRANS_ABORTED(trans))
2718 inode = lookup_free_space_inode(block_group, path);
2719 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2720 ret = PTR_ERR(inode);
2721 btrfs_release_path(path);
2725 if (IS_ERR(inode)) {
2729 if (block_group->ro)
2732 ret = create_free_space_inode(trans, block_group, path);
2739 * We want to set the generation to 0, that way if anything goes wrong
2740 * from here on out we know not to trust this cache when we load up next
2743 BTRFS_I(inode)->generation = 0;
2744 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
2747 * So theoretically we could recover from this, simply set the
2748 * super cache generation to 0 so we know to invalidate the
2749 * cache, but then we'd have to keep track of the block groups
2750 * that fail this way so we know we _have_ to reset this cache
2751 * before the next commit or risk reading stale cache. So to
2752 * limit our exposure to horrible edge cases lets just abort the
2753 * transaction, this only happens in really bad situations
2756 btrfs_abort_transaction(trans, ret);
2761 /* We've already setup this transaction, go ahead and exit */
2762 if (block_group->cache_generation == trans->transid &&
2763 i_size_read(inode)) {
2764 dcs = BTRFS_DC_SETUP;
2768 if (i_size_read(inode) > 0) {
2769 ret = btrfs_check_trunc_cache_free_space(fs_info,
2770 &fs_info->global_block_rsv);
2774 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2779 spin_lock(&block_group->lock);
2780 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2781 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2783 * don't bother trying to write stuff out _if_
2784 * a) we're not cached,
2785 * b) we're with nospace_cache mount option,
2786 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2788 dcs = BTRFS_DC_WRITTEN;
2789 spin_unlock(&block_group->lock);
2792 spin_unlock(&block_group->lock);
2795 * We hit an ENOSPC when setting up the cache in this transaction, just
2796 * skip doing the setup, we've already cleared the cache so we're safe.
2798 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2804 * Try to preallocate enough space based on how big the block group is.
2805 * Keep in mind this has to include any pinned space which could end up
2806 * taking up quite a bit since it's not folded into the other space
2809 cache_size = div_u64(block_group->length, SZ_256M);
2814 cache_size *= fs_info->sectorsize;
2816 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
2821 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
2822 cache_size, cache_size,
2825 * Our cache requires contiguous chunks so that we don't modify a bunch
2826 * of metadata or split extents when writing the cache out, which means
2827 * we can enospc if we are heavily fragmented in addition to just normal
2828 * out of space conditions. So if we hit this just skip setting up any
2829 * other block groups for this transaction, maybe we'll unpin enough
2830 * space the next time around.
2833 dcs = BTRFS_DC_SETUP;
2834 else if (ret == -ENOSPC)
2835 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2840 btrfs_release_path(path);
2842 spin_lock(&block_group->lock);
2843 if (!ret && dcs == BTRFS_DC_SETUP)
2844 block_group->cache_generation = trans->transid;
2845 block_group->disk_cache_state = dcs;
2846 spin_unlock(&block_group->lock);
2848 extent_changeset_free(data_reserved);
2852 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2854 struct btrfs_fs_info *fs_info = trans->fs_info;
2855 struct btrfs_block_group *cache, *tmp;
2856 struct btrfs_transaction *cur_trans = trans->transaction;
2857 struct btrfs_path *path;
2859 if (list_empty(&cur_trans->dirty_bgs) ||
2860 !btrfs_test_opt(fs_info, SPACE_CACHE))
2863 path = btrfs_alloc_path();
2867 /* Could add new block groups, use _safe just in case */
2868 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2870 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2871 cache_save_setup(cache, trans, path);
2874 btrfs_free_path(path);
2879 * Transaction commit does final block group cache writeback during a critical
2880 * section where nothing is allowed to change the FS. This is required in
2881 * order for the cache to actually match the block group, but can introduce a
2882 * lot of latency into the commit.
2884 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2885 * There's a chance we'll have to redo some of it if the block group changes
2886 * again during the commit, but it greatly reduces the commit latency by
2887 * getting rid of the easy block groups while we're still allowing others to
2890 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2892 struct btrfs_fs_info *fs_info = trans->fs_info;
2893 struct btrfs_block_group *cache;
2894 struct btrfs_transaction *cur_trans = trans->transaction;
2897 struct btrfs_path *path = NULL;
2899 struct list_head *io = &cur_trans->io_bgs;
2900 int num_started = 0;
2903 spin_lock(&cur_trans->dirty_bgs_lock);
2904 if (list_empty(&cur_trans->dirty_bgs)) {
2905 spin_unlock(&cur_trans->dirty_bgs_lock);
2908 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2909 spin_unlock(&cur_trans->dirty_bgs_lock);
2912 /* Make sure all the block groups on our dirty list actually exist */
2913 btrfs_create_pending_block_groups(trans);
2916 path = btrfs_alloc_path();
2924 * cache_write_mutex is here only to save us from balance or automatic
2925 * removal of empty block groups deleting this block group while we are
2926 * writing out the cache
2928 mutex_lock(&trans->transaction->cache_write_mutex);
2929 while (!list_empty(&dirty)) {
2930 bool drop_reserve = true;
2932 cache = list_first_entry(&dirty, struct btrfs_block_group,
2935 * This can happen if something re-dirties a block group that
2936 * is already under IO. Just wait for it to finish and then do
2939 if (!list_empty(&cache->io_list)) {
2940 list_del_init(&cache->io_list);
2941 btrfs_wait_cache_io(trans, cache, path);
2942 btrfs_put_block_group(cache);
2947 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
2948 * it should update the cache_state. Don't delete until after
2951 * Since we're not running in the commit critical section
2952 * we need the dirty_bgs_lock to protect from update_block_group
2954 spin_lock(&cur_trans->dirty_bgs_lock);
2955 list_del_init(&cache->dirty_list);
2956 spin_unlock(&cur_trans->dirty_bgs_lock);
2960 cache_save_setup(cache, trans, path);
2962 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
2963 cache->io_ctl.inode = NULL;
2964 ret = btrfs_write_out_cache(trans, cache, path);
2965 if (ret == 0 && cache->io_ctl.inode) {
2970 * The cache_write_mutex is protecting the
2971 * io_list, also refer to the definition of
2972 * btrfs_transaction::io_bgs for more details
2974 list_add_tail(&cache->io_list, io);
2977 * If we failed to write the cache, the
2978 * generation will be bad and life goes on
2984 ret = update_block_group_item(trans, path, cache);
2986 * Our block group might still be attached to the list
2987 * of new block groups in the transaction handle of some
2988 * other task (struct btrfs_trans_handle->new_bgs). This
2989 * means its block group item isn't yet in the extent
2990 * tree. If this happens ignore the error, as we will
2991 * try again later in the critical section of the
2992 * transaction commit.
2994 if (ret == -ENOENT) {
2996 spin_lock(&cur_trans->dirty_bgs_lock);
2997 if (list_empty(&cache->dirty_list)) {
2998 list_add_tail(&cache->dirty_list,
2999 &cur_trans->dirty_bgs);
3000 btrfs_get_block_group(cache);
3001 drop_reserve = false;
3003 spin_unlock(&cur_trans->dirty_bgs_lock);
3005 btrfs_abort_transaction(trans, ret);
3009 /* If it's not on the io list, we need to put the block group */
3011 btrfs_put_block_group(cache);
3013 btrfs_delayed_refs_rsv_release(fs_info, 1);
3015 * Avoid blocking other tasks for too long. It might even save
3016 * us from writing caches for block groups that are going to be
3019 mutex_unlock(&trans->transaction->cache_write_mutex);
3022 mutex_lock(&trans->transaction->cache_write_mutex);
3024 mutex_unlock(&trans->transaction->cache_write_mutex);
3027 * Go through delayed refs for all the stuff we've just kicked off
3028 * and then loop back (just once)
3031 ret = btrfs_run_delayed_refs(trans, 0);
3032 if (!ret && loops == 0) {
3034 spin_lock(&cur_trans->dirty_bgs_lock);
3035 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3037 * dirty_bgs_lock protects us from concurrent block group
3038 * deletes too (not just cache_write_mutex).
3040 if (!list_empty(&dirty)) {
3041 spin_unlock(&cur_trans->dirty_bgs_lock);
3044 spin_unlock(&cur_trans->dirty_bgs_lock);
3048 spin_lock(&cur_trans->dirty_bgs_lock);
3049 list_splice_init(&dirty, &cur_trans->dirty_bgs);
3050 spin_unlock(&cur_trans->dirty_bgs_lock);
3051 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3054 btrfs_free_path(path);
3058 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
3060 struct btrfs_fs_info *fs_info = trans->fs_info;
3061 struct btrfs_block_group *cache;
3062 struct btrfs_transaction *cur_trans = trans->transaction;
3065 struct btrfs_path *path;
3066 struct list_head *io = &cur_trans->io_bgs;
3067 int num_started = 0;
3069 path = btrfs_alloc_path();
3074 * Even though we are in the critical section of the transaction commit,
3075 * we can still have concurrent tasks adding elements to this
3076 * transaction's list of dirty block groups. These tasks correspond to
3077 * endio free space workers started when writeback finishes for a
3078 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3079 * allocate new block groups as a result of COWing nodes of the root
3080 * tree when updating the free space inode. The writeback for the space
3081 * caches is triggered by an earlier call to
3082 * btrfs_start_dirty_block_groups() and iterations of the following
3084 * Also we want to do the cache_save_setup first and then run the
3085 * delayed refs to make sure we have the best chance at doing this all
3088 spin_lock(&cur_trans->dirty_bgs_lock);
3089 while (!list_empty(&cur_trans->dirty_bgs)) {
3090 cache = list_first_entry(&cur_trans->dirty_bgs,
3091 struct btrfs_block_group,
3095 * This can happen if cache_save_setup re-dirties a block group
3096 * that is already under IO. Just wait for it to finish and
3097 * then do it all again
3099 if (!list_empty(&cache->io_list)) {
3100 spin_unlock(&cur_trans->dirty_bgs_lock);
3101 list_del_init(&cache->io_list);
3102 btrfs_wait_cache_io(trans, cache, path);
3103 btrfs_put_block_group(cache);
3104 spin_lock(&cur_trans->dirty_bgs_lock);
3108 * Don't remove from the dirty list until after we've waited on
3111 list_del_init(&cache->dirty_list);
3112 spin_unlock(&cur_trans->dirty_bgs_lock);
3115 cache_save_setup(cache, trans, path);
3118 ret = btrfs_run_delayed_refs(trans,
3119 (unsigned long) -1);
3121 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3122 cache->io_ctl.inode = NULL;
3123 ret = btrfs_write_out_cache(trans, cache, path);
3124 if (ret == 0 && cache->io_ctl.inode) {
3127 list_add_tail(&cache->io_list, io);
3130 * If we failed to write the cache, the
3131 * generation will be bad and life goes on
3137 ret = update_block_group_item(trans, path, cache);
3139 * One of the free space endio workers might have
3140 * created a new block group while updating a free space
3141 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3142 * and hasn't released its transaction handle yet, in
3143 * which case the new block group is still attached to
3144 * its transaction handle and its creation has not
3145 * finished yet (no block group item in the extent tree
3146 * yet, etc). If this is the case, wait for all free
3147 * space endio workers to finish and retry. This is a
3148 * very rare case so no need for a more efficient and
3151 if (ret == -ENOENT) {
3152 wait_event(cur_trans->writer_wait,
3153 atomic_read(&cur_trans->num_writers) == 1);
3154 ret = update_block_group_item(trans, path, cache);
3157 btrfs_abort_transaction(trans, ret);
3160 /* If its not on the io list, we need to put the block group */
3162 btrfs_put_block_group(cache);
3163 btrfs_delayed_refs_rsv_release(fs_info, 1);
3164 spin_lock(&cur_trans->dirty_bgs_lock);
3166 spin_unlock(&cur_trans->dirty_bgs_lock);
3169 * Refer to the definition of io_bgs member for details why it's safe
3170 * to use it without any locking
3172 while (!list_empty(io)) {
3173 cache = list_first_entry(io, struct btrfs_block_group,
3175 list_del_init(&cache->io_list);
3176 btrfs_wait_cache_io(trans, cache, path);
3177 btrfs_put_block_group(cache);
3180 btrfs_free_path(path);
3184 int btrfs_update_block_group(struct btrfs_trans_handle *trans,
3185 u64 bytenr, u64 num_bytes, bool alloc)
3187 struct btrfs_fs_info *info = trans->fs_info;
3188 struct btrfs_block_group *cache = NULL;
3189 u64 total = num_bytes;
3195 /* Block accounting for super block */
3196 spin_lock(&info->delalloc_root_lock);
3197 old_val = btrfs_super_bytes_used(info->super_copy);
3199 old_val += num_bytes;
3201 old_val -= num_bytes;
3202 btrfs_set_super_bytes_used(info->super_copy, old_val);
3203 spin_unlock(&info->delalloc_root_lock);
3206 cache = btrfs_lookup_block_group(info, bytenr);
3211 factor = btrfs_bg_type_to_factor(cache->flags);
3214 * If this block group has free space cache written out, we
3215 * need to make sure to load it if we are removing space. This
3216 * is because we need the unpinning stage to actually add the
3217 * space back to the block group, otherwise we will leak space.
3219 if (!alloc && !btrfs_block_group_done(cache))
3220 btrfs_cache_block_group(cache, 1);
3222 byte_in_group = bytenr - cache->start;
3223 WARN_ON(byte_in_group > cache->length);
3225 spin_lock(&cache->space_info->lock);
3226 spin_lock(&cache->lock);
3228 if (btrfs_test_opt(info, SPACE_CACHE) &&
3229 cache->disk_cache_state < BTRFS_DC_CLEAR)
3230 cache->disk_cache_state = BTRFS_DC_CLEAR;
3232 old_val = cache->used;
3233 num_bytes = min(total, cache->length - byte_in_group);
3235 old_val += num_bytes;
3236 cache->used = old_val;
3237 cache->reserved -= num_bytes;
3238 cache->space_info->bytes_reserved -= num_bytes;
3239 cache->space_info->bytes_used += num_bytes;
3240 cache->space_info->disk_used += num_bytes * factor;
3241 spin_unlock(&cache->lock);
3242 spin_unlock(&cache->space_info->lock);
3244 old_val -= num_bytes;
3245 cache->used = old_val;
3246 cache->pinned += num_bytes;
3247 btrfs_space_info_update_bytes_pinned(info,
3248 cache->space_info, num_bytes);
3249 cache->space_info->bytes_used -= num_bytes;
3250 cache->space_info->disk_used -= num_bytes * factor;
3251 spin_unlock(&cache->lock);
3252 spin_unlock(&cache->space_info->lock);
3254 set_extent_dirty(&trans->transaction->pinned_extents,
3255 bytenr, bytenr + num_bytes - 1,
3256 GFP_NOFS | __GFP_NOFAIL);
3259 spin_lock(&trans->transaction->dirty_bgs_lock);
3260 if (list_empty(&cache->dirty_list)) {
3261 list_add_tail(&cache->dirty_list,
3262 &trans->transaction->dirty_bgs);
3263 trans->delayed_ref_updates++;
3264 btrfs_get_block_group(cache);
3266 spin_unlock(&trans->transaction->dirty_bgs_lock);
3269 * No longer have used bytes in this block group, queue it for
3270 * deletion. We do this after adding the block group to the
3271 * dirty list to avoid races between cleaner kthread and space
3274 if (!alloc && old_val == 0) {
3275 if (!btrfs_test_opt(info, DISCARD_ASYNC))
3276 btrfs_mark_bg_unused(cache);
3279 btrfs_put_block_group(cache);
3281 bytenr += num_bytes;
3284 /* Modified block groups are accounted for in the delayed_refs_rsv. */
3285 btrfs_update_delayed_refs_rsv(trans);
3290 * btrfs_add_reserved_bytes - update the block_group and space info counters
3291 * @cache: The cache we are manipulating
3292 * @ram_bytes: The number of bytes of file content, and will be same to
3293 * @num_bytes except for the compress path.
3294 * @num_bytes: The number of bytes in question
3295 * @delalloc: The blocks are allocated for the delalloc write
3297 * This is called by the allocator when it reserves space. If this is a
3298 * reservation and the block group has become read only we cannot make the
3299 * reservation and return -EAGAIN, otherwise this function always succeeds.
3301 int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
3302 u64 ram_bytes, u64 num_bytes, int delalloc)
3304 struct btrfs_space_info *space_info = cache->space_info;
3307 spin_lock(&space_info->lock);
3308 spin_lock(&cache->lock);
3312 cache->reserved += num_bytes;
3313 space_info->bytes_reserved += num_bytes;
3314 trace_btrfs_space_reservation(cache->fs_info, "space_info",
3315 space_info->flags, num_bytes, 1);
3316 btrfs_space_info_update_bytes_may_use(cache->fs_info,
3317 space_info, -ram_bytes);
3319 cache->delalloc_bytes += num_bytes;
3322 * Compression can use less space than we reserved, so wake
3323 * tickets if that happens
3325 if (num_bytes < ram_bytes)
3326 btrfs_try_granting_tickets(cache->fs_info, space_info);
3328 spin_unlock(&cache->lock);
3329 spin_unlock(&space_info->lock);
3334 * btrfs_free_reserved_bytes - update the block_group and space info counters
3335 * @cache: The cache we are manipulating
3336 * @num_bytes: The number of bytes in question
3337 * @delalloc: The blocks are allocated for the delalloc write
3339 * This is called by somebody who is freeing space that was never actually used
3340 * on disk. For example if you reserve some space for a new leaf in transaction
3341 * A and before transaction A commits you free that leaf, you call this with
3342 * reserve set to 0 in order to clear the reservation.
3344 void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3345 u64 num_bytes, int delalloc)
3347 struct btrfs_space_info *space_info = cache->space_info;
3349 spin_lock(&space_info->lock);
3350 spin_lock(&cache->lock);
3352 space_info->bytes_readonly += num_bytes;
3353 cache->reserved -= num_bytes;
3354 space_info->bytes_reserved -= num_bytes;
3355 space_info->max_extent_size = 0;
3358 cache->delalloc_bytes -= num_bytes;
3359 spin_unlock(&cache->lock);
3361 btrfs_try_granting_tickets(cache->fs_info, space_info);
3362 spin_unlock(&space_info->lock);
3365 static void force_metadata_allocation(struct btrfs_fs_info *info)
3367 struct list_head *head = &info->space_info;
3368 struct btrfs_space_info *found;
3370 list_for_each_entry(found, head, list) {
3371 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3372 found->force_alloc = CHUNK_ALLOC_FORCE;
3376 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3377 struct btrfs_space_info *sinfo, int force)
3379 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3382 if (force == CHUNK_ALLOC_FORCE)
3386 * in limited mode, we want to have some free space up to
3387 * about 1% of the FS size.
3389 if (force == CHUNK_ALLOC_LIMITED) {
3390 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3391 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3393 if (sinfo->total_bytes - bytes_used < thresh)
3397 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3402 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3404 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3406 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3409 static int do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags)
3411 struct btrfs_block_group *bg;
3415 * Check if we have enough space in the system space info because we
3416 * will need to update device items in the chunk btree and insert a new
3417 * chunk item in the chunk btree as well. This will allocate a new
3418 * system block group if needed.
3420 check_system_chunk(trans, flags);
3422 bg = btrfs_create_chunk(trans, flags);
3428 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
3430 * Normally we are not expected to fail with -ENOSPC here, since we have
3431 * previously reserved space in the system space_info and allocated one
3432 * new system chunk if necessary. However there are three exceptions:
3434 * 1) We may have enough free space in the system space_info but all the
3435 * existing system block groups have a profile which can not be used
3436 * for extent allocation.
3438 * This happens when mounting in degraded mode. For example we have a
3439 * RAID1 filesystem with 2 devices, lose one device and mount the fs
3440 * using the other device in degraded mode. If we then allocate a chunk,
3441 * we may have enough free space in the existing system space_info, but
3442 * none of the block groups can be used for extent allocation since they
3443 * have a RAID1 profile, and because we are in degraded mode with a
3444 * single device, we are forced to allocate a new system chunk with a
3445 * SINGLE profile. Making check_system_chunk() iterate over all system
3446 * block groups and check if they have a usable profile and enough space
3447 * can be slow on very large filesystems, so we tolerate the -ENOSPC and
3448 * try again after forcing allocation of a new system chunk. Like this
3449 * we avoid paying the cost of that search in normal circumstances, when
3450 * we were not mounted in degraded mode;
3452 * 2) We had enough free space info the system space_info, and one suitable
3453 * block group to allocate from when we called check_system_chunk()
3454 * above. However right after we called it, the only system block group
3455 * with enough free space got turned into RO mode by a running scrub,
3456 * and in this case we have to allocate a new one and retry. We only
3457 * need do this allocate and retry once, since we have a transaction
3458 * handle and scrub uses the commit root to search for block groups;
3460 * 3) We had one system block group with enough free space when we called
3461 * check_system_chunk(), but after that, right before we tried to
3462 * allocate the last extent buffer we needed, a discard operation came
3463 * in and it temporarily removed the last free space entry from the
3464 * block group (discard removes a free space entry, discards it, and
3465 * then adds back the entry to the block group cache).
3467 if (ret == -ENOSPC) {
3468 const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info);
3469 struct btrfs_block_group *sys_bg;
3471 sys_bg = btrfs_create_chunk(trans, sys_flags);
3472 if (IS_ERR(sys_bg)) {
3473 ret = PTR_ERR(sys_bg);
3474 btrfs_abort_transaction(trans, ret);
3478 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3480 btrfs_abort_transaction(trans, ret);
3484 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
3486 btrfs_abort_transaction(trans, ret);
3490 btrfs_abort_transaction(trans, ret);
3494 btrfs_trans_release_chunk_metadata(trans);
3500 * Chunk allocation is done in 2 phases:
3502 * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
3503 * the chunk, the chunk mapping, create its block group and add the items
3504 * that belong in the chunk btree to it - more specifically, we need to
3505 * update device items in the chunk btree and add a new chunk item to it.
3507 * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
3508 * group item to the extent btree and the device extent items to the devices
3511 * This is done to prevent deadlocks. For example when COWing a node from the
3512 * extent btree we are holding a write lock on the node's parent and if we
3513 * trigger chunk allocation and attempted to insert the new block group item
3514 * in the extent btree right way, we could deadlock because the path for the
3515 * insertion can include that parent node. At first glance it seems impossible
3516 * to trigger chunk allocation after starting a transaction since tasks should
3517 * reserve enough transaction units (metadata space), however while that is true
3518 * most of the time, chunk allocation may still be triggered for several reasons:
3520 * 1) When reserving metadata, we check if there is enough free space in the
3521 * metadata space_info and therefore don't trigger allocation of a new chunk.
3522 * However later when the task actually tries to COW an extent buffer from
3523 * the extent btree or from the device btree for example, it is forced to
3524 * allocate a new block group (chunk) because the only one that had enough
3525 * free space was just turned to RO mode by a running scrub for example (or
3526 * device replace, block group reclaim thread, etc), so we can not use it
3527 * for allocating an extent and end up being forced to allocate a new one;
3529 * 2) Because we only check that the metadata space_info has enough free bytes,
3530 * we end up not allocating a new metadata chunk in that case. However if
3531 * the filesystem was mounted in degraded mode, none of the existing block
3532 * groups might be suitable for extent allocation due to their incompatible
3533 * profile (for e.g. mounting a 2 devices filesystem, where all block groups
3534 * use a RAID1 profile, in degraded mode using a single device). In this case
3535 * when the task attempts to COW some extent buffer of the extent btree for
3536 * example, it will trigger allocation of a new metadata block group with a
3537 * suitable profile (SINGLE profile in the example of the degraded mount of
3538 * the RAID1 filesystem);
3540 * 3) The task has reserved enough transaction units / metadata space, but when
3541 * it attempts to COW an extent buffer from the extent or device btree for
3542 * example, it does not find any free extent in any metadata block group,
3543 * therefore forced to try to allocate a new metadata block group.
3544 * This is because some other task allocated all available extents in the
3545 * meanwhile - this typically happens with tasks that don't reserve space
3546 * properly, either intentionally or as a bug. One example where this is
3547 * done intentionally is fsync, as it does not reserve any transaction units
3548 * and ends up allocating a variable number of metadata extents for log
3549 * tree extent buffers;
3551 * 4) The task has reserved enough transaction units / metadata space, but right
3552 * before it tries to allocate the last extent buffer it needs, a discard
3553 * operation comes in and, temporarily, removes the last free space entry from
3554 * the only metadata block group that had free space (discard starts by
3555 * removing a free space entry from a block group, then does the discard
3556 * operation and, once it's done, it adds back the free space entry to the
3559 * We also need this 2 phases setup when adding a device to a filesystem with
3560 * a seed device - we must create new metadata and system chunks without adding
3561 * any of the block group items to the chunk, extent and device btrees. If we
3562 * did not do it this way, we would get ENOSPC when attempting to update those
3563 * btrees, since all the chunks from the seed device are read-only.
3565 * Phase 1 does the updates and insertions to the chunk btree because if we had
3566 * it done in phase 2 and have a thundering herd of tasks allocating chunks in
3567 * parallel, we risk having too many system chunks allocated by many tasks if
3568 * many tasks reach phase 1 without the previous ones completing phase 2. In the
3569 * extreme case this leads to exhaustion of the system chunk array in the
3570 * superblock. This is easier to trigger if using a btree node/leaf size of 64K
3571 * and with RAID filesystems (so we have more device items in the chunk btree).
3572 * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
3573 * the system chunk array due to concurrent allocations") provides more details.
3575 * Allocation of system chunks does not happen through this function. A task that
3576 * needs to update the chunk btree (the only btree that uses system chunks), must
3577 * preallocate chunk space by calling either check_system_chunk() or
3578 * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or
3579 * metadata chunk or when removing a chunk, while the later is used before doing
3580 * a modification to the chunk btree - use cases for the later are adding,
3581 * removing and resizing a device as well as relocation of a system chunk.
3582 * See the comment below for more details.
3584 * The reservation of system space, done through check_system_chunk(), as well
3585 * as all the updates and insertions into the chunk btree must be done while
3586 * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
3587 * an extent buffer from the chunks btree we never trigger allocation of a new
3588 * system chunk, which would result in a deadlock (trying to lock twice an
3589 * extent buffer of the chunk btree, first time before triggering the chunk
3590 * allocation and the second time during chunk allocation while attempting to
3591 * update the chunks btree). The system chunk array is also updated while holding
3592 * that mutex. The same logic applies to removing chunks - we must reserve system
3593 * space, update the chunk btree and the system chunk array in the superblock
3594 * while holding fs_info->chunk_mutex.
3596 * This function, btrfs_chunk_alloc(), belongs to phase 1.
3598 * If @force is CHUNK_ALLOC_FORCE:
3599 * - return 1 if it successfully allocates a chunk,
3600 * - return errors including -ENOSPC otherwise.
3601 * If @force is NOT CHUNK_ALLOC_FORCE:
3602 * - return 0 if it doesn't need to allocate a new chunk,
3603 * - return 1 if it successfully allocates a chunk,
3604 * - return errors including -ENOSPC otherwise.
3606 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3607 enum btrfs_chunk_alloc_enum force)
3609 struct btrfs_fs_info *fs_info = trans->fs_info;
3610 struct btrfs_space_info *space_info;
3611 bool wait_for_alloc = false;
3612 bool should_alloc = false;
3615 /* Don't re-enter if we're already allocating a chunk */
3616 if (trans->allocating_chunk)
3619 * Allocation of system chunks can not happen through this path, as we
3620 * could end up in a deadlock if we are allocating a data or metadata
3621 * chunk and there is another task modifying the chunk btree.
3623 * This is because while we are holding the chunk mutex, we will attempt
3624 * to add the new chunk item to the chunk btree or update an existing
3625 * device item in the chunk btree, while the other task that is modifying
3626 * the chunk btree is attempting to COW an extent buffer while holding a
3627 * lock on it and on its parent - if the COW operation triggers a system
3628 * chunk allocation, then we can deadlock because we are holding the
3629 * chunk mutex and we may need to access that extent buffer or its parent
3630 * in order to add the chunk item or update a device item.
3632 * Tasks that want to modify the chunk tree should reserve system space
3633 * before updating the chunk btree, by calling either
3634 * btrfs_reserve_chunk_metadata() or check_system_chunk().
3635 * It's possible that after a task reserves the space, it still ends up
3636 * here - this happens in the cases described above at do_chunk_alloc().
3637 * The task will have to either retry or fail.
3639 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3642 space_info = btrfs_find_space_info(fs_info, flags);
3646 spin_lock(&space_info->lock);
3647 if (force < space_info->force_alloc)
3648 force = space_info->force_alloc;
3649 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3650 if (space_info->full) {
3651 /* No more free physical space */
3656 spin_unlock(&space_info->lock);
3658 } else if (!should_alloc) {
3659 spin_unlock(&space_info->lock);
3661 } else if (space_info->chunk_alloc) {
3663 * Someone is already allocating, so we need to block
3664 * until this someone is finished and then loop to
3665 * recheck if we should continue with our allocation
3668 wait_for_alloc = true;
3669 spin_unlock(&space_info->lock);
3670 mutex_lock(&fs_info->chunk_mutex);
3671 mutex_unlock(&fs_info->chunk_mutex);
3673 /* Proceed with allocation */
3674 space_info->chunk_alloc = 1;
3675 wait_for_alloc = false;
3676 spin_unlock(&space_info->lock);
3680 } while (wait_for_alloc);
3682 mutex_lock(&fs_info->chunk_mutex);
3683 trans->allocating_chunk = true;
3686 * If we have mixed data/metadata chunks we want to make sure we keep
3687 * allocating mixed chunks instead of individual chunks.
3689 if (btrfs_mixed_space_info(space_info))
3690 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3693 * if we're doing a data chunk, go ahead and make sure that
3694 * we keep a reasonable number of metadata chunks allocated in the
3697 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3698 fs_info->data_chunk_allocations++;
3699 if (!(fs_info->data_chunk_allocations %
3700 fs_info->metadata_ratio))
3701 force_metadata_allocation(fs_info);
3704 ret = do_chunk_alloc(trans, flags);
3705 trans->allocating_chunk = false;
3707 spin_lock(&space_info->lock);
3710 space_info->full = 1;
3715 space_info->max_extent_size = 0;
3718 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3720 space_info->chunk_alloc = 0;
3721 spin_unlock(&space_info->lock);
3722 mutex_unlock(&fs_info->chunk_mutex);
3727 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3731 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3733 num_dev = fs_info->fs_devices->rw_devices;
3738 static void reserve_chunk_space(struct btrfs_trans_handle *trans,
3742 struct btrfs_fs_info *fs_info = trans->fs_info;
3743 struct btrfs_space_info *info;
3748 * Needed because we can end up allocating a system chunk and for an
3749 * atomic and race free space reservation in the chunk block reserve.
3751 lockdep_assert_held(&fs_info->chunk_mutex);
3753 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3754 spin_lock(&info->lock);
3755 left = info->total_bytes - btrfs_space_info_used(info, true);
3756 spin_unlock(&info->lock);
3758 if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3759 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3761 btrfs_dump_space_info(fs_info, info, 0, 0);
3765 u64 flags = btrfs_system_alloc_profile(fs_info);
3766 struct btrfs_block_group *bg;
3769 * Ignore failure to create system chunk. We might end up not
3770 * needing it, as we might not need to COW all nodes/leafs from
3771 * the paths we visit in the chunk tree (they were already COWed
3772 * or created in the current transaction for example).
3774 bg = btrfs_create_chunk(trans, flags);
3779 * If we fail to add the chunk item here, we end up
3780 * trying again at phase 2 of chunk allocation, at
3781 * btrfs_create_pending_block_groups(). So ignore
3782 * any error here. An ENOSPC here could happen, due to
3783 * the cases described at do_chunk_alloc() - the system
3784 * block group we just created was just turned into RO
3785 * mode by a scrub for example, or a running discard
3786 * temporarily removed its free space entries, etc.
3788 btrfs_chunk_alloc_add_chunk_item(trans, bg);
3793 ret = btrfs_block_rsv_add(fs_info->chunk_root,
3794 &fs_info->chunk_block_rsv,
3795 bytes, BTRFS_RESERVE_NO_FLUSH);
3797 trans->chunk_bytes_reserved += bytes;
3802 * Reserve space in the system space for allocating or removing a chunk.
3803 * The caller must be holding fs_info->chunk_mutex.
3805 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3807 struct btrfs_fs_info *fs_info = trans->fs_info;
3808 const u64 num_devs = get_profile_num_devs(fs_info, type);
3811 /* num_devs device items to update and 1 chunk item to add or remove. */
3812 bytes = btrfs_calc_metadata_size(fs_info, num_devs) +
3813 btrfs_calc_insert_metadata_size(fs_info, 1);
3815 reserve_chunk_space(trans, bytes, type);
3819 * Reserve space in the system space, if needed, for doing a modification to the
3822 * @trans: A transaction handle.
3823 * @is_item_insertion: Indicate if the modification is for inserting a new item
3824 * in the chunk btree or if it's for the deletion or update
3825 * of an existing item.
3827 * This is used in a context where we need to update the chunk btree outside
3828 * block group allocation and removal, to avoid a deadlock with a concurrent
3829 * task that is allocating a metadata or data block group and therefore needs to
3830 * update the chunk btree while holding the chunk mutex. After the update to the
3831 * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called.
3834 void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans,
3835 bool is_item_insertion)
3837 struct btrfs_fs_info *fs_info = trans->fs_info;
3840 if (is_item_insertion)
3841 bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
3843 bytes = btrfs_calc_metadata_size(fs_info, 1);
3845 mutex_lock(&fs_info->chunk_mutex);
3846 reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM);
3847 mutex_unlock(&fs_info->chunk_mutex);
3850 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3852 struct btrfs_block_group *block_group;
3856 struct inode *inode;
3858 block_group = btrfs_lookup_first_block_group(info, last);
3859 while (block_group) {
3860 btrfs_wait_block_group_cache_done(block_group);
3861 spin_lock(&block_group->lock);
3862 if (block_group->iref)
3864 spin_unlock(&block_group->lock);
3865 block_group = btrfs_next_block_group(block_group);
3874 inode = block_group->inode;
3875 block_group->iref = 0;
3876 block_group->inode = NULL;
3877 spin_unlock(&block_group->lock);
3878 ASSERT(block_group->io_ctl.inode == NULL);
3880 last = block_group->start + block_group->length;
3881 btrfs_put_block_group(block_group);
3886 * Must be called only after stopping all workers, since we could have block
3887 * group caching kthreads running, and therefore they could race with us if we
3888 * freed the block groups before stopping them.
3890 int btrfs_free_block_groups(struct btrfs_fs_info *info)
3892 struct btrfs_block_group *block_group;
3893 struct btrfs_space_info *space_info;
3894 struct btrfs_caching_control *caching_ctl;
3897 spin_lock(&info->block_group_cache_lock);
3898 while (!list_empty(&info->caching_block_groups)) {
3899 caching_ctl = list_entry(info->caching_block_groups.next,
3900 struct btrfs_caching_control, list);
3901 list_del(&caching_ctl->list);
3902 btrfs_put_caching_control(caching_ctl);
3904 spin_unlock(&info->block_group_cache_lock);
3906 spin_lock(&info->unused_bgs_lock);
3907 while (!list_empty(&info->unused_bgs)) {
3908 block_group = list_first_entry(&info->unused_bgs,
3909 struct btrfs_block_group,
3911 list_del_init(&block_group->bg_list);
3912 btrfs_put_block_group(block_group);
3914 spin_unlock(&info->unused_bgs_lock);
3916 spin_lock(&info->unused_bgs_lock);
3917 while (!list_empty(&info->reclaim_bgs)) {
3918 block_group = list_first_entry(&info->reclaim_bgs,
3919 struct btrfs_block_group,
3921 list_del_init(&block_group->bg_list);
3922 btrfs_put_block_group(block_group);
3924 spin_unlock(&info->unused_bgs_lock);
3926 spin_lock(&info->zone_active_bgs_lock);
3927 while (!list_empty(&info->zone_active_bgs)) {
3928 block_group = list_first_entry(&info->zone_active_bgs,
3929 struct btrfs_block_group,
3931 list_del_init(&block_group->active_bg_list);
3932 btrfs_put_block_group(block_group);
3934 spin_unlock(&info->zone_active_bgs_lock);
3936 spin_lock(&info->block_group_cache_lock);
3937 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
3938 block_group = rb_entry(n, struct btrfs_block_group,
3940 rb_erase(&block_group->cache_node,
3941 &info->block_group_cache_tree);
3942 RB_CLEAR_NODE(&block_group->cache_node);
3943 spin_unlock(&info->block_group_cache_lock);
3945 down_write(&block_group->space_info->groups_sem);
3946 list_del(&block_group->list);
3947 up_write(&block_group->space_info->groups_sem);
3950 * We haven't cached this block group, which means we could
3951 * possibly have excluded extents on this block group.
3953 if (block_group->cached == BTRFS_CACHE_NO ||
3954 block_group->cached == BTRFS_CACHE_ERROR)
3955 btrfs_free_excluded_extents(block_group);
3957 btrfs_remove_free_space_cache(block_group);
3958 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
3959 ASSERT(list_empty(&block_group->dirty_list));
3960 ASSERT(list_empty(&block_group->io_list));
3961 ASSERT(list_empty(&block_group->bg_list));
3962 ASSERT(refcount_read(&block_group->refs) == 1);
3963 ASSERT(block_group->swap_extents == 0);
3964 btrfs_put_block_group(block_group);
3966 spin_lock(&info->block_group_cache_lock);
3968 spin_unlock(&info->block_group_cache_lock);
3970 btrfs_release_global_block_rsv(info);
3972 while (!list_empty(&info->space_info)) {
3973 space_info = list_entry(info->space_info.next,
3974 struct btrfs_space_info,
3978 * Do not hide this behind enospc_debug, this is actually
3979 * important and indicates a real bug if this happens.
3981 if (WARN_ON(space_info->bytes_pinned > 0 ||
3982 space_info->bytes_reserved > 0 ||
3983 space_info->bytes_may_use > 0))
3984 btrfs_dump_space_info(info, space_info, 0, 0);
3985 WARN_ON(space_info->reclaim_size > 0);
3986 list_del(&space_info->list);
3987 btrfs_sysfs_remove_space_info(space_info);
3992 void btrfs_freeze_block_group(struct btrfs_block_group *cache)
3994 atomic_inc(&cache->frozen);
3997 void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
3999 struct btrfs_fs_info *fs_info = block_group->fs_info;
4000 struct extent_map_tree *em_tree;
4001 struct extent_map *em;
4004 spin_lock(&block_group->lock);
4005 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
4006 block_group->removed);
4007 spin_unlock(&block_group->lock);
4010 em_tree = &fs_info->mapping_tree;
4011 write_lock(&em_tree->lock);
4012 em = lookup_extent_mapping(em_tree, block_group->start,
4014 BUG_ON(!em); /* logic error, can't happen */
4015 remove_extent_mapping(em_tree, em);
4016 write_unlock(&em_tree->lock);
4018 /* once for us and once for the tree */
4019 free_extent_map(em);
4020 free_extent_map(em);
4023 * We may have left one free space entry and other possible
4024 * tasks trimming this block group have left 1 entry each one.
4027 __btrfs_remove_free_space_cache(block_group->free_space_ctl);
4031 bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
4035 spin_lock(&bg->lock);
4040 spin_unlock(&bg->lock);
4045 void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
4047 spin_lock(&bg->lock);
4049 ASSERT(bg->swap_extents >= amount);
4050 bg->swap_extents -= amount;
4051 spin_unlock(&bg->lock);