1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/sizes.h>
4 #include <linux/list_sort.h>
7 #include "block-group.h"
8 #include "space-info.h"
10 #include "free-space-cache.h"
11 #include "free-space-tree.h"
13 #include "transaction.h"
14 #include "ref-verify.h"
17 #include "delalloc-space.h"
22 #include "accessors.h"
23 #include "extent-tree.h"
25 #ifdef CONFIG_BTRFS_DEBUG
26 int btrfs_should_fragment_free_space(struct btrfs_block_group
*block_group
)
28 struct btrfs_fs_info
*fs_info
= block_group
->fs_info
;
30 return (btrfs_test_opt(fs_info
, FRAGMENT_METADATA
) &&
31 block_group
->flags
& BTRFS_BLOCK_GROUP_METADATA
) ||
32 (btrfs_test_opt(fs_info
, FRAGMENT_DATA
) &&
33 block_group
->flags
& BTRFS_BLOCK_GROUP_DATA
);
38 * Return target flags in extended format or 0 if restripe for this chunk_type
41 * Should be called with balance_lock held
43 static u64
get_restripe_target(struct btrfs_fs_info
*fs_info
, u64 flags
)
45 struct btrfs_balance_control
*bctl
= fs_info
->balance_ctl
;
51 if (flags
& BTRFS_BLOCK_GROUP_DATA
&&
52 bctl
->data
.flags
& BTRFS_BALANCE_ARGS_CONVERT
) {
53 target
= BTRFS_BLOCK_GROUP_DATA
| bctl
->data
.target
;
54 } else if (flags
& BTRFS_BLOCK_GROUP_SYSTEM
&&
55 bctl
->sys
.flags
& BTRFS_BALANCE_ARGS_CONVERT
) {
56 target
= BTRFS_BLOCK_GROUP_SYSTEM
| bctl
->sys
.target
;
57 } else if (flags
& BTRFS_BLOCK_GROUP_METADATA
&&
58 bctl
->meta
.flags
& BTRFS_BALANCE_ARGS_CONVERT
) {
59 target
= BTRFS_BLOCK_GROUP_METADATA
| bctl
->meta
.target
;
66 * @flags: available profiles in extended format (see ctree.h)
68 * Return reduced profile in chunk format. If profile changing is in progress
69 * (either running or paused) picks the target profile (if it's already
70 * available), otherwise falls back to plain reducing.
72 static u64
btrfs_reduce_alloc_profile(struct btrfs_fs_info
*fs_info
, u64 flags
)
74 u64 num_devices
= fs_info
->fs_devices
->rw_devices
;
80 * See if restripe for this chunk_type is in progress, if so try to
81 * reduce to the target profile
83 spin_lock(&fs_info
->balance_lock
);
84 target
= get_restripe_target(fs_info
, flags
);
86 spin_unlock(&fs_info
->balance_lock
);
87 return extended_to_chunk(target
);
89 spin_unlock(&fs_info
->balance_lock
);
91 /* First, mask out the RAID levels which aren't possible */
92 for (raid_type
= 0; raid_type
< BTRFS_NR_RAID_TYPES
; raid_type
++) {
93 if (num_devices
>= btrfs_raid_array
[raid_type
].devs_min
)
94 allowed
|= btrfs_raid_array
[raid_type
].bg_flag
;
98 if (allowed
& BTRFS_BLOCK_GROUP_RAID6
)
99 allowed
= BTRFS_BLOCK_GROUP_RAID6
;
100 else if (allowed
& BTRFS_BLOCK_GROUP_RAID5
)
101 allowed
= BTRFS_BLOCK_GROUP_RAID5
;
102 else if (allowed
& BTRFS_BLOCK_GROUP_RAID10
)
103 allowed
= BTRFS_BLOCK_GROUP_RAID10
;
104 else if (allowed
& BTRFS_BLOCK_GROUP_RAID1
)
105 allowed
= BTRFS_BLOCK_GROUP_RAID1
;
106 else if (allowed
& BTRFS_BLOCK_GROUP_RAID0
)
107 allowed
= BTRFS_BLOCK_GROUP_RAID0
;
109 flags
&= ~BTRFS_BLOCK_GROUP_PROFILE_MASK
;
111 return extended_to_chunk(flags
| allowed
);
114 u64
btrfs_get_alloc_profile(struct btrfs_fs_info
*fs_info
, u64 orig_flags
)
121 seq
= read_seqbegin(&fs_info
->profiles_lock
);
123 if (flags
& BTRFS_BLOCK_GROUP_DATA
)
124 flags
|= fs_info
->avail_data_alloc_bits
;
125 else if (flags
& BTRFS_BLOCK_GROUP_SYSTEM
)
126 flags
|= fs_info
->avail_system_alloc_bits
;
127 else if (flags
& BTRFS_BLOCK_GROUP_METADATA
)
128 flags
|= fs_info
->avail_metadata_alloc_bits
;
129 } while (read_seqretry(&fs_info
->profiles_lock
, seq
));
131 return btrfs_reduce_alloc_profile(fs_info
, flags
);
134 void btrfs_get_block_group(struct btrfs_block_group
*cache
)
136 refcount_inc(&cache
->refs
);
139 void btrfs_put_block_group(struct btrfs_block_group
*cache
)
141 if (refcount_dec_and_test(&cache
->refs
)) {
142 WARN_ON(cache
->pinned
> 0);
144 * If there was a failure to cleanup a log tree, very likely due
145 * to an IO failure on a writeback attempt of one or more of its
146 * extent buffers, we could not do proper (and cheap) unaccounting
147 * of their reserved space, so don't warn on reserved > 0 in that
150 if (!(cache
->flags
& BTRFS_BLOCK_GROUP_METADATA
) ||
151 !BTRFS_FS_LOG_CLEANUP_ERROR(cache
->fs_info
))
152 WARN_ON(cache
->reserved
> 0);
155 * A block_group shouldn't be on the discard_list anymore.
156 * Remove the block_group from the discard_list to prevent us
157 * from causing a panic due to NULL pointer dereference.
159 if (WARN_ON(!list_empty(&cache
->discard_list
)))
160 btrfs_discard_cancel_work(&cache
->fs_info
->discard_ctl
,
164 * If not empty, someone is still holding mutex of
165 * full_stripe_lock, which can only be released by caller.
166 * And it will definitely cause use-after-free when caller
167 * tries to release full stripe lock.
169 * No better way to resolve, but only to warn.
171 WARN_ON(!RB_EMPTY_ROOT(&cache
->full_stripe_locks_root
.root
));
172 kfree(cache
->free_space_ctl
);
173 kfree(cache
->physical_map
);
179 * This adds the block group to the fs_info rb tree for the block group cache
181 static int btrfs_add_block_group_cache(struct btrfs_fs_info
*info
,
182 struct btrfs_block_group
*block_group
)
185 struct rb_node
*parent
= NULL
;
186 struct btrfs_block_group
*cache
;
187 bool leftmost
= true;
189 ASSERT(block_group
->length
!= 0);
191 write_lock(&info
->block_group_cache_lock
);
192 p
= &info
->block_group_cache_tree
.rb_root
.rb_node
;
196 cache
= rb_entry(parent
, struct btrfs_block_group
, cache_node
);
197 if (block_group
->start
< cache
->start
) {
199 } else if (block_group
->start
> cache
->start
) {
203 write_unlock(&info
->block_group_cache_lock
);
208 rb_link_node(&block_group
->cache_node
, parent
, p
);
209 rb_insert_color_cached(&block_group
->cache_node
,
210 &info
->block_group_cache_tree
, leftmost
);
212 write_unlock(&info
->block_group_cache_lock
);
218 * This will return the block group at or after bytenr if contains is 0, else
219 * it will return the block group that contains the bytenr
221 static struct btrfs_block_group
*block_group_cache_tree_search(
222 struct btrfs_fs_info
*info
, u64 bytenr
, int contains
)
224 struct btrfs_block_group
*cache
, *ret
= NULL
;
228 read_lock(&info
->block_group_cache_lock
);
229 n
= info
->block_group_cache_tree
.rb_root
.rb_node
;
232 cache
= rb_entry(n
, struct btrfs_block_group
, cache_node
);
233 end
= cache
->start
+ cache
->length
- 1;
234 start
= cache
->start
;
236 if (bytenr
< start
) {
237 if (!contains
&& (!ret
|| start
< ret
->start
))
240 } else if (bytenr
> start
) {
241 if (contains
&& bytenr
<= end
) {
252 btrfs_get_block_group(ret
);
253 read_unlock(&info
->block_group_cache_lock
);
259 * Return the block group that starts at or after bytenr
261 struct btrfs_block_group
*btrfs_lookup_first_block_group(
262 struct btrfs_fs_info
*info
, u64 bytenr
)
264 return block_group_cache_tree_search(info
, bytenr
, 0);
268 * Return the block group that contains the given bytenr
270 struct btrfs_block_group
*btrfs_lookup_block_group(
271 struct btrfs_fs_info
*info
, u64 bytenr
)
273 return block_group_cache_tree_search(info
, bytenr
, 1);
276 struct btrfs_block_group
*btrfs_next_block_group(
277 struct btrfs_block_group
*cache
)
279 struct btrfs_fs_info
*fs_info
= cache
->fs_info
;
280 struct rb_node
*node
;
282 read_lock(&fs_info
->block_group_cache_lock
);
284 /* If our block group was removed, we need a full search. */
285 if (RB_EMPTY_NODE(&cache
->cache_node
)) {
286 const u64 next_bytenr
= cache
->start
+ cache
->length
;
288 read_unlock(&fs_info
->block_group_cache_lock
);
289 btrfs_put_block_group(cache
);
290 return btrfs_lookup_first_block_group(fs_info
, next_bytenr
);
292 node
= rb_next(&cache
->cache_node
);
293 btrfs_put_block_group(cache
);
295 cache
= rb_entry(node
, struct btrfs_block_group
, cache_node
);
296 btrfs_get_block_group(cache
);
299 read_unlock(&fs_info
->block_group_cache_lock
);
304 * Check if we can do a NOCOW write for a given extent.
306 * @fs_info: The filesystem information object.
307 * @bytenr: Logical start address of the extent.
309 * Check if we can do a NOCOW write for the given extent, and increments the
310 * number of NOCOW writers in the block group that contains the extent, as long
311 * as the block group exists and it's currently not in read-only mode.
313 * Returns: A non-NULL block group pointer if we can do a NOCOW write, the caller
314 * is responsible for calling btrfs_dec_nocow_writers() later.
316 * Or NULL if we can not do a NOCOW write
318 struct btrfs_block_group
*btrfs_inc_nocow_writers(struct btrfs_fs_info
*fs_info
,
321 struct btrfs_block_group
*bg
;
322 bool can_nocow
= true;
324 bg
= btrfs_lookup_block_group(fs_info
, bytenr
);
328 spin_lock(&bg
->lock
);
332 atomic_inc(&bg
->nocow_writers
);
333 spin_unlock(&bg
->lock
);
336 btrfs_put_block_group(bg
);
340 /* No put on block group, done by btrfs_dec_nocow_writers(). */
345 * Decrement the number of NOCOW writers in a block group.
347 * This is meant to be called after a previous call to btrfs_inc_nocow_writers(),
348 * and on the block group returned by that call. Typically this is called after
349 * creating an ordered extent for a NOCOW write, to prevent races with scrub and
352 * After this call, the caller should not use the block group anymore. It it wants
353 * to use it, then it should get a reference on it before calling this function.
355 void btrfs_dec_nocow_writers(struct btrfs_block_group
*bg
)
357 if (atomic_dec_and_test(&bg
->nocow_writers
))
358 wake_up_var(&bg
->nocow_writers
);
360 /* For the lookup done by a previous call to btrfs_inc_nocow_writers(). */
361 btrfs_put_block_group(bg
);
364 void btrfs_wait_nocow_writers(struct btrfs_block_group
*bg
)
366 wait_var_event(&bg
->nocow_writers
, !atomic_read(&bg
->nocow_writers
));
369 void btrfs_dec_block_group_reservations(struct btrfs_fs_info
*fs_info
,
372 struct btrfs_block_group
*bg
;
374 bg
= btrfs_lookup_block_group(fs_info
, start
);
376 if (atomic_dec_and_test(&bg
->reservations
))
377 wake_up_var(&bg
->reservations
);
378 btrfs_put_block_group(bg
);
381 void btrfs_wait_block_group_reservations(struct btrfs_block_group
*bg
)
383 struct btrfs_space_info
*space_info
= bg
->space_info
;
387 if (!(bg
->flags
& BTRFS_BLOCK_GROUP_DATA
))
391 * Our block group is read only but before we set it to read only,
392 * some task might have had allocated an extent from it already, but it
393 * has not yet created a respective ordered extent (and added it to a
394 * root's list of ordered extents).
395 * Therefore wait for any task currently allocating extents, since the
396 * block group's reservations counter is incremented while a read lock
397 * on the groups' semaphore is held and decremented after releasing
398 * the read access on that semaphore and creating the ordered extent.
400 down_write(&space_info
->groups_sem
);
401 up_write(&space_info
->groups_sem
);
403 wait_var_event(&bg
->reservations
, !atomic_read(&bg
->reservations
));
406 struct btrfs_caching_control
*btrfs_get_caching_control(
407 struct btrfs_block_group
*cache
)
409 struct btrfs_caching_control
*ctl
;
411 spin_lock(&cache
->lock
);
412 if (!cache
->caching_ctl
) {
413 spin_unlock(&cache
->lock
);
417 ctl
= cache
->caching_ctl
;
418 refcount_inc(&ctl
->count
);
419 spin_unlock(&cache
->lock
);
423 void btrfs_put_caching_control(struct btrfs_caching_control
*ctl
)
425 if (refcount_dec_and_test(&ctl
->count
))
430 * When we wait for progress in the block group caching, its because our
431 * allocation attempt failed at least once. So, we must sleep and let some
432 * progress happen before we try again.
434 * This function will sleep at least once waiting for new free space to show
435 * up, and then it will check the block group free space numbers for our min
436 * num_bytes. Another option is to have it go ahead and look in the rbtree for
437 * a free extent of a given size, but this is a good start.
439 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
440 * any of the information in this block group.
442 void btrfs_wait_block_group_cache_progress(struct btrfs_block_group
*cache
,
445 struct btrfs_caching_control
*caching_ctl
;
447 caching_ctl
= btrfs_get_caching_control(cache
);
451 wait_event(caching_ctl
->wait
, btrfs_block_group_done(cache
) ||
452 (cache
->free_space_ctl
->free_space
>= num_bytes
));
454 btrfs_put_caching_control(caching_ctl
);
457 static int btrfs_caching_ctl_wait_done(struct btrfs_block_group
*cache
,
458 struct btrfs_caching_control
*caching_ctl
)
460 wait_event(caching_ctl
->wait
, btrfs_block_group_done(cache
));
461 return cache
->cached
== BTRFS_CACHE_ERROR
? -EIO
: 0;
464 static int btrfs_wait_block_group_cache_done(struct btrfs_block_group
*cache
)
466 struct btrfs_caching_control
*caching_ctl
;
469 caching_ctl
= btrfs_get_caching_control(cache
);
471 return (cache
->cached
== BTRFS_CACHE_ERROR
) ? -EIO
: 0;
472 ret
= btrfs_caching_ctl_wait_done(cache
, caching_ctl
);
473 btrfs_put_caching_control(caching_ctl
);
477 #ifdef CONFIG_BTRFS_DEBUG
478 static void fragment_free_space(struct btrfs_block_group
*block_group
)
480 struct btrfs_fs_info
*fs_info
= block_group
->fs_info
;
481 u64 start
= block_group
->start
;
482 u64 len
= block_group
->length
;
483 u64 chunk
= block_group
->flags
& BTRFS_BLOCK_GROUP_METADATA
?
484 fs_info
->nodesize
: fs_info
->sectorsize
;
485 u64 step
= chunk
<< 1;
487 while (len
> chunk
) {
488 btrfs_remove_free_space(block_group
, start
, chunk
);
499 * This is only called by btrfs_cache_block_group, since we could have freed
500 * extents we need to check the pinned_extents for any extents that can't be
501 * used yet since their free space will be released as soon as the transaction
504 u64
add_new_free_space(struct btrfs_block_group
*block_group
, u64 start
, u64 end
)
506 struct btrfs_fs_info
*info
= block_group
->fs_info
;
507 u64 extent_start
, extent_end
, size
, total_added
= 0;
510 while (start
< end
) {
511 ret
= find_first_extent_bit(&info
->excluded_extents
, start
,
512 &extent_start
, &extent_end
,
513 EXTENT_DIRTY
| EXTENT_UPTODATE
,
518 if (extent_start
<= start
) {
519 start
= extent_end
+ 1;
520 } else if (extent_start
> start
&& extent_start
< end
) {
521 size
= extent_start
- start
;
523 ret
= btrfs_add_free_space_async_trimmed(block_group
,
525 BUG_ON(ret
); /* -ENOMEM or logic error */
526 start
= extent_end
+ 1;
535 ret
= btrfs_add_free_space_async_trimmed(block_group
, start
,
537 BUG_ON(ret
); /* -ENOMEM or logic error */
544 * Get an arbitrary extent item index / max_index through the block group
546 * @block_group the block group to sample from
547 * @index: the integral step through the block group to grab from
548 * @max_index: the granularity of the sampling
549 * @key: return value parameter for the item we find
551 * Pre-conditions on indices:
552 * 0 <= index <= max_index
555 * Returns: 0 on success, 1 if the search didn't yield a useful item, negative
556 * error code on error.
558 static int sample_block_group_extent_item(struct btrfs_caching_control
*caching_ctl
,
559 struct btrfs_block_group
*block_group
,
560 int index
, int max_index
,
561 struct btrfs_key
*found_key
)
563 struct btrfs_fs_info
*fs_info
= block_group
->fs_info
;
564 struct btrfs_root
*extent_root
;
566 u64 search_end
= block_group
->start
+ block_group
->length
;
567 struct btrfs_path
*path
;
568 struct btrfs_key search_key
;
572 ASSERT(index
<= max_index
);
573 ASSERT(max_index
> 0);
574 lockdep_assert_held(&caching_ctl
->mutex
);
575 lockdep_assert_held_read(&fs_info
->commit_root_sem
);
577 path
= btrfs_alloc_path();
581 extent_root
= btrfs_extent_root(fs_info
, max_t(u64
, block_group
->start
,
582 BTRFS_SUPER_INFO_OFFSET
));
584 path
->skip_locking
= 1;
585 path
->search_commit_root
= 1;
586 path
->reada
= READA_FORWARD
;
588 search_offset
= index
* div_u64(block_group
->length
, max_index
);
589 search_key
.objectid
= block_group
->start
+ search_offset
;
590 search_key
.type
= BTRFS_EXTENT_ITEM_KEY
;
591 search_key
.offset
= 0;
593 btrfs_for_each_slot(extent_root
, &search_key
, found_key
, path
, ret
) {
594 /* Success; sampled an extent item in the block group */
595 if (found_key
->type
== BTRFS_EXTENT_ITEM_KEY
&&
596 found_key
->objectid
>= block_group
->start
&&
597 found_key
->objectid
+ found_key
->offset
<= search_end
)
600 /* We can't possibly find a valid extent item anymore */
601 if (found_key
->objectid
>= search_end
) {
607 lockdep_assert_held(&caching_ctl
->mutex
);
608 lockdep_assert_held_read(&fs_info
->commit_root_sem
);
609 btrfs_free_path(path
);
614 * Best effort attempt to compute a block group's size class while caching it.
616 * @block_group: the block group we are caching
618 * We cannot infer the size class while adding free space extents, because that
619 * logic doesn't care about contiguous file extents (it doesn't differentiate
620 * between a 100M extent and 100 contiguous 1M extents). So we need to read the
621 * file extent items. Reading all of them is quite wasteful, because usually
622 * only a handful are enough to give a good answer. Therefore, we just grab 5 of
623 * them at even steps through the block group and pick the smallest size class
624 * we see. Since size class is best effort, and not guaranteed in general,
625 * inaccuracy is acceptable.
627 * To be more explicit about why this algorithm makes sense:
629 * If we are caching in a block group from disk, then there are three major cases
631 * 1. the block group is well behaved and all extents in it are the same size
633 * 2. the block group is mostly one size class with rare exceptions for last
635 * 3. the block group was populated before size classes and can have a totally
636 * arbitrary mix of size classes.
638 * In case 1, looking at any extent in the block group will yield the correct
639 * result. For the mixed cases, taking the minimum size class seems like a good
640 * approximation, since gaps from frees will be usable to the size class. For
641 * 2., a small handful of file extents is likely to yield the right answer. For
642 * 3, we can either read every file extent, or admit that this is best effort
643 * anyway and try to stay fast.
645 * Returns: 0 on success, negative error code on error.
647 static int load_block_group_size_class(struct btrfs_caching_control
*caching_ctl
,
648 struct btrfs_block_group
*block_group
)
650 struct btrfs_fs_info
*fs_info
= block_group
->fs_info
;
651 struct btrfs_key key
;
653 u64 min_size
= block_group
->length
;
654 enum btrfs_block_group_size_class size_class
= BTRFS_BG_SZ_NONE
;
657 if (!btrfs_block_group_should_use_size_class(block_group
))
660 lockdep_assert_held(&caching_ctl
->mutex
);
661 lockdep_assert_held_read(&fs_info
->commit_root_sem
);
662 for (i
= 0; i
< 5; ++i
) {
663 ret
= sample_block_group_extent_item(caching_ctl
, block_group
, i
, 5, &key
);
668 min_size
= min_t(u64
, min_size
, key
.offset
);
669 size_class
= btrfs_calc_block_group_size_class(min_size
);
671 if (size_class
!= BTRFS_BG_SZ_NONE
) {
672 spin_lock(&block_group
->lock
);
673 block_group
->size_class
= size_class
;
674 spin_unlock(&block_group
->lock
);
680 static int load_extent_tree_free(struct btrfs_caching_control
*caching_ctl
)
682 struct btrfs_block_group
*block_group
= caching_ctl
->block_group
;
683 struct btrfs_fs_info
*fs_info
= block_group
->fs_info
;
684 struct btrfs_root
*extent_root
;
685 struct btrfs_path
*path
;
686 struct extent_buffer
*leaf
;
687 struct btrfs_key key
;
694 path
= btrfs_alloc_path();
698 last
= max_t(u64
, block_group
->start
, BTRFS_SUPER_INFO_OFFSET
);
699 extent_root
= btrfs_extent_root(fs_info
, last
);
701 #ifdef CONFIG_BTRFS_DEBUG
703 * If we're fragmenting we don't want to make anybody think we can
704 * allocate from this block group until we've had a chance to fragment
707 if (btrfs_should_fragment_free_space(block_group
))
711 * We don't want to deadlock with somebody trying to allocate a new
712 * extent for the extent root while also trying to search the extent
713 * root to add free space. So we skip locking and search the commit
714 * root, since its read-only
716 path
->skip_locking
= 1;
717 path
->search_commit_root
= 1;
718 path
->reada
= READA_FORWARD
;
722 key
.type
= BTRFS_EXTENT_ITEM_KEY
;
725 ret
= btrfs_search_slot(NULL
, extent_root
, &key
, path
, 0, 0);
729 leaf
= path
->nodes
[0];
730 nritems
= btrfs_header_nritems(leaf
);
733 if (btrfs_fs_closing(fs_info
) > 1) {
738 if (path
->slots
[0] < nritems
) {
739 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0]);
741 ret
= btrfs_find_next_key(extent_root
, path
, &key
, 0, 0);
745 if (need_resched() ||
746 rwsem_is_contended(&fs_info
->commit_root_sem
)) {
747 btrfs_release_path(path
);
748 up_read(&fs_info
->commit_root_sem
);
749 mutex_unlock(&caching_ctl
->mutex
);
751 mutex_lock(&caching_ctl
->mutex
);
752 down_read(&fs_info
->commit_root_sem
);
756 ret
= btrfs_next_leaf(extent_root
, path
);
761 leaf
= path
->nodes
[0];
762 nritems
= btrfs_header_nritems(leaf
);
766 if (key
.objectid
< last
) {
769 key
.type
= BTRFS_EXTENT_ITEM_KEY
;
770 btrfs_release_path(path
);
774 if (key
.objectid
< block_group
->start
) {
779 if (key
.objectid
>= block_group
->start
+ block_group
->length
)
782 if (key
.type
== BTRFS_EXTENT_ITEM_KEY
||
783 key
.type
== BTRFS_METADATA_ITEM_KEY
) {
784 total_found
+= add_new_free_space(block_group
, last
,
786 if (key
.type
== BTRFS_METADATA_ITEM_KEY
)
787 last
= key
.objectid
+
790 last
= key
.objectid
+ key
.offset
;
792 if (total_found
> CACHING_CTL_WAKE_UP
) {
795 wake_up(&caching_ctl
->wait
);
802 total_found
+= add_new_free_space(block_group
, last
,
803 block_group
->start
+ block_group
->length
);
806 btrfs_free_path(path
);
810 static noinline
void caching_thread(struct btrfs_work
*work
)
812 struct btrfs_block_group
*block_group
;
813 struct btrfs_fs_info
*fs_info
;
814 struct btrfs_caching_control
*caching_ctl
;
817 caching_ctl
= container_of(work
, struct btrfs_caching_control
, work
);
818 block_group
= caching_ctl
->block_group
;
819 fs_info
= block_group
->fs_info
;
821 mutex_lock(&caching_ctl
->mutex
);
822 down_read(&fs_info
->commit_root_sem
);
824 load_block_group_size_class(caching_ctl
, block_group
);
825 if (btrfs_test_opt(fs_info
, SPACE_CACHE
)) {
826 ret
= load_free_space_cache(block_group
);
833 * We failed to load the space cache, set ourselves to
834 * CACHE_STARTED and carry on.
836 spin_lock(&block_group
->lock
);
837 block_group
->cached
= BTRFS_CACHE_STARTED
;
838 spin_unlock(&block_group
->lock
);
839 wake_up(&caching_ctl
->wait
);
843 * If we are in the transaction that populated the free space tree we
844 * can't actually cache from the free space tree as our commit root and
845 * real root are the same, so we could change the contents of the blocks
846 * while caching. Instead do the slow caching in this case, and after
847 * the transaction has committed we will be safe.
849 if (btrfs_fs_compat_ro(fs_info
, FREE_SPACE_TREE
) &&
850 !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED
, &fs_info
->flags
)))
851 ret
= load_free_space_tree(caching_ctl
);
853 ret
= load_extent_tree_free(caching_ctl
);
855 spin_lock(&block_group
->lock
);
856 block_group
->caching_ctl
= NULL
;
857 block_group
->cached
= ret
? BTRFS_CACHE_ERROR
: BTRFS_CACHE_FINISHED
;
858 spin_unlock(&block_group
->lock
);
860 #ifdef CONFIG_BTRFS_DEBUG
861 if (btrfs_should_fragment_free_space(block_group
)) {
864 spin_lock(&block_group
->space_info
->lock
);
865 spin_lock(&block_group
->lock
);
866 bytes_used
= block_group
->length
- block_group
->used
;
867 block_group
->space_info
->bytes_used
+= bytes_used
>> 1;
868 spin_unlock(&block_group
->lock
);
869 spin_unlock(&block_group
->space_info
->lock
);
870 fragment_free_space(block_group
);
874 up_read(&fs_info
->commit_root_sem
);
875 btrfs_free_excluded_extents(block_group
);
876 mutex_unlock(&caching_ctl
->mutex
);
878 wake_up(&caching_ctl
->wait
);
880 btrfs_put_caching_control(caching_ctl
);
881 btrfs_put_block_group(block_group
);
884 int btrfs_cache_block_group(struct btrfs_block_group
*cache
, bool wait
)
886 struct btrfs_fs_info
*fs_info
= cache
->fs_info
;
887 struct btrfs_caching_control
*caching_ctl
= NULL
;
890 /* Allocator for zoned filesystems does not use the cache at all */
891 if (btrfs_is_zoned(fs_info
))
894 caching_ctl
= kzalloc(sizeof(*caching_ctl
), GFP_NOFS
);
898 INIT_LIST_HEAD(&caching_ctl
->list
);
899 mutex_init(&caching_ctl
->mutex
);
900 init_waitqueue_head(&caching_ctl
->wait
);
901 caching_ctl
->block_group
= cache
;
902 refcount_set(&caching_ctl
->count
, 2);
903 btrfs_init_work(&caching_ctl
->work
, caching_thread
, NULL
, NULL
);
905 spin_lock(&cache
->lock
);
906 if (cache
->cached
!= BTRFS_CACHE_NO
) {
909 caching_ctl
= cache
->caching_ctl
;
911 refcount_inc(&caching_ctl
->count
);
912 spin_unlock(&cache
->lock
);
915 WARN_ON(cache
->caching_ctl
);
916 cache
->caching_ctl
= caching_ctl
;
917 cache
->cached
= BTRFS_CACHE_STARTED
;
918 spin_unlock(&cache
->lock
);
920 write_lock(&fs_info
->block_group_cache_lock
);
921 refcount_inc(&caching_ctl
->count
);
922 list_add_tail(&caching_ctl
->list
, &fs_info
->caching_block_groups
);
923 write_unlock(&fs_info
->block_group_cache_lock
);
925 btrfs_get_block_group(cache
);
927 btrfs_queue_work(fs_info
->caching_workers
, &caching_ctl
->work
);
929 if (wait
&& caching_ctl
)
930 ret
= btrfs_caching_ctl_wait_done(cache
, caching_ctl
);
932 btrfs_put_caching_control(caching_ctl
);
937 static void clear_avail_alloc_bits(struct btrfs_fs_info
*fs_info
, u64 flags
)
939 u64 extra_flags
= chunk_to_extended(flags
) &
940 BTRFS_EXTENDED_PROFILE_MASK
;
942 write_seqlock(&fs_info
->profiles_lock
);
943 if (flags
& BTRFS_BLOCK_GROUP_DATA
)
944 fs_info
->avail_data_alloc_bits
&= ~extra_flags
;
945 if (flags
& BTRFS_BLOCK_GROUP_METADATA
)
946 fs_info
->avail_metadata_alloc_bits
&= ~extra_flags
;
947 if (flags
& BTRFS_BLOCK_GROUP_SYSTEM
)
948 fs_info
->avail_system_alloc_bits
&= ~extra_flags
;
949 write_sequnlock(&fs_info
->profiles_lock
);
953 * Clear incompat bits for the following feature(s):
955 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
956 * in the whole filesystem
958 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
960 static void clear_incompat_bg_bits(struct btrfs_fs_info
*fs_info
, u64 flags
)
962 bool found_raid56
= false;
963 bool found_raid1c34
= false;
965 if ((flags
& BTRFS_BLOCK_GROUP_RAID56_MASK
) ||
966 (flags
& BTRFS_BLOCK_GROUP_RAID1C3
) ||
967 (flags
& BTRFS_BLOCK_GROUP_RAID1C4
)) {
968 struct list_head
*head
= &fs_info
->space_info
;
969 struct btrfs_space_info
*sinfo
;
971 list_for_each_entry_rcu(sinfo
, head
, list
) {
972 down_read(&sinfo
->groups_sem
);
973 if (!list_empty(&sinfo
->block_groups
[BTRFS_RAID_RAID5
]))
975 if (!list_empty(&sinfo
->block_groups
[BTRFS_RAID_RAID6
]))
977 if (!list_empty(&sinfo
->block_groups
[BTRFS_RAID_RAID1C3
]))
978 found_raid1c34
= true;
979 if (!list_empty(&sinfo
->block_groups
[BTRFS_RAID_RAID1C4
]))
980 found_raid1c34
= true;
981 up_read(&sinfo
->groups_sem
);
984 btrfs_clear_fs_incompat(fs_info
, RAID56
);
986 btrfs_clear_fs_incompat(fs_info
, RAID1C34
);
990 static int remove_block_group_item(struct btrfs_trans_handle
*trans
,
991 struct btrfs_path
*path
,
992 struct btrfs_block_group
*block_group
)
994 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
995 struct btrfs_root
*root
;
996 struct btrfs_key key
;
999 root
= btrfs_block_group_root(fs_info
);
1000 key
.objectid
= block_group
->start
;
1001 key
.type
= BTRFS_BLOCK_GROUP_ITEM_KEY
;
1002 key
.offset
= block_group
->length
;
1004 ret
= btrfs_search_slot(trans
, root
, &key
, path
, -1, 1);
1010 ret
= btrfs_del_item(trans
, root
, path
);
1014 int btrfs_remove_block_group(struct btrfs_trans_handle
*trans
,
1015 u64 group_start
, struct extent_map
*em
)
1017 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
1018 struct btrfs_path
*path
;
1019 struct btrfs_block_group
*block_group
;
1020 struct btrfs_free_cluster
*cluster
;
1021 struct inode
*inode
;
1022 struct kobject
*kobj
= NULL
;
1026 struct btrfs_caching_control
*caching_ctl
= NULL
;
1028 bool remove_rsv
= false;
1030 block_group
= btrfs_lookup_block_group(fs_info
, group_start
);
1031 BUG_ON(!block_group
);
1032 BUG_ON(!block_group
->ro
);
1034 trace_btrfs_remove_block_group(block_group
);
1036 * Free the reserved super bytes from this block group before
1039 btrfs_free_excluded_extents(block_group
);
1040 btrfs_free_ref_tree_range(fs_info
, block_group
->start
,
1041 block_group
->length
);
1043 index
= btrfs_bg_flags_to_raid_index(block_group
->flags
);
1044 factor
= btrfs_bg_type_to_factor(block_group
->flags
);
1046 /* make sure this block group isn't part of an allocation cluster */
1047 cluster
= &fs_info
->data_alloc_cluster
;
1048 spin_lock(&cluster
->refill_lock
);
1049 btrfs_return_cluster_to_free_space(block_group
, cluster
);
1050 spin_unlock(&cluster
->refill_lock
);
1053 * make sure this block group isn't part of a metadata
1054 * allocation cluster
1056 cluster
= &fs_info
->meta_alloc_cluster
;
1057 spin_lock(&cluster
->refill_lock
);
1058 btrfs_return_cluster_to_free_space(block_group
, cluster
);
1059 spin_unlock(&cluster
->refill_lock
);
1061 btrfs_clear_treelog_bg(block_group
);
1062 btrfs_clear_data_reloc_bg(block_group
);
1064 path
= btrfs_alloc_path();
1071 * get the inode first so any iput calls done for the io_list
1072 * aren't the final iput (no unlinks allowed now)
1074 inode
= lookup_free_space_inode(block_group
, path
);
1076 mutex_lock(&trans
->transaction
->cache_write_mutex
);
1078 * Make sure our free space cache IO is done before removing the
1081 spin_lock(&trans
->transaction
->dirty_bgs_lock
);
1082 if (!list_empty(&block_group
->io_list
)) {
1083 list_del_init(&block_group
->io_list
);
1085 WARN_ON(!IS_ERR(inode
) && inode
!= block_group
->io_ctl
.inode
);
1087 spin_unlock(&trans
->transaction
->dirty_bgs_lock
);
1088 btrfs_wait_cache_io(trans
, block_group
, path
);
1089 btrfs_put_block_group(block_group
);
1090 spin_lock(&trans
->transaction
->dirty_bgs_lock
);
1093 if (!list_empty(&block_group
->dirty_list
)) {
1094 list_del_init(&block_group
->dirty_list
);
1096 btrfs_put_block_group(block_group
);
1098 spin_unlock(&trans
->transaction
->dirty_bgs_lock
);
1099 mutex_unlock(&trans
->transaction
->cache_write_mutex
);
1101 ret
= btrfs_remove_free_space_inode(trans
, inode
, block_group
);
1105 write_lock(&fs_info
->block_group_cache_lock
);
1106 rb_erase_cached(&block_group
->cache_node
,
1107 &fs_info
->block_group_cache_tree
);
1108 RB_CLEAR_NODE(&block_group
->cache_node
);
1110 /* Once for the block groups rbtree */
1111 btrfs_put_block_group(block_group
);
1113 write_unlock(&fs_info
->block_group_cache_lock
);
1115 down_write(&block_group
->space_info
->groups_sem
);
1117 * we must use list_del_init so people can check to see if they
1118 * are still on the list after taking the semaphore
1120 list_del_init(&block_group
->list
);
1121 if (list_empty(&block_group
->space_info
->block_groups
[index
])) {
1122 kobj
= block_group
->space_info
->block_group_kobjs
[index
];
1123 block_group
->space_info
->block_group_kobjs
[index
] = NULL
;
1124 clear_avail_alloc_bits(fs_info
, block_group
->flags
);
1126 up_write(&block_group
->space_info
->groups_sem
);
1127 clear_incompat_bg_bits(fs_info
, block_group
->flags
);
1133 if (block_group
->cached
== BTRFS_CACHE_STARTED
)
1134 btrfs_wait_block_group_cache_done(block_group
);
1136 write_lock(&fs_info
->block_group_cache_lock
);
1137 caching_ctl
= btrfs_get_caching_control(block_group
);
1139 struct btrfs_caching_control
*ctl
;
1141 list_for_each_entry(ctl
, &fs_info
->caching_block_groups
, list
) {
1142 if (ctl
->block_group
== block_group
) {
1144 refcount_inc(&caching_ctl
->count
);
1150 list_del_init(&caching_ctl
->list
);
1151 write_unlock(&fs_info
->block_group_cache_lock
);
1154 /* Once for the caching bgs list and once for us. */
1155 btrfs_put_caching_control(caching_ctl
);
1156 btrfs_put_caching_control(caching_ctl
);
1159 spin_lock(&trans
->transaction
->dirty_bgs_lock
);
1160 WARN_ON(!list_empty(&block_group
->dirty_list
));
1161 WARN_ON(!list_empty(&block_group
->io_list
));
1162 spin_unlock(&trans
->transaction
->dirty_bgs_lock
);
1164 btrfs_remove_free_space_cache(block_group
);
1166 spin_lock(&block_group
->space_info
->lock
);
1167 list_del_init(&block_group
->ro_list
);
1169 if (btrfs_test_opt(fs_info
, ENOSPC_DEBUG
)) {
1170 WARN_ON(block_group
->space_info
->total_bytes
1171 < block_group
->length
);
1172 WARN_ON(block_group
->space_info
->bytes_readonly
1173 < block_group
->length
- block_group
->zone_unusable
);
1174 WARN_ON(block_group
->space_info
->bytes_zone_unusable
1175 < block_group
->zone_unusable
);
1176 WARN_ON(block_group
->space_info
->disk_total
1177 < block_group
->length
* factor
);
1178 WARN_ON(test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE
,
1179 &block_group
->runtime_flags
) &&
1180 block_group
->space_info
->active_total_bytes
1181 < block_group
->length
);
1183 block_group
->space_info
->total_bytes
-= block_group
->length
;
1184 if (test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE
, &block_group
->runtime_flags
))
1185 block_group
->space_info
->active_total_bytes
-= block_group
->length
;
1186 block_group
->space_info
->bytes_readonly
-=
1187 (block_group
->length
- block_group
->zone_unusable
);
1188 block_group
->space_info
->bytes_zone_unusable
-=
1189 block_group
->zone_unusable
;
1190 block_group
->space_info
->disk_total
-= block_group
->length
* factor
;
1192 spin_unlock(&block_group
->space_info
->lock
);
1195 * Remove the free space for the block group from the free space tree
1196 * and the block group's item from the extent tree before marking the
1197 * block group as removed. This is to prevent races with tasks that
1198 * freeze and unfreeze a block group, this task and another task
1199 * allocating a new block group - the unfreeze task ends up removing
1200 * the block group's extent map before the task calling this function
1201 * deletes the block group item from the extent tree, allowing for
1202 * another task to attempt to create another block group with the same
1203 * item key (and failing with -EEXIST and a transaction abort).
1205 ret
= remove_block_group_free_space(trans
, block_group
);
1209 ret
= remove_block_group_item(trans
, path
, block_group
);
1213 spin_lock(&block_group
->lock
);
1214 set_bit(BLOCK_GROUP_FLAG_REMOVED
, &block_group
->runtime_flags
);
1217 * At this point trimming or scrub can't start on this block group,
1218 * because we removed the block group from the rbtree
1219 * fs_info->block_group_cache_tree so no one can't find it anymore and
1220 * even if someone already got this block group before we removed it
1221 * from the rbtree, they have already incremented block_group->frozen -
1222 * if they didn't, for the trimming case they won't find any free space
1223 * entries because we already removed them all when we called
1224 * btrfs_remove_free_space_cache().
1226 * And we must not remove the extent map from the fs_info->mapping_tree
1227 * to prevent the same logical address range and physical device space
1228 * ranges from being reused for a new block group. This is needed to
1229 * avoid races with trimming and scrub.
1231 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
1232 * completely transactionless, so while it is trimming a range the
1233 * currently running transaction might finish and a new one start,
1234 * allowing for new block groups to be created that can reuse the same
1235 * physical device locations unless we take this special care.
1237 * There may also be an implicit trim operation if the file system
1238 * is mounted with -odiscard. The same protections must remain
1239 * in place until the extents have been discarded completely when
1240 * the transaction commit has completed.
1242 remove_em
= (atomic_read(&block_group
->frozen
) == 0);
1243 spin_unlock(&block_group
->lock
);
1246 struct extent_map_tree
*em_tree
;
1248 em_tree
= &fs_info
->mapping_tree
;
1249 write_lock(&em_tree
->lock
);
1250 remove_extent_mapping(em_tree
, em
);
1251 write_unlock(&em_tree
->lock
);
1252 /* once for the tree */
1253 free_extent_map(em
);
1257 /* Once for the lookup reference */
1258 btrfs_put_block_group(block_group
);
1260 btrfs_delayed_refs_rsv_release(fs_info
, 1);
1261 btrfs_free_path(path
);
1265 struct btrfs_trans_handle
*btrfs_start_trans_remove_block_group(
1266 struct btrfs_fs_info
*fs_info
, const u64 chunk_offset
)
1268 struct btrfs_root
*root
= btrfs_block_group_root(fs_info
);
1269 struct extent_map_tree
*em_tree
= &fs_info
->mapping_tree
;
1270 struct extent_map
*em
;
1271 struct map_lookup
*map
;
1272 unsigned int num_items
;
1274 read_lock(&em_tree
->lock
);
1275 em
= lookup_extent_mapping(em_tree
, chunk_offset
, 1);
1276 read_unlock(&em_tree
->lock
);
1277 ASSERT(em
&& em
->start
== chunk_offset
);
1280 * We need to reserve 3 + N units from the metadata space info in order
1281 * to remove a block group (done at btrfs_remove_chunk() and at
1282 * btrfs_remove_block_group()), which are used for:
1284 * 1 unit for adding the free space inode's orphan (located in the tree
1286 * 1 unit for deleting the block group item (located in the extent
1288 * 1 unit for deleting the free space item (located in tree of tree
1290 * N units for deleting N device extent items corresponding to each
1291 * stripe (located in the device tree).
1293 * In order to remove a block group we also need to reserve units in the
1294 * system space info in order to update the chunk tree (update one or
1295 * more device items and remove one chunk item), but this is done at
1296 * btrfs_remove_chunk() through a call to check_system_chunk().
1298 map
= em
->map_lookup
;
1299 num_items
= 3 + map
->num_stripes
;
1300 free_extent_map(em
);
1302 return btrfs_start_transaction_fallback_global_rsv(root
, num_items
);
1306 * Mark block group @cache read-only, so later write won't happen to block
1309 * If @force is not set, this function will only mark the block group readonly
1310 * if we have enough free space (1M) in other metadata/system block groups.
1311 * If @force is not set, this function will mark the block group readonly
1312 * without checking free space.
1314 * NOTE: This function doesn't care if other block groups can contain all the
1315 * data in this block group. That check should be done by relocation routine,
1316 * not this function.
1318 static int inc_block_group_ro(struct btrfs_block_group
*cache
, int force
)
1320 struct btrfs_space_info
*sinfo
= cache
->space_info
;
1324 spin_lock(&sinfo
->lock
);
1325 spin_lock(&cache
->lock
);
1327 if (cache
->swap_extents
) {
1338 num_bytes
= cache
->length
- cache
->reserved
- cache
->pinned
-
1339 cache
->bytes_super
- cache
->zone_unusable
- cache
->used
;
1342 * Data never overcommits, even in mixed mode, so do just the straight
1343 * check of left over space in how much we have allocated.
1347 } else if (sinfo
->flags
& BTRFS_BLOCK_GROUP_DATA
) {
1348 u64 sinfo_used
= btrfs_space_info_used(sinfo
, true);
1351 * Here we make sure if we mark this bg RO, we still have enough
1352 * free space as buffer.
1354 if (sinfo_used
+ num_bytes
<= sinfo
->total_bytes
)
1358 * We overcommit metadata, so we need to do the
1359 * btrfs_can_overcommit check here, and we need to pass in
1360 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1361 * leeway to allow us to mark this block group as read only.
1363 if (btrfs_can_overcommit(cache
->fs_info
, sinfo
, num_bytes
,
1364 BTRFS_RESERVE_NO_FLUSH
))
1369 sinfo
->bytes_readonly
+= num_bytes
;
1370 if (btrfs_is_zoned(cache
->fs_info
)) {
1371 /* Migrate zone_unusable bytes to readonly */
1372 sinfo
->bytes_readonly
+= cache
->zone_unusable
;
1373 sinfo
->bytes_zone_unusable
-= cache
->zone_unusable
;
1374 cache
->zone_unusable
= 0;
1377 list_add_tail(&cache
->ro_list
, &sinfo
->ro_bgs
);
1380 spin_unlock(&cache
->lock
);
1381 spin_unlock(&sinfo
->lock
);
1382 if (ret
== -ENOSPC
&& btrfs_test_opt(cache
->fs_info
, ENOSPC_DEBUG
)) {
1383 btrfs_info(cache
->fs_info
,
1384 "unable to make block group %llu ro", cache
->start
);
1385 btrfs_dump_space_info(cache
->fs_info
, cache
->space_info
, 0, 0);
1390 static bool clean_pinned_extents(struct btrfs_trans_handle
*trans
,
1391 struct btrfs_block_group
*bg
)
1393 struct btrfs_fs_info
*fs_info
= bg
->fs_info
;
1394 struct btrfs_transaction
*prev_trans
= NULL
;
1395 const u64 start
= bg
->start
;
1396 const u64 end
= start
+ bg
->length
- 1;
1399 spin_lock(&fs_info
->trans_lock
);
1400 if (trans
->transaction
->list
.prev
!= &fs_info
->trans_list
) {
1401 prev_trans
= list_last_entry(&trans
->transaction
->list
,
1402 struct btrfs_transaction
, list
);
1403 refcount_inc(&prev_trans
->use_count
);
1405 spin_unlock(&fs_info
->trans_lock
);
1408 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1409 * btrfs_finish_extent_commit(). If we are at transaction N, another
1410 * task might be running finish_extent_commit() for the previous
1411 * transaction N - 1, and have seen a range belonging to the block
1412 * group in pinned_extents before we were able to clear the whole block
1413 * group range from pinned_extents. This means that task can lookup for
1414 * the block group after we unpinned it from pinned_extents and removed
1415 * it, leading to a BUG_ON() at unpin_extent_range().
1417 mutex_lock(&fs_info
->unused_bg_unpin_mutex
);
1419 ret
= clear_extent_bits(&prev_trans
->pinned_extents
, start
, end
,
1425 ret
= clear_extent_bits(&trans
->transaction
->pinned_extents
, start
, end
,
1428 mutex_unlock(&fs_info
->unused_bg_unpin_mutex
);
1430 btrfs_put_transaction(prev_trans
);
1436 * Process the unused_bgs list and remove any that don't have any allocated
1437 * space inside of them.
1439 void btrfs_delete_unused_bgs(struct btrfs_fs_info
*fs_info
)
1441 struct btrfs_block_group
*block_group
;
1442 struct btrfs_space_info
*space_info
;
1443 struct btrfs_trans_handle
*trans
;
1444 const bool async_trim_enabled
= btrfs_test_opt(fs_info
, DISCARD_ASYNC
);
1447 if (!test_bit(BTRFS_FS_OPEN
, &fs_info
->flags
))
1450 if (btrfs_fs_closing(fs_info
))
1454 * Long running balances can keep us blocked here for eternity, so
1455 * simply skip deletion if we're unable to get the mutex.
1457 if (!mutex_trylock(&fs_info
->reclaim_bgs_lock
))
1460 spin_lock(&fs_info
->unused_bgs_lock
);
1461 while (!list_empty(&fs_info
->unused_bgs
)) {
1464 block_group
= list_first_entry(&fs_info
->unused_bgs
,
1465 struct btrfs_block_group
,
1467 list_del_init(&block_group
->bg_list
);
1469 space_info
= block_group
->space_info
;
1471 if (ret
|| btrfs_mixed_space_info(space_info
)) {
1472 btrfs_put_block_group(block_group
);
1475 spin_unlock(&fs_info
->unused_bgs_lock
);
1477 btrfs_discard_cancel_work(&fs_info
->discard_ctl
, block_group
);
1479 /* Don't want to race with allocators so take the groups_sem */
1480 down_write(&space_info
->groups_sem
);
1483 * Async discard moves the final block group discard to be prior
1484 * to the unused_bgs code path. Therefore, if it's not fully
1485 * trimmed, punt it back to the async discard lists.
1487 if (btrfs_test_opt(fs_info
, DISCARD_ASYNC
) &&
1488 !btrfs_is_free_space_trimmed(block_group
)) {
1489 trace_btrfs_skip_unused_block_group(block_group
);
1490 up_write(&space_info
->groups_sem
);
1491 /* Requeue if we failed because of async discard */
1492 btrfs_discard_queue_work(&fs_info
->discard_ctl
,
1497 spin_lock(&block_group
->lock
);
1498 if (block_group
->reserved
|| block_group
->pinned
||
1499 block_group
->used
|| block_group
->ro
||
1500 list_is_singular(&block_group
->list
)) {
1502 * We want to bail if we made new allocations or have
1503 * outstanding allocations in this block group. We do
1504 * the ro check in case balance is currently acting on
1507 trace_btrfs_skip_unused_block_group(block_group
);
1508 spin_unlock(&block_group
->lock
);
1509 up_write(&space_info
->groups_sem
);
1512 spin_unlock(&block_group
->lock
);
1514 /* We don't want to force the issue, only flip if it's ok. */
1515 ret
= inc_block_group_ro(block_group
, 0);
1516 up_write(&space_info
->groups_sem
);
1522 ret
= btrfs_zone_finish(block_group
);
1524 btrfs_dec_block_group_ro(block_group
);
1531 * Want to do this before we do anything else so we can recover
1532 * properly if we fail to join the transaction.
1534 trans
= btrfs_start_trans_remove_block_group(fs_info
,
1535 block_group
->start
);
1536 if (IS_ERR(trans
)) {
1537 btrfs_dec_block_group_ro(block_group
);
1538 ret
= PTR_ERR(trans
);
1543 * We could have pending pinned extents for this block group,
1544 * just delete them, we don't care about them anymore.
1546 if (!clean_pinned_extents(trans
, block_group
)) {
1547 btrfs_dec_block_group_ro(block_group
);
1552 * At this point, the block_group is read only and should fail
1553 * new allocations. However, btrfs_finish_extent_commit() can
1554 * cause this block_group to be placed back on the discard
1555 * lists because now the block_group isn't fully discarded.
1556 * Bail here and try again later after discarding everything.
1558 spin_lock(&fs_info
->discard_ctl
.lock
);
1559 if (!list_empty(&block_group
->discard_list
)) {
1560 spin_unlock(&fs_info
->discard_ctl
.lock
);
1561 btrfs_dec_block_group_ro(block_group
);
1562 btrfs_discard_queue_work(&fs_info
->discard_ctl
,
1566 spin_unlock(&fs_info
->discard_ctl
.lock
);
1568 /* Reset pinned so btrfs_put_block_group doesn't complain */
1569 spin_lock(&space_info
->lock
);
1570 spin_lock(&block_group
->lock
);
1572 btrfs_space_info_update_bytes_pinned(fs_info
, space_info
,
1573 -block_group
->pinned
);
1574 space_info
->bytes_readonly
+= block_group
->pinned
;
1575 block_group
->pinned
= 0;
1577 spin_unlock(&block_group
->lock
);
1578 spin_unlock(&space_info
->lock
);
1581 * The normal path here is an unused block group is passed here,
1582 * then trimming is handled in the transaction commit path.
1583 * Async discard interposes before this to do the trimming
1584 * before coming down the unused block group path as trimming
1585 * will no longer be done later in the transaction commit path.
1587 if (!async_trim_enabled
&& btrfs_test_opt(fs_info
, DISCARD_ASYNC
))
1591 * DISCARD can flip during remount. On zoned filesystems, we
1592 * need to reset sequential-required zones.
1594 trimming
= btrfs_test_opt(fs_info
, DISCARD_SYNC
) ||
1595 btrfs_is_zoned(fs_info
);
1597 /* Implicit trim during transaction commit. */
1599 btrfs_freeze_block_group(block_group
);
1602 * Btrfs_remove_chunk will abort the transaction if things go
1605 ret
= btrfs_remove_chunk(trans
, block_group
->start
);
1609 btrfs_unfreeze_block_group(block_group
);
1614 * If we're not mounted with -odiscard, we can just forget
1615 * about this block group. Otherwise we'll need to wait
1616 * until transaction commit to do the actual discard.
1619 spin_lock(&fs_info
->unused_bgs_lock
);
1621 * A concurrent scrub might have added us to the list
1622 * fs_info->unused_bgs, so use a list_move operation
1623 * to add the block group to the deleted_bgs list.
1625 list_move(&block_group
->bg_list
,
1626 &trans
->transaction
->deleted_bgs
);
1627 spin_unlock(&fs_info
->unused_bgs_lock
);
1628 btrfs_get_block_group(block_group
);
1631 btrfs_end_transaction(trans
);
1633 btrfs_put_block_group(block_group
);
1634 spin_lock(&fs_info
->unused_bgs_lock
);
1636 spin_unlock(&fs_info
->unused_bgs_lock
);
1637 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
1641 btrfs_end_transaction(trans
);
1642 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
1643 btrfs_put_block_group(block_group
);
1644 btrfs_discard_punt_unused_bgs_list(fs_info
);
1647 void btrfs_mark_bg_unused(struct btrfs_block_group
*bg
)
1649 struct btrfs_fs_info
*fs_info
= bg
->fs_info
;
1651 spin_lock(&fs_info
->unused_bgs_lock
);
1652 if (list_empty(&bg
->bg_list
)) {
1653 btrfs_get_block_group(bg
);
1654 trace_btrfs_add_unused_block_group(bg
);
1655 list_add_tail(&bg
->bg_list
, &fs_info
->unused_bgs
);
1657 spin_unlock(&fs_info
->unused_bgs_lock
);
1661 * We want block groups with a low number of used bytes to be in the beginning
1662 * of the list, so they will get reclaimed first.
1664 static int reclaim_bgs_cmp(void *unused
, const struct list_head
*a
,
1665 const struct list_head
*b
)
1667 const struct btrfs_block_group
*bg1
, *bg2
;
1669 bg1
= list_entry(a
, struct btrfs_block_group
, bg_list
);
1670 bg2
= list_entry(b
, struct btrfs_block_group
, bg_list
);
1672 return bg1
->used
> bg2
->used
;
1675 static inline bool btrfs_should_reclaim(struct btrfs_fs_info
*fs_info
)
1677 if (btrfs_is_zoned(fs_info
))
1678 return btrfs_zoned_should_reclaim(fs_info
);
1682 static bool should_reclaim_block_group(struct btrfs_block_group
*bg
, u64 bytes_freed
)
1684 const struct btrfs_space_info
*space_info
= bg
->space_info
;
1685 const int reclaim_thresh
= READ_ONCE(space_info
->bg_reclaim_threshold
);
1686 const u64 new_val
= bg
->used
;
1687 const u64 old_val
= new_val
+ bytes_freed
;
1690 if (reclaim_thresh
== 0)
1693 thresh
= mult_perc(bg
->length
, reclaim_thresh
);
1696 * If we were below the threshold before don't reclaim, we are likely a
1697 * brand new block group and we don't want to relocate new block groups.
1699 if (old_val
< thresh
)
1701 if (new_val
>= thresh
)
1706 void btrfs_reclaim_bgs_work(struct work_struct
*work
)
1708 struct btrfs_fs_info
*fs_info
=
1709 container_of(work
, struct btrfs_fs_info
, reclaim_bgs_work
);
1710 struct btrfs_block_group
*bg
;
1711 struct btrfs_space_info
*space_info
;
1713 if (!test_bit(BTRFS_FS_OPEN
, &fs_info
->flags
))
1716 if (btrfs_fs_closing(fs_info
))
1719 if (!btrfs_should_reclaim(fs_info
))
1722 sb_start_write(fs_info
->sb
);
1724 if (!btrfs_exclop_start(fs_info
, BTRFS_EXCLOP_BALANCE
)) {
1725 sb_end_write(fs_info
->sb
);
1730 * Long running balances can keep us blocked here for eternity, so
1731 * simply skip reclaim if we're unable to get the mutex.
1733 if (!mutex_trylock(&fs_info
->reclaim_bgs_lock
)) {
1734 btrfs_exclop_finish(fs_info
);
1735 sb_end_write(fs_info
->sb
);
1739 spin_lock(&fs_info
->unused_bgs_lock
);
1741 * Sort happens under lock because we can't simply splice it and sort.
1742 * The block groups might still be in use and reachable via bg_list,
1743 * and their presence in the reclaim_bgs list must be preserved.
1745 list_sort(NULL
, &fs_info
->reclaim_bgs
, reclaim_bgs_cmp
);
1746 while (!list_empty(&fs_info
->reclaim_bgs
)) {
1750 bg
= list_first_entry(&fs_info
->reclaim_bgs
,
1751 struct btrfs_block_group
,
1753 list_del_init(&bg
->bg_list
);
1755 space_info
= bg
->space_info
;
1756 spin_unlock(&fs_info
->unused_bgs_lock
);
1758 /* Don't race with allocators so take the groups_sem */
1759 down_write(&space_info
->groups_sem
);
1761 spin_lock(&bg
->lock
);
1762 if (bg
->reserved
|| bg
->pinned
|| bg
->ro
) {
1764 * We want to bail if we made new allocations or have
1765 * outstanding allocations in this block group. We do
1766 * the ro check in case balance is currently acting on
1769 spin_unlock(&bg
->lock
);
1770 up_write(&space_info
->groups_sem
);
1773 if (bg
->used
== 0) {
1775 * It is possible that we trigger relocation on a block
1776 * group as its extents are deleted and it first goes
1777 * below the threshold, then shortly after goes empty.
1779 * In this case, relocating it does delete it, but has
1780 * some overhead in relocation specific metadata, looking
1781 * for the non-existent extents and running some extra
1782 * transactions, which we can avoid by using one of the
1783 * other mechanisms for dealing with empty block groups.
1785 if (!btrfs_test_opt(fs_info
, DISCARD_ASYNC
))
1786 btrfs_mark_bg_unused(bg
);
1787 spin_unlock(&bg
->lock
);
1788 up_write(&space_info
->groups_sem
);
1793 * The block group might no longer meet the reclaim condition by
1794 * the time we get around to reclaiming it, so to avoid
1795 * reclaiming overly full block_groups, skip reclaiming them.
1797 * Since the decision making process also depends on the amount
1798 * being freed, pass in a fake giant value to skip that extra
1799 * check, which is more meaningful when adding to the list in
1802 if (!should_reclaim_block_group(bg
, bg
->length
)) {
1803 spin_unlock(&bg
->lock
);
1804 up_write(&space_info
->groups_sem
);
1807 spin_unlock(&bg
->lock
);
1809 /* Get out fast, in case we're unmounting the filesystem */
1810 if (btrfs_fs_closing(fs_info
)) {
1811 up_write(&space_info
->groups_sem
);
1816 * Cache the zone_unusable value before turning the block group
1817 * to read only. As soon as the blog group is read only it's
1818 * zone_unusable value gets moved to the block group's read-only
1819 * bytes and isn't available for calculations anymore.
1821 zone_unusable
= bg
->zone_unusable
;
1822 ret
= inc_block_group_ro(bg
, 0);
1823 up_write(&space_info
->groups_sem
);
1828 "reclaiming chunk %llu with %llu%% used %llu%% unusable",
1830 div64_u64(bg
->used
* 100, bg
->length
),
1831 div64_u64(zone_unusable
* 100, bg
->length
));
1832 trace_btrfs_reclaim_block_group(bg
);
1833 ret
= btrfs_relocate_chunk(fs_info
, bg
->start
);
1835 btrfs_dec_block_group_ro(bg
);
1836 btrfs_err(fs_info
, "error relocating chunk %llu",
1841 btrfs_put_block_group(bg
);
1842 spin_lock(&fs_info
->unused_bgs_lock
);
1844 spin_unlock(&fs_info
->unused_bgs_lock
);
1845 mutex_unlock(&fs_info
->reclaim_bgs_lock
);
1846 btrfs_exclop_finish(fs_info
);
1847 sb_end_write(fs_info
->sb
);
1850 void btrfs_reclaim_bgs(struct btrfs_fs_info
*fs_info
)
1852 spin_lock(&fs_info
->unused_bgs_lock
);
1853 if (!list_empty(&fs_info
->reclaim_bgs
))
1854 queue_work(system_unbound_wq
, &fs_info
->reclaim_bgs_work
);
1855 spin_unlock(&fs_info
->unused_bgs_lock
);
1858 void btrfs_mark_bg_to_reclaim(struct btrfs_block_group
*bg
)
1860 struct btrfs_fs_info
*fs_info
= bg
->fs_info
;
1862 spin_lock(&fs_info
->unused_bgs_lock
);
1863 if (list_empty(&bg
->bg_list
)) {
1864 btrfs_get_block_group(bg
);
1865 trace_btrfs_add_reclaim_block_group(bg
);
1866 list_add_tail(&bg
->bg_list
, &fs_info
->reclaim_bgs
);
1868 spin_unlock(&fs_info
->unused_bgs_lock
);
1871 static int read_bg_from_eb(struct btrfs_fs_info
*fs_info
, struct btrfs_key
*key
,
1872 struct btrfs_path
*path
)
1874 struct extent_map_tree
*em_tree
;
1875 struct extent_map
*em
;
1876 struct btrfs_block_group_item bg
;
1877 struct extent_buffer
*leaf
;
1882 slot
= path
->slots
[0];
1883 leaf
= path
->nodes
[0];
1885 em_tree
= &fs_info
->mapping_tree
;
1886 read_lock(&em_tree
->lock
);
1887 em
= lookup_extent_mapping(em_tree
, key
->objectid
, key
->offset
);
1888 read_unlock(&em_tree
->lock
);
1891 "logical %llu len %llu found bg but no related chunk",
1892 key
->objectid
, key
->offset
);
1896 if (em
->start
!= key
->objectid
|| em
->len
!= key
->offset
) {
1898 "block group %llu len %llu mismatch with chunk %llu len %llu",
1899 key
->objectid
, key
->offset
, em
->start
, em
->len
);
1904 read_extent_buffer(leaf
, &bg
, btrfs_item_ptr_offset(leaf
, slot
),
1906 flags
= btrfs_stack_block_group_flags(&bg
) &
1907 BTRFS_BLOCK_GROUP_TYPE_MASK
;
1909 if (flags
!= (em
->map_lookup
->type
& BTRFS_BLOCK_GROUP_TYPE_MASK
)) {
1911 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1912 key
->objectid
, key
->offset
, flags
,
1913 (BTRFS_BLOCK_GROUP_TYPE_MASK
& em
->map_lookup
->type
));
1918 free_extent_map(em
);
1922 static int find_first_block_group(struct btrfs_fs_info
*fs_info
,
1923 struct btrfs_path
*path
,
1924 struct btrfs_key
*key
)
1926 struct btrfs_root
*root
= btrfs_block_group_root(fs_info
);
1928 struct btrfs_key found_key
;
1930 btrfs_for_each_slot(root
, key
, &found_key
, path
, ret
) {
1931 if (found_key
.objectid
>= key
->objectid
&&
1932 found_key
.type
== BTRFS_BLOCK_GROUP_ITEM_KEY
) {
1933 return read_bg_from_eb(fs_info
, &found_key
, path
);
1939 static void set_avail_alloc_bits(struct btrfs_fs_info
*fs_info
, u64 flags
)
1941 u64 extra_flags
= chunk_to_extended(flags
) &
1942 BTRFS_EXTENDED_PROFILE_MASK
;
1944 write_seqlock(&fs_info
->profiles_lock
);
1945 if (flags
& BTRFS_BLOCK_GROUP_DATA
)
1946 fs_info
->avail_data_alloc_bits
|= extra_flags
;
1947 if (flags
& BTRFS_BLOCK_GROUP_METADATA
)
1948 fs_info
->avail_metadata_alloc_bits
|= extra_flags
;
1949 if (flags
& BTRFS_BLOCK_GROUP_SYSTEM
)
1950 fs_info
->avail_system_alloc_bits
|= extra_flags
;
1951 write_sequnlock(&fs_info
->profiles_lock
);
1955 * Map a physical disk address to a list of logical addresses.
1957 * @fs_info: the filesystem
1958 * @chunk_start: logical address of block group
1959 * @physical: physical address to map to logical addresses
1960 * @logical: return array of logical addresses which map to @physical
1961 * @naddrs: length of @logical
1962 * @stripe_len: size of IO stripe for the given block group
1964 * Maps a particular @physical disk address to a list of @logical addresses.
1965 * Used primarily to exclude those portions of a block group that contain super
1968 int btrfs_rmap_block(struct btrfs_fs_info
*fs_info
, u64 chunk_start
,
1969 u64 physical
, u64
**logical
, int *naddrs
, int *stripe_len
)
1971 struct extent_map
*em
;
1972 struct map_lookup
*map
;
1975 u64 data_stripe_length
;
1980 em
= btrfs_get_chunk_map(fs_info
, chunk_start
, 1);
1984 map
= em
->map_lookup
;
1985 data_stripe_length
= em
->orig_block_len
;
1986 io_stripe_size
= map
->stripe_len
;
1987 chunk_start
= em
->start
;
1989 /* For RAID5/6 adjust to a full IO stripe length */
1990 if (map
->type
& BTRFS_BLOCK_GROUP_RAID56_MASK
)
1991 io_stripe_size
= map
->stripe_len
* nr_data_stripes(map
);
1993 buf
= kcalloc(map
->num_stripes
, sizeof(u64
), GFP_NOFS
);
1999 for (i
= 0; i
< map
->num_stripes
; i
++) {
2000 bool already_inserted
= false;
2005 if (!in_range(physical
, map
->stripes
[i
].physical
,
2006 data_stripe_length
))
2009 stripe_nr
= physical
- map
->stripes
[i
].physical
;
2010 stripe_nr
= div64_u64_rem(stripe_nr
, map
->stripe_len
, &offset
);
2012 if (map
->type
& (BTRFS_BLOCK_GROUP_RAID0
|
2013 BTRFS_BLOCK_GROUP_RAID10
)) {
2014 stripe_nr
= stripe_nr
* map
->num_stripes
+ i
;
2015 stripe_nr
= div_u64(stripe_nr
, map
->sub_stripes
);
2018 * The remaining case would be for RAID56, multiply by
2019 * nr_data_stripes(). Alternatively, just use rmap_len below
2020 * instead of map->stripe_len
2023 bytenr
= chunk_start
+ stripe_nr
* io_stripe_size
+ offset
;
2025 /* Ensure we don't add duplicate addresses */
2026 for (j
= 0; j
< nr
; j
++) {
2027 if (buf
[j
] == bytenr
) {
2028 already_inserted
= true;
2033 if (!already_inserted
)
2039 *stripe_len
= io_stripe_size
;
2041 free_extent_map(em
);
2045 static int exclude_super_stripes(struct btrfs_block_group
*cache
)
2047 struct btrfs_fs_info
*fs_info
= cache
->fs_info
;
2048 const bool zoned
= btrfs_is_zoned(fs_info
);
2054 if (cache
->start
< BTRFS_SUPER_INFO_OFFSET
) {
2055 stripe_len
= BTRFS_SUPER_INFO_OFFSET
- cache
->start
;
2056 cache
->bytes_super
+= stripe_len
;
2057 ret
= btrfs_add_excluded_extent(fs_info
, cache
->start
,
2063 for (i
= 0; i
< BTRFS_SUPER_MIRROR_MAX
; i
++) {
2064 bytenr
= btrfs_sb_offset(i
);
2065 ret
= btrfs_rmap_block(fs_info
, cache
->start
,
2066 bytenr
, &logical
, &nr
, &stripe_len
);
2070 /* Shouldn't have super stripes in sequential zones */
2073 "zoned: block group %llu must not contain super block",
2079 u64 len
= min_t(u64
, stripe_len
,
2080 cache
->start
+ cache
->length
- logical
[nr
]);
2082 cache
->bytes_super
+= len
;
2083 ret
= btrfs_add_excluded_extent(fs_info
, logical
[nr
],
2096 static struct btrfs_block_group
*btrfs_create_block_group_cache(
2097 struct btrfs_fs_info
*fs_info
, u64 start
)
2099 struct btrfs_block_group
*cache
;
2101 cache
= kzalloc(sizeof(*cache
), GFP_NOFS
);
2105 cache
->free_space_ctl
= kzalloc(sizeof(*cache
->free_space_ctl
),
2107 if (!cache
->free_space_ctl
) {
2112 cache
->start
= start
;
2114 cache
->fs_info
= fs_info
;
2115 cache
->full_stripe_len
= btrfs_full_stripe_len(fs_info
, start
);
2117 cache
->discard_index
= BTRFS_DISCARD_INDEX_UNUSED
;
2119 refcount_set(&cache
->refs
, 1);
2120 spin_lock_init(&cache
->lock
);
2121 init_rwsem(&cache
->data_rwsem
);
2122 INIT_LIST_HEAD(&cache
->list
);
2123 INIT_LIST_HEAD(&cache
->cluster_list
);
2124 INIT_LIST_HEAD(&cache
->bg_list
);
2125 INIT_LIST_HEAD(&cache
->ro_list
);
2126 INIT_LIST_HEAD(&cache
->discard_list
);
2127 INIT_LIST_HEAD(&cache
->dirty_list
);
2128 INIT_LIST_HEAD(&cache
->io_list
);
2129 INIT_LIST_HEAD(&cache
->active_bg_list
);
2130 btrfs_init_free_space_ctl(cache
, cache
->free_space_ctl
);
2131 atomic_set(&cache
->frozen
, 0);
2132 mutex_init(&cache
->free_space_lock
);
2133 cache
->full_stripe_locks_root
.root
= RB_ROOT
;
2134 mutex_init(&cache
->full_stripe_locks_root
.lock
);
2140 * Iterate all chunks and verify that each of them has the corresponding block
2143 static int check_chunk_block_group_mappings(struct btrfs_fs_info
*fs_info
)
2145 struct extent_map_tree
*map_tree
= &fs_info
->mapping_tree
;
2146 struct extent_map
*em
;
2147 struct btrfs_block_group
*bg
;
2152 read_lock(&map_tree
->lock
);
2154 * lookup_extent_mapping will return the first extent map
2155 * intersecting the range, so setting @len to 1 is enough to
2156 * get the first chunk.
2158 em
= lookup_extent_mapping(map_tree
, start
, 1);
2159 read_unlock(&map_tree
->lock
);
2163 bg
= btrfs_lookup_block_group(fs_info
, em
->start
);
2166 "chunk start=%llu len=%llu doesn't have corresponding block group",
2167 em
->start
, em
->len
);
2169 free_extent_map(em
);
2172 if (bg
->start
!= em
->start
|| bg
->length
!= em
->len
||
2173 (bg
->flags
& BTRFS_BLOCK_GROUP_TYPE_MASK
) !=
2174 (em
->map_lookup
->type
& BTRFS_BLOCK_GROUP_TYPE_MASK
)) {
2176 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
2178 em
->map_lookup
->type
& BTRFS_BLOCK_GROUP_TYPE_MASK
,
2179 bg
->start
, bg
->length
,
2180 bg
->flags
& BTRFS_BLOCK_GROUP_TYPE_MASK
);
2182 free_extent_map(em
);
2183 btrfs_put_block_group(bg
);
2186 start
= em
->start
+ em
->len
;
2187 free_extent_map(em
);
2188 btrfs_put_block_group(bg
);
2193 static int read_one_block_group(struct btrfs_fs_info
*info
,
2194 struct btrfs_block_group_item
*bgi
,
2195 const struct btrfs_key
*key
,
2198 struct btrfs_block_group
*cache
;
2199 const bool mixed
= btrfs_fs_incompat(info
, MIXED_GROUPS
);
2202 ASSERT(key
->type
== BTRFS_BLOCK_GROUP_ITEM_KEY
);
2204 cache
= btrfs_create_block_group_cache(info
, key
->objectid
);
2208 cache
->length
= key
->offset
;
2209 cache
->used
= btrfs_stack_block_group_used(bgi
);
2210 cache
->commit_used
= cache
->used
;
2211 cache
->flags
= btrfs_stack_block_group_flags(bgi
);
2212 cache
->global_root_id
= btrfs_stack_block_group_chunk_objectid(bgi
);
2214 set_free_space_tree_thresholds(cache
);
2218 * When we mount with old space cache, we need to
2219 * set BTRFS_DC_CLEAR and set dirty flag.
2221 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
2222 * truncate the old free space cache inode and
2224 * b) Setting 'dirty flag' makes sure that we flush
2225 * the new space cache info onto disk.
2227 if (btrfs_test_opt(info
, SPACE_CACHE
))
2228 cache
->disk_cache_state
= BTRFS_DC_CLEAR
;
2230 if (!mixed
&& ((cache
->flags
& BTRFS_BLOCK_GROUP_METADATA
) &&
2231 (cache
->flags
& BTRFS_BLOCK_GROUP_DATA
))) {
2233 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2239 ret
= btrfs_load_block_group_zone_info(cache
, false);
2241 btrfs_err(info
, "zoned: failed to load zone info of bg %llu",
2247 * We need to exclude the super stripes now so that the space info has
2248 * super bytes accounted for, otherwise we'll think we have more space
2249 * than we actually do.
2251 ret
= exclude_super_stripes(cache
);
2253 /* We may have excluded something, so call this just in case. */
2254 btrfs_free_excluded_extents(cache
);
2259 * For zoned filesystem, space after the allocation offset is the only
2260 * free space for a block group. So, we don't need any caching work.
2261 * btrfs_calc_zone_unusable() will set the amount of free space and
2262 * zone_unusable space.
2264 * For regular filesystem, check for two cases, either we are full, and
2265 * therefore don't need to bother with the caching work since we won't
2266 * find any space, or we are empty, and we can just add all the space
2267 * in and be done with it. This saves us _a_lot_ of time, particularly
2270 if (btrfs_is_zoned(info
)) {
2271 btrfs_calc_zone_unusable(cache
);
2272 /* Should not have any excluded extents. Just in case, though. */
2273 btrfs_free_excluded_extents(cache
);
2274 } else if (cache
->length
== cache
->used
) {
2275 cache
->cached
= BTRFS_CACHE_FINISHED
;
2276 btrfs_free_excluded_extents(cache
);
2277 } else if (cache
->used
== 0) {
2278 cache
->cached
= BTRFS_CACHE_FINISHED
;
2279 add_new_free_space(cache
, cache
->start
,
2280 cache
->start
+ cache
->length
);
2281 btrfs_free_excluded_extents(cache
);
2284 ret
= btrfs_add_block_group_cache(info
, cache
);
2286 btrfs_remove_free_space_cache(cache
);
2289 trace_btrfs_add_block_group(info
, cache
, 0);
2290 btrfs_add_bg_to_space_info(info
, cache
);
2292 set_avail_alloc_bits(info
, cache
->flags
);
2293 if (btrfs_chunk_writeable(info
, cache
->start
)) {
2294 if (cache
->used
== 0) {
2295 ASSERT(list_empty(&cache
->bg_list
));
2296 if (btrfs_test_opt(info
, DISCARD_ASYNC
))
2297 btrfs_discard_queue_work(&info
->discard_ctl
, cache
);
2299 btrfs_mark_bg_unused(cache
);
2302 inc_block_group_ro(cache
, 1);
2307 btrfs_put_block_group(cache
);
2311 static int fill_dummy_bgs(struct btrfs_fs_info
*fs_info
)
2313 struct extent_map_tree
*em_tree
= &fs_info
->mapping_tree
;
2314 struct rb_node
*node
;
2317 for (node
= rb_first_cached(&em_tree
->map
); node
; node
= rb_next(node
)) {
2318 struct extent_map
*em
;
2319 struct map_lookup
*map
;
2320 struct btrfs_block_group
*bg
;
2322 em
= rb_entry(node
, struct extent_map
, rb_node
);
2323 map
= em
->map_lookup
;
2324 bg
= btrfs_create_block_group_cache(fs_info
, em
->start
);
2330 /* Fill dummy cache as FULL */
2331 bg
->length
= em
->len
;
2332 bg
->flags
= map
->type
;
2333 bg
->cached
= BTRFS_CACHE_FINISHED
;
2335 bg
->flags
= map
->type
;
2336 ret
= btrfs_add_block_group_cache(fs_info
, bg
);
2338 * We may have some valid block group cache added already, in
2339 * that case we skip to the next one.
2341 if (ret
== -EEXIST
) {
2343 btrfs_put_block_group(bg
);
2348 btrfs_remove_free_space_cache(bg
);
2349 btrfs_put_block_group(bg
);
2353 btrfs_add_bg_to_space_info(fs_info
, bg
);
2355 set_avail_alloc_bits(fs_info
, bg
->flags
);
2358 btrfs_init_global_block_rsv(fs_info
);
2362 int btrfs_read_block_groups(struct btrfs_fs_info
*info
)
2364 struct btrfs_root
*root
= btrfs_block_group_root(info
);
2365 struct btrfs_path
*path
;
2367 struct btrfs_block_group
*cache
;
2368 struct btrfs_space_info
*space_info
;
2369 struct btrfs_key key
;
2374 * Either no extent root (with ibadroots rescue option) or we have
2375 * unsupported RO options. The fs can never be mounted read-write, so no
2376 * need to waste time searching block group items.
2378 * This also allows new extent tree related changes to be RO compat,
2379 * no need for a full incompat flag.
2381 if (!root
|| (btrfs_super_compat_ro_flags(info
->super_copy
) &
2382 ~BTRFS_FEATURE_COMPAT_RO_SUPP
))
2383 return fill_dummy_bgs(info
);
2387 key
.type
= BTRFS_BLOCK_GROUP_ITEM_KEY
;
2388 path
= btrfs_alloc_path();
2392 cache_gen
= btrfs_super_cache_generation(info
->super_copy
);
2393 if (btrfs_test_opt(info
, SPACE_CACHE
) &&
2394 btrfs_super_generation(info
->super_copy
) != cache_gen
)
2396 if (btrfs_test_opt(info
, CLEAR_CACHE
))
2400 struct btrfs_block_group_item bgi
;
2401 struct extent_buffer
*leaf
;
2404 ret
= find_first_block_group(info
, path
, &key
);
2410 leaf
= path
->nodes
[0];
2411 slot
= path
->slots
[0];
2413 read_extent_buffer(leaf
, &bgi
, btrfs_item_ptr_offset(leaf
, slot
),
2416 btrfs_item_key_to_cpu(leaf
, &key
, slot
);
2417 btrfs_release_path(path
);
2418 ret
= read_one_block_group(info
, &bgi
, &key
, need_clear
);
2421 key
.objectid
+= key
.offset
;
2424 btrfs_release_path(path
);
2426 list_for_each_entry(space_info
, &info
->space_info
, list
) {
2429 for (i
= 0; i
< BTRFS_NR_RAID_TYPES
; i
++) {
2430 if (list_empty(&space_info
->block_groups
[i
]))
2432 cache
= list_first_entry(&space_info
->block_groups
[i
],
2433 struct btrfs_block_group
,
2435 btrfs_sysfs_add_block_group_type(cache
);
2438 if (!(btrfs_get_alloc_profile(info
, space_info
->flags
) &
2439 (BTRFS_BLOCK_GROUP_RAID10
|
2440 BTRFS_BLOCK_GROUP_RAID1_MASK
|
2441 BTRFS_BLOCK_GROUP_RAID56_MASK
|
2442 BTRFS_BLOCK_GROUP_DUP
)))
2445 * Avoid allocating from un-mirrored block group if there are
2446 * mirrored block groups.
2448 list_for_each_entry(cache
,
2449 &space_info
->block_groups
[BTRFS_RAID_RAID0
],
2451 inc_block_group_ro(cache
, 1);
2452 list_for_each_entry(cache
,
2453 &space_info
->block_groups
[BTRFS_RAID_SINGLE
],
2455 inc_block_group_ro(cache
, 1);
2458 btrfs_init_global_block_rsv(info
);
2459 ret
= check_chunk_block_group_mappings(info
);
2461 btrfs_free_path(path
);
2463 * We've hit some error while reading the extent tree, and have
2464 * rescue=ibadroots mount option.
2465 * Try to fill the tree using dummy block groups so that the user can
2466 * continue to mount and grab their data.
2468 if (ret
&& btrfs_test_opt(info
, IGNOREBADROOTS
))
2469 ret
= fill_dummy_bgs(info
);
2474 * This function, insert_block_group_item(), belongs to the phase 2 of chunk
2477 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2480 static int insert_block_group_item(struct btrfs_trans_handle
*trans
,
2481 struct btrfs_block_group
*block_group
)
2483 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
2484 struct btrfs_block_group_item bgi
;
2485 struct btrfs_root
*root
= btrfs_block_group_root(fs_info
);
2486 struct btrfs_key key
;
2487 u64 old_commit_used
;
2490 spin_lock(&block_group
->lock
);
2491 btrfs_set_stack_block_group_used(&bgi
, block_group
->used
);
2492 btrfs_set_stack_block_group_chunk_objectid(&bgi
,
2493 block_group
->global_root_id
);
2494 btrfs_set_stack_block_group_flags(&bgi
, block_group
->flags
);
2495 old_commit_used
= block_group
->commit_used
;
2496 block_group
->commit_used
= block_group
->used
;
2497 key
.objectid
= block_group
->start
;
2498 key
.type
= BTRFS_BLOCK_GROUP_ITEM_KEY
;
2499 key
.offset
= block_group
->length
;
2500 spin_unlock(&block_group
->lock
);
2502 ret
= btrfs_insert_item(trans
, root
, &key
, &bgi
, sizeof(bgi
));
2504 spin_lock(&block_group
->lock
);
2505 block_group
->commit_used
= old_commit_used
;
2506 spin_unlock(&block_group
->lock
);
2512 static int insert_dev_extent(struct btrfs_trans_handle
*trans
,
2513 struct btrfs_device
*device
, u64 chunk_offset
,
2514 u64 start
, u64 num_bytes
)
2516 struct btrfs_fs_info
*fs_info
= device
->fs_info
;
2517 struct btrfs_root
*root
= fs_info
->dev_root
;
2518 struct btrfs_path
*path
;
2519 struct btrfs_dev_extent
*extent
;
2520 struct extent_buffer
*leaf
;
2521 struct btrfs_key key
;
2524 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA
, &device
->dev_state
));
2525 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT
, &device
->dev_state
));
2526 path
= btrfs_alloc_path();
2530 key
.objectid
= device
->devid
;
2531 key
.type
= BTRFS_DEV_EXTENT_KEY
;
2533 ret
= btrfs_insert_empty_item(trans
, root
, path
, &key
, sizeof(*extent
));
2537 leaf
= path
->nodes
[0];
2538 extent
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_dev_extent
);
2539 btrfs_set_dev_extent_chunk_tree(leaf
, extent
, BTRFS_CHUNK_TREE_OBJECTID
);
2540 btrfs_set_dev_extent_chunk_objectid(leaf
, extent
,
2541 BTRFS_FIRST_CHUNK_TREE_OBJECTID
);
2542 btrfs_set_dev_extent_chunk_offset(leaf
, extent
, chunk_offset
);
2544 btrfs_set_dev_extent_length(leaf
, extent
, num_bytes
);
2545 btrfs_mark_buffer_dirty(leaf
);
2547 btrfs_free_path(path
);
2552 * This function belongs to phase 2.
2554 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2557 static int insert_dev_extents(struct btrfs_trans_handle
*trans
,
2558 u64 chunk_offset
, u64 chunk_size
)
2560 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
2561 struct btrfs_device
*device
;
2562 struct extent_map
*em
;
2563 struct map_lookup
*map
;
2569 em
= btrfs_get_chunk_map(fs_info
, chunk_offset
, chunk_size
);
2573 map
= em
->map_lookup
;
2574 stripe_size
= em
->orig_block_len
;
2577 * Take the device list mutex to prevent races with the final phase of
2578 * a device replace operation that replaces the device object associated
2579 * with the map's stripes, because the device object's id can change
2580 * at any time during that final phase of the device replace operation
2581 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
2582 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
2583 * resulting in persisting a device extent item with such ID.
2585 mutex_lock(&fs_info
->fs_devices
->device_list_mutex
);
2586 for (i
= 0; i
< map
->num_stripes
; i
++) {
2587 device
= map
->stripes
[i
].dev
;
2588 dev_offset
= map
->stripes
[i
].physical
;
2590 ret
= insert_dev_extent(trans
, device
, chunk_offset
, dev_offset
,
2595 mutex_unlock(&fs_info
->fs_devices
->device_list_mutex
);
2597 free_extent_map(em
);
2602 * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
2605 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2608 void btrfs_create_pending_block_groups(struct btrfs_trans_handle
*trans
)
2610 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
2611 struct btrfs_block_group
*block_group
;
2614 while (!list_empty(&trans
->new_bgs
)) {
2617 block_group
= list_first_entry(&trans
->new_bgs
,
2618 struct btrfs_block_group
,
2623 index
= btrfs_bg_flags_to_raid_index(block_group
->flags
);
2625 ret
= insert_block_group_item(trans
, block_group
);
2627 btrfs_abort_transaction(trans
, ret
);
2628 if (!test_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED
,
2629 &block_group
->runtime_flags
)) {
2630 mutex_lock(&fs_info
->chunk_mutex
);
2631 ret
= btrfs_chunk_alloc_add_chunk_item(trans
, block_group
);
2632 mutex_unlock(&fs_info
->chunk_mutex
);
2634 btrfs_abort_transaction(trans
, ret
);
2636 ret
= insert_dev_extents(trans
, block_group
->start
,
2637 block_group
->length
);
2639 btrfs_abort_transaction(trans
, ret
);
2640 add_block_group_free_space(trans
, block_group
);
2643 * If we restriped during balance, we may have added a new raid
2644 * type, so now add the sysfs entries when it is safe to do so.
2645 * We don't have to worry about locking here as it's handled in
2646 * btrfs_sysfs_add_block_group_type.
2648 if (block_group
->space_info
->block_group_kobjs
[index
] == NULL
)
2649 btrfs_sysfs_add_block_group_type(block_group
);
2651 /* Already aborted the transaction if it failed. */
2653 btrfs_delayed_refs_rsv_release(fs_info
, 1);
2654 list_del_init(&block_group
->bg_list
);
2656 btrfs_trans_release_chunk_metadata(trans
);
2660 * For extent tree v2 we use the block_group_item->chunk_offset to point at our
2661 * global root id. For v1 it's always set to BTRFS_FIRST_CHUNK_TREE_OBJECTID.
2663 static u64
calculate_global_root_id(struct btrfs_fs_info
*fs_info
, u64 offset
)
2668 if (!btrfs_fs_incompat(fs_info
, EXTENT_TREE_V2
))
2669 return BTRFS_FIRST_CHUNK_TREE_OBJECTID
;
2671 /* If we have a smaller fs index based on 128MiB. */
2672 if (btrfs_super_total_bytes(fs_info
->super_copy
) <= (SZ_1G
* 10ULL))
2675 offset
= div64_u64(offset
, div
);
2676 div64_u64_rem(offset
, fs_info
->nr_global_roots
, &index
);
2680 struct btrfs_block_group
*btrfs_make_block_group(struct btrfs_trans_handle
*trans
,
2681 u64 bytes_used
, u64 type
,
2682 u64 chunk_offset
, u64 size
)
2684 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
2685 struct btrfs_block_group
*cache
;
2688 btrfs_set_log_full_commit(trans
);
2690 cache
= btrfs_create_block_group_cache(fs_info
, chunk_offset
);
2692 return ERR_PTR(-ENOMEM
);
2694 cache
->length
= size
;
2695 set_free_space_tree_thresholds(cache
);
2696 cache
->used
= bytes_used
;
2697 cache
->flags
= type
;
2698 cache
->cached
= BTRFS_CACHE_FINISHED
;
2699 cache
->global_root_id
= calculate_global_root_id(fs_info
, cache
->start
);
2701 if (btrfs_fs_compat_ro(fs_info
, FREE_SPACE_TREE
))
2702 set_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE
, &cache
->runtime_flags
);
2704 ret
= btrfs_load_block_group_zone_info(cache
, true);
2706 btrfs_put_block_group(cache
);
2707 return ERR_PTR(ret
);
2710 ret
= exclude_super_stripes(cache
);
2712 /* We may have excluded something, so call this just in case */
2713 btrfs_free_excluded_extents(cache
);
2714 btrfs_put_block_group(cache
);
2715 return ERR_PTR(ret
);
2718 add_new_free_space(cache
, chunk_offset
, chunk_offset
+ size
);
2720 btrfs_free_excluded_extents(cache
);
2723 * Ensure the corresponding space_info object is created and
2724 * assigned to our block group. We want our bg to be added to the rbtree
2725 * with its ->space_info set.
2727 cache
->space_info
= btrfs_find_space_info(fs_info
, cache
->flags
);
2728 ASSERT(cache
->space_info
);
2730 ret
= btrfs_add_block_group_cache(fs_info
, cache
);
2732 btrfs_remove_free_space_cache(cache
);
2733 btrfs_put_block_group(cache
);
2734 return ERR_PTR(ret
);
2738 * Now that our block group has its ->space_info set and is inserted in
2739 * the rbtree, update the space info's counters.
2741 trace_btrfs_add_block_group(fs_info
, cache
, 1);
2742 btrfs_add_bg_to_space_info(fs_info
, cache
);
2743 btrfs_update_global_block_rsv(fs_info
);
2745 #ifdef CONFIG_BTRFS_DEBUG
2746 if (btrfs_should_fragment_free_space(cache
)) {
2747 u64 new_bytes_used
= size
- bytes_used
;
2749 cache
->space_info
->bytes_used
+= new_bytes_used
>> 1;
2750 fragment_free_space(cache
);
2754 list_add_tail(&cache
->bg_list
, &trans
->new_bgs
);
2755 trans
->delayed_ref_updates
++;
2756 btrfs_update_delayed_refs_rsv(trans
);
2758 set_avail_alloc_bits(fs_info
, type
);
2763 * Mark one block group RO, can be called several times for the same block
2766 * @cache: the destination block group
2767 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2768 * ensure we still have some free space after marking this
2771 int btrfs_inc_block_group_ro(struct btrfs_block_group
*cache
,
2772 bool do_chunk_alloc
)
2774 struct btrfs_fs_info
*fs_info
= cache
->fs_info
;
2775 struct btrfs_trans_handle
*trans
;
2776 struct btrfs_root
*root
= btrfs_block_group_root(fs_info
);
2779 bool dirty_bg_running
;
2782 * This can only happen when we are doing read-only scrub on read-only
2784 * In that case we should not start a new transaction on read-only fs.
2785 * Thus here we skip all chunk allocations.
2787 if (sb_rdonly(fs_info
->sb
)) {
2788 mutex_lock(&fs_info
->ro_block_group_mutex
);
2789 ret
= inc_block_group_ro(cache
, 0);
2790 mutex_unlock(&fs_info
->ro_block_group_mutex
);
2795 trans
= btrfs_join_transaction(root
);
2797 return PTR_ERR(trans
);
2799 dirty_bg_running
= false;
2802 * We're not allowed to set block groups readonly after the dirty
2803 * block group cache has started writing. If it already started,
2804 * back off and let this transaction commit.
2806 mutex_lock(&fs_info
->ro_block_group_mutex
);
2807 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN
, &trans
->transaction
->flags
)) {
2808 u64 transid
= trans
->transid
;
2810 mutex_unlock(&fs_info
->ro_block_group_mutex
);
2811 btrfs_end_transaction(trans
);
2813 ret
= btrfs_wait_for_commit(fs_info
, transid
);
2816 dirty_bg_running
= true;
2818 } while (dirty_bg_running
);
2820 if (do_chunk_alloc
) {
2822 * If we are changing raid levels, try to allocate a
2823 * corresponding block group with the new raid level.
2825 alloc_flags
= btrfs_get_alloc_profile(fs_info
, cache
->flags
);
2826 if (alloc_flags
!= cache
->flags
) {
2827 ret
= btrfs_chunk_alloc(trans
, alloc_flags
,
2830 * ENOSPC is allowed here, we may have enough space
2831 * already allocated at the new raid level to carry on
2840 ret
= inc_block_group_ro(cache
, 0);
2841 if (!do_chunk_alloc
|| ret
== -ETXTBSY
)
2845 alloc_flags
= btrfs_get_alloc_profile(fs_info
, cache
->space_info
->flags
);
2846 ret
= btrfs_chunk_alloc(trans
, alloc_flags
, CHUNK_ALLOC_FORCE
);
2850 * We have allocated a new chunk. We also need to activate that chunk to
2851 * grant metadata tickets for zoned filesystem.
2853 ret
= btrfs_zoned_activate_one_bg(fs_info
, cache
->space_info
, true);
2857 ret
= inc_block_group_ro(cache
, 0);
2858 if (ret
== -ETXTBSY
)
2861 if (cache
->flags
& BTRFS_BLOCK_GROUP_SYSTEM
) {
2862 alloc_flags
= btrfs_get_alloc_profile(fs_info
, cache
->flags
);
2863 mutex_lock(&fs_info
->chunk_mutex
);
2864 check_system_chunk(trans
, alloc_flags
);
2865 mutex_unlock(&fs_info
->chunk_mutex
);
2868 mutex_unlock(&fs_info
->ro_block_group_mutex
);
2870 btrfs_end_transaction(trans
);
2874 void btrfs_dec_block_group_ro(struct btrfs_block_group
*cache
)
2876 struct btrfs_space_info
*sinfo
= cache
->space_info
;
2881 spin_lock(&sinfo
->lock
);
2882 spin_lock(&cache
->lock
);
2884 if (btrfs_is_zoned(cache
->fs_info
)) {
2885 /* Migrate zone_unusable bytes back */
2886 cache
->zone_unusable
=
2887 (cache
->alloc_offset
- cache
->used
) +
2888 (cache
->length
- cache
->zone_capacity
);
2889 sinfo
->bytes_zone_unusable
+= cache
->zone_unusable
;
2890 sinfo
->bytes_readonly
-= cache
->zone_unusable
;
2892 num_bytes
= cache
->length
- cache
->reserved
-
2893 cache
->pinned
- cache
->bytes_super
-
2894 cache
->zone_unusable
- cache
->used
;
2895 sinfo
->bytes_readonly
-= num_bytes
;
2896 list_del_init(&cache
->ro_list
);
2898 spin_unlock(&cache
->lock
);
2899 spin_unlock(&sinfo
->lock
);
2902 static int update_block_group_item(struct btrfs_trans_handle
*trans
,
2903 struct btrfs_path
*path
,
2904 struct btrfs_block_group
*cache
)
2906 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
2908 struct btrfs_root
*root
= btrfs_block_group_root(fs_info
);
2910 struct extent_buffer
*leaf
;
2911 struct btrfs_block_group_item bgi
;
2912 struct btrfs_key key
;
2913 u64 old_commit_used
;
2917 * Block group items update can be triggered out of commit transaction
2918 * critical section, thus we need a consistent view of used bytes.
2919 * We cannot use cache->used directly outside of the spin lock, as it
2922 spin_lock(&cache
->lock
);
2923 old_commit_used
= cache
->commit_used
;
2925 /* No change in used bytes, can safely skip it. */
2926 if (cache
->commit_used
== used
) {
2927 spin_unlock(&cache
->lock
);
2930 cache
->commit_used
= used
;
2931 spin_unlock(&cache
->lock
);
2933 key
.objectid
= cache
->start
;
2934 key
.type
= BTRFS_BLOCK_GROUP_ITEM_KEY
;
2935 key
.offset
= cache
->length
;
2937 ret
= btrfs_search_slot(trans
, root
, &key
, path
, 0, 1);
2944 leaf
= path
->nodes
[0];
2945 bi
= btrfs_item_ptr_offset(leaf
, path
->slots
[0]);
2946 btrfs_set_stack_block_group_used(&bgi
, used
);
2947 btrfs_set_stack_block_group_chunk_objectid(&bgi
,
2948 cache
->global_root_id
);
2949 btrfs_set_stack_block_group_flags(&bgi
, cache
->flags
);
2950 write_extent_buffer(leaf
, &bgi
, bi
, sizeof(bgi
));
2951 btrfs_mark_buffer_dirty(leaf
);
2953 btrfs_release_path(path
);
2954 /* We didn't update the block group item, need to revert @commit_used. */
2956 spin_lock(&cache
->lock
);
2957 cache
->commit_used
= old_commit_used
;
2958 spin_unlock(&cache
->lock
);
2964 static int cache_save_setup(struct btrfs_block_group
*block_group
,
2965 struct btrfs_trans_handle
*trans
,
2966 struct btrfs_path
*path
)
2968 struct btrfs_fs_info
*fs_info
= block_group
->fs_info
;
2969 struct btrfs_root
*root
= fs_info
->tree_root
;
2970 struct inode
*inode
= NULL
;
2971 struct extent_changeset
*data_reserved
= NULL
;
2973 int dcs
= BTRFS_DC_ERROR
;
2978 if (!btrfs_test_opt(fs_info
, SPACE_CACHE
))
2982 * If this block group is smaller than 100 megs don't bother caching the
2985 if (block_group
->length
< (100 * SZ_1M
)) {
2986 spin_lock(&block_group
->lock
);
2987 block_group
->disk_cache_state
= BTRFS_DC_WRITTEN
;
2988 spin_unlock(&block_group
->lock
);
2992 if (TRANS_ABORTED(trans
))
2995 inode
= lookup_free_space_inode(block_group
, path
);
2996 if (IS_ERR(inode
) && PTR_ERR(inode
) != -ENOENT
) {
2997 ret
= PTR_ERR(inode
);
2998 btrfs_release_path(path
);
3002 if (IS_ERR(inode
)) {
3006 if (block_group
->ro
)
3009 ret
= create_free_space_inode(trans
, block_group
, path
);
3016 * We want to set the generation to 0, that way if anything goes wrong
3017 * from here on out we know not to trust this cache when we load up next
3020 BTRFS_I(inode
)->generation
= 0;
3021 ret
= btrfs_update_inode(trans
, root
, BTRFS_I(inode
));
3024 * So theoretically we could recover from this, simply set the
3025 * super cache generation to 0 so we know to invalidate the
3026 * cache, but then we'd have to keep track of the block groups
3027 * that fail this way so we know we _have_ to reset this cache
3028 * before the next commit or risk reading stale cache. So to
3029 * limit our exposure to horrible edge cases lets just abort the
3030 * transaction, this only happens in really bad situations
3033 btrfs_abort_transaction(trans
, ret
);
3038 /* We've already setup this transaction, go ahead and exit */
3039 if (block_group
->cache_generation
== trans
->transid
&&
3040 i_size_read(inode
)) {
3041 dcs
= BTRFS_DC_SETUP
;
3045 if (i_size_read(inode
) > 0) {
3046 ret
= btrfs_check_trunc_cache_free_space(fs_info
,
3047 &fs_info
->global_block_rsv
);
3051 ret
= btrfs_truncate_free_space_cache(trans
, NULL
, inode
);
3056 spin_lock(&block_group
->lock
);
3057 if (block_group
->cached
!= BTRFS_CACHE_FINISHED
||
3058 !btrfs_test_opt(fs_info
, SPACE_CACHE
)) {
3060 * don't bother trying to write stuff out _if_
3061 * a) we're not cached,
3062 * b) we're with nospace_cache mount option,
3063 * c) we're with v2 space_cache (FREE_SPACE_TREE).
3065 dcs
= BTRFS_DC_WRITTEN
;
3066 spin_unlock(&block_group
->lock
);
3069 spin_unlock(&block_group
->lock
);
3072 * We hit an ENOSPC when setting up the cache in this transaction, just
3073 * skip doing the setup, we've already cleared the cache so we're safe.
3075 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC
, &trans
->transaction
->flags
)) {
3081 * Try to preallocate enough space based on how big the block group is.
3082 * Keep in mind this has to include any pinned space which could end up
3083 * taking up quite a bit since it's not folded into the other space
3086 cache_size
= div_u64(block_group
->length
, SZ_256M
);
3091 cache_size
*= fs_info
->sectorsize
;
3093 ret
= btrfs_check_data_free_space(BTRFS_I(inode
), &data_reserved
, 0,
3098 ret
= btrfs_prealloc_file_range_trans(inode
, trans
, 0, 0, cache_size
,
3099 cache_size
, cache_size
,
3102 * Our cache requires contiguous chunks so that we don't modify a bunch
3103 * of metadata or split extents when writing the cache out, which means
3104 * we can enospc if we are heavily fragmented in addition to just normal
3105 * out of space conditions. So if we hit this just skip setting up any
3106 * other block groups for this transaction, maybe we'll unpin enough
3107 * space the next time around.
3110 dcs
= BTRFS_DC_SETUP
;
3111 else if (ret
== -ENOSPC
)
3112 set_bit(BTRFS_TRANS_CACHE_ENOSPC
, &trans
->transaction
->flags
);
3117 btrfs_release_path(path
);
3119 spin_lock(&block_group
->lock
);
3120 if (!ret
&& dcs
== BTRFS_DC_SETUP
)
3121 block_group
->cache_generation
= trans
->transid
;
3122 block_group
->disk_cache_state
= dcs
;
3123 spin_unlock(&block_group
->lock
);
3125 extent_changeset_free(data_reserved
);
3129 int btrfs_setup_space_cache(struct btrfs_trans_handle
*trans
)
3131 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
3132 struct btrfs_block_group
*cache
, *tmp
;
3133 struct btrfs_transaction
*cur_trans
= trans
->transaction
;
3134 struct btrfs_path
*path
;
3136 if (list_empty(&cur_trans
->dirty_bgs
) ||
3137 !btrfs_test_opt(fs_info
, SPACE_CACHE
))
3140 path
= btrfs_alloc_path();
3144 /* Could add new block groups, use _safe just in case */
3145 list_for_each_entry_safe(cache
, tmp
, &cur_trans
->dirty_bgs
,
3147 if (cache
->disk_cache_state
== BTRFS_DC_CLEAR
)
3148 cache_save_setup(cache
, trans
, path
);
3151 btrfs_free_path(path
);
3156 * Transaction commit does final block group cache writeback during a critical
3157 * section where nothing is allowed to change the FS. This is required in
3158 * order for the cache to actually match the block group, but can introduce a
3159 * lot of latency into the commit.
3161 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
3162 * There's a chance we'll have to redo some of it if the block group changes
3163 * again during the commit, but it greatly reduces the commit latency by
3164 * getting rid of the easy block groups while we're still allowing others to
3167 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle
*trans
)
3169 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
3170 struct btrfs_block_group
*cache
;
3171 struct btrfs_transaction
*cur_trans
= trans
->transaction
;
3174 struct btrfs_path
*path
= NULL
;
3176 struct list_head
*io
= &cur_trans
->io_bgs
;
3179 spin_lock(&cur_trans
->dirty_bgs_lock
);
3180 if (list_empty(&cur_trans
->dirty_bgs
)) {
3181 spin_unlock(&cur_trans
->dirty_bgs_lock
);
3184 list_splice_init(&cur_trans
->dirty_bgs
, &dirty
);
3185 spin_unlock(&cur_trans
->dirty_bgs_lock
);
3188 /* Make sure all the block groups on our dirty list actually exist */
3189 btrfs_create_pending_block_groups(trans
);
3192 path
= btrfs_alloc_path();
3200 * cache_write_mutex is here only to save us from balance or automatic
3201 * removal of empty block groups deleting this block group while we are
3202 * writing out the cache
3204 mutex_lock(&trans
->transaction
->cache_write_mutex
);
3205 while (!list_empty(&dirty
)) {
3206 bool drop_reserve
= true;
3208 cache
= list_first_entry(&dirty
, struct btrfs_block_group
,
3211 * This can happen if something re-dirties a block group that
3212 * is already under IO. Just wait for it to finish and then do
3215 if (!list_empty(&cache
->io_list
)) {
3216 list_del_init(&cache
->io_list
);
3217 btrfs_wait_cache_io(trans
, cache
, path
);
3218 btrfs_put_block_group(cache
);
3223 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
3224 * it should update the cache_state. Don't delete until after
3227 * Since we're not running in the commit critical section
3228 * we need the dirty_bgs_lock to protect from update_block_group
3230 spin_lock(&cur_trans
->dirty_bgs_lock
);
3231 list_del_init(&cache
->dirty_list
);
3232 spin_unlock(&cur_trans
->dirty_bgs_lock
);
3236 cache_save_setup(cache
, trans
, path
);
3238 if (cache
->disk_cache_state
== BTRFS_DC_SETUP
) {
3239 cache
->io_ctl
.inode
= NULL
;
3240 ret
= btrfs_write_out_cache(trans
, cache
, path
);
3241 if (ret
== 0 && cache
->io_ctl
.inode
) {
3245 * The cache_write_mutex is protecting the
3246 * io_list, also refer to the definition of
3247 * btrfs_transaction::io_bgs for more details
3249 list_add_tail(&cache
->io_list
, io
);
3252 * If we failed to write the cache, the
3253 * generation will be bad and life goes on
3259 ret
= update_block_group_item(trans
, path
, cache
);
3261 * Our block group might still be attached to the list
3262 * of new block groups in the transaction handle of some
3263 * other task (struct btrfs_trans_handle->new_bgs). This
3264 * means its block group item isn't yet in the extent
3265 * tree. If this happens ignore the error, as we will
3266 * try again later in the critical section of the
3267 * transaction commit.
3269 if (ret
== -ENOENT
) {
3271 spin_lock(&cur_trans
->dirty_bgs_lock
);
3272 if (list_empty(&cache
->dirty_list
)) {
3273 list_add_tail(&cache
->dirty_list
,
3274 &cur_trans
->dirty_bgs
);
3275 btrfs_get_block_group(cache
);
3276 drop_reserve
= false;
3278 spin_unlock(&cur_trans
->dirty_bgs_lock
);
3280 btrfs_abort_transaction(trans
, ret
);
3284 /* If it's not on the io list, we need to put the block group */
3286 btrfs_put_block_group(cache
);
3288 btrfs_delayed_refs_rsv_release(fs_info
, 1);
3290 * Avoid blocking other tasks for too long. It might even save
3291 * us from writing caches for block groups that are going to be
3294 mutex_unlock(&trans
->transaction
->cache_write_mutex
);
3297 mutex_lock(&trans
->transaction
->cache_write_mutex
);
3299 mutex_unlock(&trans
->transaction
->cache_write_mutex
);
3302 * Go through delayed refs for all the stuff we've just kicked off
3303 * and then loop back (just once)
3306 ret
= btrfs_run_delayed_refs(trans
, 0);
3307 if (!ret
&& loops
== 0) {
3309 spin_lock(&cur_trans
->dirty_bgs_lock
);
3310 list_splice_init(&cur_trans
->dirty_bgs
, &dirty
);
3312 * dirty_bgs_lock protects us from concurrent block group
3313 * deletes too (not just cache_write_mutex).
3315 if (!list_empty(&dirty
)) {
3316 spin_unlock(&cur_trans
->dirty_bgs_lock
);
3319 spin_unlock(&cur_trans
->dirty_bgs_lock
);
3323 spin_lock(&cur_trans
->dirty_bgs_lock
);
3324 list_splice_init(&dirty
, &cur_trans
->dirty_bgs
);
3325 spin_unlock(&cur_trans
->dirty_bgs_lock
);
3326 btrfs_cleanup_dirty_bgs(cur_trans
, fs_info
);
3329 btrfs_free_path(path
);
3333 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle
*trans
)
3335 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
3336 struct btrfs_block_group
*cache
;
3337 struct btrfs_transaction
*cur_trans
= trans
->transaction
;
3340 struct btrfs_path
*path
;
3341 struct list_head
*io
= &cur_trans
->io_bgs
;
3343 path
= btrfs_alloc_path();
3348 * Even though we are in the critical section of the transaction commit,
3349 * we can still have concurrent tasks adding elements to this
3350 * transaction's list of dirty block groups. These tasks correspond to
3351 * endio free space workers started when writeback finishes for a
3352 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3353 * allocate new block groups as a result of COWing nodes of the root
3354 * tree when updating the free space inode. The writeback for the space
3355 * caches is triggered by an earlier call to
3356 * btrfs_start_dirty_block_groups() and iterations of the following
3358 * Also we want to do the cache_save_setup first and then run the
3359 * delayed refs to make sure we have the best chance at doing this all
3362 spin_lock(&cur_trans
->dirty_bgs_lock
);
3363 while (!list_empty(&cur_trans
->dirty_bgs
)) {
3364 cache
= list_first_entry(&cur_trans
->dirty_bgs
,
3365 struct btrfs_block_group
,
3369 * This can happen if cache_save_setup re-dirties a block group
3370 * that is already under IO. Just wait for it to finish and
3371 * then do it all again
3373 if (!list_empty(&cache
->io_list
)) {
3374 spin_unlock(&cur_trans
->dirty_bgs_lock
);
3375 list_del_init(&cache
->io_list
);
3376 btrfs_wait_cache_io(trans
, cache
, path
);
3377 btrfs_put_block_group(cache
);
3378 spin_lock(&cur_trans
->dirty_bgs_lock
);
3382 * Don't remove from the dirty list until after we've waited on
3385 list_del_init(&cache
->dirty_list
);
3386 spin_unlock(&cur_trans
->dirty_bgs_lock
);
3389 cache_save_setup(cache
, trans
, path
);
3392 ret
= btrfs_run_delayed_refs(trans
,
3393 (unsigned long) -1);
3395 if (!ret
&& cache
->disk_cache_state
== BTRFS_DC_SETUP
) {
3396 cache
->io_ctl
.inode
= NULL
;
3397 ret
= btrfs_write_out_cache(trans
, cache
, path
);
3398 if (ret
== 0 && cache
->io_ctl
.inode
) {
3400 list_add_tail(&cache
->io_list
, io
);
3403 * If we failed to write the cache, the
3404 * generation will be bad and life goes on
3410 ret
= update_block_group_item(trans
, path
, cache
);
3412 * One of the free space endio workers might have
3413 * created a new block group while updating a free space
3414 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3415 * and hasn't released its transaction handle yet, in
3416 * which case the new block group is still attached to
3417 * its transaction handle and its creation has not
3418 * finished yet (no block group item in the extent tree
3419 * yet, etc). If this is the case, wait for all free
3420 * space endio workers to finish and retry. This is a
3421 * very rare case so no need for a more efficient and
3424 if (ret
== -ENOENT
) {
3425 wait_event(cur_trans
->writer_wait
,
3426 atomic_read(&cur_trans
->num_writers
) == 1);
3427 ret
= update_block_group_item(trans
, path
, cache
);
3430 btrfs_abort_transaction(trans
, ret
);
3433 /* If its not on the io list, we need to put the block group */
3435 btrfs_put_block_group(cache
);
3436 btrfs_delayed_refs_rsv_release(fs_info
, 1);
3437 spin_lock(&cur_trans
->dirty_bgs_lock
);
3439 spin_unlock(&cur_trans
->dirty_bgs_lock
);
3442 * Refer to the definition of io_bgs member for details why it's safe
3443 * to use it without any locking
3445 while (!list_empty(io
)) {
3446 cache
= list_first_entry(io
, struct btrfs_block_group
,
3448 list_del_init(&cache
->io_list
);
3449 btrfs_wait_cache_io(trans
, cache
, path
);
3450 btrfs_put_block_group(cache
);
3453 btrfs_free_path(path
);
3457 int btrfs_update_block_group(struct btrfs_trans_handle
*trans
,
3458 u64 bytenr
, u64 num_bytes
, bool alloc
)
3460 struct btrfs_fs_info
*info
= trans
->fs_info
;
3461 struct btrfs_block_group
*cache
= NULL
;
3462 u64 total
= num_bytes
;
3468 /* Block accounting for super block */
3469 spin_lock(&info
->delalloc_root_lock
);
3470 old_val
= btrfs_super_bytes_used(info
->super_copy
);
3472 old_val
+= num_bytes
;
3474 old_val
-= num_bytes
;
3475 btrfs_set_super_bytes_used(info
->super_copy
, old_val
);
3476 spin_unlock(&info
->delalloc_root_lock
);
3479 bool reclaim
= false;
3481 cache
= btrfs_lookup_block_group(info
, bytenr
);
3486 factor
= btrfs_bg_type_to_factor(cache
->flags
);
3489 * If this block group has free space cache written out, we
3490 * need to make sure to load it if we are removing space. This
3491 * is because we need the unpinning stage to actually add the
3492 * space back to the block group, otherwise we will leak space.
3494 if (!alloc
&& !btrfs_block_group_done(cache
))
3495 btrfs_cache_block_group(cache
, true);
3497 byte_in_group
= bytenr
- cache
->start
;
3498 WARN_ON(byte_in_group
> cache
->length
);
3500 spin_lock(&cache
->space_info
->lock
);
3501 spin_lock(&cache
->lock
);
3503 if (btrfs_test_opt(info
, SPACE_CACHE
) &&
3504 cache
->disk_cache_state
< BTRFS_DC_CLEAR
)
3505 cache
->disk_cache_state
= BTRFS_DC_CLEAR
;
3507 old_val
= cache
->used
;
3508 num_bytes
= min(total
, cache
->length
- byte_in_group
);
3510 old_val
+= num_bytes
;
3511 cache
->used
= old_val
;
3512 cache
->reserved
-= num_bytes
;
3513 cache
->space_info
->bytes_reserved
-= num_bytes
;
3514 cache
->space_info
->bytes_used
+= num_bytes
;
3515 cache
->space_info
->disk_used
+= num_bytes
* factor
;
3516 spin_unlock(&cache
->lock
);
3517 spin_unlock(&cache
->space_info
->lock
);
3519 old_val
-= num_bytes
;
3520 cache
->used
= old_val
;
3521 cache
->pinned
+= num_bytes
;
3522 btrfs_space_info_update_bytes_pinned(info
,
3523 cache
->space_info
, num_bytes
);
3524 cache
->space_info
->bytes_used
-= num_bytes
;
3525 cache
->space_info
->disk_used
-= num_bytes
* factor
;
3527 reclaim
= should_reclaim_block_group(cache
, num_bytes
);
3529 spin_unlock(&cache
->lock
);
3530 spin_unlock(&cache
->space_info
->lock
);
3532 set_extent_dirty(&trans
->transaction
->pinned_extents
,
3533 bytenr
, bytenr
+ num_bytes
- 1,
3534 GFP_NOFS
| __GFP_NOFAIL
);
3537 spin_lock(&trans
->transaction
->dirty_bgs_lock
);
3538 if (list_empty(&cache
->dirty_list
)) {
3539 list_add_tail(&cache
->dirty_list
,
3540 &trans
->transaction
->dirty_bgs
);
3541 trans
->delayed_ref_updates
++;
3542 btrfs_get_block_group(cache
);
3544 spin_unlock(&trans
->transaction
->dirty_bgs_lock
);
3547 * No longer have used bytes in this block group, queue it for
3548 * deletion. We do this after adding the block group to the
3549 * dirty list to avoid races between cleaner kthread and space
3552 if (!alloc
&& old_val
== 0) {
3553 if (!btrfs_test_opt(info
, DISCARD_ASYNC
))
3554 btrfs_mark_bg_unused(cache
);
3555 } else if (!alloc
&& reclaim
) {
3556 btrfs_mark_bg_to_reclaim(cache
);
3559 btrfs_put_block_group(cache
);
3561 bytenr
+= num_bytes
;
3564 /* Modified block groups are accounted for in the delayed_refs_rsv. */
3565 btrfs_update_delayed_refs_rsv(trans
);
3570 * Update the block_group and space info counters.
3572 * @cache: The cache we are manipulating
3573 * @ram_bytes: The number of bytes of file content, and will be same to
3574 * @num_bytes except for the compress path.
3575 * @num_bytes: The number of bytes in question
3576 * @delalloc: The blocks are allocated for the delalloc write
3578 * This is called by the allocator when it reserves space. If this is a
3579 * reservation and the block group has become read only we cannot make the
3580 * reservation and return -EAGAIN, otherwise this function always succeeds.
3582 int btrfs_add_reserved_bytes(struct btrfs_block_group
*cache
,
3583 u64 ram_bytes
, u64 num_bytes
, int delalloc
,
3584 bool force_wrong_size_class
)
3586 struct btrfs_space_info
*space_info
= cache
->space_info
;
3587 enum btrfs_block_group_size_class size_class
;
3590 spin_lock(&space_info
->lock
);
3591 spin_lock(&cache
->lock
);
3597 if (btrfs_block_group_should_use_size_class(cache
)) {
3598 size_class
= btrfs_calc_block_group_size_class(num_bytes
);
3599 ret
= btrfs_use_block_group_size_class(cache
, size_class
, force_wrong_size_class
);
3603 cache
->reserved
+= num_bytes
;
3604 space_info
->bytes_reserved
+= num_bytes
;
3605 trace_btrfs_space_reservation(cache
->fs_info
, "space_info",
3606 space_info
->flags
, num_bytes
, 1);
3607 btrfs_space_info_update_bytes_may_use(cache
->fs_info
,
3608 space_info
, -ram_bytes
);
3610 cache
->delalloc_bytes
+= num_bytes
;
3613 * Compression can use less space than we reserved, so wake tickets if
3616 if (num_bytes
< ram_bytes
)
3617 btrfs_try_granting_tickets(cache
->fs_info
, space_info
);
3619 spin_unlock(&cache
->lock
);
3620 spin_unlock(&space_info
->lock
);
3625 * Update the block_group and space info counters.
3627 * @cache: The cache we are manipulating
3628 * @num_bytes: The number of bytes in question
3629 * @delalloc: The blocks are allocated for the delalloc write
3631 * This is called by somebody who is freeing space that was never actually used
3632 * on disk. For example if you reserve some space for a new leaf in transaction
3633 * A and before transaction A commits you free that leaf, you call this with
3634 * reserve set to 0 in order to clear the reservation.
3636 void btrfs_free_reserved_bytes(struct btrfs_block_group
*cache
,
3637 u64 num_bytes
, int delalloc
)
3639 struct btrfs_space_info
*space_info
= cache
->space_info
;
3641 spin_lock(&space_info
->lock
);
3642 spin_lock(&cache
->lock
);
3644 space_info
->bytes_readonly
+= num_bytes
;
3645 cache
->reserved
-= num_bytes
;
3646 space_info
->bytes_reserved
-= num_bytes
;
3647 space_info
->max_extent_size
= 0;
3650 cache
->delalloc_bytes
-= num_bytes
;
3651 spin_unlock(&cache
->lock
);
3653 btrfs_try_granting_tickets(cache
->fs_info
, space_info
);
3654 spin_unlock(&space_info
->lock
);
3657 static void force_metadata_allocation(struct btrfs_fs_info
*info
)
3659 struct list_head
*head
= &info
->space_info
;
3660 struct btrfs_space_info
*found
;
3662 list_for_each_entry(found
, head
, list
) {
3663 if (found
->flags
& BTRFS_BLOCK_GROUP_METADATA
)
3664 found
->force_alloc
= CHUNK_ALLOC_FORCE
;
3668 static int should_alloc_chunk(struct btrfs_fs_info
*fs_info
,
3669 struct btrfs_space_info
*sinfo
, int force
)
3671 u64 bytes_used
= btrfs_space_info_used(sinfo
, false);
3674 if (force
== CHUNK_ALLOC_FORCE
)
3678 * in limited mode, we want to have some free space up to
3679 * about 1% of the FS size.
3681 if (force
== CHUNK_ALLOC_LIMITED
) {
3682 thresh
= btrfs_super_total_bytes(fs_info
->super_copy
);
3683 thresh
= max_t(u64
, SZ_64M
, mult_perc(thresh
, 1));
3685 if (sinfo
->total_bytes
- bytes_used
< thresh
)
3689 if (bytes_used
+ SZ_2M
< mult_perc(sinfo
->total_bytes
, 80))
3694 int btrfs_force_chunk_alloc(struct btrfs_trans_handle
*trans
, u64 type
)
3696 u64 alloc_flags
= btrfs_get_alloc_profile(trans
->fs_info
, type
);
3698 return btrfs_chunk_alloc(trans
, alloc_flags
, CHUNK_ALLOC_FORCE
);
3701 static struct btrfs_block_group
*do_chunk_alloc(struct btrfs_trans_handle
*trans
, u64 flags
)
3703 struct btrfs_block_group
*bg
;
3707 * Check if we have enough space in the system space info because we
3708 * will need to update device items in the chunk btree and insert a new
3709 * chunk item in the chunk btree as well. This will allocate a new
3710 * system block group if needed.
3712 check_system_chunk(trans
, flags
);
3714 bg
= btrfs_create_chunk(trans
, flags
);
3720 ret
= btrfs_chunk_alloc_add_chunk_item(trans
, bg
);
3722 * Normally we are not expected to fail with -ENOSPC here, since we have
3723 * previously reserved space in the system space_info and allocated one
3724 * new system chunk if necessary. However there are three exceptions:
3726 * 1) We may have enough free space in the system space_info but all the
3727 * existing system block groups have a profile which can not be used
3728 * for extent allocation.
3730 * This happens when mounting in degraded mode. For example we have a
3731 * RAID1 filesystem with 2 devices, lose one device and mount the fs
3732 * using the other device in degraded mode. If we then allocate a chunk,
3733 * we may have enough free space in the existing system space_info, but
3734 * none of the block groups can be used for extent allocation since they
3735 * have a RAID1 profile, and because we are in degraded mode with a
3736 * single device, we are forced to allocate a new system chunk with a
3737 * SINGLE profile. Making check_system_chunk() iterate over all system
3738 * block groups and check if they have a usable profile and enough space
3739 * can be slow on very large filesystems, so we tolerate the -ENOSPC and
3740 * try again after forcing allocation of a new system chunk. Like this
3741 * we avoid paying the cost of that search in normal circumstances, when
3742 * we were not mounted in degraded mode;
3744 * 2) We had enough free space info the system space_info, and one suitable
3745 * block group to allocate from when we called check_system_chunk()
3746 * above. However right after we called it, the only system block group
3747 * with enough free space got turned into RO mode by a running scrub,
3748 * and in this case we have to allocate a new one and retry. We only
3749 * need do this allocate and retry once, since we have a transaction
3750 * handle and scrub uses the commit root to search for block groups;
3752 * 3) We had one system block group with enough free space when we called
3753 * check_system_chunk(), but after that, right before we tried to
3754 * allocate the last extent buffer we needed, a discard operation came
3755 * in and it temporarily removed the last free space entry from the
3756 * block group (discard removes a free space entry, discards it, and
3757 * then adds back the entry to the block group cache).
3759 if (ret
== -ENOSPC
) {
3760 const u64 sys_flags
= btrfs_system_alloc_profile(trans
->fs_info
);
3761 struct btrfs_block_group
*sys_bg
;
3763 sys_bg
= btrfs_create_chunk(trans
, sys_flags
);
3764 if (IS_ERR(sys_bg
)) {
3765 ret
= PTR_ERR(sys_bg
);
3766 btrfs_abort_transaction(trans
, ret
);
3770 ret
= btrfs_chunk_alloc_add_chunk_item(trans
, sys_bg
);
3772 btrfs_abort_transaction(trans
, ret
);
3776 ret
= btrfs_chunk_alloc_add_chunk_item(trans
, bg
);
3778 btrfs_abort_transaction(trans
, ret
);
3782 btrfs_abort_transaction(trans
, ret
);
3786 btrfs_trans_release_chunk_metadata(trans
);
3789 return ERR_PTR(ret
);
3791 btrfs_get_block_group(bg
);
3796 * Chunk allocation is done in 2 phases:
3798 * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
3799 * the chunk, the chunk mapping, create its block group and add the items
3800 * that belong in the chunk btree to it - more specifically, we need to
3801 * update device items in the chunk btree and add a new chunk item to it.
3803 * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
3804 * group item to the extent btree and the device extent items to the devices
3807 * This is done to prevent deadlocks. For example when COWing a node from the
3808 * extent btree we are holding a write lock on the node's parent and if we
3809 * trigger chunk allocation and attempted to insert the new block group item
3810 * in the extent btree right way, we could deadlock because the path for the
3811 * insertion can include that parent node. At first glance it seems impossible
3812 * to trigger chunk allocation after starting a transaction since tasks should
3813 * reserve enough transaction units (metadata space), however while that is true
3814 * most of the time, chunk allocation may still be triggered for several reasons:
3816 * 1) When reserving metadata, we check if there is enough free space in the
3817 * metadata space_info and therefore don't trigger allocation of a new chunk.
3818 * However later when the task actually tries to COW an extent buffer from
3819 * the extent btree or from the device btree for example, it is forced to
3820 * allocate a new block group (chunk) because the only one that had enough
3821 * free space was just turned to RO mode by a running scrub for example (or
3822 * device replace, block group reclaim thread, etc), so we can not use it
3823 * for allocating an extent and end up being forced to allocate a new one;
3825 * 2) Because we only check that the metadata space_info has enough free bytes,
3826 * we end up not allocating a new metadata chunk in that case. However if
3827 * the filesystem was mounted in degraded mode, none of the existing block
3828 * groups might be suitable for extent allocation due to their incompatible
3829 * profile (for e.g. mounting a 2 devices filesystem, where all block groups
3830 * use a RAID1 profile, in degraded mode using a single device). In this case
3831 * when the task attempts to COW some extent buffer of the extent btree for
3832 * example, it will trigger allocation of a new metadata block group with a
3833 * suitable profile (SINGLE profile in the example of the degraded mount of
3834 * the RAID1 filesystem);
3836 * 3) The task has reserved enough transaction units / metadata space, but when
3837 * it attempts to COW an extent buffer from the extent or device btree for
3838 * example, it does not find any free extent in any metadata block group,
3839 * therefore forced to try to allocate a new metadata block group.
3840 * This is because some other task allocated all available extents in the
3841 * meanwhile - this typically happens with tasks that don't reserve space
3842 * properly, either intentionally or as a bug. One example where this is
3843 * done intentionally is fsync, as it does not reserve any transaction units
3844 * and ends up allocating a variable number of metadata extents for log
3845 * tree extent buffers;
3847 * 4) The task has reserved enough transaction units / metadata space, but right
3848 * before it tries to allocate the last extent buffer it needs, a discard
3849 * operation comes in and, temporarily, removes the last free space entry from
3850 * the only metadata block group that had free space (discard starts by
3851 * removing a free space entry from a block group, then does the discard
3852 * operation and, once it's done, it adds back the free space entry to the
3855 * We also need this 2 phases setup when adding a device to a filesystem with
3856 * a seed device - we must create new metadata and system chunks without adding
3857 * any of the block group items to the chunk, extent and device btrees. If we
3858 * did not do it this way, we would get ENOSPC when attempting to update those
3859 * btrees, since all the chunks from the seed device are read-only.
3861 * Phase 1 does the updates and insertions to the chunk btree because if we had
3862 * it done in phase 2 and have a thundering herd of tasks allocating chunks in
3863 * parallel, we risk having too many system chunks allocated by many tasks if
3864 * many tasks reach phase 1 without the previous ones completing phase 2. In the
3865 * extreme case this leads to exhaustion of the system chunk array in the
3866 * superblock. This is easier to trigger if using a btree node/leaf size of 64K
3867 * and with RAID filesystems (so we have more device items in the chunk btree).
3868 * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
3869 * the system chunk array due to concurrent allocations") provides more details.
3871 * Allocation of system chunks does not happen through this function. A task that
3872 * needs to update the chunk btree (the only btree that uses system chunks), must
3873 * preallocate chunk space by calling either check_system_chunk() or
3874 * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or
3875 * metadata chunk or when removing a chunk, while the later is used before doing
3876 * a modification to the chunk btree - use cases for the later are adding,
3877 * removing and resizing a device as well as relocation of a system chunk.
3878 * See the comment below for more details.
3880 * The reservation of system space, done through check_system_chunk(), as well
3881 * as all the updates and insertions into the chunk btree must be done while
3882 * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
3883 * an extent buffer from the chunks btree we never trigger allocation of a new
3884 * system chunk, which would result in a deadlock (trying to lock twice an
3885 * extent buffer of the chunk btree, first time before triggering the chunk
3886 * allocation and the second time during chunk allocation while attempting to
3887 * update the chunks btree). The system chunk array is also updated while holding
3888 * that mutex. The same logic applies to removing chunks - we must reserve system
3889 * space, update the chunk btree and the system chunk array in the superblock
3890 * while holding fs_info->chunk_mutex.
3892 * This function, btrfs_chunk_alloc(), belongs to phase 1.
3894 * If @force is CHUNK_ALLOC_FORCE:
3895 * - return 1 if it successfully allocates a chunk,
3896 * - return errors including -ENOSPC otherwise.
3897 * If @force is NOT CHUNK_ALLOC_FORCE:
3898 * - return 0 if it doesn't need to allocate a new chunk,
3899 * - return 1 if it successfully allocates a chunk,
3900 * - return errors including -ENOSPC otherwise.
3902 int btrfs_chunk_alloc(struct btrfs_trans_handle
*trans
, u64 flags
,
3903 enum btrfs_chunk_alloc_enum force
)
3905 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
3906 struct btrfs_space_info
*space_info
;
3907 struct btrfs_block_group
*ret_bg
;
3908 bool wait_for_alloc
= false;
3909 bool should_alloc
= false;
3910 bool from_extent_allocation
= false;
3913 if (force
== CHUNK_ALLOC_FORCE_FOR_EXTENT
) {
3914 from_extent_allocation
= true;
3915 force
= CHUNK_ALLOC_FORCE
;
3918 /* Don't re-enter if we're already allocating a chunk */
3919 if (trans
->allocating_chunk
)
3922 * Allocation of system chunks can not happen through this path, as we
3923 * could end up in a deadlock if we are allocating a data or metadata
3924 * chunk and there is another task modifying the chunk btree.
3926 * This is because while we are holding the chunk mutex, we will attempt
3927 * to add the new chunk item to the chunk btree or update an existing
3928 * device item in the chunk btree, while the other task that is modifying
3929 * the chunk btree is attempting to COW an extent buffer while holding a
3930 * lock on it and on its parent - if the COW operation triggers a system
3931 * chunk allocation, then we can deadlock because we are holding the
3932 * chunk mutex and we may need to access that extent buffer or its parent
3933 * in order to add the chunk item or update a device item.
3935 * Tasks that want to modify the chunk tree should reserve system space
3936 * before updating the chunk btree, by calling either
3937 * btrfs_reserve_chunk_metadata() or check_system_chunk().
3938 * It's possible that after a task reserves the space, it still ends up
3939 * here - this happens in the cases described above at do_chunk_alloc().
3940 * The task will have to either retry or fail.
3942 if (flags
& BTRFS_BLOCK_GROUP_SYSTEM
)
3945 space_info
= btrfs_find_space_info(fs_info
, flags
);
3949 spin_lock(&space_info
->lock
);
3950 if (force
< space_info
->force_alloc
)
3951 force
= space_info
->force_alloc
;
3952 should_alloc
= should_alloc_chunk(fs_info
, space_info
, force
);
3953 if (space_info
->full
) {
3954 /* No more free physical space */
3959 spin_unlock(&space_info
->lock
);
3961 } else if (!should_alloc
) {
3962 spin_unlock(&space_info
->lock
);
3964 } else if (space_info
->chunk_alloc
) {
3966 * Someone is already allocating, so we need to block
3967 * until this someone is finished and then loop to
3968 * recheck if we should continue with our allocation
3971 wait_for_alloc
= true;
3972 force
= CHUNK_ALLOC_NO_FORCE
;
3973 spin_unlock(&space_info
->lock
);
3974 mutex_lock(&fs_info
->chunk_mutex
);
3975 mutex_unlock(&fs_info
->chunk_mutex
);
3977 /* Proceed with allocation */
3978 space_info
->chunk_alloc
= 1;
3979 wait_for_alloc
= false;
3980 spin_unlock(&space_info
->lock
);
3984 } while (wait_for_alloc
);
3986 mutex_lock(&fs_info
->chunk_mutex
);
3987 trans
->allocating_chunk
= true;
3990 * If we have mixed data/metadata chunks we want to make sure we keep
3991 * allocating mixed chunks instead of individual chunks.
3993 if (btrfs_mixed_space_info(space_info
))
3994 flags
|= (BTRFS_BLOCK_GROUP_DATA
| BTRFS_BLOCK_GROUP_METADATA
);
3997 * if we're doing a data chunk, go ahead and make sure that
3998 * we keep a reasonable number of metadata chunks allocated in the
4001 if (flags
& BTRFS_BLOCK_GROUP_DATA
&& fs_info
->metadata_ratio
) {
4002 fs_info
->data_chunk_allocations
++;
4003 if (!(fs_info
->data_chunk_allocations
%
4004 fs_info
->metadata_ratio
))
4005 force_metadata_allocation(fs_info
);
4008 ret_bg
= do_chunk_alloc(trans
, flags
);
4009 trans
->allocating_chunk
= false;
4011 if (IS_ERR(ret_bg
)) {
4012 ret
= PTR_ERR(ret_bg
);
4013 } else if (from_extent_allocation
) {
4015 * New block group is likely to be used soon. Try to activate
4016 * it now. Failure is OK for now.
4018 btrfs_zone_activate(ret_bg
);
4022 btrfs_put_block_group(ret_bg
);
4024 spin_lock(&space_info
->lock
);
4027 space_info
->full
= 1;
4032 space_info
->max_extent_size
= 0;
4035 space_info
->force_alloc
= CHUNK_ALLOC_NO_FORCE
;
4037 space_info
->chunk_alloc
= 0;
4038 spin_unlock(&space_info
->lock
);
4039 mutex_unlock(&fs_info
->chunk_mutex
);
4044 static u64
get_profile_num_devs(struct btrfs_fs_info
*fs_info
, u64 type
)
4048 num_dev
= btrfs_raid_array
[btrfs_bg_flags_to_raid_index(type
)].devs_max
;
4050 num_dev
= fs_info
->fs_devices
->rw_devices
;
4055 static void reserve_chunk_space(struct btrfs_trans_handle
*trans
,
4059 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
4060 struct btrfs_space_info
*info
;
4065 * Needed because we can end up allocating a system chunk and for an
4066 * atomic and race free space reservation in the chunk block reserve.
4068 lockdep_assert_held(&fs_info
->chunk_mutex
);
4070 info
= btrfs_find_space_info(fs_info
, BTRFS_BLOCK_GROUP_SYSTEM
);
4071 spin_lock(&info
->lock
);
4072 left
= info
->total_bytes
- btrfs_space_info_used(info
, true);
4073 spin_unlock(&info
->lock
);
4075 if (left
< bytes
&& btrfs_test_opt(fs_info
, ENOSPC_DEBUG
)) {
4076 btrfs_info(fs_info
, "left=%llu, need=%llu, flags=%llu",
4078 btrfs_dump_space_info(fs_info
, info
, 0, 0);
4082 u64 flags
= btrfs_system_alloc_profile(fs_info
);
4083 struct btrfs_block_group
*bg
;
4086 * Ignore failure to create system chunk. We might end up not
4087 * needing it, as we might not need to COW all nodes/leafs from
4088 * the paths we visit in the chunk tree (they were already COWed
4089 * or created in the current transaction for example).
4091 bg
= btrfs_create_chunk(trans
, flags
);
4096 * We have a new chunk. We also need to activate it for
4099 ret
= btrfs_zoned_activate_one_bg(fs_info
, info
, true);
4104 * If we fail to add the chunk item here, we end up
4105 * trying again at phase 2 of chunk allocation, at
4106 * btrfs_create_pending_block_groups(). So ignore
4107 * any error here. An ENOSPC here could happen, due to
4108 * the cases described at do_chunk_alloc() - the system
4109 * block group we just created was just turned into RO
4110 * mode by a scrub for example, or a running discard
4111 * temporarily removed its free space entries, etc.
4113 btrfs_chunk_alloc_add_chunk_item(trans
, bg
);
4118 ret
= btrfs_block_rsv_add(fs_info
,
4119 &fs_info
->chunk_block_rsv
,
4120 bytes
, BTRFS_RESERVE_NO_FLUSH
);
4122 trans
->chunk_bytes_reserved
+= bytes
;
4127 * Reserve space in the system space for allocating or removing a chunk.
4128 * The caller must be holding fs_info->chunk_mutex.
4130 void check_system_chunk(struct btrfs_trans_handle
*trans
, u64 type
)
4132 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
4133 const u64 num_devs
= get_profile_num_devs(fs_info
, type
);
4136 /* num_devs device items to update and 1 chunk item to add or remove. */
4137 bytes
= btrfs_calc_metadata_size(fs_info
, num_devs
) +
4138 btrfs_calc_insert_metadata_size(fs_info
, 1);
4140 reserve_chunk_space(trans
, bytes
, type
);
4144 * Reserve space in the system space, if needed, for doing a modification to the
4147 * @trans: A transaction handle.
4148 * @is_item_insertion: Indicate if the modification is for inserting a new item
4149 * in the chunk btree or if it's for the deletion or update
4150 * of an existing item.
4152 * This is used in a context where we need to update the chunk btree outside
4153 * block group allocation and removal, to avoid a deadlock with a concurrent
4154 * task that is allocating a metadata or data block group and therefore needs to
4155 * update the chunk btree while holding the chunk mutex. After the update to the
4156 * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called.
4159 void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle
*trans
,
4160 bool is_item_insertion
)
4162 struct btrfs_fs_info
*fs_info
= trans
->fs_info
;
4165 if (is_item_insertion
)
4166 bytes
= btrfs_calc_insert_metadata_size(fs_info
, 1);
4168 bytes
= btrfs_calc_metadata_size(fs_info
, 1);
4170 mutex_lock(&fs_info
->chunk_mutex
);
4171 reserve_chunk_space(trans
, bytes
, BTRFS_BLOCK_GROUP_SYSTEM
);
4172 mutex_unlock(&fs_info
->chunk_mutex
);
4175 void btrfs_put_block_group_cache(struct btrfs_fs_info
*info
)
4177 struct btrfs_block_group
*block_group
;
4179 block_group
= btrfs_lookup_first_block_group(info
, 0);
4180 while (block_group
) {
4181 btrfs_wait_block_group_cache_done(block_group
);
4182 spin_lock(&block_group
->lock
);
4183 if (test_and_clear_bit(BLOCK_GROUP_FLAG_IREF
,
4184 &block_group
->runtime_flags
)) {
4185 struct inode
*inode
= block_group
->inode
;
4187 block_group
->inode
= NULL
;
4188 spin_unlock(&block_group
->lock
);
4190 ASSERT(block_group
->io_ctl
.inode
== NULL
);
4193 spin_unlock(&block_group
->lock
);
4195 block_group
= btrfs_next_block_group(block_group
);
4200 * Must be called only after stopping all workers, since we could have block
4201 * group caching kthreads running, and therefore they could race with us if we
4202 * freed the block groups before stopping them.
4204 int btrfs_free_block_groups(struct btrfs_fs_info
*info
)
4206 struct btrfs_block_group
*block_group
;
4207 struct btrfs_space_info
*space_info
;
4208 struct btrfs_caching_control
*caching_ctl
;
4211 write_lock(&info
->block_group_cache_lock
);
4212 while (!list_empty(&info
->caching_block_groups
)) {
4213 caching_ctl
= list_entry(info
->caching_block_groups
.next
,
4214 struct btrfs_caching_control
, list
);
4215 list_del(&caching_ctl
->list
);
4216 btrfs_put_caching_control(caching_ctl
);
4218 write_unlock(&info
->block_group_cache_lock
);
4220 spin_lock(&info
->unused_bgs_lock
);
4221 while (!list_empty(&info
->unused_bgs
)) {
4222 block_group
= list_first_entry(&info
->unused_bgs
,
4223 struct btrfs_block_group
,
4225 list_del_init(&block_group
->bg_list
);
4226 btrfs_put_block_group(block_group
);
4229 while (!list_empty(&info
->reclaim_bgs
)) {
4230 block_group
= list_first_entry(&info
->reclaim_bgs
,
4231 struct btrfs_block_group
,
4233 list_del_init(&block_group
->bg_list
);
4234 btrfs_put_block_group(block_group
);
4236 spin_unlock(&info
->unused_bgs_lock
);
4238 spin_lock(&info
->zone_active_bgs_lock
);
4239 while (!list_empty(&info
->zone_active_bgs
)) {
4240 block_group
= list_first_entry(&info
->zone_active_bgs
,
4241 struct btrfs_block_group
,
4243 list_del_init(&block_group
->active_bg_list
);
4244 btrfs_put_block_group(block_group
);
4246 spin_unlock(&info
->zone_active_bgs_lock
);
4248 write_lock(&info
->block_group_cache_lock
);
4249 while ((n
= rb_last(&info
->block_group_cache_tree
.rb_root
)) != NULL
) {
4250 block_group
= rb_entry(n
, struct btrfs_block_group
,
4252 rb_erase_cached(&block_group
->cache_node
,
4253 &info
->block_group_cache_tree
);
4254 RB_CLEAR_NODE(&block_group
->cache_node
);
4255 write_unlock(&info
->block_group_cache_lock
);
4257 down_write(&block_group
->space_info
->groups_sem
);
4258 list_del(&block_group
->list
);
4259 up_write(&block_group
->space_info
->groups_sem
);
4262 * We haven't cached this block group, which means we could
4263 * possibly have excluded extents on this block group.
4265 if (block_group
->cached
== BTRFS_CACHE_NO
||
4266 block_group
->cached
== BTRFS_CACHE_ERROR
)
4267 btrfs_free_excluded_extents(block_group
);
4269 btrfs_remove_free_space_cache(block_group
);
4270 ASSERT(block_group
->cached
!= BTRFS_CACHE_STARTED
);
4271 ASSERT(list_empty(&block_group
->dirty_list
));
4272 ASSERT(list_empty(&block_group
->io_list
));
4273 ASSERT(list_empty(&block_group
->bg_list
));
4274 ASSERT(refcount_read(&block_group
->refs
) == 1);
4275 ASSERT(block_group
->swap_extents
== 0);
4276 btrfs_put_block_group(block_group
);
4278 write_lock(&info
->block_group_cache_lock
);
4280 write_unlock(&info
->block_group_cache_lock
);
4282 btrfs_release_global_block_rsv(info
);
4284 while (!list_empty(&info
->space_info
)) {
4285 space_info
= list_entry(info
->space_info
.next
,
4286 struct btrfs_space_info
,
4290 * Do not hide this behind enospc_debug, this is actually
4291 * important and indicates a real bug if this happens.
4293 if (WARN_ON(space_info
->bytes_pinned
> 0 ||
4294 space_info
->bytes_may_use
> 0))
4295 btrfs_dump_space_info(info
, space_info
, 0, 0);
4298 * If there was a failure to cleanup a log tree, very likely due
4299 * to an IO failure on a writeback attempt of one or more of its
4300 * extent buffers, we could not do proper (and cheap) unaccounting
4301 * of their reserved space, so don't warn on bytes_reserved > 0 in
4304 if (!(space_info
->flags
& BTRFS_BLOCK_GROUP_METADATA
) ||
4305 !BTRFS_FS_LOG_CLEANUP_ERROR(info
)) {
4306 if (WARN_ON(space_info
->bytes_reserved
> 0))
4307 btrfs_dump_space_info(info
, space_info
, 0, 0);
4310 WARN_ON(space_info
->reclaim_size
> 0);
4311 list_del(&space_info
->list
);
4312 btrfs_sysfs_remove_space_info(space_info
);
4317 void btrfs_freeze_block_group(struct btrfs_block_group
*cache
)
4319 atomic_inc(&cache
->frozen
);
4322 void btrfs_unfreeze_block_group(struct btrfs_block_group
*block_group
)
4324 struct btrfs_fs_info
*fs_info
= block_group
->fs_info
;
4325 struct extent_map_tree
*em_tree
;
4326 struct extent_map
*em
;
4329 spin_lock(&block_group
->lock
);
4330 cleanup
= (atomic_dec_and_test(&block_group
->frozen
) &&
4331 test_bit(BLOCK_GROUP_FLAG_REMOVED
, &block_group
->runtime_flags
));
4332 spin_unlock(&block_group
->lock
);
4335 em_tree
= &fs_info
->mapping_tree
;
4336 write_lock(&em_tree
->lock
);
4337 em
= lookup_extent_mapping(em_tree
, block_group
->start
,
4339 BUG_ON(!em
); /* logic error, can't happen */
4340 remove_extent_mapping(em_tree
, em
);
4341 write_unlock(&em_tree
->lock
);
4343 /* once for us and once for the tree */
4344 free_extent_map(em
);
4345 free_extent_map(em
);
4348 * We may have left one free space entry and other possible
4349 * tasks trimming this block group have left 1 entry each one.
4352 btrfs_remove_free_space_cache(block_group
);
4356 bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group
*bg
)
4360 spin_lock(&bg
->lock
);
4365 spin_unlock(&bg
->lock
);
4370 void btrfs_dec_block_group_swap_extents(struct btrfs_block_group
*bg
, int amount
)
4372 spin_lock(&bg
->lock
);
4374 ASSERT(bg
->swap_extents
>= amount
);
4375 bg
->swap_extents
-= amount
;
4376 spin_unlock(&bg
->lock
);
4379 enum btrfs_block_group_size_class
btrfs_calc_block_group_size_class(u64 size
)
4381 if (size
<= SZ_128K
)
4382 return BTRFS_BG_SZ_SMALL
;
4384 return BTRFS_BG_SZ_MEDIUM
;
4385 return BTRFS_BG_SZ_LARGE
;
4389 * Handle a block group allocating an extent in a size class
4391 * @bg: The block group we allocated in.
4392 * @size_class: The size class of the allocation.
4393 * @force_wrong_size_class: Whether we are desperate enough to allow
4394 * mismatched size classes.
4396 * Returns: 0 if the size class was valid for this block_group, -EAGAIN in the
4397 * case of a race that leads to the wrong size class without
4398 * force_wrong_size_class set.
4400 * find_free_extent will skip block groups with a mismatched size class until
4401 * it really needs to avoid ENOSPC. In that case it will set
4402 * force_wrong_size_class. However, if a block group is newly allocated and
4403 * doesn't yet have a size class, then it is possible for two allocations of
4404 * different sizes to race and both try to use it. The loser is caught here and
4407 int btrfs_use_block_group_size_class(struct btrfs_block_group
*bg
,
4408 enum btrfs_block_group_size_class size_class
,
4409 bool force_wrong_size_class
)
4411 ASSERT(size_class
!= BTRFS_BG_SZ_NONE
);
4413 /* The new allocation is in the right size class, do nothing */
4414 if (bg
->size_class
== size_class
)
4417 * The new allocation is in a mismatched size class.
4418 * This means one of two things:
4420 * 1. Two tasks in find_free_extent for different size_classes raced
4421 * and hit the same empty block_group. Make the loser try again.
4422 * 2. A call to find_free_extent got desperate enough to set
4423 * 'force_wrong_slab'. Don't change the size_class, but allow the
4426 if (bg
->size_class
!= BTRFS_BG_SZ_NONE
) {
4427 if (force_wrong_size_class
)
4432 * The happy new block group case: the new allocation is the first
4433 * one in the block_group so we set size_class.
4435 bg
->size_class
= size_class
;
4440 bool btrfs_block_group_should_use_size_class(struct btrfs_block_group
*bg
)
4442 if (btrfs_is_zoned(bg
->fs_info
))
4444 if (!btrfs_is_block_group_data_only(bg
))