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 /* Pick target profile only if it's already available */
69 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
70 spin_unlock(&fs_info->balance_lock);
71 return extended_to_chunk(target);
74 spin_unlock(&fs_info->balance_lock);
76 /* First, mask out the RAID levels which aren't possible */
77 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
78 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
79 allowed |= btrfs_raid_array[raid_type].bg_flag;
83 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
84 allowed = BTRFS_BLOCK_GROUP_RAID6;
85 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
86 allowed = BTRFS_BLOCK_GROUP_RAID5;
87 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
88 allowed = BTRFS_BLOCK_GROUP_RAID10;
89 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
90 allowed = BTRFS_BLOCK_GROUP_RAID1;
91 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
92 allowed = BTRFS_BLOCK_GROUP_RAID0;
94 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
96 return extended_to_chunk(flags | allowed);
99 u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
106 seq = read_seqbegin(&fs_info->profiles_lock);
108 if (flags & BTRFS_BLOCK_GROUP_DATA)
109 flags |= fs_info->avail_data_alloc_bits;
110 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
111 flags |= fs_info->avail_system_alloc_bits;
112 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
113 flags |= fs_info->avail_metadata_alloc_bits;
114 } while (read_seqretry(&fs_info->profiles_lock, seq));
116 return btrfs_reduce_alloc_profile(fs_info, flags);
119 void btrfs_get_block_group(struct btrfs_block_group *cache)
121 atomic_inc(&cache->count);
124 void btrfs_put_block_group(struct btrfs_block_group *cache)
126 if (atomic_dec_and_test(&cache->count)) {
127 WARN_ON(cache->pinned > 0);
128 WARN_ON(cache->reserved > 0);
131 * A block_group shouldn't be on the discard_list anymore.
132 * Remove the block_group from the discard_list to prevent us
133 * from causing a panic due to NULL pointer dereference.
135 if (WARN_ON(!list_empty(&cache->discard_list)))
136 btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
140 * If not empty, someone is still holding mutex of
141 * full_stripe_lock, which can only be released by caller.
142 * And it will definitely cause use-after-free when caller
143 * tries to release full stripe lock.
145 * No better way to resolve, but only to warn.
147 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
148 kfree(cache->free_space_ctl);
154 * This adds the block group to the fs_info rb tree for the block group cache
156 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
157 struct btrfs_block_group *block_group)
160 struct rb_node *parent = NULL;
161 struct btrfs_block_group *cache;
163 ASSERT(block_group->length != 0);
165 spin_lock(&info->block_group_cache_lock);
166 p = &info->block_group_cache_tree.rb_node;
170 cache = rb_entry(parent, struct btrfs_block_group, cache_node);
171 if (block_group->start < cache->start) {
173 } else if (block_group->start > cache->start) {
176 spin_unlock(&info->block_group_cache_lock);
181 rb_link_node(&block_group->cache_node, parent, p);
182 rb_insert_color(&block_group->cache_node,
183 &info->block_group_cache_tree);
185 if (info->first_logical_byte > block_group->start)
186 info->first_logical_byte = block_group->start;
188 spin_unlock(&info->block_group_cache_lock);
194 * This will return the block group at or after bytenr if contains is 0, else
195 * it will return the block group that contains the bytenr
197 static struct btrfs_block_group *block_group_cache_tree_search(
198 struct btrfs_fs_info *info, u64 bytenr, int contains)
200 struct btrfs_block_group *cache, *ret = NULL;
204 spin_lock(&info->block_group_cache_lock);
205 n = info->block_group_cache_tree.rb_node;
208 cache = rb_entry(n, struct btrfs_block_group, cache_node);
209 end = cache->start + cache->length - 1;
210 start = cache->start;
212 if (bytenr < start) {
213 if (!contains && (!ret || start < ret->start))
216 } else if (bytenr > start) {
217 if (contains && bytenr <= end) {
228 btrfs_get_block_group(ret);
229 if (bytenr == 0 && info->first_logical_byte > ret->start)
230 info->first_logical_byte = ret->start;
232 spin_unlock(&info->block_group_cache_lock);
238 * Return the block group that starts at or after bytenr
240 struct btrfs_block_group *btrfs_lookup_first_block_group(
241 struct btrfs_fs_info *info, u64 bytenr)
243 return block_group_cache_tree_search(info, bytenr, 0);
247 * Return the block group that contains the given bytenr
249 struct btrfs_block_group *btrfs_lookup_block_group(
250 struct btrfs_fs_info *info, u64 bytenr)
252 return block_group_cache_tree_search(info, bytenr, 1);
255 struct btrfs_block_group *btrfs_next_block_group(
256 struct btrfs_block_group *cache)
258 struct btrfs_fs_info *fs_info = cache->fs_info;
259 struct rb_node *node;
261 spin_lock(&fs_info->block_group_cache_lock);
263 /* If our block group was removed, we need a full search. */
264 if (RB_EMPTY_NODE(&cache->cache_node)) {
265 const u64 next_bytenr = cache->start + cache->length;
267 spin_unlock(&fs_info->block_group_cache_lock);
268 btrfs_put_block_group(cache);
269 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
271 node = rb_next(&cache->cache_node);
272 btrfs_put_block_group(cache);
274 cache = rb_entry(node, struct btrfs_block_group, cache_node);
275 btrfs_get_block_group(cache);
278 spin_unlock(&fs_info->block_group_cache_lock);
282 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
284 struct btrfs_block_group *bg;
287 bg = btrfs_lookup_block_group(fs_info, bytenr);
291 spin_lock(&bg->lock);
295 atomic_inc(&bg->nocow_writers);
296 spin_unlock(&bg->lock);
298 /* No put on block group, done by btrfs_dec_nocow_writers */
300 btrfs_put_block_group(bg);
305 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
307 struct btrfs_block_group *bg;
309 bg = btrfs_lookup_block_group(fs_info, bytenr);
311 if (atomic_dec_and_test(&bg->nocow_writers))
312 wake_up_var(&bg->nocow_writers);
314 * Once for our lookup and once for the lookup done by a previous call
315 * to btrfs_inc_nocow_writers()
317 btrfs_put_block_group(bg);
318 btrfs_put_block_group(bg);
321 void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
323 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
326 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
329 struct btrfs_block_group *bg;
331 bg = btrfs_lookup_block_group(fs_info, start);
333 if (atomic_dec_and_test(&bg->reservations))
334 wake_up_var(&bg->reservations);
335 btrfs_put_block_group(bg);
338 void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
340 struct btrfs_space_info *space_info = bg->space_info;
344 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
348 * Our block group is read only but before we set it to read only,
349 * some task might have had allocated an extent from it already, but it
350 * has not yet created a respective ordered extent (and added it to a
351 * root's list of ordered extents).
352 * Therefore wait for any task currently allocating extents, since the
353 * block group's reservations counter is incremented while a read lock
354 * on the groups' semaphore is held and decremented after releasing
355 * the read access on that semaphore and creating the ordered extent.
357 down_write(&space_info->groups_sem);
358 up_write(&space_info->groups_sem);
360 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
363 struct btrfs_caching_control *btrfs_get_caching_control(
364 struct btrfs_block_group *cache)
366 struct btrfs_caching_control *ctl;
368 spin_lock(&cache->lock);
369 if (!cache->caching_ctl) {
370 spin_unlock(&cache->lock);
374 ctl = cache->caching_ctl;
375 refcount_inc(&ctl->count);
376 spin_unlock(&cache->lock);
380 void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
382 if (refcount_dec_and_test(&ctl->count))
387 * When we wait for progress in the block group caching, its because our
388 * allocation attempt failed at least once. So, we must sleep and let some
389 * progress happen before we try again.
391 * This function will sleep at least once waiting for new free space to show
392 * up, and then it will check the block group free space numbers for our min
393 * num_bytes. Another option is to have it go ahead and look in the rbtree for
394 * a free extent of a given size, but this is a good start.
396 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
397 * any of the information in this block group.
399 void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
402 struct btrfs_caching_control *caching_ctl;
404 caching_ctl = btrfs_get_caching_control(cache);
408 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
409 (cache->free_space_ctl->free_space >= num_bytes));
411 btrfs_put_caching_control(caching_ctl);
414 int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
416 struct btrfs_caching_control *caching_ctl;
419 caching_ctl = btrfs_get_caching_control(cache);
421 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
423 wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
424 if (cache->cached == BTRFS_CACHE_ERROR)
426 btrfs_put_caching_control(caching_ctl);
430 #ifdef CONFIG_BTRFS_DEBUG
431 static void fragment_free_space(struct btrfs_block_group *block_group)
433 struct btrfs_fs_info *fs_info = block_group->fs_info;
434 u64 start = block_group->start;
435 u64 len = block_group->length;
436 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
437 fs_info->nodesize : fs_info->sectorsize;
438 u64 step = chunk << 1;
440 while (len > chunk) {
441 btrfs_remove_free_space(block_group, start, chunk);
452 * This is only called by btrfs_cache_block_group, since we could have freed
453 * extents we need to check the pinned_extents for any extents that can't be
454 * used yet since their free space will be released as soon as the transaction
457 u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
459 struct btrfs_fs_info *info = block_group->fs_info;
460 u64 extent_start, extent_end, size, total_added = 0;
463 while (start < end) {
464 ret = find_first_extent_bit(&info->excluded_extents, start,
465 &extent_start, &extent_end,
466 EXTENT_DIRTY | EXTENT_UPTODATE,
471 if (extent_start <= start) {
472 start = extent_end + 1;
473 } else if (extent_start > start && extent_start < end) {
474 size = extent_start - start;
476 ret = btrfs_add_free_space_async_trimmed(block_group,
478 BUG_ON(ret); /* -ENOMEM or logic error */
479 start = extent_end + 1;
488 ret = btrfs_add_free_space_async_trimmed(block_group, start,
490 BUG_ON(ret); /* -ENOMEM or logic error */
496 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
498 struct btrfs_block_group *block_group = caching_ctl->block_group;
499 struct btrfs_fs_info *fs_info = block_group->fs_info;
500 struct btrfs_root *extent_root = fs_info->extent_root;
501 struct btrfs_path *path;
502 struct extent_buffer *leaf;
503 struct btrfs_key key;
510 path = btrfs_alloc_path();
514 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
516 #ifdef CONFIG_BTRFS_DEBUG
518 * If we're fragmenting we don't want to make anybody think we can
519 * allocate from this block group until we've had a chance to fragment
522 if (btrfs_should_fragment_free_space(block_group))
526 * We don't want to deadlock with somebody trying to allocate a new
527 * extent for the extent root while also trying to search the extent
528 * root to add free space. So we skip locking and search the commit
529 * root, since its read-only
531 path->skip_locking = 1;
532 path->search_commit_root = 1;
533 path->reada = READA_FORWARD;
537 key.type = BTRFS_EXTENT_ITEM_KEY;
540 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
544 leaf = path->nodes[0];
545 nritems = btrfs_header_nritems(leaf);
548 if (btrfs_fs_closing(fs_info) > 1) {
553 if (path->slots[0] < nritems) {
554 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
556 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
560 if (need_resched() ||
561 rwsem_is_contended(&fs_info->commit_root_sem)) {
563 caching_ctl->progress = last;
564 btrfs_release_path(path);
565 up_read(&fs_info->commit_root_sem);
566 mutex_unlock(&caching_ctl->mutex);
568 mutex_lock(&caching_ctl->mutex);
569 down_read(&fs_info->commit_root_sem);
573 ret = btrfs_next_leaf(extent_root, path);
578 leaf = path->nodes[0];
579 nritems = btrfs_header_nritems(leaf);
583 if (key.objectid < last) {
586 key.type = BTRFS_EXTENT_ITEM_KEY;
589 caching_ctl->progress = last;
590 btrfs_release_path(path);
594 if (key.objectid < block_group->start) {
599 if (key.objectid >= block_group->start + block_group->length)
602 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
603 key.type == BTRFS_METADATA_ITEM_KEY) {
604 total_found += add_new_free_space(block_group, last,
606 if (key.type == BTRFS_METADATA_ITEM_KEY)
607 last = key.objectid +
610 last = key.objectid + key.offset;
612 if (total_found > CACHING_CTL_WAKE_UP) {
615 wake_up(&caching_ctl->wait);
622 total_found += add_new_free_space(block_group, last,
623 block_group->start + block_group->length);
624 caching_ctl->progress = (u64)-1;
627 btrfs_free_path(path);
631 static noinline void caching_thread(struct btrfs_work *work)
633 struct btrfs_block_group *block_group;
634 struct btrfs_fs_info *fs_info;
635 struct btrfs_caching_control *caching_ctl;
638 caching_ctl = container_of(work, struct btrfs_caching_control, work);
639 block_group = caching_ctl->block_group;
640 fs_info = block_group->fs_info;
642 mutex_lock(&caching_ctl->mutex);
643 down_read(&fs_info->commit_root_sem);
645 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
646 ret = load_free_space_tree(caching_ctl);
648 ret = load_extent_tree_free(caching_ctl);
650 spin_lock(&block_group->lock);
651 block_group->caching_ctl = NULL;
652 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
653 spin_unlock(&block_group->lock);
655 #ifdef CONFIG_BTRFS_DEBUG
656 if (btrfs_should_fragment_free_space(block_group)) {
659 spin_lock(&block_group->space_info->lock);
660 spin_lock(&block_group->lock);
661 bytes_used = block_group->length - block_group->used;
662 block_group->space_info->bytes_used += bytes_used >> 1;
663 spin_unlock(&block_group->lock);
664 spin_unlock(&block_group->space_info->lock);
665 fragment_free_space(block_group);
669 caching_ctl->progress = (u64)-1;
671 up_read(&fs_info->commit_root_sem);
672 btrfs_free_excluded_extents(block_group);
673 mutex_unlock(&caching_ctl->mutex);
675 wake_up(&caching_ctl->wait);
677 btrfs_put_caching_control(caching_ctl);
678 btrfs_put_block_group(block_group);
681 int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
684 struct btrfs_fs_info *fs_info = cache->fs_info;
685 struct btrfs_caching_control *caching_ctl;
688 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
692 INIT_LIST_HEAD(&caching_ctl->list);
693 mutex_init(&caching_ctl->mutex);
694 init_waitqueue_head(&caching_ctl->wait);
695 caching_ctl->block_group = cache;
696 caching_ctl->progress = cache->start;
697 refcount_set(&caching_ctl->count, 1);
698 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
700 spin_lock(&cache->lock);
702 * This should be a rare occasion, but this could happen I think in the
703 * case where one thread starts to load the space cache info, and then
704 * some other thread starts a transaction commit which tries to do an
705 * allocation while the other thread is still loading the space cache
706 * info. The previous loop should have kept us from choosing this block
707 * group, but if we've moved to the state where we will wait on caching
708 * block groups we need to first check if we're doing a fast load here,
709 * so we can wait for it to finish, otherwise we could end up allocating
710 * from a block group who's cache gets evicted for one reason or
713 while (cache->cached == BTRFS_CACHE_FAST) {
714 struct btrfs_caching_control *ctl;
716 ctl = cache->caching_ctl;
717 refcount_inc(&ctl->count);
718 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
719 spin_unlock(&cache->lock);
723 finish_wait(&ctl->wait, &wait);
724 btrfs_put_caching_control(ctl);
725 spin_lock(&cache->lock);
728 if (cache->cached != BTRFS_CACHE_NO) {
729 spin_unlock(&cache->lock);
733 WARN_ON(cache->caching_ctl);
734 cache->caching_ctl = caching_ctl;
735 cache->cached = BTRFS_CACHE_FAST;
736 spin_unlock(&cache->lock);
738 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
739 mutex_lock(&caching_ctl->mutex);
740 ret = load_free_space_cache(cache);
742 spin_lock(&cache->lock);
744 cache->caching_ctl = NULL;
745 cache->cached = BTRFS_CACHE_FINISHED;
746 cache->last_byte_to_unpin = (u64)-1;
747 caching_ctl->progress = (u64)-1;
749 if (load_cache_only) {
750 cache->caching_ctl = NULL;
751 cache->cached = BTRFS_CACHE_NO;
753 cache->cached = BTRFS_CACHE_STARTED;
754 cache->has_caching_ctl = 1;
757 spin_unlock(&cache->lock);
758 #ifdef CONFIG_BTRFS_DEBUG
760 btrfs_should_fragment_free_space(cache)) {
763 spin_lock(&cache->space_info->lock);
764 spin_lock(&cache->lock);
765 bytes_used = cache->length - cache->used;
766 cache->space_info->bytes_used += bytes_used >> 1;
767 spin_unlock(&cache->lock);
768 spin_unlock(&cache->space_info->lock);
769 fragment_free_space(cache);
772 mutex_unlock(&caching_ctl->mutex);
774 wake_up(&caching_ctl->wait);
776 btrfs_put_caching_control(caching_ctl);
777 btrfs_free_excluded_extents(cache);
782 * We're either using the free space tree or no caching at all.
783 * Set cached to the appropriate value and wakeup any waiters.
785 spin_lock(&cache->lock);
786 if (load_cache_only) {
787 cache->caching_ctl = NULL;
788 cache->cached = BTRFS_CACHE_NO;
790 cache->cached = BTRFS_CACHE_STARTED;
791 cache->has_caching_ctl = 1;
793 spin_unlock(&cache->lock);
794 wake_up(&caching_ctl->wait);
797 if (load_cache_only) {
798 btrfs_put_caching_control(caching_ctl);
802 down_write(&fs_info->commit_root_sem);
803 refcount_inc(&caching_ctl->count);
804 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
805 up_write(&fs_info->commit_root_sem);
807 btrfs_get_block_group(cache);
809 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
814 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
816 u64 extra_flags = chunk_to_extended(flags) &
817 BTRFS_EXTENDED_PROFILE_MASK;
819 write_seqlock(&fs_info->profiles_lock);
820 if (flags & BTRFS_BLOCK_GROUP_DATA)
821 fs_info->avail_data_alloc_bits &= ~extra_flags;
822 if (flags & BTRFS_BLOCK_GROUP_METADATA)
823 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
824 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
825 fs_info->avail_system_alloc_bits &= ~extra_flags;
826 write_sequnlock(&fs_info->profiles_lock);
830 * Clear incompat bits for the following feature(s):
832 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
833 * in the whole filesystem
835 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
837 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
839 bool found_raid56 = false;
840 bool found_raid1c34 = false;
842 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
843 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
844 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
845 struct list_head *head = &fs_info->space_info;
846 struct btrfs_space_info *sinfo;
848 list_for_each_entry_rcu(sinfo, head, list) {
849 down_read(&sinfo->groups_sem);
850 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
852 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
854 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
855 found_raid1c34 = true;
856 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
857 found_raid1c34 = true;
858 up_read(&sinfo->groups_sem);
861 btrfs_clear_fs_incompat(fs_info, RAID56);
863 btrfs_clear_fs_incompat(fs_info, RAID1C34);
867 static int remove_block_group_item(struct btrfs_trans_handle *trans,
868 struct btrfs_path *path,
869 struct btrfs_block_group *block_group)
871 struct btrfs_fs_info *fs_info = trans->fs_info;
872 struct btrfs_root *root;
873 struct btrfs_key key;
876 root = fs_info->extent_root;
877 key.objectid = block_group->start;
878 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
879 key.offset = block_group->length;
881 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
887 ret = btrfs_del_item(trans, root, path);
891 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
892 u64 group_start, struct extent_map *em)
894 struct btrfs_fs_info *fs_info = trans->fs_info;
895 struct btrfs_path *path;
896 struct btrfs_block_group *block_group;
897 struct btrfs_free_cluster *cluster;
898 struct btrfs_root *tree_root = fs_info->tree_root;
899 struct btrfs_key key;
901 struct kobject *kobj = NULL;
905 struct btrfs_caching_control *caching_ctl = NULL;
907 bool remove_rsv = false;
909 block_group = btrfs_lookup_block_group(fs_info, group_start);
910 BUG_ON(!block_group);
911 BUG_ON(!block_group->ro);
913 trace_btrfs_remove_block_group(block_group);
915 * Free the reserved super bytes from this block group before
918 btrfs_free_excluded_extents(block_group);
919 btrfs_free_ref_tree_range(fs_info, block_group->start,
920 block_group->length);
922 index = btrfs_bg_flags_to_raid_index(block_group->flags);
923 factor = btrfs_bg_type_to_factor(block_group->flags);
925 /* make sure this block group isn't part of an allocation cluster */
926 cluster = &fs_info->data_alloc_cluster;
927 spin_lock(&cluster->refill_lock);
928 btrfs_return_cluster_to_free_space(block_group, cluster);
929 spin_unlock(&cluster->refill_lock);
932 * make sure this block group isn't part of a metadata
935 cluster = &fs_info->meta_alloc_cluster;
936 spin_lock(&cluster->refill_lock);
937 btrfs_return_cluster_to_free_space(block_group, cluster);
938 spin_unlock(&cluster->refill_lock);
940 path = btrfs_alloc_path();
947 * get the inode first so any iput calls done for the io_list
948 * aren't the final iput (no unlinks allowed now)
950 inode = lookup_free_space_inode(block_group, path);
952 mutex_lock(&trans->transaction->cache_write_mutex);
954 * Make sure our free space cache IO is done before removing the
957 spin_lock(&trans->transaction->dirty_bgs_lock);
958 if (!list_empty(&block_group->io_list)) {
959 list_del_init(&block_group->io_list);
961 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
963 spin_unlock(&trans->transaction->dirty_bgs_lock);
964 btrfs_wait_cache_io(trans, block_group, path);
965 btrfs_put_block_group(block_group);
966 spin_lock(&trans->transaction->dirty_bgs_lock);
969 if (!list_empty(&block_group->dirty_list)) {
970 list_del_init(&block_group->dirty_list);
972 btrfs_put_block_group(block_group);
974 spin_unlock(&trans->transaction->dirty_bgs_lock);
975 mutex_unlock(&trans->transaction->cache_write_mutex);
977 if (!IS_ERR(inode)) {
978 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
980 btrfs_add_delayed_iput(inode);
984 /* One for the block groups ref */
985 spin_lock(&block_group->lock);
986 if (block_group->iref) {
987 block_group->iref = 0;
988 block_group->inode = NULL;
989 spin_unlock(&block_group->lock);
992 spin_unlock(&block_group->lock);
994 /* One for our lookup ref */
995 btrfs_add_delayed_iput(inode);
998 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
1000 key.offset = block_group->start;
1002 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
1006 btrfs_release_path(path);
1008 ret = btrfs_del_item(trans, tree_root, path);
1011 btrfs_release_path(path);
1014 spin_lock(&fs_info->block_group_cache_lock);
1015 rb_erase(&block_group->cache_node,
1016 &fs_info->block_group_cache_tree);
1017 RB_CLEAR_NODE(&block_group->cache_node);
1019 if (fs_info->first_logical_byte == block_group->start)
1020 fs_info->first_logical_byte = (u64)-1;
1021 spin_unlock(&fs_info->block_group_cache_lock);
1023 down_write(&block_group->space_info->groups_sem);
1025 * we must use list_del_init so people can check to see if they
1026 * are still on the list after taking the semaphore
1028 list_del_init(&block_group->list);
1029 if (list_empty(&block_group->space_info->block_groups[index])) {
1030 kobj = block_group->space_info->block_group_kobjs[index];
1031 block_group->space_info->block_group_kobjs[index] = NULL;
1032 clear_avail_alloc_bits(fs_info, block_group->flags);
1034 up_write(&block_group->space_info->groups_sem);
1035 clear_incompat_bg_bits(fs_info, block_group->flags);
1041 if (block_group->has_caching_ctl)
1042 caching_ctl = btrfs_get_caching_control(block_group);
1043 if (block_group->cached == BTRFS_CACHE_STARTED)
1044 btrfs_wait_block_group_cache_done(block_group);
1045 if (block_group->has_caching_ctl) {
1046 down_write(&fs_info->commit_root_sem);
1048 struct btrfs_caching_control *ctl;
1050 list_for_each_entry(ctl,
1051 &fs_info->caching_block_groups, list)
1052 if (ctl->block_group == block_group) {
1054 refcount_inc(&caching_ctl->count);
1059 list_del_init(&caching_ctl->list);
1060 up_write(&fs_info->commit_root_sem);
1062 /* Once for the caching bgs list and once for us. */
1063 btrfs_put_caching_control(caching_ctl);
1064 btrfs_put_caching_control(caching_ctl);
1068 spin_lock(&trans->transaction->dirty_bgs_lock);
1069 WARN_ON(!list_empty(&block_group->dirty_list));
1070 WARN_ON(!list_empty(&block_group->io_list));
1071 spin_unlock(&trans->transaction->dirty_bgs_lock);
1073 btrfs_remove_free_space_cache(block_group);
1075 spin_lock(&block_group->space_info->lock);
1076 list_del_init(&block_group->ro_list);
1078 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1079 WARN_ON(block_group->space_info->total_bytes
1080 < block_group->length);
1081 WARN_ON(block_group->space_info->bytes_readonly
1082 < block_group->length);
1083 WARN_ON(block_group->space_info->disk_total
1084 < block_group->length * factor);
1086 block_group->space_info->total_bytes -= block_group->length;
1087 block_group->space_info->bytes_readonly -= block_group->length;
1088 block_group->space_info->disk_total -= block_group->length * factor;
1090 spin_unlock(&block_group->space_info->lock);
1092 mutex_lock(&fs_info->chunk_mutex);
1093 spin_lock(&block_group->lock);
1094 block_group->removed = 1;
1096 * At this point trimming or scrub can't start on this block group,
1097 * because we removed the block group from the rbtree
1098 * fs_info->block_group_cache_tree so no one can't find it anymore and
1099 * even if someone already got this block group before we removed it
1100 * from the rbtree, they have already incremented block_group->frozen -
1101 * if they didn't, for the trimming case they won't find any free space
1102 * entries because we already removed them all when we called
1103 * btrfs_remove_free_space_cache().
1105 * And we must not remove the extent map from the fs_info->mapping_tree
1106 * to prevent the same logical address range and physical device space
1107 * ranges from being reused for a new block group. This is needed to
1108 * avoid races with trimming and scrub.
1110 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1111 * completely transactionless, so while it is trimming a range the
1112 * currently running transaction might finish and a new one start,
1113 * allowing for new block groups to be created that can reuse the same
1114 * physical device locations unless we take this special care.
1116 * There may also be an implicit trim operation if the file system
1117 * is mounted with -odiscard. The same protections must remain
1118 * in place until the extents have been discarded completely when
1119 * the transaction commit has completed.
1121 remove_em = (atomic_read(&block_group->frozen) == 0);
1122 spin_unlock(&block_group->lock);
1124 mutex_unlock(&fs_info->chunk_mutex);
1126 ret = remove_block_group_free_space(trans, block_group);
1130 /* Once for the block groups rbtree */
1131 btrfs_put_block_group(block_group);
1133 ret = remove_block_group_item(trans, path, block_group);
1138 struct extent_map_tree *em_tree;
1140 em_tree = &fs_info->mapping_tree;
1141 write_lock(&em_tree->lock);
1142 remove_extent_mapping(em_tree, em);
1143 write_unlock(&em_tree->lock);
1144 /* once for the tree */
1145 free_extent_map(em);
1149 /* Once for the lookup reference */
1150 btrfs_put_block_group(block_group);
1153 btrfs_delayed_refs_rsv_release(fs_info, 1);
1154 btrfs_free_path(path);
1158 struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1159 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1161 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1162 struct extent_map *em;
1163 struct map_lookup *map;
1164 unsigned int num_items;
1166 read_lock(&em_tree->lock);
1167 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1168 read_unlock(&em_tree->lock);
1169 ASSERT(em && em->start == chunk_offset);
1172 * We need to reserve 3 + N units from the metadata space info in order
1173 * to remove a block group (done at btrfs_remove_chunk() and at
1174 * btrfs_remove_block_group()), which are used for:
1176 * 1 unit for adding the free space inode's orphan (located in the tree
1178 * 1 unit for deleting the block group item (located in the extent
1180 * 1 unit for deleting the free space item (located in tree of tree
1182 * N units for deleting N device extent items corresponding to each
1183 * stripe (located in the device tree).
1185 * In order to remove a block group we also need to reserve units in the
1186 * system space info in order to update the chunk tree (update one or
1187 * more device items and remove one chunk item), but this is done at
1188 * btrfs_remove_chunk() through a call to check_system_chunk().
1190 map = em->map_lookup;
1191 num_items = 3 + map->num_stripes;
1192 free_extent_map(em);
1194 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
1199 * Mark block group @cache read-only, so later write won't happen to block
1202 * If @force is not set, this function will only mark the block group readonly
1203 * if we have enough free space (1M) in other metadata/system block groups.
1204 * If @force is not set, this function will mark the block group readonly
1205 * without checking free space.
1207 * NOTE: This function doesn't care if other block groups can contain all the
1208 * data in this block group. That check should be done by relocation routine,
1209 * not this function.
1211 static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
1213 struct btrfs_space_info *sinfo = cache->space_info;
1217 spin_lock(&sinfo->lock);
1218 spin_lock(&cache->lock);
1226 num_bytes = cache->length - cache->reserved - cache->pinned -
1227 cache->bytes_super - cache->used;
1230 * Data never overcommits, even in mixed mode, so do just the straight
1231 * check of left over space in how much we have allocated.
1235 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1236 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1239 * Here we make sure if we mark this bg RO, we still have enough
1240 * free space as buffer.
1242 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1246 * We overcommit metadata, so we need to do the
1247 * btrfs_can_overcommit check here, and we need to pass in
1248 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1249 * leeway to allow us to mark this block group as read only.
1251 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1252 BTRFS_RESERVE_NO_FLUSH))
1257 sinfo->bytes_readonly += num_bytes;
1259 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
1262 spin_unlock(&cache->lock);
1263 spin_unlock(&sinfo->lock);
1264 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1265 btrfs_info(cache->fs_info,
1266 "unable to make block group %llu ro", cache->start);
1267 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1272 static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1273 struct btrfs_block_group *bg)
1275 struct btrfs_fs_info *fs_info = bg->fs_info;
1276 struct btrfs_transaction *prev_trans = NULL;
1277 const u64 start = bg->start;
1278 const u64 end = start + bg->length - 1;
1281 spin_lock(&fs_info->trans_lock);
1282 if (trans->transaction->list.prev != &fs_info->trans_list) {
1283 prev_trans = list_last_entry(&trans->transaction->list,
1284 struct btrfs_transaction, list);
1285 refcount_inc(&prev_trans->use_count);
1287 spin_unlock(&fs_info->trans_lock);
1290 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1291 * btrfs_finish_extent_commit(). If we are at transaction N, another
1292 * task might be running finish_extent_commit() for the previous
1293 * transaction N - 1, and have seen a range belonging to the block
1294 * group in pinned_extents before we were able to clear the whole block
1295 * group range from pinned_extents. This means that task can lookup for
1296 * the block group after we unpinned it from pinned_extents and removed
1297 * it, leading to a BUG_ON() at unpin_extent_range().
1299 mutex_lock(&fs_info->unused_bg_unpin_mutex);
1301 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1307 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
1310 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1312 btrfs_put_transaction(prev_trans);
1318 * Process the unused_bgs list and remove any that don't have any allocated
1319 * space inside of them.
1321 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1323 struct btrfs_block_group *block_group;
1324 struct btrfs_space_info *space_info;
1325 struct btrfs_trans_handle *trans;
1326 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1329 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1332 spin_lock(&fs_info->unused_bgs_lock);
1333 while (!list_empty(&fs_info->unused_bgs)) {
1336 block_group = list_first_entry(&fs_info->unused_bgs,
1337 struct btrfs_block_group,
1339 list_del_init(&block_group->bg_list);
1341 space_info = block_group->space_info;
1343 if (ret || btrfs_mixed_space_info(space_info)) {
1344 btrfs_put_block_group(block_group);
1347 spin_unlock(&fs_info->unused_bgs_lock);
1349 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1351 mutex_lock(&fs_info->delete_unused_bgs_mutex);
1353 /* Don't want to race with allocators so take the groups_sem */
1354 down_write(&space_info->groups_sem);
1357 * Async discard moves the final block group discard to be prior
1358 * to the unused_bgs code path. Therefore, if it's not fully
1359 * trimmed, punt it back to the async discard lists.
1361 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1362 !btrfs_is_free_space_trimmed(block_group)) {
1363 trace_btrfs_skip_unused_block_group(block_group);
1364 up_write(&space_info->groups_sem);
1365 /* Requeue if we failed because of async discard */
1366 btrfs_discard_queue_work(&fs_info->discard_ctl,
1371 spin_lock(&block_group->lock);
1372 if (block_group->reserved || block_group->pinned ||
1373 block_group->used || block_group->ro ||
1374 list_is_singular(&block_group->list)) {
1376 * We want to bail if we made new allocations or have
1377 * outstanding allocations in this block group. We do
1378 * the ro check in case balance is currently acting on
1381 trace_btrfs_skip_unused_block_group(block_group);
1382 spin_unlock(&block_group->lock);
1383 up_write(&space_info->groups_sem);
1386 spin_unlock(&block_group->lock);
1388 /* We don't want to force the issue, only flip if it's ok. */
1389 ret = inc_block_group_ro(block_group, 0);
1390 up_write(&space_info->groups_sem);
1397 * Want to do this before we do anything else so we can recover
1398 * properly if we fail to join the transaction.
1400 trans = btrfs_start_trans_remove_block_group(fs_info,
1401 block_group->start);
1402 if (IS_ERR(trans)) {
1403 btrfs_dec_block_group_ro(block_group);
1404 ret = PTR_ERR(trans);
1409 * We could have pending pinned extents for this block group,
1410 * just delete them, we don't care about them anymore.
1412 if (!clean_pinned_extents(trans, block_group)) {
1413 btrfs_dec_block_group_ro(block_group);
1418 * At this point, the block_group is read only and should fail
1419 * new allocations. However, btrfs_finish_extent_commit() can
1420 * cause this block_group to be placed back on the discard
1421 * lists because now the block_group isn't fully discarded.
1422 * Bail here and try again later after discarding everything.
1424 spin_lock(&fs_info->discard_ctl.lock);
1425 if (!list_empty(&block_group->discard_list)) {
1426 spin_unlock(&fs_info->discard_ctl.lock);
1427 btrfs_dec_block_group_ro(block_group);
1428 btrfs_discard_queue_work(&fs_info->discard_ctl,
1432 spin_unlock(&fs_info->discard_ctl.lock);
1434 /* Reset pinned so btrfs_put_block_group doesn't complain */
1435 spin_lock(&space_info->lock);
1436 spin_lock(&block_group->lock);
1438 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1439 -block_group->pinned);
1440 space_info->bytes_readonly += block_group->pinned;
1441 percpu_counter_add_batch(&space_info->total_bytes_pinned,
1442 -block_group->pinned,
1443 BTRFS_TOTAL_BYTES_PINNED_BATCH);
1444 block_group->pinned = 0;
1446 spin_unlock(&block_group->lock);
1447 spin_unlock(&space_info->lock);
1450 * The normal path here is an unused block group is passed here,
1451 * then trimming is handled in the transaction commit path.
1452 * Async discard interposes before this to do the trimming
1453 * before coming down the unused block group path as trimming
1454 * will no longer be done later in the transaction commit path.
1456 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1459 /* DISCARD can flip during remount */
1460 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC);
1462 /* Implicit trim during transaction commit. */
1464 btrfs_freeze_block_group(block_group);
1467 * Btrfs_remove_chunk will abort the transaction if things go
1470 ret = btrfs_remove_chunk(trans, block_group->start);
1474 btrfs_unfreeze_block_group(block_group);
1479 * If we're not mounted with -odiscard, we can just forget
1480 * about this block group. Otherwise we'll need to wait
1481 * until transaction commit to do the actual discard.
1484 spin_lock(&fs_info->unused_bgs_lock);
1486 * A concurrent scrub might have added us to the list
1487 * fs_info->unused_bgs, so use a list_move operation
1488 * to add the block group to the deleted_bgs list.
1490 list_move(&block_group->bg_list,
1491 &trans->transaction->deleted_bgs);
1492 spin_unlock(&fs_info->unused_bgs_lock);
1493 btrfs_get_block_group(block_group);
1496 btrfs_end_transaction(trans);
1498 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1499 btrfs_put_block_group(block_group);
1500 spin_lock(&fs_info->unused_bgs_lock);
1502 spin_unlock(&fs_info->unused_bgs_lock);
1506 btrfs_end_transaction(trans);
1507 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1508 btrfs_put_block_group(block_group);
1509 btrfs_discard_punt_unused_bgs_list(fs_info);
1512 void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1514 struct btrfs_fs_info *fs_info = bg->fs_info;
1516 spin_lock(&fs_info->unused_bgs_lock);
1517 if (list_empty(&bg->bg_list)) {
1518 btrfs_get_block_group(bg);
1519 trace_btrfs_add_unused_block_group(bg);
1520 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1522 spin_unlock(&fs_info->unused_bgs_lock);
1525 static int find_first_block_group(struct btrfs_fs_info *fs_info,
1526 struct btrfs_path *path,
1527 struct btrfs_key *key)
1529 struct btrfs_root *root = fs_info->extent_root;
1531 struct btrfs_key found_key;
1532 struct extent_buffer *leaf;
1533 struct btrfs_block_group_item bg;
1537 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1542 slot = path->slots[0];
1543 leaf = path->nodes[0];
1544 if (slot >= btrfs_header_nritems(leaf)) {
1545 ret = btrfs_next_leaf(root, path);
1552 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1554 if (found_key.objectid >= key->objectid &&
1555 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1556 struct extent_map_tree *em_tree;
1557 struct extent_map *em;
1559 em_tree = &root->fs_info->mapping_tree;
1560 read_lock(&em_tree->lock);
1561 em = lookup_extent_mapping(em_tree, found_key.objectid,
1563 read_unlock(&em_tree->lock);
1566 "logical %llu len %llu found bg but no related chunk",
1567 found_key.objectid, found_key.offset);
1569 } else if (em->start != found_key.objectid ||
1570 em->len != found_key.offset) {
1572 "block group %llu len %llu mismatch with chunk %llu len %llu",
1573 found_key.objectid, found_key.offset,
1574 em->start, em->len);
1577 read_extent_buffer(leaf, &bg,
1578 btrfs_item_ptr_offset(leaf, slot),
1580 flags = btrfs_stack_block_group_flags(&bg) &
1581 BTRFS_BLOCK_GROUP_TYPE_MASK;
1583 if (flags != (em->map_lookup->type &
1584 BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1586 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1588 found_key.offset, flags,
1589 (BTRFS_BLOCK_GROUP_TYPE_MASK &
1590 em->map_lookup->type));
1596 free_extent_map(em);
1605 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1607 u64 extra_flags = chunk_to_extended(flags) &
1608 BTRFS_EXTENDED_PROFILE_MASK;
1610 write_seqlock(&fs_info->profiles_lock);
1611 if (flags & BTRFS_BLOCK_GROUP_DATA)
1612 fs_info->avail_data_alloc_bits |= extra_flags;
1613 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1614 fs_info->avail_metadata_alloc_bits |= extra_flags;
1615 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1616 fs_info->avail_system_alloc_bits |= extra_flags;
1617 write_sequnlock(&fs_info->profiles_lock);
1621 * btrfs_rmap_block - Map a physical disk address to a list of logical addresses
1622 * @chunk_start: logical address of block group
1623 * @physical: physical address to map to logical addresses
1624 * @logical: return array of logical addresses which map to @physical
1625 * @naddrs: length of @logical
1626 * @stripe_len: size of IO stripe for the given block group
1628 * Maps a particular @physical disk address to a list of @logical addresses.
1629 * Used primarily to exclude those portions of a block group that contain super
1633 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1634 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
1636 struct extent_map *em;
1637 struct map_lookup *map;
1640 u64 data_stripe_length;
1645 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1649 map = em->map_lookup;
1650 data_stripe_length = em->len;
1651 io_stripe_size = map->stripe_len;
1653 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
1654 data_stripe_length = div_u64(data_stripe_length,
1655 map->num_stripes / map->sub_stripes);
1656 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
1657 data_stripe_length = div_u64(data_stripe_length, map->num_stripes);
1658 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
1659 data_stripe_length = div_u64(data_stripe_length,
1660 nr_data_stripes(map));
1661 io_stripe_size = map->stripe_len * nr_data_stripes(map);
1664 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
1670 for (i = 0; i < map->num_stripes; i++) {
1671 bool already_inserted = false;
1675 if (!in_range(physical, map->stripes[i].physical,
1676 data_stripe_length))
1679 stripe_nr = physical - map->stripes[i].physical;
1680 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
1682 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1683 stripe_nr = stripe_nr * map->num_stripes + i;
1684 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1685 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1686 stripe_nr = stripe_nr * map->num_stripes + i;
1689 * The remaining case would be for RAID56, multiply by
1690 * nr_data_stripes(). Alternatively, just use rmap_len below
1691 * instead of map->stripe_len
1694 bytenr = chunk_start + stripe_nr * io_stripe_size;
1696 /* Ensure we don't add duplicate addresses */
1697 for (j = 0; j < nr; j++) {
1698 if (buf[j] == bytenr) {
1699 already_inserted = true;
1704 if (!already_inserted)
1710 *stripe_len = io_stripe_size;
1712 free_extent_map(em);
1716 static int exclude_super_stripes(struct btrfs_block_group *cache)
1718 struct btrfs_fs_info *fs_info = cache->fs_info;
1724 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1725 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
1726 cache->bytes_super += stripe_len;
1727 ret = btrfs_add_excluded_extent(fs_info, cache->start,
1733 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1734 bytenr = btrfs_sb_offset(i);
1735 ret = btrfs_rmap_block(fs_info, cache->start,
1736 bytenr, &logical, &nr, &stripe_len);
1743 if (logical[nr] > cache->start + cache->length)
1746 if (logical[nr] + stripe_len <= cache->start)
1749 start = logical[nr];
1750 if (start < cache->start) {
1751 start = cache->start;
1752 len = (logical[nr] + stripe_len) - start;
1754 len = min_t(u64, stripe_len,
1755 cache->start + cache->length - start);
1758 cache->bytes_super += len;
1759 ret = btrfs_add_excluded_extent(fs_info, start, len);
1771 static void link_block_group(struct btrfs_block_group *cache)
1773 struct btrfs_space_info *space_info = cache->space_info;
1774 int index = btrfs_bg_flags_to_raid_index(cache->flags);
1777 down_write(&space_info->groups_sem);
1778 if (list_empty(&space_info->block_groups[index]))
1780 list_add_tail(&cache->list, &space_info->block_groups[index]);
1781 up_write(&space_info->groups_sem);
1784 btrfs_sysfs_add_block_group_type(cache);
1787 static struct btrfs_block_group *btrfs_create_block_group_cache(
1788 struct btrfs_fs_info *fs_info, u64 start)
1790 struct btrfs_block_group *cache;
1792 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1796 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1798 if (!cache->free_space_ctl) {
1803 cache->start = start;
1805 cache->fs_info = fs_info;
1806 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
1807 set_free_space_tree_thresholds(cache);
1809 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1811 atomic_set(&cache->count, 1);
1812 spin_lock_init(&cache->lock);
1813 init_rwsem(&cache->data_rwsem);
1814 INIT_LIST_HEAD(&cache->list);
1815 INIT_LIST_HEAD(&cache->cluster_list);
1816 INIT_LIST_HEAD(&cache->bg_list);
1817 INIT_LIST_HEAD(&cache->ro_list);
1818 INIT_LIST_HEAD(&cache->discard_list);
1819 INIT_LIST_HEAD(&cache->dirty_list);
1820 INIT_LIST_HEAD(&cache->io_list);
1821 btrfs_init_free_space_ctl(cache);
1822 atomic_set(&cache->frozen, 0);
1823 mutex_init(&cache->free_space_lock);
1824 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1830 * Iterate all chunks and verify that each of them has the corresponding block
1833 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1835 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1836 struct extent_map *em;
1837 struct btrfs_block_group *bg;
1842 read_lock(&map_tree->lock);
1844 * lookup_extent_mapping will return the first extent map
1845 * intersecting the range, so setting @len to 1 is enough to
1846 * get the first chunk.
1848 em = lookup_extent_mapping(map_tree, start, 1);
1849 read_unlock(&map_tree->lock);
1853 bg = btrfs_lookup_block_group(fs_info, em->start);
1856 "chunk start=%llu len=%llu doesn't have corresponding block group",
1857 em->start, em->len);
1859 free_extent_map(em);
1862 if (bg->start != em->start || bg->length != em->len ||
1863 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1864 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1866 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
1868 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
1869 bg->start, bg->length,
1870 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
1872 free_extent_map(em);
1873 btrfs_put_block_group(bg);
1876 start = em->start + em->len;
1877 free_extent_map(em);
1878 btrfs_put_block_group(bg);
1883 static int read_block_group_item(struct btrfs_block_group *cache,
1884 struct btrfs_path *path,
1885 const struct btrfs_key *key)
1887 struct extent_buffer *leaf = path->nodes[0];
1888 struct btrfs_block_group_item bgi;
1889 int slot = path->slots[0];
1891 cache->length = key->offset;
1893 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
1895 cache->used = btrfs_stack_block_group_used(&bgi);
1896 cache->flags = btrfs_stack_block_group_flags(&bgi);
1901 static int read_one_block_group(struct btrfs_fs_info *info,
1902 struct btrfs_path *path,
1903 const struct btrfs_key *key,
1906 struct btrfs_block_group *cache;
1907 struct btrfs_space_info *space_info;
1908 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
1911 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
1913 cache = btrfs_create_block_group_cache(info, key->objectid);
1917 ret = read_block_group_item(cache, path, key);
1923 * When we mount with old space cache, we need to
1924 * set BTRFS_DC_CLEAR and set dirty flag.
1926 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
1927 * truncate the old free space cache inode and
1929 * b) Setting 'dirty flag' makes sure that we flush
1930 * the new space cache info onto disk.
1932 if (btrfs_test_opt(info, SPACE_CACHE))
1933 cache->disk_cache_state = BTRFS_DC_CLEAR;
1935 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
1936 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
1938 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
1945 * We need to exclude the super stripes now so that the space info has
1946 * super bytes accounted for, otherwise we'll think we have more space
1947 * than we actually do.
1949 ret = exclude_super_stripes(cache);
1951 /* We may have excluded something, so call this just in case. */
1952 btrfs_free_excluded_extents(cache);
1957 * Check for two cases, either we are full, and therefore don't need
1958 * to bother with the caching work since we won't find any space, or we
1959 * are empty, and we can just add all the space in and be done with it.
1960 * This saves us _a_lot_ of time, particularly in the full case.
1962 if (cache->length == cache->used) {
1963 cache->last_byte_to_unpin = (u64)-1;
1964 cache->cached = BTRFS_CACHE_FINISHED;
1965 btrfs_free_excluded_extents(cache);
1966 } else if (cache->used == 0) {
1967 cache->last_byte_to_unpin = (u64)-1;
1968 cache->cached = BTRFS_CACHE_FINISHED;
1969 add_new_free_space(cache, cache->start,
1970 cache->start + cache->length);
1971 btrfs_free_excluded_extents(cache);
1974 ret = btrfs_add_block_group_cache(info, cache);
1976 btrfs_remove_free_space_cache(cache);
1979 trace_btrfs_add_block_group(info, cache, 0);
1980 btrfs_update_space_info(info, cache->flags, cache->length,
1981 cache->used, cache->bytes_super, &space_info);
1983 cache->space_info = space_info;
1985 link_block_group(cache);
1987 set_avail_alloc_bits(info, cache->flags);
1988 if (btrfs_chunk_readonly(info, cache->start)) {
1989 inc_block_group_ro(cache, 1);
1990 } else if (cache->used == 0) {
1991 ASSERT(list_empty(&cache->bg_list));
1992 if (btrfs_test_opt(info, DISCARD_ASYNC))
1993 btrfs_discard_queue_work(&info->discard_ctl, cache);
1995 btrfs_mark_bg_unused(cache);
1999 btrfs_put_block_group(cache);
2003 int btrfs_read_block_groups(struct btrfs_fs_info *info)
2005 struct btrfs_path *path;
2007 struct btrfs_block_group *cache;
2008 struct btrfs_space_info *space_info;
2009 struct btrfs_key key;
2015 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2016 path = btrfs_alloc_path();
2020 cache_gen = btrfs_super_cache_generation(info->super_copy);
2021 if (btrfs_test_opt(info, SPACE_CACHE) &&
2022 btrfs_super_generation(info->super_copy) != cache_gen)
2024 if (btrfs_test_opt(info, CLEAR_CACHE))
2028 ret = find_first_block_group(info, path, &key);
2034 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2035 ret = read_one_block_group(info, path, &key, need_clear);
2038 key.objectid += key.offset;
2040 btrfs_release_path(path);
2044 list_for_each_entry_rcu(space_info, &info->space_info, list) {
2045 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2046 (BTRFS_BLOCK_GROUP_RAID10 |
2047 BTRFS_BLOCK_GROUP_RAID1_MASK |
2048 BTRFS_BLOCK_GROUP_RAID56_MASK |
2049 BTRFS_BLOCK_GROUP_DUP)))
2052 * Avoid allocating from un-mirrored block group if there are
2053 * mirrored block groups.
2055 list_for_each_entry(cache,
2056 &space_info->block_groups[BTRFS_RAID_RAID0],
2058 inc_block_group_ro(cache, 1);
2059 list_for_each_entry(cache,
2060 &space_info->block_groups[BTRFS_RAID_SINGLE],
2062 inc_block_group_ro(cache, 1);
2066 btrfs_init_global_block_rsv(info);
2067 ret = check_chunk_block_group_mappings(info);
2069 btrfs_free_path(path);
2073 static int insert_block_group_item(struct btrfs_trans_handle *trans,
2074 struct btrfs_block_group *block_group)
2076 struct btrfs_fs_info *fs_info = trans->fs_info;
2077 struct btrfs_block_group_item bgi;
2078 struct btrfs_root *root;
2079 struct btrfs_key key;
2081 spin_lock(&block_group->lock);
2082 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2083 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2084 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2085 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2086 key.objectid = block_group->start;
2087 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2088 key.offset = block_group->length;
2089 spin_unlock(&block_group->lock);
2091 root = fs_info->extent_root;
2092 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2095 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2097 struct btrfs_fs_info *fs_info = trans->fs_info;
2098 struct btrfs_block_group *block_group;
2101 if (!trans->can_flush_pending_bgs)
2104 while (!list_empty(&trans->new_bgs)) {
2105 block_group = list_first_entry(&trans->new_bgs,
2106 struct btrfs_block_group,
2111 ret = insert_block_group_item(trans, block_group);
2113 btrfs_abort_transaction(trans, ret);
2114 ret = btrfs_finish_chunk_alloc(trans, block_group->start,
2115 block_group->length);
2117 btrfs_abort_transaction(trans, ret);
2118 add_block_group_free_space(trans, block_group);
2119 /* Already aborted the transaction if it failed. */
2121 btrfs_delayed_refs_rsv_release(fs_info, 1);
2122 list_del_init(&block_group->bg_list);
2124 btrfs_trans_release_chunk_metadata(trans);
2127 int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
2128 u64 type, u64 chunk_offset, u64 size)
2130 struct btrfs_fs_info *fs_info = trans->fs_info;
2131 struct btrfs_block_group *cache;
2134 btrfs_set_log_full_commit(trans);
2136 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
2140 cache->length = size;
2141 cache->used = bytes_used;
2142 cache->flags = type;
2143 cache->last_byte_to_unpin = (u64)-1;
2144 cache->cached = BTRFS_CACHE_FINISHED;
2145 cache->needs_free_space = 1;
2146 ret = exclude_super_stripes(cache);
2148 /* We may have excluded something, so call this just in case */
2149 btrfs_free_excluded_extents(cache);
2150 btrfs_put_block_group(cache);
2154 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2156 btrfs_free_excluded_extents(cache);
2158 #ifdef CONFIG_BTRFS_DEBUG
2159 if (btrfs_should_fragment_free_space(cache)) {
2160 u64 new_bytes_used = size - bytes_used;
2162 bytes_used += new_bytes_used >> 1;
2163 fragment_free_space(cache);
2167 * Ensure the corresponding space_info object is created and
2168 * assigned to our block group. We want our bg to be added to the rbtree
2169 * with its ->space_info set.
2171 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2172 ASSERT(cache->space_info);
2174 ret = btrfs_add_block_group_cache(fs_info, cache);
2176 btrfs_remove_free_space_cache(cache);
2177 btrfs_put_block_group(cache);
2182 * Now that our block group has its ->space_info set and is inserted in
2183 * the rbtree, update the space info's counters.
2185 trace_btrfs_add_block_group(fs_info, cache, 1);
2186 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
2187 cache->bytes_super, &cache->space_info);
2188 btrfs_update_global_block_rsv(fs_info);
2190 link_block_group(cache);
2192 list_add_tail(&cache->bg_list, &trans->new_bgs);
2193 trans->delayed_ref_updates++;
2194 btrfs_update_delayed_refs_rsv(trans);
2196 set_avail_alloc_bits(fs_info, type);
2200 static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
2206 * if restripe for this chunk_type is on pick target profile and
2207 * return, otherwise do the usual balance
2209 stripped = get_restripe_target(fs_info, flags);
2211 return extended_to_chunk(stripped);
2213 num_devices = fs_info->fs_devices->rw_devices;
2215 stripped = BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID56_MASK |
2216 BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10;
2218 if (num_devices == 1) {
2219 stripped |= BTRFS_BLOCK_GROUP_DUP;
2220 stripped = flags & ~stripped;
2222 /* turn raid0 into single device chunks */
2223 if (flags & BTRFS_BLOCK_GROUP_RAID0)
2226 /* turn mirroring into duplication */
2227 if (flags & (BTRFS_BLOCK_GROUP_RAID1_MASK |
2228 BTRFS_BLOCK_GROUP_RAID10))
2229 return stripped | BTRFS_BLOCK_GROUP_DUP;
2231 /* they already had raid on here, just return */
2232 if (flags & stripped)
2235 stripped |= BTRFS_BLOCK_GROUP_DUP;
2236 stripped = flags & ~stripped;
2238 /* switch duplicated blocks with raid1 */
2239 if (flags & BTRFS_BLOCK_GROUP_DUP)
2240 return stripped | BTRFS_BLOCK_GROUP_RAID1;
2242 /* this is drive concat, leave it alone */
2249 * Mark one block group RO, can be called several times for the same block
2252 * @cache: the destination block group
2253 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2254 * ensure we still have some free space after marking this
2257 int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2258 bool do_chunk_alloc)
2260 struct btrfs_fs_info *fs_info = cache->fs_info;
2261 struct btrfs_trans_handle *trans;
2266 trans = btrfs_join_transaction(fs_info->extent_root);
2268 return PTR_ERR(trans);
2271 * we're not allowed to set block groups readonly after the dirty
2272 * block groups cache has started writing. If it already started,
2273 * back off and let this transaction commit
2275 mutex_lock(&fs_info->ro_block_group_mutex);
2276 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2277 u64 transid = trans->transid;
2279 mutex_unlock(&fs_info->ro_block_group_mutex);
2280 btrfs_end_transaction(trans);
2282 ret = btrfs_wait_for_commit(fs_info, transid);
2288 if (do_chunk_alloc) {
2290 * If we are changing raid levels, try to allocate a
2291 * corresponding block group with the new raid level.
2293 alloc_flags = update_block_group_flags(fs_info, cache->flags);
2294 if (alloc_flags != cache->flags) {
2295 ret = btrfs_chunk_alloc(trans, alloc_flags,
2298 * ENOSPC is allowed here, we may have enough space
2299 * already allocated at the new raid level to carry on
2308 ret = inc_block_group_ro(cache, 0);
2309 if (!do_chunk_alloc)
2313 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2314 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2317 ret = inc_block_group_ro(cache, 0);
2319 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2320 alloc_flags = update_block_group_flags(fs_info, cache->flags);
2321 mutex_lock(&fs_info->chunk_mutex);
2322 check_system_chunk(trans, alloc_flags);
2323 mutex_unlock(&fs_info->chunk_mutex);
2326 mutex_unlock(&fs_info->ro_block_group_mutex);
2328 btrfs_end_transaction(trans);
2332 void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
2334 struct btrfs_space_info *sinfo = cache->space_info;
2339 spin_lock(&sinfo->lock);
2340 spin_lock(&cache->lock);
2342 num_bytes = cache->length - cache->reserved -
2343 cache->pinned - cache->bytes_super - cache->used;
2344 sinfo->bytes_readonly -= num_bytes;
2345 list_del_init(&cache->ro_list);
2347 spin_unlock(&cache->lock);
2348 spin_unlock(&sinfo->lock);
2351 static int update_block_group_item(struct btrfs_trans_handle *trans,
2352 struct btrfs_path *path,
2353 struct btrfs_block_group *cache)
2355 struct btrfs_fs_info *fs_info = trans->fs_info;
2357 struct btrfs_root *root = fs_info->extent_root;
2359 struct extent_buffer *leaf;
2360 struct btrfs_block_group_item bgi;
2361 struct btrfs_key key;
2363 key.objectid = cache->start;
2364 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2365 key.offset = cache->length;
2367 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2374 leaf = path->nodes[0];
2375 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2376 btrfs_set_stack_block_group_used(&bgi, cache->used);
2377 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2378 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2379 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2380 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
2381 btrfs_mark_buffer_dirty(leaf);
2383 btrfs_release_path(path);
2388 static int cache_save_setup(struct btrfs_block_group *block_group,
2389 struct btrfs_trans_handle *trans,
2390 struct btrfs_path *path)
2392 struct btrfs_fs_info *fs_info = block_group->fs_info;
2393 struct btrfs_root *root = fs_info->tree_root;
2394 struct inode *inode = NULL;
2395 struct extent_changeset *data_reserved = NULL;
2397 int dcs = BTRFS_DC_ERROR;
2403 * If this block group is smaller than 100 megs don't bother caching the
2406 if (block_group->length < (100 * SZ_1M)) {
2407 spin_lock(&block_group->lock);
2408 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2409 spin_unlock(&block_group->lock);
2413 if (TRANS_ABORTED(trans))
2416 inode = lookup_free_space_inode(block_group, path);
2417 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2418 ret = PTR_ERR(inode);
2419 btrfs_release_path(path);
2423 if (IS_ERR(inode)) {
2427 if (block_group->ro)
2430 ret = create_free_space_inode(trans, block_group, path);
2437 * We want to set the generation to 0, that way if anything goes wrong
2438 * from here on out we know not to trust this cache when we load up next
2441 BTRFS_I(inode)->generation = 0;
2442 ret = btrfs_update_inode(trans, root, inode);
2445 * So theoretically we could recover from this, simply set the
2446 * super cache generation to 0 so we know to invalidate the
2447 * cache, but then we'd have to keep track of the block groups
2448 * that fail this way so we know we _have_ to reset this cache
2449 * before the next commit or risk reading stale cache. So to
2450 * limit our exposure to horrible edge cases lets just abort the
2451 * transaction, this only happens in really bad situations
2454 btrfs_abort_transaction(trans, ret);
2459 /* We've already setup this transaction, go ahead and exit */
2460 if (block_group->cache_generation == trans->transid &&
2461 i_size_read(inode)) {
2462 dcs = BTRFS_DC_SETUP;
2466 if (i_size_read(inode) > 0) {
2467 ret = btrfs_check_trunc_cache_free_space(fs_info,
2468 &fs_info->global_block_rsv);
2472 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2477 spin_lock(&block_group->lock);
2478 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2479 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2481 * don't bother trying to write stuff out _if_
2482 * a) we're not cached,
2483 * b) we're with nospace_cache mount option,
2484 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2486 dcs = BTRFS_DC_WRITTEN;
2487 spin_unlock(&block_group->lock);
2490 spin_unlock(&block_group->lock);
2493 * We hit an ENOSPC when setting up the cache in this transaction, just
2494 * skip doing the setup, we've already cleared the cache so we're safe.
2496 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2502 * Try to preallocate enough space based on how big the block group is.
2503 * Keep in mind this has to include any pinned space which could end up
2504 * taking up quite a bit since it's not folded into the other space
2507 num_pages = div_u64(block_group->length, SZ_256M);
2512 num_pages *= PAGE_SIZE;
2514 ret = btrfs_check_data_free_space(inode, &data_reserved, 0, num_pages);
2518 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2519 num_pages, num_pages,
2522 * Our cache requires contiguous chunks so that we don't modify a bunch
2523 * of metadata or split extents when writing the cache out, which means
2524 * we can enospc if we are heavily fragmented in addition to just normal
2525 * out of space conditions. So if we hit this just skip setting up any
2526 * other block groups for this transaction, maybe we'll unpin enough
2527 * space the next time around.
2530 dcs = BTRFS_DC_SETUP;
2531 else if (ret == -ENOSPC)
2532 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2537 btrfs_release_path(path);
2539 spin_lock(&block_group->lock);
2540 if (!ret && dcs == BTRFS_DC_SETUP)
2541 block_group->cache_generation = trans->transid;
2542 block_group->disk_cache_state = dcs;
2543 spin_unlock(&block_group->lock);
2545 extent_changeset_free(data_reserved);
2549 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2551 struct btrfs_fs_info *fs_info = trans->fs_info;
2552 struct btrfs_block_group *cache, *tmp;
2553 struct btrfs_transaction *cur_trans = trans->transaction;
2554 struct btrfs_path *path;
2556 if (list_empty(&cur_trans->dirty_bgs) ||
2557 !btrfs_test_opt(fs_info, SPACE_CACHE))
2560 path = btrfs_alloc_path();
2564 /* Could add new block groups, use _safe just in case */
2565 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2567 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2568 cache_save_setup(cache, trans, path);
2571 btrfs_free_path(path);
2576 * Transaction commit does final block group cache writeback during a critical
2577 * section where nothing is allowed to change the FS. This is required in
2578 * order for the cache to actually match the block group, but can introduce a
2579 * lot of latency into the commit.
2581 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2582 * There's a chance we'll have to redo some of it if the block group changes
2583 * again during the commit, but it greatly reduces the commit latency by
2584 * getting rid of the easy block groups while we're still allowing others to
2587 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2589 struct btrfs_fs_info *fs_info = trans->fs_info;
2590 struct btrfs_block_group *cache;
2591 struct btrfs_transaction *cur_trans = trans->transaction;
2594 struct btrfs_path *path = NULL;
2596 struct list_head *io = &cur_trans->io_bgs;
2597 int num_started = 0;
2600 spin_lock(&cur_trans->dirty_bgs_lock);
2601 if (list_empty(&cur_trans->dirty_bgs)) {
2602 spin_unlock(&cur_trans->dirty_bgs_lock);
2605 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2606 spin_unlock(&cur_trans->dirty_bgs_lock);
2609 /* Make sure all the block groups on our dirty list actually exist */
2610 btrfs_create_pending_block_groups(trans);
2613 path = btrfs_alloc_path();
2619 * cache_write_mutex is here only to save us from balance or automatic
2620 * removal of empty block groups deleting this block group while we are
2621 * writing out the cache
2623 mutex_lock(&trans->transaction->cache_write_mutex);
2624 while (!list_empty(&dirty)) {
2625 bool drop_reserve = true;
2627 cache = list_first_entry(&dirty, struct btrfs_block_group,
2630 * This can happen if something re-dirties a block group that
2631 * is already under IO. Just wait for it to finish and then do
2634 if (!list_empty(&cache->io_list)) {
2635 list_del_init(&cache->io_list);
2636 btrfs_wait_cache_io(trans, cache, path);
2637 btrfs_put_block_group(cache);
2642 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
2643 * it should update the cache_state. Don't delete until after
2646 * Since we're not running in the commit critical section
2647 * we need the dirty_bgs_lock to protect from update_block_group
2649 spin_lock(&cur_trans->dirty_bgs_lock);
2650 list_del_init(&cache->dirty_list);
2651 spin_unlock(&cur_trans->dirty_bgs_lock);
2655 cache_save_setup(cache, trans, path);
2657 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
2658 cache->io_ctl.inode = NULL;
2659 ret = btrfs_write_out_cache(trans, cache, path);
2660 if (ret == 0 && cache->io_ctl.inode) {
2665 * The cache_write_mutex is protecting the
2666 * io_list, also refer to the definition of
2667 * btrfs_transaction::io_bgs for more details
2669 list_add_tail(&cache->io_list, io);
2672 * If we failed to write the cache, the
2673 * generation will be bad and life goes on
2679 ret = update_block_group_item(trans, path, cache);
2681 * Our block group might still be attached to the list
2682 * of new block groups in the transaction handle of some
2683 * other task (struct btrfs_trans_handle->new_bgs). This
2684 * means its block group item isn't yet in the extent
2685 * tree. If this happens ignore the error, as we will
2686 * try again later in the critical section of the
2687 * transaction commit.
2689 if (ret == -ENOENT) {
2691 spin_lock(&cur_trans->dirty_bgs_lock);
2692 if (list_empty(&cache->dirty_list)) {
2693 list_add_tail(&cache->dirty_list,
2694 &cur_trans->dirty_bgs);
2695 btrfs_get_block_group(cache);
2696 drop_reserve = false;
2698 spin_unlock(&cur_trans->dirty_bgs_lock);
2700 btrfs_abort_transaction(trans, ret);
2704 /* If it's not on the io list, we need to put the block group */
2706 btrfs_put_block_group(cache);
2708 btrfs_delayed_refs_rsv_release(fs_info, 1);
2714 * Avoid blocking other tasks for too long. It might even save
2715 * us from writing caches for block groups that are going to be
2718 mutex_unlock(&trans->transaction->cache_write_mutex);
2719 mutex_lock(&trans->transaction->cache_write_mutex);
2721 mutex_unlock(&trans->transaction->cache_write_mutex);
2724 * Go through delayed refs for all the stuff we've just kicked off
2725 * and then loop back (just once)
2727 ret = btrfs_run_delayed_refs(trans, 0);
2728 if (!ret && loops == 0) {
2730 spin_lock(&cur_trans->dirty_bgs_lock);
2731 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2733 * dirty_bgs_lock protects us from concurrent block group
2734 * deletes too (not just cache_write_mutex).
2736 if (!list_empty(&dirty)) {
2737 spin_unlock(&cur_trans->dirty_bgs_lock);
2740 spin_unlock(&cur_trans->dirty_bgs_lock);
2741 } else if (ret < 0) {
2742 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
2745 btrfs_free_path(path);
2749 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
2751 struct btrfs_fs_info *fs_info = trans->fs_info;
2752 struct btrfs_block_group *cache;
2753 struct btrfs_transaction *cur_trans = trans->transaction;
2756 struct btrfs_path *path;
2757 struct list_head *io = &cur_trans->io_bgs;
2758 int num_started = 0;
2760 path = btrfs_alloc_path();
2765 * Even though we are in the critical section of the transaction commit,
2766 * we can still have concurrent tasks adding elements to this
2767 * transaction's list of dirty block groups. These tasks correspond to
2768 * endio free space workers started when writeback finishes for a
2769 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
2770 * allocate new block groups as a result of COWing nodes of the root
2771 * tree when updating the free space inode. The writeback for the space
2772 * caches is triggered by an earlier call to
2773 * btrfs_start_dirty_block_groups() and iterations of the following
2775 * Also we want to do the cache_save_setup first and then run the
2776 * delayed refs to make sure we have the best chance at doing this all
2779 spin_lock(&cur_trans->dirty_bgs_lock);
2780 while (!list_empty(&cur_trans->dirty_bgs)) {
2781 cache = list_first_entry(&cur_trans->dirty_bgs,
2782 struct btrfs_block_group,
2786 * This can happen if cache_save_setup re-dirties a block group
2787 * that is already under IO. Just wait for it to finish and
2788 * then do it all again
2790 if (!list_empty(&cache->io_list)) {
2791 spin_unlock(&cur_trans->dirty_bgs_lock);
2792 list_del_init(&cache->io_list);
2793 btrfs_wait_cache_io(trans, cache, path);
2794 btrfs_put_block_group(cache);
2795 spin_lock(&cur_trans->dirty_bgs_lock);
2799 * Don't remove from the dirty list until after we've waited on
2802 list_del_init(&cache->dirty_list);
2803 spin_unlock(&cur_trans->dirty_bgs_lock);
2806 cache_save_setup(cache, trans, path);
2809 ret = btrfs_run_delayed_refs(trans,
2810 (unsigned long) -1);
2812 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
2813 cache->io_ctl.inode = NULL;
2814 ret = btrfs_write_out_cache(trans, cache, path);
2815 if (ret == 0 && cache->io_ctl.inode) {
2818 list_add_tail(&cache->io_list, io);
2821 * If we failed to write the cache, the
2822 * generation will be bad and life goes on
2828 ret = update_block_group_item(trans, path, cache);
2830 * One of the free space endio workers might have
2831 * created a new block group while updating a free space
2832 * cache's inode (at inode.c:btrfs_finish_ordered_io())
2833 * and hasn't released its transaction handle yet, in
2834 * which case the new block group is still attached to
2835 * its transaction handle and its creation has not
2836 * finished yet (no block group item in the extent tree
2837 * yet, etc). If this is the case, wait for all free
2838 * space endio workers to finish and retry. This is a
2839 * a very rare case so no need for a more efficient and
2842 if (ret == -ENOENT) {
2843 wait_event(cur_trans->writer_wait,
2844 atomic_read(&cur_trans->num_writers) == 1);
2845 ret = update_block_group_item(trans, path, cache);
2848 btrfs_abort_transaction(trans, ret);
2851 /* If its not on the io list, we need to put the block group */
2853 btrfs_put_block_group(cache);
2854 btrfs_delayed_refs_rsv_release(fs_info, 1);
2855 spin_lock(&cur_trans->dirty_bgs_lock);
2857 spin_unlock(&cur_trans->dirty_bgs_lock);
2860 * Refer to the definition of io_bgs member for details why it's safe
2861 * to use it without any locking
2863 while (!list_empty(io)) {
2864 cache = list_first_entry(io, struct btrfs_block_group,
2866 list_del_init(&cache->io_list);
2867 btrfs_wait_cache_io(trans, cache, path);
2868 btrfs_put_block_group(cache);
2871 btrfs_free_path(path);
2875 int btrfs_update_block_group(struct btrfs_trans_handle *trans,
2876 u64 bytenr, u64 num_bytes, int alloc)
2878 struct btrfs_fs_info *info = trans->fs_info;
2879 struct btrfs_block_group *cache = NULL;
2880 u64 total = num_bytes;
2886 /* Block accounting for super block */
2887 spin_lock(&info->delalloc_root_lock);
2888 old_val = btrfs_super_bytes_used(info->super_copy);
2890 old_val += num_bytes;
2892 old_val -= num_bytes;
2893 btrfs_set_super_bytes_used(info->super_copy, old_val);
2894 spin_unlock(&info->delalloc_root_lock);
2897 cache = btrfs_lookup_block_group(info, bytenr);
2902 factor = btrfs_bg_type_to_factor(cache->flags);
2905 * If this block group has free space cache written out, we
2906 * need to make sure to load it if we are removing space. This
2907 * is because we need the unpinning stage to actually add the
2908 * space back to the block group, otherwise we will leak space.
2910 if (!alloc && !btrfs_block_group_done(cache))
2911 btrfs_cache_block_group(cache, 1);
2913 byte_in_group = bytenr - cache->start;
2914 WARN_ON(byte_in_group > cache->length);
2916 spin_lock(&cache->space_info->lock);
2917 spin_lock(&cache->lock);
2919 if (btrfs_test_opt(info, SPACE_CACHE) &&
2920 cache->disk_cache_state < BTRFS_DC_CLEAR)
2921 cache->disk_cache_state = BTRFS_DC_CLEAR;
2923 old_val = cache->used;
2924 num_bytes = min(total, cache->length - byte_in_group);
2926 old_val += num_bytes;
2927 cache->used = old_val;
2928 cache->reserved -= num_bytes;
2929 cache->space_info->bytes_reserved -= num_bytes;
2930 cache->space_info->bytes_used += num_bytes;
2931 cache->space_info->disk_used += num_bytes * factor;
2932 spin_unlock(&cache->lock);
2933 spin_unlock(&cache->space_info->lock);
2935 old_val -= num_bytes;
2936 cache->used = old_val;
2937 cache->pinned += num_bytes;
2938 btrfs_space_info_update_bytes_pinned(info,
2939 cache->space_info, num_bytes);
2940 cache->space_info->bytes_used -= num_bytes;
2941 cache->space_info->disk_used -= num_bytes * factor;
2942 spin_unlock(&cache->lock);
2943 spin_unlock(&cache->space_info->lock);
2945 percpu_counter_add_batch(
2946 &cache->space_info->total_bytes_pinned,
2948 BTRFS_TOTAL_BYTES_PINNED_BATCH);
2949 set_extent_dirty(&trans->transaction->pinned_extents,
2950 bytenr, bytenr + num_bytes - 1,
2951 GFP_NOFS | __GFP_NOFAIL);
2954 spin_lock(&trans->transaction->dirty_bgs_lock);
2955 if (list_empty(&cache->dirty_list)) {
2956 list_add_tail(&cache->dirty_list,
2957 &trans->transaction->dirty_bgs);
2958 trans->delayed_ref_updates++;
2959 btrfs_get_block_group(cache);
2961 spin_unlock(&trans->transaction->dirty_bgs_lock);
2964 * No longer have used bytes in this block group, queue it for
2965 * deletion. We do this after adding the block group to the
2966 * dirty list to avoid races between cleaner kthread and space
2969 if (!alloc && old_val == 0) {
2970 if (!btrfs_test_opt(info, DISCARD_ASYNC))
2971 btrfs_mark_bg_unused(cache);
2974 btrfs_put_block_group(cache);
2976 bytenr += num_bytes;
2979 /* Modified block groups are accounted for in the delayed_refs_rsv. */
2980 btrfs_update_delayed_refs_rsv(trans);
2985 * btrfs_add_reserved_bytes - update the block_group and space info counters
2986 * @cache: The cache we are manipulating
2987 * @ram_bytes: The number of bytes of file content, and will be same to
2988 * @num_bytes except for the compress path.
2989 * @num_bytes: The number of bytes in question
2990 * @delalloc: The blocks are allocated for the delalloc write
2992 * This is called by the allocator when it reserves space. If this is a
2993 * reservation and the block group has become read only we cannot make the
2994 * reservation and return -EAGAIN, otherwise this function always succeeds.
2996 int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
2997 u64 ram_bytes, u64 num_bytes, int delalloc)
2999 struct btrfs_space_info *space_info = cache->space_info;
3002 spin_lock(&space_info->lock);
3003 spin_lock(&cache->lock);
3007 cache->reserved += num_bytes;
3008 space_info->bytes_reserved += num_bytes;
3009 trace_btrfs_space_reservation(cache->fs_info, "space_info",
3010 space_info->flags, num_bytes, 1);
3011 btrfs_space_info_update_bytes_may_use(cache->fs_info,
3012 space_info, -ram_bytes);
3014 cache->delalloc_bytes += num_bytes;
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);
3048 spin_unlock(&space_info->lock);
3051 static void force_metadata_allocation(struct btrfs_fs_info *info)
3053 struct list_head *head = &info->space_info;
3054 struct btrfs_space_info *found;
3057 list_for_each_entry_rcu(found, head, list) {
3058 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3059 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 spin_unlock(&space_info->lock);
3147 mutex_lock(&fs_info->chunk_mutex);
3148 mutex_unlock(&fs_info->chunk_mutex);
3150 /* Proceed with allocation */
3151 space_info->chunk_alloc = 1;
3152 wait_for_alloc = false;
3153 spin_unlock(&space_info->lock);
3157 } while (wait_for_alloc);
3159 mutex_lock(&fs_info->chunk_mutex);
3160 trans->allocating_chunk = true;
3163 * If we have mixed data/metadata chunks we want to make sure we keep
3164 * allocating mixed chunks instead of individual chunks.
3166 if (btrfs_mixed_space_info(space_info))
3167 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3170 * if we're doing a data chunk, go ahead and make sure that
3171 * we keep a reasonable number of metadata chunks allocated in the
3174 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3175 fs_info->data_chunk_allocations++;
3176 if (!(fs_info->data_chunk_allocations %
3177 fs_info->metadata_ratio))
3178 force_metadata_allocation(fs_info);
3182 * Check if we have enough space in SYSTEM chunk because we may need
3183 * to update devices.
3185 check_system_chunk(trans, flags);
3187 ret = btrfs_alloc_chunk(trans, flags);
3188 trans->allocating_chunk = false;
3190 spin_lock(&space_info->lock);
3193 space_info->full = 1;
3198 space_info->max_extent_size = 0;
3201 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3203 space_info->chunk_alloc = 0;
3204 spin_unlock(&space_info->lock);
3205 mutex_unlock(&fs_info->chunk_mutex);
3207 * When we allocate a new chunk we reserve space in the chunk block
3208 * reserve to make sure we can COW nodes/leafs in the chunk tree or
3209 * add new nodes/leafs to it if we end up needing to do it when
3210 * inserting the chunk item and updating device items as part of the
3211 * second phase of chunk allocation, performed by
3212 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
3213 * large number of new block groups to create in our transaction
3214 * handle's new_bgs list to avoid exhausting the chunk block reserve
3215 * in extreme cases - like having a single transaction create many new
3216 * block groups when starting to write out the free space caches of all
3217 * the block groups that were made dirty during the lifetime of the
3220 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
3221 btrfs_create_pending_block_groups(trans);
3226 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3230 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3232 num_dev = fs_info->fs_devices->rw_devices;
3238 * Reserve space in the system space for allocating or removing a chunk
3240 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3242 struct btrfs_fs_info *fs_info = trans->fs_info;
3243 struct btrfs_space_info *info;
3250 * Needed because we can end up allocating a system chunk and for an
3251 * atomic and race free space reservation in the chunk block reserve.
3253 lockdep_assert_held(&fs_info->chunk_mutex);
3255 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3256 spin_lock(&info->lock);
3257 left = info->total_bytes - btrfs_space_info_used(info, true);
3258 spin_unlock(&info->lock);
3260 num_devs = get_profile_num_devs(fs_info, type);
3262 /* num_devs device items to update and 1 chunk item to add or remove */
3263 thresh = btrfs_calc_metadata_size(fs_info, num_devs) +
3264 btrfs_calc_insert_metadata_size(fs_info, 1);
3266 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3267 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3268 left, thresh, type);
3269 btrfs_dump_space_info(fs_info, info, 0, 0);
3272 if (left < thresh) {
3273 u64 flags = btrfs_system_alloc_profile(fs_info);
3276 * Ignore failure to create system chunk. We might end up not
3277 * needing it, as we might not need to COW all nodes/leafs from
3278 * the paths we visit in the chunk tree (they were already COWed
3279 * or created in the current transaction for example).
3281 ret = btrfs_alloc_chunk(trans, flags);
3285 ret = btrfs_block_rsv_add(fs_info->chunk_root,
3286 &fs_info->chunk_block_rsv,
3287 thresh, BTRFS_RESERVE_NO_FLUSH);
3289 trans->chunk_bytes_reserved += thresh;
3293 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3295 struct btrfs_block_group *block_group;
3299 struct inode *inode;
3301 block_group = btrfs_lookup_first_block_group(info, last);
3302 while (block_group) {
3303 btrfs_wait_block_group_cache_done(block_group);
3304 spin_lock(&block_group->lock);
3305 if (block_group->iref)
3307 spin_unlock(&block_group->lock);
3308 block_group = btrfs_next_block_group(block_group);
3317 inode = block_group->inode;
3318 block_group->iref = 0;
3319 block_group->inode = NULL;
3320 spin_unlock(&block_group->lock);
3321 ASSERT(block_group->io_ctl.inode == NULL);
3323 last = block_group->start + block_group->length;
3324 btrfs_put_block_group(block_group);
3329 * Must be called only after stopping all workers, since we could have block
3330 * group caching kthreads running, and therefore they could race with us if we
3331 * freed the block groups before stopping them.
3333 int btrfs_free_block_groups(struct btrfs_fs_info *info)
3335 struct btrfs_block_group *block_group;
3336 struct btrfs_space_info *space_info;
3337 struct btrfs_caching_control *caching_ctl;
3340 down_write(&info->commit_root_sem);
3341 while (!list_empty(&info->caching_block_groups)) {
3342 caching_ctl = list_entry(info->caching_block_groups.next,
3343 struct btrfs_caching_control, list);
3344 list_del(&caching_ctl->list);
3345 btrfs_put_caching_control(caching_ctl);
3347 up_write(&info->commit_root_sem);
3349 spin_lock(&info->unused_bgs_lock);
3350 while (!list_empty(&info->unused_bgs)) {
3351 block_group = list_first_entry(&info->unused_bgs,
3352 struct btrfs_block_group,
3354 list_del_init(&block_group->bg_list);
3355 btrfs_put_block_group(block_group);
3357 spin_unlock(&info->unused_bgs_lock);
3359 spin_lock(&info->block_group_cache_lock);
3360 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
3361 block_group = rb_entry(n, struct btrfs_block_group,
3363 rb_erase(&block_group->cache_node,
3364 &info->block_group_cache_tree);
3365 RB_CLEAR_NODE(&block_group->cache_node);
3366 spin_unlock(&info->block_group_cache_lock);
3368 down_write(&block_group->space_info->groups_sem);
3369 list_del(&block_group->list);
3370 up_write(&block_group->space_info->groups_sem);
3373 * We haven't cached this block group, which means we could
3374 * possibly have excluded extents on this block group.
3376 if (block_group->cached == BTRFS_CACHE_NO ||
3377 block_group->cached == BTRFS_CACHE_ERROR)
3378 btrfs_free_excluded_extents(block_group);
3380 btrfs_remove_free_space_cache(block_group);
3381 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
3382 ASSERT(list_empty(&block_group->dirty_list));
3383 ASSERT(list_empty(&block_group->io_list));
3384 ASSERT(list_empty(&block_group->bg_list));
3385 ASSERT(atomic_read(&block_group->count) == 1);
3386 btrfs_put_block_group(block_group);
3388 spin_lock(&info->block_group_cache_lock);
3390 spin_unlock(&info->block_group_cache_lock);
3393 * Now that all the block groups are freed, go through and free all the
3394 * space_info structs. This is only called during the final stages of
3395 * unmount, and so we know nobody is using them. We call
3396 * synchronize_rcu() once before we start, just to be on the safe side.
3400 btrfs_release_global_block_rsv(info);
3402 while (!list_empty(&info->space_info)) {
3403 space_info = list_entry(info->space_info.next,
3404 struct btrfs_space_info,
3408 * Do not hide this behind enospc_debug, this is actually
3409 * important and indicates a real bug if this happens.
3411 if (WARN_ON(space_info->bytes_pinned > 0 ||
3412 space_info->bytes_reserved > 0 ||
3413 space_info->bytes_may_use > 0))
3414 btrfs_dump_space_info(info, space_info, 0, 0);
3415 WARN_ON(space_info->reclaim_size > 0);
3416 list_del(&space_info->list);
3417 btrfs_sysfs_remove_space_info(space_info);
3422 void btrfs_freeze_block_group(struct btrfs_block_group *cache)
3424 atomic_inc(&cache->frozen);
3427 void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
3429 struct btrfs_fs_info *fs_info = block_group->fs_info;
3430 struct extent_map_tree *em_tree;
3431 struct extent_map *em;
3434 spin_lock(&block_group->lock);
3435 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
3436 block_group->removed);
3437 spin_unlock(&block_group->lock);
3440 mutex_lock(&fs_info->chunk_mutex);
3441 em_tree = &fs_info->mapping_tree;
3442 write_lock(&em_tree->lock);
3443 em = lookup_extent_mapping(em_tree, block_group->start,
3445 BUG_ON(!em); /* logic error, can't happen */
3446 remove_extent_mapping(em_tree, em);
3447 write_unlock(&em_tree->lock);
3448 mutex_unlock(&fs_info->chunk_mutex);
3450 /* once for us and once for the tree */
3451 free_extent_map(em);
3452 free_extent_map(em);
3455 * We may have left one free space entry and other possible
3456 * tasks trimming this block group have left 1 entry each one.
3459 __btrfs_remove_free_space_cache(block_group->free_space_ctl);