1 // SPDX-License-Identifier: GPL-2.0
5 #include "block-group.h"
6 #include "space-info.h"
8 #include "free-space-cache.h"
9 #include "free-space-tree.h"
11 #include "transaction.h"
12 #include "ref-verify.h"
15 #include "delalloc-space.h"
20 * Return target flags in extended format or 0 if restripe for this chunk_type
23 * Should be called with balance_lock held
25 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
27 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
33 if (flags & BTRFS_BLOCK_GROUP_DATA &&
34 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
35 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
36 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
37 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
38 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
39 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
40 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
41 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
48 * @flags: available profiles in extended format (see ctree.h)
50 * Return reduced profile in chunk format. If profile changing is in progress
51 * (either running or paused) picks the target profile (if it's already
52 * available), otherwise falls back to plain reducing.
54 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
56 u64 num_devices = fs_info->fs_devices->rw_devices;
62 * See if restripe for this chunk_type is in progress, if so try to
63 * reduce to the target profile
65 spin_lock(&fs_info->balance_lock);
66 target = get_restripe_target(fs_info, flags);
68 spin_unlock(&fs_info->balance_lock);
69 return extended_to_chunk(target);
71 spin_unlock(&fs_info->balance_lock);
73 /* First, mask out the RAID levels which aren't possible */
74 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
75 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
76 allowed |= btrfs_raid_array[raid_type].bg_flag;
80 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
81 allowed = BTRFS_BLOCK_GROUP_RAID6;
82 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
83 allowed = BTRFS_BLOCK_GROUP_RAID5;
84 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
85 allowed = BTRFS_BLOCK_GROUP_RAID10;
86 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
87 allowed = BTRFS_BLOCK_GROUP_RAID1;
88 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
89 allowed = BTRFS_BLOCK_GROUP_RAID0;
91 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
93 return extended_to_chunk(flags | allowed);
96 u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
103 seq = read_seqbegin(&fs_info->profiles_lock);
105 if (flags & BTRFS_BLOCK_GROUP_DATA)
106 flags |= fs_info->avail_data_alloc_bits;
107 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
108 flags |= fs_info->avail_system_alloc_bits;
109 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
110 flags |= fs_info->avail_metadata_alloc_bits;
111 } while (read_seqretry(&fs_info->profiles_lock, seq));
113 return btrfs_reduce_alloc_profile(fs_info, flags);
116 void btrfs_get_block_group(struct btrfs_block_group *cache)
118 refcount_inc(&cache->refs);
121 void btrfs_put_block_group(struct btrfs_block_group *cache)
123 if (refcount_dec_and_test(&cache->refs)) {
124 WARN_ON(cache->pinned > 0);
125 WARN_ON(cache->reserved > 0);
128 * A block_group shouldn't be on the discard_list anymore.
129 * Remove the block_group from the discard_list to prevent us
130 * from causing a panic due to NULL pointer dereference.
132 if (WARN_ON(!list_empty(&cache->discard_list)))
133 btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
137 * If not empty, someone is still holding mutex of
138 * full_stripe_lock, which can only be released by caller.
139 * And it will definitely cause use-after-free when caller
140 * tries to release full stripe lock.
142 * No better way to resolve, but only to warn.
144 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
145 kfree(cache->free_space_ctl);
151 * This adds the block group to the fs_info rb tree for the block group cache
153 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
154 struct btrfs_block_group *block_group)
157 struct rb_node *parent = NULL;
158 struct btrfs_block_group *cache;
160 ASSERT(block_group->length != 0);
162 spin_lock(&info->block_group_cache_lock);
163 p = &info->block_group_cache_tree.rb_node;
167 cache = rb_entry(parent, struct btrfs_block_group, cache_node);
168 if (block_group->start < cache->start) {
170 } else if (block_group->start > cache->start) {
173 spin_unlock(&info->block_group_cache_lock);
178 rb_link_node(&block_group->cache_node, parent, p);
179 rb_insert_color(&block_group->cache_node,
180 &info->block_group_cache_tree);
182 if (info->first_logical_byte > block_group->start)
183 info->first_logical_byte = block_group->start;
185 spin_unlock(&info->block_group_cache_lock);
191 * This will return the block group at or after bytenr if contains is 0, else
192 * it will return the block group that contains the bytenr
194 static struct btrfs_block_group *block_group_cache_tree_search(
195 struct btrfs_fs_info *info, u64 bytenr, int contains)
197 struct btrfs_block_group *cache, *ret = NULL;
201 spin_lock(&info->block_group_cache_lock);
202 n = info->block_group_cache_tree.rb_node;
205 cache = rb_entry(n, struct btrfs_block_group, cache_node);
206 end = cache->start + cache->length - 1;
207 start = cache->start;
209 if (bytenr < start) {
210 if (!contains && (!ret || start < ret->start))
213 } else if (bytenr > start) {
214 if (contains && bytenr <= end) {
225 btrfs_get_block_group(ret);
226 if (bytenr == 0 && info->first_logical_byte > ret->start)
227 info->first_logical_byte = ret->start;
229 spin_unlock(&info->block_group_cache_lock);
235 * Return the block group that starts at or after bytenr
237 struct btrfs_block_group *btrfs_lookup_first_block_group(
238 struct btrfs_fs_info *info, u64 bytenr)
240 return block_group_cache_tree_search(info, bytenr, 0);
244 * Return the block group that contains the given bytenr
246 struct btrfs_block_group *btrfs_lookup_block_group(
247 struct btrfs_fs_info *info, u64 bytenr)
249 return block_group_cache_tree_search(info, bytenr, 1);
252 struct btrfs_block_group *btrfs_next_block_group(
253 struct btrfs_block_group *cache)
255 struct btrfs_fs_info *fs_info = cache->fs_info;
256 struct rb_node *node;
258 spin_lock(&fs_info->block_group_cache_lock);
260 /* If our block group was removed, we need a full search. */
261 if (RB_EMPTY_NODE(&cache->cache_node)) {
262 const u64 next_bytenr = cache->start + cache->length;
264 spin_unlock(&fs_info->block_group_cache_lock);
265 btrfs_put_block_group(cache);
266 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
268 node = rb_next(&cache->cache_node);
269 btrfs_put_block_group(cache);
271 cache = rb_entry(node, struct btrfs_block_group, cache_node);
272 btrfs_get_block_group(cache);
275 spin_unlock(&fs_info->block_group_cache_lock);
279 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
281 struct btrfs_block_group *bg;
284 bg = btrfs_lookup_block_group(fs_info, bytenr);
288 spin_lock(&bg->lock);
292 atomic_inc(&bg->nocow_writers);
293 spin_unlock(&bg->lock);
295 /* No put on block group, done by btrfs_dec_nocow_writers */
297 btrfs_put_block_group(bg);
302 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
304 struct btrfs_block_group *bg;
306 bg = btrfs_lookup_block_group(fs_info, bytenr);
308 if (atomic_dec_and_test(&bg->nocow_writers))
309 wake_up_var(&bg->nocow_writers);
311 * Once for our lookup and once for the lookup done by a previous call
312 * to btrfs_inc_nocow_writers()
314 btrfs_put_block_group(bg);
315 btrfs_put_block_group(bg);
318 void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
320 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
323 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
326 struct btrfs_block_group *bg;
328 bg = btrfs_lookup_block_group(fs_info, start);
330 if (atomic_dec_and_test(&bg->reservations))
331 wake_up_var(&bg->reservations);
332 btrfs_put_block_group(bg);
335 void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
337 struct btrfs_space_info *space_info = bg->space_info;
341 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
345 * Our block group is read only but before we set it to read only,
346 * some task might have had allocated an extent from it already, but it
347 * has not yet created a respective ordered extent (and added it to a
348 * root's list of ordered extents).
349 * Therefore wait for any task currently allocating extents, since the
350 * block group's reservations counter is incremented while a read lock
351 * on the groups' semaphore is held and decremented after releasing
352 * the read access on that semaphore and creating the ordered extent.
354 down_write(&space_info->groups_sem);
355 up_write(&space_info->groups_sem);
357 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
360 struct btrfs_caching_control *btrfs_get_caching_control(
361 struct btrfs_block_group *cache)
363 struct btrfs_caching_control *ctl;
365 spin_lock(&cache->lock);
366 if (!cache->caching_ctl) {
367 spin_unlock(&cache->lock);
371 ctl = cache->caching_ctl;
372 refcount_inc(&ctl->count);
373 spin_unlock(&cache->lock);
377 void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
379 if (refcount_dec_and_test(&ctl->count))
384 * When we wait for progress in the block group caching, its because our
385 * allocation attempt failed at least once. So, we must sleep and let some
386 * progress happen before we try again.
388 * This function will sleep at least once waiting for new free space to show
389 * up, and then it will check the block group free space numbers for our min
390 * num_bytes. Another option is to have it go ahead and look in the rbtree for
391 * a free extent of a given size, but this is a good start.
393 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
394 * any of the information in this block group.
396 void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
399 struct btrfs_caching_control *caching_ctl;
401 caching_ctl = btrfs_get_caching_control(cache);
405 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
406 (cache->free_space_ctl->free_space >= num_bytes));
408 btrfs_put_caching_control(caching_ctl);
411 int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
413 struct btrfs_caching_control *caching_ctl;
416 caching_ctl = btrfs_get_caching_control(cache);
418 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
420 wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
421 if (cache->cached == BTRFS_CACHE_ERROR)
423 btrfs_put_caching_control(caching_ctl);
427 #ifdef CONFIG_BTRFS_DEBUG
428 static void fragment_free_space(struct btrfs_block_group *block_group)
430 struct btrfs_fs_info *fs_info = block_group->fs_info;
431 u64 start = block_group->start;
432 u64 len = block_group->length;
433 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
434 fs_info->nodesize : fs_info->sectorsize;
435 u64 step = chunk << 1;
437 while (len > chunk) {
438 btrfs_remove_free_space(block_group, start, chunk);
449 * This is only called by btrfs_cache_block_group, since we could have freed
450 * extents we need to check the pinned_extents for any extents that can't be
451 * used yet since their free space will be released as soon as the transaction
454 u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
456 struct btrfs_fs_info *info = block_group->fs_info;
457 u64 extent_start, extent_end, size, total_added = 0;
460 while (start < end) {
461 ret = find_first_extent_bit(&info->excluded_extents, start,
462 &extent_start, &extent_end,
463 EXTENT_DIRTY | EXTENT_UPTODATE,
468 if (extent_start <= start) {
469 start = extent_end + 1;
470 } else if (extent_start > start && extent_start < end) {
471 size = extent_start - start;
473 ret = btrfs_add_free_space_async_trimmed(block_group,
475 BUG_ON(ret); /* -ENOMEM or logic error */
476 start = extent_end + 1;
485 ret = btrfs_add_free_space_async_trimmed(block_group, start,
487 BUG_ON(ret); /* -ENOMEM or logic error */
493 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
495 struct btrfs_block_group *block_group = caching_ctl->block_group;
496 struct btrfs_fs_info *fs_info = block_group->fs_info;
497 struct btrfs_root *extent_root = fs_info->extent_root;
498 struct btrfs_path *path;
499 struct extent_buffer *leaf;
500 struct btrfs_key key;
507 path = btrfs_alloc_path();
511 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
513 #ifdef CONFIG_BTRFS_DEBUG
515 * If we're fragmenting we don't want to make anybody think we can
516 * allocate from this block group until we've had a chance to fragment
519 if (btrfs_should_fragment_free_space(block_group))
523 * We don't want to deadlock with somebody trying to allocate a new
524 * extent for the extent root while also trying to search the extent
525 * root to add free space. So we skip locking and search the commit
526 * root, since its read-only
528 path->skip_locking = 1;
529 path->search_commit_root = 1;
530 path->reada = READA_FORWARD;
534 key.type = BTRFS_EXTENT_ITEM_KEY;
537 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
541 leaf = path->nodes[0];
542 nritems = btrfs_header_nritems(leaf);
545 if (btrfs_fs_closing(fs_info) > 1) {
550 if (path->slots[0] < nritems) {
551 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
553 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
557 if (need_resched() ||
558 rwsem_is_contended(&fs_info->commit_root_sem)) {
560 caching_ctl->progress = last;
561 btrfs_release_path(path);
562 up_read(&fs_info->commit_root_sem);
563 mutex_unlock(&caching_ctl->mutex);
565 mutex_lock(&caching_ctl->mutex);
566 down_read(&fs_info->commit_root_sem);
570 ret = btrfs_next_leaf(extent_root, path);
575 leaf = path->nodes[0];
576 nritems = btrfs_header_nritems(leaf);
580 if (key.objectid < last) {
583 key.type = BTRFS_EXTENT_ITEM_KEY;
586 caching_ctl->progress = last;
587 btrfs_release_path(path);
591 if (key.objectid < block_group->start) {
596 if (key.objectid >= block_group->start + block_group->length)
599 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
600 key.type == BTRFS_METADATA_ITEM_KEY) {
601 total_found += add_new_free_space(block_group, last,
603 if (key.type == BTRFS_METADATA_ITEM_KEY)
604 last = key.objectid +
607 last = key.objectid + key.offset;
609 if (total_found > CACHING_CTL_WAKE_UP) {
612 wake_up(&caching_ctl->wait);
619 total_found += add_new_free_space(block_group, last,
620 block_group->start + block_group->length);
621 caching_ctl->progress = (u64)-1;
624 btrfs_free_path(path);
628 static noinline void caching_thread(struct btrfs_work *work)
630 struct btrfs_block_group *block_group;
631 struct btrfs_fs_info *fs_info;
632 struct btrfs_caching_control *caching_ctl;
635 caching_ctl = container_of(work, struct btrfs_caching_control, work);
636 block_group = caching_ctl->block_group;
637 fs_info = block_group->fs_info;
639 mutex_lock(&caching_ctl->mutex);
640 down_read(&fs_info->commit_root_sem);
642 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
643 ret = load_free_space_tree(caching_ctl);
645 ret = load_extent_tree_free(caching_ctl);
647 spin_lock(&block_group->lock);
648 block_group->caching_ctl = NULL;
649 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
650 spin_unlock(&block_group->lock);
652 #ifdef CONFIG_BTRFS_DEBUG
653 if (btrfs_should_fragment_free_space(block_group)) {
656 spin_lock(&block_group->space_info->lock);
657 spin_lock(&block_group->lock);
658 bytes_used = block_group->length - block_group->used;
659 block_group->space_info->bytes_used += bytes_used >> 1;
660 spin_unlock(&block_group->lock);
661 spin_unlock(&block_group->space_info->lock);
662 fragment_free_space(block_group);
666 caching_ctl->progress = (u64)-1;
668 up_read(&fs_info->commit_root_sem);
669 btrfs_free_excluded_extents(block_group);
670 mutex_unlock(&caching_ctl->mutex);
672 wake_up(&caching_ctl->wait);
674 btrfs_put_caching_control(caching_ctl);
675 btrfs_put_block_group(block_group);
678 int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
681 struct btrfs_fs_info *fs_info = cache->fs_info;
682 struct btrfs_caching_control *caching_ctl;
685 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
689 INIT_LIST_HEAD(&caching_ctl->list);
690 mutex_init(&caching_ctl->mutex);
691 init_waitqueue_head(&caching_ctl->wait);
692 caching_ctl->block_group = cache;
693 caching_ctl->progress = cache->start;
694 refcount_set(&caching_ctl->count, 1);
695 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
697 spin_lock(&cache->lock);
699 * This should be a rare occasion, but this could happen I think in the
700 * case where one thread starts to load the space cache info, and then
701 * some other thread starts a transaction commit which tries to do an
702 * allocation while the other thread is still loading the space cache
703 * info. The previous loop should have kept us from choosing this block
704 * group, but if we've moved to the state where we will wait on caching
705 * block groups we need to first check if we're doing a fast load here,
706 * so we can wait for it to finish, otherwise we could end up allocating
707 * from a block group who's cache gets evicted for one reason or
710 while (cache->cached == BTRFS_CACHE_FAST) {
711 struct btrfs_caching_control *ctl;
713 ctl = cache->caching_ctl;
714 refcount_inc(&ctl->count);
715 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
716 spin_unlock(&cache->lock);
720 finish_wait(&ctl->wait, &wait);
721 btrfs_put_caching_control(ctl);
722 spin_lock(&cache->lock);
725 if (cache->cached != BTRFS_CACHE_NO) {
726 spin_unlock(&cache->lock);
730 WARN_ON(cache->caching_ctl);
731 cache->caching_ctl = caching_ctl;
732 cache->cached = BTRFS_CACHE_FAST;
733 spin_unlock(&cache->lock);
735 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
736 mutex_lock(&caching_ctl->mutex);
737 ret = load_free_space_cache(cache);
739 spin_lock(&cache->lock);
741 cache->caching_ctl = NULL;
742 cache->cached = BTRFS_CACHE_FINISHED;
743 cache->last_byte_to_unpin = (u64)-1;
744 caching_ctl->progress = (u64)-1;
746 if (load_cache_only) {
747 cache->caching_ctl = NULL;
748 cache->cached = BTRFS_CACHE_NO;
750 cache->cached = BTRFS_CACHE_STARTED;
751 cache->has_caching_ctl = 1;
754 spin_unlock(&cache->lock);
755 #ifdef CONFIG_BTRFS_DEBUG
757 btrfs_should_fragment_free_space(cache)) {
760 spin_lock(&cache->space_info->lock);
761 spin_lock(&cache->lock);
762 bytes_used = cache->length - cache->used;
763 cache->space_info->bytes_used += bytes_used >> 1;
764 spin_unlock(&cache->lock);
765 spin_unlock(&cache->space_info->lock);
766 fragment_free_space(cache);
769 mutex_unlock(&caching_ctl->mutex);
771 wake_up(&caching_ctl->wait);
773 btrfs_put_caching_control(caching_ctl);
774 btrfs_free_excluded_extents(cache);
779 * We're either using the free space tree or no caching at all.
780 * Set cached to the appropriate value and wakeup any waiters.
782 spin_lock(&cache->lock);
783 if (load_cache_only) {
784 cache->caching_ctl = NULL;
785 cache->cached = BTRFS_CACHE_NO;
787 cache->cached = BTRFS_CACHE_STARTED;
788 cache->has_caching_ctl = 1;
790 spin_unlock(&cache->lock);
791 wake_up(&caching_ctl->wait);
794 if (load_cache_only) {
795 btrfs_put_caching_control(caching_ctl);
799 down_write(&fs_info->commit_root_sem);
800 refcount_inc(&caching_ctl->count);
801 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
802 up_write(&fs_info->commit_root_sem);
804 btrfs_get_block_group(cache);
806 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
811 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
813 u64 extra_flags = chunk_to_extended(flags) &
814 BTRFS_EXTENDED_PROFILE_MASK;
816 write_seqlock(&fs_info->profiles_lock);
817 if (flags & BTRFS_BLOCK_GROUP_DATA)
818 fs_info->avail_data_alloc_bits &= ~extra_flags;
819 if (flags & BTRFS_BLOCK_GROUP_METADATA)
820 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
821 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
822 fs_info->avail_system_alloc_bits &= ~extra_flags;
823 write_sequnlock(&fs_info->profiles_lock);
827 * Clear incompat bits for the following feature(s):
829 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
830 * in the whole filesystem
832 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
834 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
836 bool found_raid56 = false;
837 bool found_raid1c34 = false;
839 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
840 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
841 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
842 struct list_head *head = &fs_info->space_info;
843 struct btrfs_space_info *sinfo;
845 list_for_each_entry_rcu(sinfo, head, list) {
846 down_read(&sinfo->groups_sem);
847 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
849 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
851 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
852 found_raid1c34 = true;
853 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
854 found_raid1c34 = true;
855 up_read(&sinfo->groups_sem);
858 btrfs_clear_fs_incompat(fs_info, RAID56);
860 btrfs_clear_fs_incompat(fs_info, RAID1C34);
864 static int remove_block_group_item(struct btrfs_trans_handle *trans,
865 struct btrfs_path *path,
866 struct btrfs_block_group *block_group)
868 struct btrfs_fs_info *fs_info = trans->fs_info;
869 struct btrfs_root *root;
870 struct btrfs_key key;
873 root = fs_info->extent_root;
874 key.objectid = block_group->start;
875 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
876 key.offset = block_group->length;
878 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
884 ret = btrfs_del_item(trans, root, path);
888 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
889 u64 group_start, struct extent_map *em)
891 struct btrfs_fs_info *fs_info = trans->fs_info;
892 struct btrfs_path *path;
893 struct btrfs_block_group *block_group;
894 struct btrfs_free_cluster *cluster;
895 struct btrfs_root *tree_root = fs_info->tree_root;
896 struct btrfs_key key;
898 struct kobject *kobj = NULL;
902 struct btrfs_caching_control *caching_ctl = NULL;
904 bool remove_rsv = false;
906 block_group = btrfs_lookup_block_group(fs_info, group_start);
907 BUG_ON(!block_group);
908 BUG_ON(!block_group->ro);
910 trace_btrfs_remove_block_group(block_group);
912 * Free the reserved super bytes from this block group before
915 btrfs_free_excluded_extents(block_group);
916 btrfs_free_ref_tree_range(fs_info, block_group->start,
917 block_group->length);
919 index = btrfs_bg_flags_to_raid_index(block_group->flags);
920 factor = btrfs_bg_type_to_factor(block_group->flags);
922 /* make sure this block group isn't part of an allocation cluster */
923 cluster = &fs_info->data_alloc_cluster;
924 spin_lock(&cluster->refill_lock);
925 btrfs_return_cluster_to_free_space(block_group, cluster);
926 spin_unlock(&cluster->refill_lock);
929 * make sure this block group isn't part of a metadata
932 cluster = &fs_info->meta_alloc_cluster;
933 spin_lock(&cluster->refill_lock);
934 btrfs_return_cluster_to_free_space(block_group, cluster);
935 spin_unlock(&cluster->refill_lock);
937 path = btrfs_alloc_path();
944 * get the inode first so any iput calls done for the io_list
945 * aren't the final iput (no unlinks allowed now)
947 inode = lookup_free_space_inode(block_group, path);
949 mutex_lock(&trans->transaction->cache_write_mutex);
951 * Make sure our free space cache IO is done before removing the
954 spin_lock(&trans->transaction->dirty_bgs_lock);
955 if (!list_empty(&block_group->io_list)) {
956 list_del_init(&block_group->io_list);
958 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
960 spin_unlock(&trans->transaction->dirty_bgs_lock);
961 btrfs_wait_cache_io(trans, block_group, path);
962 btrfs_put_block_group(block_group);
963 spin_lock(&trans->transaction->dirty_bgs_lock);
966 if (!list_empty(&block_group->dirty_list)) {
967 list_del_init(&block_group->dirty_list);
969 btrfs_put_block_group(block_group);
971 spin_unlock(&trans->transaction->dirty_bgs_lock);
972 mutex_unlock(&trans->transaction->cache_write_mutex);
974 if (!IS_ERR(inode)) {
975 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
977 btrfs_add_delayed_iput(inode);
981 /* One for the block groups ref */
982 spin_lock(&block_group->lock);
983 if (block_group->iref) {
984 block_group->iref = 0;
985 block_group->inode = NULL;
986 spin_unlock(&block_group->lock);
989 spin_unlock(&block_group->lock);
991 /* One for our lookup ref */
992 btrfs_add_delayed_iput(inode);
995 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
997 key.offset = block_group->start;
999 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
1003 btrfs_release_path(path);
1005 ret = btrfs_del_item(trans, tree_root, path);
1008 btrfs_release_path(path);
1011 spin_lock(&fs_info->block_group_cache_lock);
1012 rb_erase(&block_group->cache_node,
1013 &fs_info->block_group_cache_tree);
1014 RB_CLEAR_NODE(&block_group->cache_node);
1016 /* Once for the block groups rbtree */
1017 btrfs_put_block_group(block_group);
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);
1093 * Remove the free space for the block group from the free space tree
1094 * and the block group's item from the extent tree before marking the
1095 * block group as removed. This is to prevent races with tasks that
1096 * freeze and unfreeze a block group, this task and another task
1097 * allocating a new block group - the unfreeze task ends up removing
1098 * the block group's extent map before the task calling this function
1099 * deletes the block group item from the extent tree, allowing for
1100 * another task to attempt to create another block group with the same
1101 * item key (and failing with -EEXIST and a transaction abort).
1103 ret = remove_block_group_free_space(trans, block_group);
1107 ret = remove_block_group_item(trans, path, block_group);
1111 spin_lock(&block_group->lock);
1112 block_group->removed = 1;
1114 * At this point trimming or scrub can't start on this block group,
1115 * because we removed the block group from the rbtree
1116 * fs_info->block_group_cache_tree so no one can't find it anymore and
1117 * even if someone already got this block group before we removed it
1118 * from the rbtree, they have already incremented block_group->frozen -
1119 * if they didn't, for the trimming case they won't find any free space
1120 * entries because we already removed them all when we called
1121 * btrfs_remove_free_space_cache().
1123 * And we must not remove the extent map from the fs_info->mapping_tree
1124 * to prevent the same logical address range and physical device space
1125 * ranges from being reused for a new block group. This is needed to
1126 * avoid races with trimming and scrub.
1128 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1129 * completely transactionless, so while it is trimming a range the
1130 * currently running transaction might finish and a new one start,
1131 * allowing for new block groups to be created that can reuse the same
1132 * physical device locations unless we take this special care.
1134 * There may also be an implicit trim operation if the file system
1135 * is mounted with -odiscard. The same protections must remain
1136 * in place until the extents have been discarded completely when
1137 * the transaction commit has completed.
1139 remove_em = (atomic_read(&block_group->frozen) == 0);
1140 spin_unlock(&block_group->lock);
1143 struct extent_map_tree *em_tree;
1145 em_tree = &fs_info->mapping_tree;
1146 write_lock(&em_tree->lock);
1147 remove_extent_mapping(em_tree, em);
1148 write_unlock(&em_tree->lock);
1149 /* once for the tree */
1150 free_extent_map(em);
1154 /* Once for the lookup reference */
1155 btrfs_put_block_group(block_group);
1157 btrfs_delayed_refs_rsv_release(fs_info, 1);
1158 btrfs_free_path(path);
1162 struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1163 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1165 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1166 struct extent_map *em;
1167 struct map_lookup *map;
1168 unsigned int num_items;
1170 read_lock(&em_tree->lock);
1171 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1172 read_unlock(&em_tree->lock);
1173 ASSERT(em && em->start == chunk_offset);
1176 * We need to reserve 3 + N units from the metadata space info in order
1177 * to remove a block group (done at btrfs_remove_chunk() and at
1178 * btrfs_remove_block_group()), which are used for:
1180 * 1 unit for adding the free space inode's orphan (located in the tree
1182 * 1 unit for deleting the block group item (located in the extent
1184 * 1 unit for deleting the free space item (located in tree of tree
1186 * N units for deleting N device extent items corresponding to each
1187 * stripe (located in the device tree).
1189 * In order to remove a block group we also need to reserve units in the
1190 * system space info in order to update the chunk tree (update one or
1191 * more device items and remove one chunk item), but this is done at
1192 * btrfs_remove_chunk() through a call to check_system_chunk().
1194 map = em->map_lookup;
1195 num_items = 3 + map->num_stripes;
1196 free_extent_map(em);
1198 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
1203 * Mark block group @cache read-only, so later write won't happen to block
1206 * If @force is not set, this function will only mark the block group readonly
1207 * if we have enough free space (1M) in other metadata/system block groups.
1208 * If @force is not set, this function will mark the block group readonly
1209 * without checking free space.
1211 * NOTE: This function doesn't care if other block groups can contain all the
1212 * data in this block group. That check should be done by relocation routine,
1213 * not this function.
1215 static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
1217 struct btrfs_space_info *sinfo = cache->space_info;
1221 spin_lock(&sinfo->lock);
1222 spin_lock(&cache->lock);
1230 num_bytes = cache->length - cache->reserved - cache->pinned -
1231 cache->bytes_super - cache->used;
1234 * Data never overcommits, even in mixed mode, so do just the straight
1235 * check of left over space in how much we have allocated.
1239 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1240 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1243 * Here we make sure if we mark this bg RO, we still have enough
1244 * free space as buffer.
1246 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1250 * We overcommit metadata, so we need to do the
1251 * btrfs_can_overcommit check here, and we need to pass in
1252 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1253 * leeway to allow us to mark this block group as read only.
1255 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1256 BTRFS_RESERVE_NO_FLUSH))
1261 sinfo->bytes_readonly += num_bytes;
1263 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
1266 spin_unlock(&cache->lock);
1267 spin_unlock(&sinfo->lock);
1268 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1269 btrfs_info(cache->fs_info,
1270 "unable to make block group %llu ro", cache->start);
1271 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1276 static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1277 struct btrfs_block_group *bg)
1279 struct btrfs_fs_info *fs_info = bg->fs_info;
1280 struct btrfs_transaction *prev_trans = NULL;
1281 const u64 start = bg->start;
1282 const u64 end = start + bg->length - 1;
1285 spin_lock(&fs_info->trans_lock);
1286 if (trans->transaction->list.prev != &fs_info->trans_list) {
1287 prev_trans = list_last_entry(&trans->transaction->list,
1288 struct btrfs_transaction, list);
1289 refcount_inc(&prev_trans->use_count);
1291 spin_unlock(&fs_info->trans_lock);
1294 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1295 * btrfs_finish_extent_commit(). If we are at transaction N, another
1296 * task might be running finish_extent_commit() for the previous
1297 * transaction N - 1, and have seen a range belonging to the block
1298 * group in pinned_extents before we were able to clear the whole block
1299 * group range from pinned_extents. This means that task can lookup for
1300 * the block group after we unpinned it from pinned_extents and removed
1301 * it, leading to a BUG_ON() at unpin_extent_range().
1303 mutex_lock(&fs_info->unused_bg_unpin_mutex);
1305 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1311 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
1314 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1316 btrfs_put_transaction(prev_trans);
1322 * Process the unused_bgs list and remove any that don't have any allocated
1323 * space inside of them.
1325 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1327 struct btrfs_block_group *block_group;
1328 struct btrfs_space_info *space_info;
1329 struct btrfs_trans_handle *trans;
1330 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1333 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1336 spin_lock(&fs_info->unused_bgs_lock);
1337 while (!list_empty(&fs_info->unused_bgs)) {
1340 block_group = list_first_entry(&fs_info->unused_bgs,
1341 struct btrfs_block_group,
1343 list_del_init(&block_group->bg_list);
1345 space_info = block_group->space_info;
1347 if (ret || btrfs_mixed_space_info(space_info)) {
1348 btrfs_put_block_group(block_group);
1351 spin_unlock(&fs_info->unused_bgs_lock);
1353 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1355 mutex_lock(&fs_info->delete_unused_bgs_mutex);
1357 /* Don't want to race with allocators so take the groups_sem */
1358 down_write(&space_info->groups_sem);
1361 * Async discard moves the final block group discard to be prior
1362 * to the unused_bgs code path. Therefore, if it's not fully
1363 * trimmed, punt it back to the async discard lists.
1365 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1366 !btrfs_is_free_space_trimmed(block_group)) {
1367 trace_btrfs_skip_unused_block_group(block_group);
1368 up_write(&space_info->groups_sem);
1369 /* Requeue if we failed because of async discard */
1370 btrfs_discard_queue_work(&fs_info->discard_ctl,
1375 spin_lock(&block_group->lock);
1376 if (block_group->reserved || block_group->pinned ||
1377 block_group->used || block_group->ro ||
1378 list_is_singular(&block_group->list)) {
1380 * We want to bail if we made new allocations or have
1381 * outstanding allocations in this block group. We do
1382 * the ro check in case balance is currently acting on
1385 trace_btrfs_skip_unused_block_group(block_group);
1386 spin_unlock(&block_group->lock);
1387 up_write(&space_info->groups_sem);
1390 spin_unlock(&block_group->lock);
1392 /* We don't want to force the issue, only flip if it's ok. */
1393 ret = inc_block_group_ro(block_group, 0);
1394 up_write(&space_info->groups_sem);
1401 * Want to do this before we do anything else so we can recover
1402 * properly if we fail to join the transaction.
1404 trans = btrfs_start_trans_remove_block_group(fs_info,
1405 block_group->start);
1406 if (IS_ERR(trans)) {
1407 btrfs_dec_block_group_ro(block_group);
1408 ret = PTR_ERR(trans);
1413 * We could have pending pinned extents for this block group,
1414 * just delete them, we don't care about them anymore.
1416 if (!clean_pinned_extents(trans, block_group)) {
1417 btrfs_dec_block_group_ro(block_group);
1422 * At this point, the block_group is read only and should fail
1423 * new allocations. However, btrfs_finish_extent_commit() can
1424 * cause this block_group to be placed back on the discard
1425 * lists because now the block_group isn't fully discarded.
1426 * Bail here and try again later after discarding everything.
1428 spin_lock(&fs_info->discard_ctl.lock);
1429 if (!list_empty(&block_group->discard_list)) {
1430 spin_unlock(&fs_info->discard_ctl.lock);
1431 btrfs_dec_block_group_ro(block_group);
1432 btrfs_discard_queue_work(&fs_info->discard_ctl,
1436 spin_unlock(&fs_info->discard_ctl.lock);
1438 /* Reset pinned so btrfs_put_block_group doesn't complain */
1439 spin_lock(&space_info->lock);
1440 spin_lock(&block_group->lock);
1442 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1443 -block_group->pinned);
1444 space_info->bytes_readonly += block_group->pinned;
1445 percpu_counter_add_batch(&space_info->total_bytes_pinned,
1446 -block_group->pinned,
1447 BTRFS_TOTAL_BYTES_PINNED_BATCH);
1448 block_group->pinned = 0;
1450 spin_unlock(&block_group->lock);
1451 spin_unlock(&space_info->lock);
1454 * The normal path here is an unused block group is passed here,
1455 * then trimming is handled in the transaction commit path.
1456 * Async discard interposes before this to do the trimming
1457 * before coming down the unused block group path as trimming
1458 * will no longer be done later in the transaction commit path.
1460 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1463 /* DISCARD can flip during remount */
1464 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC);
1466 /* Implicit trim during transaction commit. */
1468 btrfs_freeze_block_group(block_group);
1471 * Btrfs_remove_chunk will abort the transaction if things go
1474 ret = btrfs_remove_chunk(trans, block_group->start);
1478 btrfs_unfreeze_block_group(block_group);
1483 * If we're not mounted with -odiscard, we can just forget
1484 * about this block group. Otherwise we'll need to wait
1485 * until transaction commit to do the actual discard.
1488 spin_lock(&fs_info->unused_bgs_lock);
1490 * A concurrent scrub might have added us to the list
1491 * fs_info->unused_bgs, so use a list_move operation
1492 * to add the block group to the deleted_bgs list.
1494 list_move(&block_group->bg_list,
1495 &trans->transaction->deleted_bgs);
1496 spin_unlock(&fs_info->unused_bgs_lock);
1497 btrfs_get_block_group(block_group);
1500 btrfs_end_transaction(trans);
1502 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1503 btrfs_put_block_group(block_group);
1504 spin_lock(&fs_info->unused_bgs_lock);
1506 spin_unlock(&fs_info->unused_bgs_lock);
1510 btrfs_end_transaction(trans);
1511 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1512 btrfs_put_block_group(block_group);
1513 btrfs_discard_punt_unused_bgs_list(fs_info);
1516 void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1518 struct btrfs_fs_info *fs_info = bg->fs_info;
1520 spin_lock(&fs_info->unused_bgs_lock);
1521 if (list_empty(&bg->bg_list)) {
1522 btrfs_get_block_group(bg);
1523 trace_btrfs_add_unused_block_group(bg);
1524 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1526 spin_unlock(&fs_info->unused_bgs_lock);
1529 static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1530 struct btrfs_path *path)
1532 struct extent_map_tree *em_tree;
1533 struct extent_map *em;
1534 struct btrfs_block_group_item bg;
1535 struct extent_buffer *leaf;
1540 slot = path->slots[0];
1541 leaf = path->nodes[0];
1543 em_tree = &fs_info->mapping_tree;
1544 read_lock(&em_tree->lock);
1545 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1546 read_unlock(&em_tree->lock);
1549 "logical %llu len %llu found bg but no related chunk",
1550 key->objectid, key->offset);
1554 if (em->start != key->objectid || em->len != key->offset) {
1556 "block group %llu len %llu mismatch with chunk %llu len %llu",
1557 key->objectid, key->offset, em->start, em->len);
1562 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1564 flags = btrfs_stack_block_group_flags(&bg) &
1565 BTRFS_BLOCK_GROUP_TYPE_MASK;
1567 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1569 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1570 key->objectid, key->offset, flags,
1571 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1576 free_extent_map(em);
1580 static int find_first_block_group(struct btrfs_fs_info *fs_info,
1581 struct btrfs_path *path,
1582 struct btrfs_key *key)
1584 struct btrfs_root *root = fs_info->extent_root;
1586 struct btrfs_key found_key;
1587 struct extent_buffer *leaf;
1590 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1595 slot = path->slots[0];
1596 leaf = path->nodes[0];
1597 if (slot >= btrfs_header_nritems(leaf)) {
1598 ret = btrfs_next_leaf(root, path);
1605 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1607 if (found_key.objectid >= key->objectid &&
1608 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1609 ret = read_bg_from_eb(fs_info, &found_key, path);
1619 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1621 u64 extra_flags = chunk_to_extended(flags) &
1622 BTRFS_EXTENDED_PROFILE_MASK;
1624 write_seqlock(&fs_info->profiles_lock);
1625 if (flags & BTRFS_BLOCK_GROUP_DATA)
1626 fs_info->avail_data_alloc_bits |= extra_flags;
1627 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1628 fs_info->avail_metadata_alloc_bits |= extra_flags;
1629 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1630 fs_info->avail_system_alloc_bits |= extra_flags;
1631 write_sequnlock(&fs_info->profiles_lock);
1635 * btrfs_rmap_block - Map a physical disk address to a list of logical addresses
1636 * @chunk_start: logical address of block group
1637 * @physical: physical address to map to logical addresses
1638 * @logical: return array of logical addresses which map to @physical
1639 * @naddrs: length of @logical
1640 * @stripe_len: size of IO stripe for the given block group
1642 * Maps a particular @physical disk address to a list of @logical addresses.
1643 * Used primarily to exclude those portions of a block group that contain super
1647 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1648 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
1650 struct extent_map *em;
1651 struct map_lookup *map;
1654 u64 data_stripe_length;
1659 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1663 map = em->map_lookup;
1664 data_stripe_length = em->orig_block_len;
1665 io_stripe_size = map->stripe_len;
1667 /* For RAID5/6 adjust to a full IO stripe length */
1668 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
1669 io_stripe_size = map->stripe_len * nr_data_stripes(map);
1671 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
1677 for (i = 0; i < map->num_stripes; i++) {
1678 bool already_inserted = false;
1682 if (!in_range(physical, map->stripes[i].physical,
1683 data_stripe_length))
1686 stripe_nr = physical - map->stripes[i].physical;
1687 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
1689 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1690 stripe_nr = stripe_nr * map->num_stripes + i;
1691 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1692 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1693 stripe_nr = stripe_nr * map->num_stripes + i;
1696 * The remaining case would be for RAID56, multiply by
1697 * nr_data_stripes(). Alternatively, just use rmap_len below
1698 * instead of map->stripe_len
1701 bytenr = chunk_start + stripe_nr * io_stripe_size;
1703 /* Ensure we don't add duplicate addresses */
1704 for (j = 0; j < nr; j++) {
1705 if (buf[j] == bytenr) {
1706 already_inserted = true;
1711 if (!already_inserted)
1717 *stripe_len = io_stripe_size;
1719 free_extent_map(em);
1723 static int exclude_super_stripes(struct btrfs_block_group *cache)
1725 struct btrfs_fs_info *fs_info = cache->fs_info;
1731 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1732 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
1733 cache->bytes_super += stripe_len;
1734 ret = btrfs_add_excluded_extent(fs_info, cache->start,
1740 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1741 bytenr = btrfs_sb_offset(i);
1742 ret = btrfs_rmap_block(fs_info, cache->start,
1743 bytenr, &logical, &nr, &stripe_len);
1748 u64 len = min_t(u64, stripe_len,
1749 cache->start + cache->length - logical[nr]);
1751 cache->bytes_super += len;
1752 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
1765 static void link_block_group(struct btrfs_block_group *cache)
1767 struct btrfs_space_info *space_info = cache->space_info;
1768 int index = btrfs_bg_flags_to_raid_index(cache->flags);
1770 down_write(&space_info->groups_sem);
1771 list_add_tail(&cache->list, &space_info->block_groups[index]);
1772 up_write(&space_info->groups_sem);
1775 static struct btrfs_block_group *btrfs_create_block_group_cache(
1776 struct btrfs_fs_info *fs_info, u64 start)
1778 struct btrfs_block_group *cache;
1780 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1784 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1786 if (!cache->free_space_ctl) {
1791 cache->start = start;
1793 cache->fs_info = fs_info;
1794 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
1796 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1798 refcount_set(&cache->refs, 1);
1799 spin_lock_init(&cache->lock);
1800 init_rwsem(&cache->data_rwsem);
1801 INIT_LIST_HEAD(&cache->list);
1802 INIT_LIST_HEAD(&cache->cluster_list);
1803 INIT_LIST_HEAD(&cache->bg_list);
1804 INIT_LIST_HEAD(&cache->ro_list);
1805 INIT_LIST_HEAD(&cache->discard_list);
1806 INIT_LIST_HEAD(&cache->dirty_list);
1807 INIT_LIST_HEAD(&cache->io_list);
1808 btrfs_init_free_space_ctl(cache);
1809 atomic_set(&cache->frozen, 0);
1810 mutex_init(&cache->free_space_lock);
1811 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1817 * Iterate all chunks and verify that each of them has the corresponding block
1820 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1822 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1823 struct extent_map *em;
1824 struct btrfs_block_group *bg;
1829 read_lock(&map_tree->lock);
1831 * lookup_extent_mapping will return the first extent map
1832 * intersecting the range, so setting @len to 1 is enough to
1833 * get the first chunk.
1835 em = lookup_extent_mapping(map_tree, start, 1);
1836 read_unlock(&map_tree->lock);
1840 bg = btrfs_lookup_block_group(fs_info, em->start);
1843 "chunk start=%llu len=%llu doesn't have corresponding block group",
1844 em->start, em->len);
1846 free_extent_map(em);
1849 if (bg->start != em->start || bg->length != em->len ||
1850 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1851 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1853 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
1855 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
1856 bg->start, bg->length,
1857 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
1859 free_extent_map(em);
1860 btrfs_put_block_group(bg);
1863 start = em->start + em->len;
1864 free_extent_map(em);
1865 btrfs_put_block_group(bg);
1870 static void read_block_group_item(struct btrfs_block_group *cache,
1871 struct btrfs_path *path,
1872 const struct btrfs_key *key)
1874 struct extent_buffer *leaf = path->nodes[0];
1875 struct btrfs_block_group_item bgi;
1876 int slot = path->slots[0];
1878 cache->length = key->offset;
1880 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
1882 cache->used = btrfs_stack_block_group_used(&bgi);
1883 cache->flags = btrfs_stack_block_group_flags(&bgi);
1886 static int read_one_block_group(struct btrfs_fs_info *info,
1887 struct btrfs_path *path,
1888 const struct btrfs_key *key,
1891 struct btrfs_block_group *cache;
1892 struct btrfs_space_info *space_info;
1893 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
1896 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
1898 cache = btrfs_create_block_group_cache(info, key->objectid);
1902 read_block_group_item(cache, path, key);
1904 set_free_space_tree_thresholds(cache);
1908 * When we mount with old space cache, we need to
1909 * set BTRFS_DC_CLEAR and set dirty flag.
1911 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
1912 * truncate the old free space cache inode and
1914 * b) Setting 'dirty flag' makes sure that we flush
1915 * the new space cache info onto disk.
1917 if (btrfs_test_opt(info, SPACE_CACHE))
1918 cache->disk_cache_state = BTRFS_DC_CLEAR;
1920 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
1921 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
1923 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
1930 * We need to exclude the super stripes now so that the space info has
1931 * super bytes accounted for, otherwise we'll think we have more space
1932 * than we actually do.
1934 ret = exclude_super_stripes(cache);
1936 /* We may have excluded something, so call this just in case. */
1937 btrfs_free_excluded_extents(cache);
1942 * Check for two cases, either we are full, and therefore don't need
1943 * to bother with the caching work since we won't find any space, or we
1944 * are empty, and we can just add all the space in and be done with it.
1945 * This saves us _a_lot_ of time, particularly in the full case.
1947 if (cache->length == cache->used) {
1948 cache->last_byte_to_unpin = (u64)-1;
1949 cache->cached = BTRFS_CACHE_FINISHED;
1950 btrfs_free_excluded_extents(cache);
1951 } else if (cache->used == 0) {
1952 cache->last_byte_to_unpin = (u64)-1;
1953 cache->cached = BTRFS_CACHE_FINISHED;
1954 add_new_free_space(cache, cache->start,
1955 cache->start + cache->length);
1956 btrfs_free_excluded_extents(cache);
1959 ret = btrfs_add_block_group_cache(info, cache);
1961 btrfs_remove_free_space_cache(cache);
1964 trace_btrfs_add_block_group(info, cache, 0);
1965 btrfs_update_space_info(info, cache->flags, cache->length,
1966 cache->used, cache->bytes_super, &space_info);
1968 cache->space_info = space_info;
1970 link_block_group(cache);
1972 set_avail_alloc_bits(info, cache->flags);
1973 if (btrfs_chunk_readonly(info, cache->start)) {
1974 inc_block_group_ro(cache, 1);
1975 } else if (cache->used == 0) {
1976 ASSERT(list_empty(&cache->bg_list));
1977 if (btrfs_test_opt(info, DISCARD_ASYNC))
1978 btrfs_discard_queue_work(&info->discard_ctl, cache);
1980 btrfs_mark_bg_unused(cache);
1984 btrfs_put_block_group(cache);
1988 int btrfs_read_block_groups(struct btrfs_fs_info *info)
1990 struct btrfs_path *path;
1992 struct btrfs_block_group *cache;
1993 struct btrfs_space_info *space_info;
1994 struct btrfs_key key;
2000 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2001 path = btrfs_alloc_path();
2005 cache_gen = btrfs_super_cache_generation(info->super_copy);
2006 if (btrfs_test_opt(info, SPACE_CACHE) &&
2007 btrfs_super_generation(info->super_copy) != cache_gen)
2009 if (btrfs_test_opt(info, CLEAR_CACHE))
2013 ret = find_first_block_group(info, path, &key);
2019 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2020 ret = read_one_block_group(info, path, &key, need_clear);
2023 key.objectid += key.offset;
2025 btrfs_release_path(path);
2028 list_for_each_entry(space_info, &info->space_info, list) {
2031 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2032 if (list_empty(&space_info->block_groups[i]))
2034 cache = list_first_entry(&space_info->block_groups[i],
2035 struct btrfs_block_group,
2037 btrfs_sysfs_add_block_group_type(cache);
2040 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2041 (BTRFS_BLOCK_GROUP_RAID10 |
2042 BTRFS_BLOCK_GROUP_RAID1_MASK |
2043 BTRFS_BLOCK_GROUP_RAID56_MASK |
2044 BTRFS_BLOCK_GROUP_DUP)))
2047 * Avoid allocating from un-mirrored block group if there are
2048 * mirrored block groups.
2050 list_for_each_entry(cache,
2051 &space_info->block_groups[BTRFS_RAID_RAID0],
2053 inc_block_group_ro(cache, 1);
2054 list_for_each_entry(cache,
2055 &space_info->block_groups[BTRFS_RAID_SINGLE],
2057 inc_block_group_ro(cache, 1);
2060 btrfs_init_global_block_rsv(info);
2061 ret = check_chunk_block_group_mappings(info);
2063 btrfs_free_path(path);
2067 static int insert_block_group_item(struct btrfs_trans_handle *trans,
2068 struct btrfs_block_group *block_group)
2070 struct btrfs_fs_info *fs_info = trans->fs_info;
2071 struct btrfs_block_group_item bgi;
2072 struct btrfs_root *root;
2073 struct btrfs_key key;
2075 spin_lock(&block_group->lock);
2076 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2077 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2078 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2079 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2080 key.objectid = block_group->start;
2081 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2082 key.offset = block_group->length;
2083 spin_unlock(&block_group->lock);
2085 root = fs_info->extent_root;
2086 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2089 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2091 struct btrfs_fs_info *fs_info = trans->fs_info;
2092 struct btrfs_block_group *block_group;
2095 if (!trans->can_flush_pending_bgs)
2098 while (!list_empty(&trans->new_bgs)) {
2101 block_group = list_first_entry(&trans->new_bgs,
2102 struct btrfs_block_group,
2107 index = btrfs_bg_flags_to_raid_index(block_group->flags);
2109 ret = insert_block_group_item(trans, block_group);
2111 btrfs_abort_transaction(trans, ret);
2112 ret = btrfs_finish_chunk_alloc(trans, block_group->start,
2113 block_group->length);
2115 btrfs_abort_transaction(trans, ret);
2116 add_block_group_free_space(trans, block_group);
2119 * If we restriped during balance, we may have added a new raid
2120 * type, so now add the sysfs entries when it is safe to do so.
2121 * We don't have to worry about locking here as it's handled in
2122 * btrfs_sysfs_add_block_group_type.
2124 if (block_group->space_info->block_group_kobjs[index] == NULL)
2125 btrfs_sysfs_add_block_group_type(block_group);
2127 /* Already aborted the transaction if it failed. */
2129 btrfs_delayed_refs_rsv_release(fs_info, 1);
2130 list_del_init(&block_group->bg_list);
2132 btrfs_trans_release_chunk_metadata(trans);
2135 int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
2136 u64 type, u64 chunk_offset, u64 size)
2138 struct btrfs_fs_info *fs_info = trans->fs_info;
2139 struct btrfs_block_group *cache;
2142 btrfs_set_log_full_commit(trans);
2144 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
2148 cache->length = size;
2149 set_free_space_tree_thresholds(cache);
2150 cache->used = bytes_used;
2151 cache->flags = type;
2152 cache->last_byte_to_unpin = (u64)-1;
2153 cache->cached = BTRFS_CACHE_FINISHED;
2154 cache->needs_free_space = 1;
2155 ret = exclude_super_stripes(cache);
2157 /* We may have excluded something, so call this just in case */
2158 btrfs_free_excluded_extents(cache);
2159 btrfs_put_block_group(cache);
2163 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2165 btrfs_free_excluded_extents(cache);
2167 #ifdef CONFIG_BTRFS_DEBUG
2168 if (btrfs_should_fragment_free_space(cache)) {
2169 u64 new_bytes_used = size - bytes_used;
2171 bytes_used += new_bytes_used >> 1;
2172 fragment_free_space(cache);
2176 * Ensure the corresponding space_info object is created and
2177 * assigned to our block group. We want our bg to be added to the rbtree
2178 * with its ->space_info set.
2180 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2181 ASSERT(cache->space_info);
2183 ret = btrfs_add_block_group_cache(fs_info, cache);
2185 btrfs_remove_free_space_cache(cache);
2186 btrfs_put_block_group(cache);
2191 * Now that our block group has its ->space_info set and is inserted in
2192 * the rbtree, update the space info's counters.
2194 trace_btrfs_add_block_group(fs_info, cache, 1);
2195 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
2196 cache->bytes_super, &cache->space_info);
2197 btrfs_update_global_block_rsv(fs_info);
2199 link_block_group(cache);
2201 list_add_tail(&cache->bg_list, &trans->new_bgs);
2202 trans->delayed_ref_updates++;
2203 btrfs_update_delayed_refs_rsv(trans);
2205 set_avail_alloc_bits(fs_info, type);
2210 * Mark one block group RO, can be called several times for the same block
2213 * @cache: the destination block group
2214 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2215 * ensure we still have some free space after marking this
2218 int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2219 bool do_chunk_alloc)
2221 struct btrfs_fs_info *fs_info = cache->fs_info;
2222 struct btrfs_trans_handle *trans;
2227 trans = btrfs_join_transaction(fs_info->extent_root);
2229 return PTR_ERR(trans);
2232 * we're not allowed to set block groups readonly after the dirty
2233 * block groups cache has started writing. If it already started,
2234 * back off and let this transaction commit
2236 mutex_lock(&fs_info->ro_block_group_mutex);
2237 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2238 u64 transid = trans->transid;
2240 mutex_unlock(&fs_info->ro_block_group_mutex);
2241 btrfs_end_transaction(trans);
2243 ret = btrfs_wait_for_commit(fs_info, transid);
2249 if (do_chunk_alloc) {
2251 * If we are changing raid levels, try to allocate a
2252 * corresponding block group with the new raid level.
2254 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2255 if (alloc_flags != cache->flags) {
2256 ret = btrfs_chunk_alloc(trans, alloc_flags,
2259 * ENOSPC is allowed here, we may have enough space
2260 * already allocated at the new raid level to carry on
2269 ret = inc_block_group_ro(cache, 0);
2270 if (!do_chunk_alloc)
2274 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2275 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2278 ret = inc_block_group_ro(cache, 0);
2280 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2281 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2282 mutex_lock(&fs_info->chunk_mutex);
2283 check_system_chunk(trans, alloc_flags);
2284 mutex_unlock(&fs_info->chunk_mutex);
2287 mutex_unlock(&fs_info->ro_block_group_mutex);
2289 btrfs_end_transaction(trans);
2293 void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
2295 struct btrfs_space_info *sinfo = cache->space_info;
2300 spin_lock(&sinfo->lock);
2301 spin_lock(&cache->lock);
2303 num_bytes = cache->length - cache->reserved -
2304 cache->pinned - cache->bytes_super - cache->used;
2305 sinfo->bytes_readonly -= num_bytes;
2306 list_del_init(&cache->ro_list);
2308 spin_unlock(&cache->lock);
2309 spin_unlock(&sinfo->lock);
2312 static int update_block_group_item(struct btrfs_trans_handle *trans,
2313 struct btrfs_path *path,
2314 struct btrfs_block_group *cache)
2316 struct btrfs_fs_info *fs_info = trans->fs_info;
2318 struct btrfs_root *root = fs_info->extent_root;
2320 struct extent_buffer *leaf;
2321 struct btrfs_block_group_item bgi;
2322 struct btrfs_key key;
2324 key.objectid = cache->start;
2325 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2326 key.offset = cache->length;
2328 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2335 leaf = path->nodes[0];
2336 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2337 btrfs_set_stack_block_group_used(&bgi, cache->used);
2338 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2339 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2340 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2341 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
2342 btrfs_mark_buffer_dirty(leaf);
2344 btrfs_release_path(path);
2349 static int cache_save_setup(struct btrfs_block_group *block_group,
2350 struct btrfs_trans_handle *trans,
2351 struct btrfs_path *path)
2353 struct btrfs_fs_info *fs_info = block_group->fs_info;
2354 struct btrfs_root *root = fs_info->tree_root;
2355 struct inode *inode = NULL;
2356 struct extent_changeset *data_reserved = NULL;
2358 int dcs = BTRFS_DC_ERROR;
2364 * If this block group is smaller than 100 megs don't bother caching the
2367 if (block_group->length < (100 * SZ_1M)) {
2368 spin_lock(&block_group->lock);
2369 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2370 spin_unlock(&block_group->lock);
2374 if (TRANS_ABORTED(trans))
2377 inode = lookup_free_space_inode(block_group, path);
2378 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2379 ret = PTR_ERR(inode);
2380 btrfs_release_path(path);
2384 if (IS_ERR(inode)) {
2388 if (block_group->ro)
2391 ret = create_free_space_inode(trans, block_group, path);
2398 * We want to set the generation to 0, that way if anything goes wrong
2399 * from here on out we know not to trust this cache when we load up next
2402 BTRFS_I(inode)->generation = 0;
2403 ret = btrfs_update_inode(trans, root, inode);
2406 * So theoretically we could recover from this, simply set the
2407 * super cache generation to 0 so we know to invalidate the
2408 * cache, but then we'd have to keep track of the block groups
2409 * that fail this way so we know we _have_ to reset this cache
2410 * before the next commit or risk reading stale cache. So to
2411 * limit our exposure to horrible edge cases lets just abort the
2412 * transaction, this only happens in really bad situations
2415 btrfs_abort_transaction(trans, ret);
2420 /* We've already setup this transaction, go ahead and exit */
2421 if (block_group->cache_generation == trans->transid &&
2422 i_size_read(inode)) {
2423 dcs = BTRFS_DC_SETUP;
2427 if (i_size_read(inode) > 0) {
2428 ret = btrfs_check_trunc_cache_free_space(fs_info,
2429 &fs_info->global_block_rsv);
2433 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2438 spin_lock(&block_group->lock);
2439 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2440 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2442 * don't bother trying to write stuff out _if_
2443 * a) we're not cached,
2444 * b) we're with nospace_cache mount option,
2445 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2447 dcs = BTRFS_DC_WRITTEN;
2448 spin_unlock(&block_group->lock);
2451 spin_unlock(&block_group->lock);
2454 * We hit an ENOSPC when setting up the cache in this transaction, just
2455 * skip doing the setup, we've already cleared the cache so we're safe.
2457 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2463 * Try to preallocate enough space based on how big the block group is.
2464 * Keep in mind this has to include any pinned space which could end up
2465 * taking up quite a bit since it's not folded into the other space
2468 num_pages = div_u64(block_group->length, SZ_256M);
2473 num_pages *= PAGE_SIZE;
2475 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
2480 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2481 num_pages, num_pages,
2484 * Our cache requires contiguous chunks so that we don't modify a bunch
2485 * of metadata or split extents when writing the cache out, which means
2486 * we can enospc if we are heavily fragmented in addition to just normal
2487 * out of space conditions. So if we hit this just skip setting up any
2488 * other block groups for this transaction, maybe we'll unpin enough
2489 * space the next time around.
2492 dcs = BTRFS_DC_SETUP;
2493 else if (ret == -ENOSPC)
2494 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2499 btrfs_release_path(path);
2501 spin_lock(&block_group->lock);
2502 if (!ret && dcs == BTRFS_DC_SETUP)
2503 block_group->cache_generation = trans->transid;
2504 block_group->disk_cache_state = dcs;
2505 spin_unlock(&block_group->lock);
2507 extent_changeset_free(data_reserved);
2511 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2513 struct btrfs_fs_info *fs_info = trans->fs_info;
2514 struct btrfs_block_group *cache, *tmp;
2515 struct btrfs_transaction *cur_trans = trans->transaction;
2516 struct btrfs_path *path;
2518 if (list_empty(&cur_trans->dirty_bgs) ||
2519 !btrfs_test_opt(fs_info, SPACE_CACHE))
2522 path = btrfs_alloc_path();
2526 /* Could add new block groups, use _safe just in case */
2527 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2529 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2530 cache_save_setup(cache, trans, path);
2533 btrfs_free_path(path);
2538 * Transaction commit does final block group cache writeback during a critical
2539 * section where nothing is allowed to change the FS. This is required in
2540 * order for the cache to actually match the block group, but can introduce a
2541 * lot of latency into the commit.
2543 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2544 * There's a chance we'll have to redo some of it if the block group changes
2545 * again during the commit, but it greatly reduces the commit latency by
2546 * getting rid of the easy block groups while we're still allowing others to
2549 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2551 struct btrfs_fs_info *fs_info = trans->fs_info;
2552 struct btrfs_block_group *cache;
2553 struct btrfs_transaction *cur_trans = trans->transaction;
2556 struct btrfs_path *path = NULL;
2558 struct list_head *io = &cur_trans->io_bgs;
2559 int num_started = 0;
2562 spin_lock(&cur_trans->dirty_bgs_lock);
2563 if (list_empty(&cur_trans->dirty_bgs)) {
2564 spin_unlock(&cur_trans->dirty_bgs_lock);
2567 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2568 spin_unlock(&cur_trans->dirty_bgs_lock);
2571 /* Make sure all the block groups on our dirty list actually exist */
2572 btrfs_create_pending_block_groups(trans);
2575 path = btrfs_alloc_path();
2581 * cache_write_mutex is here only to save us from balance or automatic
2582 * removal of empty block groups deleting this block group while we are
2583 * writing out the cache
2585 mutex_lock(&trans->transaction->cache_write_mutex);
2586 while (!list_empty(&dirty)) {
2587 bool drop_reserve = true;
2589 cache = list_first_entry(&dirty, struct btrfs_block_group,
2592 * This can happen if something re-dirties a block group that
2593 * is already under IO. Just wait for it to finish and then do
2596 if (!list_empty(&cache->io_list)) {
2597 list_del_init(&cache->io_list);
2598 btrfs_wait_cache_io(trans, cache, path);
2599 btrfs_put_block_group(cache);
2604 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
2605 * it should update the cache_state. Don't delete until after
2608 * Since we're not running in the commit critical section
2609 * we need the dirty_bgs_lock to protect from update_block_group
2611 spin_lock(&cur_trans->dirty_bgs_lock);
2612 list_del_init(&cache->dirty_list);
2613 spin_unlock(&cur_trans->dirty_bgs_lock);
2617 cache_save_setup(cache, trans, path);
2619 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
2620 cache->io_ctl.inode = NULL;
2621 ret = btrfs_write_out_cache(trans, cache, path);
2622 if (ret == 0 && cache->io_ctl.inode) {
2627 * The cache_write_mutex is protecting the
2628 * io_list, also refer to the definition of
2629 * btrfs_transaction::io_bgs for more details
2631 list_add_tail(&cache->io_list, io);
2634 * If we failed to write the cache, the
2635 * generation will be bad and life goes on
2641 ret = update_block_group_item(trans, path, cache);
2643 * Our block group might still be attached to the list
2644 * of new block groups in the transaction handle of some
2645 * other task (struct btrfs_trans_handle->new_bgs). This
2646 * means its block group item isn't yet in the extent
2647 * tree. If this happens ignore the error, as we will
2648 * try again later in the critical section of the
2649 * transaction commit.
2651 if (ret == -ENOENT) {
2653 spin_lock(&cur_trans->dirty_bgs_lock);
2654 if (list_empty(&cache->dirty_list)) {
2655 list_add_tail(&cache->dirty_list,
2656 &cur_trans->dirty_bgs);
2657 btrfs_get_block_group(cache);
2658 drop_reserve = false;
2660 spin_unlock(&cur_trans->dirty_bgs_lock);
2662 btrfs_abort_transaction(trans, ret);
2666 /* If it's not on the io list, we need to put the block group */
2668 btrfs_put_block_group(cache);
2670 btrfs_delayed_refs_rsv_release(fs_info, 1);
2676 * Avoid blocking other tasks for too long. It might even save
2677 * us from writing caches for block groups that are going to be
2680 mutex_unlock(&trans->transaction->cache_write_mutex);
2681 mutex_lock(&trans->transaction->cache_write_mutex);
2683 mutex_unlock(&trans->transaction->cache_write_mutex);
2686 * Go through delayed refs for all the stuff we've just kicked off
2687 * and then loop back (just once)
2689 ret = btrfs_run_delayed_refs(trans, 0);
2690 if (!ret && loops == 0) {
2692 spin_lock(&cur_trans->dirty_bgs_lock);
2693 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2695 * dirty_bgs_lock protects us from concurrent block group
2696 * deletes too (not just cache_write_mutex).
2698 if (!list_empty(&dirty)) {
2699 spin_unlock(&cur_trans->dirty_bgs_lock);
2702 spin_unlock(&cur_trans->dirty_bgs_lock);
2703 } else if (ret < 0) {
2704 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
2707 btrfs_free_path(path);
2711 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
2713 struct btrfs_fs_info *fs_info = trans->fs_info;
2714 struct btrfs_block_group *cache;
2715 struct btrfs_transaction *cur_trans = trans->transaction;
2718 struct btrfs_path *path;
2719 struct list_head *io = &cur_trans->io_bgs;
2720 int num_started = 0;
2722 path = btrfs_alloc_path();
2727 * Even though we are in the critical section of the transaction commit,
2728 * we can still have concurrent tasks adding elements to this
2729 * transaction's list of dirty block groups. These tasks correspond to
2730 * endio free space workers started when writeback finishes for a
2731 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
2732 * allocate new block groups as a result of COWing nodes of the root
2733 * tree when updating the free space inode. The writeback for the space
2734 * caches is triggered by an earlier call to
2735 * btrfs_start_dirty_block_groups() and iterations of the following
2737 * Also we want to do the cache_save_setup first and then run the
2738 * delayed refs to make sure we have the best chance at doing this all
2741 spin_lock(&cur_trans->dirty_bgs_lock);
2742 while (!list_empty(&cur_trans->dirty_bgs)) {
2743 cache = list_first_entry(&cur_trans->dirty_bgs,
2744 struct btrfs_block_group,
2748 * This can happen if cache_save_setup re-dirties a block group
2749 * that is already under IO. Just wait for it to finish and
2750 * then do it all again
2752 if (!list_empty(&cache->io_list)) {
2753 spin_unlock(&cur_trans->dirty_bgs_lock);
2754 list_del_init(&cache->io_list);
2755 btrfs_wait_cache_io(trans, cache, path);
2756 btrfs_put_block_group(cache);
2757 spin_lock(&cur_trans->dirty_bgs_lock);
2761 * Don't remove from the dirty list until after we've waited on
2764 list_del_init(&cache->dirty_list);
2765 spin_unlock(&cur_trans->dirty_bgs_lock);
2768 cache_save_setup(cache, trans, path);
2771 ret = btrfs_run_delayed_refs(trans,
2772 (unsigned long) -1);
2774 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
2775 cache->io_ctl.inode = NULL;
2776 ret = btrfs_write_out_cache(trans, cache, path);
2777 if (ret == 0 && cache->io_ctl.inode) {
2780 list_add_tail(&cache->io_list, io);
2783 * If we failed to write the cache, the
2784 * generation will be bad and life goes on
2790 ret = update_block_group_item(trans, path, cache);
2792 * One of the free space endio workers might have
2793 * created a new block group while updating a free space
2794 * cache's inode (at inode.c:btrfs_finish_ordered_io())
2795 * and hasn't released its transaction handle yet, in
2796 * which case the new block group is still attached to
2797 * its transaction handle and its creation has not
2798 * finished yet (no block group item in the extent tree
2799 * yet, etc). If this is the case, wait for all free
2800 * space endio workers to finish and retry. This is a
2801 * very rare case so no need for a more efficient and
2804 if (ret == -ENOENT) {
2805 wait_event(cur_trans->writer_wait,
2806 atomic_read(&cur_trans->num_writers) == 1);
2807 ret = update_block_group_item(trans, path, cache);
2810 btrfs_abort_transaction(trans, ret);
2813 /* If its not on the io list, we need to put the block group */
2815 btrfs_put_block_group(cache);
2816 btrfs_delayed_refs_rsv_release(fs_info, 1);
2817 spin_lock(&cur_trans->dirty_bgs_lock);
2819 spin_unlock(&cur_trans->dirty_bgs_lock);
2822 * Refer to the definition of io_bgs member for details why it's safe
2823 * to use it without any locking
2825 while (!list_empty(io)) {
2826 cache = list_first_entry(io, struct btrfs_block_group,
2828 list_del_init(&cache->io_list);
2829 btrfs_wait_cache_io(trans, cache, path);
2830 btrfs_put_block_group(cache);
2833 btrfs_free_path(path);
2837 int btrfs_update_block_group(struct btrfs_trans_handle *trans,
2838 u64 bytenr, u64 num_bytes, int alloc)
2840 struct btrfs_fs_info *info = trans->fs_info;
2841 struct btrfs_block_group *cache = NULL;
2842 u64 total = num_bytes;
2848 /* Block accounting for super block */
2849 spin_lock(&info->delalloc_root_lock);
2850 old_val = btrfs_super_bytes_used(info->super_copy);
2852 old_val += num_bytes;
2854 old_val -= num_bytes;
2855 btrfs_set_super_bytes_used(info->super_copy, old_val);
2856 spin_unlock(&info->delalloc_root_lock);
2859 cache = btrfs_lookup_block_group(info, bytenr);
2864 factor = btrfs_bg_type_to_factor(cache->flags);
2867 * If this block group has free space cache written out, we
2868 * need to make sure to load it if we are removing space. This
2869 * is because we need the unpinning stage to actually add the
2870 * space back to the block group, otherwise we will leak space.
2872 if (!alloc && !btrfs_block_group_done(cache))
2873 btrfs_cache_block_group(cache, 1);
2875 byte_in_group = bytenr - cache->start;
2876 WARN_ON(byte_in_group > cache->length);
2878 spin_lock(&cache->space_info->lock);
2879 spin_lock(&cache->lock);
2881 if (btrfs_test_opt(info, SPACE_CACHE) &&
2882 cache->disk_cache_state < BTRFS_DC_CLEAR)
2883 cache->disk_cache_state = BTRFS_DC_CLEAR;
2885 old_val = cache->used;
2886 num_bytes = min(total, cache->length - byte_in_group);
2888 old_val += num_bytes;
2889 cache->used = old_val;
2890 cache->reserved -= num_bytes;
2891 cache->space_info->bytes_reserved -= num_bytes;
2892 cache->space_info->bytes_used += num_bytes;
2893 cache->space_info->disk_used += num_bytes * factor;
2894 spin_unlock(&cache->lock);
2895 spin_unlock(&cache->space_info->lock);
2897 old_val -= num_bytes;
2898 cache->used = old_val;
2899 cache->pinned += num_bytes;
2900 btrfs_space_info_update_bytes_pinned(info,
2901 cache->space_info, num_bytes);
2902 cache->space_info->bytes_used -= num_bytes;
2903 cache->space_info->disk_used -= num_bytes * factor;
2904 spin_unlock(&cache->lock);
2905 spin_unlock(&cache->space_info->lock);
2907 percpu_counter_add_batch(
2908 &cache->space_info->total_bytes_pinned,
2910 BTRFS_TOTAL_BYTES_PINNED_BATCH);
2911 set_extent_dirty(&trans->transaction->pinned_extents,
2912 bytenr, bytenr + num_bytes - 1,
2913 GFP_NOFS | __GFP_NOFAIL);
2916 spin_lock(&trans->transaction->dirty_bgs_lock);
2917 if (list_empty(&cache->dirty_list)) {
2918 list_add_tail(&cache->dirty_list,
2919 &trans->transaction->dirty_bgs);
2920 trans->delayed_ref_updates++;
2921 btrfs_get_block_group(cache);
2923 spin_unlock(&trans->transaction->dirty_bgs_lock);
2926 * No longer have used bytes in this block group, queue it for
2927 * deletion. We do this after adding the block group to the
2928 * dirty list to avoid races between cleaner kthread and space
2931 if (!alloc && old_val == 0) {
2932 if (!btrfs_test_opt(info, DISCARD_ASYNC))
2933 btrfs_mark_bg_unused(cache);
2936 btrfs_put_block_group(cache);
2938 bytenr += num_bytes;
2941 /* Modified block groups are accounted for in the delayed_refs_rsv. */
2942 btrfs_update_delayed_refs_rsv(trans);
2947 * btrfs_add_reserved_bytes - update the block_group and space info counters
2948 * @cache: The cache we are manipulating
2949 * @ram_bytes: The number of bytes of file content, and will be same to
2950 * @num_bytes except for the compress path.
2951 * @num_bytes: The number of bytes in question
2952 * @delalloc: The blocks are allocated for the delalloc write
2954 * This is called by the allocator when it reserves space. If this is a
2955 * reservation and the block group has become read only we cannot make the
2956 * reservation and return -EAGAIN, otherwise this function always succeeds.
2958 int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
2959 u64 ram_bytes, u64 num_bytes, int delalloc)
2961 struct btrfs_space_info *space_info = cache->space_info;
2964 spin_lock(&space_info->lock);
2965 spin_lock(&cache->lock);
2969 cache->reserved += num_bytes;
2970 space_info->bytes_reserved += num_bytes;
2971 trace_btrfs_space_reservation(cache->fs_info, "space_info",
2972 space_info->flags, num_bytes, 1);
2973 btrfs_space_info_update_bytes_may_use(cache->fs_info,
2974 space_info, -ram_bytes);
2976 cache->delalloc_bytes += num_bytes;
2979 * Compression can use less space than we reserved, so wake
2980 * tickets if that happens
2982 if (num_bytes < ram_bytes)
2983 btrfs_try_granting_tickets(cache->fs_info, space_info);
2985 spin_unlock(&cache->lock);
2986 spin_unlock(&space_info->lock);
2991 * btrfs_free_reserved_bytes - update the block_group and space info counters
2992 * @cache: The cache we are manipulating
2993 * @num_bytes: The number of bytes in question
2994 * @delalloc: The blocks are allocated for the delalloc write
2996 * This is called by somebody who is freeing space that was never actually used
2997 * on disk. For example if you reserve some space for a new leaf in transaction
2998 * A and before transaction A commits you free that leaf, you call this with
2999 * reserve set to 0 in order to clear the reservation.
3001 void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3002 u64 num_bytes, int delalloc)
3004 struct btrfs_space_info *space_info = cache->space_info;
3006 spin_lock(&space_info->lock);
3007 spin_lock(&cache->lock);
3009 space_info->bytes_readonly += num_bytes;
3010 cache->reserved -= num_bytes;
3011 space_info->bytes_reserved -= num_bytes;
3012 space_info->max_extent_size = 0;
3015 cache->delalloc_bytes -= num_bytes;
3016 spin_unlock(&cache->lock);
3018 btrfs_try_granting_tickets(cache->fs_info, space_info);
3019 spin_unlock(&space_info->lock);
3022 static void force_metadata_allocation(struct btrfs_fs_info *info)
3024 struct list_head *head = &info->space_info;
3025 struct btrfs_space_info *found;
3027 list_for_each_entry(found, head, list) {
3028 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3029 found->force_alloc = CHUNK_ALLOC_FORCE;
3033 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3034 struct btrfs_space_info *sinfo, int force)
3036 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3039 if (force == CHUNK_ALLOC_FORCE)
3043 * in limited mode, we want to have some free space up to
3044 * about 1% of the FS size.
3046 if (force == CHUNK_ALLOC_LIMITED) {
3047 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3048 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3050 if (sinfo->total_bytes - bytes_used < thresh)
3054 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3059 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3061 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3063 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3067 * If force is CHUNK_ALLOC_FORCE:
3068 * - return 1 if it successfully allocates a chunk,
3069 * - return errors including -ENOSPC otherwise.
3070 * If force is NOT CHUNK_ALLOC_FORCE:
3071 * - return 0 if it doesn't need to allocate a new chunk,
3072 * - return 1 if it successfully allocates a chunk,
3073 * - return errors including -ENOSPC otherwise.
3075 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3076 enum btrfs_chunk_alloc_enum force)
3078 struct btrfs_fs_info *fs_info = trans->fs_info;
3079 struct btrfs_space_info *space_info;
3080 bool wait_for_alloc = false;
3081 bool should_alloc = false;
3084 /* Don't re-enter if we're already allocating a chunk */
3085 if (trans->allocating_chunk)
3088 space_info = btrfs_find_space_info(fs_info, flags);
3092 spin_lock(&space_info->lock);
3093 if (force < space_info->force_alloc)
3094 force = space_info->force_alloc;
3095 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3096 if (space_info->full) {
3097 /* No more free physical space */
3102 spin_unlock(&space_info->lock);
3104 } else if (!should_alloc) {
3105 spin_unlock(&space_info->lock);
3107 } else if (space_info->chunk_alloc) {
3109 * Someone is already allocating, so we need to block
3110 * until this someone is finished and then loop to
3111 * recheck if we should continue with our allocation
3114 wait_for_alloc = true;
3115 spin_unlock(&space_info->lock);
3116 mutex_lock(&fs_info->chunk_mutex);
3117 mutex_unlock(&fs_info->chunk_mutex);
3119 /* Proceed with allocation */
3120 space_info->chunk_alloc = 1;
3121 wait_for_alloc = false;
3122 spin_unlock(&space_info->lock);
3126 } while (wait_for_alloc);
3128 mutex_lock(&fs_info->chunk_mutex);
3129 trans->allocating_chunk = true;
3132 * If we have mixed data/metadata chunks we want to make sure we keep
3133 * allocating mixed chunks instead of individual chunks.
3135 if (btrfs_mixed_space_info(space_info))
3136 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3139 * if we're doing a data chunk, go ahead and make sure that
3140 * we keep a reasonable number of metadata chunks allocated in the
3143 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3144 fs_info->data_chunk_allocations++;
3145 if (!(fs_info->data_chunk_allocations %
3146 fs_info->metadata_ratio))
3147 force_metadata_allocation(fs_info);
3151 * Check if we have enough space in SYSTEM chunk because we may need
3152 * to update devices.
3154 check_system_chunk(trans, flags);
3156 ret = btrfs_alloc_chunk(trans, flags);
3157 trans->allocating_chunk = false;
3159 spin_lock(&space_info->lock);
3162 space_info->full = 1;
3167 space_info->max_extent_size = 0;
3170 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3172 space_info->chunk_alloc = 0;
3173 spin_unlock(&space_info->lock);
3174 mutex_unlock(&fs_info->chunk_mutex);
3176 * When we allocate a new chunk we reserve space in the chunk block
3177 * reserve to make sure we can COW nodes/leafs in the chunk tree or
3178 * add new nodes/leafs to it if we end up needing to do it when
3179 * inserting the chunk item and updating device items as part of the
3180 * second phase of chunk allocation, performed by
3181 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
3182 * large number of new block groups to create in our transaction
3183 * handle's new_bgs list to avoid exhausting the chunk block reserve
3184 * in extreme cases - like having a single transaction create many new
3185 * block groups when starting to write out the free space caches of all
3186 * the block groups that were made dirty during the lifetime of the
3189 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
3190 btrfs_create_pending_block_groups(trans);
3195 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3199 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3201 num_dev = fs_info->fs_devices->rw_devices;
3207 * Reserve space in the system space for allocating or removing a chunk
3209 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3211 struct btrfs_fs_info *fs_info = trans->fs_info;
3212 struct btrfs_space_info *info;
3219 * Needed because we can end up allocating a system chunk and for an
3220 * atomic and race free space reservation in the chunk block reserve.
3222 lockdep_assert_held(&fs_info->chunk_mutex);
3224 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3225 spin_lock(&info->lock);
3226 left = info->total_bytes - btrfs_space_info_used(info, true);
3227 spin_unlock(&info->lock);
3229 num_devs = get_profile_num_devs(fs_info, type);
3231 /* num_devs device items to update and 1 chunk item to add or remove */
3232 thresh = btrfs_calc_metadata_size(fs_info, num_devs) +
3233 btrfs_calc_insert_metadata_size(fs_info, 1);
3235 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3236 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3237 left, thresh, type);
3238 btrfs_dump_space_info(fs_info, info, 0, 0);
3241 if (left < thresh) {
3242 u64 flags = btrfs_system_alloc_profile(fs_info);
3245 * Ignore failure to create system chunk. We might end up not
3246 * needing it, as we might not need to COW all nodes/leafs from
3247 * the paths we visit in the chunk tree (they were already COWed
3248 * or created in the current transaction for example).
3250 ret = btrfs_alloc_chunk(trans, flags);
3254 ret = btrfs_block_rsv_add(fs_info->chunk_root,
3255 &fs_info->chunk_block_rsv,
3256 thresh, BTRFS_RESERVE_NO_FLUSH);
3258 trans->chunk_bytes_reserved += thresh;
3262 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3264 struct btrfs_block_group *block_group;
3268 struct inode *inode;
3270 block_group = btrfs_lookup_first_block_group(info, last);
3271 while (block_group) {
3272 btrfs_wait_block_group_cache_done(block_group);
3273 spin_lock(&block_group->lock);
3274 if (block_group->iref)
3276 spin_unlock(&block_group->lock);
3277 block_group = btrfs_next_block_group(block_group);
3286 inode = block_group->inode;
3287 block_group->iref = 0;
3288 block_group->inode = NULL;
3289 spin_unlock(&block_group->lock);
3290 ASSERT(block_group->io_ctl.inode == NULL);
3292 last = block_group->start + block_group->length;
3293 btrfs_put_block_group(block_group);
3298 * Must be called only after stopping all workers, since we could have block
3299 * group caching kthreads running, and therefore they could race with us if we
3300 * freed the block groups before stopping them.
3302 int btrfs_free_block_groups(struct btrfs_fs_info *info)
3304 struct btrfs_block_group *block_group;
3305 struct btrfs_space_info *space_info;
3306 struct btrfs_caching_control *caching_ctl;
3309 down_write(&info->commit_root_sem);
3310 while (!list_empty(&info->caching_block_groups)) {
3311 caching_ctl = list_entry(info->caching_block_groups.next,
3312 struct btrfs_caching_control, list);
3313 list_del(&caching_ctl->list);
3314 btrfs_put_caching_control(caching_ctl);
3316 up_write(&info->commit_root_sem);
3318 spin_lock(&info->unused_bgs_lock);
3319 while (!list_empty(&info->unused_bgs)) {
3320 block_group = list_first_entry(&info->unused_bgs,
3321 struct btrfs_block_group,
3323 list_del_init(&block_group->bg_list);
3324 btrfs_put_block_group(block_group);
3326 spin_unlock(&info->unused_bgs_lock);
3328 spin_lock(&info->block_group_cache_lock);
3329 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
3330 block_group = rb_entry(n, struct btrfs_block_group,
3332 rb_erase(&block_group->cache_node,
3333 &info->block_group_cache_tree);
3334 RB_CLEAR_NODE(&block_group->cache_node);
3335 spin_unlock(&info->block_group_cache_lock);
3337 down_write(&block_group->space_info->groups_sem);
3338 list_del(&block_group->list);
3339 up_write(&block_group->space_info->groups_sem);
3342 * We haven't cached this block group, which means we could
3343 * possibly have excluded extents on this block group.
3345 if (block_group->cached == BTRFS_CACHE_NO ||
3346 block_group->cached == BTRFS_CACHE_ERROR)
3347 btrfs_free_excluded_extents(block_group);
3349 btrfs_remove_free_space_cache(block_group);
3350 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
3351 ASSERT(list_empty(&block_group->dirty_list));
3352 ASSERT(list_empty(&block_group->io_list));
3353 ASSERT(list_empty(&block_group->bg_list));
3354 ASSERT(refcount_read(&block_group->refs) == 1);
3355 btrfs_put_block_group(block_group);
3357 spin_lock(&info->block_group_cache_lock);
3359 spin_unlock(&info->block_group_cache_lock);
3361 btrfs_release_global_block_rsv(info);
3363 while (!list_empty(&info->space_info)) {
3364 space_info = list_entry(info->space_info.next,
3365 struct btrfs_space_info,
3369 * Do not hide this behind enospc_debug, this is actually
3370 * important and indicates a real bug if this happens.
3372 if (WARN_ON(space_info->bytes_pinned > 0 ||
3373 space_info->bytes_reserved > 0 ||
3374 space_info->bytes_may_use > 0))
3375 btrfs_dump_space_info(info, space_info, 0, 0);
3376 WARN_ON(space_info->reclaim_size > 0);
3377 list_del(&space_info->list);
3378 btrfs_sysfs_remove_space_info(space_info);
3383 void btrfs_freeze_block_group(struct btrfs_block_group *cache)
3385 atomic_inc(&cache->frozen);
3388 void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
3390 struct btrfs_fs_info *fs_info = block_group->fs_info;
3391 struct extent_map_tree *em_tree;
3392 struct extent_map *em;
3395 spin_lock(&block_group->lock);
3396 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
3397 block_group->removed);
3398 spin_unlock(&block_group->lock);
3401 em_tree = &fs_info->mapping_tree;
3402 write_lock(&em_tree->lock);
3403 em = lookup_extent_mapping(em_tree, block_group->start,
3405 BUG_ON(!em); /* logic error, can't happen */
3406 remove_extent_mapping(em_tree, em);
3407 write_unlock(&em_tree->lock);
3409 /* once for us and once for the tree */
3410 free_extent_map(em);
3411 free_extent_map(em);
3414 * We may have left one free space entry and other possible
3415 * tasks trimming this block group have left 1 entry each one.
3418 __btrfs_remove_free_space_cache(block_group->free_space_ctl);