1 // SPDX-License-Identifier: GPL-2.0
5 #include "block-group.h"
6 #include "space-info.h"
8 #include "free-space-cache.h"
9 #include "free-space-tree.h"
11 #include "transaction.h"
12 #include "ref-verify.h"
15 #include "delalloc-space.h"
21 * Return target flags in extended format or 0 if restripe for this chunk_type
24 * Should be called with balance_lock held
26 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
28 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
34 if (flags & BTRFS_BLOCK_GROUP_DATA &&
35 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
36 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
37 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
38 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
39 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
40 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
41 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
42 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
49 * @flags: available profiles in extended format (see ctree.h)
51 * Return reduced profile in chunk format. If profile changing is in progress
52 * (either running or paused) picks the target profile (if it's already
53 * available), otherwise falls back to plain reducing.
55 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
57 u64 num_devices = fs_info->fs_devices->rw_devices;
63 * See if restripe for this chunk_type is in progress, if so try to
64 * reduce to the target profile
66 spin_lock(&fs_info->balance_lock);
67 target = get_restripe_target(fs_info, flags);
69 spin_unlock(&fs_info->balance_lock);
70 return extended_to_chunk(target);
72 spin_unlock(&fs_info->balance_lock);
74 /* First, mask out the RAID levels which aren't possible */
75 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
76 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
77 allowed |= btrfs_raid_array[raid_type].bg_flag;
81 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
82 allowed = BTRFS_BLOCK_GROUP_RAID6;
83 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
84 allowed = BTRFS_BLOCK_GROUP_RAID5;
85 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
86 allowed = BTRFS_BLOCK_GROUP_RAID10;
87 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
88 allowed = BTRFS_BLOCK_GROUP_RAID1;
89 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
90 allowed = BTRFS_BLOCK_GROUP_RAID0;
92 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
94 return extended_to_chunk(flags | allowed);
97 u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
104 seq = read_seqbegin(&fs_info->profiles_lock);
106 if (flags & BTRFS_BLOCK_GROUP_DATA)
107 flags |= fs_info->avail_data_alloc_bits;
108 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
109 flags |= fs_info->avail_system_alloc_bits;
110 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
111 flags |= fs_info->avail_metadata_alloc_bits;
112 } while (read_seqretry(&fs_info->profiles_lock, seq));
114 return btrfs_reduce_alloc_profile(fs_info, flags);
117 void btrfs_get_block_group(struct btrfs_block_group *cache)
119 refcount_inc(&cache->refs);
122 void btrfs_put_block_group(struct btrfs_block_group *cache)
124 if (refcount_dec_and_test(&cache->refs)) {
125 WARN_ON(cache->pinned > 0);
127 * If there was a failure to cleanup a log tree, very likely due
128 * to an IO failure on a writeback attempt of one or more of its
129 * extent buffers, we could not do proper (and cheap) unaccounting
130 * of their reserved space, so don't warn on reserved > 0 in that
133 if (!(cache->flags & BTRFS_BLOCK_GROUP_METADATA) ||
134 !BTRFS_FS_LOG_CLEANUP_ERROR(cache->fs_info))
135 WARN_ON(cache->reserved > 0);
138 * A block_group shouldn't be on the discard_list anymore.
139 * Remove the block_group from the discard_list to prevent us
140 * from causing a panic due to NULL pointer dereference.
142 if (WARN_ON(!list_empty(&cache->discard_list)))
143 btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
147 * If not empty, someone is still holding mutex of
148 * full_stripe_lock, which can only be released by caller.
149 * And it will definitely cause use-after-free when caller
150 * tries to release full stripe lock.
152 * No better way to resolve, but only to warn.
154 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
155 kfree(cache->free_space_ctl);
161 * This adds the block group to the fs_info rb tree for the block group cache
163 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
164 struct btrfs_block_group *block_group)
167 struct rb_node *parent = NULL;
168 struct btrfs_block_group *cache;
170 ASSERT(block_group->length != 0);
172 spin_lock(&info->block_group_cache_lock);
173 p = &info->block_group_cache_tree.rb_node;
177 cache = rb_entry(parent, struct btrfs_block_group, cache_node);
178 if (block_group->start < cache->start) {
180 } else if (block_group->start > cache->start) {
183 spin_unlock(&info->block_group_cache_lock);
188 rb_link_node(&block_group->cache_node, parent, p);
189 rb_insert_color(&block_group->cache_node,
190 &info->block_group_cache_tree);
192 if (info->first_logical_byte > block_group->start)
193 info->first_logical_byte = block_group->start;
195 spin_unlock(&info->block_group_cache_lock);
201 * This will return the block group at or after bytenr if contains is 0, else
202 * it will return the block group that contains the bytenr
204 static struct btrfs_block_group *block_group_cache_tree_search(
205 struct btrfs_fs_info *info, u64 bytenr, int contains)
207 struct btrfs_block_group *cache, *ret = NULL;
211 spin_lock(&info->block_group_cache_lock);
212 n = info->block_group_cache_tree.rb_node;
215 cache = rb_entry(n, struct btrfs_block_group, cache_node);
216 end = cache->start + cache->length - 1;
217 start = cache->start;
219 if (bytenr < start) {
220 if (!contains && (!ret || start < ret->start))
223 } else if (bytenr > start) {
224 if (contains && bytenr <= end) {
235 btrfs_get_block_group(ret);
236 if (bytenr == 0 && info->first_logical_byte > ret->start)
237 info->first_logical_byte = ret->start;
239 spin_unlock(&info->block_group_cache_lock);
245 * Return the block group that starts at or after bytenr
247 struct btrfs_block_group *btrfs_lookup_first_block_group(
248 struct btrfs_fs_info *info, u64 bytenr)
250 return block_group_cache_tree_search(info, bytenr, 0);
254 * Return the block group that contains the given bytenr
256 struct btrfs_block_group *btrfs_lookup_block_group(
257 struct btrfs_fs_info *info, u64 bytenr)
259 return block_group_cache_tree_search(info, bytenr, 1);
262 struct btrfs_block_group *btrfs_next_block_group(
263 struct btrfs_block_group *cache)
265 struct btrfs_fs_info *fs_info = cache->fs_info;
266 struct rb_node *node;
268 spin_lock(&fs_info->block_group_cache_lock);
270 /* If our block group was removed, we need a full search. */
271 if (RB_EMPTY_NODE(&cache->cache_node)) {
272 const u64 next_bytenr = cache->start + cache->length;
274 spin_unlock(&fs_info->block_group_cache_lock);
275 btrfs_put_block_group(cache);
276 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
278 node = rb_next(&cache->cache_node);
279 btrfs_put_block_group(cache);
281 cache = rb_entry(node, struct btrfs_block_group, cache_node);
282 btrfs_get_block_group(cache);
285 spin_unlock(&fs_info->block_group_cache_lock);
289 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
291 struct btrfs_block_group *bg;
294 bg = btrfs_lookup_block_group(fs_info, bytenr);
298 spin_lock(&bg->lock);
302 atomic_inc(&bg->nocow_writers);
303 spin_unlock(&bg->lock);
305 /* No put on block group, done by btrfs_dec_nocow_writers */
307 btrfs_put_block_group(bg);
312 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
314 struct btrfs_block_group *bg;
316 bg = btrfs_lookup_block_group(fs_info, bytenr);
318 if (atomic_dec_and_test(&bg->nocow_writers))
319 wake_up_var(&bg->nocow_writers);
321 * Once for our lookup and once for the lookup done by a previous call
322 * to btrfs_inc_nocow_writers()
324 btrfs_put_block_group(bg);
325 btrfs_put_block_group(bg);
328 void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
330 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
333 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
336 struct btrfs_block_group *bg;
338 bg = btrfs_lookup_block_group(fs_info, start);
340 if (atomic_dec_and_test(&bg->reservations))
341 wake_up_var(&bg->reservations);
342 btrfs_put_block_group(bg);
345 void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
347 struct btrfs_space_info *space_info = bg->space_info;
351 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
355 * Our block group is read only but before we set it to read only,
356 * some task might have had allocated an extent from it already, but it
357 * has not yet created a respective ordered extent (and added it to a
358 * root's list of ordered extents).
359 * Therefore wait for any task currently allocating extents, since the
360 * block group's reservations counter is incremented while a read lock
361 * on the groups' semaphore is held and decremented after releasing
362 * the read access on that semaphore and creating the ordered extent.
364 down_write(&space_info->groups_sem);
365 up_write(&space_info->groups_sem);
367 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
370 struct btrfs_caching_control *btrfs_get_caching_control(
371 struct btrfs_block_group *cache)
373 struct btrfs_caching_control *ctl;
375 spin_lock(&cache->lock);
376 if (!cache->caching_ctl) {
377 spin_unlock(&cache->lock);
381 ctl = cache->caching_ctl;
382 refcount_inc(&ctl->count);
383 spin_unlock(&cache->lock);
387 void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
389 if (refcount_dec_and_test(&ctl->count))
394 * When we wait for progress in the block group caching, its because our
395 * allocation attempt failed at least once. So, we must sleep and let some
396 * progress happen before we try again.
398 * This function will sleep at least once waiting for new free space to show
399 * up, and then it will check the block group free space numbers for our min
400 * num_bytes. Another option is to have it go ahead and look in the rbtree for
401 * a free extent of a given size, but this is a good start.
403 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
404 * any of the information in this block group.
406 void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
409 struct btrfs_caching_control *caching_ctl;
411 caching_ctl = btrfs_get_caching_control(cache);
415 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
416 (cache->free_space_ctl->free_space >= num_bytes));
418 btrfs_put_caching_control(caching_ctl);
421 int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
423 struct btrfs_caching_control *caching_ctl;
426 caching_ctl = btrfs_get_caching_control(cache);
428 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
430 wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
431 if (cache->cached == BTRFS_CACHE_ERROR)
433 btrfs_put_caching_control(caching_ctl);
437 static bool space_cache_v1_done(struct btrfs_block_group *cache)
441 spin_lock(&cache->lock);
442 ret = cache->cached != BTRFS_CACHE_FAST;
443 spin_unlock(&cache->lock);
448 void btrfs_wait_space_cache_v1_finished(struct btrfs_block_group *cache,
449 struct btrfs_caching_control *caching_ctl)
451 wait_event(caching_ctl->wait, space_cache_v1_done(cache));
454 #ifdef CONFIG_BTRFS_DEBUG
455 static void fragment_free_space(struct btrfs_block_group *block_group)
457 struct btrfs_fs_info *fs_info = block_group->fs_info;
458 u64 start = block_group->start;
459 u64 len = block_group->length;
460 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
461 fs_info->nodesize : fs_info->sectorsize;
462 u64 step = chunk << 1;
464 while (len > chunk) {
465 btrfs_remove_free_space(block_group, start, chunk);
476 * This is only called by btrfs_cache_block_group, since we could have freed
477 * extents we need to check the pinned_extents for any extents that can't be
478 * used yet since their free space will be released as soon as the transaction
481 u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
483 struct btrfs_fs_info *info = block_group->fs_info;
484 u64 extent_start, extent_end, size, total_added = 0;
487 while (start < end) {
488 ret = find_first_extent_bit(&info->excluded_extents, start,
489 &extent_start, &extent_end,
490 EXTENT_DIRTY | EXTENT_UPTODATE,
495 if (extent_start <= start) {
496 start = extent_end + 1;
497 } else if (extent_start > start && extent_start < end) {
498 size = extent_start - start;
500 ret = btrfs_add_free_space_async_trimmed(block_group,
502 BUG_ON(ret); /* -ENOMEM or logic error */
503 start = extent_end + 1;
512 ret = btrfs_add_free_space_async_trimmed(block_group, start,
514 BUG_ON(ret); /* -ENOMEM or logic error */
520 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
522 struct btrfs_block_group *block_group = caching_ctl->block_group;
523 struct btrfs_fs_info *fs_info = block_group->fs_info;
524 struct btrfs_root *extent_root = fs_info->extent_root;
525 struct btrfs_path *path;
526 struct extent_buffer *leaf;
527 struct btrfs_key key;
534 path = btrfs_alloc_path();
538 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
540 #ifdef CONFIG_BTRFS_DEBUG
542 * If we're fragmenting we don't want to make anybody think we can
543 * allocate from this block group until we've had a chance to fragment
546 if (btrfs_should_fragment_free_space(block_group))
550 * We don't want to deadlock with somebody trying to allocate a new
551 * extent for the extent root while also trying to search the extent
552 * root to add free space. So we skip locking and search the commit
553 * root, since its read-only
555 path->skip_locking = 1;
556 path->search_commit_root = 1;
557 path->reada = READA_FORWARD;
561 key.type = BTRFS_EXTENT_ITEM_KEY;
564 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
568 leaf = path->nodes[0];
569 nritems = btrfs_header_nritems(leaf);
572 if (btrfs_fs_closing(fs_info) > 1) {
577 if (path->slots[0] < nritems) {
578 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
580 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
584 if (need_resched() ||
585 rwsem_is_contended(&fs_info->commit_root_sem)) {
587 caching_ctl->progress = last;
588 btrfs_release_path(path);
589 up_read(&fs_info->commit_root_sem);
590 mutex_unlock(&caching_ctl->mutex);
592 mutex_lock(&caching_ctl->mutex);
593 down_read(&fs_info->commit_root_sem);
597 ret = btrfs_next_leaf(extent_root, path);
602 leaf = path->nodes[0];
603 nritems = btrfs_header_nritems(leaf);
607 if (key.objectid < last) {
610 key.type = BTRFS_EXTENT_ITEM_KEY;
613 caching_ctl->progress = last;
614 btrfs_release_path(path);
618 if (key.objectid < block_group->start) {
623 if (key.objectid >= block_group->start + block_group->length)
626 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
627 key.type == BTRFS_METADATA_ITEM_KEY) {
628 total_found += add_new_free_space(block_group, last,
630 if (key.type == BTRFS_METADATA_ITEM_KEY)
631 last = key.objectid +
634 last = key.objectid + key.offset;
636 if (total_found > CACHING_CTL_WAKE_UP) {
639 wake_up(&caching_ctl->wait);
646 total_found += add_new_free_space(block_group, last,
647 block_group->start + block_group->length);
648 caching_ctl->progress = (u64)-1;
651 btrfs_free_path(path);
655 static noinline void caching_thread(struct btrfs_work *work)
657 struct btrfs_block_group *block_group;
658 struct btrfs_fs_info *fs_info;
659 struct btrfs_caching_control *caching_ctl;
662 caching_ctl = container_of(work, struct btrfs_caching_control, work);
663 block_group = caching_ctl->block_group;
664 fs_info = block_group->fs_info;
666 mutex_lock(&caching_ctl->mutex);
667 down_read(&fs_info->commit_root_sem);
669 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
670 ret = load_free_space_cache(block_group);
677 * We failed to load the space cache, set ourselves to
678 * CACHE_STARTED and carry on.
680 spin_lock(&block_group->lock);
681 block_group->cached = BTRFS_CACHE_STARTED;
682 spin_unlock(&block_group->lock);
683 wake_up(&caching_ctl->wait);
687 * If we are in the transaction that populated the free space tree we
688 * can't actually cache from the free space tree as our commit root and
689 * real root are the same, so we could change the contents of the blocks
690 * while caching. Instead do the slow caching in this case, and after
691 * the transaction has committed we will be safe.
693 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
694 !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
695 ret = load_free_space_tree(caching_ctl);
697 ret = load_extent_tree_free(caching_ctl);
699 spin_lock(&block_group->lock);
700 block_group->caching_ctl = NULL;
701 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
702 spin_unlock(&block_group->lock);
704 #ifdef CONFIG_BTRFS_DEBUG
705 if (btrfs_should_fragment_free_space(block_group)) {
708 spin_lock(&block_group->space_info->lock);
709 spin_lock(&block_group->lock);
710 bytes_used = block_group->length - block_group->used;
711 block_group->space_info->bytes_used += bytes_used >> 1;
712 spin_unlock(&block_group->lock);
713 spin_unlock(&block_group->space_info->lock);
714 fragment_free_space(block_group);
718 caching_ctl->progress = (u64)-1;
720 up_read(&fs_info->commit_root_sem);
721 btrfs_free_excluded_extents(block_group);
722 mutex_unlock(&caching_ctl->mutex);
724 wake_up(&caching_ctl->wait);
726 btrfs_put_caching_control(caching_ctl);
727 btrfs_put_block_group(block_group);
730 int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
733 struct btrfs_fs_info *fs_info = cache->fs_info;
734 struct btrfs_caching_control *caching_ctl = NULL;
737 /* Allocator for zoned filesystems does not use the cache at all */
738 if (btrfs_is_zoned(fs_info))
741 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
745 INIT_LIST_HEAD(&caching_ctl->list);
746 mutex_init(&caching_ctl->mutex);
747 init_waitqueue_head(&caching_ctl->wait);
748 caching_ctl->block_group = cache;
749 caching_ctl->progress = cache->start;
750 refcount_set(&caching_ctl->count, 2);
751 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
753 spin_lock(&cache->lock);
754 if (cache->cached != BTRFS_CACHE_NO) {
757 caching_ctl = cache->caching_ctl;
759 refcount_inc(&caching_ctl->count);
760 spin_unlock(&cache->lock);
763 WARN_ON(cache->caching_ctl);
764 cache->caching_ctl = caching_ctl;
765 if (btrfs_test_opt(fs_info, SPACE_CACHE))
766 cache->cached = BTRFS_CACHE_FAST;
768 cache->cached = BTRFS_CACHE_STARTED;
769 cache->has_caching_ctl = 1;
770 spin_unlock(&cache->lock);
772 spin_lock(&fs_info->block_group_cache_lock);
773 refcount_inc(&caching_ctl->count);
774 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
775 spin_unlock(&fs_info->block_group_cache_lock);
777 btrfs_get_block_group(cache);
779 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
781 if (load_cache_only && caching_ctl)
782 btrfs_wait_space_cache_v1_finished(cache, caching_ctl);
784 btrfs_put_caching_control(caching_ctl);
789 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
791 u64 extra_flags = chunk_to_extended(flags) &
792 BTRFS_EXTENDED_PROFILE_MASK;
794 write_seqlock(&fs_info->profiles_lock);
795 if (flags & BTRFS_BLOCK_GROUP_DATA)
796 fs_info->avail_data_alloc_bits &= ~extra_flags;
797 if (flags & BTRFS_BLOCK_GROUP_METADATA)
798 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
799 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
800 fs_info->avail_system_alloc_bits &= ~extra_flags;
801 write_sequnlock(&fs_info->profiles_lock);
805 * Clear incompat bits for the following feature(s):
807 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
808 * in the whole filesystem
810 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
812 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
814 bool found_raid56 = false;
815 bool found_raid1c34 = false;
817 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
818 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
819 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
820 struct list_head *head = &fs_info->space_info;
821 struct btrfs_space_info *sinfo;
823 list_for_each_entry_rcu(sinfo, head, list) {
824 down_read(&sinfo->groups_sem);
825 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
827 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
829 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
830 found_raid1c34 = true;
831 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
832 found_raid1c34 = true;
833 up_read(&sinfo->groups_sem);
836 btrfs_clear_fs_incompat(fs_info, RAID56);
838 btrfs_clear_fs_incompat(fs_info, RAID1C34);
842 static int remove_block_group_item(struct btrfs_trans_handle *trans,
843 struct btrfs_path *path,
844 struct btrfs_block_group *block_group)
846 struct btrfs_fs_info *fs_info = trans->fs_info;
847 struct btrfs_root *root;
848 struct btrfs_key key;
851 root = fs_info->extent_root;
852 key.objectid = block_group->start;
853 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
854 key.offset = block_group->length;
856 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
862 ret = btrfs_del_item(trans, root, path);
866 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
867 u64 group_start, struct extent_map *em)
869 struct btrfs_fs_info *fs_info = trans->fs_info;
870 struct btrfs_path *path;
871 struct btrfs_block_group *block_group;
872 struct btrfs_free_cluster *cluster;
874 struct kobject *kobj = NULL;
878 struct btrfs_caching_control *caching_ctl = NULL;
880 bool remove_rsv = false;
882 block_group = btrfs_lookup_block_group(fs_info, group_start);
883 BUG_ON(!block_group);
884 BUG_ON(!block_group->ro);
886 trace_btrfs_remove_block_group(block_group);
888 * Free the reserved super bytes from this block group before
891 btrfs_free_excluded_extents(block_group);
892 btrfs_free_ref_tree_range(fs_info, block_group->start,
893 block_group->length);
895 index = btrfs_bg_flags_to_raid_index(block_group->flags);
896 factor = btrfs_bg_type_to_factor(block_group->flags);
898 /* make sure this block group isn't part of an allocation cluster */
899 cluster = &fs_info->data_alloc_cluster;
900 spin_lock(&cluster->refill_lock);
901 btrfs_return_cluster_to_free_space(block_group, cluster);
902 spin_unlock(&cluster->refill_lock);
905 * make sure this block group isn't part of a metadata
908 cluster = &fs_info->meta_alloc_cluster;
909 spin_lock(&cluster->refill_lock);
910 btrfs_return_cluster_to_free_space(block_group, cluster);
911 spin_unlock(&cluster->refill_lock);
913 btrfs_clear_treelog_bg(block_group);
914 btrfs_clear_data_reloc_bg(block_group);
916 path = btrfs_alloc_path();
923 * get the inode first so any iput calls done for the io_list
924 * aren't the final iput (no unlinks allowed now)
926 inode = lookup_free_space_inode(block_group, path);
928 mutex_lock(&trans->transaction->cache_write_mutex);
930 * Make sure our free space cache IO is done before removing the
933 spin_lock(&trans->transaction->dirty_bgs_lock);
934 if (!list_empty(&block_group->io_list)) {
935 list_del_init(&block_group->io_list);
937 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
939 spin_unlock(&trans->transaction->dirty_bgs_lock);
940 btrfs_wait_cache_io(trans, block_group, path);
941 btrfs_put_block_group(block_group);
942 spin_lock(&trans->transaction->dirty_bgs_lock);
945 if (!list_empty(&block_group->dirty_list)) {
946 list_del_init(&block_group->dirty_list);
948 btrfs_put_block_group(block_group);
950 spin_unlock(&trans->transaction->dirty_bgs_lock);
951 mutex_unlock(&trans->transaction->cache_write_mutex);
953 ret = btrfs_remove_free_space_inode(trans, inode, block_group);
957 spin_lock(&fs_info->block_group_cache_lock);
958 rb_erase(&block_group->cache_node,
959 &fs_info->block_group_cache_tree);
960 RB_CLEAR_NODE(&block_group->cache_node);
962 /* Once for the block groups rbtree */
963 btrfs_put_block_group(block_group);
965 if (fs_info->first_logical_byte == block_group->start)
966 fs_info->first_logical_byte = (u64)-1;
967 spin_unlock(&fs_info->block_group_cache_lock);
969 down_write(&block_group->space_info->groups_sem);
971 * we must use list_del_init so people can check to see if they
972 * are still on the list after taking the semaphore
974 list_del_init(&block_group->list);
975 if (list_empty(&block_group->space_info->block_groups[index])) {
976 kobj = block_group->space_info->block_group_kobjs[index];
977 block_group->space_info->block_group_kobjs[index] = NULL;
978 clear_avail_alloc_bits(fs_info, block_group->flags);
980 up_write(&block_group->space_info->groups_sem);
981 clear_incompat_bg_bits(fs_info, block_group->flags);
987 if (block_group->has_caching_ctl)
988 caching_ctl = btrfs_get_caching_control(block_group);
989 if (block_group->cached == BTRFS_CACHE_STARTED)
990 btrfs_wait_block_group_cache_done(block_group);
991 if (block_group->has_caching_ctl) {
992 spin_lock(&fs_info->block_group_cache_lock);
994 struct btrfs_caching_control *ctl;
996 list_for_each_entry(ctl,
997 &fs_info->caching_block_groups, list)
998 if (ctl->block_group == block_group) {
1000 refcount_inc(&caching_ctl->count);
1005 list_del_init(&caching_ctl->list);
1006 spin_unlock(&fs_info->block_group_cache_lock);
1008 /* Once for the caching bgs list and once for us. */
1009 btrfs_put_caching_control(caching_ctl);
1010 btrfs_put_caching_control(caching_ctl);
1014 spin_lock(&trans->transaction->dirty_bgs_lock);
1015 WARN_ON(!list_empty(&block_group->dirty_list));
1016 WARN_ON(!list_empty(&block_group->io_list));
1017 spin_unlock(&trans->transaction->dirty_bgs_lock);
1019 btrfs_remove_free_space_cache(block_group);
1021 spin_lock(&block_group->space_info->lock);
1022 list_del_init(&block_group->ro_list);
1024 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1025 WARN_ON(block_group->space_info->total_bytes
1026 < block_group->length);
1027 WARN_ON(block_group->space_info->bytes_readonly
1028 < block_group->length - block_group->zone_unusable);
1029 WARN_ON(block_group->space_info->bytes_zone_unusable
1030 < block_group->zone_unusable);
1031 WARN_ON(block_group->space_info->disk_total
1032 < block_group->length * factor);
1034 block_group->space_info->total_bytes -= block_group->length;
1035 block_group->space_info->bytes_readonly -=
1036 (block_group->length - block_group->zone_unusable);
1037 block_group->space_info->bytes_zone_unusable -=
1038 block_group->zone_unusable;
1039 block_group->space_info->disk_total -= block_group->length * factor;
1041 spin_unlock(&block_group->space_info->lock);
1044 * Remove the free space for the block group from the free space tree
1045 * and the block group's item from the extent tree before marking the
1046 * block group as removed. This is to prevent races with tasks that
1047 * freeze and unfreeze a block group, this task and another task
1048 * allocating a new block group - the unfreeze task ends up removing
1049 * the block group's extent map before the task calling this function
1050 * deletes the block group item from the extent tree, allowing for
1051 * another task to attempt to create another block group with the same
1052 * item key (and failing with -EEXIST and a transaction abort).
1054 ret = remove_block_group_free_space(trans, block_group);
1058 ret = remove_block_group_item(trans, path, block_group);
1062 spin_lock(&block_group->lock);
1063 block_group->removed = 1;
1065 * At this point trimming or scrub can't start on this block group,
1066 * because we removed the block group from the rbtree
1067 * fs_info->block_group_cache_tree so no one can't find it anymore and
1068 * even if someone already got this block group before we removed it
1069 * from the rbtree, they have already incremented block_group->frozen -
1070 * if they didn't, for the trimming case they won't find any free space
1071 * entries because we already removed them all when we called
1072 * btrfs_remove_free_space_cache().
1074 * And we must not remove the extent map from the fs_info->mapping_tree
1075 * to prevent the same logical address range and physical device space
1076 * ranges from being reused for a new block group. This is needed to
1077 * avoid races with trimming and scrub.
1079 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1080 * completely transactionless, so while it is trimming a range the
1081 * currently running transaction might finish and a new one start,
1082 * allowing for new block groups to be created that can reuse the same
1083 * physical device locations unless we take this special care.
1085 * There may also be an implicit trim operation if the file system
1086 * is mounted with -odiscard. The same protections must remain
1087 * in place until the extents have been discarded completely when
1088 * the transaction commit has completed.
1090 remove_em = (atomic_read(&block_group->frozen) == 0);
1091 spin_unlock(&block_group->lock);
1094 struct extent_map_tree *em_tree;
1096 em_tree = &fs_info->mapping_tree;
1097 write_lock(&em_tree->lock);
1098 remove_extent_mapping(em_tree, em);
1099 write_unlock(&em_tree->lock);
1100 /* once for the tree */
1101 free_extent_map(em);
1105 /* Once for the lookup reference */
1106 btrfs_put_block_group(block_group);
1108 btrfs_delayed_refs_rsv_release(fs_info, 1);
1109 btrfs_free_path(path);
1113 struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1114 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1116 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1117 struct extent_map *em;
1118 struct map_lookup *map;
1119 unsigned int num_items;
1121 read_lock(&em_tree->lock);
1122 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1123 read_unlock(&em_tree->lock);
1124 ASSERT(em && em->start == chunk_offset);
1127 * We need to reserve 3 + N units from the metadata space info in order
1128 * to remove a block group (done at btrfs_remove_chunk() and at
1129 * btrfs_remove_block_group()), which are used for:
1131 * 1 unit for adding the free space inode's orphan (located in the tree
1133 * 1 unit for deleting the block group item (located in the extent
1135 * 1 unit for deleting the free space item (located in tree of tree
1137 * N units for deleting N device extent items corresponding to each
1138 * stripe (located in the device tree).
1140 * In order to remove a block group we also need to reserve units in the
1141 * system space info in order to update the chunk tree (update one or
1142 * more device items and remove one chunk item), but this is done at
1143 * btrfs_remove_chunk() through a call to check_system_chunk().
1145 map = em->map_lookup;
1146 num_items = 3 + map->num_stripes;
1147 free_extent_map(em);
1149 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
1154 * Mark block group @cache read-only, so later write won't happen to block
1157 * If @force is not set, this function will only mark the block group readonly
1158 * if we have enough free space (1M) in other metadata/system block groups.
1159 * If @force is not set, this function will mark the block group readonly
1160 * without checking free space.
1162 * NOTE: This function doesn't care if other block groups can contain all the
1163 * data in this block group. That check should be done by relocation routine,
1164 * not this function.
1166 static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
1168 struct btrfs_space_info *sinfo = cache->space_info;
1172 spin_lock(&sinfo->lock);
1173 spin_lock(&cache->lock);
1175 if (cache->swap_extents) {
1186 num_bytes = cache->length - cache->reserved - cache->pinned -
1187 cache->bytes_super - cache->zone_unusable - cache->used;
1190 * Data never overcommits, even in mixed mode, so do just the straight
1191 * check of left over space in how much we have allocated.
1195 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1196 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1199 * Here we make sure if we mark this bg RO, we still have enough
1200 * free space as buffer.
1202 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1206 * We overcommit metadata, so we need to do the
1207 * btrfs_can_overcommit check here, and we need to pass in
1208 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1209 * leeway to allow us to mark this block group as read only.
1211 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1212 BTRFS_RESERVE_NO_FLUSH))
1217 sinfo->bytes_readonly += num_bytes;
1218 if (btrfs_is_zoned(cache->fs_info)) {
1219 /* Migrate zone_unusable bytes to readonly */
1220 sinfo->bytes_readonly += cache->zone_unusable;
1221 sinfo->bytes_zone_unusable -= cache->zone_unusable;
1222 cache->zone_unusable = 0;
1225 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
1228 spin_unlock(&cache->lock);
1229 spin_unlock(&sinfo->lock);
1230 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1231 btrfs_info(cache->fs_info,
1232 "unable to make block group %llu ro", cache->start);
1233 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1238 static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1239 struct btrfs_block_group *bg)
1241 struct btrfs_fs_info *fs_info = bg->fs_info;
1242 struct btrfs_transaction *prev_trans = NULL;
1243 const u64 start = bg->start;
1244 const u64 end = start + bg->length - 1;
1247 spin_lock(&fs_info->trans_lock);
1248 if (trans->transaction->list.prev != &fs_info->trans_list) {
1249 prev_trans = list_last_entry(&trans->transaction->list,
1250 struct btrfs_transaction, list);
1251 refcount_inc(&prev_trans->use_count);
1253 spin_unlock(&fs_info->trans_lock);
1256 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1257 * btrfs_finish_extent_commit(). If we are at transaction N, another
1258 * task might be running finish_extent_commit() for the previous
1259 * transaction N - 1, and have seen a range belonging to the block
1260 * group in pinned_extents before we were able to clear the whole block
1261 * group range from pinned_extents. This means that task can lookup for
1262 * the block group after we unpinned it from pinned_extents and removed
1263 * it, leading to a BUG_ON() at unpin_extent_range().
1265 mutex_lock(&fs_info->unused_bg_unpin_mutex);
1267 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1273 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
1276 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1278 btrfs_put_transaction(prev_trans);
1284 * Process the unused_bgs list and remove any that don't have any allocated
1285 * space inside of them.
1287 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1289 struct btrfs_block_group *block_group;
1290 struct btrfs_space_info *space_info;
1291 struct btrfs_trans_handle *trans;
1292 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1295 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1299 * Long running balances can keep us blocked here for eternity, so
1300 * simply skip deletion if we're unable to get the mutex.
1302 if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
1305 spin_lock(&fs_info->unused_bgs_lock);
1306 while (!list_empty(&fs_info->unused_bgs)) {
1309 block_group = list_first_entry(&fs_info->unused_bgs,
1310 struct btrfs_block_group,
1312 list_del_init(&block_group->bg_list);
1314 space_info = block_group->space_info;
1316 if (ret || btrfs_mixed_space_info(space_info)) {
1317 btrfs_put_block_group(block_group);
1320 spin_unlock(&fs_info->unused_bgs_lock);
1322 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1324 /* Don't want to race with allocators so take the groups_sem */
1325 down_write(&space_info->groups_sem);
1328 * Async discard moves the final block group discard to be prior
1329 * to the unused_bgs code path. Therefore, if it's not fully
1330 * trimmed, punt it back to the async discard lists.
1332 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1333 !btrfs_is_free_space_trimmed(block_group)) {
1334 trace_btrfs_skip_unused_block_group(block_group);
1335 up_write(&space_info->groups_sem);
1336 /* Requeue if we failed because of async discard */
1337 btrfs_discard_queue_work(&fs_info->discard_ctl,
1342 spin_lock(&block_group->lock);
1343 if (block_group->reserved || block_group->pinned ||
1344 block_group->used || block_group->ro ||
1345 list_is_singular(&block_group->list)) {
1347 * We want to bail if we made new allocations or have
1348 * outstanding allocations in this block group. We do
1349 * the ro check in case balance is currently acting on
1352 trace_btrfs_skip_unused_block_group(block_group);
1353 spin_unlock(&block_group->lock);
1354 up_write(&space_info->groups_sem);
1357 spin_unlock(&block_group->lock);
1359 /* We don't want to force the issue, only flip if it's ok. */
1360 ret = inc_block_group_ro(block_group, 0);
1361 up_write(&space_info->groups_sem);
1368 * Want to do this before we do anything else so we can recover
1369 * properly if we fail to join the transaction.
1371 trans = btrfs_start_trans_remove_block_group(fs_info,
1372 block_group->start);
1373 if (IS_ERR(trans)) {
1374 btrfs_dec_block_group_ro(block_group);
1375 ret = PTR_ERR(trans);
1380 * We could have pending pinned extents for this block group,
1381 * just delete them, we don't care about them anymore.
1383 if (!clean_pinned_extents(trans, block_group)) {
1384 btrfs_dec_block_group_ro(block_group);
1389 * At this point, the block_group is read only and should fail
1390 * new allocations. However, btrfs_finish_extent_commit() can
1391 * cause this block_group to be placed back on the discard
1392 * lists because now the block_group isn't fully discarded.
1393 * Bail here and try again later after discarding everything.
1395 spin_lock(&fs_info->discard_ctl.lock);
1396 if (!list_empty(&block_group->discard_list)) {
1397 spin_unlock(&fs_info->discard_ctl.lock);
1398 btrfs_dec_block_group_ro(block_group);
1399 btrfs_discard_queue_work(&fs_info->discard_ctl,
1403 spin_unlock(&fs_info->discard_ctl.lock);
1405 /* Reset pinned so btrfs_put_block_group doesn't complain */
1406 spin_lock(&space_info->lock);
1407 spin_lock(&block_group->lock);
1409 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1410 -block_group->pinned);
1411 space_info->bytes_readonly += block_group->pinned;
1412 block_group->pinned = 0;
1414 spin_unlock(&block_group->lock);
1415 spin_unlock(&space_info->lock);
1418 * The normal path here is an unused block group is passed here,
1419 * then trimming is handled in the transaction commit path.
1420 * Async discard interposes before this to do the trimming
1421 * before coming down the unused block group path as trimming
1422 * will no longer be done later in the transaction commit path.
1424 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1428 * DISCARD can flip during remount. On zoned filesystems, we
1429 * need to reset sequential-required zones.
1431 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) ||
1432 btrfs_is_zoned(fs_info);
1434 /* Implicit trim during transaction commit. */
1436 btrfs_freeze_block_group(block_group);
1439 * Btrfs_remove_chunk will abort the transaction if things go
1442 ret = btrfs_remove_chunk(trans, block_group->start);
1446 btrfs_unfreeze_block_group(block_group);
1451 * If we're not mounted with -odiscard, we can just forget
1452 * about this block group. Otherwise we'll need to wait
1453 * until transaction commit to do the actual discard.
1456 spin_lock(&fs_info->unused_bgs_lock);
1458 * A concurrent scrub might have added us to the list
1459 * fs_info->unused_bgs, so use a list_move operation
1460 * to add the block group to the deleted_bgs list.
1462 list_move(&block_group->bg_list,
1463 &trans->transaction->deleted_bgs);
1464 spin_unlock(&fs_info->unused_bgs_lock);
1465 btrfs_get_block_group(block_group);
1468 btrfs_end_transaction(trans);
1470 btrfs_put_block_group(block_group);
1471 spin_lock(&fs_info->unused_bgs_lock);
1473 spin_unlock(&fs_info->unused_bgs_lock);
1474 mutex_unlock(&fs_info->reclaim_bgs_lock);
1478 btrfs_end_transaction(trans);
1479 mutex_unlock(&fs_info->reclaim_bgs_lock);
1480 btrfs_put_block_group(block_group);
1481 btrfs_discard_punt_unused_bgs_list(fs_info);
1484 void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1486 struct btrfs_fs_info *fs_info = bg->fs_info;
1488 spin_lock(&fs_info->unused_bgs_lock);
1489 if (list_empty(&bg->bg_list)) {
1490 btrfs_get_block_group(bg);
1491 trace_btrfs_add_unused_block_group(bg);
1492 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1494 spin_unlock(&fs_info->unused_bgs_lock);
1497 void btrfs_reclaim_bgs_work(struct work_struct *work)
1499 struct btrfs_fs_info *fs_info =
1500 container_of(work, struct btrfs_fs_info, reclaim_bgs_work);
1501 struct btrfs_block_group *bg;
1502 struct btrfs_space_info *space_info;
1504 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1507 sb_start_write(fs_info->sb);
1509 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
1510 sb_end_write(fs_info->sb);
1515 * Long running balances can keep us blocked here for eternity, so
1516 * simply skip reclaim if we're unable to get the mutex.
1518 if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) {
1519 btrfs_exclop_finish(fs_info);
1520 sb_end_write(fs_info->sb);
1524 spin_lock(&fs_info->unused_bgs_lock);
1525 while (!list_empty(&fs_info->reclaim_bgs)) {
1529 bg = list_first_entry(&fs_info->reclaim_bgs,
1530 struct btrfs_block_group,
1532 list_del_init(&bg->bg_list);
1534 space_info = bg->space_info;
1535 spin_unlock(&fs_info->unused_bgs_lock);
1537 /* Don't race with allocators so take the groups_sem */
1538 down_write(&space_info->groups_sem);
1540 spin_lock(&bg->lock);
1541 if (bg->reserved || bg->pinned || bg->ro) {
1543 * We want to bail if we made new allocations or have
1544 * outstanding allocations in this block group. We do
1545 * the ro check in case balance is currently acting on
1548 spin_unlock(&bg->lock);
1549 up_write(&space_info->groups_sem);
1552 spin_unlock(&bg->lock);
1554 /* Get out fast, in case we're unmounting the filesystem */
1555 if (btrfs_fs_closing(fs_info)) {
1556 up_write(&space_info->groups_sem);
1561 * Cache the zone_unusable value before turning the block group
1562 * to read only. As soon as the blog group is read only it's
1563 * zone_unusable value gets moved to the block group's read-only
1564 * bytes and isn't available for calculations anymore.
1566 zone_unusable = bg->zone_unusable;
1567 ret = inc_block_group_ro(bg, 0);
1568 up_write(&space_info->groups_sem);
1573 "reclaiming chunk %llu with %llu%% used %llu%% unusable",
1574 bg->start, div_u64(bg->used * 100, bg->length),
1575 div64_u64(zone_unusable * 100, bg->length));
1576 trace_btrfs_reclaim_block_group(bg);
1577 ret = btrfs_relocate_chunk(fs_info, bg->start);
1579 btrfs_err(fs_info, "error relocating chunk %llu",
1583 btrfs_put_block_group(bg);
1584 spin_lock(&fs_info->unused_bgs_lock);
1586 spin_unlock(&fs_info->unused_bgs_lock);
1587 mutex_unlock(&fs_info->reclaim_bgs_lock);
1588 btrfs_exclop_finish(fs_info);
1589 sb_end_write(fs_info->sb);
1592 void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
1594 spin_lock(&fs_info->unused_bgs_lock);
1595 if (!list_empty(&fs_info->reclaim_bgs))
1596 queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
1597 spin_unlock(&fs_info->unused_bgs_lock);
1600 void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
1602 struct btrfs_fs_info *fs_info = bg->fs_info;
1604 spin_lock(&fs_info->unused_bgs_lock);
1605 if (list_empty(&bg->bg_list)) {
1606 btrfs_get_block_group(bg);
1607 trace_btrfs_add_reclaim_block_group(bg);
1608 list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
1610 spin_unlock(&fs_info->unused_bgs_lock);
1613 static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1614 struct btrfs_path *path)
1616 struct extent_map_tree *em_tree;
1617 struct extent_map *em;
1618 struct btrfs_block_group_item bg;
1619 struct extent_buffer *leaf;
1624 slot = path->slots[0];
1625 leaf = path->nodes[0];
1627 em_tree = &fs_info->mapping_tree;
1628 read_lock(&em_tree->lock);
1629 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1630 read_unlock(&em_tree->lock);
1633 "logical %llu len %llu found bg but no related chunk",
1634 key->objectid, key->offset);
1638 if (em->start != key->objectid || em->len != key->offset) {
1640 "block group %llu len %llu mismatch with chunk %llu len %llu",
1641 key->objectid, key->offset, em->start, em->len);
1646 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1648 flags = btrfs_stack_block_group_flags(&bg) &
1649 BTRFS_BLOCK_GROUP_TYPE_MASK;
1651 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1653 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1654 key->objectid, key->offset, flags,
1655 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1660 free_extent_map(em);
1664 static int find_first_block_group(struct btrfs_fs_info *fs_info,
1665 struct btrfs_path *path,
1666 struct btrfs_key *key)
1668 struct btrfs_root *root = fs_info->extent_root;
1670 struct btrfs_key found_key;
1671 struct extent_buffer *leaf;
1674 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1679 slot = path->slots[0];
1680 leaf = path->nodes[0];
1681 if (slot >= btrfs_header_nritems(leaf)) {
1682 ret = btrfs_next_leaf(root, path);
1689 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1691 if (found_key.objectid >= key->objectid &&
1692 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1693 ret = read_bg_from_eb(fs_info, &found_key, path);
1703 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1705 u64 extra_flags = chunk_to_extended(flags) &
1706 BTRFS_EXTENDED_PROFILE_MASK;
1708 write_seqlock(&fs_info->profiles_lock);
1709 if (flags & BTRFS_BLOCK_GROUP_DATA)
1710 fs_info->avail_data_alloc_bits |= extra_flags;
1711 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1712 fs_info->avail_metadata_alloc_bits |= extra_flags;
1713 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1714 fs_info->avail_system_alloc_bits |= extra_flags;
1715 write_sequnlock(&fs_info->profiles_lock);
1719 * Map a physical disk address to a list of logical addresses
1721 * @fs_info: the filesystem
1722 * @chunk_start: logical address of block group
1723 * @bdev: physical device to resolve, can be NULL to indicate any device
1724 * @physical: physical address to map to logical addresses
1725 * @logical: return array of logical addresses which map to @physical
1726 * @naddrs: length of @logical
1727 * @stripe_len: size of IO stripe for the given block group
1729 * Maps a particular @physical disk address to a list of @logical addresses.
1730 * Used primarily to exclude those portions of a block group that contain super
1733 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1734 struct block_device *bdev, u64 physical, u64 **logical,
1735 int *naddrs, int *stripe_len)
1737 struct extent_map *em;
1738 struct map_lookup *map;
1741 u64 data_stripe_length;
1746 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1750 map = em->map_lookup;
1751 data_stripe_length = em->orig_block_len;
1752 io_stripe_size = map->stripe_len;
1753 chunk_start = em->start;
1755 /* For RAID5/6 adjust to a full IO stripe length */
1756 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
1757 io_stripe_size = map->stripe_len * nr_data_stripes(map);
1759 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
1765 for (i = 0; i < map->num_stripes; i++) {
1766 bool already_inserted = false;
1771 if (!in_range(physical, map->stripes[i].physical,
1772 data_stripe_length))
1775 if (bdev && map->stripes[i].dev->bdev != bdev)
1778 stripe_nr = physical - map->stripes[i].physical;
1779 stripe_nr = div64_u64_rem(stripe_nr, map->stripe_len, &offset);
1781 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1782 stripe_nr = stripe_nr * map->num_stripes + i;
1783 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1784 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1785 stripe_nr = stripe_nr * map->num_stripes + i;
1788 * The remaining case would be for RAID56, multiply by
1789 * nr_data_stripes(). Alternatively, just use rmap_len below
1790 * instead of map->stripe_len
1793 bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
1795 /* Ensure we don't add duplicate addresses */
1796 for (j = 0; j < nr; j++) {
1797 if (buf[j] == bytenr) {
1798 already_inserted = true;
1803 if (!already_inserted)
1809 *stripe_len = io_stripe_size;
1811 free_extent_map(em);
1815 static int exclude_super_stripes(struct btrfs_block_group *cache)
1817 struct btrfs_fs_info *fs_info = cache->fs_info;
1818 const bool zoned = btrfs_is_zoned(fs_info);
1824 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1825 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
1826 cache->bytes_super += stripe_len;
1827 ret = btrfs_add_excluded_extent(fs_info, cache->start,
1833 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1834 bytenr = btrfs_sb_offset(i);
1835 ret = btrfs_rmap_block(fs_info, cache->start, NULL,
1836 bytenr, &logical, &nr, &stripe_len);
1840 /* Shouldn't have super stripes in sequential zones */
1843 "zoned: block group %llu must not contain super block",
1849 u64 len = min_t(u64, stripe_len,
1850 cache->start + cache->length - logical[nr]);
1852 cache->bytes_super += len;
1853 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
1866 static void link_block_group(struct btrfs_block_group *cache)
1868 struct btrfs_space_info *space_info = cache->space_info;
1869 int index = btrfs_bg_flags_to_raid_index(cache->flags);
1871 down_write(&space_info->groups_sem);
1872 list_add_tail(&cache->list, &space_info->block_groups[index]);
1873 up_write(&space_info->groups_sem);
1876 static struct btrfs_block_group *btrfs_create_block_group_cache(
1877 struct btrfs_fs_info *fs_info, u64 start)
1879 struct btrfs_block_group *cache;
1881 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1885 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1887 if (!cache->free_space_ctl) {
1892 cache->start = start;
1894 cache->fs_info = fs_info;
1895 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
1897 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1899 refcount_set(&cache->refs, 1);
1900 spin_lock_init(&cache->lock);
1901 init_rwsem(&cache->data_rwsem);
1902 INIT_LIST_HEAD(&cache->list);
1903 INIT_LIST_HEAD(&cache->cluster_list);
1904 INIT_LIST_HEAD(&cache->bg_list);
1905 INIT_LIST_HEAD(&cache->ro_list);
1906 INIT_LIST_HEAD(&cache->discard_list);
1907 INIT_LIST_HEAD(&cache->dirty_list);
1908 INIT_LIST_HEAD(&cache->io_list);
1909 btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
1910 atomic_set(&cache->frozen, 0);
1911 mutex_init(&cache->free_space_lock);
1912 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1918 * Iterate all chunks and verify that each of them has the corresponding block
1921 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1923 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1924 struct extent_map *em;
1925 struct btrfs_block_group *bg;
1930 read_lock(&map_tree->lock);
1932 * lookup_extent_mapping will return the first extent map
1933 * intersecting the range, so setting @len to 1 is enough to
1934 * get the first chunk.
1936 em = lookup_extent_mapping(map_tree, start, 1);
1937 read_unlock(&map_tree->lock);
1941 bg = btrfs_lookup_block_group(fs_info, em->start);
1944 "chunk start=%llu len=%llu doesn't have corresponding block group",
1945 em->start, em->len);
1947 free_extent_map(em);
1950 if (bg->start != em->start || bg->length != em->len ||
1951 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1952 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1954 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
1956 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
1957 bg->start, bg->length,
1958 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
1960 free_extent_map(em);
1961 btrfs_put_block_group(bg);
1964 start = em->start + em->len;
1965 free_extent_map(em);
1966 btrfs_put_block_group(bg);
1971 static int read_one_block_group(struct btrfs_fs_info *info,
1972 struct btrfs_block_group_item *bgi,
1973 const struct btrfs_key *key,
1976 struct btrfs_block_group *cache;
1977 struct btrfs_space_info *space_info;
1978 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
1981 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
1983 cache = btrfs_create_block_group_cache(info, key->objectid);
1987 cache->length = key->offset;
1988 cache->used = btrfs_stack_block_group_used(bgi);
1989 cache->flags = btrfs_stack_block_group_flags(bgi);
1991 set_free_space_tree_thresholds(cache);
1995 * When we mount with old space cache, we need to
1996 * set BTRFS_DC_CLEAR and set dirty flag.
1998 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
1999 * truncate the old free space cache inode and
2001 * b) Setting 'dirty flag' makes sure that we flush
2002 * the new space cache info onto disk.
2004 if (btrfs_test_opt(info, SPACE_CACHE))
2005 cache->disk_cache_state = BTRFS_DC_CLEAR;
2007 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
2008 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
2010 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2016 ret = btrfs_load_block_group_zone_info(cache, false);
2018 btrfs_err(info, "zoned: failed to load zone info of bg %llu",
2024 * We need to exclude the super stripes now so that the space info has
2025 * super bytes accounted for, otherwise we'll think we have more space
2026 * than we actually do.
2028 ret = exclude_super_stripes(cache);
2030 /* We may have excluded something, so call this just in case. */
2031 btrfs_free_excluded_extents(cache);
2036 * For zoned filesystem, space after the allocation offset is the only
2037 * free space for a block group. So, we don't need any caching work.
2038 * btrfs_calc_zone_unusable() will set the amount of free space and
2039 * zone_unusable space.
2041 * For regular filesystem, check for two cases, either we are full, and
2042 * therefore don't need to bother with the caching work since we won't
2043 * find any space, or we are empty, and we can just add all the space
2044 * in and be done with it. This saves us _a_lot_ of time, particularly
2047 if (btrfs_is_zoned(info)) {
2048 btrfs_calc_zone_unusable(cache);
2049 } else if (cache->length == cache->used) {
2050 cache->last_byte_to_unpin = (u64)-1;
2051 cache->cached = BTRFS_CACHE_FINISHED;
2052 btrfs_free_excluded_extents(cache);
2053 } else if (cache->used == 0) {
2054 cache->last_byte_to_unpin = (u64)-1;
2055 cache->cached = BTRFS_CACHE_FINISHED;
2056 add_new_free_space(cache, cache->start,
2057 cache->start + cache->length);
2058 btrfs_free_excluded_extents(cache);
2061 ret = btrfs_add_block_group_cache(info, cache);
2063 btrfs_remove_free_space_cache(cache);
2066 trace_btrfs_add_block_group(info, cache, 0);
2067 btrfs_update_space_info(info, cache->flags, cache->length,
2068 cache->used, cache->bytes_super,
2069 cache->zone_unusable, &space_info);
2071 cache->space_info = space_info;
2073 link_block_group(cache);
2075 set_avail_alloc_bits(info, cache->flags);
2076 if (btrfs_chunk_readonly(info, cache->start)) {
2077 inc_block_group_ro(cache, 1);
2078 } else if (cache->used == 0) {
2079 ASSERT(list_empty(&cache->bg_list));
2080 if (btrfs_test_opt(info, DISCARD_ASYNC))
2081 btrfs_discard_queue_work(&info->discard_ctl, cache);
2083 btrfs_mark_bg_unused(cache);
2087 btrfs_put_block_group(cache);
2091 static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
2093 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
2094 struct btrfs_space_info *space_info;
2095 struct rb_node *node;
2098 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
2099 struct extent_map *em;
2100 struct map_lookup *map;
2101 struct btrfs_block_group *bg;
2103 em = rb_entry(node, struct extent_map, rb_node);
2104 map = em->map_lookup;
2105 bg = btrfs_create_block_group_cache(fs_info, em->start);
2111 /* Fill dummy cache as FULL */
2112 bg->length = em->len;
2113 bg->flags = map->type;
2114 bg->last_byte_to_unpin = (u64)-1;
2115 bg->cached = BTRFS_CACHE_FINISHED;
2117 bg->flags = map->type;
2118 ret = btrfs_add_block_group_cache(fs_info, bg);
2120 * We may have some valid block group cache added already, in
2121 * that case we skip to the next one.
2123 if (ret == -EEXIST) {
2125 btrfs_put_block_group(bg);
2130 btrfs_remove_free_space_cache(bg);
2131 btrfs_put_block_group(bg);
2135 btrfs_update_space_info(fs_info, bg->flags, em->len, em->len,
2137 bg->space_info = space_info;
2138 link_block_group(bg);
2140 set_avail_alloc_bits(fs_info, bg->flags);
2143 btrfs_init_global_block_rsv(fs_info);
2147 int btrfs_read_block_groups(struct btrfs_fs_info *info)
2149 struct btrfs_path *path;
2151 struct btrfs_block_group *cache;
2152 struct btrfs_space_info *space_info;
2153 struct btrfs_key key;
2157 if (!info->extent_root)
2158 return fill_dummy_bgs(info);
2162 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2163 path = btrfs_alloc_path();
2167 cache_gen = btrfs_super_cache_generation(info->super_copy);
2168 if (btrfs_test_opt(info, SPACE_CACHE) &&
2169 btrfs_super_generation(info->super_copy) != cache_gen)
2171 if (btrfs_test_opt(info, CLEAR_CACHE))
2175 struct btrfs_block_group_item bgi;
2176 struct extent_buffer *leaf;
2179 ret = find_first_block_group(info, path, &key);
2185 leaf = path->nodes[0];
2186 slot = path->slots[0];
2188 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
2191 btrfs_item_key_to_cpu(leaf, &key, slot);
2192 btrfs_release_path(path);
2193 ret = read_one_block_group(info, &bgi, &key, need_clear);
2196 key.objectid += key.offset;
2199 btrfs_release_path(path);
2201 list_for_each_entry(space_info, &info->space_info, list) {
2204 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2205 if (list_empty(&space_info->block_groups[i]))
2207 cache = list_first_entry(&space_info->block_groups[i],
2208 struct btrfs_block_group,
2210 btrfs_sysfs_add_block_group_type(cache);
2213 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2214 (BTRFS_BLOCK_GROUP_RAID10 |
2215 BTRFS_BLOCK_GROUP_RAID1_MASK |
2216 BTRFS_BLOCK_GROUP_RAID56_MASK |
2217 BTRFS_BLOCK_GROUP_DUP)))
2220 * Avoid allocating from un-mirrored block group if there are
2221 * mirrored block groups.
2223 list_for_each_entry(cache,
2224 &space_info->block_groups[BTRFS_RAID_RAID0],
2226 inc_block_group_ro(cache, 1);
2227 list_for_each_entry(cache,
2228 &space_info->block_groups[BTRFS_RAID_SINGLE],
2230 inc_block_group_ro(cache, 1);
2233 btrfs_init_global_block_rsv(info);
2234 ret = check_chunk_block_group_mappings(info);
2236 btrfs_free_path(path);
2238 * We've hit some error while reading the extent tree, and have
2239 * rescue=ibadroots mount option.
2240 * Try to fill the tree using dummy block groups so that the user can
2241 * continue to mount and grab their data.
2243 if (ret && btrfs_test_opt(info, IGNOREBADROOTS))
2244 ret = fill_dummy_bgs(info);
2249 * This function, insert_block_group_item(), belongs to the phase 2 of chunk
2252 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2255 static int insert_block_group_item(struct btrfs_trans_handle *trans,
2256 struct btrfs_block_group *block_group)
2258 struct btrfs_fs_info *fs_info = trans->fs_info;
2259 struct btrfs_block_group_item bgi;
2260 struct btrfs_root *root;
2261 struct btrfs_key key;
2263 spin_lock(&block_group->lock);
2264 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2265 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2266 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2267 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2268 key.objectid = block_group->start;
2269 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2270 key.offset = block_group->length;
2271 spin_unlock(&block_group->lock);
2273 root = fs_info->extent_root;
2274 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2277 static int insert_dev_extent(struct btrfs_trans_handle *trans,
2278 struct btrfs_device *device, u64 chunk_offset,
2279 u64 start, u64 num_bytes)
2281 struct btrfs_fs_info *fs_info = device->fs_info;
2282 struct btrfs_root *root = fs_info->dev_root;
2283 struct btrfs_path *path;
2284 struct btrfs_dev_extent *extent;
2285 struct extent_buffer *leaf;
2286 struct btrfs_key key;
2289 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
2290 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
2291 path = btrfs_alloc_path();
2295 key.objectid = device->devid;
2296 key.type = BTRFS_DEV_EXTENT_KEY;
2298 ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent));
2302 leaf = path->nodes[0];
2303 extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
2304 btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID);
2305 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
2306 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2307 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
2309 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
2310 btrfs_mark_buffer_dirty(leaf);
2312 btrfs_free_path(path);
2317 * This function belongs to phase 2.
2319 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2322 static int insert_dev_extents(struct btrfs_trans_handle *trans,
2323 u64 chunk_offset, u64 chunk_size)
2325 struct btrfs_fs_info *fs_info = trans->fs_info;
2326 struct btrfs_device *device;
2327 struct extent_map *em;
2328 struct map_lookup *map;
2334 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
2338 map = em->map_lookup;
2339 stripe_size = em->orig_block_len;
2342 * Take the device list mutex to prevent races with the final phase of
2343 * a device replace operation that replaces the device object associated
2344 * with the map's stripes, because the device object's id can change
2345 * at any time during that final phase of the device replace operation
2346 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
2347 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
2348 * resulting in persisting a device extent item with such ID.
2350 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2351 for (i = 0; i < map->num_stripes; i++) {
2352 device = map->stripes[i].dev;
2353 dev_offset = map->stripes[i].physical;
2355 ret = insert_dev_extent(trans, device, chunk_offset, dev_offset,
2360 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2362 free_extent_map(em);
2367 * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
2370 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2373 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2375 struct btrfs_fs_info *fs_info = trans->fs_info;
2376 struct btrfs_block_group *block_group;
2379 while (!list_empty(&trans->new_bgs)) {
2382 block_group = list_first_entry(&trans->new_bgs,
2383 struct btrfs_block_group,
2388 index = btrfs_bg_flags_to_raid_index(block_group->flags);
2390 ret = insert_block_group_item(trans, block_group);
2392 btrfs_abort_transaction(trans, ret);
2393 if (!block_group->chunk_item_inserted) {
2394 mutex_lock(&fs_info->chunk_mutex);
2395 ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group);
2396 mutex_unlock(&fs_info->chunk_mutex);
2398 btrfs_abort_transaction(trans, ret);
2400 ret = insert_dev_extents(trans, block_group->start,
2401 block_group->length);
2403 btrfs_abort_transaction(trans, ret);
2404 add_block_group_free_space(trans, block_group);
2407 * If we restriped during balance, we may have added a new raid
2408 * type, so now add the sysfs entries when it is safe to do so.
2409 * We don't have to worry about locking here as it's handled in
2410 * btrfs_sysfs_add_block_group_type.
2412 if (block_group->space_info->block_group_kobjs[index] == NULL)
2413 btrfs_sysfs_add_block_group_type(block_group);
2415 /* Already aborted the transaction if it failed. */
2417 btrfs_delayed_refs_rsv_release(fs_info, 1);
2418 list_del_init(&block_group->bg_list);
2420 btrfs_trans_release_chunk_metadata(trans);
2423 struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
2424 u64 bytes_used, u64 type,
2425 u64 chunk_offset, u64 size)
2427 struct btrfs_fs_info *fs_info = trans->fs_info;
2428 struct btrfs_block_group *cache;
2431 btrfs_set_log_full_commit(trans);
2433 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
2435 return ERR_PTR(-ENOMEM);
2437 cache->length = size;
2438 set_free_space_tree_thresholds(cache);
2439 cache->used = bytes_used;
2440 cache->flags = type;
2441 cache->last_byte_to_unpin = (u64)-1;
2442 cache->cached = BTRFS_CACHE_FINISHED;
2443 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
2444 cache->needs_free_space = 1;
2446 ret = btrfs_load_block_group_zone_info(cache, true);
2448 btrfs_put_block_group(cache);
2449 return ERR_PTR(ret);
2452 ret = exclude_super_stripes(cache);
2454 /* We may have excluded something, so call this just in case */
2455 btrfs_free_excluded_extents(cache);
2456 btrfs_put_block_group(cache);
2457 return ERR_PTR(ret);
2460 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2462 btrfs_free_excluded_extents(cache);
2464 #ifdef CONFIG_BTRFS_DEBUG
2465 if (btrfs_should_fragment_free_space(cache)) {
2466 u64 new_bytes_used = size - bytes_used;
2468 bytes_used += new_bytes_used >> 1;
2469 fragment_free_space(cache);
2473 * Ensure the corresponding space_info object is created and
2474 * assigned to our block group. We want our bg to be added to the rbtree
2475 * with its ->space_info set.
2477 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2478 ASSERT(cache->space_info);
2480 ret = btrfs_add_block_group_cache(fs_info, cache);
2482 btrfs_remove_free_space_cache(cache);
2483 btrfs_put_block_group(cache);
2484 return ERR_PTR(ret);
2488 * Now that our block group has its ->space_info set and is inserted in
2489 * the rbtree, update the space info's counters.
2491 trace_btrfs_add_block_group(fs_info, cache, 1);
2492 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
2493 cache->bytes_super, 0, &cache->space_info);
2494 btrfs_update_global_block_rsv(fs_info);
2496 link_block_group(cache);
2498 list_add_tail(&cache->bg_list, &trans->new_bgs);
2499 trans->delayed_ref_updates++;
2500 btrfs_update_delayed_refs_rsv(trans);
2502 set_avail_alloc_bits(fs_info, type);
2507 * Mark one block group RO, can be called several times for the same block
2510 * @cache: the destination block group
2511 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2512 * ensure we still have some free space after marking this
2515 int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2516 bool do_chunk_alloc)
2518 struct btrfs_fs_info *fs_info = cache->fs_info;
2519 struct btrfs_trans_handle *trans;
2522 bool dirty_bg_running;
2525 * This can only happen when we are doing read-only scrub on read-only
2527 * In that case we should not start a new transaction on read-only fs.
2528 * Thus here we skip all chunk allocations.
2530 if (sb_rdonly(fs_info->sb)) {
2531 mutex_lock(&fs_info->ro_block_group_mutex);
2532 ret = inc_block_group_ro(cache, 0);
2533 mutex_unlock(&fs_info->ro_block_group_mutex);
2538 trans = btrfs_join_transaction(fs_info->extent_root);
2540 return PTR_ERR(trans);
2542 dirty_bg_running = false;
2545 * We're not allowed to set block groups readonly after the dirty
2546 * block group cache has started writing. If it already started,
2547 * back off and let this transaction commit.
2549 mutex_lock(&fs_info->ro_block_group_mutex);
2550 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2551 u64 transid = trans->transid;
2553 mutex_unlock(&fs_info->ro_block_group_mutex);
2554 btrfs_end_transaction(trans);
2556 ret = btrfs_wait_for_commit(fs_info, transid);
2559 dirty_bg_running = true;
2561 } while (dirty_bg_running);
2563 if (do_chunk_alloc) {
2565 * If we are changing raid levels, try to allocate a
2566 * corresponding block group with the new raid level.
2568 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2569 if (alloc_flags != cache->flags) {
2570 ret = btrfs_chunk_alloc(trans, alloc_flags,
2573 * ENOSPC is allowed here, we may have enough space
2574 * already allocated at the new raid level to carry on
2583 ret = inc_block_group_ro(cache, 0);
2584 if (!do_chunk_alloc || ret == -ETXTBSY)
2588 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2589 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2592 ret = inc_block_group_ro(cache, 0);
2593 if (ret == -ETXTBSY)
2596 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2597 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2598 mutex_lock(&fs_info->chunk_mutex);
2599 check_system_chunk(trans, alloc_flags);
2600 mutex_unlock(&fs_info->chunk_mutex);
2603 mutex_unlock(&fs_info->ro_block_group_mutex);
2605 btrfs_end_transaction(trans);
2609 void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
2611 struct btrfs_space_info *sinfo = cache->space_info;
2616 spin_lock(&sinfo->lock);
2617 spin_lock(&cache->lock);
2619 if (btrfs_is_zoned(cache->fs_info)) {
2620 /* Migrate zone_unusable bytes back */
2621 cache->zone_unusable = cache->alloc_offset - cache->used;
2622 sinfo->bytes_zone_unusable += cache->zone_unusable;
2623 sinfo->bytes_readonly -= cache->zone_unusable;
2625 num_bytes = cache->length - cache->reserved -
2626 cache->pinned - cache->bytes_super -
2627 cache->zone_unusable - cache->used;
2628 sinfo->bytes_readonly -= num_bytes;
2629 list_del_init(&cache->ro_list);
2631 spin_unlock(&cache->lock);
2632 spin_unlock(&sinfo->lock);
2635 static int update_block_group_item(struct btrfs_trans_handle *trans,
2636 struct btrfs_path *path,
2637 struct btrfs_block_group *cache)
2639 struct btrfs_fs_info *fs_info = trans->fs_info;
2641 struct btrfs_root *root = fs_info->extent_root;
2643 struct extent_buffer *leaf;
2644 struct btrfs_block_group_item bgi;
2645 struct btrfs_key key;
2647 key.objectid = cache->start;
2648 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2649 key.offset = cache->length;
2651 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2658 leaf = path->nodes[0];
2659 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2660 btrfs_set_stack_block_group_used(&bgi, cache->used);
2661 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2662 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2663 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2664 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
2665 btrfs_mark_buffer_dirty(leaf);
2667 btrfs_release_path(path);
2672 static int cache_save_setup(struct btrfs_block_group *block_group,
2673 struct btrfs_trans_handle *trans,
2674 struct btrfs_path *path)
2676 struct btrfs_fs_info *fs_info = block_group->fs_info;
2677 struct btrfs_root *root = fs_info->tree_root;
2678 struct inode *inode = NULL;
2679 struct extent_changeset *data_reserved = NULL;
2681 int dcs = BTRFS_DC_ERROR;
2686 if (!btrfs_test_opt(fs_info, SPACE_CACHE))
2690 * If this block group is smaller than 100 megs don't bother caching the
2693 if (block_group->length < (100 * SZ_1M)) {
2694 spin_lock(&block_group->lock);
2695 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2696 spin_unlock(&block_group->lock);
2700 if (TRANS_ABORTED(trans))
2703 inode = lookup_free_space_inode(block_group, path);
2704 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2705 ret = PTR_ERR(inode);
2706 btrfs_release_path(path);
2710 if (IS_ERR(inode)) {
2714 if (block_group->ro)
2717 ret = create_free_space_inode(trans, block_group, path);
2724 * We want to set the generation to 0, that way if anything goes wrong
2725 * from here on out we know not to trust this cache when we load up next
2728 BTRFS_I(inode)->generation = 0;
2729 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
2732 * So theoretically we could recover from this, simply set the
2733 * super cache generation to 0 so we know to invalidate the
2734 * cache, but then we'd have to keep track of the block groups
2735 * that fail this way so we know we _have_ to reset this cache
2736 * before the next commit or risk reading stale cache. So to
2737 * limit our exposure to horrible edge cases lets just abort the
2738 * transaction, this only happens in really bad situations
2741 btrfs_abort_transaction(trans, ret);
2746 /* We've already setup this transaction, go ahead and exit */
2747 if (block_group->cache_generation == trans->transid &&
2748 i_size_read(inode)) {
2749 dcs = BTRFS_DC_SETUP;
2753 if (i_size_read(inode) > 0) {
2754 ret = btrfs_check_trunc_cache_free_space(fs_info,
2755 &fs_info->global_block_rsv);
2759 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2764 spin_lock(&block_group->lock);
2765 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2766 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2768 * don't bother trying to write stuff out _if_
2769 * a) we're not cached,
2770 * b) we're with nospace_cache mount option,
2771 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2773 dcs = BTRFS_DC_WRITTEN;
2774 spin_unlock(&block_group->lock);
2777 spin_unlock(&block_group->lock);
2780 * We hit an ENOSPC when setting up the cache in this transaction, just
2781 * skip doing the setup, we've already cleared the cache so we're safe.
2783 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2789 * Try to preallocate enough space based on how big the block group is.
2790 * Keep in mind this has to include any pinned space which could end up
2791 * taking up quite a bit since it's not folded into the other space
2794 cache_size = div_u64(block_group->length, SZ_256M);
2799 cache_size *= fs_info->sectorsize;
2801 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
2806 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
2807 cache_size, cache_size,
2810 * Our cache requires contiguous chunks so that we don't modify a bunch
2811 * of metadata or split extents when writing the cache out, which means
2812 * we can enospc if we are heavily fragmented in addition to just normal
2813 * out of space conditions. So if we hit this just skip setting up any
2814 * other block groups for this transaction, maybe we'll unpin enough
2815 * space the next time around.
2818 dcs = BTRFS_DC_SETUP;
2819 else if (ret == -ENOSPC)
2820 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2825 btrfs_release_path(path);
2827 spin_lock(&block_group->lock);
2828 if (!ret && dcs == BTRFS_DC_SETUP)
2829 block_group->cache_generation = trans->transid;
2830 block_group->disk_cache_state = dcs;
2831 spin_unlock(&block_group->lock);
2833 extent_changeset_free(data_reserved);
2837 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2839 struct btrfs_fs_info *fs_info = trans->fs_info;
2840 struct btrfs_block_group *cache, *tmp;
2841 struct btrfs_transaction *cur_trans = trans->transaction;
2842 struct btrfs_path *path;
2844 if (list_empty(&cur_trans->dirty_bgs) ||
2845 !btrfs_test_opt(fs_info, SPACE_CACHE))
2848 path = btrfs_alloc_path();
2852 /* Could add new block groups, use _safe just in case */
2853 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2855 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2856 cache_save_setup(cache, trans, path);
2859 btrfs_free_path(path);
2864 * Transaction commit does final block group cache writeback during a critical
2865 * section where nothing is allowed to change the FS. This is required in
2866 * order for the cache to actually match the block group, but can introduce a
2867 * lot of latency into the commit.
2869 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2870 * There's a chance we'll have to redo some of it if the block group changes
2871 * again during the commit, but it greatly reduces the commit latency by
2872 * getting rid of the easy block groups while we're still allowing others to
2875 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2877 struct btrfs_fs_info *fs_info = trans->fs_info;
2878 struct btrfs_block_group *cache;
2879 struct btrfs_transaction *cur_trans = trans->transaction;
2882 struct btrfs_path *path = NULL;
2884 struct list_head *io = &cur_trans->io_bgs;
2887 spin_lock(&cur_trans->dirty_bgs_lock);
2888 if (list_empty(&cur_trans->dirty_bgs)) {
2889 spin_unlock(&cur_trans->dirty_bgs_lock);
2892 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2893 spin_unlock(&cur_trans->dirty_bgs_lock);
2896 /* Make sure all the block groups on our dirty list actually exist */
2897 btrfs_create_pending_block_groups(trans);
2900 path = btrfs_alloc_path();
2908 * cache_write_mutex is here only to save us from balance or automatic
2909 * removal of empty block groups deleting this block group while we are
2910 * writing out the cache
2912 mutex_lock(&trans->transaction->cache_write_mutex);
2913 while (!list_empty(&dirty)) {
2914 bool drop_reserve = true;
2916 cache = list_first_entry(&dirty, struct btrfs_block_group,
2919 * This can happen if something re-dirties a block group that
2920 * is already under IO. Just wait for it to finish and then do
2923 if (!list_empty(&cache->io_list)) {
2924 list_del_init(&cache->io_list);
2925 btrfs_wait_cache_io(trans, cache, path);
2926 btrfs_put_block_group(cache);
2931 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
2932 * it should update the cache_state. Don't delete until after
2935 * Since we're not running in the commit critical section
2936 * we need the dirty_bgs_lock to protect from update_block_group
2938 spin_lock(&cur_trans->dirty_bgs_lock);
2939 list_del_init(&cache->dirty_list);
2940 spin_unlock(&cur_trans->dirty_bgs_lock);
2944 cache_save_setup(cache, trans, path);
2946 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
2947 cache->io_ctl.inode = NULL;
2948 ret = btrfs_write_out_cache(trans, cache, path);
2949 if (ret == 0 && cache->io_ctl.inode) {
2953 * The cache_write_mutex is protecting the
2954 * io_list, also refer to the definition of
2955 * btrfs_transaction::io_bgs for more details
2957 list_add_tail(&cache->io_list, io);
2960 * If we failed to write the cache, the
2961 * generation will be bad and life goes on
2967 ret = update_block_group_item(trans, path, cache);
2969 * Our block group might still be attached to the list
2970 * of new block groups in the transaction handle of some
2971 * other task (struct btrfs_trans_handle->new_bgs). This
2972 * means its block group item isn't yet in the extent
2973 * tree. If this happens ignore the error, as we will
2974 * try again later in the critical section of the
2975 * transaction commit.
2977 if (ret == -ENOENT) {
2979 spin_lock(&cur_trans->dirty_bgs_lock);
2980 if (list_empty(&cache->dirty_list)) {
2981 list_add_tail(&cache->dirty_list,
2982 &cur_trans->dirty_bgs);
2983 btrfs_get_block_group(cache);
2984 drop_reserve = false;
2986 spin_unlock(&cur_trans->dirty_bgs_lock);
2988 btrfs_abort_transaction(trans, ret);
2992 /* If it's not on the io list, we need to put the block group */
2994 btrfs_put_block_group(cache);
2996 btrfs_delayed_refs_rsv_release(fs_info, 1);
2998 * Avoid blocking other tasks for too long. It might even save
2999 * us from writing caches for block groups that are going to be
3002 mutex_unlock(&trans->transaction->cache_write_mutex);
3005 mutex_lock(&trans->transaction->cache_write_mutex);
3007 mutex_unlock(&trans->transaction->cache_write_mutex);
3010 * Go through delayed refs for all the stuff we've just kicked off
3011 * and then loop back (just once)
3014 ret = btrfs_run_delayed_refs(trans, 0);
3015 if (!ret && loops == 0) {
3017 spin_lock(&cur_trans->dirty_bgs_lock);
3018 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3020 * dirty_bgs_lock protects us from concurrent block group
3021 * deletes too (not just cache_write_mutex).
3023 if (!list_empty(&dirty)) {
3024 spin_unlock(&cur_trans->dirty_bgs_lock);
3027 spin_unlock(&cur_trans->dirty_bgs_lock);
3031 spin_lock(&cur_trans->dirty_bgs_lock);
3032 list_splice_init(&dirty, &cur_trans->dirty_bgs);
3033 spin_unlock(&cur_trans->dirty_bgs_lock);
3034 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3037 btrfs_free_path(path);
3041 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
3043 struct btrfs_fs_info *fs_info = trans->fs_info;
3044 struct btrfs_block_group *cache;
3045 struct btrfs_transaction *cur_trans = trans->transaction;
3048 struct btrfs_path *path;
3049 struct list_head *io = &cur_trans->io_bgs;
3051 path = btrfs_alloc_path();
3056 * Even though we are in the critical section of the transaction commit,
3057 * we can still have concurrent tasks adding elements to this
3058 * transaction's list of dirty block groups. These tasks correspond to
3059 * endio free space workers started when writeback finishes for a
3060 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3061 * allocate new block groups as a result of COWing nodes of the root
3062 * tree when updating the free space inode. The writeback for the space
3063 * caches is triggered by an earlier call to
3064 * btrfs_start_dirty_block_groups() and iterations of the following
3066 * Also we want to do the cache_save_setup first and then run the
3067 * delayed refs to make sure we have the best chance at doing this all
3070 spin_lock(&cur_trans->dirty_bgs_lock);
3071 while (!list_empty(&cur_trans->dirty_bgs)) {
3072 cache = list_first_entry(&cur_trans->dirty_bgs,
3073 struct btrfs_block_group,
3077 * This can happen if cache_save_setup re-dirties a block group
3078 * that is already under IO. Just wait for it to finish and
3079 * then do it all again
3081 if (!list_empty(&cache->io_list)) {
3082 spin_unlock(&cur_trans->dirty_bgs_lock);
3083 list_del_init(&cache->io_list);
3084 btrfs_wait_cache_io(trans, cache, path);
3085 btrfs_put_block_group(cache);
3086 spin_lock(&cur_trans->dirty_bgs_lock);
3090 * Don't remove from the dirty list until after we've waited on
3093 list_del_init(&cache->dirty_list);
3094 spin_unlock(&cur_trans->dirty_bgs_lock);
3097 cache_save_setup(cache, trans, path);
3100 ret = btrfs_run_delayed_refs(trans,
3101 (unsigned long) -1);
3103 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3104 cache->io_ctl.inode = NULL;
3105 ret = btrfs_write_out_cache(trans, cache, path);
3106 if (ret == 0 && cache->io_ctl.inode) {
3108 list_add_tail(&cache->io_list, io);
3111 * If we failed to write the cache, the
3112 * generation will be bad and life goes on
3118 ret = update_block_group_item(trans, path, cache);
3120 * One of the free space endio workers might have
3121 * created a new block group while updating a free space
3122 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3123 * and hasn't released its transaction handle yet, in
3124 * which case the new block group is still attached to
3125 * its transaction handle and its creation has not
3126 * finished yet (no block group item in the extent tree
3127 * yet, etc). If this is the case, wait for all free
3128 * space endio workers to finish and retry. This is a
3129 * very rare case so no need for a more efficient and
3132 if (ret == -ENOENT) {
3133 wait_event(cur_trans->writer_wait,
3134 atomic_read(&cur_trans->num_writers) == 1);
3135 ret = update_block_group_item(trans, path, cache);
3138 btrfs_abort_transaction(trans, ret);
3141 /* If its not on the io list, we need to put the block group */
3143 btrfs_put_block_group(cache);
3144 btrfs_delayed_refs_rsv_release(fs_info, 1);
3145 spin_lock(&cur_trans->dirty_bgs_lock);
3147 spin_unlock(&cur_trans->dirty_bgs_lock);
3150 * Refer to the definition of io_bgs member for details why it's safe
3151 * to use it without any locking
3153 while (!list_empty(io)) {
3154 cache = list_first_entry(io, struct btrfs_block_group,
3156 list_del_init(&cache->io_list);
3157 btrfs_wait_cache_io(trans, cache, path);
3158 btrfs_put_block_group(cache);
3161 btrfs_free_path(path);
3165 int btrfs_update_block_group(struct btrfs_trans_handle *trans,
3166 u64 bytenr, u64 num_bytes, int alloc)
3168 struct btrfs_fs_info *info = trans->fs_info;
3169 struct btrfs_block_group *cache = NULL;
3170 u64 total = num_bytes;
3176 /* Block accounting for super block */
3177 spin_lock(&info->delalloc_root_lock);
3178 old_val = btrfs_super_bytes_used(info->super_copy);
3180 old_val += num_bytes;
3182 old_val -= num_bytes;
3183 btrfs_set_super_bytes_used(info->super_copy, old_val);
3184 spin_unlock(&info->delalloc_root_lock);
3187 cache = btrfs_lookup_block_group(info, bytenr);
3192 factor = btrfs_bg_type_to_factor(cache->flags);
3195 * If this block group has free space cache written out, we
3196 * need to make sure to load it if we are removing space. This
3197 * is because we need the unpinning stage to actually add the
3198 * space back to the block group, otherwise we will leak space.
3200 if (!alloc && !btrfs_block_group_done(cache))
3201 btrfs_cache_block_group(cache, 1);
3203 byte_in_group = bytenr - cache->start;
3204 WARN_ON(byte_in_group > cache->length);
3206 spin_lock(&cache->space_info->lock);
3207 spin_lock(&cache->lock);
3209 if (btrfs_test_opt(info, SPACE_CACHE) &&
3210 cache->disk_cache_state < BTRFS_DC_CLEAR)
3211 cache->disk_cache_state = BTRFS_DC_CLEAR;
3213 old_val = cache->used;
3214 num_bytes = min(total, cache->length - byte_in_group);
3216 old_val += num_bytes;
3217 cache->used = old_val;
3218 cache->reserved -= num_bytes;
3219 cache->space_info->bytes_reserved -= num_bytes;
3220 cache->space_info->bytes_used += num_bytes;
3221 cache->space_info->disk_used += num_bytes * factor;
3222 spin_unlock(&cache->lock);
3223 spin_unlock(&cache->space_info->lock);
3225 old_val -= num_bytes;
3226 cache->used = old_val;
3227 cache->pinned += num_bytes;
3228 btrfs_space_info_update_bytes_pinned(info,
3229 cache->space_info, num_bytes);
3230 cache->space_info->bytes_used -= num_bytes;
3231 cache->space_info->disk_used -= num_bytes * factor;
3232 spin_unlock(&cache->lock);
3233 spin_unlock(&cache->space_info->lock);
3235 set_extent_dirty(&trans->transaction->pinned_extents,
3236 bytenr, bytenr + num_bytes - 1,
3237 GFP_NOFS | __GFP_NOFAIL);
3240 spin_lock(&trans->transaction->dirty_bgs_lock);
3241 if (list_empty(&cache->dirty_list)) {
3242 list_add_tail(&cache->dirty_list,
3243 &trans->transaction->dirty_bgs);
3244 trans->delayed_ref_updates++;
3245 btrfs_get_block_group(cache);
3247 spin_unlock(&trans->transaction->dirty_bgs_lock);
3250 * No longer have used bytes in this block group, queue it for
3251 * deletion. We do this after adding the block group to the
3252 * dirty list to avoid races between cleaner kthread and space
3255 if (!alloc && old_val == 0) {
3256 if (!btrfs_test_opt(info, DISCARD_ASYNC))
3257 btrfs_mark_bg_unused(cache);
3260 btrfs_put_block_group(cache);
3262 bytenr += num_bytes;
3265 /* Modified block groups are accounted for in the delayed_refs_rsv. */
3266 btrfs_update_delayed_refs_rsv(trans);
3271 * btrfs_add_reserved_bytes - update the block_group and space info counters
3272 * @cache: The cache we are manipulating
3273 * @ram_bytes: The number of bytes of file content, and will be same to
3274 * @num_bytes except for the compress path.
3275 * @num_bytes: The number of bytes in question
3276 * @delalloc: The blocks are allocated for the delalloc write
3278 * This is called by the allocator when it reserves space. If this is a
3279 * reservation and the block group has become read only we cannot make the
3280 * reservation and return -EAGAIN, otherwise this function always succeeds.
3282 int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
3283 u64 ram_bytes, u64 num_bytes, int delalloc)
3285 struct btrfs_space_info *space_info = cache->space_info;
3288 spin_lock(&space_info->lock);
3289 spin_lock(&cache->lock);
3293 cache->reserved += num_bytes;
3294 space_info->bytes_reserved += num_bytes;
3295 trace_btrfs_space_reservation(cache->fs_info, "space_info",
3296 space_info->flags, num_bytes, 1);
3297 btrfs_space_info_update_bytes_may_use(cache->fs_info,
3298 space_info, -ram_bytes);
3300 cache->delalloc_bytes += num_bytes;
3303 * Compression can use less space than we reserved, so wake
3304 * tickets if that happens
3306 if (num_bytes < ram_bytes)
3307 btrfs_try_granting_tickets(cache->fs_info, space_info);
3309 spin_unlock(&cache->lock);
3310 spin_unlock(&space_info->lock);
3315 * btrfs_free_reserved_bytes - update the block_group and space info counters
3316 * @cache: The cache we are manipulating
3317 * @num_bytes: The number of bytes in question
3318 * @delalloc: The blocks are allocated for the delalloc write
3320 * This is called by somebody who is freeing space that was never actually used
3321 * on disk. For example if you reserve some space for a new leaf in transaction
3322 * A and before transaction A commits you free that leaf, you call this with
3323 * reserve set to 0 in order to clear the reservation.
3325 void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3326 u64 num_bytes, int delalloc)
3328 struct btrfs_space_info *space_info = cache->space_info;
3330 spin_lock(&space_info->lock);
3331 spin_lock(&cache->lock);
3333 space_info->bytes_readonly += num_bytes;
3334 cache->reserved -= num_bytes;
3335 space_info->bytes_reserved -= num_bytes;
3336 space_info->max_extent_size = 0;
3339 cache->delalloc_bytes -= num_bytes;
3340 spin_unlock(&cache->lock);
3342 btrfs_try_granting_tickets(cache->fs_info, space_info);
3343 spin_unlock(&space_info->lock);
3346 static void force_metadata_allocation(struct btrfs_fs_info *info)
3348 struct list_head *head = &info->space_info;
3349 struct btrfs_space_info *found;
3351 list_for_each_entry(found, head, list) {
3352 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3353 found->force_alloc = CHUNK_ALLOC_FORCE;
3357 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3358 struct btrfs_space_info *sinfo, int force)
3360 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3363 if (force == CHUNK_ALLOC_FORCE)
3367 * in limited mode, we want to have some free space up to
3368 * about 1% of the FS size.
3370 if (force == CHUNK_ALLOC_LIMITED) {
3371 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3372 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3374 if (sinfo->total_bytes - bytes_used < thresh)
3378 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3383 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3385 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3387 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3390 static int do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags)
3392 struct btrfs_block_group *bg;
3396 * Check if we have enough space in the system space info because we
3397 * will need to update device items in the chunk btree and insert a new
3398 * chunk item in the chunk btree as well. This will allocate a new
3399 * system block group if needed.
3401 check_system_chunk(trans, flags);
3403 bg = btrfs_create_chunk(trans, flags);
3410 * If this is a system chunk allocation then stop right here and do not
3411 * add the chunk item to the chunk btree. This is to prevent a deadlock
3412 * because this system chunk allocation can be triggered while COWing
3413 * some extent buffer of the chunk btree and while holding a lock on a
3414 * parent extent buffer, in which case attempting to insert the chunk
3415 * item (or update the device item) would result in a deadlock on that
3416 * parent extent buffer. In this case defer the chunk btree updates to
3417 * the second phase of chunk allocation and keep our reservation until
3418 * the second phase completes.
3420 * This is a rare case and can only be triggered by the very few cases
3421 * we have where we need to touch the chunk btree outside chunk allocation
3422 * and chunk removal. These cases are basically adding a device, removing
3423 * a device or resizing a device.
3425 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
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 two 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 if (ret == -ENOSPC) {
3461 const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info);
3462 struct btrfs_block_group *sys_bg;
3464 sys_bg = btrfs_create_chunk(trans, sys_flags);
3465 if (IS_ERR(sys_bg)) {
3466 ret = PTR_ERR(sys_bg);
3467 btrfs_abort_transaction(trans, ret);
3471 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3473 btrfs_abort_transaction(trans, ret);
3477 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
3479 btrfs_abort_transaction(trans, ret);
3483 btrfs_abort_transaction(trans, ret);
3487 btrfs_trans_release_chunk_metadata(trans);
3493 * Chunk allocation is done in 2 phases:
3495 * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
3496 * the chunk, the chunk mapping, create its block group and add the items
3497 * that belong in the chunk btree to it - more specifically, we need to
3498 * update device items in the chunk btree and add a new chunk item to it.
3500 * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
3501 * group item to the extent btree and the device extent items to the devices
3504 * This is done to prevent deadlocks. For example when COWing a node from the
3505 * extent btree we are holding a write lock on the node's parent and if we
3506 * trigger chunk allocation and attempted to insert the new block group item
3507 * in the extent btree right way, we could deadlock because the path for the
3508 * insertion can include that parent node. At first glance it seems impossible
3509 * to trigger chunk allocation after starting a transaction since tasks should
3510 * reserve enough transaction units (metadata space), however while that is true
3511 * most of the time, chunk allocation may still be triggered for several reasons:
3513 * 1) When reserving metadata, we check if there is enough free space in the
3514 * metadata space_info and therefore don't trigger allocation of a new chunk.
3515 * However later when the task actually tries to COW an extent buffer from
3516 * the extent btree or from the device btree for example, it is forced to
3517 * allocate a new block group (chunk) because the only one that had enough
3518 * free space was just turned to RO mode by a running scrub for example (or
3519 * device replace, block group reclaim thread, etc), so we can not use it
3520 * for allocating an extent and end up being forced to allocate a new one;
3522 * 2) Because we only check that the metadata space_info has enough free bytes,
3523 * we end up not allocating a new metadata chunk in that case. However if
3524 * the filesystem was mounted in degraded mode, none of the existing block
3525 * groups might be suitable for extent allocation due to their incompatible
3526 * profile (for e.g. mounting a 2 devices filesystem, where all block groups
3527 * use a RAID1 profile, in degraded mode using a single device). In this case
3528 * when the task attempts to COW some extent buffer of the extent btree for
3529 * example, it will trigger allocation of a new metadata block group with a
3530 * suitable profile (SINGLE profile in the example of the degraded mount of
3531 * the RAID1 filesystem);
3533 * 3) The task has reserved enough transaction units / metadata space, but when
3534 * it attempts to COW an extent buffer from the extent or device btree for
3535 * example, it does not find any free extent in any metadata block group,
3536 * therefore forced to try to allocate a new metadata block group.
3537 * This is because some other task allocated all available extents in the
3538 * meanwhile - this typically happens with tasks that don't reserve space
3539 * properly, either intentionally or as a bug. One example where this is
3540 * done intentionally is fsync, as it does not reserve any transaction units
3541 * and ends up allocating a variable number of metadata extents for log
3542 * tree extent buffers.
3544 * We also need this 2 phases setup when adding a device to a filesystem with
3545 * a seed device - we must create new metadata and system chunks without adding
3546 * any of the block group items to the chunk, extent and device btrees. If we
3547 * did not do it this way, we would get ENOSPC when attempting to update those
3548 * btrees, since all the chunks from the seed device are read-only.
3550 * Phase 1 does the updates and insertions to the chunk btree because if we had
3551 * it done in phase 2 and have a thundering herd of tasks allocating chunks in
3552 * parallel, we risk having too many system chunks allocated by many tasks if
3553 * many tasks reach phase 1 without the previous ones completing phase 2. In the
3554 * extreme case this leads to exhaustion of the system chunk array in the
3555 * superblock. This is easier to trigger if using a btree node/leaf size of 64K
3556 * and with RAID filesystems (so we have more device items in the chunk btree).
3557 * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
3558 * the system chunk array due to concurrent allocations") provides more details.
3560 * For allocation of system chunks, we defer the updates and insertions into the
3561 * chunk btree to phase 2. This is to prevent deadlocks on extent buffers because
3562 * if the chunk allocation is triggered while COWing an extent buffer of the
3563 * chunk btree, we are holding a lock on the parent of that extent buffer and
3564 * doing the chunk btree updates and insertions can require locking that parent.
3565 * This is for the very few and rare cases where we update the chunk btree that
3566 * are not chunk allocation or chunk removal: adding a device, removing a device
3567 * or resizing a device.
3569 * The reservation of system space, done through check_system_chunk(), as well
3570 * as all the updates and insertions into the chunk btree must be done while
3571 * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
3572 * an extent buffer from the chunks btree we never trigger allocation of a new
3573 * system chunk, which would result in a deadlock (trying to lock twice an
3574 * extent buffer of the chunk btree, first time before triggering the chunk
3575 * allocation and the second time during chunk allocation while attempting to
3576 * update the chunks btree). The system chunk array is also updated while holding
3577 * that mutex. The same logic applies to removing chunks - we must reserve system
3578 * space, update the chunk btree and the system chunk array in the superblock
3579 * while holding fs_info->chunk_mutex.
3581 * This function, btrfs_chunk_alloc(), belongs to phase 1.
3583 * If @force is CHUNK_ALLOC_FORCE:
3584 * - return 1 if it successfully allocates a chunk,
3585 * - return errors including -ENOSPC otherwise.
3586 * If @force is NOT CHUNK_ALLOC_FORCE:
3587 * - return 0 if it doesn't need to allocate a new chunk,
3588 * - return 1 if it successfully allocates a chunk,
3589 * - return errors including -ENOSPC otherwise.
3591 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3592 enum btrfs_chunk_alloc_enum force)
3594 struct btrfs_fs_info *fs_info = trans->fs_info;
3595 struct btrfs_space_info *space_info;
3596 bool wait_for_alloc = false;
3597 bool should_alloc = false;
3600 /* Don't re-enter if we're already allocating a chunk */
3601 if (trans->allocating_chunk)
3604 * If we are removing a chunk, don't re-enter or we would deadlock.
3605 * System space reservation and system chunk allocation is done by the
3606 * chunk remove operation (btrfs_remove_chunk()).
3608 if (trans->removing_chunk)
3611 space_info = btrfs_find_space_info(fs_info, flags);
3615 spin_lock(&space_info->lock);
3616 if (force < space_info->force_alloc)
3617 force = space_info->force_alloc;
3618 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3619 if (space_info->full) {
3620 /* No more free physical space */
3625 spin_unlock(&space_info->lock);
3627 } else if (!should_alloc) {
3628 spin_unlock(&space_info->lock);
3630 } else if (space_info->chunk_alloc) {
3632 * Someone is already allocating, so we need to block
3633 * until this someone is finished and then loop to
3634 * recheck if we should continue with our allocation
3637 wait_for_alloc = true;
3638 spin_unlock(&space_info->lock);
3639 mutex_lock(&fs_info->chunk_mutex);
3640 mutex_unlock(&fs_info->chunk_mutex);
3642 /* Proceed with allocation */
3643 space_info->chunk_alloc = 1;
3644 wait_for_alloc = false;
3645 spin_unlock(&space_info->lock);
3649 } while (wait_for_alloc);
3651 mutex_lock(&fs_info->chunk_mutex);
3652 trans->allocating_chunk = true;
3655 * If we have mixed data/metadata chunks we want to make sure we keep
3656 * allocating mixed chunks instead of individual chunks.
3658 if (btrfs_mixed_space_info(space_info))
3659 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3662 * if we're doing a data chunk, go ahead and make sure that
3663 * we keep a reasonable number of metadata chunks allocated in the
3666 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3667 fs_info->data_chunk_allocations++;
3668 if (!(fs_info->data_chunk_allocations %
3669 fs_info->metadata_ratio))
3670 force_metadata_allocation(fs_info);
3673 ret = do_chunk_alloc(trans, flags);
3674 trans->allocating_chunk = false;
3676 spin_lock(&space_info->lock);
3679 space_info->full = 1;
3684 space_info->max_extent_size = 0;
3687 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3689 space_info->chunk_alloc = 0;
3690 spin_unlock(&space_info->lock);
3691 mutex_unlock(&fs_info->chunk_mutex);
3696 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3700 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3702 num_dev = fs_info->fs_devices->rw_devices;
3708 * Reserve space in the system space for allocating or removing a chunk
3710 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3712 struct btrfs_fs_info *fs_info = trans->fs_info;
3713 struct btrfs_space_info *info;
3720 * Needed because we can end up allocating a system chunk and for an
3721 * atomic and race free space reservation in the chunk block reserve.
3723 lockdep_assert_held(&fs_info->chunk_mutex);
3725 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3726 spin_lock(&info->lock);
3727 left = info->total_bytes - btrfs_space_info_used(info, true);
3728 spin_unlock(&info->lock);
3730 num_devs = get_profile_num_devs(fs_info, type);
3732 /* num_devs device items to update and 1 chunk item to add or remove */
3733 thresh = btrfs_calc_metadata_size(fs_info, num_devs) +
3734 btrfs_calc_insert_metadata_size(fs_info, 1);
3736 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3737 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3738 left, thresh, type);
3739 btrfs_dump_space_info(fs_info, info, 0, 0);
3742 if (left < thresh) {
3743 u64 flags = btrfs_system_alloc_profile(fs_info);
3744 struct btrfs_block_group *bg;
3747 * Ignore failure to create system chunk. We might end up not
3748 * needing it, as we might not need to COW all nodes/leafs from
3749 * the paths we visit in the chunk tree (they were already COWed
3750 * or created in the current transaction for example).
3752 * Also, if our caller is allocating a system chunk, do not
3753 * attempt to insert the chunk item in the chunk btree, as we
3754 * could deadlock on an extent buffer since our caller may be
3755 * COWing an extent buffer from the chunk btree.
3757 bg = btrfs_create_chunk(trans, flags);
3760 } else if (!(type & BTRFS_BLOCK_GROUP_SYSTEM)) {
3762 * If we fail to add the chunk item here, we end up
3763 * trying again at phase 2 of chunk allocation, at
3764 * btrfs_create_pending_block_groups(). So ignore
3767 btrfs_chunk_alloc_add_chunk_item(trans, bg);
3772 ret = btrfs_block_rsv_add(fs_info->chunk_root,
3773 &fs_info->chunk_block_rsv,
3774 thresh, BTRFS_RESERVE_NO_FLUSH);
3776 trans->chunk_bytes_reserved += thresh;
3780 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3782 struct btrfs_block_group *block_group;
3786 struct inode *inode;
3788 block_group = btrfs_lookup_first_block_group(info, last);
3789 while (block_group) {
3790 btrfs_wait_block_group_cache_done(block_group);
3791 spin_lock(&block_group->lock);
3792 if (block_group->iref)
3794 spin_unlock(&block_group->lock);
3795 block_group = btrfs_next_block_group(block_group);
3804 inode = block_group->inode;
3805 block_group->iref = 0;
3806 block_group->inode = NULL;
3807 spin_unlock(&block_group->lock);
3808 ASSERT(block_group->io_ctl.inode == NULL);
3810 last = block_group->start + block_group->length;
3811 btrfs_put_block_group(block_group);
3816 * Must be called only after stopping all workers, since we could have block
3817 * group caching kthreads running, and therefore they could race with us if we
3818 * freed the block groups before stopping them.
3820 int btrfs_free_block_groups(struct btrfs_fs_info *info)
3822 struct btrfs_block_group *block_group;
3823 struct btrfs_space_info *space_info;
3824 struct btrfs_caching_control *caching_ctl;
3827 spin_lock(&info->block_group_cache_lock);
3828 while (!list_empty(&info->caching_block_groups)) {
3829 caching_ctl = list_entry(info->caching_block_groups.next,
3830 struct btrfs_caching_control, list);
3831 list_del(&caching_ctl->list);
3832 btrfs_put_caching_control(caching_ctl);
3834 spin_unlock(&info->block_group_cache_lock);
3836 spin_lock(&info->unused_bgs_lock);
3837 while (!list_empty(&info->unused_bgs)) {
3838 block_group = list_first_entry(&info->unused_bgs,
3839 struct btrfs_block_group,
3841 list_del_init(&block_group->bg_list);
3842 btrfs_put_block_group(block_group);
3844 spin_unlock(&info->unused_bgs_lock);
3846 spin_lock(&info->unused_bgs_lock);
3847 while (!list_empty(&info->reclaim_bgs)) {
3848 block_group = list_first_entry(&info->reclaim_bgs,
3849 struct btrfs_block_group,
3851 list_del_init(&block_group->bg_list);
3852 btrfs_put_block_group(block_group);
3854 spin_unlock(&info->unused_bgs_lock);
3856 spin_lock(&info->block_group_cache_lock);
3857 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
3858 block_group = rb_entry(n, struct btrfs_block_group,
3860 rb_erase(&block_group->cache_node,
3861 &info->block_group_cache_tree);
3862 RB_CLEAR_NODE(&block_group->cache_node);
3863 spin_unlock(&info->block_group_cache_lock);
3865 down_write(&block_group->space_info->groups_sem);
3866 list_del(&block_group->list);
3867 up_write(&block_group->space_info->groups_sem);
3870 * We haven't cached this block group, which means we could
3871 * possibly have excluded extents on this block group.
3873 if (block_group->cached == BTRFS_CACHE_NO ||
3874 block_group->cached == BTRFS_CACHE_ERROR)
3875 btrfs_free_excluded_extents(block_group);
3877 btrfs_remove_free_space_cache(block_group);
3878 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
3879 ASSERT(list_empty(&block_group->dirty_list));
3880 ASSERT(list_empty(&block_group->io_list));
3881 ASSERT(list_empty(&block_group->bg_list));
3882 ASSERT(refcount_read(&block_group->refs) == 1);
3883 ASSERT(block_group->swap_extents == 0);
3884 btrfs_put_block_group(block_group);
3886 spin_lock(&info->block_group_cache_lock);
3888 spin_unlock(&info->block_group_cache_lock);
3890 btrfs_release_global_block_rsv(info);
3892 while (!list_empty(&info->space_info)) {
3893 space_info = list_entry(info->space_info.next,
3894 struct btrfs_space_info,
3898 * Do not hide this behind enospc_debug, this is actually
3899 * important and indicates a real bug if this happens.
3901 if (WARN_ON(space_info->bytes_pinned > 0 ||
3902 space_info->bytes_may_use > 0))
3903 btrfs_dump_space_info(info, space_info, 0, 0);
3906 * If there was a failure to cleanup a log tree, very likely due
3907 * to an IO failure on a writeback attempt of one or more of its
3908 * extent buffers, we could not do proper (and cheap) unaccounting
3909 * of their reserved space, so don't warn on bytes_reserved > 0 in
3912 if (!(space_info->flags & BTRFS_BLOCK_GROUP_METADATA) ||
3913 !BTRFS_FS_LOG_CLEANUP_ERROR(info)) {
3914 if (WARN_ON(space_info->bytes_reserved > 0))
3915 btrfs_dump_space_info(info, space_info, 0, 0);
3918 WARN_ON(space_info->reclaim_size > 0);
3919 list_del(&space_info->list);
3920 btrfs_sysfs_remove_space_info(space_info);
3925 void btrfs_freeze_block_group(struct btrfs_block_group *cache)
3927 atomic_inc(&cache->frozen);
3930 void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
3932 struct btrfs_fs_info *fs_info = block_group->fs_info;
3933 struct extent_map_tree *em_tree;
3934 struct extent_map *em;
3937 spin_lock(&block_group->lock);
3938 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
3939 block_group->removed);
3940 spin_unlock(&block_group->lock);
3943 em_tree = &fs_info->mapping_tree;
3944 write_lock(&em_tree->lock);
3945 em = lookup_extent_mapping(em_tree, block_group->start,
3947 BUG_ON(!em); /* logic error, can't happen */
3948 remove_extent_mapping(em_tree, em);
3949 write_unlock(&em_tree->lock);
3951 /* once for us and once for the tree */
3952 free_extent_map(em);
3953 free_extent_map(em);
3956 * We may have left one free space entry and other possible
3957 * tasks trimming this block group have left 1 entry each one.
3960 __btrfs_remove_free_space_cache(block_group->free_space_ctl);
3964 bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
3968 spin_lock(&bg->lock);
3973 spin_unlock(&bg->lock);
3978 void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
3980 spin_lock(&bg->lock);
3982 ASSERT(bg->swap_extents >= amount);
3983 bg->swap_extents -= amount;
3984 spin_unlock(&bg->lock);