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);
677 * If we are in the transaction that populated the free space tree we
678 * can't actually cache from the free space tree as our commit root and
679 * real root are the same, so we could change the contents of the blocks
680 * while caching. Instead do the slow caching in this case, and after
681 * the transaction has committed we will be safe.
683 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
684 !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
685 ret = load_free_space_tree(caching_ctl);
687 ret = load_extent_tree_free(caching_ctl);
689 spin_lock(&block_group->lock);
690 block_group->caching_ctl = NULL;
691 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
692 spin_unlock(&block_group->lock);
694 #ifdef CONFIG_BTRFS_DEBUG
695 if (btrfs_should_fragment_free_space(block_group)) {
698 spin_lock(&block_group->space_info->lock);
699 spin_lock(&block_group->lock);
700 bytes_used = block_group->length - block_group->used;
701 block_group->space_info->bytes_used += bytes_used >> 1;
702 spin_unlock(&block_group->lock);
703 spin_unlock(&block_group->space_info->lock);
704 fragment_free_space(block_group);
708 caching_ctl->progress = (u64)-1;
710 up_read(&fs_info->commit_root_sem);
711 btrfs_free_excluded_extents(block_group);
712 mutex_unlock(&caching_ctl->mutex);
714 wake_up(&caching_ctl->wait);
716 btrfs_put_caching_control(caching_ctl);
717 btrfs_put_block_group(block_group);
720 int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
723 struct btrfs_fs_info *fs_info = cache->fs_info;
724 struct btrfs_caching_control *caching_ctl = NULL;
727 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
731 INIT_LIST_HEAD(&caching_ctl->list);
732 mutex_init(&caching_ctl->mutex);
733 init_waitqueue_head(&caching_ctl->wait);
734 caching_ctl->block_group = cache;
735 caching_ctl->progress = cache->start;
736 refcount_set(&caching_ctl->count, 2);
737 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
739 spin_lock(&cache->lock);
740 if (cache->cached != BTRFS_CACHE_NO) {
743 caching_ctl = cache->caching_ctl;
745 refcount_inc(&caching_ctl->count);
746 spin_unlock(&cache->lock);
749 WARN_ON(cache->caching_ctl);
750 cache->caching_ctl = caching_ctl;
751 if (btrfs_test_opt(fs_info, SPACE_CACHE))
752 cache->cached = BTRFS_CACHE_FAST;
754 cache->cached = BTRFS_CACHE_STARTED;
755 cache->has_caching_ctl = 1;
756 spin_unlock(&cache->lock);
758 spin_lock(&fs_info->block_group_cache_lock);
759 refcount_inc(&caching_ctl->count);
760 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
761 spin_unlock(&fs_info->block_group_cache_lock);
763 btrfs_get_block_group(cache);
765 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
767 if (load_cache_only && caching_ctl)
768 btrfs_wait_space_cache_v1_finished(cache, caching_ctl);
770 btrfs_put_caching_control(caching_ctl);
775 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
777 u64 extra_flags = chunk_to_extended(flags) &
778 BTRFS_EXTENDED_PROFILE_MASK;
780 write_seqlock(&fs_info->profiles_lock);
781 if (flags & BTRFS_BLOCK_GROUP_DATA)
782 fs_info->avail_data_alloc_bits &= ~extra_flags;
783 if (flags & BTRFS_BLOCK_GROUP_METADATA)
784 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
785 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
786 fs_info->avail_system_alloc_bits &= ~extra_flags;
787 write_sequnlock(&fs_info->profiles_lock);
791 * Clear incompat bits for the following feature(s):
793 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
794 * in the whole filesystem
796 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
798 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
800 bool found_raid56 = false;
801 bool found_raid1c34 = false;
803 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
804 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
805 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
806 struct list_head *head = &fs_info->space_info;
807 struct btrfs_space_info *sinfo;
809 list_for_each_entry_rcu(sinfo, head, list) {
810 down_read(&sinfo->groups_sem);
811 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
813 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
815 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
816 found_raid1c34 = true;
817 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
818 found_raid1c34 = true;
819 up_read(&sinfo->groups_sem);
822 btrfs_clear_fs_incompat(fs_info, RAID56);
824 btrfs_clear_fs_incompat(fs_info, RAID1C34);
828 static int remove_block_group_item(struct btrfs_trans_handle *trans,
829 struct btrfs_path *path,
830 struct btrfs_block_group *block_group)
832 struct btrfs_fs_info *fs_info = trans->fs_info;
833 struct btrfs_root *root;
834 struct btrfs_key key;
837 root = fs_info->extent_root;
838 key.objectid = block_group->start;
839 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
840 key.offset = block_group->length;
842 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
848 ret = btrfs_del_item(trans, root, path);
852 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
853 u64 group_start, struct extent_map *em)
855 struct btrfs_fs_info *fs_info = trans->fs_info;
856 struct btrfs_path *path;
857 struct btrfs_block_group *block_group;
858 struct btrfs_free_cluster *cluster;
860 struct kobject *kobj = NULL;
864 struct btrfs_caching_control *caching_ctl = NULL;
866 bool remove_rsv = false;
868 block_group = btrfs_lookup_block_group(fs_info, group_start);
869 BUG_ON(!block_group);
870 BUG_ON(!block_group->ro);
872 trace_btrfs_remove_block_group(block_group);
874 * Free the reserved super bytes from this block group before
877 btrfs_free_excluded_extents(block_group);
878 btrfs_free_ref_tree_range(fs_info, block_group->start,
879 block_group->length);
881 index = btrfs_bg_flags_to_raid_index(block_group->flags);
882 factor = btrfs_bg_type_to_factor(block_group->flags);
884 /* make sure this block group isn't part of an allocation cluster */
885 cluster = &fs_info->data_alloc_cluster;
886 spin_lock(&cluster->refill_lock);
887 btrfs_return_cluster_to_free_space(block_group, cluster);
888 spin_unlock(&cluster->refill_lock);
891 * make sure this block group isn't part of a metadata
894 cluster = &fs_info->meta_alloc_cluster;
895 spin_lock(&cluster->refill_lock);
896 btrfs_return_cluster_to_free_space(block_group, cluster);
897 spin_unlock(&cluster->refill_lock);
899 path = btrfs_alloc_path();
906 * get the inode first so any iput calls done for the io_list
907 * aren't the final iput (no unlinks allowed now)
909 inode = lookup_free_space_inode(block_group, path);
911 mutex_lock(&trans->transaction->cache_write_mutex);
913 * Make sure our free space cache IO is done before removing the
916 spin_lock(&trans->transaction->dirty_bgs_lock);
917 if (!list_empty(&block_group->io_list)) {
918 list_del_init(&block_group->io_list);
920 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
922 spin_unlock(&trans->transaction->dirty_bgs_lock);
923 btrfs_wait_cache_io(trans, block_group, path);
924 btrfs_put_block_group(block_group);
925 spin_lock(&trans->transaction->dirty_bgs_lock);
928 if (!list_empty(&block_group->dirty_list)) {
929 list_del_init(&block_group->dirty_list);
931 btrfs_put_block_group(block_group);
933 spin_unlock(&trans->transaction->dirty_bgs_lock);
934 mutex_unlock(&trans->transaction->cache_write_mutex);
936 ret = btrfs_remove_free_space_inode(trans, inode, block_group);
940 spin_lock(&fs_info->block_group_cache_lock);
941 rb_erase(&block_group->cache_node,
942 &fs_info->block_group_cache_tree);
943 RB_CLEAR_NODE(&block_group->cache_node);
945 /* Once for the block groups rbtree */
946 btrfs_put_block_group(block_group);
948 if (fs_info->first_logical_byte == block_group->start)
949 fs_info->first_logical_byte = (u64)-1;
950 spin_unlock(&fs_info->block_group_cache_lock);
952 down_write(&block_group->space_info->groups_sem);
954 * we must use list_del_init so people can check to see if they
955 * are still on the list after taking the semaphore
957 list_del_init(&block_group->list);
958 if (list_empty(&block_group->space_info->block_groups[index])) {
959 kobj = block_group->space_info->block_group_kobjs[index];
960 block_group->space_info->block_group_kobjs[index] = NULL;
961 clear_avail_alloc_bits(fs_info, block_group->flags);
963 up_write(&block_group->space_info->groups_sem);
964 clear_incompat_bg_bits(fs_info, block_group->flags);
970 if (block_group->has_caching_ctl)
971 caching_ctl = btrfs_get_caching_control(block_group);
972 if (block_group->cached == BTRFS_CACHE_STARTED)
973 btrfs_wait_block_group_cache_done(block_group);
974 if (block_group->has_caching_ctl) {
975 spin_lock(&fs_info->block_group_cache_lock);
977 struct btrfs_caching_control *ctl;
979 list_for_each_entry(ctl,
980 &fs_info->caching_block_groups, list)
981 if (ctl->block_group == block_group) {
983 refcount_inc(&caching_ctl->count);
988 list_del_init(&caching_ctl->list);
989 spin_unlock(&fs_info->block_group_cache_lock);
991 /* Once for the caching bgs list and once for us. */
992 btrfs_put_caching_control(caching_ctl);
993 btrfs_put_caching_control(caching_ctl);
997 spin_lock(&trans->transaction->dirty_bgs_lock);
998 WARN_ON(!list_empty(&block_group->dirty_list));
999 WARN_ON(!list_empty(&block_group->io_list));
1000 spin_unlock(&trans->transaction->dirty_bgs_lock);
1002 btrfs_remove_free_space_cache(block_group);
1004 spin_lock(&block_group->space_info->lock);
1005 list_del_init(&block_group->ro_list);
1007 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1008 WARN_ON(block_group->space_info->total_bytes
1009 < block_group->length);
1010 WARN_ON(block_group->space_info->bytes_readonly
1011 < block_group->length);
1012 WARN_ON(block_group->space_info->disk_total
1013 < block_group->length * factor);
1015 block_group->space_info->total_bytes -= block_group->length;
1016 block_group->space_info->bytes_readonly -= block_group->length;
1017 block_group->space_info->disk_total -= block_group->length * factor;
1019 spin_unlock(&block_group->space_info->lock);
1022 * Remove the free space for the block group from the free space tree
1023 * and the block group's item from the extent tree before marking the
1024 * block group as removed. This is to prevent races with tasks that
1025 * freeze and unfreeze a block group, this task and another task
1026 * allocating a new block group - the unfreeze task ends up removing
1027 * the block group's extent map before the task calling this function
1028 * deletes the block group item from the extent tree, allowing for
1029 * another task to attempt to create another block group with the same
1030 * item key (and failing with -EEXIST and a transaction abort).
1032 ret = remove_block_group_free_space(trans, block_group);
1036 ret = remove_block_group_item(trans, path, block_group);
1040 spin_lock(&block_group->lock);
1041 block_group->removed = 1;
1043 * At this point trimming or scrub can't start on this block group,
1044 * because we removed the block group from the rbtree
1045 * fs_info->block_group_cache_tree so no one can't find it anymore and
1046 * even if someone already got this block group before we removed it
1047 * from the rbtree, they have already incremented block_group->frozen -
1048 * if they didn't, for the trimming case they won't find any free space
1049 * entries because we already removed them all when we called
1050 * btrfs_remove_free_space_cache().
1052 * And we must not remove the extent map from the fs_info->mapping_tree
1053 * to prevent the same logical address range and physical device space
1054 * ranges from being reused for a new block group. This is needed to
1055 * avoid races with trimming and scrub.
1057 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1058 * completely transactionless, so while it is trimming a range the
1059 * currently running transaction might finish and a new one start,
1060 * allowing for new block groups to be created that can reuse the same
1061 * physical device locations unless we take this special care.
1063 * There may also be an implicit trim operation if the file system
1064 * is mounted with -odiscard. The same protections must remain
1065 * in place until the extents have been discarded completely when
1066 * the transaction commit has completed.
1068 remove_em = (atomic_read(&block_group->frozen) == 0);
1069 spin_unlock(&block_group->lock);
1072 struct extent_map_tree *em_tree;
1074 em_tree = &fs_info->mapping_tree;
1075 write_lock(&em_tree->lock);
1076 remove_extent_mapping(em_tree, em);
1077 write_unlock(&em_tree->lock);
1078 /* once for the tree */
1079 free_extent_map(em);
1083 /* Once for the lookup reference */
1084 btrfs_put_block_group(block_group);
1086 btrfs_delayed_refs_rsv_release(fs_info, 1);
1087 btrfs_free_path(path);
1091 struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1092 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1094 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1095 struct extent_map *em;
1096 struct map_lookup *map;
1097 unsigned int num_items;
1099 read_lock(&em_tree->lock);
1100 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1101 read_unlock(&em_tree->lock);
1102 ASSERT(em && em->start == chunk_offset);
1105 * We need to reserve 3 + N units from the metadata space info in order
1106 * to remove a block group (done at btrfs_remove_chunk() and at
1107 * btrfs_remove_block_group()), which are used for:
1109 * 1 unit for adding the free space inode's orphan (located in the tree
1111 * 1 unit for deleting the block group item (located in the extent
1113 * 1 unit for deleting the free space item (located in tree of tree
1115 * N units for deleting N device extent items corresponding to each
1116 * stripe (located in the device tree).
1118 * In order to remove a block group we also need to reserve units in the
1119 * system space info in order to update the chunk tree (update one or
1120 * more device items and remove one chunk item), but this is done at
1121 * btrfs_remove_chunk() through a call to check_system_chunk().
1123 map = em->map_lookup;
1124 num_items = 3 + map->num_stripes;
1125 free_extent_map(em);
1127 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
1132 * Mark block group @cache read-only, so later write won't happen to block
1135 * If @force is not set, this function will only mark the block group readonly
1136 * if we have enough free space (1M) in other metadata/system block groups.
1137 * If @force is not set, this function will mark the block group readonly
1138 * without checking free space.
1140 * NOTE: This function doesn't care if other block groups can contain all the
1141 * data in this block group. That check should be done by relocation routine,
1142 * not this function.
1144 static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
1146 struct btrfs_space_info *sinfo = cache->space_info;
1150 spin_lock(&sinfo->lock);
1151 spin_lock(&cache->lock);
1159 num_bytes = cache->length - cache->reserved - cache->pinned -
1160 cache->bytes_super - cache->used;
1163 * Data never overcommits, even in mixed mode, so do just the straight
1164 * check of left over space in how much we have allocated.
1168 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1169 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1172 * Here we make sure if we mark this bg RO, we still have enough
1173 * free space as buffer.
1175 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1179 * We overcommit metadata, so we need to do the
1180 * btrfs_can_overcommit check here, and we need to pass in
1181 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1182 * leeway to allow us to mark this block group as read only.
1184 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1185 BTRFS_RESERVE_NO_FLUSH))
1190 sinfo->bytes_readonly += num_bytes;
1192 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
1195 spin_unlock(&cache->lock);
1196 spin_unlock(&sinfo->lock);
1197 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1198 btrfs_info(cache->fs_info,
1199 "unable to make block group %llu ro", cache->start);
1200 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1205 static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1206 struct btrfs_block_group *bg)
1208 struct btrfs_fs_info *fs_info = bg->fs_info;
1209 struct btrfs_transaction *prev_trans = NULL;
1210 const u64 start = bg->start;
1211 const u64 end = start + bg->length - 1;
1214 spin_lock(&fs_info->trans_lock);
1215 if (trans->transaction->list.prev != &fs_info->trans_list) {
1216 prev_trans = list_last_entry(&trans->transaction->list,
1217 struct btrfs_transaction, list);
1218 refcount_inc(&prev_trans->use_count);
1220 spin_unlock(&fs_info->trans_lock);
1223 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1224 * btrfs_finish_extent_commit(). If we are at transaction N, another
1225 * task might be running finish_extent_commit() for the previous
1226 * transaction N - 1, and have seen a range belonging to the block
1227 * group in pinned_extents before we were able to clear the whole block
1228 * group range from pinned_extents. This means that task can lookup for
1229 * the block group after we unpinned it from pinned_extents and removed
1230 * it, leading to a BUG_ON() at unpin_extent_range().
1232 mutex_lock(&fs_info->unused_bg_unpin_mutex);
1234 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1240 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
1243 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1245 btrfs_put_transaction(prev_trans);
1251 * Process the unused_bgs list and remove any that don't have any allocated
1252 * space inside of them.
1254 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1256 struct btrfs_block_group *block_group;
1257 struct btrfs_space_info *space_info;
1258 struct btrfs_trans_handle *trans;
1259 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
1262 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1265 spin_lock(&fs_info->unused_bgs_lock);
1266 while (!list_empty(&fs_info->unused_bgs)) {
1269 block_group = list_first_entry(&fs_info->unused_bgs,
1270 struct btrfs_block_group,
1272 list_del_init(&block_group->bg_list);
1274 space_info = block_group->space_info;
1276 if (ret || btrfs_mixed_space_info(space_info)) {
1277 btrfs_put_block_group(block_group);
1280 spin_unlock(&fs_info->unused_bgs_lock);
1282 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1284 mutex_lock(&fs_info->delete_unused_bgs_mutex);
1286 /* Don't want to race with allocators so take the groups_sem */
1287 down_write(&space_info->groups_sem);
1290 * Async discard moves the final block group discard to be prior
1291 * to the unused_bgs code path. Therefore, if it's not fully
1292 * trimmed, punt it back to the async discard lists.
1294 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1295 !btrfs_is_free_space_trimmed(block_group)) {
1296 trace_btrfs_skip_unused_block_group(block_group);
1297 up_write(&space_info->groups_sem);
1298 /* Requeue if we failed because of async discard */
1299 btrfs_discard_queue_work(&fs_info->discard_ctl,
1304 spin_lock(&block_group->lock);
1305 if (block_group->reserved || block_group->pinned ||
1306 block_group->used || block_group->ro ||
1307 list_is_singular(&block_group->list)) {
1309 * We want to bail if we made new allocations or have
1310 * outstanding allocations in this block group. We do
1311 * the ro check in case balance is currently acting on
1314 trace_btrfs_skip_unused_block_group(block_group);
1315 spin_unlock(&block_group->lock);
1316 up_write(&space_info->groups_sem);
1319 spin_unlock(&block_group->lock);
1321 /* We don't want to force the issue, only flip if it's ok. */
1322 ret = inc_block_group_ro(block_group, 0);
1323 up_write(&space_info->groups_sem);
1330 * Want to do this before we do anything else so we can recover
1331 * properly if we fail to join the transaction.
1333 trans = btrfs_start_trans_remove_block_group(fs_info,
1334 block_group->start);
1335 if (IS_ERR(trans)) {
1336 btrfs_dec_block_group_ro(block_group);
1337 ret = PTR_ERR(trans);
1342 * We could have pending pinned extents for this block group,
1343 * just delete them, we don't care about them anymore.
1345 if (!clean_pinned_extents(trans, block_group)) {
1346 btrfs_dec_block_group_ro(block_group);
1351 * At this point, the block_group is read only and should fail
1352 * new allocations. However, btrfs_finish_extent_commit() can
1353 * cause this block_group to be placed back on the discard
1354 * lists because now the block_group isn't fully discarded.
1355 * Bail here and try again later after discarding everything.
1357 spin_lock(&fs_info->discard_ctl.lock);
1358 if (!list_empty(&block_group->discard_list)) {
1359 spin_unlock(&fs_info->discard_ctl.lock);
1360 btrfs_dec_block_group_ro(block_group);
1361 btrfs_discard_queue_work(&fs_info->discard_ctl,
1365 spin_unlock(&fs_info->discard_ctl.lock);
1367 /* Reset pinned so btrfs_put_block_group doesn't complain */
1368 spin_lock(&space_info->lock);
1369 spin_lock(&block_group->lock);
1371 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1372 -block_group->pinned);
1373 space_info->bytes_readonly += block_group->pinned;
1374 percpu_counter_add_batch(&space_info->total_bytes_pinned,
1375 -block_group->pinned,
1376 BTRFS_TOTAL_BYTES_PINNED_BATCH);
1377 block_group->pinned = 0;
1379 spin_unlock(&block_group->lock);
1380 spin_unlock(&space_info->lock);
1383 * The normal path here is an unused block group is passed here,
1384 * then trimming is handled in the transaction commit path.
1385 * Async discard interposes before this to do the trimming
1386 * before coming down the unused block group path as trimming
1387 * will no longer be done later in the transaction commit path.
1389 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1392 /* DISCARD can flip during remount */
1393 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC);
1395 /* Implicit trim during transaction commit. */
1397 btrfs_freeze_block_group(block_group);
1400 * Btrfs_remove_chunk will abort the transaction if things go
1403 ret = btrfs_remove_chunk(trans, block_group->start);
1407 btrfs_unfreeze_block_group(block_group);
1412 * If we're not mounted with -odiscard, we can just forget
1413 * about this block group. Otherwise we'll need to wait
1414 * until transaction commit to do the actual discard.
1417 spin_lock(&fs_info->unused_bgs_lock);
1419 * A concurrent scrub might have added us to the list
1420 * fs_info->unused_bgs, so use a list_move operation
1421 * to add the block group to the deleted_bgs list.
1423 list_move(&block_group->bg_list,
1424 &trans->transaction->deleted_bgs);
1425 spin_unlock(&fs_info->unused_bgs_lock);
1426 btrfs_get_block_group(block_group);
1429 btrfs_end_transaction(trans);
1431 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1432 btrfs_put_block_group(block_group);
1433 spin_lock(&fs_info->unused_bgs_lock);
1435 spin_unlock(&fs_info->unused_bgs_lock);
1439 btrfs_end_transaction(trans);
1440 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1441 btrfs_put_block_group(block_group);
1442 btrfs_discard_punt_unused_bgs_list(fs_info);
1445 void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
1447 struct btrfs_fs_info *fs_info = bg->fs_info;
1449 spin_lock(&fs_info->unused_bgs_lock);
1450 if (list_empty(&bg->bg_list)) {
1451 btrfs_get_block_group(bg);
1452 trace_btrfs_add_unused_block_group(bg);
1453 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1455 spin_unlock(&fs_info->unused_bgs_lock);
1458 static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1459 struct btrfs_path *path)
1461 struct extent_map_tree *em_tree;
1462 struct extent_map *em;
1463 struct btrfs_block_group_item bg;
1464 struct extent_buffer *leaf;
1469 slot = path->slots[0];
1470 leaf = path->nodes[0];
1472 em_tree = &fs_info->mapping_tree;
1473 read_lock(&em_tree->lock);
1474 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1475 read_unlock(&em_tree->lock);
1478 "logical %llu len %llu found bg but no related chunk",
1479 key->objectid, key->offset);
1483 if (em->start != key->objectid || em->len != key->offset) {
1485 "block group %llu len %llu mismatch with chunk %llu len %llu",
1486 key->objectid, key->offset, em->start, em->len);
1491 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1493 flags = btrfs_stack_block_group_flags(&bg) &
1494 BTRFS_BLOCK_GROUP_TYPE_MASK;
1496 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1498 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1499 key->objectid, key->offset, flags,
1500 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1505 free_extent_map(em);
1509 static int find_first_block_group(struct btrfs_fs_info *fs_info,
1510 struct btrfs_path *path,
1511 struct btrfs_key *key)
1513 struct btrfs_root *root = fs_info->extent_root;
1515 struct btrfs_key found_key;
1516 struct extent_buffer *leaf;
1519 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1524 slot = path->slots[0];
1525 leaf = path->nodes[0];
1526 if (slot >= btrfs_header_nritems(leaf)) {
1527 ret = btrfs_next_leaf(root, path);
1534 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1536 if (found_key.objectid >= key->objectid &&
1537 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1538 ret = read_bg_from_eb(fs_info, &found_key, path);
1548 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1550 u64 extra_flags = chunk_to_extended(flags) &
1551 BTRFS_EXTENDED_PROFILE_MASK;
1553 write_seqlock(&fs_info->profiles_lock);
1554 if (flags & BTRFS_BLOCK_GROUP_DATA)
1555 fs_info->avail_data_alloc_bits |= extra_flags;
1556 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1557 fs_info->avail_metadata_alloc_bits |= extra_flags;
1558 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1559 fs_info->avail_system_alloc_bits |= extra_flags;
1560 write_sequnlock(&fs_info->profiles_lock);
1564 * Map a physical disk address to a list of logical addresses
1566 * @fs_info: the filesystem
1567 * @chunk_start: logical address of block group
1568 * @physical: physical address to map to logical addresses
1569 * @logical: return array of logical addresses which map to @physical
1570 * @naddrs: length of @logical
1571 * @stripe_len: size of IO stripe for the given block group
1573 * Maps a particular @physical disk address to a list of @logical addresses.
1574 * Used primarily to exclude those portions of a block group that contain super
1578 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1579 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
1581 struct extent_map *em;
1582 struct map_lookup *map;
1585 u64 data_stripe_length;
1590 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1594 map = em->map_lookup;
1595 data_stripe_length = em->orig_block_len;
1596 io_stripe_size = map->stripe_len;
1598 /* For RAID5/6 adjust to a full IO stripe length */
1599 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
1600 io_stripe_size = map->stripe_len * nr_data_stripes(map);
1602 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
1608 for (i = 0; i < map->num_stripes; i++) {
1609 bool already_inserted = false;
1613 if (!in_range(physical, map->stripes[i].physical,
1614 data_stripe_length))
1617 stripe_nr = physical - map->stripes[i].physical;
1618 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
1620 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1621 stripe_nr = stripe_nr * map->num_stripes + i;
1622 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1623 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1624 stripe_nr = stripe_nr * map->num_stripes + i;
1627 * The remaining case would be for RAID56, multiply by
1628 * nr_data_stripes(). Alternatively, just use rmap_len below
1629 * instead of map->stripe_len
1632 bytenr = chunk_start + stripe_nr * io_stripe_size;
1634 /* Ensure we don't add duplicate addresses */
1635 for (j = 0; j < nr; j++) {
1636 if (buf[j] == bytenr) {
1637 already_inserted = true;
1642 if (!already_inserted)
1648 *stripe_len = io_stripe_size;
1650 free_extent_map(em);
1654 static int exclude_super_stripes(struct btrfs_block_group *cache)
1656 struct btrfs_fs_info *fs_info = cache->fs_info;
1657 const bool zoned = btrfs_is_zoned(fs_info);
1663 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1664 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
1665 cache->bytes_super += stripe_len;
1666 ret = btrfs_add_excluded_extent(fs_info, cache->start,
1672 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1673 bytenr = btrfs_sb_offset(i);
1674 ret = btrfs_rmap_block(fs_info, cache->start,
1675 bytenr, &logical, &nr, &stripe_len);
1679 /* Shouldn't have super stripes in sequential zones */
1682 "zoned: block group %llu must not contain super block",
1688 u64 len = min_t(u64, stripe_len,
1689 cache->start + cache->length - logical[nr]);
1691 cache->bytes_super += len;
1692 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
1705 static void link_block_group(struct btrfs_block_group *cache)
1707 struct btrfs_space_info *space_info = cache->space_info;
1708 int index = btrfs_bg_flags_to_raid_index(cache->flags);
1710 down_write(&space_info->groups_sem);
1711 list_add_tail(&cache->list, &space_info->block_groups[index]);
1712 up_write(&space_info->groups_sem);
1715 static struct btrfs_block_group *btrfs_create_block_group_cache(
1716 struct btrfs_fs_info *fs_info, u64 start)
1718 struct btrfs_block_group *cache;
1720 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1724 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1726 if (!cache->free_space_ctl) {
1731 cache->start = start;
1733 cache->fs_info = fs_info;
1734 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
1736 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1738 refcount_set(&cache->refs, 1);
1739 spin_lock_init(&cache->lock);
1740 init_rwsem(&cache->data_rwsem);
1741 INIT_LIST_HEAD(&cache->list);
1742 INIT_LIST_HEAD(&cache->cluster_list);
1743 INIT_LIST_HEAD(&cache->bg_list);
1744 INIT_LIST_HEAD(&cache->ro_list);
1745 INIT_LIST_HEAD(&cache->discard_list);
1746 INIT_LIST_HEAD(&cache->dirty_list);
1747 INIT_LIST_HEAD(&cache->io_list);
1748 btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
1749 atomic_set(&cache->frozen, 0);
1750 mutex_init(&cache->free_space_lock);
1751 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1757 * Iterate all chunks and verify that each of them has the corresponding block
1760 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1762 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1763 struct extent_map *em;
1764 struct btrfs_block_group *bg;
1769 read_lock(&map_tree->lock);
1771 * lookup_extent_mapping will return the first extent map
1772 * intersecting the range, so setting @len to 1 is enough to
1773 * get the first chunk.
1775 em = lookup_extent_mapping(map_tree, start, 1);
1776 read_unlock(&map_tree->lock);
1780 bg = btrfs_lookup_block_group(fs_info, em->start);
1783 "chunk start=%llu len=%llu doesn't have corresponding block group",
1784 em->start, em->len);
1786 free_extent_map(em);
1789 if (bg->start != em->start || bg->length != em->len ||
1790 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1791 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1793 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
1795 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
1796 bg->start, bg->length,
1797 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
1799 free_extent_map(em);
1800 btrfs_put_block_group(bg);
1803 start = em->start + em->len;
1804 free_extent_map(em);
1805 btrfs_put_block_group(bg);
1810 static void read_block_group_item(struct btrfs_block_group *cache,
1811 struct btrfs_path *path,
1812 const struct btrfs_key *key)
1814 struct extent_buffer *leaf = path->nodes[0];
1815 struct btrfs_block_group_item bgi;
1816 int slot = path->slots[0];
1818 cache->length = key->offset;
1820 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
1822 cache->used = btrfs_stack_block_group_used(&bgi);
1823 cache->flags = btrfs_stack_block_group_flags(&bgi);
1826 static int read_one_block_group(struct btrfs_fs_info *info,
1827 struct btrfs_path *path,
1828 const struct btrfs_key *key,
1831 struct btrfs_block_group *cache;
1832 struct btrfs_space_info *space_info;
1833 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
1836 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
1838 cache = btrfs_create_block_group_cache(info, key->objectid);
1842 read_block_group_item(cache, path, key);
1844 set_free_space_tree_thresholds(cache);
1848 * When we mount with old space cache, we need to
1849 * set BTRFS_DC_CLEAR and set dirty flag.
1851 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
1852 * truncate the old free space cache inode and
1854 * b) Setting 'dirty flag' makes sure that we flush
1855 * the new space cache info onto disk.
1857 if (btrfs_test_opt(info, SPACE_CACHE))
1858 cache->disk_cache_state = BTRFS_DC_CLEAR;
1860 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
1861 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
1863 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
1870 * We need to exclude the super stripes now so that the space info has
1871 * super bytes accounted for, otherwise we'll think we have more space
1872 * than we actually do.
1874 ret = exclude_super_stripes(cache);
1876 /* We may have excluded something, so call this just in case. */
1877 btrfs_free_excluded_extents(cache);
1882 * Check for two cases, either we are full, and therefore don't need
1883 * to bother with the caching work since we won't find any space, or we
1884 * are empty, and we can just add all the space in and be done with it.
1885 * This saves us _a_lot_ of time, particularly in the full case.
1887 if (cache->length == cache->used) {
1888 cache->last_byte_to_unpin = (u64)-1;
1889 cache->cached = BTRFS_CACHE_FINISHED;
1890 btrfs_free_excluded_extents(cache);
1891 } else if (cache->used == 0) {
1892 cache->last_byte_to_unpin = (u64)-1;
1893 cache->cached = BTRFS_CACHE_FINISHED;
1894 add_new_free_space(cache, cache->start,
1895 cache->start + cache->length);
1896 btrfs_free_excluded_extents(cache);
1899 ret = btrfs_add_block_group_cache(info, cache);
1901 btrfs_remove_free_space_cache(cache);
1904 trace_btrfs_add_block_group(info, cache, 0);
1905 btrfs_update_space_info(info, cache->flags, cache->length,
1906 cache->used, cache->bytes_super, &space_info);
1908 cache->space_info = space_info;
1910 link_block_group(cache);
1912 set_avail_alloc_bits(info, cache->flags);
1913 if (btrfs_chunk_readonly(info, cache->start)) {
1914 inc_block_group_ro(cache, 1);
1915 } else if (cache->used == 0) {
1916 ASSERT(list_empty(&cache->bg_list));
1917 if (btrfs_test_opt(info, DISCARD_ASYNC))
1918 btrfs_discard_queue_work(&info->discard_ctl, cache);
1920 btrfs_mark_bg_unused(cache);
1924 btrfs_put_block_group(cache);
1928 static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
1930 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1931 struct btrfs_space_info *space_info;
1932 struct rb_node *node;
1935 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
1936 struct extent_map *em;
1937 struct map_lookup *map;
1938 struct btrfs_block_group *bg;
1940 em = rb_entry(node, struct extent_map, rb_node);
1941 map = em->map_lookup;
1942 bg = btrfs_create_block_group_cache(fs_info, em->start);
1948 /* Fill dummy cache as FULL */
1949 bg->length = em->len;
1950 bg->flags = map->type;
1951 bg->last_byte_to_unpin = (u64)-1;
1952 bg->cached = BTRFS_CACHE_FINISHED;
1954 bg->flags = map->type;
1955 ret = btrfs_add_block_group_cache(fs_info, bg);
1957 btrfs_remove_free_space_cache(bg);
1958 btrfs_put_block_group(bg);
1961 btrfs_update_space_info(fs_info, bg->flags, em->len, em->len,
1963 bg->space_info = space_info;
1964 link_block_group(bg);
1966 set_avail_alloc_bits(fs_info, bg->flags);
1969 btrfs_init_global_block_rsv(fs_info);
1973 int btrfs_read_block_groups(struct btrfs_fs_info *info)
1975 struct btrfs_path *path;
1977 struct btrfs_block_group *cache;
1978 struct btrfs_space_info *space_info;
1979 struct btrfs_key key;
1983 if (!info->extent_root)
1984 return fill_dummy_bgs(info);
1988 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
1989 path = btrfs_alloc_path();
1993 cache_gen = btrfs_super_cache_generation(info->super_copy);
1994 if (btrfs_test_opt(info, SPACE_CACHE) &&
1995 btrfs_super_generation(info->super_copy) != cache_gen)
1997 if (btrfs_test_opt(info, CLEAR_CACHE))
2001 ret = find_first_block_group(info, path, &key);
2007 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2008 ret = read_one_block_group(info, path, &key, need_clear);
2011 key.objectid += key.offset;
2013 btrfs_release_path(path);
2015 btrfs_release_path(path);
2017 list_for_each_entry(space_info, &info->space_info, list) {
2020 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2021 if (list_empty(&space_info->block_groups[i]))
2023 cache = list_first_entry(&space_info->block_groups[i],
2024 struct btrfs_block_group,
2026 btrfs_sysfs_add_block_group_type(cache);
2029 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2030 (BTRFS_BLOCK_GROUP_RAID10 |
2031 BTRFS_BLOCK_GROUP_RAID1_MASK |
2032 BTRFS_BLOCK_GROUP_RAID56_MASK |
2033 BTRFS_BLOCK_GROUP_DUP)))
2036 * Avoid allocating from un-mirrored block group if there are
2037 * mirrored block groups.
2039 list_for_each_entry(cache,
2040 &space_info->block_groups[BTRFS_RAID_RAID0],
2042 inc_block_group_ro(cache, 1);
2043 list_for_each_entry(cache,
2044 &space_info->block_groups[BTRFS_RAID_SINGLE],
2046 inc_block_group_ro(cache, 1);
2049 btrfs_init_global_block_rsv(info);
2050 ret = check_chunk_block_group_mappings(info);
2052 btrfs_free_path(path);
2056 static int insert_block_group_item(struct btrfs_trans_handle *trans,
2057 struct btrfs_block_group *block_group)
2059 struct btrfs_fs_info *fs_info = trans->fs_info;
2060 struct btrfs_block_group_item bgi;
2061 struct btrfs_root *root;
2062 struct btrfs_key key;
2064 spin_lock(&block_group->lock);
2065 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2066 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2067 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2068 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2069 key.objectid = block_group->start;
2070 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2071 key.offset = block_group->length;
2072 spin_unlock(&block_group->lock);
2074 root = fs_info->extent_root;
2075 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2078 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2080 struct btrfs_fs_info *fs_info = trans->fs_info;
2081 struct btrfs_block_group *block_group;
2084 if (!trans->can_flush_pending_bgs)
2087 while (!list_empty(&trans->new_bgs)) {
2090 block_group = list_first_entry(&trans->new_bgs,
2091 struct btrfs_block_group,
2096 index = btrfs_bg_flags_to_raid_index(block_group->flags);
2098 ret = insert_block_group_item(trans, block_group);
2100 btrfs_abort_transaction(trans, ret);
2101 ret = btrfs_finish_chunk_alloc(trans, block_group->start,
2102 block_group->length);
2104 btrfs_abort_transaction(trans, ret);
2105 add_block_group_free_space(trans, block_group);
2108 * If we restriped during balance, we may have added a new raid
2109 * type, so now add the sysfs entries when it is safe to do so.
2110 * We don't have to worry about locking here as it's handled in
2111 * btrfs_sysfs_add_block_group_type.
2113 if (block_group->space_info->block_group_kobjs[index] == NULL)
2114 btrfs_sysfs_add_block_group_type(block_group);
2116 /* Already aborted the transaction if it failed. */
2118 btrfs_delayed_refs_rsv_release(fs_info, 1);
2119 list_del_init(&block_group->bg_list);
2121 btrfs_trans_release_chunk_metadata(trans);
2124 int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
2125 u64 type, u64 chunk_offset, u64 size)
2127 struct btrfs_fs_info *fs_info = trans->fs_info;
2128 struct btrfs_block_group *cache;
2131 btrfs_set_log_full_commit(trans);
2133 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
2137 cache->length = size;
2138 set_free_space_tree_thresholds(cache);
2139 cache->used = bytes_used;
2140 cache->flags = type;
2141 cache->last_byte_to_unpin = (u64)-1;
2142 cache->cached = BTRFS_CACHE_FINISHED;
2143 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
2144 cache->needs_free_space = 1;
2145 ret = exclude_super_stripes(cache);
2147 /* We may have excluded something, so call this just in case */
2148 btrfs_free_excluded_extents(cache);
2149 btrfs_put_block_group(cache);
2153 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2155 btrfs_free_excluded_extents(cache);
2157 #ifdef CONFIG_BTRFS_DEBUG
2158 if (btrfs_should_fragment_free_space(cache)) {
2159 u64 new_bytes_used = size - bytes_used;
2161 bytes_used += new_bytes_used >> 1;
2162 fragment_free_space(cache);
2166 * Ensure the corresponding space_info object is created and
2167 * assigned to our block group. We want our bg to be added to the rbtree
2168 * with its ->space_info set.
2170 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2171 ASSERT(cache->space_info);
2173 ret = btrfs_add_block_group_cache(fs_info, cache);
2175 btrfs_remove_free_space_cache(cache);
2176 btrfs_put_block_group(cache);
2181 * Now that our block group has its ->space_info set and is inserted in
2182 * the rbtree, update the space info's counters.
2184 trace_btrfs_add_block_group(fs_info, cache, 1);
2185 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
2186 cache->bytes_super, &cache->space_info);
2187 btrfs_update_global_block_rsv(fs_info);
2189 link_block_group(cache);
2191 list_add_tail(&cache->bg_list, &trans->new_bgs);
2192 trans->delayed_ref_updates++;
2193 btrfs_update_delayed_refs_rsv(trans);
2195 set_avail_alloc_bits(fs_info, type);
2200 * Mark one block group RO, can be called several times for the same block
2203 * @cache: the destination block group
2204 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2205 * ensure we still have some free space after marking this
2208 int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2209 bool do_chunk_alloc)
2211 struct btrfs_fs_info *fs_info = cache->fs_info;
2212 struct btrfs_trans_handle *trans;
2217 trans = btrfs_join_transaction(fs_info->extent_root);
2219 return PTR_ERR(trans);
2222 * we're not allowed to set block groups readonly after the dirty
2223 * block groups cache has started writing. If it already started,
2224 * back off and let this transaction commit
2226 mutex_lock(&fs_info->ro_block_group_mutex);
2227 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2228 u64 transid = trans->transid;
2230 mutex_unlock(&fs_info->ro_block_group_mutex);
2231 btrfs_end_transaction(trans);
2233 ret = btrfs_wait_for_commit(fs_info, transid);
2239 if (do_chunk_alloc) {
2241 * If we are changing raid levels, try to allocate a
2242 * corresponding block group with the new raid level.
2244 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2245 if (alloc_flags != cache->flags) {
2246 ret = btrfs_chunk_alloc(trans, alloc_flags,
2249 * ENOSPC is allowed here, we may have enough space
2250 * already allocated at the new raid level to carry on
2259 ret = inc_block_group_ro(cache, 0);
2260 if (!do_chunk_alloc)
2264 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2265 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2268 ret = inc_block_group_ro(cache, 0);
2270 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2271 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
2272 mutex_lock(&fs_info->chunk_mutex);
2273 check_system_chunk(trans, alloc_flags);
2274 mutex_unlock(&fs_info->chunk_mutex);
2277 mutex_unlock(&fs_info->ro_block_group_mutex);
2279 btrfs_end_transaction(trans);
2283 void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
2285 struct btrfs_space_info *sinfo = cache->space_info;
2290 spin_lock(&sinfo->lock);
2291 spin_lock(&cache->lock);
2293 num_bytes = cache->length - cache->reserved -
2294 cache->pinned - cache->bytes_super - cache->used;
2295 sinfo->bytes_readonly -= num_bytes;
2296 list_del_init(&cache->ro_list);
2298 spin_unlock(&cache->lock);
2299 spin_unlock(&sinfo->lock);
2302 static int update_block_group_item(struct btrfs_trans_handle *trans,
2303 struct btrfs_path *path,
2304 struct btrfs_block_group *cache)
2306 struct btrfs_fs_info *fs_info = trans->fs_info;
2308 struct btrfs_root *root = fs_info->extent_root;
2310 struct extent_buffer *leaf;
2311 struct btrfs_block_group_item bgi;
2312 struct btrfs_key key;
2314 key.objectid = cache->start;
2315 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2316 key.offset = cache->length;
2318 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2325 leaf = path->nodes[0];
2326 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2327 btrfs_set_stack_block_group_used(&bgi, cache->used);
2328 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2329 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2330 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2331 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
2332 btrfs_mark_buffer_dirty(leaf);
2334 btrfs_release_path(path);
2339 static int cache_save_setup(struct btrfs_block_group *block_group,
2340 struct btrfs_trans_handle *trans,
2341 struct btrfs_path *path)
2343 struct btrfs_fs_info *fs_info = block_group->fs_info;
2344 struct btrfs_root *root = fs_info->tree_root;
2345 struct inode *inode = NULL;
2346 struct extent_changeset *data_reserved = NULL;
2348 int dcs = BTRFS_DC_ERROR;
2353 if (!btrfs_test_opt(fs_info, SPACE_CACHE))
2357 * If this block group is smaller than 100 megs don't bother caching the
2360 if (block_group->length < (100 * SZ_1M)) {
2361 spin_lock(&block_group->lock);
2362 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2363 spin_unlock(&block_group->lock);
2367 if (TRANS_ABORTED(trans))
2370 inode = lookup_free_space_inode(block_group, path);
2371 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2372 ret = PTR_ERR(inode);
2373 btrfs_release_path(path);
2377 if (IS_ERR(inode)) {
2381 if (block_group->ro)
2384 ret = create_free_space_inode(trans, block_group, path);
2391 * We want to set the generation to 0, that way if anything goes wrong
2392 * from here on out we know not to trust this cache when we load up next
2395 BTRFS_I(inode)->generation = 0;
2396 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
2399 * So theoretically we could recover from this, simply set the
2400 * super cache generation to 0 so we know to invalidate the
2401 * cache, but then we'd have to keep track of the block groups
2402 * that fail this way so we know we _have_ to reset this cache
2403 * before the next commit or risk reading stale cache. So to
2404 * limit our exposure to horrible edge cases lets just abort the
2405 * transaction, this only happens in really bad situations
2408 btrfs_abort_transaction(trans, ret);
2413 /* We've already setup this transaction, go ahead and exit */
2414 if (block_group->cache_generation == trans->transid &&
2415 i_size_read(inode)) {
2416 dcs = BTRFS_DC_SETUP;
2420 if (i_size_read(inode) > 0) {
2421 ret = btrfs_check_trunc_cache_free_space(fs_info,
2422 &fs_info->global_block_rsv);
2426 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2431 spin_lock(&block_group->lock);
2432 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2433 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2435 * don't bother trying to write stuff out _if_
2436 * a) we're not cached,
2437 * b) we're with nospace_cache mount option,
2438 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2440 dcs = BTRFS_DC_WRITTEN;
2441 spin_unlock(&block_group->lock);
2444 spin_unlock(&block_group->lock);
2447 * We hit an ENOSPC when setting up the cache in this transaction, just
2448 * skip doing the setup, we've already cleared the cache so we're safe.
2450 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2456 * Try to preallocate enough space based on how big the block group is.
2457 * Keep in mind this has to include any pinned space which could end up
2458 * taking up quite a bit since it's not folded into the other space
2461 num_pages = div_u64(block_group->length, SZ_256M);
2466 num_pages *= PAGE_SIZE;
2468 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
2473 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2474 num_pages, num_pages,
2477 * Our cache requires contiguous chunks so that we don't modify a bunch
2478 * of metadata or split extents when writing the cache out, which means
2479 * we can enospc if we are heavily fragmented in addition to just normal
2480 * out of space conditions. So if we hit this just skip setting up any
2481 * other block groups for this transaction, maybe we'll unpin enough
2482 * space the next time around.
2485 dcs = BTRFS_DC_SETUP;
2486 else if (ret == -ENOSPC)
2487 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2492 btrfs_release_path(path);
2494 spin_lock(&block_group->lock);
2495 if (!ret && dcs == BTRFS_DC_SETUP)
2496 block_group->cache_generation = trans->transid;
2497 block_group->disk_cache_state = dcs;
2498 spin_unlock(&block_group->lock);
2500 extent_changeset_free(data_reserved);
2504 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2506 struct btrfs_fs_info *fs_info = trans->fs_info;
2507 struct btrfs_block_group *cache, *tmp;
2508 struct btrfs_transaction *cur_trans = trans->transaction;
2509 struct btrfs_path *path;
2511 if (list_empty(&cur_trans->dirty_bgs) ||
2512 !btrfs_test_opt(fs_info, SPACE_CACHE))
2515 path = btrfs_alloc_path();
2519 /* Could add new block groups, use _safe just in case */
2520 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2522 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2523 cache_save_setup(cache, trans, path);
2526 btrfs_free_path(path);
2531 * Transaction commit does final block group cache writeback during a critical
2532 * section where nothing is allowed to change the FS. This is required in
2533 * order for the cache to actually match the block group, but can introduce a
2534 * lot of latency into the commit.
2536 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2537 * There's a chance we'll have to redo some of it if the block group changes
2538 * again during the commit, but it greatly reduces the commit latency by
2539 * getting rid of the easy block groups while we're still allowing others to
2542 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2544 struct btrfs_fs_info *fs_info = trans->fs_info;
2545 struct btrfs_block_group *cache;
2546 struct btrfs_transaction *cur_trans = trans->transaction;
2549 struct btrfs_path *path = NULL;
2551 struct list_head *io = &cur_trans->io_bgs;
2552 int num_started = 0;
2555 spin_lock(&cur_trans->dirty_bgs_lock);
2556 if (list_empty(&cur_trans->dirty_bgs)) {
2557 spin_unlock(&cur_trans->dirty_bgs_lock);
2560 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2561 spin_unlock(&cur_trans->dirty_bgs_lock);
2564 /* Make sure all the block groups on our dirty list actually exist */
2565 btrfs_create_pending_block_groups(trans);
2568 path = btrfs_alloc_path();
2574 * cache_write_mutex is here only to save us from balance or automatic
2575 * removal of empty block groups deleting this block group while we are
2576 * writing out the cache
2578 mutex_lock(&trans->transaction->cache_write_mutex);
2579 while (!list_empty(&dirty)) {
2580 bool drop_reserve = true;
2582 cache = list_first_entry(&dirty, struct btrfs_block_group,
2585 * This can happen if something re-dirties a block group that
2586 * is already under IO. Just wait for it to finish and then do
2589 if (!list_empty(&cache->io_list)) {
2590 list_del_init(&cache->io_list);
2591 btrfs_wait_cache_io(trans, cache, path);
2592 btrfs_put_block_group(cache);
2597 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
2598 * it should update the cache_state. Don't delete until after
2601 * Since we're not running in the commit critical section
2602 * we need the dirty_bgs_lock to protect from update_block_group
2604 spin_lock(&cur_trans->dirty_bgs_lock);
2605 list_del_init(&cache->dirty_list);
2606 spin_unlock(&cur_trans->dirty_bgs_lock);
2610 cache_save_setup(cache, trans, path);
2612 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
2613 cache->io_ctl.inode = NULL;
2614 ret = btrfs_write_out_cache(trans, cache, path);
2615 if (ret == 0 && cache->io_ctl.inode) {
2620 * The cache_write_mutex is protecting the
2621 * io_list, also refer to the definition of
2622 * btrfs_transaction::io_bgs for more details
2624 list_add_tail(&cache->io_list, io);
2627 * If we failed to write the cache, the
2628 * generation will be bad and life goes on
2634 ret = update_block_group_item(trans, path, cache);
2636 * Our block group might still be attached to the list
2637 * of new block groups in the transaction handle of some
2638 * other task (struct btrfs_trans_handle->new_bgs). This
2639 * means its block group item isn't yet in the extent
2640 * tree. If this happens ignore the error, as we will
2641 * try again later in the critical section of the
2642 * transaction commit.
2644 if (ret == -ENOENT) {
2646 spin_lock(&cur_trans->dirty_bgs_lock);
2647 if (list_empty(&cache->dirty_list)) {
2648 list_add_tail(&cache->dirty_list,
2649 &cur_trans->dirty_bgs);
2650 btrfs_get_block_group(cache);
2651 drop_reserve = false;
2653 spin_unlock(&cur_trans->dirty_bgs_lock);
2655 btrfs_abort_transaction(trans, ret);
2659 /* If it's not on the io list, we need to put the block group */
2661 btrfs_put_block_group(cache);
2663 btrfs_delayed_refs_rsv_release(fs_info, 1);
2669 * Avoid blocking other tasks for too long. It might even save
2670 * us from writing caches for block groups that are going to be
2673 mutex_unlock(&trans->transaction->cache_write_mutex);
2674 mutex_lock(&trans->transaction->cache_write_mutex);
2676 mutex_unlock(&trans->transaction->cache_write_mutex);
2679 * Go through delayed refs for all the stuff we've just kicked off
2680 * and then loop back (just once)
2683 ret = btrfs_run_delayed_refs(trans, 0);
2684 if (!ret && loops == 0) {
2686 spin_lock(&cur_trans->dirty_bgs_lock);
2687 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2689 * dirty_bgs_lock protects us from concurrent block group
2690 * deletes too (not just cache_write_mutex).
2692 if (!list_empty(&dirty)) {
2693 spin_unlock(&cur_trans->dirty_bgs_lock);
2696 spin_unlock(&cur_trans->dirty_bgs_lock);
2697 } else if (ret < 0) {
2698 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
2701 btrfs_free_path(path);
2705 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
2707 struct btrfs_fs_info *fs_info = trans->fs_info;
2708 struct btrfs_block_group *cache;
2709 struct btrfs_transaction *cur_trans = trans->transaction;
2712 struct btrfs_path *path;
2713 struct list_head *io = &cur_trans->io_bgs;
2714 int num_started = 0;
2716 path = btrfs_alloc_path();
2721 * Even though we are in the critical section of the transaction commit,
2722 * we can still have concurrent tasks adding elements to this
2723 * transaction's list of dirty block groups. These tasks correspond to
2724 * endio free space workers started when writeback finishes for a
2725 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
2726 * allocate new block groups as a result of COWing nodes of the root
2727 * tree when updating the free space inode. The writeback for the space
2728 * caches is triggered by an earlier call to
2729 * btrfs_start_dirty_block_groups() and iterations of the following
2731 * Also we want to do the cache_save_setup first and then run the
2732 * delayed refs to make sure we have the best chance at doing this all
2735 spin_lock(&cur_trans->dirty_bgs_lock);
2736 while (!list_empty(&cur_trans->dirty_bgs)) {
2737 cache = list_first_entry(&cur_trans->dirty_bgs,
2738 struct btrfs_block_group,
2742 * This can happen if cache_save_setup re-dirties a block group
2743 * that is already under IO. Just wait for it to finish and
2744 * then do it all again
2746 if (!list_empty(&cache->io_list)) {
2747 spin_unlock(&cur_trans->dirty_bgs_lock);
2748 list_del_init(&cache->io_list);
2749 btrfs_wait_cache_io(trans, cache, path);
2750 btrfs_put_block_group(cache);
2751 spin_lock(&cur_trans->dirty_bgs_lock);
2755 * Don't remove from the dirty list until after we've waited on
2758 list_del_init(&cache->dirty_list);
2759 spin_unlock(&cur_trans->dirty_bgs_lock);
2762 cache_save_setup(cache, trans, path);
2765 ret = btrfs_run_delayed_refs(trans,
2766 (unsigned long) -1);
2768 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
2769 cache->io_ctl.inode = NULL;
2770 ret = btrfs_write_out_cache(trans, cache, path);
2771 if (ret == 0 && cache->io_ctl.inode) {
2774 list_add_tail(&cache->io_list, io);
2777 * If we failed to write the cache, the
2778 * generation will be bad and life goes on
2784 ret = update_block_group_item(trans, path, cache);
2786 * One of the free space endio workers might have
2787 * created a new block group while updating a free space
2788 * cache's inode (at inode.c:btrfs_finish_ordered_io())
2789 * and hasn't released its transaction handle yet, in
2790 * which case the new block group is still attached to
2791 * its transaction handle and its creation has not
2792 * finished yet (no block group item in the extent tree
2793 * yet, etc). If this is the case, wait for all free
2794 * space endio workers to finish and retry. This is a
2795 * very rare case so no need for a more efficient and
2798 if (ret == -ENOENT) {
2799 wait_event(cur_trans->writer_wait,
2800 atomic_read(&cur_trans->num_writers) == 1);
2801 ret = update_block_group_item(trans, path, cache);
2804 btrfs_abort_transaction(trans, ret);
2807 /* If its not on the io list, we need to put the block group */
2809 btrfs_put_block_group(cache);
2810 btrfs_delayed_refs_rsv_release(fs_info, 1);
2811 spin_lock(&cur_trans->dirty_bgs_lock);
2813 spin_unlock(&cur_trans->dirty_bgs_lock);
2816 * Refer to the definition of io_bgs member for details why it's safe
2817 * to use it without any locking
2819 while (!list_empty(io)) {
2820 cache = list_first_entry(io, struct btrfs_block_group,
2822 list_del_init(&cache->io_list);
2823 btrfs_wait_cache_io(trans, cache, path);
2824 btrfs_put_block_group(cache);
2827 btrfs_free_path(path);
2831 int btrfs_update_block_group(struct btrfs_trans_handle *trans,
2832 u64 bytenr, u64 num_bytes, int alloc)
2834 struct btrfs_fs_info *info = trans->fs_info;
2835 struct btrfs_block_group *cache = NULL;
2836 u64 total = num_bytes;
2842 /* Block accounting for super block */
2843 spin_lock(&info->delalloc_root_lock);
2844 old_val = btrfs_super_bytes_used(info->super_copy);
2846 old_val += num_bytes;
2848 old_val -= num_bytes;
2849 btrfs_set_super_bytes_used(info->super_copy, old_val);
2850 spin_unlock(&info->delalloc_root_lock);
2853 cache = btrfs_lookup_block_group(info, bytenr);
2858 factor = btrfs_bg_type_to_factor(cache->flags);
2861 * If this block group has free space cache written out, we
2862 * need to make sure to load it if we are removing space. This
2863 * is because we need the unpinning stage to actually add the
2864 * space back to the block group, otherwise we will leak space.
2866 if (!alloc && !btrfs_block_group_done(cache))
2867 btrfs_cache_block_group(cache, 1);
2869 byte_in_group = bytenr - cache->start;
2870 WARN_ON(byte_in_group > cache->length);
2872 spin_lock(&cache->space_info->lock);
2873 spin_lock(&cache->lock);
2875 if (btrfs_test_opt(info, SPACE_CACHE) &&
2876 cache->disk_cache_state < BTRFS_DC_CLEAR)
2877 cache->disk_cache_state = BTRFS_DC_CLEAR;
2879 old_val = cache->used;
2880 num_bytes = min(total, cache->length - byte_in_group);
2882 old_val += num_bytes;
2883 cache->used = old_val;
2884 cache->reserved -= num_bytes;
2885 cache->space_info->bytes_reserved -= num_bytes;
2886 cache->space_info->bytes_used += num_bytes;
2887 cache->space_info->disk_used += num_bytes * factor;
2888 spin_unlock(&cache->lock);
2889 spin_unlock(&cache->space_info->lock);
2891 old_val -= num_bytes;
2892 cache->used = old_val;
2893 cache->pinned += num_bytes;
2894 btrfs_space_info_update_bytes_pinned(info,
2895 cache->space_info, num_bytes);
2896 cache->space_info->bytes_used -= num_bytes;
2897 cache->space_info->disk_used -= num_bytes * factor;
2898 spin_unlock(&cache->lock);
2899 spin_unlock(&cache->space_info->lock);
2901 percpu_counter_add_batch(
2902 &cache->space_info->total_bytes_pinned,
2904 BTRFS_TOTAL_BYTES_PINNED_BATCH);
2905 set_extent_dirty(&trans->transaction->pinned_extents,
2906 bytenr, bytenr + num_bytes - 1,
2907 GFP_NOFS | __GFP_NOFAIL);
2910 spin_lock(&trans->transaction->dirty_bgs_lock);
2911 if (list_empty(&cache->dirty_list)) {
2912 list_add_tail(&cache->dirty_list,
2913 &trans->transaction->dirty_bgs);
2914 trans->delayed_ref_updates++;
2915 btrfs_get_block_group(cache);
2917 spin_unlock(&trans->transaction->dirty_bgs_lock);
2920 * No longer have used bytes in this block group, queue it for
2921 * deletion. We do this after adding the block group to the
2922 * dirty list to avoid races between cleaner kthread and space
2925 if (!alloc && old_val == 0) {
2926 if (!btrfs_test_opt(info, DISCARD_ASYNC))
2927 btrfs_mark_bg_unused(cache);
2930 btrfs_put_block_group(cache);
2932 bytenr += num_bytes;
2935 /* Modified block groups are accounted for in the delayed_refs_rsv. */
2936 btrfs_update_delayed_refs_rsv(trans);
2941 * btrfs_add_reserved_bytes - update the block_group and space info counters
2942 * @cache: The cache we are manipulating
2943 * @ram_bytes: The number of bytes of file content, and will be same to
2944 * @num_bytes except for the compress path.
2945 * @num_bytes: The number of bytes in question
2946 * @delalloc: The blocks are allocated for the delalloc write
2948 * This is called by the allocator when it reserves space. If this is a
2949 * reservation and the block group has become read only we cannot make the
2950 * reservation and return -EAGAIN, otherwise this function always succeeds.
2952 int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
2953 u64 ram_bytes, u64 num_bytes, int delalloc)
2955 struct btrfs_space_info *space_info = cache->space_info;
2958 spin_lock(&space_info->lock);
2959 spin_lock(&cache->lock);
2963 cache->reserved += num_bytes;
2964 space_info->bytes_reserved += num_bytes;
2965 trace_btrfs_space_reservation(cache->fs_info, "space_info",
2966 space_info->flags, num_bytes, 1);
2967 btrfs_space_info_update_bytes_may_use(cache->fs_info,
2968 space_info, -ram_bytes);
2970 cache->delalloc_bytes += num_bytes;
2973 * Compression can use less space than we reserved, so wake
2974 * tickets if that happens
2976 if (num_bytes < ram_bytes)
2977 btrfs_try_granting_tickets(cache->fs_info, space_info);
2979 spin_unlock(&cache->lock);
2980 spin_unlock(&space_info->lock);
2985 * btrfs_free_reserved_bytes - update the block_group and space info counters
2986 * @cache: The cache we are manipulating
2987 * @num_bytes: The number of bytes in question
2988 * @delalloc: The blocks are allocated for the delalloc write
2990 * This is called by somebody who is freeing space that was never actually used
2991 * on disk. For example if you reserve some space for a new leaf in transaction
2992 * A and before transaction A commits you free that leaf, you call this with
2993 * reserve set to 0 in order to clear the reservation.
2995 void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
2996 u64 num_bytes, int delalloc)
2998 struct btrfs_space_info *space_info = cache->space_info;
3000 spin_lock(&space_info->lock);
3001 spin_lock(&cache->lock);
3003 space_info->bytes_readonly += num_bytes;
3004 cache->reserved -= num_bytes;
3005 space_info->bytes_reserved -= num_bytes;
3006 space_info->max_extent_size = 0;
3009 cache->delalloc_bytes -= num_bytes;
3010 spin_unlock(&cache->lock);
3012 btrfs_try_granting_tickets(cache->fs_info, space_info);
3013 spin_unlock(&space_info->lock);
3016 static void force_metadata_allocation(struct btrfs_fs_info *info)
3018 struct list_head *head = &info->space_info;
3019 struct btrfs_space_info *found;
3021 list_for_each_entry(found, head, list) {
3022 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3023 found->force_alloc = CHUNK_ALLOC_FORCE;
3027 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3028 struct btrfs_space_info *sinfo, int force)
3030 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3033 if (force == CHUNK_ALLOC_FORCE)
3037 * in limited mode, we want to have some free space up to
3038 * about 1% of the FS size.
3040 if (force == CHUNK_ALLOC_LIMITED) {
3041 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3042 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3044 if (sinfo->total_bytes - bytes_used < thresh)
3048 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3053 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3055 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3057 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3061 * If force is CHUNK_ALLOC_FORCE:
3062 * - return 1 if it successfully allocates a chunk,
3063 * - return errors including -ENOSPC otherwise.
3064 * If force is NOT CHUNK_ALLOC_FORCE:
3065 * - return 0 if it doesn't need to allocate a new chunk,
3066 * - return 1 if it successfully allocates a chunk,
3067 * - return errors including -ENOSPC otherwise.
3069 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3070 enum btrfs_chunk_alloc_enum force)
3072 struct btrfs_fs_info *fs_info = trans->fs_info;
3073 struct btrfs_space_info *space_info;
3074 bool wait_for_alloc = false;
3075 bool should_alloc = false;
3078 /* Don't re-enter if we're already allocating a chunk */
3079 if (trans->allocating_chunk)
3082 space_info = btrfs_find_space_info(fs_info, flags);
3086 spin_lock(&space_info->lock);
3087 if (force < space_info->force_alloc)
3088 force = space_info->force_alloc;
3089 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3090 if (space_info->full) {
3091 /* No more free physical space */
3096 spin_unlock(&space_info->lock);
3098 } else if (!should_alloc) {
3099 spin_unlock(&space_info->lock);
3101 } else if (space_info->chunk_alloc) {
3103 * Someone is already allocating, so we need to block
3104 * until this someone is finished and then loop to
3105 * recheck if we should continue with our allocation
3108 wait_for_alloc = true;
3109 spin_unlock(&space_info->lock);
3110 mutex_lock(&fs_info->chunk_mutex);
3111 mutex_unlock(&fs_info->chunk_mutex);
3113 /* Proceed with allocation */
3114 space_info->chunk_alloc = 1;
3115 wait_for_alloc = false;
3116 spin_unlock(&space_info->lock);
3120 } while (wait_for_alloc);
3122 mutex_lock(&fs_info->chunk_mutex);
3123 trans->allocating_chunk = true;
3126 * If we have mixed data/metadata chunks we want to make sure we keep
3127 * allocating mixed chunks instead of individual chunks.
3129 if (btrfs_mixed_space_info(space_info))
3130 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3133 * if we're doing a data chunk, go ahead and make sure that
3134 * we keep a reasonable number of metadata chunks allocated in the
3137 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3138 fs_info->data_chunk_allocations++;
3139 if (!(fs_info->data_chunk_allocations %
3140 fs_info->metadata_ratio))
3141 force_metadata_allocation(fs_info);
3145 * Check if we have enough space in SYSTEM chunk because we may need
3146 * to update devices.
3148 check_system_chunk(trans, flags);
3150 ret = btrfs_alloc_chunk(trans, flags);
3151 trans->allocating_chunk = false;
3153 spin_lock(&space_info->lock);
3156 space_info->full = 1;
3161 space_info->max_extent_size = 0;
3164 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3166 space_info->chunk_alloc = 0;
3167 spin_unlock(&space_info->lock);
3168 mutex_unlock(&fs_info->chunk_mutex);
3170 * When we allocate a new chunk we reserve space in the chunk block
3171 * reserve to make sure we can COW nodes/leafs in the chunk tree or
3172 * add new nodes/leafs to it if we end up needing to do it when
3173 * inserting the chunk item and updating device items as part of the
3174 * second phase of chunk allocation, performed by
3175 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
3176 * large number of new block groups to create in our transaction
3177 * handle's new_bgs list to avoid exhausting the chunk block reserve
3178 * in extreme cases - like having a single transaction create many new
3179 * block groups when starting to write out the free space caches of all
3180 * the block groups that were made dirty during the lifetime of the
3183 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
3184 btrfs_create_pending_block_groups(trans);
3189 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3193 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3195 num_dev = fs_info->fs_devices->rw_devices;
3201 * Reserve space in the system space for allocating or removing a chunk
3203 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3205 struct btrfs_fs_info *fs_info = trans->fs_info;
3206 struct btrfs_space_info *info;
3213 * Needed because we can end up allocating a system chunk and for an
3214 * atomic and race free space reservation in the chunk block reserve.
3216 lockdep_assert_held(&fs_info->chunk_mutex);
3218 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3219 spin_lock(&info->lock);
3220 left = info->total_bytes - btrfs_space_info_used(info, true);
3221 spin_unlock(&info->lock);
3223 num_devs = get_profile_num_devs(fs_info, type);
3225 /* num_devs device items to update and 1 chunk item to add or remove */
3226 thresh = btrfs_calc_metadata_size(fs_info, num_devs) +
3227 btrfs_calc_insert_metadata_size(fs_info, 1);
3229 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3230 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3231 left, thresh, type);
3232 btrfs_dump_space_info(fs_info, info, 0, 0);
3235 if (left < thresh) {
3236 u64 flags = btrfs_system_alloc_profile(fs_info);
3239 * Ignore failure to create system chunk. We might end up not
3240 * needing it, as we might not need to COW all nodes/leafs from
3241 * the paths we visit in the chunk tree (they were already COWed
3242 * or created in the current transaction for example).
3244 ret = btrfs_alloc_chunk(trans, flags);
3248 ret = btrfs_block_rsv_add(fs_info->chunk_root,
3249 &fs_info->chunk_block_rsv,
3250 thresh, BTRFS_RESERVE_NO_FLUSH);
3252 trans->chunk_bytes_reserved += thresh;
3256 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3258 struct btrfs_block_group *block_group;
3262 struct inode *inode;
3264 block_group = btrfs_lookup_first_block_group(info, last);
3265 while (block_group) {
3266 btrfs_wait_block_group_cache_done(block_group);
3267 spin_lock(&block_group->lock);
3268 if (block_group->iref)
3270 spin_unlock(&block_group->lock);
3271 block_group = btrfs_next_block_group(block_group);
3280 inode = block_group->inode;
3281 block_group->iref = 0;
3282 block_group->inode = NULL;
3283 spin_unlock(&block_group->lock);
3284 ASSERT(block_group->io_ctl.inode == NULL);
3286 last = block_group->start + block_group->length;
3287 btrfs_put_block_group(block_group);
3292 * Must be called only after stopping all workers, since we could have block
3293 * group caching kthreads running, and therefore they could race with us if we
3294 * freed the block groups before stopping them.
3296 int btrfs_free_block_groups(struct btrfs_fs_info *info)
3298 struct btrfs_block_group *block_group;
3299 struct btrfs_space_info *space_info;
3300 struct btrfs_caching_control *caching_ctl;
3303 spin_lock(&info->block_group_cache_lock);
3304 while (!list_empty(&info->caching_block_groups)) {
3305 caching_ctl = list_entry(info->caching_block_groups.next,
3306 struct btrfs_caching_control, list);
3307 list_del(&caching_ctl->list);
3308 btrfs_put_caching_control(caching_ctl);
3310 spin_unlock(&info->block_group_cache_lock);
3312 spin_lock(&info->unused_bgs_lock);
3313 while (!list_empty(&info->unused_bgs)) {
3314 block_group = list_first_entry(&info->unused_bgs,
3315 struct btrfs_block_group,
3317 list_del_init(&block_group->bg_list);
3318 btrfs_put_block_group(block_group);
3320 spin_unlock(&info->unused_bgs_lock);
3322 spin_lock(&info->block_group_cache_lock);
3323 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
3324 block_group = rb_entry(n, struct btrfs_block_group,
3326 rb_erase(&block_group->cache_node,
3327 &info->block_group_cache_tree);
3328 RB_CLEAR_NODE(&block_group->cache_node);
3329 spin_unlock(&info->block_group_cache_lock);
3331 down_write(&block_group->space_info->groups_sem);
3332 list_del(&block_group->list);
3333 up_write(&block_group->space_info->groups_sem);
3336 * We haven't cached this block group, which means we could
3337 * possibly have excluded extents on this block group.
3339 if (block_group->cached == BTRFS_CACHE_NO ||
3340 block_group->cached == BTRFS_CACHE_ERROR)
3341 btrfs_free_excluded_extents(block_group);
3343 btrfs_remove_free_space_cache(block_group);
3344 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
3345 ASSERT(list_empty(&block_group->dirty_list));
3346 ASSERT(list_empty(&block_group->io_list));
3347 ASSERT(list_empty(&block_group->bg_list));
3348 ASSERT(refcount_read(&block_group->refs) == 1);
3349 btrfs_put_block_group(block_group);
3351 spin_lock(&info->block_group_cache_lock);
3353 spin_unlock(&info->block_group_cache_lock);
3355 btrfs_release_global_block_rsv(info);
3357 while (!list_empty(&info->space_info)) {
3358 space_info = list_entry(info->space_info.next,
3359 struct btrfs_space_info,
3363 * Do not hide this behind enospc_debug, this is actually
3364 * important and indicates a real bug if this happens.
3366 if (WARN_ON(space_info->bytes_pinned > 0 ||
3367 space_info->bytes_reserved > 0 ||
3368 space_info->bytes_may_use > 0))
3369 btrfs_dump_space_info(info, space_info, 0, 0);
3370 WARN_ON(space_info->reclaim_size > 0);
3371 list_del(&space_info->list);
3372 btrfs_sysfs_remove_space_info(space_info);
3377 void btrfs_freeze_block_group(struct btrfs_block_group *cache)
3379 atomic_inc(&cache->frozen);
3382 void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
3384 struct btrfs_fs_info *fs_info = block_group->fs_info;
3385 struct extent_map_tree *em_tree;
3386 struct extent_map *em;
3389 spin_lock(&block_group->lock);
3390 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
3391 block_group->removed);
3392 spin_unlock(&block_group->lock);
3395 em_tree = &fs_info->mapping_tree;
3396 write_lock(&em_tree->lock);
3397 em = lookup_extent_mapping(em_tree, block_group->start,
3399 BUG_ON(!em); /* logic error, can't happen */
3400 remove_extent_mapping(em_tree, em);
3401 write_unlock(&em_tree->lock);
3403 /* once for us and once for the tree */
3404 free_extent_map(em);
3405 free_extent_map(em);
3408 * We may have left one free space entry and other possible
3409 * tasks trimming this block group have left 1 entry each one.
3412 __btrfs_remove_free_space_cache(block_group->free_space_ctl);