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"
20 * Return target flags in extended format or 0 if restripe for this chunk_type
23 * Should be called with balance_lock held
25 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
27 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
33 if (flags & BTRFS_BLOCK_GROUP_DATA &&
34 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
35 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
36 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
37 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
38 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
39 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
40 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
41 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
48 * @flags: available profiles in extended format (see ctree.h)
50 * Return reduced profile in chunk format. If profile changing is in progress
51 * (either running or paused) picks the target profile (if it's already
52 * available), otherwise falls back to plain reducing.
54 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
56 u64 num_devices = fs_info->fs_devices->rw_devices;
62 * See if restripe for this chunk_type is in progress, if so try to
63 * reduce to the target profile
65 spin_lock(&fs_info->balance_lock);
66 target = get_restripe_target(fs_info, flags);
68 spin_unlock(&fs_info->balance_lock);
69 return extended_to_chunk(target);
71 spin_unlock(&fs_info->balance_lock);
73 /* First, mask out the RAID levels which aren't possible */
74 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
75 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
76 allowed |= btrfs_raid_array[raid_type].bg_flag;
80 /* Select the highest-redundancy RAID level. */
81 if (allowed & BTRFS_BLOCK_GROUP_RAID1C4)
82 allowed = BTRFS_BLOCK_GROUP_RAID1C4;
83 else if (allowed & BTRFS_BLOCK_GROUP_RAID6)
84 allowed = BTRFS_BLOCK_GROUP_RAID6;
85 else if (allowed & BTRFS_BLOCK_GROUP_RAID1C3)
86 allowed = BTRFS_BLOCK_GROUP_RAID1C3;
87 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
88 allowed = BTRFS_BLOCK_GROUP_RAID5;
89 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
90 allowed = BTRFS_BLOCK_GROUP_RAID10;
91 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
92 allowed = BTRFS_BLOCK_GROUP_RAID1;
93 else if (allowed & BTRFS_BLOCK_GROUP_DUP)
94 allowed = BTRFS_BLOCK_GROUP_DUP;
95 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
96 allowed = BTRFS_BLOCK_GROUP_RAID0;
98 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
100 return extended_to_chunk(flags | allowed);
103 u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
110 seq = read_seqbegin(&fs_info->profiles_lock);
112 if (flags & BTRFS_BLOCK_GROUP_DATA)
113 flags |= fs_info->avail_data_alloc_bits;
114 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
115 flags |= fs_info->avail_system_alloc_bits;
116 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
117 flags |= fs_info->avail_metadata_alloc_bits;
118 } while (read_seqretry(&fs_info->profiles_lock, seq));
120 return btrfs_reduce_alloc_profile(fs_info, flags);
123 void btrfs_get_block_group(struct btrfs_block_group *cache)
125 refcount_inc(&cache->refs);
128 void btrfs_put_block_group(struct btrfs_block_group *cache)
130 if (refcount_dec_and_test(&cache->refs)) {
131 WARN_ON(cache->pinned > 0);
132 WARN_ON(cache->reserved > 0);
135 * A block_group shouldn't be on the discard_list anymore.
136 * Remove the block_group from the discard_list to prevent us
137 * from causing a panic due to NULL pointer dereference.
139 if (WARN_ON(!list_empty(&cache->discard_list)))
140 btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
144 * If not empty, someone is still holding mutex of
145 * full_stripe_lock, which can only be released by caller.
146 * And it will definitely cause use-after-free when caller
147 * tries to release full stripe lock.
149 * No better way to resolve, but only to warn.
151 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
152 kfree(cache->free_space_ctl);
158 * This adds the block group to the fs_info rb tree for the block group cache
160 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
161 struct btrfs_block_group *block_group)
164 struct rb_node *parent = NULL;
165 struct btrfs_block_group *cache;
167 ASSERT(block_group->length != 0);
169 spin_lock(&info->block_group_cache_lock);
170 p = &info->block_group_cache_tree.rb_node;
174 cache = rb_entry(parent, struct btrfs_block_group, cache_node);
175 if (block_group->start < cache->start) {
177 } else if (block_group->start > cache->start) {
180 spin_unlock(&info->block_group_cache_lock);
185 rb_link_node(&block_group->cache_node, parent, p);
186 rb_insert_color(&block_group->cache_node,
187 &info->block_group_cache_tree);
189 if (info->first_logical_byte > block_group->start)
190 info->first_logical_byte = block_group->start;
192 spin_unlock(&info->block_group_cache_lock);
198 * This will return the block group at or after bytenr if contains is 0, else
199 * it will return the block group that contains the bytenr
201 static struct btrfs_block_group *block_group_cache_tree_search(
202 struct btrfs_fs_info *info, u64 bytenr, int contains)
204 struct btrfs_block_group *cache, *ret = NULL;
208 spin_lock(&info->block_group_cache_lock);
209 n = info->block_group_cache_tree.rb_node;
212 cache = rb_entry(n, struct btrfs_block_group, cache_node);
213 end = cache->start + cache->length - 1;
214 start = cache->start;
216 if (bytenr < start) {
217 if (!contains && (!ret || start < ret->start))
220 } else if (bytenr > start) {
221 if (contains && bytenr <= end) {
232 btrfs_get_block_group(ret);
233 if (bytenr == 0 && info->first_logical_byte > ret->start)
234 info->first_logical_byte = ret->start;
236 spin_unlock(&info->block_group_cache_lock);
242 * Return the block group that starts at or after bytenr
244 struct btrfs_block_group *btrfs_lookup_first_block_group(
245 struct btrfs_fs_info *info, u64 bytenr)
247 return block_group_cache_tree_search(info, bytenr, 0);
251 * Return the block group that contains the given bytenr
253 struct btrfs_block_group *btrfs_lookup_block_group(
254 struct btrfs_fs_info *info, u64 bytenr)
256 return block_group_cache_tree_search(info, bytenr, 1);
259 struct btrfs_block_group *btrfs_next_block_group(
260 struct btrfs_block_group *cache)
262 struct btrfs_fs_info *fs_info = cache->fs_info;
263 struct rb_node *node;
265 spin_lock(&fs_info->block_group_cache_lock);
267 /* If our block group was removed, we need a full search. */
268 if (RB_EMPTY_NODE(&cache->cache_node)) {
269 const u64 next_bytenr = cache->start + cache->length;
271 spin_unlock(&fs_info->block_group_cache_lock);
272 btrfs_put_block_group(cache);
273 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
275 node = rb_next(&cache->cache_node);
276 btrfs_put_block_group(cache);
278 cache = rb_entry(node, struct btrfs_block_group, cache_node);
279 btrfs_get_block_group(cache);
282 spin_unlock(&fs_info->block_group_cache_lock);
286 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
288 struct btrfs_block_group *bg;
291 bg = btrfs_lookup_block_group(fs_info, bytenr);
295 spin_lock(&bg->lock);
299 atomic_inc(&bg->nocow_writers);
300 spin_unlock(&bg->lock);
302 /* No put on block group, done by btrfs_dec_nocow_writers */
304 btrfs_put_block_group(bg);
309 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
311 struct btrfs_block_group *bg;
313 bg = btrfs_lookup_block_group(fs_info, bytenr);
315 if (atomic_dec_and_test(&bg->nocow_writers))
316 wake_up_var(&bg->nocow_writers);
318 * Once for our lookup and once for the lookup done by a previous call
319 * to btrfs_inc_nocow_writers()
321 btrfs_put_block_group(bg);
322 btrfs_put_block_group(bg);
325 void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
327 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
330 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
333 struct btrfs_block_group *bg;
335 bg = btrfs_lookup_block_group(fs_info, start);
337 if (atomic_dec_and_test(&bg->reservations))
338 wake_up_var(&bg->reservations);
339 btrfs_put_block_group(bg);
342 void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
344 struct btrfs_space_info *space_info = bg->space_info;
348 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
352 * Our block group is read only but before we set it to read only,
353 * some task might have had allocated an extent from it already, but it
354 * has not yet created a respective ordered extent (and added it to a
355 * root's list of ordered extents).
356 * Therefore wait for any task currently allocating extents, since the
357 * block group's reservations counter is incremented while a read lock
358 * on the groups' semaphore is held and decremented after releasing
359 * the read access on that semaphore and creating the ordered extent.
361 down_write(&space_info->groups_sem);
362 up_write(&space_info->groups_sem);
364 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
367 struct btrfs_caching_control *btrfs_get_caching_control(
368 struct btrfs_block_group *cache)
370 struct btrfs_caching_control *ctl;
372 spin_lock(&cache->lock);
373 if (!cache->caching_ctl) {
374 spin_unlock(&cache->lock);
378 ctl = cache->caching_ctl;
379 refcount_inc(&ctl->count);
380 spin_unlock(&cache->lock);
384 void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
386 if (refcount_dec_and_test(&ctl->count))
391 * When we wait for progress in the block group caching, its because our
392 * allocation attempt failed at least once. So, we must sleep and let some
393 * progress happen before we try again.
395 * This function will sleep at least once waiting for new free space to show
396 * up, and then it will check the block group free space numbers for our min
397 * num_bytes. Another option is to have it go ahead and look in the rbtree for
398 * a free extent of a given size, but this is a good start.
400 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
401 * any of the information in this block group.
403 void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
406 struct btrfs_caching_control *caching_ctl;
408 caching_ctl = btrfs_get_caching_control(cache);
412 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
413 (cache->free_space_ctl->free_space >= num_bytes));
415 btrfs_put_caching_control(caching_ctl);
418 int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
420 struct btrfs_caching_control *caching_ctl;
423 caching_ctl = btrfs_get_caching_control(cache);
425 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
427 wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
428 if (cache->cached == BTRFS_CACHE_ERROR)
430 btrfs_put_caching_control(caching_ctl);
434 #ifdef CONFIG_BTRFS_DEBUG
435 static void fragment_free_space(struct btrfs_block_group *block_group)
437 struct btrfs_fs_info *fs_info = block_group->fs_info;
438 u64 start = block_group->start;
439 u64 len = block_group->length;
440 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
441 fs_info->nodesize : fs_info->sectorsize;
442 u64 step = chunk << 1;
444 while (len > chunk) {
445 btrfs_remove_free_space(block_group, start, chunk);
456 * This is only called by btrfs_cache_block_group, since we could have freed
457 * extents we need to check the pinned_extents for any extents that can't be
458 * used yet since their free space will be released as soon as the transaction
461 u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
463 struct btrfs_fs_info *info = block_group->fs_info;
464 u64 extent_start, extent_end, size, total_added = 0;
467 while (start < end) {
468 ret = find_first_extent_bit(&info->excluded_extents, start,
469 &extent_start, &extent_end,
470 EXTENT_DIRTY | EXTENT_UPTODATE,
475 if (extent_start <= start) {
476 start = extent_end + 1;
477 } else if (extent_start > start && extent_start < end) {
478 size = extent_start - start;
480 ret = btrfs_add_free_space_async_trimmed(block_group,
482 BUG_ON(ret); /* -ENOMEM or logic error */
483 start = extent_end + 1;
492 ret = btrfs_add_free_space_async_trimmed(block_group, start,
494 BUG_ON(ret); /* -ENOMEM or logic error */
500 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
502 struct btrfs_block_group *block_group = caching_ctl->block_group;
503 struct btrfs_fs_info *fs_info = block_group->fs_info;
504 struct btrfs_root *extent_root = fs_info->extent_root;
505 struct btrfs_path *path;
506 struct extent_buffer *leaf;
507 struct btrfs_key key;
514 path = btrfs_alloc_path();
518 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
520 #ifdef CONFIG_BTRFS_DEBUG
522 * If we're fragmenting we don't want to make anybody think we can
523 * allocate from this block group until we've had a chance to fragment
526 if (btrfs_should_fragment_free_space(block_group))
530 * We don't want to deadlock with somebody trying to allocate a new
531 * extent for the extent root while also trying to search the extent
532 * root to add free space. So we skip locking and search the commit
533 * root, since its read-only
535 path->skip_locking = 1;
536 path->search_commit_root = 1;
537 path->reada = READA_FORWARD;
541 key.type = BTRFS_EXTENT_ITEM_KEY;
544 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
548 leaf = path->nodes[0];
549 nritems = btrfs_header_nritems(leaf);
552 if (btrfs_fs_closing(fs_info) > 1) {
557 if (path->slots[0] < nritems) {
558 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
560 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
564 if (need_resched() ||
565 rwsem_is_contended(&fs_info->commit_root_sem)) {
567 caching_ctl->progress = last;
568 btrfs_release_path(path);
569 up_read(&fs_info->commit_root_sem);
570 mutex_unlock(&caching_ctl->mutex);
572 mutex_lock(&caching_ctl->mutex);
573 down_read(&fs_info->commit_root_sem);
577 ret = btrfs_next_leaf(extent_root, path);
582 leaf = path->nodes[0];
583 nritems = btrfs_header_nritems(leaf);
587 if (key.objectid < last) {
590 key.type = BTRFS_EXTENT_ITEM_KEY;
593 caching_ctl->progress = last;
594 btrfs_release_path(path);
598 if (key.objectid < block_group->start) {
603 if (key.objectid >= block_group->start + block_group->length)
606 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
607 key.type == BTRFS_METADATA_ITEM_KEY) {
608 total_found += add_new_free_space(block_group, last,
610 if (key.type == BTRFS_METADATA_ITEM_KEY)
611 last = key.objectid +
614 last = key.objectid + key.offset;
616 if (total_found > CACHING_CTL_WAKE_UP) {
619 wake_up(&caching_ctl->wait);
626 total_found += add_new_free_space(block_group, last,
627 block_group->start + block_group->length);
628 caching_ctl->progress = (u64)-1;
631 btrfs_free_path(path);
635 static noinline void caching_thread(struct btrfs_work *work)
637 struct btrfs_block_group *block_group;
638 struct btrfs_fs_info *fs_info;
639 struct btrfs_caching_control *caching_ctl;
642 caching_ctl = container_of(work, struct btrfs_caching_control, work);
643 block_group = caching_ctl->block_group;
644 fs_info = block_group->fs_info;
646 mutex_lock(&caching_ctl->mutex);
647 down_read(&fs_info->commit_root_sem);
650 * If we are in the transaction that populated the free space tree we
651 * can't actually cache from the free space tree as our commit root and
652 * real root are the same, so we could change the contents of the blocks
653 * while caching. Instead do the slow caching in this case, and after
654 * the transaction has committed we will be safe.
656 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
657 !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
658 ret = load_free_space_tree(caching_ctl);
660 ret = load_extent_tree_free(caching_ctl);
662 spin_lock(&block_group->lock);
663 block_group->caching_ctl = NULL;
664 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
665 spin_unlock(&block_group->lock);
667 #ifdef CONFIG_BTRFS_DEBUG
668 if (btrfs_should_fragment_free_space(block_group)) {
671 spin_lock(&block_group->space_info->lock);
672 spin_lock(&block_group->lock);
673 bytes_used = block_group->length - block_group->used;
674 block_group->space_info->bytes_used += bytes_used >> 1;
675 spin_unlock(&block_group->lock);
676 spin_unlock(&block_group->space_info->lock);
677 fragment_free_space(block_group);
681 caching_ctl->progress = (u64)-1;
683 up_read(&fs_info->commit_root_sem);
684 btrfs_free_excluded_extents(block_group);
685 mutex_unlock(&caching_ctl->mutex);
687 wake_up(&caching_ctl->wait);
689 btrfs_put_caching_control(caching_ctl);
690 btrfs_put_block_group(block_group);
693 int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
696 struct btrfs_fs_info *fs_info = cache->fs_info;
697 struct btrfs_caching_control *caching_ctl;
700 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
704 INIT_LIST_HEAD(&caching_ctl->list);
705 mutex_init(&caching_ctl->mutex);
706 init_waitqueue_head(&caching_ctl->wait);
707 caching_ctl->block_group = cache;
708 caching_ctl->progress = cache->start;
709 refcount_set(&caching_ctl->count, 1);
710 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
712 spin_lock(&cache->lock);
714 * This should be a rare occasion, but this could happen I think in the
715 * case where one thread starts to load the space cache info, and then
716 * some other thread starts a transaction commit which tries to do an
717 * allocation while the other thread is still loading the space cache
718 * info. The previous loop should have kept us from choosing this block
719 * group, but if we've moved to the state where we will wait on caching
720 * block groups we need to first check if we're doing a fast load here,
721 * so we can wait for it to finish, otherwise we could end up allocating
722 * from a block group who's cache gets evicted for one reason or
725 while (cache->cached == BTRFS_CACHE_FAST) {
726 struct btrfs_caching_control *ctl;
728 ctl = cache->caching_ctl;
729 refcount_inc(&ctl->count);
730 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
731 spin_unlock(&cache->lock);
735 finish_wait(&ctl->wait, &wait);
736 btrfs_put_caching_control(ctl);
737 spin_lock(&cache->lock);
740 if (cache->cached != BTRFS_CACHE_NO) {
741 spin_unlock(&cache->lock);
745 WARN_ON(cache->caching_ctl);
746 cache->caching_ctl = caching_ctl;
747 cache->cached = BTRFS_CACHE_FAST;
748 spin_unlock(&cache->lock);
750 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
751 mutex_lock(&caching_ctl->mutex);
752 ret = load_free_space_cache(cache);
754 spin_lock(&cache->lock);
756 cache->caching_ctl = NULL;
757 cache->cached = BTRFS_CACHE_FINISHED;
758 cache->last_byte_to_unpin = (u64)-1;
759 caching_ctl->progress = (u64)-1;
761 if (load_cache_only) {
762 cache->caching_ctl = NULL;
763 cache->cached = BTRFS_CACHE_NO;
765 cache->cached = BTRFS_CACHE_STARTED;
766 cache->has_caching_ctl = 1;
769 spin_unlock(&cache->lock);
770 #ifdef CONFIG_BTRFS_DEBUG
772 btrfs_should_fragment_free_space(cache)) {
775 spin_lock(&cache->space_info->lock);
776 spin_lock(&cache->lock);
777 bytes_used = cache->length - cache->used;
778 cache->space_info->bytes_used += bytes_used >> 1;
779 spin_unlock(&cache->lock);
780 spin_unlock(&cache->space_info->lock);
781 fragment_free_space(cache);
784 mutex_unlock(&caching_ctl->mutex);
786 wake_up(&caching_ctl->wait);
788 btrfs_put_caching_control(caching_ctl);
789 btrfs_free_excluded_extents(cache);
794 * We're either using the free space tree or no caching at all.
795 * Set cached to the appropriate value and wakeup any waiters.
797 spin_lock(&cache->lock);
798 if (load_cache_only) {
799 cache->caching_ctl = NULL;
800 cache->cached = BTRFS_CACHE_NO;
802 cache->cached = BTRFS_CACHE_STARTED;
803 cache->has_caching_ctl = 1;
805 spin_unlock(&cache->lock);
806 wake_up(&caching_ctl->wait);
809 if (load_cache_only) {
810 btrfs_put_caching_control(caching_ctl);
814 down_write(&fs_info->commit_root_sem);
815 refcount_inc(&caching_ctl->count);
816 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
817 up_write(&fs_info->commit_root_sem);
819 btrfs_get_block_group(cache);
821 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
826 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
828 u64 extra_flags = chunk_to_extended(flags) &
829 BTRFS_EXTENDED_PROFILE_MASK;
831 write_seqlock(&fs_info->profiles_lock);
832 if (flags & BTRFS_BLOCK_GROUP_DATA)
833 fs_info->avail_data_alloc_bits &= ~extra_flags;
834 if (flags & BTRFS_BLOCK_GROUP_METADATA)
835 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
836 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
837 fs_info->avail_system_alloc_bits &= ~extra_flags;
838 write_sequnlock(&fs_info->profiles_lock);
842 * Clear incompat bits for the following feature(s):
844 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
845 * in the whole filesystem
847 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
849 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
851 bool found_raid56 = false;
852 bool found_raid1c34 = false;
854 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
855 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
856 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
857 struct list_head *head = &fs_info->space_info;
858 struct btrfs_space_info *sinfo;
860 list_for_each_entry_rcu(sinfo, head, list) {
861 down_read(&sinfo->groups_sem);
862 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
864 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
866 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
867 found_raid1c34 = true;
868 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
869 found_raid1c34 = true;
870 up_read(&sinfo->groups_sem);
873 btrfs_clear_fs_incompat(fs_info, RAID56);
875 btrfs_clear_fs_incompat(fs_info, RAID1C34);
879 static int remove_block_group_item(struct btrfs_trans_handle *trans,
880 struct btrfs_path *path,
881 struct btrfs_block_group *block_group)
883 struct btrfs_fs_info *fs_info = trans->fs_info;
884 struct btrfs_root *root;
885 struct btrfs_key key;
888 root = fs_info->extent_root;
889 key.objectid = block_group->start;
890 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
891 key.offset = block_group->length;
893 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
899 ret = btrfs_del_item(trans, root, path);
903 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
904 u64 group_start, struct extent_map *em)
906 struct btrfs_fs_info *fs_info = trans->fs_info;
907 struct btrfs_path *path;
908 struct btrfs_block_group *block_group;
909 struct btrfs_free_cluster *cluster;
910 struct btrfs_root *tree_root = fs_info->tree_root;
911 struct btrfs_key key;
913 struct kobject *kobj = NULL;
917 struct btrfs_caching_control *caching_ctl = NULL;
919 bool remove_rsv = false;
921 block_group = btrfs_lookup_block_group(fs_info, group_start);
922 BUG_ON(!block_group);
923 BUG_ON(!block_group->ro);
925 trace_btrfs_remove_block_group(block_group);
927 * Free the reserved super bytes from this block group before
930 btrfs_free_excluded_extents(block_group);
931 btrfs_free_ref_tree_range(fs_info, block_group->start,
932 block_group->length);
934 index = btrfs_bg_flags_to_raid_index(block_group->flags);
935 factor = btrfs_bg_type_to_factor(block_group->flags);
937 /* make sure this block group isn't part of an allocation cluster */
938 cluster = &fs_info->data_alloc_cluster;
939 spin_lock(&cluster->refill_lock);
940 btrfs_return_cluster_to_free_space(block_group, cluster);
941 spin_unlock(&cluster->refill_lock);
944 * make sure this block group isn't part of a metadata
947 cluster = &fs_info->meta_alloc_cluster;
948 spin_lock(&cluster->refill_lock);
949 btrfs_return_cluster_to_free_space(block_group, cluster);
950 spin_unlock(&cluster->refill_lock);
952 path = btrfs_alloc_path();
959 * get the inode first so any iput calls done for the io_list
960 * aren't the final iput (no unlinks allowed now)
962 inode = lookup_free_space_inode(block_group, path);
964 mutex_lock(&trans->transaction->cache_write_mutex);
966 * Make sure our free space cache IO is done before removing the
969 spin_lock(&trans->transaction->dirty_bgs_lock);
970 if (!list_empty(&block_group->io_list)) {
971 list_del_init(&block_group->io_list);
973 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
975 spin_unlock(&trans->transaction->dirty_bgs_lock);
976 btrfs_wait_cache_io(trans, block_group, path);
977 btrfs_put_block_group(block_group);
978 spin_lock(&trans->transaction->dirty_bgs_lock);
981 if (!list_empty(&block_group->dirty_list)) {
982 list_del_init(&block_group->dirty_list);
984 btrfs_put_block_group(block_group);
986 spin_unlock(&trans->transaction->dirty_bgs_lock);
987 mutex_unlock(&trans->transaction->cache_write_mutex);
989 if (!IS_ERR(inode)) {
990 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
992 btrfs_add_delayed_iput(inode);
996 /* One for the block groups ref */
997 spin_lock(&block_group->lock);
998 if (block_group->iref) {
999 block_group->iref = 0;
1000 block_group->inode = NULL;
1001 spin_unlock(&block_group->lock);
1004 spin_unlock(&block_group->lock);
1006 /* One for our lookup ref */
1007 btrfs_add_delayed_iput(inode);
1010 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
1012 key.offset = block_group->start;
1014 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
1018 btrfs_release_path(path);
1020 ret = btrfs_del_item(trans, tree_root, path);
1023 btrfs_release_path(path);
1026 spin_lock(&fs_info->block_group_cache_lock);
1027 rb_erase(&block_group->cache_node,
1028 &fs_info->block_group_cache_tree);
1029 RB_CLEAR_NODE(&block_group->cache_node);
1031 /* Once for the block groups rbtree */
1032 btrfs_put_block_group(block_group);
1034 if (fs_info->first_logical_byte == block_group->start)
1035 fs_info->first_logical_byte = (u64)-1;
1036 spin_unlock(&fs_info->block_group_cache_lock);
1038 down_write(&block_group->space_info->groups_sem);
1040 * we must use list_del_init so people can check to see if they
1041 * are still on the list after taking the semaphore
1043 list_del_init(&block_group->list);
1044 if (list_empty(&block_group->space_info->block_groups[index])) {
1045 kobj = block_group->space_info->block_group_kobjs[index];
1046 block_group->space_info->block_group_kobjs[index] = NULL;
1047 clear_avail_alloc_bits(fs_info, block_group->flags);
1049 up_write(&block_group->space_info->groups_sem);
1050 clear_incompat_bg_bits(fs_info, block_group->flags);
1056 if (block_group->has_caching_ctl)
1057 caching_ctl = btrfs_get_caching_control(block_group);
1058 if (block_group->cached == BTRFS_CACHE_STARTED)
1059 btrfs_wait_block_group_cache_done(block_group);
1060 if (block_group->has_caching_ctl) {
1061 down_write(&fs_info->commit_root_sem);
1063 struct btrfs_caching_control *ctl;
1065 list_for_each_entry(ctl,
1066 &fs_info->caching_block_groups, list)
1067 if (ctl->block_group == block_group) {
1069 refcount_inc(&caching_ctl->count);
1074 list_del_init(&caching_ctl->list);
1075 up_write(&fs_info->commit_root_sem);
1077 /* Once for the caching bgs list and once for us. */
1078 btrfs_put_caching_control(caching_ctl);
1079 btrfs_put_caching_control(caching_ctl);
1083 spin_lock(&trans->transaction->dirty_bgs_lock);
1084 WARN_ON(!list_empty(&block_group->dirty_list));
1085 WARN_ON(!list_empty(&block_group->io_list));
1086 spin_unlock(&trans->transaction->dirty_bgs_lock);
1088 btrfs_remove_free_space_cache(block_group);
1090 spin_lock(&block_group->space_info->lock);
1091 list_del_init(&block_group->ro_list);
1093 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1094 WARN_ON(block_group->space_info->total_bytes
1095 < block_group->length);
1096 WARN_ON(block_group->space_info->bytes_readonly
1097 < block_group->length);
1098 WARN_ON(block_group->space_info->disk_total
1099 < block_group->length * factor);
1101 block_group->space_info->total_bytes -= block_group->length;
1102 block_group->space_info->bytes_readonly -= block_group->length;
1103 block_group->space_info->disk_total -= block_group->length * factor;
1105 spin_unlock(&block_group->space_info->lock);
1108 * Remove the free space for the block group from the free space tree
1109 * and the block group's item from the extent tree before marking the
1110 * block group as removed. This is to prevent races with tasks that
1111 * freeze and unfreeze a block group, this task and another task
1112 * allocating a new block group - the unfreeze task ends up removing
1113 * the block group's extent map before the task calling this function
1114 * deletes the block group item from the extent tree, allowing for
1115 * another task to attempt to create another block group with the same
1116 * item key (and failing with -EEXIST and a transaction abort).
1118 ret = remove_block_group_free_space(trans, block_group);
1122 ret = remove_block_group_item(trans, path, block_group);
1126 spin_lock(&block_group->lock);
1127 block_group->removed = 1;
1129 * At this point trimming or scrub can't start on this block group,
1130 * because we removed the block group from the rbtree
1131 * fs_info->block_group_cache_tree so no one can't find it anymore and
1132 * even if someone already got this block group before we removed it
1133 * from the rbtree, they have already incremented block_group->frozen -
1134 * if they didn't, for the trimming case they won't find any free space
1135 * entries because we already removed them all when we called
1136 * btrfs_remove_free_space_cache().
1138 * And we must not remove the extent map from the fs_info->mapping_tree
1139 * to prevent the same logical address range and physical device space
1140 * ranges from being reused for a new block group. This is needed to
1141 * avoid races with trimming and scrub.
1143 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1144 * completely transactionless, so while it is trimming a range the
1145 * currently running transaction might finish and a new one start,
1146 * allowing for new block groups to be created that can reuse the same
1147 * physical device locations unless we take this special care.
1149 * There may also be an implicit trim operation if the file system
1150 * is mounted with -odiscard. The same protections must remain
1151 * in place until the extents have been discarded completely when
1152 * the transaction commit has completed.
1154 remove_em = (atomic_read(&block_group->frozen) == 0);
1155 spin_unlock(&block_group->lock);
1158 struct extent_map_tree *em_tree;
1160 em_tree = &fs_info->mapping_tree;
1161 write_lock(&em_tree->lock);
1162 remove_extent_mapping(em_tree, em);
1163 write_unlock(&em_tree->lock);
1164 /* once for the tree */
1165 free_extent_map(em);
1169 /* Once for the lookup reference */
1170 btrfs_put_block_group(block_group);
1172 btrfs_delayed_refs_rsv_release(fs_info, 1);
1173 btrfs_free_path(path);
1177 struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1178 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1180 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1181 struct extent_map *em;
1182 struct map_lookup *map;
1183 unsigned int num_items;
1185 read_lock(&em_tree->lock);
1186 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1187 read_unlock(&em_tree->lock);
1188 ASSERT(em && em->start == chunk_offset);
1191 * We need to reserve 3 + N units from the metadata space info in order
1192 * to remove a block group (done at btrfs_remove_chunk() and at
1193 * btrfs_remove_block_group()), which are used for:
1195 * 1 unit for adding the free space inode's orphan (located in the tree
1197 * 1 unit for deleting the block group item (located in the extent
1199 * 1 unit for deleting the free space item (located in tree of tree
1201 * N units for deleting N device extent items corresponding to each
1202 * stripe (located in the device tree).
1204 * In order to remove a block group we also need to reserve units in the
1205 * system space info in order to update the chunk tree (update one or
1206 * more device items and remove one chunk item), but this is done at
1207 * btrfs_remove_chunk() through a call to check_system_chunk().
1209 map = em->map_lookup;
1210 num_items = 3 + map->num_stripes;
1211 free_extent_map(em);
1213 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
1218 * Mark block group @cache read-only, so later write won't happen to block
1221 * If @force is not set, this function will only mark the block group readonly
1222 * if we have enough free space (1M) in other metadata/system block groups.
1223 * If @force is not set, this function will mark the block group readonly
1224 * without checking free space.
1226 * NOTE: This function doesn't care if other block groups can contain all the
1227 * data in this block group. That check should be done by relocation routine,
1228 * not this function.
1230 static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
1232 struct btrfs_space_info *sinfo = cache->space_info;
1236 spin_lock(&sinfo->lock);
1237 spin_lock(&cache->lock);
1239 if (cache->swap_extents) {
1250 num_bytes = cache->length - cache->reserved - cache->pinned -
1251 cache->bytes_super - cache->used;
1254 * Data never overcommits, even in mixed mode, so do just the straight
1255 * check of left over space in how much we have allocated.
1259 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1260 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1263 * Here we make sure if we mark this bg RO, we still have enough
1264 * free space as buffer.
1266 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1270 * We overcommit metadata, so we need to do the
1271 * btrfs_can_overcommit check here, and we need to pass in
1272 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1273 * leeway to allow us to mark this block group as read only.
1275 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1276 BTRFS_RESERVE_NO_FLUSH))
1281 sinfo->bytes_readonly += num_bytes;
1283 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
1286 spin_unlock(&cache->lock);
1287 spin_unlock(&sinfo->lock);
1288 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1289 btrfs_info(cache->fs_info,
1290 "unable to make block group %llu ro", cache->start);
1291 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1296 static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1297 struct btrfs_block_group *bg)
1299 struct btrfs_fs_info *fs_info = bg->fs_info;
1300 struct btrfs_transaction *prev_trans = NULL;
1301 const u64 start = bg->start;
1302 const u64 end = start + bg->length - 1;
1305 spin_lock(&fs_info->trans_lock);
1306 if (trans->transaction->list.prev != &fs_info->trans_list) {
1307 prev_trans = list_last_entry(&trans->transaction->list,
1308 struct btrfs_transaction, list);
1309 refcount_inc(&prev_trans->use_count);
1311 spin_unlock(&fs_info->trans_lock);
1314 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1315 * btrfs_finish_extent_commit(). If we are at transaction N, another
1316 * task might be running finish_extent_commit() for the previous
1317 * transaction N - 1, and have seen a range belonging to the block
1318 * group in pinned_extents before we were able to clear the whole block
1319 * group range from pinned_extents. This means that task can lookup for
1320 * the block group after we unpinned it from pinned_extents and removed
1321 * it, leading to a BUG_ON() at unpin_extent_range().
1323 mutex_lock(&fs_info->unused_bg_unpin_mutex);
1325 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1331 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
1334 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1336 btrfs_put_transaction(prev_trans);
1342 * Process the unused_bgs list and remove any that don't have any allocated
1343 * space inside of them.
1345 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1347 struct btrfs_block_group *block_group;
1348 struct btrfs_space_info *space_info;
1349 struct btrfs_trans_handle *trans;
1350 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1353 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1356 spin_lock(&fs_info->unused_bgs_lock);
1357 while (!list_empty(&fs_info->unused_bgs)) {
1360 block_group = list_first_entry(&fs_info->unused_bgs,
1361 struct btrfs_block_group,
1363 list_del_init(&block_group->bg_list);
1365 space_info = block_group->space_info;
1367 if (ret || btrfs_mixed_space_info(space_info)) {
1368 btrfs_put_block_group(block_group);
1371 spin_unlock(&fs_info->unused_bgs_lock);
1373 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1375 mutex_lock(&fs_info->delete_unused_bgs_mutex);
1377 /* Don't want to race with allocators so take the groups_sem */
1378 down_write(&space_info->groups_sem);
1381 * Async discard moves the final block group discard to be prior
1382 * to the unused_bgs code path. Therefore, if it's not fully
1383 * trimmed, punt it back to the async discard lists.
1385 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1386 !btrfs_is_free_space_trimmed(block_group)) {
1387 trace_btrfs_skip_unused_block_group(block_group);
1388 up_write(&space_info->groups_sem);
1389 /* Requeue if we failed because of async discard */
1390 btrfs_discard_queue_work(&fs_info->discard_ctl,
1395 spin_lock(&block_group->lock);
1396 if (block_group->reserved || block_group->pinned ||
1397 block_group->used || block_group->ro ||
1398 list_is_singular(&block_group->list)) {
1400 * We want to bail if we made new allocations or have
1401 * outstanding allocations in this block group. We do
1402 * the ro check in case balance is currently acting on
1405 trace_btrfs_skip_unused_block_group(block_group);
1406 spin_unlock(&block_group->lock);
1407 up_write(&space_info->groups_sem);
1410 spin_unlock(&block_group->lock);
1412 /* We don't want to force the issue, only flip if it's ok. */
1413 ret = inc_block_group_ro(block_group, 0);
1414 up_write(&space_info->groups_sem);
1421 * Want to do this before we do anything else so we can recover
1422 * properly if we fail to join the transaction.
1424 trans = btrfs_start_trans_remove_block_group(fs_info,
1425 block_group->start);
1426 if (IS_ERR(trans)) {
1427 btrfs_dec_block_group_ro(block_group);
1428 ret = PTR_ERR(trans);
1433 * We could have pending pinned extents for this block group,
1434 * just delete them, we don't care about them anymore.
1436 if (!clean_pinned_extents(trans, block_group)) {
1437 btrfs_dec_block_group_ro(block_group);
1442 * At this point, the block_group is read only and should fail
1443 * new allocations. However, btrfs_finish_extent_commit() can
1444 * cause this block_group to be placed back on the discard
1445 * lists because now the block_group isn't fully discarded.
1446 * Bail here and try again later after discarding everything.
1448 spin_lock(&fs_info->discard_ctl.lock);
1449 if (!list_empty(&block_group->discard_list)) {
1450 spin_unlock(&fs_info->discard_ctl.lock);
1451 btrfs_dec_block_group_ro(block_group);
1452 btrfs_discard_queue_work(&fs_info->discard_ctl,
1456 spin_unlock(&fs_info->discard_ctl.lock);
1458 /* Reset pinned so btrfs_put_block_group doesn't complain */
1459 spin_lock(&space_info->lock);
1460 spin_lock(&block_group->lock);
1462 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1463 -block_group->pinned);
1464 space_info->bytes_readonly += block_group->pinned;
1465 __btrfs_mod_total_bytes_pinned(space_info, -block_group->pinned);
1466 block_group->pinned = 0;
1468 spin_unlock(&block_group->lock);
1469 spin_unlock(&space_info->lock);
1472 * The normal path here is an unused block group is passed here,
1473 * then trimming is handled in the transaction commit path.
1474 * Async discard interposes before this to do the trimming
1475 * before coming down the unused block group path as trimming
1476 * will no longer be done later in the transaction commit path.
1478 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1481 /* DISCARD can flip during remount */
1482 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC);
1484 /* Implicit trim during transaction commit. */
1486 btrfs_freeze_block_group(block_group);
1489 * Btrfs_remove_chunk will abort the transaction if things go
1492 ret = btrfs_remove_chunk(trans, block_group->start);
1496 btrfs_unfreeze_block_group(block_group);
1501 * If we're not mounted with -odiscard, we can just forget
1502 * about this block group. Otherwise we'll need to wait
1503 * until transaction commit to do the actual discard.
1506 spin_lock(&fs_info->unused_bgs_lock);
1508 * A concurrent scrub might have added us to the list
1509 * fs_info->unused_bgs, so use a list_move operation
1510 * to add the block group to the deleted_bgs list.
1512 list_move(&block_group->bg_list,
1513 &trans->transaction->deleted_bgs);
1514 spin_unlock(&fs_info->unused_bgs_lock);
1515 btrfs_get_block_group(block_group);
1518 btrfs_end_transaction(trans);
1520 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1521 btrfs_put_block_group(block_group);
1522 spin_lock(&fs_info->unused_bgs_lock);
1524 spin_unlock(&fs_info->unused_bgs_lock);
1528 btrfs_end_transaction(trans);
1529 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1530 btrfs_put_block_group(block_group);
1531 btrfs_discard_punt_unused_bgs_list(fs_info);
1534 void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1536 struct btrfs_fs_info *fs_info = bg->fs_info;
1538 spin_lock(&fs_info->unused_bgs_lock);
1539 if (list_empty(&bg->bg_list)) {
1540 btrfs_get_block_group(bg);
1541 trace_btrfs_add_unused_block_group(bg);
1542 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1544 spin_unlock(&fs_info->unused_bgs_lock);
1547 static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1548 struct btrfs_path *path)
1550 struct extent_map_tree *em_tree;
1551 struct extent_map *em;
1552 struct btrfs_block_group_item bg;
1553 struct extent_buffer *leaf;
1558 slot = path->slots[0];
1559 leaf = path->nodes[0];
1561 em_tree = &fs_info->mapping_tree;
1562 read_lock(&em_tree->lock);
1563 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1564 read_unlock(&em_tree->lock);
1567 "logical %llu len %llu found bg but no related chunk",
1568 key->objectid, key->offset);
1572 if (em->start != key->objectid || em->len != key->offset) {
1574 "block group %llu len %llu mismatch with chunk %llu len %llu",
1575 key->objectid, key->offset, em->start, em->len);
1580 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1582 flags = btrfs_stack_block_group_flags(&bg) &
1583 BTRFS_BLOCK_GROUP_TYPE_MASK;
1585 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1587 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1588 key->objectid, key->offset, flags,
1589 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1594 free_extent_map(em);
1598 static int find_first_block_group(struct btrfs_fs_info *fs_info,
1599 struct btrfs_path *path,
1600 struct btrfs_key *key)
1602 struct btrfs_root *root = fs_info->extent_root;
1604 struct btrfs_key found_key;
1605 struct extent_buffer *leaf;
1608 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1613 slot = path->slots[0];
1614 leaf = path->nodes[0];
1615 if (slot >= btrfs_header_nritems(leaf)) {
1616 ret = btrfs_next_leaf(root, path);
1623 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1625 if (found_key.objectid >= key->objectid &&
1626 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1627 ret = read_bg_from_eb(fs_info, &found_key, path);
1637 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1639 u64 extra_flags = chunk_to_extended(flags) &
1640 BTRFS_EXTENDED_PROFILE_MASK;
1642 write_seqlock(&fs_info->profiles_lock);
1643 if (flags & BTRFS_BLOCK_GROUP_DATA)
1644 fs_info->avail_data_alloc_bits |= extra_flags;
1645 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1646 fs_info->avail_metadata_alloc_bits |= extra_flags;
1647 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1648 fs_info->avail_system_alloc_bits |= extra_flags;
1649 write_sequnlock(&fs_info->profiles_lock);
1653 * btrfs_rmap_block - Map a physical disk address to a list of logical addresses
1654 * @chunk_start: logical address of block group
1655 * @physical: physical address to map to logical addresses
1656 * @logical: return array of logical addresses which map to @physical
1657 * @naddrs: length of @logical
1658 * @stripe_len: size of IO stripe for the given block group
1660 * Maps a particular @physical disk address to a list of @logical addresses.
1661 * Used primarily to exclude those portions of a block group that contain super
1665 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1666 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
1668 struct extent_map *em;
1669 struct map_lookup *map;
1672 u64 data_stripe_length;
1677 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1681 map = em->map_lookup;
1682 data_stripe_length = em->orig_block_len;
1683 io_stripe_size = map->stripe_len;
1685 /* For RAID5/6 adjust to a full IO stripe length */
1686 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
1687 io_stripe_size = map->stripe_len * nr_data_stripes(map);
1689 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
1695 for (i = 0; i < map->num_stripes; i++) {
1696 bool already_inserted = false;
1700 if (!in_range(physical, map->stripes[i].physical,
1701 data_stripe_length))
1704 stripe_nr = physical - map->stripes[i].physical;
1705 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
1707 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1708 stripe_nr = stripe_nr * map->num_stripes + i;
1709 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1710 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1711 stripe_nr = stripe_nr * map->num_stripes + i;
1714 * The remaining case would be for RAID56, multiply by
1715 * nr_data_stripes(). Alternatively, just use rmap_len below
1716 * instead of map->stripe_len
1719 bytenr = chunk_start + stripe_nr * io_stripe_size;
1721 /* Ensure we don't add duplicate addresses */
1722 for (j = 0; j < nr; j++) {
1723 if (buf[j] == bytenr) {
1724 already_inserted = true;
1729 if (!already_inserted)
1735 *stripe_len = io_stripe_size;
1737 free_extent_map(em);
1741 static int exclude_super_stripes(struct btrfs_block_group *cache)
1743 struct btrfs_fs_info *fs_info = cache->fs_info;
1749 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1750 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
1751 cache->bytes_super += stripe_len;
1752 ret = btrfs_add_excluded_extent(fs_info, cache->start,
1758 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1759 bytenr = btrfs_sb_offset(i);
1760 ret = btrfs_rmap_block(fs_info, cache->start,
1761 bytenr, &logical, &nr, &stripe_len);
1766 u64 len = min_t(u64, stripe_len,
1767 cache->start + cache->length - logical[nr]);
1769 cache->bytes_super += len;
1770 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
1783 static void link_block_group(struct btrfs_block_group *cache)
1785 struct btrfs_space_info *space_info = cache->space_info;
1786 int index = btrfs_bg_flags_to_raid_index(cache->flags);
1788 down_write(&space_info->groups_sem);
1789 list_add_tail(&cache->list, &space_info->block_groups[index]);
1790 up_write(&space_info->groups_sem);
1793 static struct btrfs_block_group *btrfs_create_block_group_cache(
1794 struct btrfs_fs_info *fs_info, u64 start)
1796 struct btrfs_block_group *cache;
1798 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1802 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1804 if (!cache->free_space_ctl) {
1809 cache->start = start;
1811 cache->fs_info = fs_info;
1812 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
1814 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1816 refcount_set(&cache->refs, 1);
1817 spin_lock_init(&cache->lock);
1818 init_rwsem(&cache->data_rwsem);
1819 INIT_LIST_HEAD(&cache->list);
1820 INIT_LIST_HEAD(&cache->cluster_list);
1821 INIT_LIST_HEAD(&cache->bg_list);
1822 INIT_LIST_HEAD(&cache->ro_list);
1823 INIT_LIST_HEAD(&cache->discard_list);
1824 INIT_LIST_HEAD(&cache->dirty_list);
1825 INIT_LIST_HEAD(&cache->io_list);
1826 btrfs_init_free_space_ctl(cache);
1827 atomic_set(&cache->frozen, 0);
1828 mutex_init(&cache->free_space_lock);
1829 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1835 * Iterate all chunks and verify that each of them has the corresponding block
1838 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1840 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1841 struct extent_map *em;
1842 struct btrfs_block_group *bg;
1847 read_lock(&map_tree->lock);
1849 * lookup_extent_mapping will return the first extent map
1850 * intersecting the range, so setting @len to 1 is enough to
1851 * get the first chunk.
1853 em = lookup_extent_mapping(map_tree, start, 1);
1854 read_unlock(&map_tree->lock);
1858 bg = btrfs_lookup_block_group(fs_info, em->start);
1861 "chunk start=%llu len=%llu doesn't have corresponding block group",
1862 em->start, em->len);
1864 free_extent_map(em);
1867 if (bg->start != em->start || bg->length != em->len ||
1868 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1869 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1871 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
1873 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
1874 bg->start, bg->length,
1875 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
1877 free_extent_map(em);
1878 btrfs_put_block_group(bg);
1881 start = em->start + em->len;
1882 free_extent_map(em);
1883 btrfs_put_block_group(bg);
1888 static void read_block_group_item(struct btrfs_block_group *cache,
1889 struct btrfs_path *path,
1890 const struct btrfs_key *key)
1892 struct extent_buffer *leaf = path->nodes[0];
1893 struct btrfs_block_group_item bgi;
1894 int slot = path->slots[0];
1896 cache->length = key->offset;
1898 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
1900 cache->used = btrfs_stack_block_group_used(&bgi);
1901 cache->flags = btrfs_stack_block_group_flags(&bgi);
1904 static int read_one_block_group(struct btrfs_fs_info *info,
1905 struct btrfs_path *path,
1906 const struct btrfs_key *key,
1909 struct btrfs_block_group *cache;
1910 struct btrfs_space_info *space_info;
1911 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
1914 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
1916 cache = btrfs_create_block_group_cache(info, key->objectid);
1920 read_block_group_item(cache, path, key);
1922 set_free_space_tree_thresholds(cache);
1926 * When we mount with old space cache, we need to
1927 * set BTRFS_DC_CLEAR and set dirty flag.
1929 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
1930 * truncate the old free space cache inode and
1932 * b) Setting 'dirty flag' makes sure that we flush
1933 * the new space cache info onto disk.
1935 if (btrfs_test_opt(info, SPACE_CACHE))
1936 cache->disk_cache_state = BTRFS_DC_CLEAR;
1938 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
1939 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
1941 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
1948 * We need to exclude the super stripes now so that the space info has
1949 * super bytes accounted for, otherwise we'll think we have more space
1950 * than we actually do.
1952 ret = exclude_super_stripes(cache);
1954 /* We may have excluded something, so call this just in case. */
1955 btrfs_free_excluded_extents(cache);
1960 * Check for two cases, either we are full, and therefore don't need
1961 * to bother with the caching work since we won't find any space, or we
1962 * are empty, and we can just add all the space in and be done with it.
1963 * This saves us _a_lot_ of time, particularly in the full case.
1965 if (cache->length == cache->used) {
1966 cache->last_byte_to_unpin = (u64)-1;
1967 cache->cached = BTRFS_CACHE_FINISHED;
1968 btrfs_free_excluded_extents(cache);
1969 } else if (cache->used == 0) {
1970 cache->last_byte_to_unpin = (u64)-1;
1971 cache->cached = BTRFS_CACHE_FINISHED;
1972 add_new_free_space(cache, cache->start,
1973 cache->start + cache->length);
1974 btrfs_free_excluded_extents(cache);
1977 ret = btrfs_add_block_group_cache(info, cache);
1979 btrfs_remove_free_space_cache(cache);
1982 trace_btrfs_add_block_group(info, cache, 0);
1983 btrfs_update_space_info(info, cache->flags, cache->length,
1984 cache->used, cache->bytes_super, &space_info);
1986 cache->space_info = space_info;
1988 link_block_group(cache);
1990 set_avail_alloc_bits(info, cache->flags);
1991 if (btrfs_chunk_readonly(info, cache->start)) {
1992 inc_block_group_ro(cache, 1);
1993 } else if (cache->used == 0) {
1994 ASSERT(list_empty(&cache->bg_list));
1995 if (btrfs_test_opt(info, DISCARD_ASYNC))
1996 btrfs_discard_queue_work(&info->discard_ctl, cache);
1998 btrfs_mark_bg_unused(cache);
2002 btrfs_put_block_group(cache);
2006 int btrfs_read_block_groups(struct btrfs_fs_info *info)
2008 struct btrfs_path *path;
2010 struct btrfs_block_group *cache;
2011 struct btrfs_space_info *space_info;
2012 struct btrfs_key key;
2018 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2019 path = btrfs_alloc_path();
2023 cache_gen = btrfs_super_cache_generation(info->super_copy);
2024 if (btrfs_test_opt(info, SPACE_CACHE) &&
2025 btrfs_super_generation(info->super_copy) != cache_gen)
2027 if (btrfs_test_opt(info, CLEAR_CACHE))
2031 ret = find_first_block_group(info, path, &key);
2037 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2038 ret = read_one_block_group(info, path, &key, need_clear);
2041 key.objectid += key.offset;
2043 btrfs_release_path(path);
2045 btrfs_release_path(path);
2047 list_for_each_entry(space_info, &info->space_info, list) {
2050 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2051 if (list_empty(&space_info->block_groups[i]))
2053 cache = list_first_entry(&space_info->block_groups[i],
2054 struct btrfs_block_group,
2056 btrfs_sysfs_add_block_group_type(cache);
2059 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2060 (BTRFS_BLOCK_GROUP_RAID10 |
2061 BTRFS_BLOCK_GROUP_RAID1_MASK |
2062 BTRFS_BLOCK_GROUP_RAID56_MASK |
2063 BTRFS_BLOCK_GROUP_DUP)))
2066 * Avoid allocating from un-mirrored block group if there are
2067 * mirrored block groups.
2069 list_for_each_entry(cache,
2070 &space_info->block_groups[BTRFS_RAID_RAID0],
2072 inc_block_group_ro(cache, 1);
2073 list_for_each_entry(cache,
2074 &space_info->block_groups[BTRFS_RAID_SINGLE],
2076 inc_block_group_ro(cache, 1);
2079 btrfs_init_global_block_rsv(info);
2080 ret = check_chunk_block_group_mappings(info);
2082 btrfs_free_path(path);
2086 static int insert_block_group_item(struct btrfs_trans_handle *trans,
2087 struct btrfs_block_group *block_group)
2089 struct btrfs_fs_info *fs_info = trans->fs_info;
2090 struct btrfs_block_group_item bgi;
2091 struct btrfs_root *root;
2092 struct btrfs_key key;
2094 spin_lock(&block_group->lock);
2095 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2096 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2097 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2098 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2099 key.objectid = block_group->start;
2100 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2101 key.offset = block_group->length;
2102 spin_unlock(&block_group->lock);
2104 root = fs_info->extent_root;
2105 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2108 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2110 struct btrfs_fs_info *fs_info = trans->fs_info;
2111 struct btrfs_block_group *block_group;
2114 if (!trans->can_flush_pending_bgs)
2117 while (!list_empty(&trans->new_bgs)) {
2120 block_group = list_first_entry(&trans->new_bgs,
2121 struct btrfs_block_group,
2126 index = btrfs_bg_flags_to_raid_index(block_group->flags);
2128 ret = insert_block_group_item(trans, block_group);
2130 btrfs_abort_transaction(trans, ret);
2131 ret = btrfs_finish_chunk_alloc(trans, block_group->start,
2132 block_group->length);
2134 btrfs_abort_transaction(trans, ret);
2135 add_block_group_free_space(trans, block_group);
2138 * If we restriped during balance, we may have added a new raid
2139 * type, so now add the sysfs entries when it is safe to do so.
2140 * We don't have to worry about locking here as it's handled in
2141 * btrfs_sysfs_add_block_group_type.
2143 if (block_group->space_info->block_group_kobjs[index] == NULL)
2144 btrfs_sysfs_add_block_group_type(block_group);
2146 /* Already aborted the transaction if it failed. */
2148 btrfs_delayed_refs_rsv_release(fs_info, 1);
2149 list_del_init(&block_group->bg_list);
2151 btrfs_trans_release_chunk_metadata(trans);
2154 int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
2155 u64 type, u64 chunk_offset, u64 size)
2157 struct btrfs_fs_info *fs_info = trans->fs_info;
2158 struct btrfs_block_group *cache;
2161 btrfs_set_log_full_commit(trans);
2163 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
2167 cache->length = size;
2168 set_free_space_tree_thresholds(cache);
2169 cache->used = bytes_used;
2170 cache->flags = type;
2171 cache->last_byte_to_unpin = (u64)-1;
2172 cache->cached = BTRFS_CACHE_FINISHED;
2173 cache->needs_free_space = 1;
2174 ret = exclude_super_stripes(cache);
2176 /* We may have excluded something, so call this just in case */
2177 btrfs_free_excluded_extents(cache);
2178 btrfs_put_block_group(cache);
2182 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2184 btrfs_free_excluded_extents(cache);
2186 #ifdef CONFIG_BTRFS_DEBUG
2187 if (btrfs_should_fragment_free_space(cache)) {
2188 u64 new_bytes_used = size - bytes_used;
2190 bytes_used += new_bytes_used >> 1;
2191 fragment_free_space(cache);
2195 * Ensure the corresponding space_info object is created and
2196 * assigned to our block group. We want our bg to be added to the rbtree
2197 * with its ->space_info set.
2199 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2200 ASSERT(cache->space_info);
2202 ret = btrfs_add_block_group_cache(fs_info, cache);
2204 btrfs_remove_free_space_cache(cache);
2205 btrfs_put_block_group(cache);
2210 * Now that our block group has its ->space_info set and is inserted in
2211 * the rbtree, update the space info's counters.
2213 trace_btrfs_add_block_group(fs_info, cache, 1);
2214 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
2215 cache->bytes_super, &cache->space_info);
2216 btrfs_update_global_block_rsv(fs_info);
2218 link_block_group(cache);
2220 list_add_tail(&cache->bg_list, &trans->new_bgs);
2221 trans->delayed_ref_updates++;
2222 btrfs_update_delayed_refs_rsv(trans);
2224 set_avail_alloc_bits(fs_info, type);
2229 * Mark one block group RO, can be called several times for the same block
2232 * @cache: the destination block group
2233 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2234 * ensure we still have some free space after marking this
2237 int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2238 bool do_chunk_alloc)
2240 struct btrfs_fs_info *fs_info = cache->fs_info;
2241 struct btrfs_trans_handle *trans;
2246 trans = btrfs_join_transaction(fs_info->extent_root);
2248 return PTR_ERR(trans);
2251 * we're not allowed to set block groups readonly after the dirty
2252 * block groups cache has started writing. If it already started,
2253 * back off and let this transaction commit
2255 mutex_lock(&fs_info->ro_block_group_mutex);
2256 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2257 u64 transid = trans->transid;
2259 mutex_unlock(&fs_info->ro_block_group_mutex);
2260 btrfs_end_transaction(trans);
2262 ret = btrfs_wait_for_commit(fs_info, transid);
2268 if (do_chunk_alloc) {
2270 * If we are changing raid levels, try to allocate a
2271 * corresponding block group with the new raid level.
2273 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2274 if (alloc_flags != cache->flags) {
2275 ret = btrfs_chunk_alloc(trans, alloc_flags,
2278 * ENOSPC is allowed here, we may have enough space
2279 * already allocated at the new raid level to carry on
2288 ret = inc_block_group_ro(cache, 0);
2291 if (ret == -ETXTBSY)
2295 * Skip chunk alloction if the bg is SYSTEM, this is to avoid system
2296 * chunk allocation storm to exhaust the system chunk array. Otherwise
2297 * we still want to try our best to mark the block group read-only.
2299 if (!do_chunk_alloc && ret == -ENOSPC &&
2300 (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM))
2303 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2304 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2307 ret = inc_block_group_ro(cache, 0);
2308 if (ret == -ETXTBSY)
2311 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2312 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2313 mutex_lock(&fs_info->chunk_mutex);
2314 check_system_chunk(trans, alloc_flags);
2315 mutex_unlock(&fs_info->chunk_mutex);
2318 mutex_unlock(&fs_info->ro_block_group_mutex);
2320 btrfs_end_transaction(trans);
2324 void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
2326 struct btrfs_space_info *sinfo = cache->space_info;
2331 spin_lock(&sinfo->lock);
2332 spin_lock(&cache->lock);
2334 num_bytes = cache->length - cache->reserved -
2335 cache->pinned - cache->bytes_super - cache->used;
2336 sinfo->bytes_readonly -= num_bytes;
2337 list_del_init(&cache->ro_list);
2339 spin_unlock(&cache->lock);
2340 spin_unlock(&sinfo->lock);
2343 static int update_block_group_item(struct btrfs_trans_handle *trans,
2344 struct btrfs_path *path,
2345 struct btrfs_block_group *cache)
2347 struct btrfs_fs_info *fs_info = trans->fs_info;
2349 struct btrfs_root *root = fs_info->extent_root;
2351 struct extent_buffer *leaf;
2352 struct btrfs_block_group_item bgi;
2353 struct btrfs_key key;
2355 key.objectid = cache->start;
2356 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2357 key.offset = cache->length;
2359 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2366 leaf = path->nodes[0];
2367 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2368 btrfs_set_stack_block_group_used(&bgi, cache->used);
2369 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2370 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2371 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2372 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
2373 btrfs_mark_buffer_dirty(leaf);
2375 btrfs_release_path(path);
2380 static int cache_save_setup(struct btrfs_block_group *block_group,
2381 struct btrfs_trans_handle *trans,
2382 struct btrfs_path *path)
2384 struct btrfs_fs_info *fs_info = block_group->fs_info;
2385 struct btrfs_root *root = fs_info->tree_root;
2386 struct inode *inode = NULL;
2387 struct extent_changeset *data_reserved = NULL;
2389 int dcs = BTRFS_DC_ERROR;
2395 * If this block group is smaller than 100 megs don't bother caching the
2398 if (block_group->length < (100 * SZ_1M)) {
2399 spin_lock(&block_group->lock);
2400 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2401 spin_unlock(&block_group->lock);
2405 if (TRANS_ABORTED(trans))
2408 inode = lookup_free_space_inode(block_group, path);
2409 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2410 ret = PTR_ERR(inode);
2411 btrfs_release_path(path);
2415 if (IS_ERR(inode)) {
2419 if (block_group->ro)
2422 ret = create_free_space_inode(trans, block_group, path);
2429 * We want to set the generation to 0, that way if anything goes wrong
2430 * from here on out we know not to trust this cache when we load up next
2433 BTRFS_I(inode)->generation = 0;
2434 ret = btrfs_update_inode(trans, root, inode);
2437 * So theoretically we could recover from this, simply set the
2438 * super cache generation to 0 so we know to invalidate the
2439 * cache, but then we'd have to keep track of the block groups
2440 * that fail this way so we know we _have_ to reset this cache
2441 * before the next commit or risk reading stale cache. So to
2442 * limit our exposure to horrible edge cases lets just abort the
2443 * transaction, this only happens in really bad situations
2446 btrfs_abort_transaction(trans, ret);
2451 /* We've already setup this transaction, go ahead and exit */
2452 if (block_group->cache_generation == trans->transid &&
2453 i_size_read(inode)) {
2454 dcs = BTRFS_DC_SETUP;
2458 if (i_size_read(inode) > 0) {
2459 ret = btrfs_check_trunc_cache_free_space(fs_info,
2460 &fs_info->global_block_rsv);
2464 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2469 spin_lock(&block_group->lock);
2470 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2471 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2473 * don't bother trying to write stuff out _if_
2474 * a) we're not cached,
2475 * b) we're with nospace_cache mount option,
2476 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2478 dcs = BTRFS_DC_WRITTEN;
2479 spin_unlock(&block_group->lock);
2482 spin_unlock(&block_group->lock);
2485 * We hit an ENOSPC when setting up the cache in this transaction, just
2486 * skip doing the setup, we've already cleared the cache so we're safe.
2488 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2494 * Try to preallocate enough space based on how big the block group is.
2495 * Keep in mind this has to include any pinned space which could end up
2496 * taking up quite a bit since it's not folded into the other space
2499 num_pages = div_u64(block_group->length, SZ_256M);
2504 num_pages *= PAGE_SIZE;
2506 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
2511 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2512 num_pages, num_pages,
2515 * Our cache requires contiguous chunks so that we don't modify a bunch
2516 * of metadata or split extents when writing the cache out, which means
2517 * we can enospc if we are heavily fragmented in addition to just normal
2518 * out of space conditions. So if we hit this just skip setting up any
2519 * other block groups for this transaction, maybe we'll unpin enough
2520 * space the next time around.
2523 dcs = BTRFS_DC_SETUP;
2524 else if (ret == -ENOSPC)
2525 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2530 btrfs_release_path(path);
2532 spin_lock(&block_group->lock);
2533 if (!ret && dcs == BTRFS_DC_SETUP)
2534 block_group->cache_generation = trans->transid;
2535 block_group->disk_cache_state = dcs;
2536 spin_unlock(&block_group->lock);
2538 extent_changeset_free(data_reserved);
2542 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2544 struct btrfs_fs_info *fs_info = trans->fs_info;
2545 struct btrfs_block_group *cache, *tmp;
2546 struct btrfs_transaction *cur_trans = trans->transaction;
2547 struct btrfs_path *path;
2549 if (list_empty(&cur_trans->dirty_bgs) ||
2550 !btrfs_test_opt(fs_info, SPACE_CACHE))
2553 path = btrfs_alloc_path();
2557 /* Could add new block groups, use _safe just in case */
2558 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2560 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2561 cache_save_setup(cache, trans, path);
2564 btrfs_free_path(path);
2569 * Transaction commit does final block group cache writeback during a critical
2570 * section where nothing is allowed to change the FS. This is required in
2571 * order for the cache to actually match the block group, but can introduce a
2572 * lot of latency into the commit.
2574 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2575 * There's a chance we'll have to redo some of it if the block group changes
2576 * again during the commit, but it greatly reduces the commit latency by
2577 * getting rid of the easy block groups while we're still allowing others to
2580 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2582 struct btrfs_fs_info *fs_info = trans->fs_info;
2583 struct btrfs_block_group *cache;
2584 struct btrfs_transaction *cur_trans = trans->transaction;
2587 struct btrfs_path *path = NULL;
2589 struct list_head *io = &cur_trans->io_bgs;
2592 spin_lock(&cur_trans->dirty_bgs_lock);
2593 if (list_empty(&cur_trans->dirty_bgs)) {
2594 spin_unlock(&cur_trans->dirty_bgs_lock);
2597 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2598 spin_unlock(&cur_trans->dirty_bgs_lock);
2601 /* Make sure all the block groups on our dirty list actually exist */
2602 btrfs_create_pending_block_groups(trans);
2605 path = btrfs_alloc_path();
2613 * cache_write_mutex is here only to save us from balance or automatic
2614 * removal of empty block groups deleting this block group while we are
2615 * writing out the cache
2617 mutex_lock(&trans->transaction->cache_write_mutex);
2618 while (!list_empty(&dirty)) {
2619 bool drop_reserve = true;
2621 cache = list_first_entry(&dirty, struct btrfs_block_group,
2624 * This can happen if something re-dirties a block group that
2625 * is already under IO. Just wait for it to finish and then do
2628 if (!list_empty(&cache->io_list)) {
2629 list_del_init(&cache->io_list);
2630 btrfs_wait_cache_io(trans, cache, path);
2631 btrfs_put_block_group(cache);
2636 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
2637 * it should update the cache_state. Don't delete until after
2640 * Since we're not running in the commit critical section
2641 * we need the dirty_bgs_lock to protect from update_block_group
2643 spin_lock(&cur_trans->dirty_bgs_lock);
2644 list_del_init(&cache->dirty_list);
2645 spin_unlock(&cur_trans->dirty_bgs_lock);
2649 cache_save_setup(cache, trans, path);
2651 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
2652 cache->io_ctl.inode = NULL;
2653 ret = btrfs_write_out_cache(trans, cache, path);
2654 if (ret == 0 && cache->io_ctl.inode) {
2658 * The cache_write_mutex is protecting the
2659 * io_list, also refer to the definition of
2660 * btrfs_transaction::io_bgs for more details
2662 list_add_tail(&cache->io_list, io);
2665 * If we failed to write the cache, the
2666 * generation will be bad and life goes on
2672 ret = update_block_group_item(trans, path, cache);
2674 * Our block group might still be attached to the list
2675 * of new block groups in the transaction handle of some
2676 * other task (struct btrfs_trans_handle->new_bgs). This
2677 * means its block group item isn't yet in the extent
2678 * tree. If this happens ignore the error, as we will
2679 * try again later in the critical section of the
2680 * transaction commit.
2682 if (ret == -ENOENT) {
2684 spin_lock(&cur_trans->dirty_bgs_lock);
2685 if (list_empty(&cache->dirty_list)) {
2686 list_add_tail(&cache->dirty_list,
2687 &cur_trans->dirty_bgs);
2688 btrfs_get_block_group(cache);
2689 drop_reserve = false;
2691 spin_unlock(&cur_trans->dirty_bgs_lock);
2693 btrfs_abort_transaction(trans, ret);
2697 /* If it's not on the io list, we need to put the block group */
2699 btrfs_put_block_group(cache);
2701 btrfs_delayed_refs_rsv_release(fs_info, 1);
2703 * Avoid blocking other tasks for too long. It might even save
2704 * us from writing caches for block groups that are going to be
2707 mutex_unlock(&trans->transaction->cache_write_mutex);
2710 mutex_lock(&trans->transaction->cache_write_mutex);
2712 mutex_unlock(&trans->transaction->cache_write_mutex);
2715 * Go through delayed refs for all the stuff we've just kicked off
2716 * and then loop back (just once)
2719 ret = btrfs_run_delayed_refs(trans, 0);
2720 if (!ret && loops == 0) {
2722 spin_lock(&cur_trans->dirty_bgs_lock);
2723 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2725 * dirty_bgs_lock protects us from concurrent block group
2726 * deletes too (not just cache_write_mutex).
2728 if (!list_empty(&dirty)) {
2729 spin_unlock(&cur_trans->dirty_bgs_lock);
2732 spin_unlock(&cur_trans->dirty_bgs_lock);
2736 spin_lock(&cur_trans->dirty_bgs_lock);
2737 list_splice_init(&dirty, &cur_trans->dirty_bgs);
2738 spin_unlock(&cur_trans->dirty_bgs_lock);
2739 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
2742 btrfs_free_path(path);
2746 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
2748 struct btrfs_fs_info *fs_info = trans->fs_info;
2749 struct btrfs_block_group *cache;
2750 struct btrfs_transaction *cur_trans = trans->transaction;
2753 struct btrfs_path *path;
2754 struct list_head *io = &cur_trans->io_bgs;
2756 path = btrfs_alloc_path();
2761 * Even though we are in the critical section of the transaction commit,
2762 * we can still have concurrent tasks adding elements to this
2763 * transaction's list of dirty block groups. These tasks correspond to
2764 * endio free space workers started when writeback finishes for a
2765 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
2766 * allocate new block groups as a result of COWing nodes of the root
2767 * tree when updating the free space inode. The writeback for the space
2768 * caches is triggered by an earlier call to
2769 * btrfs_start_dirty_block_groups() and iterations of the following
2771 * Also we want to do the cache_save_setup first and then run the
2772 * delayed refs to make sure we have the best chance at doing this all
2775 spin_lock(&cur_trans->dirty_bgs_lock);
2776 while (!list_empty(&cur_trans->dirty_bgs)) {
2777 cache = list_first_entry(&cur_trans->dirty_bgs,
2778 struct btrfs_block_group,
2782 * This can happen if cache_save_setup re-dirties a block group
2783 * that is already under IO. Just wait for it to finish and
2784 * then do it all again
2786 if (!list_empty(&cache->io_list)) {
2787 spin_unlock(&cur_trans->dirty_bgs_lock);
2788 list_del_init(&cache->io_list);
2789 btrfs_wait_cache_io(trans, cache, path);
2790 btrfs_put_block_group(cache);
2791 spin_lock(&cur_trans->dirty_bgs_lock);
2795 * Don't remove from the dirty list until after we've waited on
2798 list_del_init(&cache->dirty_list);
2799 spin_unlock(&cur_trans->dirty_bgs_lock);
2802 cache_save_setup(cache, trans, path);
2805 ret = btrfs_run_delayed_refs(trans,
2806 (unsigned long) -1);
2808 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
2809 cache->io_ctl.inode = NULL;
2810 ret = btrfs_write_out_cache(trans, cache, path);
2811 if (ret == 0 && cache->io_ctl.inode) {
2813 list_add_tail(&cache->io_list, io);
2816 * If we failed to write the cache, the
2817 * generation will be bad and life goes on
2823 ret = update_block_group_item(trans, path, cache);
2825 * One of the free space endio workers might have
2826 * created a new block group while updating a free space
2827 * cache's inode (at inode.c:btrfs_finish_ordered_io())
2828 * and hasn't released its transaction handle yet, in
2829 * which case the new block group is still attached to
2830 * its transaction handle and its creation has not
2831 * finished yet (no block group item in the extent tree
2832 * yet, etc). If this is the case, wait for all free
2833 * space endio workers to finish and retry. This is a
2834 * very rare case so no need for a more efficient and
2837 if (ret == -ENOENT) {
2838 wait_event(cur_trans->writer_wait,
2839 atomic_read(&cur_trans->num_writers) == 1);
2840 ret = update_block_group_item(trans, path, cache);
2843 btrfs_abort_transaction(trans, ret);
2846 /* If its not on the io list, we need to put the block group */
2848 btrfs_put_block_group(cache);
2849 btrfs_delayed_refs_rsv_release(fs_info, 1);
2850 spin_lock(&cur_trans->dirty_bgs_lock);
2852 spin_unlock(&cur_trans->dirty_bgs_lock);
2855 * Refer to the definition of io_bgs member for details why it's safe
2856 * to use it without any locking
2858 while (!list_empty(io)) {
2859 cache = list_first_entry(io, struct btrfs_block_group,
2861 list_del_init(&cache->io_list);
2862 btrfs_wait_cache_io(trans, cache, path);
2863 btrfs_put_block_group(cache);
2866 btrfs_free_path(path);
2870 int btrfs_update_block_group(struct btrfs_trans_handle *trans,
2871 u64 bytenr, u64 num_bytes, int alloc)
2873 struct btrfs_fs_info *info = trans->fs_info;
2874 struct btrfs_block_group *cache = NULL;
2875 u64 total = num_bytes;
2881 /* Block accounting for super block */
2882 spin_lock(&info->delalloc_root_lock);
2883 old_val = btrfs_super_bytes_used(info->super_copy);
2885 old_val += num_bytes;
2887 old_val -= num_bytes;
2888 btrfs_set_super_bytes_used(info->super_copy, old_val);
2889 spin_unlock(&info->delalloc_root_lock);
2892 cache = btrfs_lookup_block_group(info, bytenr);
2897 factor = btrfs_bg_type_to_factor(cache->flags);
2900 * If this block group has free space cache written out, we
2901 * need to make sure to load it if we are removing space. This
2902 * is because we need the unpinning stage to actually add the
2903 * space back to the block group, otherwise we will leak space.
2905 if (!alloc && !btrfs_block_group_done(cache))
2906 btrfs_cache_block_group(cache, 1);
2908 byte_in_group = bytenr - cache->start;
2909 WARN_ON(byte_in_group > cache->length);
2911 spin_lock(&cache->space_info->lock);
2912 spin_lock(&cache->lock);
2914 if (btrfs_test_opt(info, SPACE_CACHE) &&
2915 cache->disk_cache_state < BTRFS_DC_CLEAR)
2916 cache->disk_cache_state = BTRFS_DC_CLEAR;
2918 old_val = cache->used;
2919 num_bytes = min(total, cache->length - byte_in_group);
2921 old_val += num_bytes;
2922 cache->used = old_val;
2923 cache->reserved -= num_bytes;
2924 cache->space_info->bytes_reserved -= num_bytes;
2925 cache->space_info->bytes_used += num_bytes;
2926 cache->space_info->disk_used += num_bytes * factor;
2927 spin_unlock(&cache->lock);
2928 spin_unlock(&cache->space_info->lock);
2930 old_val -= num_bytes;
2931 cache->used = old_val;
2932 cache->pinned += num_bytes;
2933 btrfs_space_info_update_bytes_pinned(info,
2934 cache->space_info, num_bytes);
2935 cache->space_info->bytes_used -= num_bytes;
2936 cache->space_info->disk_used -= num_bytes * factor;
2937 spin_unlock(&cache->lock);
2938 spin_unlock(&cache->space_info->lock);
2940 __btrfs_mod_total_bytes_pinned(cache->space_info,
2942 set_extent_dirty(&trans->transaction->pinned_extents,
2943 bytenr, bytenr + num_bytes - 1,
2944 GFP_NOFS | __GFP_NOFAIL);
2947 spin_lock(&trans->transaction->dirty_bgs_lock);
2948 if (list_empty(&cache->dirty_list)) {
2949 list_add_tail(&cache->dirty_list,
2950 &trans->transaction->dirty_bgs);
2951 trans->delayed_ref_updates++;
2952 btrfs_get_block_group(cache);
2954 spin_unlock(&trans->transaction->dirty_bgs_lock);
2957 * No longer have used bytes in this block group, queue it for
2958 * deletion. We do this after adding the block group to the
2959 * dirty list to avoid races between cleaner kthread and space
2962 if (!alloc && old_val == 0) {
2963 if (!btrfs_test_opt(info, DISCARD_ASYNC))
2964 btrfs_mark_bg_unused(cache);
2967 btrfs_put_block_group(cache);
2969 bytenr += num_bytes;
2972 /* Modified block groups are accounted for in the delayed_refs_rsv. */
2973 btrfs_update_delayed_refs_rsv(trans);
2978 * btrfs_add_reserved_bytes - update the block_group and space info counters
2979 * @cache: The cache we are manipulating
2980 * @ram_bytes: The number of bytes of file content, and will be same to
2981 * @num_bytes except for the compress path.
2982 * @num_bytes: The number of bytes in question
2983 * @delalloc: The blocks are allocated for the delalloc write
2985 * This is called by the allocator when it reserves space. If this is a
2986 * reservation and the block group has become read only we cannot make the
2987 * reservation and return -EAGAIN, otherwise this function always succeeds.
2989 int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
2990 u64 ram_bytes, u64 num_bytes, int delalloc)
2992 struct btrfs_space_info *space_info = cache->space_info;
2995 spin_lock(&space_info->lock);
2996 spin_lock(&cache->lock);
3000 cache->reserved += num_bytes;
3001 space_info->bytes_reserved += num_bytes;
3002 trace_btrfs_space_reservation(cache->fs_info, "space_info",
3003 space_info->flags, num_bytes, 1);
3004 btrfs_space_info_update_bytes_may_use(cache->fs_info,
3005 space_info, -ram_bytes);
3007 cache->delalloc_bytes += num_bytes;
3010 * Compression can use less space than we reserved, so wake
3011 * tickets if that happens
3013 if (num_bytes < ram_bytes)
3014 btrfs_try_granting_tickets(cache->fs_info, space_info);
3016 spin_unlock(&cache->lock);
3017 spin_unlock(&space_info->lock);
3022 * btrfs_free_reserved_bytes - update the block_group and space info counters
3023 * @cache: The cache we are manipulating
3024 * @num_bytes: The number of bytes in question
3025 * @delalloc: The blocks are allocated for the delalloc write
3027 * This is called by somebody who is freeing space that was never actually used
3028 * on disk. For example if you reserve some space for a new leaf in transaction
3029 * A and before transaction A commits you free that leaf, you call this with
3030 * reserve set to 0 in order to clear the reservation.
3032 void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3033 u64 num_bytes, int delalloc)
3035 struct btrfs_space_info *space_info = cache->space_info;
3037 spin_lock(&space_info->lock);
3038 spin_lock(&cache->lock);
3040 space_info->bytes_readonly += num_bytes;
3041 cache->reserved -= num_bytes;
3042 space_info->bytes_reserved -= num_bytes;
3043 space_info->max_extent_size = 0;
3046 cache->delalloc_bytes -= num_bytes;
3047 spin_unlock(&cache->lock);
3049 btrfs_try_granting_tickets(cache->fs_info, space_info);
3050 spin_unlock(&space_info->lock);
3053 static void force_metadata_allocation(struct btrfs_fs_info *info)
3055 struct list_head *head = &info->space_info;
3056 struct btrfs_space_info *found;
3058 list_for_each_entry(found, head, list) {
3059 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3060 found->force_alloc = CHUNK_ALLOC_FORCE;
3064 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3065 struct btrfs_space_info *sinfo, int force)
3067 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3070 if (force == CHUNK_ALLOC_FORCE)
3074 * in limited mode, we want to have some free space up to
3075 * about 1% of the FS size.
3077 if (force == CHUNK_ALLOC_LIMITED) {
3078 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3079 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3081 if (sinfo->total_bytes - bytes_used < thresh)
3085 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3090 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3092 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3094 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3098 * If force is CHUNK_ALLOC_FORCE:
3099 * - return 1 if it successfully allocates a chunk,
3100 * - return errors including -ENOSPC otherwise.
3101 * If force is NOT CHUNK_ALLOC_FORCE:
3102 * - return 0 if it doesn't need to allocate a new chunk,
3103 * - return 1 if it successfully allocates a chunk,
3104 * - return errors including -ENOSPC otherwise.
3106 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3107 enum btrfs_chunk_alloc_enum force)
3109 struct btrfs_fs_info *fs_info = trans->fs_info;
3110 struct btrfs_space_info *space_info;
3111 bool wait_for_alloc = false;
3112 bool should_alloc = false;
3115 /* Don't re-enter if we're already allocating a chunk */
3116 if (trans->allocating_chunk)
3119 space_info = btrfs_find_space_info(fs_info, flags);
3123 spin_lock(&space_info->lock);
3124 if (force < space_info->force_alloc)
3125 force = space_info->force_alloc;
3126 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3127 if (space_info->full) {
3128 /* No more free physical space */
3133 spin_unlock(&space_info->lock);
3135 } else if (!should_alloc) {
3136 spin_unlock(&space_info->lock);
3138 } else if (space_info->chunk_alloc) {
3140 * Someone is already allocating, so we need to block
3141 * until this someone is finished and then loop to
3142 * recheck if we should continue with our allocation
3145 wait_for_alloc = true;
3146 force = CHUNK_ALLOC_NO_FORCE;
3147 spin_unlock(&space_info->lock);
3148 mutex_lock(&fs_info->chunk_mutex);
3149 mutex_unlock(&fs_info->chunk_mutex);
3151 /* Proceed with allocation */
3152 space_info->chunk_alloc = 1;
3153 wait_for_alloc = false;
3154 spin_unlock(&space_info->lock);
3158 } while (wait_for_alloc);
3160 mutex_lock(&fs_info->chunk_mutex);
3161 trans->allocating_chunk = true;
3164 * If we have mixed data/metadata chunks we want to make sure we keep
3165 * allocating mixed chunks instead of individual chunks.
3167 if (btrfs_mixed_space_info(space_info))
3168 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3171 * if we're doing a data chunk, go ahead and make sure that
3172 * we keep a reasonable number of metadata chunks allocated in the
3175 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3176 fs_info->data_chunk_allocations++;
3177 if (!(fs_info->data_chunk_allocations %
3178 fs_info->metadata_ratio))
3179 force_metadata_allocation(fs_info);
3183 * Check if we have enough space in SYSTEM chunk because we may need
3184 * to update devices.
3186 check_system_chunk(trans, flags);
3188 ret = btrfs_alloc_chunk(trans, flags);
3189 trans->allocating_chunk = false;
3191 spin_lock(&space_info->lock);
3194 space_info->full = 1;
3199 space_info->max_extent_size = 0;
3202 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3204 space_info->chunk_alloc = 0;
3205 spin_unlock(&space_info->lock);
3206 mutex_unlock(&fs_info->chunk_mutex);
3208 * When we allocate a new chunk we reserve space in the chunk block
3209 * reserve to make sure we can COW nodes/leafs in the chunk tree or
3210 * add new nodes/leafs to it if we end up needing to do it when
3211 * inserting the chunk item and updating device items as part of the
3212 * second phase of chunk allocation, performed by
3213 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
3214 * large number of new block groups to create in our transaction
3215 * handle's new_bgs list to avoid exhausting the chunk block reserve
3216 * in extreme cases - like having a single transaction create many new
3217 * block groups when starting to write out the free space caches of all
3218 * the block groups that were made dirty during the lifetime of the
3221 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
3222 btrfs_create_pending_block_groups(trans);
3227 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3231 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3233 num_dev = fs_info->fs_devices->rw_devices;
3239 * Reserve space in the system space for allocating or removing a chunk
3241 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3243 struct btrfs_fs_info *fs_info = trans->fs_info;
3244 struct btrfs_space_info *info;
3251 * Needed because we can end up allocating a system chunk and for an
3252 * atomic and race free space reservation in the chunk block reserve.
3254 lockdep_assert_held(&fs_info->chunk_mutex);
3256 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3257 spin_lock(&info->lock);
3258 left = info->total_bytes - btrfs_space_info_used(info, true);
3259 spin_unlock(&info->lock);
3261 num_devs = get_profile_num_devs(fs_info, type);
3263 /* num_devs device items to update and 1 chunk item to add or remove */
3264 thresh = btrfs_calc_metadata_size(fs_info, num_devs) +
3265 btrfs_calc_insert_metadata_size(fs_info, 1);
3267 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3268 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3269 left, thresh, type);
3270 btrfs_dump_space_info(fs_info, info, 0, 0);
3273 if (left < thresh) {
3274 u64 flags = btrfs_system_alloc_profile(fs_info);
3277 * Ignore failure to create system chunk. We might end up not
3278 * needing it, as we might not need to COW all nodes/leafs from
3279 * the paths we visit in the chunk tree (they were already COWed
3280 * or created in the current transaction for example).
3282 ret = btrfs_alloc_chunk(trans, flags);
3286 ret = btrfs_block_rsv_add(fs_info->chunk_root,
3287 &fs_info->chunk_block_rsv,
3288 thresh, BTRFS_RESERVE_NO_FLUSH);
3290 trans->chunk_bytes_reserved += thresh;
3294 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3296 struct btrfs_block_group *block_group;
3300 struct inode *inode;
3302 block_group = btrfs_lookup_first_block_group(info, last);
3303 while (block_group) {
3304 btrfs_wait_block_group_cache_done(block_group);
3305 spin_lock(&block_group->lock);
3306 if (block_group->iref)
3308 spin_unlock(&block_group->lock);
3309 block_group = btrfs_next_block_group(block_group);
3318 inode = block_group->inode;
3319 block_group->iref = 0;
3320 block_group->inode = NULL;
3321 spin_unlock(&block_group->lock);
3322 ASSERT(block_group->io_ctl.inode == NULL);
3324 last = block_group->start + block_group->length;
3325 btrfs_put_block_group(block_group);
3330 * Must be called only after stopping all workers, since we could have block
3331 * group caching kthreads running, and therefore they could race with us if we
3332 * freed the block groups before stopping them.
3334 int btrfs_free_block_groups(struct btrfs_fs_info *info)
3336 struct btrfs_block_group *block_group;
3337 struct btrfs_space_info *space_info;
3338 struct btrfs_caching_control *caching_ctl;
3341 down_write(&info->commit_root_sem);
3342 while (!list_empty(&info->caching_block_groups)) {
3343 caching_ctl = list_entry(info->caching_block_groups.next,
3344 struct btrfs_caching_control, list);
3345 list_del(&caching_ctl->list);
3346 btrfs_put_caching_control(caching_ctl);
3348 up_write(&info->commit_root_sem);
3350 spin_lock(&info->unused_bgs_lock);
3351 while (!list_empty(&info->unused_bgs)) {
3352 block_group = list_first_entry(&info->unused_bgs,
3353 struct btrfs_block_group,
3355 list_del_init(&block_group->bg_list);
3356 btrfs_put_block_group(block_group);
3358 spin_unlock(&info->unused_bgs_lock);
3360 spin_lock(&info->block_group_cache_lock);
3361 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
3362 block_group = rb_entry(n, struct btrfs_block_group,
3364 rb_erase(&block_group->cache_node,
3365 &info->block_group_cache_tree);
3366 RB_CLEAR_NODE(&block_group->cache_node);
3367 spin_unlock(&info->block_group_cache_lock);
3369 down_write(&block_group->space_info->groups_sem);
3370 list_del(&block_group->list);
3371 up_write(&block_group->space_info->groups_sem);
3374 * We haven't cached this block group, which means we could
3375 * possibly have excluded extents on this block group.
3377 if (block_group->cached == BTRFS_CACHE_NO ||
3378 block_group->cached == BTRFS_CACHE_ERROR)
3379 btrfs_free_excluded_extents(block_group);
3381 btrfs_remove_free_space_cache(block_group);
3382 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
3383 ASSERT(list_empty(&block_group->dirty_list));
3384 ASSERT(list_empty(&block_group->io_list));
3385 ASSERT(list_empty(&block_group->bg_list));
3386 ASSERT(refcount_read(&block_group->refs) == 1);
3387 ASSERT(block_group->swap_extents == 0);
3388 btrfs_put_block_group(block_group);
3390 spin_lock(&info->block_group_cache_lock);
3392 spin_unlock(&info->block_group_cache_lock);
3394 btrfs_release_global_block_rsv(info);
3396 while (!list_empty(&info->space_info)) {
3397 space_info = list_entry(info->space_info.next,
3398 struct btrfs_space_info,
3402 * Do not hide this behind enospc_debug, this is actually
3403 * important and indicates a real bug if this happens.
3405 if (WARN_ON(space_info->bytes_pinned > 0 ||
3406 space_info->bytes_reserved > 0 ||
3407 space_info->bytes_may_use > 0))
3408 btrfs_dump_space_info(info, space_info, 0, 0);
3409 WARN_ON(space_info->reclaim_size > 0);
3410 list_del(&space_info->list);
3411 btrfs_sysfs_remove_space_info(space_info);
3416 void btrfs_freeze_block_group(struct btrfs_block_group *cache)
3418 atomic_inc(&cache->frozen);
3421 void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
3423 struct btrfs_fs_info *fs_info = block_group->fs_info;
3424 struct extent_map_tree *em_tree;
3425 struct extent_map *em;
3428 spin_lock(&block_group->lock);
3429 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
3430 block_group->removed);
3431 spin_unlock(&block_group->lock);
3434 em_tree = &fs_info->mapping_tree;
3435 write_lock(&em_tree->lock);
3436 em = lookup_extent_mapping(em_tree, block_group->start,
3438 BUG_ON(!em); /* logic error, can't happen */
3439 remove_extent_mapping(em_tree, em);
3440 write_unlock(&em_tree->lock);
3442 /* once for us and once for the tree */
3443 free_extent_map(em);
3444 free_extent_map(em);
3447 * We may have left one free space entry and other possible
3448 * tasks trimming this block group have left 1 entry each one.
3451 __btrfs_remove_free_space_cache(block_group->free_space_ctl);
3455 bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
3459 spin_lock(&bg->lock);
3464 spin_unlock(&bg->lock);
3469 void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
3471 spin_lock(&bg->lock);
3473 ASSERT(bg->swap_extents >= amount);
3474 bg->swap_extents -= amount;
3475 spin_unlock(&bg->lock);