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 static bool space_cache_v1_done(struct btrfs_block_group *cache)
431 spin_lock(&cache->lock);
432 ret = cache->cached != BTRFS_CACHE_FAST;
433 spin_unlock(&cache->lock);
438 void btrfs_wait_space_cache_v1_finished(struct btrfs_block_group *cache,
439 struct btrfs_caching_control *caching_ctl)
441 wait_event(caching_ctl->wait, space_cache_v1_done(cache));
444 #ifdef CONFIG_BTRFS_DEBUG
445 static void fragment_free_space(struct btrfs_block_group *block_group)
447 struct btrfs_fs_info *fs_info = block_group->fs_info;
448 u64 start = block_group->start;
449 u64 len = block_group->length;
450 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
451 fs_info->nodesize : fs_info->sectorsize;
452 u64 step = chunk << 1;
454 while (len > chunk) {
455 btrfs_remove_free_space(block_group, start, chunk);
466 * This is only called by btrfs_cache_block_group, since we could have freed
467 * extents we need to check the pinned_extents for any extents that can't be
468 * used yet since their free space will be released as soon as the transaction
471 u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
473 struct btrfs_fs_info *info = block_group->fs_info;
474 u64 extent_start, extent_end, size, total_added = 0;
477 while (start < end) {
478 ret = find_first_extent_bit(&info->excluded_extents, start,
479 &extent_start, &extent_end,
480 EXTENT_DIRTY | EXTENT_UPTODATE,
485 if (extent_start <= start) {
486 start = extent_end + 1;
487 } else if (extent_start > start && extent_start < end) {
488 size = extent_start - start;
490 ret = btrfs_add_free_space_async_trimmed(block_group,
492 BUG_ON(ret); /* -ENOMEM or logic error */
493 start = extent_end + 1;
502 ret = btrfs_add_free_space_async_trimmed(block_group, start,
504 BUG_ON(ret); /* -ENOMEM or logic error */
510 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
512 struct btrfs_block_group *block_group = caching_ctl->block_group;
513 struct btrfs_fs_info *fs_info = block_group->fs_info;
514 struct btrfs_root *extent_root = fs_info->extent_root;
515 struct btrfs_path *path;
516 struct extent_buffer *leaf;
517 struct btrfs_key key;
524 path = btrfs_alloc_path();
528 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
530 #ifdef CONFIG_BTRFS_DEBUG
532 * If we're fragmenting we don't want to make anybody think we can
533 * allocate from this block group until we've had a chance to fragment
536 if (btrfs_should_fragment_free_space(block_group))
540 * We don't want to deadlock with somebody trying to allocate a new
541 * extent for the extent root while also trying to search the extent
542 * root to add free space. So we skip locking and search the commit
543 * root, since its read-only
545 path->skip_locking = 1;
546 path->search_commit_root = 1;
547 path->reada = READA_FORWARD;
551 key.type = BTRFS_EXTENT_ITEM_KEY;
554 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
558 leaf = path->nodes[0];
559 nritems = btrfs_header_nritems(leaf);
562 if (btrfs_fs_closing(fs_info) > 1) {
567 if (path->slots[0] < nritems) {
568 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
570 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
574 if (need_resched() ||
575 rwsem_is_contended(&fs_info->commit_root_sem)) {
577 caching_ctl->progress = last;
578 btrfs_release_path(path);
579 up_read(&fs_info->commit_root_sem);
580 mutex_unlock(&caching_ctl->mutex);
582 mutex_lock(&caching_ctl->mutex);
583 down_read(&fs_info->commit_root_sem);
587 ret = btrfs_next_leaf(extent_root, path);
592 leaf = path->nodes[0];
593 nritems = btrfs_header_nritems(leaf);
597 if (key.objectid < last) {
600 key.type = BTRFS_EXTENT_ITEM_KEY;
603 caching_ctl->progress = last;
604 btrfs_release_path(path);
608 if (key.objectid < block_group->start) {
613 if (key.objectid >= block_group->start + block_group->length)
616 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
617 key.type == BTRFS_METADATA_ITEM_KEY) {
618 total_found += add_new_free_space(block_group, last,
620 if (key.type == BTRFS_METADATA_ITEM_KEY)
621 last = key.objectid +
624 last = key.objectid + key.offset;
626 if (total_found > CACHING_CTL_WAKE_UP) {
629 wake_up(&caching_ctl->wait);
636 total_found += add_new_free_space(block_group, last,
637 block_group->start + block_group->length);
638 caching_ctl->progress = (u64)-1;
641 btrfs_free_path(path);
645 static noinline void caching_thread(struct btrfs_work *work)
647 struct btrfs_block_group *block_group;
648 struct btrfs_fs_info *fs_info;
649 struct btrfs_caching_control *caching_ctl;
652 caching_ctl = container_of(work, struct btrfs_caching_control, work);
653 block_group = caching_ctl->block_group;
654 fs_info = block_group->fs_info;
656 mutex_lock(&caching_ctl->mutex);
657 down_read(&fs_info->commit_root_sem);
659 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
660 ret = load_free_space_cache(block_group);
667 * We failed to load the space cache, set ourselves to
668 * CACHE_STARTED and carry on.
670 spin_lock(&block_group->lock);
671 block_group->cached = BTRFS_CACHE_STARTED;
672 spin_unlock(&block_group->lock);
673 wake_up(&caching_ctl->wait);
676 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
677 ret = load_free_space_tree(caching_ctl);
679 ret = load_extent_tree_free(caching_ctl);
681 spin_lock(&block_group->lock);
682 block_group->caching_ctl = NULL;
683 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
684 spin_unlock(&block_group->lock);
686 #ifdef CONFIG_BTRFS_DEBUG
687 if (btrfs_should_fragment_free_space(block_group)) {
690 spin_lock(&block_group->space_info->lock);
691 spin_lock(&block_group->lock);
692 bytes_used = block_group->length - block_group->used;
693 block_group->space_info->bytes_used += bytes_used >> 1;
694 spin_unlock(&block_group->lock);
695 spin_unlock(&block_group->space_info->lock);
696 fragment_free_space(block_group);
700 caching_ctl->progress = (u64)-1;
702 up_read(&fs_info->commit_root_sem);
703 btrfs_free_excluded_extents(block_group);
704 mutex_unlock(&caching_ctl->mutex);
706 wake_up(&caching_ctl->wait);
708 btrfs_put_caching_control(caching_ctl);
709 btrfs_put_block_group(block_group);
712 int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
715 struct btrfs_fs_info *fs_info = cache->fs_info;
716 struct btrfs_caching_control *caching_ctl = NULL;
719 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
723 INIT_LIST_HEAD(&caching_ctl->list);
724 mutex_init(&caching_ctl->mutex);
725 init_waitqueue_head(&caching_ctl->wait);
726 caching_ctl->block_group = cache;
727 caching_ctl->progress = cache->start;
728 refcount_set(&caching_ctl->count, 2);
729 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
731 spin_lock(&cache->lock);
732 if (cache->cached != BTRFS_CACHE_NO) {
735 caching_ctl = cache->caching_ctl;
737 refcount_inc(&caching_ctl->count);
738 spin_unlock(&cache->lock);
741 WARN_ON(cache->caching_ctl);
742 cache->caching_ctl = caching_ctl;
743 if (btrfs_test_opt(fs_info, SPACE_CACHE))
744 cache->cached = BTRFS_CACHE_FAST;
746 cache->cached = BTRFS_CACHE_STARTED;
747 cache->has_caching_ctl = 1;
748 spin_unlock(&cache->lock);
750 spin_lock(&fs_info->block_group_cache_lock);
751 refcount_inc(&caching_ctl->count);
752 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
753 spin_unlock(&fs_info->block_group_cache_lock);
755 btrfs_get_block_group(cache);
757 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
759 if (load_cache_only && caching_ctl)
760 btrfs_wait_space_cache_v1_finished(cache, caching_ctl);
762 btrfs_put_caching_control(caching_ctl);
767 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
769 u64 extra_flags = chunk_to_extended(flags) &
770 BTRFS_EXTENDED_PROFILE_MASK;
772 write_seqlock(&fs_info->profiles_lock);
773 if (flags & BTRFS_BLOCK_GROUP_DATA)
774 fs_info->avail_data_alloc_bits &= ~extra_flags;
775 if (flags & BTRFS_BLOCK_GROUP_METADATA)
776 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
777 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
778 fs_info->avail_system_alloc_bits &= ~extra_flags;
779 write_sequnlock(&fs_info->profiles_lock);
783 * Clear incompat bits for the following feature(s):
785 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
786 * in the whole filesystem
788 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
790 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
792 bool found_raid56 = false;
793 bool found_raid1c34 = false;
795 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
796 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
797 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
798 struct list_head *head = &fs_info->space_info;
799 struct btrfs_space_info *sinfo;
801 list_for_each_entry_rcu(sinfo, head, list) {
802 down_read(&sinfo->groups_sem);
803 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
805 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
807 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
808 found_raid1c34 = true;
809 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
810 found_raid1c34 = true;
811 up_read(&sinfo->groups_sem);
814 btrfs_clear_fs_incompat(fs_info, RAID56);
816 btrfs_clear_fs_incompat(fs_info, RAID1C34);
820 static int remove_block_group_item(struct btrfs_trans_handle *trans,
821 struct btrfs_path *path,
822 struct btrfs_block_group *block_group)
824 struct btrfs_fs_info *fs_info = trans->fs_info;
825 struct btrfs_root *root;
826 struct btrfs_key key;
829 root = fs_info->extent_root;
830 key.objectid = block_group->start;
831 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
832 key.offset = block_group->length;
834 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
840 ret = btrfs_del_item(trans, root, path);
844 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
845 u64 group_start, struct extent_map *em)
847 struct btrfs_fs_info *fs_info = trans->fs_info;
848 struct btrfs_path *path;
849 struct btrfs_block_group *block_group;
850 struct btrfs_free_cluster *cluster;
851 struct btrfs_root *tree_root = fs_info->tree_root;
852 struct btrfs_key key;
854 struct kobject *kobj = NULL;
858 struct btrfs_caching_control *caching_ctl = NULL;
860 bool remove_rsv = false;
862 block_group = btrfs_lookup_block_group(fs_info, group_start);
863 BUG_ON(!block_group);
864 BUG_ON(!block_group->ro);
866 trace_btrfs_remove_block_group(block_group);
868 * Free the reserved super bytes from this block group before
871 btrfs_free_excluded_extents(block_group);
872 btrfs_free_ref_tree_range(fs_info, block_group->start,
873 block_group->length);
875 index = btrfs_bg_flags_to_raid_index(block_group->flags);
876 factor = btrfs_bg_type_to_factor(block_group->flags);
878 /* make sure this block group isn't part of an allocation cluster */
879 cluster = &fs_info->data_alloc_cluster;
880 spin_lock(&cluster->refill_lock);
881 btrfs_return_cluster_to_free_space(block_group, cluster);
882 spin_unlock(&cluster->refill_lock);
885 * make sure this block group isn't part of a metadata
888 cluster = &fs_info->meta_alloc_cluster;
889 spin_lock(&cluster->refill_lock);
890 btrfs_return_cluster_to_free_space(block_group, cluster);
891 spin_unlock(&cluster->refill_lock);
893 path = btrfs_alloc_path();
900 * get the inode first so any iput calls done for the io_list
901 * aren't the final iput (no unlinks allowed now)
903 inode = lookup_free_space_inode(block_group, path);
905 mutex_lock(&trans->transaction->cache_write_mutex);
907 * Make sure our free space cache IO is done before removing the
910 spin_lock(&trans->transaction->dirty_bgs_lock);
911 if (!list_empty(&block_group->io_list)) {
912 list_del_init(&block_group->io_list);
914 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
916 spin_unlock(&trans->transaction->dirty_bgs_lock);
917 btrfs_wait_cache_io(trans, block_group, path);
918 btrfs_put_block_group(block_group);
919 spin_lock(&trans->transaction->dirty_bgs_lock);
922 if (!list_empty(&block_group->dirty_list)) {
923 list_del_init(&block_group->dirty_list);
925 btrfs_put_block_group(block_group);
927 spin_unlock(&trans->transaction->dirty_bgs_lock);
928 mutex_unlock(&trans->transaction->cache_write_mutex);
930 if (!IS_ERR(inode)) {
931 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
933 btrfs_add_delayed_iput(inode);
937 /* One for the block groups ref */
938 spin_lock(&block_group->lock);
939 if (block_group->iref) {
940 block_group->iref = 0;
941 block_group->inode = NULL;
942 spin_unlock(&block_group->lock);
945 spin_unlock(&block_group->lock);
947 /* One for our lookup ref */
948 btrfs_add_delayed_iput(inode);
951 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
953 key.offset = block_group->start;
955 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
959 btrfs_release_path(path);
961 ret = btrfs_del_item(trans, tree_root, path);
964 btrfs_release_path(path);
967 spin_lock(&fs_info->block_group_cache_lock);
968 rb_erase(&block_group->cache_node,
969 &fs_info->block_group_cache_tree);
970 RB_CLEAR_NODE(&block_group->cache_node);
972 /* Once for the block groups rbtree */
973 btrfs_put_block_group(block_group);
975 if (fs_info->first_logical_byte == block_group->start)
976 fs_info->first_logical_byte = (u64)-1;
977 spin_unlock(&fs_info->block_group_cache_lock);
979 down_write(&block_group->space_info->groups_sem);
981 * we must use list_del_init so people can check to see if they
982 * are still on the list after taking the semaphore
984 list_del_init(&block_group->list);
985 if (list_empty(&block_group->space_info->block_groups[index])) {
986 kobj = block_group->space_info->block_group_kobjs[index];
987 block_group->space_info->block_group_kobjs[index] = NULL;
988 clear_avail_alloc_bits(fs_info, block_group->flags);
990 up_write(&block_group->space_info->groups_sem);
991 clear_incompat_bg_bits(fs_info, block_group->flags);
997 if (block_group->has_caching_ctl)
998 caching_ctl = btrfs_get_caching_control(block_group);
999 if (block_group->cached == BTRFS_CACHE_STARTED)
1000 btrfs_wait_block_group_cache_done(block_group);
1001 if (block_group->has_caching_ctl) {
1002 spin_lock(&fs_info->block_group_cache_lock);
1004 struct btrfs_caching_control *ctl;
1006 list_for_each_entry(ctl,
1007 &fs_info->caching_block_groups, list)
1008 if (ctl->block_group == block_group) {
1010 refcount_inc(&caching_ctl->count);
1015 list_del_init(&caching_ctl->list);
1016 spin_unlock(&fs_info->block_group_cache_lock);
1018 /* Once for the caching bgs list and once for us. */
1019 btrfs_put_caching_control(caching_ctl);
1020 btrfs_put_caching_control(caching_ctl);
1024 spin_lock(&trans->transaction->dirty_bgs_lock);
1025 WARN_ON(!list_empty(&block_group->dirty_list));
1026 WARN_ON(!list_empty(&block_group->io_list));
1027 spin_unlock(&trans->transaction->dirty_bgs_lock);
1029 btrfs_remove_free_space_cache(block_group);
1031 spin_lock(&block_group->space_info->lock);
1032 list_del_init(&block_group->ro_list);
1034 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1035 WARN_ON(block_group->space_info->total_bytes
1036 < block_group->length);
1037 WARN_ON(block_group->space_info->bytes_readonly
1038 < block_group->length);
1039 WARN_ON(block_group->space_info->disk_total
1040 < block_group->length * factor);
1042 block_group->space_info->total_bytes -= block_group->length;
1043 block_group->space_info->bytes_readonly -= block_group->length;
1044 block_group->space_info->disk_total -= block_group->length * factor;
1046 spin_unlock(&block_group->space_info->lock);
1049 * Remove the free space for the block group from the free space tree
1050 * and the block group's item from the extent tree before marking the
1051 * block group as removed. This is to prevent races with tasks that
1052 * freeze and unfreeze a block group, this task and another task
1053 * allocating a new block group - the unfreeze task ends up removing
1054 * the block group's extent map before the task calling this function
1055 * deletes the block group item from the extent tree, allowing for
1056 * another task to attempt to create another block group with the same
1057 * item key (and failing with -EEXIST and a transaction abort).
1059 ret = remove_block_group_free_space(trans, block_group);
1063 ret = remove_block_group_item(trans, path, block_group);
1067 spin_lock(&block_group->lock);
1068 block_group->removed = 1;
1070 * At this point trimming or scrub can't start on this block group,
1071 * because we removed the block group from the rbtree
1072 * fs_info->block_group_cache_tree so no one can't find it anymore and
1073 * even if someone already got this block group before we removed it
1074 * from the rbtree, they have already incremented block_group->frozen -
1075 * if they didn't, for the trimming case they won't find any free space
1076 * entries because we already removed them all when we called
1077 * btrfs_remove_free_space_cache().
1079 * And we must not remove the extent map from the fs_info->mapping_tree
1080 * to prevent the same logical address range and physical device space
1081 * ranges from being reused for a new block group. This is needed to
1082 * avoid races with trimming and scrub.
1084 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1085 * completely transactionless, so while it is trimming a range the
1086 * currently running transaction might finish and a new one start,
1087 * allowing for new block groups to be created that can reuse the same
1088 * physical device locations unless we take this special care.
1090 * There may also be an implicit trim operation if the file system
1091 * is mounted with -odiscard. The same protections must remain
1092 * in place until the extents have been discarded completely when
1093 * the transaction commit has completed.
1095 remove_em = (atomic_read(&block_group->frozen) == 0);
1096 spin_unlock(&block_group->lock);
1099 struct extent_map_tree *em_tree;
1101 em_tree = &fs_info->mapping_tree;
1102 write_lock(&em_tree->lock);
1103 remove_extent_mapping(em_tree, em);
1104 write_unlock(&em_tree->lock);
1105 /* once for the tree */
1106 free_extent_map(em);
1110 /* Once for the lookup reference */
1111 btrfs_put_block_group(block_group);
1113 btrfs_delayed_refs_rsv_release(fs_info, 1);
1114 btrfs_free_path(path);
1118 struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1119 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1121 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1122 struct extent_map *em;
1123 struct map_lookup *map;
1124 unsigned int num_items;
1126 read_lock(&em_tree->lock);
1127 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1128 read_unlock(&em_tree->lock);
1129 ASSERT(em && em->start == chunk_offset);
1132 * We need to reserve 3 + N units from the metadata space info in order
1133 * to remove a block group (done at btrfs_remove_chunk() and at
1134 * btrfs_remove_block_group()), which are used for:
1136 * 1 unit for adding the free space inode's orphan (located in the tree
1138 * 1 unit for deleting the block group item (located in the extent
1140 * 1 unit for deleting the free space item (located in tree of tree
1142 * N units for deleting N device extent items corresponding to each
1143 * stripe (located in the device tree).
1145 * In order to remove a block group we also need to reserve units in the
1146 * system space info in order to update the chunk tree (update one or
1147 * more device items and remove one chunk item), but this is done at
1148 * btrfs_remove_chunk() through a call to check_system_chunk().
1150 map = em->map_lookup;
1151 num_items = 3 + map->num_stripes;
1152 free_extent_map(em);
1154 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
1159 * Mark block group @cache read-only, so later write won't happen to block
1162 * If @force is not set, this function will only mark the block group readonly
1163 * if we have enough free space (1M) in other metadata/system block groups.
1164 * If @force is not set, this function will mark the block group readonly
1165 * without checking free space.
1167 * NOTE: This function doesn't care if other block groups can contain all the
1168 * data in this block group. That check should be done by relocation routine,
1169 * not this function.
1171 static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
1173 struct btrfs_space_info *sinfo = cache->space_info;
1177 spin_lock(&sinfo->lock);
1178 spin_lock(&cache->lock);
1186 num_bytes = cache->length - cache->reserved - cache->pinned -
1187 cache->bytes_super - cache->used;
1190 * Data never overcommits, even in mixed mode, so do just the straight
1191 * check of left over space in how much we have allocated.
1195 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1196 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1199 * Here we make sure if we mark this bg RO, we still have enough
1200 * free space as buffer.
1202 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1206 * We overcommit metadata, so we need to do the
1207 * btrfs_can_overcommit check here, and we need to pass in
1208 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1209 * leeway to allow us to mark this block group as read only.
1211 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1212 BTRFS_RESERVE_NO_FLUSH))
1217 sinfo->bytes_readonly += num_bytes;
1219 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
1222 spin_unlock(&cache->lock);
1223 spin_unlock(&sinfo->lock);
1224 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1225 btrfs_info(cache->fs_info,
1226 "unable to make block group %llu ro", cache->start);
1227 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1232 static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1233 struct btrfs_block_group *bg)
1235 struct btrfs_fs_info *fs_info = bg->fs_info;
1236 struct btrfs_transaction *prev_trans = NULL;
1237 const u64 start = bg->start;
1238 const u64 end = start + bg->length - 1;
1241 spin_lock(&fs_info->trans_lock);
1242 if (trans->transaction->list.prev != &fs_info->trans_list) {
1243 prev_trans = list_last_entry(&trans->transaction->list,
1244 struct btrfs_transaction, list);
1245 refcount_inc(&prev_trans->use_count);
1247 spin_unlock(&fs_info->trans_lock);
1250 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1251 * btrfs_finish_extent_commit(). If we are at transaction N, another
1252 * task might be running finish_extent_commit() for the previous
1253 * transaction N - 1, and have seen a range belonging to the block
1254 * group in pinned_extents before we were able to clear the whole block
1255 * group range from pinned_extents. This means that task can lookup for
1256 * the block group after we unpinned it from pinned_extents and removed
1257 * it, leading to a BUG_ON() at unpin_extent_range().
1259 mutex_lock(&fs_info->unused_bg_unpin_mutex);
1261 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1267 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
1270 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1272 btrfs_put_transaction(prev_trans);
1278 * Process the unused_bgs list and remove any that don't have any allocated
1279 * space inside of them.
1281 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1283 struct btrfs_block_group *block_group;
1284 struct btrfs_space_info *space_info;
1285 struct btrfs_trans_handle *trans;
1286 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1289 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1292 spin_lock(&fs_info->unused_bgs_lock);
1293 while (!list_empty(&fs_info->unused_bgs)) {
1296 block_group = list_first_entry(&fs_info->unused_bgs,
1297 struct btrfs_block_group,
1299 list_del_init(&block_group->bg_list);
1301 space_info = block_group->space_info;
1303 if (ret || btrfs_mixed_space_info(space_info)) {
1304 btrfs_put_block_group(block_group);
1307 spin_unlock(&fs_info->unused_bgs_lock);
1309 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1311 mutex_lock(&fs_info->delete_unused_bgs_mutex);
1313 /* Don't want to race with allocators so take the groups_sem */
1314 down_write(&space_info->groups_sem);
1317 * Async discard moves the final block group discard to be prior
1318 * to the unused_bgs code path. Therefore, if it's not fully
1319 * trimmed, punt it back to the async discard lists.
1321 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1322 !btrfs_is_free_space_trimmed(block_group)) {
1323 trace_btrfs_skip_unused_block_group(block_group);
1324 up_write(&space_info->groups_sem);
1325 /* Requeue if we failed because of async discard */
1326 btrfs_discard_queue_work(&fs_info->discard_ctl,
1331 spin_lock(&block_group->lock);
1332 if (block_group->reserved || block_group->pinned ||
1333 block_group->used || block_group->ro ||
1334 list_is_singular(&block_group->list)) {
1336 * We want to bail if we made new allocations or have
1337 * outstanding allocations in this block group. We do
1338 * the ro check in case balance is currently acting on
1341 trace_btrfs_skip_unused_block_group(block_group);
1342 spin_unlock(&block_group->lock);
1343 up_write(&space_info->groups_sem);
1346 spin_unlock(&block_group->lock);
1348 /* We don't want to force the issue, only flip if it's ok. */
1349 ret = inc_block_group_ro(block_group, 0);
1350 up_write(&space_info->groups_sem);
1357 * Want to do this before we do anything else so we can recover
1358 * properly if we fail to join the transaction.
1360 trans = btrfs_start_trans_remove_block_group(fs_info,
1361 block_group->start);
1362 if (IS_ERR(trans)) {
1363 btrfs_dec_block_group_ro(block_group);
1364 ret = PTR_ERR(trans);
1369 * We could have pending pinned extents for this block group,
1370 * just delete them, we don't care about them anymore.
1372 if (!clean_pinned_extents(trans, block_group)) {
1373 btrfs_dec_block_group_ro(block_group);
1378 * At this point, the block_group is read only and should fail
1379 * new allocations. However, btrfs_finish_extent_commit() can
1380 * cause this block_group to be placed back on the discard
1381 * lists because now the block_group isn't fully discarded.
1382 * Bail here and try again later after discarding everything.
1384 spin_lock(&fs_info->discard_ctl.lock);
1385 if (!list_empty(&block_group->discard_list)) {
1386 spin_unlock(&fs_info->discard_ctl.lock);
1387 btrfs_dec_block_group_ro(block_group);
1388 btrfs_discard_queue_work(&fs_info->discard_ctl,
1392 spin_unlock(&fs_info->discard_ctl.lock);
1394 /* Reset pinned so btrfs_put_block_group doesn't complain */
1395 spin_lock(&space_info->lock);
1396 spin_lock(&block_group->lock);
1398 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1399 -block_group->pinned);
1400 space_info->bytes_readonly += block_group->pinned;
1401 percpu_counter_add_batch(&space_info->total_bytes_pinned,
1402 -block_group->pinned,
1403 BTRFS_TOTAL_BYTES_PINNED_BATCH);
1404 block_group->pinned = 0;
1406 spin_unlock(&block_group->lock);
1407 spin_unlock(&space_info->lock);
1410 * The normal path here is an unused block group is passed here,
1411 * then trimming is handled in the transaction commit path.
1412 * Async discard interposes before this to do the trimming
1413 * before coming down the unused block group path as trimming
1414 * will no longer be done later in the transaction commit path.
1416 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1419 /* DISCARD can flip during remount */
1420 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC);
1422 /* Implicit trim during transaction commit. */
1424 btrfs_freeze_block_group(block_group);
1427 * Btrfs_remove_chunk will abort the transaction if things go
1430 ret = btrfs_remove_chunk(trans, block_group->start);
1434 btrfs_unfreeze_block_group(block_group);
1439 * If we're not mounted with -odiscard, we can just forget
1440 * about this block group. Otherwise we'll need to wait
1441 * until transaction commit to do the actual discard.
1444 spin_lock(&fs_info->unused_bgs_lock);
1446 * A concurrent scrub might have added us to the list
1447 * fs_info->unused_bgs, so use a list_move operation
1448 * to add the block group to the deleted_bgs list.
1450 list_move(&block_group->bg_list,
1451 &trans->transaction->deleted_bgs);
1452 spin_unlock(&fs_info->unused_bgs_lock);
1453 btrfs_get_block_group(block_group);
1456 btrfs_end_transaction(trans);
1458 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1459 btrfs_put_block_group(block_group);
1460 spin_lock(&fs_info->unused_bgs_lock);
1462 spin_unlock(&fs_info->unused_bgs_lock);
1466 btrfs_end_transaction(trans);
1467 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1468 btrfs_put_block_group(block_group);
1469 btrfs_discard_punt_unused_bgs_list(fs_info);
1472 void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1474 struct btrfs_fs_info *fs_info = bg->fs_info;
1476 spin_lock(&fs_info->unused_bgs_lock);
1477 if (list_empty(&bg->bg_list)) {
1478 btrfs_get_block_group(bg);
1479 trace_btrfs_add_unused_block_group(bg);
1480 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1482 spin_unlock(&fs_info->unused_bgs_lock);
1485 static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1486 struct btrfs_path *path)
1488 struct extent_map_tree *em_tree;
1489 struct extent_map *em;
1490 struct btrfs_block_group_item bg;
1491 struct extent_buffer *leaf;
1496 slot = path->slots[0];
1497 leaf = path->nodes[0];
1499 em_tree = &fs_info->mapping_tree;
1500 read_lock(&em_tree->lock);
1501 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1502 read_unlock(&em_tree->lock);
1505 "logical %llu len %llu found bg but no related chunk",
1506 key->objectid, key->offset);
1510 if (em->start != key->objectid || em->len != key->offset) {
1512 "block group %llu len %llu mismatch with chunk %llu len %llu",
1513 key->objectid, key->offset, em->start, em->len);
1518 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1520 flags = btrfs_stack_block_group_flags(&bg) &
1521 BTRFS_BLOCK_GROUP_TYPE_MASK;
1523 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1525 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1526 key->objectid, key->offset, flags,
1527 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1532 free_extent_map(em);
1536 static int find_first_block_group(struct btrfs_fs_info *fs_info,
1537 struct btrfs_path *path,
1538 struct btrfs_key *key)
1540 struct btrfs_root *root = fs_info->extent_root;
1542 struct btrfs_key found_key;
1543 struct extent_buffer *leaf;
1546 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1551 slot = path->slots[0];
1552 leaf = path->nodes[0];
1553 if (slot >= btrfs_header_nritems(leaf)) {
1554 ret = btrfs_next_leaf(root, path);
1561 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1563 if (found_key.objectid >= key->objectid &&
1564 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1565 ret = read_bg_from_eb(fs_info, &found_key, path);
1575 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1577 u64 extra_flags = chunk_to_extended(flags) &
1578 BTRFS_EXTENDED_PROFILE_MASK;
1580 write_seqlock(&fs_info->profiles_lock);
1581 if (flags & BTRFS_BLOCK_GROUP_DATA)
1582 fs_info->avail_data_alloc_bits |= extra_flags;
1583 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1584 fs_info->avail_metadata_alloc_bits |= extra_flags;
1585 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1586 fs_info->avail_system_alloc_bits |= extra_flags;
1587 write_sequnlock(&fs_info->profiles_lock);
1591 * btrfs_rmap_block - Map a physical disk address to a list of logical addresses
1592 * @chunk_start: logical address of block group
1593 * @physical: physical address to map to logical addresses
1594 * @logical: return array of logical addresses which map to @physical
1595 * @naddrs: length of @logical
1596 * @stripe_len: size of IO stripe for the given block group
1598 * Maps a particular @physical disk address to a list of @logical addresses.
1599 * Used primarily to exclude those portions of a block group that contain super
1603 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1604 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
1606 struct extent_map *em;
1607 struct map_lookup *map;
1610 u64 data_stripe_length;
1615 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1619 map = em->map_lookup;
1620 data_stripe_length = em->orig_block_len;
1621 io_stripe_size = map->stripe_len;
1623 /* For RAID5/6 adjust to a full IO stripe length */
1624 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
1625 io_stripe_size = map->stripe_len * nr_data_stripes(map);
1627 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
1633 for (i = 0; i < map->num_stripes; i++) {
1634 bool already_inserted = false;
1638 if (!in_range(physical, map->stripes[i].physical,
1639 data_stripe_length))
1642 stripe_nr = physical - map->stripes[i].physical;
1643 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
1645 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1646 stripe_nr = stripe_nr * map->num_stripes + i;
1647 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1648 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1649 stripe_nr = stripe_nr * map->num_stripes + i;
1652 * The remaining case would be for RAID56, multiply by
1653 * nr_data_stripes(). Alternatively, just use rmap_len below
1654 * instead of map->stripe_len
1657 bytenr = chunk_start + stripe_nr * io_stripe_size;
1659 /* Ensure we don't add duplicate addresses */
1660 for (j = 0; j < nr; j++) {
1661 if (buf[j] == bytenr) {
1662 already_inserted = true;
1667 if (!already_inserted)
1673 *stripe_len = io_stripe_size;
1675 free_extent_map(em);
1679 static int exclude_super_stripes(struct btrfs_block_group *cache)
1681 struct btrfs_fs_info *fs_info = cache->fs_info;
1687 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1688 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
1689 cache->bytes_super += stripe_len;
1690 ret = btrfs_add_excluded_extent(fs_info, cache->start,
1696 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1697 bytenr = btrfs_sb_offset(i);
1698 ret = btrfs_rmap_block(fs_info, cache->start,
1699 bytenr, &logical, &nr, &stripe_len);
1704 u64 len = min_t(u64, stripe_len,
1705 cache->start + cache->length - logical[nr]);
1707 cache->bytes_super += len;
1708 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
1721 static void link_block_group(struct btrfs_block_group *cache)
1723 struct btrfs_space_info *space_info = cache->space_info;
1724 int index = btrfs_bg_flags_to_raid_index(cache->flags);
1726 down_write(&space_info->groups_sem);
1727 list_add_tail(&cache->list, &space_info->block_groups[index]);
1728 up_write(&space_info->groups_sem);
1731 static struct btrfs_block_group *btrfs_create_block_group_cache(
1732 struct btrfs_fs_info *fs_info, u64 start)
1734 struct btrfs_block_group *cache;
1736 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1740 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1742 if (!cache->free_space_ctl) {
1747 cache->start = start;
1749 cache->fs_info = fs_info;
1750 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
1752 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1754 refcount_set(&cache->refs, 1);
1755 spin_lock_init(&cache->lock);
1756 init_rwsem(&cache->data_rwsem);
1757 INIT_LIST_HEAD(&cache->list);
1758 INIT_LIST_HEAD(&cache->cluster_list);
1759 INIT_LIST_HEAD(&cache->bg_list);
1760 INIT_LIST_HEAD(&cache->ro_list);
1761 INIT_LIST_HEAD(&cache->discard_list);
1762 INIT_LIST_HEAD(&cache->dirty_list);
1763 INIT_LIST_HEAD(&cache->io_list);
1764 btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
1765 atomic_set(&cache->frozen, 0);
1766 mutex_init(&cache->free_space_lock);
1767 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1773 * Iterate all chunks and verify that each of them has the corresponding block
1776 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1778 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1779 struct extent_map *em;
1780 struct btrfs_block_group *bg;
1785 read_lock(&map_tree->lock);
1787 * lookup_extent_mapping will return the first extent map
1788 * intersecting the range, so setting @len to 1 is enough to
1789 * get the first chunk.
1791 em = lookup_extent_mapping(map_tree, start, 1);
1792 read_unlock(&map_tree->lock);
1796 bg = btrfs_lookup_block_group(fs_info, em->start);
1799 "chunk start=%llu len=%llu doesn't have corresponding block group",
1800 em->start, em->len);
1802 free_extent_map(em);
1805 if (bg->start != em->start || bg->length != em->len ||
1806 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1807 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1809 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
1811 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
1812 bg->start, bg->length,
1813 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
1815 free_extent_map(em);
1816 btrfs_put_block_group(bg);
1819 start = em->start + em->len;
1820 free_extent_map(em);
1821 btrfs_put_block_group(bg);
1826 static void read_block_group_item(struct btrfs_block_group *cache,
1827 struct btrfs_path *path,
1828 const struct btrfs_key *key)
1830 struct extent_buffer *leaf = path->nodes[0];
1831 struct btrfs_block_group_item bgi;
1832 int slot = path->slots[0];
1834 cache->length = key->offset;
1836 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
1838 cache->used = btrfs_stack_block_group_used(&bgi);
1839 cache->flags = btrfs_stack_block_group_flags(&bgi);
1842 static int read_one_block_group(struct btrfs_fs_info *info,
1843 struct btrfs_path *path,
1844 const struct btrfs_key *key,
1847 struct btrfs_block_group *cache;
1848 struct btrfs_space_info *space_info;
1849 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
1852 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
1854 cache = btrfs_create_block_group_cache(info, key->objectid);
1858 read_block_group_item(cache, path, key);
1860 set_free_space_tree_thresholds(cache);
1864 * When we mount with old space cache, we need to
1865 * set BTRFS_DC_CLEAR and set dirty flag.
1867 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
1868 * truncate the old free space cache inode and
1870 * b) Setting 'dirty flag' makes sure that we flush
1871 * the new space cache info onto disk.
1873 if (btrfs_test_opt(info, SPACE_CACHE))
1874 cache->disk_cache_state = BTRFS_DC_CLEAR;
1876 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
1877 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
1879 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
1886 * We need to exclude the super stripes now so that the space info has
1887 * super bytes accounted for, otherwise we'll think we have more space
1888 * than we actually do.
1890 ret = exclude_super_stripes(cache);
1892 /* We may have excluded something, so call this just in case. */
1893 btrfs_free_excluded_extents(cache);
1898 * Check for two cases, either we are full, and therefore don't need
1899 * to bother with the caching work since we won't find any space, or we
1900 * are empty, and we can just add all the space in and be done with it.
1901 * This saves us _a_lot_ of time, particularly in the full case.
1903 if (cache->length == cache->used) {
1904 cache->last_byte_to_unpin = (u64)-1;
1905 cache->cached = BTRFS_CACHE_FINISHED;
1906 btrfs_free_excluded_extents(cache);
1907 } else if (cache->used == 0) {
1908 cache->last_byte_to_unpin = (u64)-1;
1909 cache->cached = BTRFS_CACHE_FINISHED;
1910 add_new_free_space(cache, cache->start,
1911 cache->start + cache->length);
1912 btrfs_free_excluded_extents(cache);
1915 ret = btrfs_add_block_group_cache(info, cache);
1917 btrfs_remove_free_space_cache(cache);
1920 trace_btrfs_add_block_group(info, cache, 0);
1921 btrfs_update_space_info(info, cache->flags, cache->length,
1922 cache->used, cache->bytes_super, &space_info);
1924 cache->space_info = space_info;
1926 link_block_group(cache);
1928 set_avail_alloc_bits(info, cache->flags);
1929 if (btrfs_chunk_readonly(info, cache->start)) {
1930 inc_block_group_ro(cache, 1);
1931 } else if (cache->used == 0) {
1932 ASSERT(list_empty(&cache->bg_list));
1933 if (btrfs_test_opt(info, DISCARD_ASYNC))
1934 btrfs_discard_queue_work(&info->discard_ctl, cache);
1936 btrfs_mark_bg_unused(cache);
1940 btrfs_put_block_group(cache);
1944 static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
1946 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1947 struct btrfs_space_info *space_info;
1948 struct rb_node *node;
1951 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
1952 struct extent_map *em;
1953 struct map_lookup *map;
1954 struct btrfs_block_group *bg;
1956 em = rb_entry(node, struct extent_map, rb_node);
1957 map = em->map_lookup;
1958 bg = btrfs_create_block_group_cache(fs_info, em->start);
1964 /* Fill dummy cache as FULL */
1965 bg->length = em->len;
1966 bg->flags = map->type;
1967 bg->last_byte_to_unpin = (u64)-1;
1968 bg->cached = BTRFS_CACHE_FINISHED;
1970 bg->flags = map->type;
1971 ret = btrfs_add_block_group_cache(fs_info, bg);
1973 btrfs_remove_free_space_cache(bg);
1974 btrfs_put_block_group(bg);
1977 btrfs_update_space_info(fs_info, bg->flags, em->len, em->len,
1979 bg->space_info = space_info;
1980 link_block_group(bg);
1982 set_avail_alloc_bits(fs_info, bg->flags);
1985 btrfs_init_global_block_rsv(fs_info);
1989 int btrfs_read_block_groups(struct btrfs_fs_info *info)
1991 struct btrfs_path *path;
1993 struct btrfs_block_group *cache;
1994 struct btrfs_space_info *space_info;
1995 struct btrfs_key key;
1999 if (!info->extent_root)
2000 return fill_dummy_bgs(info);
2004 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2005 path = btrfs_alloc_path();
2009 cache_gen = btrfs_super_cache_generation(info->super_copy);
2010 if (btrfs_test_opt(info, SPACE_CACHE) &&
2011 btrfs_super_generation(info->super_copy) != cache_gen)
2013 if (btrfs_test_opt(info, CLEAR_CACHE))
2017 ret = find_first_block_group(info, path, &key);
2023 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2024 ret = read_one_block_group(info, path, &key, need_clear);
2027 key.objectid += key.offset;
2029 btrfs_release_path(path);
2031 btrfs_release_path(path);
2033 list_for_each_entry(space_info, &info->space_info, list) {
2036 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2037 if (list_empty(&space_info->block_groups[i]))
2039 cache = list_first_entry(&space_info->block_groups[i],
2040 struct btrfs_block_group,
2042 btrfs_sysfs_add_block_group_type(cache);
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);
2065 btrfs_init_global_block_rsv(info);
2066 ret = check_chunk_block_group_mappings(info);
2068 btrfs_free_path(path);
2072 static int insert_block_group_item(struct btrfs_trans_handle *trans,
2073 struct btrfs_block_group *block_group)
2075 struct btrfs_fs_info *fs_info = trans->fs_info;
2076 struct btrfs_block_group_item bgi;
2077 struct btrfs_root *root;
2078 struct btrfs_key key;
2080 spin_lock(&block_group->lock);
2081 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2082 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2083 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2084 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2085 key.objectid = block_group->start;
2086 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2087 key.offset = block_group->length;
2088 spin_unlock(&block_group->lock);
2090 root = fs_info->extent_root;
2091 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2094 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2096 struct btrfs_fs_info *fs_info = trans->fs_info;
2097 struct btrfs_block_group *block_group;
2100 if (!trans->can_flush_pending_bgs)
2103 while (!list_empty(&trans->new_bgs)) {
2106 block_group = list_first_entry(&trans->new_bgs,
2107 struct btrfs_block_group,
2112 index = btrfs_bg_flags_to_raid_index(block_group->flags);
2114 ret = insert_block_group_item(trans, block_group);
2116 btrfs_abort_transaction(trans, ret);
2117 ret = btrfs_finish_chunk_alloc(trans, block_group->start,
2118 block_group->length);
2120 btrfs_abort_transaction(trans, ret);
2121 add_block_group_free_space(trans, block_group);
2124 * If we restriped during balance, we may have added a new raid
2125 * type, so now add the sysfs entries when it is safe to do so.
2126 * We don't have to worry about locking here as it's handled in
2127 * btrfs_sysfs_add_block_group_type.
2129 if (block_group->space_info->block_group_kobjs[index] == NULL)
2130 btrfs_sysfs_add_block_group_type(block_group);
2132 /* Already aborted the transaction if it failed. */
2134 btrfs_delayed_refs_rsv_release(fs_info, 1);
2135 list_del_init(&block_group->bg_list);
2137 btrfs_trans_release_chunk_metadata(trans);
2140 int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
2141 u64 type, u64 chunk_offset, u64 size)
2143 struct btrfs_fs_info *fs_info = trans->fs_info;
2144 struct btrfs_block_group *cache;
2147 btrfs_set_log_full_commit(trans);
2149 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
2153 cache->length = size;
2154 set_free_space_tree_thresholds(cache);
2155 cache->used = bytes_used;
2156 cache->flags = type;
2157 cache->last_byte_to_unpin = (u64)-1;
2158 cache->cached = BTRFS_CACHE_FINISHED;
2159 cache->needs_free_space = 1;
2160 ret = exclude_super_stripes(cache);
2162 /* We may have excluded something, so call this just in case */
2163 btrfs_free_excluded_extents(cache);
2164 btrfs_put_block_group(cache);
2168 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2170 btrfs_free_excluded_extents(cache);
2172 #ifdef CONFIG_BTRFS_DEBUG
2173 if (btrfs_should_fragment_free_space(cache)) {
2174 u64 new_bytes_used = size - bytes_used;
2176 bytes_used += new_bytes_used >> 1;
2177 fragment_free_space(cache);
2181 * Ensure the corresponding space_info object is created and
2182 * assigned to our block group. We want our bg to be added to the rbtree
2183 * with its ->space_info set.
2185 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2186 ASSERT(cache->space_info);
2188 ret = btrfs_add_block_group_cache(fs_info, cache);
2190 btrfs_remove_free_space_cache(cache);
2191 btrfs_put_block_group(cache);
2196 * Now that our block group has its ->space_info set and is inserted in
2197 * the rbtree, update the space info's counters.
2199 trace_btrfs_add_block_group(fs_info, cache, 1);
2200 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
2201 cache->bytes_super, &cache->space_info);
2202 btrfs_update_global_block_rsv(fs_info);
2204 link_block_group(cache);
2206 list_add_tail(&cache->bg_list, &trans->new_bgs);
2207 trans->delayed_ref_updates++;
2208 btrfs_update_delayed_refs_rsv(trans);
2210 set_avail_alloc_bits(fs_info, type);
2215 * Mark one block group RO, can be called several times for the same block
2218 * @cache: the destination block group
2219 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2220 * ensure we still have some free space after marking this
2223 int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2224 bool do_chunk_alloc)
2226 struct btrfs_fs_info *fs_info = cache->fs_info;
2227 struct btrfs_trans_handle *trans;
2232 trans = btrfs_join_transaction(fs_info->extent_root);
2234 return PTR_ERR(trans);
2237 * we're not allowed to set block groups readonly after the dirty
2238 * block groups cache has started writing. If it already started,
2239 * back off and let this transaction commit
2241 mutex_lock(&fs_info->ro_block_group_mutex);
2242 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2243 u64 transid = trans->transid;
2245 mutex_unlock(&fs_info->ro_block_group_mutex);
2246 btrfs_end_transaction(trans);
2248 ret = btrfs_wait_for_commit(fs_info, transid);
2254 if (do_chunk_alloc) {
2256 * If we are changing raid levels, try to allocate a
2257 * corresponding block group with the new raid level.
2259 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2260 if (alloc_flags != cache->flags) {
2261 ret = btrfs_chunk_alloc(trans, alloc_flags,
2264 * ENOSPC is allowed here, we may have enough space
2265 * already allocated at the new raid level to carry on
2274 ret = inc_block_group_ro(cache, 0);
2275 if (!do_chunk_alloc)
2279 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2280 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2283 ret = inc_block_group_ro(cache, 0);
2285 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2286 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2287 mutex_lock(&fs_info->chunk_mutex);
2288 check_system_chunk(trans, alloc_flags);
2289 mutex_unlock(&fs_info->chunk_mutex);
2292 mutex_unlock(&fs_info->ro_block_group_mutex);
2294 btrfs_end_transaction(trans);
2298 void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
2300 struct btrfs_space_info *sinfo = cache->space_info;
2305 spin_lock(&sinfo->lock);
2306 spin_lock(&cache->lock);
2308 num_bytes = cache->length - cache->reserved -
2309 cache->pinned - cache->bytes_super - cache->used;
2310 sinfo->bytes_readonly -= num_bytes;
2311 list_del_init(&cache->ro_list);
2313 spin_unlock(&cache->lock);
2314 spin_unlock(&sinfo->lock);
2317 static int update_block_group_item(struct btrfs_trans_handle *trans,
2318 struct btrfs_path *path,
2319 struct btrfs_block_group *cache)
2321 struct btrfs_fs_info *fs_info = trans->fs_info;
2323 struct btrfs_root *root = fs_info->extent_root;
2325 struct extent_buffer *leaf;
2326 struct btrfs_block_group_item bgi;
2327 struct btrfs_key key;
2329 key.objectid = cache->start;
2330 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2331 key.offset = cache->length;
2333 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2340 leaf = path->nodes[0];
2341 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2342 btrfs_set_stack_block_group_used(&bgi, cache->used);
2343 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2344 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2345 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2346 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
2347 btrfs_mark_buffer_dirty(leaf);
2349 btrfs_release_path(path);
2354 static int cache_save_setup(struct btrfs_block_group *block_group,
2355 struct btrfs_trans_handle *trans,
2356 struct btrfs_path *path)
2358 struct btrfs_fs_info *fs_info = block_group->fs_info;
2359 struct btrfs_root *root = fs_info->tree_root;
2360 struct inode *inode = NULL;
2361 struct extent_changeset *data_reserved = NULL;
2363 int dcs = BTRFS_DC_ERROR;
2369 * If this block group is smaller than 100 megs don't bother caching the
2372 if (block_group->length < (100 * SZ_1M)) {
2373 spin_lock(&block_group->lock);
2374 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2375 spin_unlock(&block_group->lock);
2379 if (TRANS_ABORTED(trans))
2382 inode = lookup_free_space_inode(block_group, path);
2383 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2384 ret = PTR_ERR(inode);
2385 btrfs_release_path(path);
2389 if (IS_ERR(inode)) {
2393 if (block_group->ro)
2396 ret = create_free_space_inode(trans, block_group, path);
2403 * We want to set the generation to 0, that way if anything goes wrong
2404 * from here on out we know not to trust this cache when we load up next
2407 BTRFS_I(inode)->generation = 0;
2408 ret = btrfs_update_inode(trans, root, inode);
2411 * So theoretically we could recover from this, simply set the
2412 * super cache generation to 0 so we know to invalidate the
2413 * cache, but then we'd have to keep track of the block groups
2414 * that fail this way so we know we _have_ to reset this cache
2415 * before the next commit or risk reading stale cache. So to
2416 * limit our exposure to horrible edge cases lets just abort the
2417 * transaction, this only happens in really bad situations
2420 btrfs_abort_transaction(trans, ret);
2425 /* We've already setup this transaction, go ahead and exit */
2426 if (block_group->cache_generation == trans->transid &&
2427 i_size_read(inode)) {
2428 dcs = BTRFS_DC_SETUP;
2432 if (i_size_read(inode) > 0) {
2433 ret = btrfs_check_trunc_cache_free_space(fs_info,
2434 &fs_info->global_block_rsv);
2438 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2443 spin_lock(&block_group->lock);
2444 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2445 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2447 * don't bother trying to write stuff out _if_
2448 * a) we're not cached,
2449 * b) we're with nospace_cache mount option,
2450 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2452 dcs = BTRFS_DC_WRITTEN;
2453 spin_unlock(&block_group->lock);
2456 spin_unlock(&block_group->lock);
2459 * We hit an ENOSPC when setting up the cache in this transaction, just
2460 * skip doing the setup, we've already cleared the cache so we're safe.
2462 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2468 * Try to preallocate enough space based on how big the block group is.
2469 * Keep in mind this has to include any pinned space which could end up
2470 * taking up quite a bit since it's not folded into the other space
2473 num_pages = div_u64(block_group->length, SZ_256M);
2478 num_pages *= PAGE_SIZE;
2480 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
2485 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2486 num_pages, num_pages,
2489 * Our cache requires contiguous chunks so that we don't modify a bunch
2490 * of metadata or split extents when writing the cache out, which means
2491 * we can enospc if we are heavily fragmented in addition to just normal
2492 * out of space conditions. So if we hit this just skip setting up any
2493 * other block groups for this transaction, maybe we'll unpin enough
2494 * space the next time around.
2497 dcs = BTRFS_DC_SETUP;
2498 else if (ret == -ENOSPC)
2499 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2504 btrfs_release_path(path);
2506 spin_lock(&block_group->lock);
2507 if (!ret && dcs == BTRFS_DC_SETUP)
2508 block_group->cache_generation = trans->transid;
2509 block_group->disk_cache_state = dcs;
2510 spin_unlock(&block_group->lock);
2512 extent_changeset_free(data_reserved);
2516 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2518 struct btrfs_fs_info *fs_info = trans->fs_info;
2519 struct btrfs_block_group *cache, *tmp;
2520 struct btrfs_transaction *cur_trans = trans->transaction;
2521 struct btrfs_path *path;
2523 if (list_empty(&cur_trans->dirty_bgs) ||
2524 !btrfs_test_opt(fs_info, SPACE_CACHE))
2527 path = btrfs_alloc_path();
2531 /* Could add new block groups, use _safe just in case */
2532 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2534 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2535 cache_save_setup(cache, trans, path);
2538 btrfs_free_path(path);
2543 * Transaction commit does final block group cache writeback during a critical
2544 * section where nothing is allowed to change the FS. This is required in
2545 * order for the cache to actually match the block group, but can introduce a
2546 * lot of latency into the commit.
2548 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2549 * There's a chance we'll have to redo some of it if the block group changes
2550 * again during the commit, but it greatly reduces the commit latency by
2551 * getting rid of the easy block groups while we're still allowing others to
2554 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2556 struct btrfs_fs_info *fs_info = trans->fs_info;
2557 struct btrfs_block_group *cache;
2558 struct btrfs_transaction *cur_trans = trans->transaction;
2561 struct btrfs_path *path = NULL;
2563 struct list_head *io = &cur_trans->io_bgs;
2564 int num_started = 0;
2567 spin_lock(&cur_trans->dirty_bgs_lock);
2568 if (list_empty(&cur_trans->dirty_bgs)) {
2569 spin_unlock(&cur_trans->dirty_bgs_lock);
2572 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2573 spin_unlock(&cur_trans->dirty_bgs_lock);
2576 /* Make sure all the block groups on our dirty list actually exist */
2577 btrfs_create_pending_block_groups(trans);
2580 path = btrfs_alloc_path();
2586 * cache_write_mutex is here only to save us from balance or automatic
2587 * removal of empty block groups deleting this block group while we are
2588 * writing out the cache
2590 mutex_lock(&trans->transaction->cache_write_mutex);
2591 while (!list_empty(&dirty)) {
2592 bool drop_reserve = true;
2594 cache = list_first_entry(&dirty, struct btrfs_block_group,
2597 * This can happen if something re-dirties a block group that
2598 * is already under IO. Just wait for it to finish and then do
2601 if (!list_empty(&cache->io_list)) {
2602 list_del_init(&cache->io_list);
2603 btrfs_wait_cache_io(trans, cache, path);
2604 btrfs_put_block_group(cache);
2609 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
2610 * it should update the cache_state. Don't delete until after
2613 * Since we're not running in the commit critical section
2614 * we need the dirty_bgs_lock to protect from update_block_group
2616 spin_lock(&cur_trans->dirty_bgs_lock);
2617 list_del_init(&cache->dirty_list);
2618 spin_unlock(&cur_trans->dirty_bgs_lock);
2622 cache_save_setup(cache, trans, path);
2624 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
2625 cache->io_ctl.inode = NULL;
2626 ret = btrfs_write_out_cache(trans, cache, path);
2627 if (ret == 0 && cache->io_ctl.inode) {
2632 * The cache_write_mutex is protecting the
2633 * io_list, also refer to the definition of
2634 * btrfs_transaction::io_bgs for more details
2636 list_add_tail(&cache->io_list, io);
2639 * If we failed to write the cache, the
2640 * generation will be bad and life goes on
2646 ret = update_block_group_item(trans, path, cache);
2648 * Our block group might still be attached to the list
2649 * of new block groups in the transaction handle of some
2650 * other task (struct btrfs_trans_handle->new_bgs). This
2651 * means its block group item isn't yet in the extent
2652 * tree. If this happens ignore the error, as we will
2653 * try again later in the critical section of the
2654 * transaction commit.
2656 if (ret == -ENOENT) {
2658 spin_lock(&cur_trans->dirty_bgs_lock);
2659 if (list_empty(&cache->dirty_list)) {
2660 list_add_tail(&cache->dirty_list,
2661 &cur_trans->dirty_bgs);
2662 btrfs_get_block_group(cache);
2663 drop_reserve = false;
2665 spin_unlock(&cur_trans->dirty_bgs_lock);
2667 btrfs_abort_transaction(trans, ret);
2671 /* If it's not on the io list, we need to put the block group */
2673 btrfs_put_block_group(cache);
2675 btrfs_delayed_refs_rsv_release(fs_info, 1);
2681 * Avoid blocking other tasks for too long. It might even save
2682 * us from writing caches for block groups that are going to be
2685 mutex_unlock(&trans->transaction->cache_write_mutex);
2686 mutex_lock(&trans->transaction->cache_write_mutex);
2688 mutex_unlock(&trans->transaction->cache_write_mutex);
2691 * Go through delayed refs for all the stuff we've just kicked off
2692 * and then loop back (just once)
2694 ret = btrfs_run_delayed_refs(trans, 0);
2695 if (!ret && loops == 0) {
2697 spin_lock(&cur_trans->dirty_bgs_lock);
2698 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2700 * dirty_bgs_lock protects us from concurrent block group
2701 * deletes too (not just cache_write_mutex).
2703 if (!list_empty(&dirty)) {
2704 spin_unlock(&cur_trans->dirty_bgs_lock);
2707 spin_unlock(&cur_trans->dirty_bgs_lock);
2708 } else if (ret < 0) {
2709 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
2712 btrfs_free_path(path);
2716 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
2718 struct btrfs_fs_info *fs_info = trans->fs_info;
2719 struct btrfs_block_group *cache;
2720 struct btrfs_transaction *cur_trans = trans->transaction;
2723 struct btrfs_path *path;
2724 struct list_head *io = &cur_trans->io_bgs;
2725 int num_started = 0;
2727 path = btrfs_alloc_path();
2732 * Even though we are in the critical section of the transaction commit,
2733 * we can still have concurrent tasks adding elements to this
2734 * transaction's list of dirty block groups. These tasks correspond to
2735 * endio free space workers started when writeback finishes for a
2736 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
2737 * allocate new block groups as a result of COWing nodes of the root
2738 * tree when updating the free space inode. The writeback for the space
2739 * caches is triggered by an earlier call to
2740 * btrfs_start_dirty_block_groups() and iterations of the following
2742 * Also we want to do the cache_save_setup first and then run the
2743 * delayed refs to make sure we have the best chance at doing this all
2746 spin_lock(&cur_trans->dirty_bgs_lock);
2747 while (!list_empty(&cur_trans->dirty_bgs)) {
2748 cache = list_first_entry(&cur_trans->dirty_bgs,
2749 struct btrfs_block_group,
2753 * This can happen if cache_save_setup re-dirties a block group
2754 * that is already under IO. Just wait for it to finish and
2755 * then do it all again
2757 if (!list_empty(&cache->io_list)) {
2758 spin_unlock(&cur_trans->dirty_bgs_lock);
2759 list_del_init(&cache->io_list);
2760 btrfs_wait_cache_io(trans, cache, path);
2761 btrfs_put_block_group(cache);
2762 spin_lock(&cur_trans->dirty_bgs_lock);
2766 * Don't remove from the dirty list until after we've waited on
2769 list_del_init(&cache->dirty_list);
2770 spin_unlock(&cur_trans->dirty_bgs_lock);
2773 cache_save_setup(cache, trans, path);
2776 ret = btrfs_run_delayed_refs(trans,
2777 (unsigned long) -1);
2779 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
2780 cache->io_ctl.inode = NULL;
2781 ret = btrfs_write_out_cache(trans, cache, path);
2782 if (ret == 0 && cache->io_ctl.inode) {
2785 list_add_tail(&cache->io_list, io);
2788 * If we failed to write the cache, the
2789 * generation will be bad and life goes on
2795 ret = update_block_group_item(trans, path, cache);
2797 * One of the free space endio workers might have
2798 * created a new block group while updating a free space
2799 * cache's inode (at inode.c:btrfs_finish_ordered_io())
2800 * and hasn't released its transaction handle yet, in
2801 * which case the new block group is still attached to
2802 * its transaction handle and its creation has not
2803 * finished yet (no block group item in the extent tree
2804 * yet, etc). If this is the case, wait for all free
2805 * space endio workers to finish and retry. This is a
2806 * very rare case so no need for a more efficient and
2809 if (ret == -ENOENT) {
2810 wait_event(cur_trans->writer_wait,
2811 atomic_read(&cur_trans->num_writers) == 1);
2812 ret = update_block_group_item(trans, path, cache);
2815 btrfs_abort_transaction(trans, ret);
2818 /* If its not on the io list, we need to put the block group */
2820 btrfs_put_block_group(cache);
2821 btrfs_delayed_refs_rsv_release(fs_info, 1);
2822 spin_lock(&cur_trans->dirty_bgs_lock);
2824 spin_unlock(&cur_trans->dirty_bgs_lock);
2827 * Refer to the definition of io_bgs member for details why it's safe
2828 * to use it without any locking
2830 while (!list_empty(io)) {
2831 cache = list_first_entry(io, struct btrfs_block_group,
2833 list_del_init(&cache->io_list);
2834 btrfs_wait_cache_io(trans, cache, path);
2835 btrfs_put_block_group(cache);
2838 btrfs_free_path(path);
2842 int btrfs_update_block_group(struct btrfs_trans_handle *trans,
2843 u64 bytenr, u64 num_bytes, int alloc)
2845 struct btrfs_fs_info *info = trans->fs_info;
2846 struct btrfs_block_group *cache = NULL;
2847 u64 total = num_bytes;
2853 /* Block accounting for super block */
2854 spin_lock(&info->delalloc_root_lock);
2855 old_val = btrfs_super_bytes_used(info->super_copy);
2857 old_val += num_bytes;
2859 old_val -= num_bytes;
2860 btrfs_set_super_bytes_used(info->super_copy, old_val);
2861 spin_unlock(&info->delalloc_root_lock);
2864 cache = btrfs_lookup_block_group(info, bytenr);
2869 factor = btrfs_bg_type_to_factor(cache->flags);
2872 * If this block group has free space cache written out, we
2873 * need to make sure to load it if we are removing space. This
2874 * is because we need the unpinning stage to actually add the
2875 * space back to the block group, otherwise we will leak space.
2877 if (!alloc && !btrfs_block_group_done(cache))
2878 btrfs_cache_block_group(cache, 1);
2880 byte_in_group = bytenr - cache->start;
2881 WARN_ON(byte_in_group > cache->length);
2883 spin_lock(&cache->space_info->lock);
2884 spin_lock(&cache->lock);
2886 if (btrfs_test_opt(info, SPACE_CACHE) &&
2887 cache->disk_cache_state < BTRFS_DC_CLEAR)
2888 cache->disk_cache_state = BTRFS_DC_CLEAR;
2890 old_val = cache->used;
2891 num_bytes = min(total, cache->length - byte_in_group);
2893 old_val += num_bytes;
2894 cache->used = old_val;
2895 cache->reserved -= num_bytes;
2896 cache->space_info->bytes_reserved -= num_bytes;
2897 cache->space_info->bytes_used += num_bytes;
2898 cache->space_info->disk_used += num_bytes * factor;
2899 spin_unlock(&cache->lock);
2900 spin_unlock(&cache->space_info->lock);
2902 old_val -= num_bytes;
2903 cache->used = old_val;
2904 cache->pinned += num_bytes;
2905 btrfs_space_info_update_bytes_pinned(info,
2906 cache->space_info, num_bytes);
2907 cache->space_info->bytes_used -= num_bytes;
2908 cache->space_info->disk_used -= num_bytes * factor;
2909 spin_unlock(&cache->lock);
2910 spin_unlock(&cache->space_info->lock);
2912 percpu_counter_add_batch(
2913 &cache->space_info->total_bytes_pinned,
2915 BTRFS_TOTAL_BYTES_PINNED_BATCH);
2916 set_extent_dirty(&trans->transaction->pinned_extents,
2917 bytenr, bytenr + num_bytes - 1,
2918 GFP_NOFS | __GFP_NOFAIL);
2921 spin_lock(&trans->transaction->dirty_bgs_lock);
2922 if (list_empty(&cache->dirty_list)) {
2923 list_add_tail(&cache->dirty_list,
2924 &trans->transaction->dirty_bgs);
2925 trans->delayed_ref_updates++;
2926 btrfs_get_block_group(cache);
2928 spin_unlock(&trans->transaction->dirty_bgs_lock);
2931 * No longer have used bytes in this block group, queue it for
2932 * deletion. We do this after adding the block group to the
2933 * dirty list to avoid races between cleaner kthread and space
2936 if (!alloc && old_val == 0) {
2937 if (!btrfs_test_opt(info, DISCARD_ASYNC))
2938 btrfs_mark_bg_unused(cache);
2941 btrfs_put_block_group(cache);
2943 bytenr += num_bytes;
2946 /* Modified block groups are accounted for in the delayed_refs_rsv. */
2947 btrfs_update_delayed_refs_rsv(trans);
2952 * btrfs_add_reserved_bytes - update the block_group and space info counters
2953 * @cache: The cache we are manipulating
2954 * @ram_bytes: The number of bytes of file content, and will be same to
2955 * @num_bytes except for the compress path.
2956 * @num_bytes: The number of bytes in question
2957 * @delalloc: The blocks are allocated for the delalloc write
2959 * This is called by the allocator when it reserves space. If this is a
2960 * reservation and the block group has become read only we cannot make the
2961 * reservation and return -EAGAIN, otherwise this function always succeeds.
2963 int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
2964 u64 ram_bytes, u64 num_bytes, int delalloc)
2966 struct btrfs_space_info *space_info = cache->space_info;
2969 spin_lock(&space_info->lock);
2970 spin_lock(&cache->lock);
2974 cache->reserved += num_bytes;
2975 space_info->bytes_reserved += num_bytes;
2976 trace_btrfs_space_reservation(cache->fs_info, "space_info",
2977 space_info->flags, num_bytes, 1);
2978 btrfs_space_info_update_bytes_may_use(cache->fs_info,
2979 space_info, -ram_bytes);
2981 cache->delalloc_bytes += num_bytes;
2984 * Compression can use less space than we reserved, so wake
2985 * tickets if that happens
2987 if (num_bytes < ram_bytes)
2988 btrfs_try_granting_tickets(cache->fs_info, space_info);
2990 spin_unlock(&cache->lock);
2991 spin_unlock(&space_info->lock);
2996 * btrfs_free_reserved_bytes - update the block_group and space info counters
2997 * @cache: The cache we are manipulating
2998 * @num_bytes: The number of bytes in question
2999 * @delalloc: The blocks are allocated for the delalloc write
3001 * This is called by somebody who is freeing space that was never actually used
3002 * on disk. For example if you reserve some space for a new leaf in transaction
3003 * A and before transaction A commits you free that leaf, you call this with
3004 * reserve set to 0 in order to clear the reservation.
3006 void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
3007 u64 num_bytes, int delalloc)
3009 struct btrfs_space_info *space_info = cache->space_info;
3011 spin_lock(&space_info->lock);
3012 spin_lock(&cache->lock);
3014 space_info->bytes_readonly += num_bytes;
3015 cache->reserved -= num_bytes;
3016 space_info->bytes_reserved -= num_bytes;
3017 space_info->max_extent_size = 0;
3020 cache->delalloc_bytes -= num_bytes;
3021 spin_unlock(&cache->lock);
3023 btrfs_try_granting_tickets(cache->fs_info, space_info);
3024 spin_unlock(&space_info->lock);
3027 static void force_metadata_allocation(struct btrfs_fs_info *info)
3029 struct list_head *head = &info->space_info;
3030 struct btrfs_space_info *found;
3032 list_for_each_entry(found, head, list) {
3033 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3034 found->force_alloc = CHUNK_ALLOC_FORCE;
3038 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3039 struct btrfs_space_info *sinfo, int force)
3041 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3044 if (force == CHUNK_ALLOC_FORCE)
3048 * in limited mode, we want to have some free space up to
3049 * about 1% of the FS size.
3051 if (force == CHUNK_ALLOC_LIMITED) {
3052 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3053 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3055 if (sinfo->total_bytes - bytes_used < thresh)
3059 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3064 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3066 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3068 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3072 * If force is CHUNK_ALLOC_FORCE:
3073 * - return 1 if it successfully allocates a chunk,
3074 * - return errors including -ENOSPC otherwise.
3075 * If force is NOT CHUNK_ALLOC_FORCE:
3076 * - return 0 if it doesn't need to allocate a new chunk,
3077 * - return 1 if it successfully allocates a chunk,
3078 * - return errors including -ENOSPC otherwise.
3080 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3081 enum btrfs_chunk_alloc_enum force)
3083 struct btrfs_fs_info *fs_info = trans->fs_info;
3084 struct btrfs_space_info *space_info;
3085 bool wait_for_alloc = false;
3086 bool should_alloc = false;
3089 /* Don't re-enter if we're already allocating a chunk */
3090 if (trans->allocating_chunk)
3093 space_info = btrfs_find_space_info(fs_info, flags);
3097 spin_lock(&space_info->lock);
3098 if (force < space_info->force_alloc)
3099 force = space_info->force_alloc;
3100 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3101 if (space_info->full) {
3102 /* No more free physical space */
3107 spin_unlock(&space_info->lock);
3109 } else if (!should_alloc) {
3110 spin_unlock(&space_info->lock);
3112 } else if (space_info->chunk_alloc) {
3114 * Someone is already allocating, so we need to block
3115 * until this someone is finished and then loop to
3116 * recheck if we should continue with our allocation
3119 wait_for_alloc = true;
3120 spin_unlock(&space_info->lock);
3121 mutex_lock(&fs_info->chunk_mutex);
3122 mutex_unlock(&fs_info->chunk_mutex);
3124 /* Proceed with allocation */
3125 space_info->chunk_alloc = 1;
3126 wait_for_alloc = false;
3127 spin_unlock(&space_info->lock);
3131 } while (wait_for_alloc);
3133 mutex_lock(&fs_info->chunk_mutex);
3134 trans->allocating_chunk = true;
3137 * If we have mixed data/metadata chunks we want to make sure we keep
3138 * allocating mixed chunks instead of individual chunks.
3140 if (btrfs_mixed_space_info(space_info))
3141 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3144 * if we're doing a data chunk, go ahead and make sure that
3145 * we keep a reasonable number of metadata chunks allocated in the
3148 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3149 fs_info->data_chunk_allocations++;
3150 if (!(fs_info->data_chunk_allocations %
3151 fs_info->metadata_ratio))
3152 force_metadata_allocation(fs_info);
3156 * Check if we have enough space in SYSTEM chunk because we may need
3157 * to update devices.
3159 check_system_chunk(trans, flags);
3161 ret = btrfs_alloc_chunk(trans, flags);
3162 trans->allocating_chunk = false;
3164 spin_lock(&space_info->lock);
3167 space_info->full = 1;
3172 space_info->max_extent_size = 0;
3175 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3177 space_info->chunk_alloc = 0;
3178 spin_unlock(&space_info->lock);
3179 mutex_unlock(&fs_info->chunk_mutex);
3181 * When we allocate a new chunk we reserve space in the chunk block
3182 * reserve to make sure we can COW nodes/leafs in the chunk tree or
3183 * add new nodes/leafs to it if we end up needing to do it when
3184 * inserting the chunk item and updating device items as part of the
3185 * second phase of chunk allocation, performed by
3186 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
3187 * large number of new block groups to create in our transaction
3188 * handle's new_bgs list to avoid exhausting the chunk block reserve
3189 * in extreme cases - like having a single transaction create many new
3190 * block groups when starting to write out the free space caches of all
3191 * the block groups that were made dirty during the lifetime of the
3194 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
3195 btrfs_create_pending_block_groups(trans);
3200 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3204 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3206 num_dev = fs_info->fs_devices->rw_devices;
3212 * Reserve space in the system space for allocating or removing a chunk
3214 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3216 struct btrfs_fs_info *fs_info = trans->fs_info;
3217 struct btrfs_space_info *info;
3224 * Needed because we can end up allocating a system chunk and for an
3225 * atomic and race free space reservation in the chunk block reserve.
3227 lockdep_assert_held(&fs_info->chunk_mutex);
3229 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3230 spin_lock(&info->lock);
3231 left = info->total_bytes - btrfs_space_info_used(info, true);
3232 spin_unlock(&info->lock);
3234 num_devs = get_profile_num_devs(fs_info, type);
3236 /* num_devs device items to update and 1 chunk item to add or remove */
3237 thresh = btrfs_calc_metadata_size(fs_info, num_devs) +
3238 btrfs_calc_insert_metadata_size(fs_info, 1);
3240 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3241 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3242 left, thresh, type);
3243 btrfs_dump_space_info(fs_info, info, 0, 0);
3246 if (left < thresh) {
3247 u64 flags = btrfs_system_alloc_profile(fs_info);
3250 * Ignore failure to create system chunk. We might end up not
3251 * needing it, as we might not need to COW all nodes/leafs from
3252 * the paths we visit in the chunk tree (they were already COWed
3253 * or created in the current transaction for example).
3255 ret = btrfs_alloc_chunk(trans, flags);
3259 ret = btrfs_block_rsv_add(fs_info->chunk_root,
3260 &fs_info->chunk_block_rsv,
3261 thresh, BTRFS_RESERVE_NO_FLUSH);
3263 trans->chunk_bytes_reserved += thresh;
3267 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3269 struct btrfs_block_group *block_group;
3273 struct inode *inode;
3275 block_group = btrfs_lookup_first_block_group(info, last);
3276 while (block_group) {
3277 btrfs_wait_block_group_cache_done(block_group);
3278 spin_lock(&block_group->lock);
3279 if (block_group->iref)
3281 spin_unlock(&block_group->lock);
3282 block_group = btrfs_next_block_group(block_group);
3291 inode = block_group->inode;
3292 block_group->iref = 0;
3293 block_group->inode = NULL;
3294 spin_unlock(&block_group->lock);
3295 ASSERT(block_group->io_ctl.inode == NULL);
3297 last = block_group->start + block_group->length;
3298 btrfs_put_block_group(block_group);
3303 * Must be called only after stopping all workers, since we could have block
3304 * group caching kthreads running, and therefore they could race with us if we
3305 * freed the block groups before stopping them.
3307 int btrfs_free_block_groups(struct btrfs_fs_info *info)
3309 struct btrfs_block_group *block_group;
3310 struct btrfs_space_info *space_info;
3311 struct btrfs_caching_control *caching_ctl;
3314 spin_lock(&info->block_group_cache_lock);
3315 while (!list_empty(&info->caching_block_groups)) {
3316 caching_ctl = list_entry(info->caching_block_groups.next,
3317 struct btrfs_caching_control, list);
3318 list_del(&caching_ctl->list);
3319 btrfs_put_caching_control(caching_ctl);
3321 spin_unlock(&info->block_group_cache_lock);
3323 spin_lock(&info->unused_bgs_lock);
3324 while (!list_empty(&info->unused_bgs)) {
3325 block_group = list_first_entry(&info->unused_bgs,
3326 struct btrfs_block_group,
3328 list_del_init(&block_group->bg_list);
3329 btrfs_put_block_group(block_group);
3331 spin_unlock(&info->unused_bgs_lock);
3333 spin_lock(&info->block_group_cache_lock);
3334 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
3335 block_group = rb_entry(n, struct btrfs_block_group,
3337 rb_erase(&block_group->cache_node,
3338 &info->block_group_cache_tree);
3339 RB_CLEAR_NODE(&block_group->cache_node);
3340 spin_unlock(&info->block_group_cache_lock);
3342 down_write(&block_group->space_info->groups_sem);
3343 list_del(&block_group->list);
3344 up_write(&block_group->space_info->groups_sem);
3347 * We haven't cached this block group, which means we could
3348 * possibly have excluded extents on this block group.
3350 if (block_group->cached == BTRFS_CACHE_NO ||
3351 block_group->cached == BTRFS_CACHE_ERROR)
3352 btrfs_free_excluded_extents(block_group);
3354 btrfs_remove_free_space_cache(block_group);
3355 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
3356 ASSERT(list_empty(&block_group->dirty_list));
3357 ASSERT(list_empty(&block_group->io_list));
3358 ASSERT(list_empty(&block_group->bg_list));
3359 ASSERT(refcount_read(&block_group->refs) == 1);
3360 btrfs_put_block_group(block_group);
3362 spin_lock(&info->block_group_cache_lock);
3364 spin_unlock(&info->block_group_cache_lock);
3366 btrfs_release_global_block_rsv(info);
3368 while (!list_empty(&info->space_info)) {
3369 space_info = list_entry(info->space_info.next,
3370 struct btrfs_space_info,
3374 * Do not hide this behind enospc_debug, this is actually
3375 * important and indicates a real bug if this happens.
3377 if (WARN_ON(space_info->bytes_pinned > 0 ||
3378 space_info->bytes_reserved > 0 ||
3379 space_info->bytes_may_use > 0))
3380 btrfs_dump_space_info(info, space_info, 0, 0);
3381 WARN_ON(space_info->reclaim_size > 0);
3382 list_del(&space_info->list);
3383 btrfs_sysfs_remove_space_info(space_info);
3388 void btrfs_freeze_block_group(struct btrfs_block_group *cache)
3390 atomic_inc(&cache->frozen);
3393 void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
3395 struct btrfs_fs_info *fs_info = block_group->fs_info;
3396 struct extent_map_tree *em_tree;
3397 struct extent_map *em;
3400 spin_lock(&block_group->lock);
3401 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
3402 block_group->removed);
3403 spin_unlock(&block_group->lock);
3406 em_tree = &fs_info->mapping_tree;
3407 write_lock(&em_tree->lock);
3408 em = lookup_extent_mapping(em_tree, block_group->start,
3410 BUG_ON(!em); /* logic error, can't happen */
3411 remove_extent_mapping(em_tree, em);
3412 write_unlock(&em_tree->lock);
3414 /* once for us and once for the tree */
3415 free_extent_map(em);
3416 free_extent_map(em);
3419 * We may have left one free space entry and other possible
3420 * tasks trimming this block group have left 1 entry each one.
3423 __btrfs_remove_free_space_cache(block_group->free_space_ctl);