1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/sched/mm.h>
8 #include <linux/sched/signal.h>
9 #include <linux/pagemap.h>
10 #include <linux/writeback.h>
11 #include <linux/blkdev.h>
12 #include <linux/sort.h>
13 #include <linux/rcupdate.h>
14 #include <linux/kthread.h>
15 #include <linux/slab.h>
16 #include <linux/ratelimit.h>
17 #include <linux/percpu_counter.h>
18 #include <linux/lockdep.h>
19 #include <linux/crc32c.h>
22 #include "print-tree.h"
26 #include "free-space-cache.h"
27 #include "free-space-tree.h"
31 #include "ref-verify.h"
32 #include "space-info.h"
33 #include "block-rsv.h"
34 #include "delalloc-space.h"
36 #undef SCRAMBLE_DELAYED_REFS
39 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
40 struct btrfs_delayed_ref_node *node, u64 parent,
41 u64 root_objectid, u64 owner_objectid,
42 u64 owner_offset, int refs_to_drop,
43 struct btrfs_delayed_extent_op *extra_op);
44 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
45 struct extent_buffer *leaf,
46 struct btrfs_extent_item *ei);
47 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
48 u64 parent, u64 root_objectid,
49 u64 flags, u64 owner, u64 offset,
50 struct btrfs_key *ins, int ref_mod);
51 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
52 struct btrfs_delayed_ref_node *node,
53 struct btrfs_delayed_extent_op *extent_op);
54 static int find_next_key(struct btrfs_path *path, int level,
55 struct btrfs_key *key);
58 block_group_cache_done(struct btrfs_block_group_cache *cache)
61 return cache->cached == BTRFS_CACHE_FINISHED ||
62 cache->cached == BTRFS_CACHE_ERROR;
65 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
67 return (cache->flags & bits) == bits;
70 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
72 atomic_inc(&cache->count);
75 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
77 if (atomic_dec_and_test(&cache->count)) {
78 WARN_ON(cache->pinned > 0);
79 WARN_ON(cache->reserved > 0);
82 * If not empty, someone is still holding mutex of
83 * full_stripe_lock, which can only be released by caller.
84 * And it will definitely cause use-after-free when caller
85 * tries to release full stripe lock.
87 * No better way to resolve, but only to warn.
89 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
90 kfree(cache->free_space_ctl);
96 * this adds the block group to the fs_info rb tree for the block group
99 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
100 struct btrfs_block_group_cache *block_group)
103 struct rb_node *parent = NULL;
104 struct btrfs_block_group_cache *cache;
106 spin_lock(&info->block_group_cache_lock);
107 p = &info->block_group_cache_tree.rb_node;
111 cache = rb_entry(parent, struct btrfs_block_group_cache,
113 if (block_group->key.objectid < cache->key.objectid) {
115 } else if (block_group->key.objectid > cache->key.objectid) {
118 spin_unlock(&info->block_group_cache_lock);
123 rb_link_node(&block_group->cache_node, parent, p);
124 rb_insert_color(&block_group->cache_node,
125 &info->block_group_cache_tree);
127 if (info->first_logical_byte > block_group->key.objectid)
128 info->first_logical_byte = block_group->key.objectid;
130 spin_unlock(&info->block_group_cache_lock);
136 * This will return the block group at or after bytenr if contains is 0, else
137 * it will return the block group that contains the bytenr
139 static struct btrfs_block_group_cache *
140 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
143 struct btrfs_block_group_cache *cache, *ret = NULL;
147 spin_lock(&info->block_group_cache_lock);
148 n = info->block_group_cache_tree.rb_node;
151 cache = rb_entry(n, struct btrfs_block_group_cache,
153 end = cache->key.objectid + cache->key.offset - 1;
154 start = cache->key.objectid;
156 if (bytenr < start) {
157 if (!contains && (!ret || start < ret->key.objectid))
160 } else if (bytenr > start) {
161 if (contains && bytenr <= end) {
172 btrfs_get_block_group(ret);
173 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
174 info->first_logical_byte = ret->key.objectid;
176 spin_unlock(&info->block_group_cache_lock);
181 static int add_excluded_extent(struct btrfs_fs_info *fs_info,
182 u64 start, u64 num_bytes)
184 u64 end = start + num_bytes - 1;
185 set_extent_bits(&fs_info->freed_extents[0],
186 start, end, EXTENT_UPTODATE);
187 set_extent_bits(&fs_info->freed_extents[1],
188 start, end, EXTENT_UPTODATE);
192 static void free_excluded_extents(struct btrfs_block_group_cache *cache)
194 struct btrfs_fs_info *fs_info = cache->fs_info;
197 start = cache->key.objectid;
198 end = start + cache->key.offset - 1;
200 clear_extent_bits(&fs_info->freed_extents[0],
201 start, end, EXTENT_UPTODATE);
202 clear_extent_bits(&fs_info->freed_extents[1],
203 start, end, EXTENT_UPTODATE);
206 static int exclude_super_stripes(struct btrfs_block_group_cache *cache)
208 struct btrfs_fs_info *fs_info = cache->fs_info;
214 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
215 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
216 cache->bytes_super += stripe_len;
217 ret = add_excluded_extent(fs_info, cache->key.objectid,
223 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
224 bytenr = btrfs_sb_offset(i);
225 ret = btrfs_rmap_block(fs_info, cache->key.objectid,
226 bytenr, &logical, &nr, &stripe_len);
233 if (logical[nr] > cache->key.objectid +
237 if (logical[nr] + stripe_len <= cache->key.objectid)
241 if (start < cache->key.objectid) {
242 start = cache->key.objectid;
243 len = (logical[nr] + stripe_len) - start;
245 len = min_t(u64, stripe_len,
246 cache->key.objectid +
247 cache->key.offset - start);
250 cache->bytes_super += len;
251 ret = add_excluded_extent(fs_info, start, len);
263 static struct btrfs_caching_control *
264 get_caching_control(struct btrfs_block_group_cache *cache)
266 struct btrfs_caching_control *ctl;
268 spin_lock(&cache->lock);
269 if (!cache->caching_ctl) {
270 spin_unlock(&cache->lock);
274 ctl = cache->caching_ctl;
275 refcount_inc(&ctl->count);
276 spin_unlock(&cache->lock);
280 static void put_caching_control(struct btrfs_caching_control *ctl)
282 if (refcount_dec_and_test(&ctl->count))
286 #ifdef CONFIG_BTRFS_DEBUG
287 static void fragment_free_space(struct btrfs_block_group_cache *block_group)
289 struct btrfs_fs_info *fs_info = block_group->fs_info;
290 u64 start = block_group->key.objectid;
291 u64 len = block_group->key.offset;
292 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
293 fs_info->nodesize : fs_info->sectorsize;
294 u64 step = chunk << 1;
296 while (len > chunk) {
297 btrfs_remove_free_space(block_group, start, chunk);
308 * this is only called by cache_block_group, since we could have freed extents
309 * we need to check the pinned_extents for any extents that can't be used yet
310 * since their free space will be released as soon as the transaction commits.
312 u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
315 struct btrfs_fs_info *info = block_group->fs_info;
316 u64 extent_start, extent_end, size, total_added = 0;
319 while (start < end) {
320 ret = find_first_extent_bit(info->pinned_extents, start,
321 &extent_start, &extent_end,
322 EXTENT_DIRTY | EXTENT_UPTODATE,
327 if (extent_start <= start) {
328 start = extent_end + 1;
329 } else if (extent_start > start && extent_start < end) {
330 size = extent_start - start;
332 ret = btrfs_add_free_space(block_group, start,
334 BUG_ON(ret); /* -ENOMEM or logic error */
335 start = extent_end + 1;
344 ret = btrfs_add_free_space(block_group, start, size);
345 BUG_ON(ret); /* -ENOMEM or logic error */
351 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
353 struct btrfs_block_group_cache *block_group = caching_ctl->block_group;
354 struct btrfs_fs_info *fs_info = block_group->fs_info;
355 struct btrfs_root *extent_root = fs_info->extent_root;
356 struct btrfs_path *path;
357 struct extent_buffer *leaf;
358 struct btrfs_key key;
365 path = btrfs_alloc_path();
369 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
371 #ifdef CONFIG_BTRFS_DEBUG
373 * If we're fragmenting we don't want to make anybody think we can
374 * allocate from this block group until we've had a chance to fragment
377 if (btrfs_should_fragment_free_space(block_group))
381 * We don't want to deadlock with somebody trying to allocate a new
382 * extent for the extent root while also trying to search the extent
383 * root to add free space. So we skip locking and search the commit
384 * root, since its read-only
386 path->skip_locking = 1;
387 path->search_commit_root = 1;
388 path->reada = READA_FORWARD;
392 key.type = BTRFS_EXTENT_ITEM_KEY;
395 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
399 leaf = path->nodes[0];
400 nritems = btrfs_header_nritems(leaf);
403 if (btrfs_fs_closing(fs_info) > 1) {
408 if (path->slots[0] < nritems) {
409 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
411 ret = find_next_key(path, 0, &key);
415 if (need_resched() ||
416 rwsem_is_contended(&fs_info->commit_root_sem)) {
418 caching_ctl->progress = last;
419 btrfs_release_path(path);
420 up_read(&fs_info->commit_root_sem);
421 mutex_unlock(&caching_ctl->mutex);
423 mutex_lock(&caching_ctl->mutex);
424 down_read(&fs_info->commit_root_sem);
428 ret = btrfs_next_leaf(extent_root, path);
433 leaf = path->nodes[0];
434 nritems = btrfs_header_nritems(leaf);
438 if (key.objectid < last) {
441 key.type = BTRFS_EXTENT_ITEM_KEY;
444 caching_ctl->progress = last;
445 btrfs_release_path(path);
449 if (key.objectid < block_group->key.objectid) {
454 if (key.objectid >= block_group->key.objectid +
455 block_group->key.offset)
458 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
459 key.type == BTRFS_METADATA_ITEM_KEY) {
460 total_found += add_new_free_space(block_group, last,
462 if (key.type == BTRFS_METADATA_ITEM_KEY)
463 last = key.objectid +
466 last = key.objectid + key.offset;
468 if (total_found > CACHING_CTL_WAKE_UP) {
471 wake_up(&caching_ctl->wait);
478 total_found += add_new_free_space(block_group, last,
479 block_group->key.objectid +
480 block_group->key.offset);
481 caching_ctl->progress = (u64)-1;
484 btrfs_free_path(path);
488 static noinline void caching_thread(struct btrfs_work *work)
490 struct btrfs_block_group_cache *block_group;
491 struct btrfs_fs_info *fs_info;
492 struct btrfs_caching_control *caching_ctl;
495 caching_ctl = container_of(work, struct btrfs_caching_control, work);
496 block_group = caching_ctl->block_group;
497 fs_info = block_group->fs_info;
499 mutex_lock(&caching_ctl->mutex);
500 down_read(&fs_info->commit_root_sem);
502 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
503 ret = load_free_space_tree(caching_ctl);
505 ret = load_extent_tree_free(caching_ctl);
507 spin_lock(&block_group->lock);
508 block_group->caching_ctl = NULL;
509 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
510 spin_unlock(&block_group->lock);
512 #ifdef CONFIG_BTRFS_DEBUG
513 if (btrfs_should_fragment_free_space(block_group)) {
516 spin_lock(&block_group->space_info->lock);
517 spin_lock(&block_group->lock);
518 bytes_used = block_group->key.offset -
519 btrfs_block_group_used(&block_group->item);
520 block_group->space_info->bytes_used += bytes_used >> 1;
521 spin_unlock(&block_group->lock);
522 spin_unlock(&block_group->space_info->lock);
523 fragment_free_space(block_group);
527 caching_ctl->progress = (u64)-1;
529 up_read(&fs_info->commit_root_sem);
530 free_excluded_extents(block_group);
531 mutex_unlock(&caching_ctl->mutex);
533 wake_up(&caching_ctl->wait);
535 put_caching_control(caching_ctl);
536 btrfs_put_block_group(block_group);
539 static int cache_block_group(struct btrfs_block_group_cache *cache,
543 struct btrfs_fs_info *fs_info = cache->fs_info;
544 struct btrfs_caching_control *caching_ctl;
547 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
551 INIT_LIST_HEAD(&caching_ctl->list);
552 mutex_init(&caching_ctl->mutex);
553 init_waitqueue_head(&caching_ctl->wait);
554 caching_ctl->block_group = cache;
555 caching_ctl->progress = cache->key.objectid;
556 refcount_set(&caching_ctl->count, 1);
557 btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
558 caching_thread, NULL, NULL);
560 spin_lock(&cache->lock);
562 * This should be a rare occasion, but this could happen I think in the
563 * case where one thread starts to load the space cache info, and then
564 * some other thread starts a transaction commit which tries to do an
565 * allocation while the other thread is still loading the space cache
566 * info. The previous loop should have kept us from choosing this block
567 * group, but if we've moved to the state where we will wait on caching
568 * block groups we need to first check if we're doing a fast load here,
569 * so we can wait for it to finish, otherwise we could end up allocating
570 * from a block group who's cache gets evicted for one reason or
573 while (cache->cached == BTRFS_CACHE_FAST) {
574 struct btrfs_caching_control *ctl;
576 ctl = cache->caching_ctl;
577 refcount_inc(&ctl->count);
578 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
579 spin_unlock(&cache->lock);
583 finish_wait(&ctl->wait, &wait);
584 put_caching_control(ctl);
585 spin_lock(&cache->lock);
588 if (cache->cached != BTRFS_CACHE_NO) {
589 spin_unlock(&cache->lock);
593 WARN_ON(cache->caching_ctl);
594 cache->caching_ctl = caching_ctl;
595 cache->cached = BTRFS_CACHE_FAST;
596 spin_unlock(&cache->lock);
598 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
599 mutex_lock(&caching_ctl->mutex);
600 ret = load_free_space_cache(cache);
602 spin_lock(&cache->lock);
604 cache->caching_ctl = NULL;
605 cache->cached = BTRFS_CACHE_FINISHED;
606 cache->last_byte_to_unpin = (u64)-1;
607 caching_ctl->progress = (u64)-1;
609 if (load_cache_only) {
610 cache->caching_ctl = NULL;
611 cache->cached = BTRFS_CACHE_NO;
613 cache->cached = BTRFS_CACHE_STARTED;
614 cache->has_caching_ctl = 1;
617 spin_unlock(&cache->lock);
618 #ifdef CONFIG_BTRFS_DEBUG
620 btrfs_should_fragment_free_space(cache)) {
623 spin_lock(&cache->space_info->lock);
624 spin_lock(&cache->lock);
625 bytes_used = cache->key.offset -
626 btrfs_block_group_used(&cache->item);
627 cache->space_info->bytes_used += bytes_used >> 1;
628 spin_unlock(&cache->lock);
629 spin_unlock(&cache->space_info->lock);
630 fragment_free_space(cache);
633 mutex_unlock(&caching_ctl->mutex);
635 wake_up(&caching_ctl->wait);
637 put_caching_control(caching_ctl);
638 free_excluded_extents(cache);
643 * We're either using the free space tree or no caching at all.
644 * Set cached to the appropriate value and wakeup any waiters.
646 spin_lock(&cache->lock);
647 if (load_cache_only) {
648 cache->caching_ctl = NULL;
649 cache->cached = BTRFS_CACHE_NO;
651 cache->cached = BTRFS_CACHE_STARTED;
652 cache->has_caching_ctl = 1;
654 spin_unlock(&cache->lock);
655 wake_up(&caching_ctl->wait);
658 if (load_cache_only) {
659 put_caching_control(caching_ctl);
663 down_write(&fs_info->commit_root_sem);
664 refcount_inc(&caching_ctl->count);
665 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
666 up_write(&fs_info->commit_root_sem);
668 btrfs_get_block_group(cache);
670 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
676 * return the block group that starts at or after bytenr
678 static struct btrfs_block_group_cache *
679 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
681 return block_group_cache_tree_search(info, bytenr, 0);
685 * return the block group that contains the given bytenr
687 struct btrfs_block_group_cache *btrfs_lookup_block_group(
688 struct btrfs_fs_info *info,
691 return block_group_cache_tree_search(info, bytenr, 1);
694 static u64 generic_ref_to_space_flags(struct btrfs_ref *ref)
696 if (ref->type == BTRFS_REF_METADATA) {
697 if (ref->tree_ref.root == BTRFS_CHUNK_TREE_OBJECTID)
698 return BTRFS_BLOCK_GROUP_SYSTEM;
700 return BTRFS_BLOCK_GROUP_METADATA;
702 return BTRFS_BLOCK_GROUP_DATA;
705 static void add_pinned_bytes(struct btrfs_fs_info *fs_info,
706 struct btrfs_ref *ref)
708 struct btrfs_space_info *space_info;
709 u64 flags = generic_ref_to_space_flags(ref);
711 space_info = btrfs_find_space_info(fs_info, flags);
713 percpu_counter_add_batch(&space_info->total_bytes_pinned, ref->len,
714 BTRFS_TOTAL_BYTES_PINNED_BATCH);
717 static void sub_pinned_bytes(struct btrfs_fs_info *fs_info,
718 struct btrfs_ref *ref)
720 struct btrfs_space_info *space_info;
721 u64 flags = generic_ref_to_space_flags(ref);
723 space_info = btrfs_find_space_info(fs_info, flags);
725 percpu_counter_add_batch(&space_info->total_bytes_pinned, -ref->len,
726 BTRFS_TOTAL_BYTES_PINNED_BATCH);
729 /* simple helper to search for an existing data extent at a given offset */
730 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
733 struct btrfs_key key;
734 struct btrfs_path *path;
736 path = btrfs_alloc_path();
740 key.objectid = start;
742 key.type = BTRFS_EXTENT_ITEM_KEY;
743 ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
744 btrfs_free_path(path);
749 * helper function to lookup reference count and flags of a tree block.
751 * the head node for delayed ref is used to store the sum of all the
752 * reference count modifications queued up in the rbtree. the head
753 * node may also store the extent flags to set. This way you can check
754 * to see what the reference count and extent flags would be if all of
755 * the delayed refs are not processed.
757 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
758 struct btrfs_fs_info *fs_info, u64 bytenr,
759 u64 offset, int metadata, u64 *refs, u64 *flags)
761 struct btrfs_delayed_ref_head *head;
762 struct btrfs_delayed_ref_root *delayed_refs;
763 struct btrfs_path *path;
764 struct btrfs_extent_item *ei;
765 struct extent_buffer *leaf;
766 struct btrfs_key key;
773 * If we don't have skinny metadata, don't bother doing anything
776 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
777 offset = fs_info->nodesize;
781 path = btrfs_alloc_path();
786 path->skip_locking = 1;
787 path->search_commit_root = 1;
791 key.objectid = bytenr;
794 key.type = BTRFS_METADATA_ITEM_KEY;
796 key.type = BTRFS_EXTENT_ITEM_KEY;
798 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
802 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
803 if (path->slots[0]) {
805 btrfs_item_key_to_cpu(path->nodes[0], &key,
807 if (key.objectid == bytenr &&
808 key.type == BTRFS_EXTENT_ITEM_KEY &&
809 key.offset == fs_info->nodesize)
815 leaf = path->nodes[0];
816 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
817 if (item_size >= sizeof(*ei)) {
818 ei = btrfs_item_ptr(leaf, path->slots[0],
819 struct btrfs_extent_item);
820 num_refs = btrfs_extent_refs(leaf, ei);
821 extent_flags = btrfs_extent_flags(leaf, ei);
824 btrfs_print_v0_err(fs_info);
826 btrfs_abort_transaction(trans, ret);
828 btrfs_handle_fs_error(fs_info, ret, NULL);
833 BUG_ON(num_refs == 0);
843 delayed_refs = &trans->transaction->delayed_refs;
844 spin_lock(&delayed_refs->lock);
845 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
847 if (!mutex_trylock(&head->mutex)) {
848 refcount_inc(&head->refs);
849 spin_unlock(&delayed_refs->lock);
851 btrfs_release_path(path);
854 * Mutex was contended, block until it's released and try
857 mutex_lock(&head->mutex);
858 mutex_unlock(&head->mutex);
859 btrfs_put_delayed_ref_head(head);
862 spin_lock(&head->lock);
863 if (head->extent_op && head->extent_op->update_flags)
864 extent_flags |= head->extent_op->flags_to_set;
866 BUG_ON(num_refs == 0);
868 num_refs += head->ref_mod;
869 spin_unlock(&head->lock);
870 mutex_unlock(&head->mutex);
872 spin_unlock(&delayed_refs->lock);
874 WARN_ON(num_refs == 0);
878 *flags = extent_flags;
880 btrfs_free_path(path);
885 * Back reference rules. Back refs have three main goals:
887 * 1) differentiate between all holders of references to an extent so that
888 * when a reference is dropped we can make sure it was a valid reference
889 * before freeing the extent.
891 * 2) Provide enough information to quickly find the holders of an extent
892 * if we notice a given block is corrupted or bad.
894 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
895 * maintenance. This is actually the same as #2, but with a slightly
896 * different use case.
898 * There are two kinds of back refs. The implicit back refs is optimized
899 * for pointers in non-shared tree blocks. For a given pointer in a block,
900 * back refs of this kind provide information about the block's owner tree
901 * and the pointer's key. These information allow us to find the block by
902 * b-tree searching. The full back refs is for pointers in tree blocks not
903 * referenced by their owner trees. The location of tree block is recorded
904 * in the back refs. Actually the full back refs is generic, and can be
905 * used in all cases the implicit back refs is used. The major shortcoming
906 * of the full back refs is its overhead. Every time a tree block gets
907 * COWed, we have to update back refs entry for all pointers in it.
909 * For a newly allocated tree block, we use implicit back refs for
910 * pointers in it. This means most tree related operations only involve
911 * implicit back refs. For a tree block created in old transaction, the
912 * only way to drop a reference to it is COW it. So we can detect the
913 * event that tree block loses its owner tree's reference and do the
914 * back refs conversion.
916 * When a tree block is COWed through a tree, there are four cases:
918 * The reference count of the block is one and the tree is the block's
919 * owner tree. Nothing to do in this case.
921 * The reference count of the block is one and the tree is not the
922 * block's owner tree. In this case, full back refs is used for pointers
923 * in the block. Remove these full back refs, add implicit back refs for
924 * every pointers in the new block.
926 * The reference count of the block is greater than one and the tree is
927 * the block's owner tree. In this case, implicit back refs is used for
928 * pointers in the block. Add full back refs for every pointers in the
929 * block, increase lower level extents' reference counts. The original
930 * implicit back refs are entailed to the new block.
932 * The reference count of the block is greater than one and the tree is
933 * not the block's owner tree. Add implicit back refs for every pointer in
934 * the new block, increase lower level extents' reference count.
936 * Back Reference Key composing:
938 * The key objectid corresponds to the first byte in the extent,
939 * The key type is used to differentiate between types of back refs.
940 * There are different meanings of the key offset for different types
943 * File extents can be referenced by:
945 * - multiple snapshots, subvolumes, or different generations in one subvol
946 * - different files inside a single subvolume
947 * - different offsets inside a file (bookend extents in file.c)
949 * The extent ref structure for the implicit back refs has fields for:
951 * - Objectid of the subvolume root
952 * - objectid of the file holding the reference
953 * - original offset in the file
954 * - how many bookend extents
956 * The key offset for the implicit back refs is hash of the first
959 * The extent ref structure for the full back refs has field for:
961 * - number of pointers in the tree leaf
963 * The key offset for the implicit back refs is the first byte of
966 * When a file extent is allocated, The implicit back refs is used.
967 * the fields are filled in:
969 * (root_key.objectid, inode objectid, offset in file, 1)
971 * When a file extent is removed file truncation, we find the
972 * corresponding implicit back refs and check the following fields:
974 * (btrfs_header_owner(leaf), inode objectid, offset in file)
976 * Btree extents can be referenced by:
978 * - Different subvolumes
980 * Both the implicit back refs and the full back refs for tree blocks
981 * only consist of key. The key offset for the implicit back refs is
982 * objectid of block's owner tree. The key offset for the full back refs
983 * is the first byte of parent block.
985 * When implicit back refs is used, information about the lowest key and
986 * level of the tree block are required. These information are stored in
987 * tree block info structure.
991 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
992 * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
993 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
995 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
996 struct btrfs_extent_inline_ref *iref,
997 enum btrfs_inline_ref_type is_data)
999 int type = btrfs_extent_inline_ref_type(eb, iref);
1000 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
1002 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
1003 type == BTRFS_SHARED_BLOCK_REF_KEY ||
1004 type == BTRFS_SHARED_DATA_REF_KEY ||
1005 type == BTRFS_EXTENT_DATA_REF_KEY) {
1006 if (is_data == BTRFS_REF_TYPE_BLOCK) {
1007 if (type == BTRFS_TREE_BLOCK_REF_KEY)
1009 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1010 ASSERT(eb->fs_info);
1012 * Every shared one has parent tree
1013 * block, which must be aligned to
1017 IS_ALIGNED(offset, eb->fs_info->nodesize))
1020 } else if (is_data == BTRFS_REF_TYPE_DATA) {
1021 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1023 if (type == BTRFS_SHARED_DATA_REF_KEY) {
1024 ASSERT(eb->fs_info);
1026 * Every shared one has parent tree
1027 * block, which must be aligned to
1031 IS_ALIGNED(offset, eb->fs_info->nodesize))
1035 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
1040 btrfs_print_leaf((struct extent_buffer *)eb);
1041 btrfs_err(eb->fs_info, "eb %llu invalid extent inline ref type %d",
1045 return BTRFS_REF_TYPE_INVALID;
1048 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1050 u32 high_crc = ~(u32)0;
1051 u32 low_crc = ~(u32)0;
1054 lenum = cpu_to_le64(root_objectid);
1055 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
1056 lenum = cpu_to_le64(owner);
1057 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1058 lenum = cpu_to_le64(offset);
1059 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1061 return ((u64)high_crc << 31) ^ (u64)low_crc;
1064 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1065 struct btrfs_extent_data_ref *ref)
1067 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1068 btrfs_extent_data_ref_objectid(leaf, ref),
1069 btrfs_extent_data_ref_offset(leaf, ref));
1072 static int match_extent_data_ref(struct extent_buffer *leaf,
1073 struct btrfs_extent_data_ref *ref,
1074 u64 root_objectid, u64 owner, u64 offset)
1076 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1077 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1078 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1083 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1084 struct btrfs_path *path,
1085 u64 bytenr, u64 parent,
1087 u64 owner, u64 offset)
1089 struct btrfs_root *root = trans->fs_info->extent_root;
1090 struct btrfs_key key;
1091 struct btrfs_extent_data_ref *ref;
1092 struct extent_buffer *leaf;
1098 key.objectid = bytenr;
1100 key.type = BTRFS_SHARED_DATA_REF_KEY;
1101 key.offset = parent;
1103 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1104 key.offset = hash_extent_data_ref(root_objectid,
1109 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1121 leaf = path->nodes[0];
1122 nritems = btrfs_header_nritems(leaf);
1124 if (path->slots[0] >= nritems) {
1125 ret = btrfs_next_leaf(root, path);
1131 leaf = path->nodes[0];
1132 nritems = btrfs_header_nritems(leaf);
1136 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1137 if (key.objectid != bytenr ||
1138 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1141 ref = btrfs_item_ptr(leaf, path->slots[0],
1142 struct btrfs_extent_data_ref);
1144 if (match_extent_data_ref(leaf, ref, root_objectid,
1147 btrfs_release_path(path);
1159 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1160 struct btrfs_path *path,
1161 u64 bytenr, u64 parent,
1162 u64 root_objectid, u64 owner,
1163 u64 offset, int refs_to_add)
1165 struct btrfs_root *root = trans->fs_info->extent_root;
1166 struct btrfs_key key;
1167 struct extent_buffer *leaf;
1172 key.objectid = bytenr;
1174 key.type = BTRFS_SHARED_DATA_REF_KEY;
1175 key.offset = parent;
1176 size = sizeof(struct btrfs_shared_data_ref);
1178 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1179 key.offset = hash_extent_data_ref(root_objectid,
1181 size = sizeof(struct btrfs_extent_data_ref);
1184 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1185 if (ret && ret != -EEXIST)
1188 leaf = path->nodes[0];
1190 struct btrfs_shared_data_ref *ref;
1191 ref = btrfs_item_ptr(leaf, path->slots[0],
1192 struct btrfs_shared_data_ref);
1194 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1196 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1197 num_refs += refs_to_add;
1198 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1201 struct btrfs_extent_data_ref *ref;
1202 while (ret == -EEXIST) {
1203 ref = btrfs_item_ptr(leaf, path->slots[0],
1204 struct btrfs_extent_data_ref);
1205 if (match_extent_data_ref(leaf, ref, root_objectid,
1208 btrfs_release_path(path);
1210 ret = btrfs_insert_empty_item(trans, root, path, &key,
1212 if (ret && ret != -EEXIST)
1215 leaf = path->nodes[0];
1217 ref = btrfs_item_ptr(leaf, path->slots[0],
1218 struct btrfs_extent_data_ref);
1220 btrfs_set_extent_data_ref_root(leaf, ref,
1222 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1223 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1224 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1226 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1227 num_refs += refs_to_add;
1228 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1231 btrfs_mark_buffer_dirty(leaf);
1234 btrfs_release_path(path);
1238 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1239 struct btrfs_path *path,
1240 int refs_to_drop, int *last_ref)
1242 struct btrfs_key key;
1243 struct btrfs_extent_data_ref *ref1 = NULL;
1244 struct btrfs_shared_data_ref *ref2 = NULL;
1245 struct extent_buffer *leaf;
1249 leaf = path->nodes[0];
1250 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1252 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1253 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1254 struct btrfs_extent_data_ref);
1255 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1256 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1257 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1258 struct btrfs_shared_data_ref);
1259 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1260 } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
1261 btrfs_print_v0_err(trans->fs_info);
1262 btrfs_abort_transaction(trans, -EINVAL);
1268 BUG_ON(num_refs < refs_to_drop);
1269 num_refs -= refs_to_drop;
1271 if (num_refs == 0) {
1272 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1275 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1276 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1277 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1278 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1279 btrfs_mark_buffer_dirty(leaf);
1284 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1285 struct btrfs_extent_inline_ref *iref)
1287 struct btrfs_key key;
1288 struct extent_buffer *leaf;
1289 struct btrfs_extent_data_ref *ref1;
1290 struct btrfs_shared_data_ref *ref2;
1294 leaf = path->nodes[0];
1295 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1297 BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
1300 * If type is invalid, we should have bailed out earlier than
1303 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
1304 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1305 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1306 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1307 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1309 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1310 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1312 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1313 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1314 struct btrfs_extent_data_ref);
1315 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1316 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1317 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1318 struct btrfs_shared_data_ref);
1319 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1326 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1327 struct btrfs_path *path,
1328 u64 bytenr, u64 parent,
1331 struct btrfs_root *root = trans->fs_info->extent_root;
1332 struct btrfs_key key;
1335 key.objectid = bytenr;
1337 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1338 key.offset = parent;
1340 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1341 key.offset = root_objectid;
1344 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1350 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1351 struct btrfs_path *path,
1352 u64 bytenr, u64 parent,
1355 struct btrfs_key key;
1358 key.objectid = bytenr;
1360 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1361 key.offset = parent;
1363 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1364 key.offset = root_objectid;
1367 ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
1369 btrfs_release_path(path);
1373 static inline int extent_ref_type(u64 parent, u64 owner)
1376 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1378 type = BTRFS_SHARED_BLOCK_REF_KEY;
1380 type = BTRFS_TREE_BLOCK_REF_KEY;
1383 type = BTRFS_SHARED_DATA_REF_KEY;
1385 type = BTRFS_EXTENT_DATA_REF_KEY;
1390 static int find_next_key(struct btrfs_path *path, int level,
1391 struct btrfs_key *key)
1394 for (; level < BTRFS_MAX_LEVEL; level++) {
1395 if (!path->nodes[level])
1397 if (path->slots[level] + 1 >=
1398 btrfs_header_nritems(path->nodes[level]))
1401 btrfs_item_key_to_cpu(path->nodes[level], key,
1402 path->slots[level] + 1);
1404 btrfs_node_key_to_cpu(path->nodes[level], key,
1405 path->slots[level] + 1);
1412 * look for inline back ref. if back ref is found, *ref_ret is set
1413 * to the address of inline back ref, and 0 is returned.
1415 * if back ref isn't found, *ref_ret is set to the address where it
1416 * should be inserted, and -ENOENT is returned.
1418 * if insert is true and there are too many inline back refs, the path
1419 * points to the extent item, and -EAGAIN is returned.
1421 * NOTE: inline back refs are ordered in the same way that back ref
1422 * items in the tree are ordered.
1424 static noinline_for_stack
1425 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1426 struct btrfs_path *path,
1427 struct btrfs_extent_inline_ref **ref_ret,
1428 u64 bytenr, u64 num_bytes,
1429 u64 parent, u64 root_objectid,
1430 u64 owner, u64 offset, int insert)
1432 struct btrfs_fs_info *fs_info = trans->fs_info;
1433 struct btrfs_root *root = fs_info->extent_root;
1434 struct btrfs_key key;
1435 struct extent_buffer *leaf;
1436 struct btrfs_extent_item *ei;
1437 struct btrfs_extent_inline_ref *iref;
1447 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1450 key.objectid = bytenr;
1451 key.type = BTRFS_EXTENT_ITEM_KEY;
1452 key.offset = num_bytes;
1454 want = extent_ref_type(parent, owner);
1456 extra_size = btrfs_extent_inline_ref_size(want);
1457 path->keep_locks = 1;
1462 * Owner is our level, so we can just add one to get the level for the
1463 * block we are interested in.
1465 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1466 key.type = BTRFS_METADATA_ITEM_KEY;
1471 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1478 * We may be a newly converted file system which still has the old fat
1479 * extent entries for metadata, so try and see if we have one of those.
1481 if (ret > 0 && skinny_metadata) {
1482 skinny_metadata = false;
1483 if (path->slots[0]) {
1485 btrfs_item_key_to_cpu(path->nodes[0], &key,
1487 if (key.objectid == bytenr &&
1488 key.type == BTRFS_EXTENT_ITEM_KEY &&
1489 key.offset == num_bytes)
1493 key.objectid = bytenr;
1494 key.type = BTRFS_EXTENT_ITEM_KEY;
1495 key.offset = num_bytes;
1496 btrfs_release_path(path);
1501 if (ret && !insert) {
1504 } else if (WARN_ON(ret)) {
1509 leaf = path->nodes[0];
1510 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1511 if (unlikely(item_size < sizeof(*ei))) {
1513 btrfs_print_v0_err(fs_info);
1514 btrfs_abort_transaction(trans, err);
1518 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1519 flags = btrfs_extent_flags(leaf, ei);
1521 ptr = (unsigned long)(ei + 1);
1522 end = (unsigned long)ei + item_size;
1524 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1525 ptr += sizeof(struct btrfs_tree_block_info);
1529 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
1530 needed = BTRFS_REF_TYPE_DATA;
1532 needed = BTRFS_REF_TYPE_BLOCK;
1540 iref = (struct btrfs_extent_inline_ref *)ptr;
1541 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
1542 if (type == BTRFS_REF_TYPE_INVALID) {
1550 ptr += btrfs_extent_inline_ref_size(type);
1554 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1555 struct btrfs_extent_data_ref *dref;
1556 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1557 if (match_extent_data_ref(leaf, dref, root_objectid,
1562 if (hash_extent_data_ref_item(leaf, dref) <
1563 hash_extent_data_ref(root_objectid, owner, offset))
1567 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1569 if (parent == ref_offset) {
1573 if (ref_offset < parent)
1576 if (root_objectid == ref_offset) {
1580 if (ref_offset < root_objectid)
1584 ptr += btrfs_extent_inline_ref_size(type);
1586 if (err == -ENOENT && insert) {
1587 if (item_size + extra_size >=
1588 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1593 * To add new inline back ref, we have to make sure
1594 * there is no corresponding back ref item.
1595 * For simplicity, we just do not add new inline back
1596 * ref if there is any kind of item for this block
1598 if (find_next_key(path, 0, &key) == 0 &&
1599 key.objectid == bytenr &&
1600 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1605 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1608 path->keep_locks = 0;
1609 btrfs_unlock_up_safe(path, 1);
1615 * helper to add new inline back ref
1617 static noinline_for_stack
1618 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1619 struct btrfs_path *path,
1620 struct btrfs_extent_inline_ref *iref,
1621 u64 parent, u64 root_objectid,
1622 u64 owner, u64 offset, int refs_to_add,
1623 struct btrfs_delayed_extent_op *extent_op)
1625 struct extent_buffer *leaf;
1626 struct btrfs_extent_item *ei;
1629 unsigned long item_offset;
1634 leaf = path->nodes[0];
1635 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1636 item_offset = (unsigned long)iref - (unsigned long)ei;
1638 type = extent_ref_type(parent, owner);
1639 size = btrfs_extent_inline_ref_size(type);
1641 btrfs_extend_item(path, size);
1643 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1644 refs = btrfs_extent_refs(leaf, ei);
1645 refs += refs_to_add;
1646 btrfs_set_extent_refs(leaf, ei, refs);
1648 __run_delayed_extent_op(extent_op, leaf, ei);
1650 ptr = (unsigned long)ei + item_offset;
1651 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1652 if (ptr < end - size)
1653 memmove_extent_buffer(leaf, ptr + size, ptr,
1656 iref = (struct btrfs_extent_inline_ref *)ptr;
1657 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1658 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1659 struct btrfs_extent_data_ref *dref;
1660 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1661 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1662 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1663 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1664 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1665 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1666 struct btrfs_shared_data_ref *sref;
1667 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1668 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1669 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1670 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1671 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1673 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1675 btrfs_mark_buffer_dirty(leaf);
1678 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1679 struct btrfs_path *path,
1680 struct btrfs_extent_inline_ref **ref_ret,
1681 u64 bytenr, u64 num_bytes, u64 parent,
1682 u64 root_objectid, u64 owner, u64 offset)
1686 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1687 num_bytes, parent, root_objectid,
1692 btrfs_release_path(path);
1695 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1696 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1699 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1700 root_objectid, owner, offset);
1706 * helper to update/remove inline back ref
1708 static noinline_for_stack
1709 void update_inline_extent_backref(struct btrfs_path *path,
1710 struct btrfs_extent_inline_ref *iref,
1712 struct btrfs_delayed_extent_op *extent_op,
1715 struct extent_buffer *leaf = path->nodes[0];
1716 struct btrfs_extent_item *ei;
1717 struct btrfs_extent_data_ref *dref = NULL;
1718 struct btrfs_shared_data_ref *sref = NULL;
1726 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1727 refs = btrfs_extent_refs(leaf, ei);
1728 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1729 refs += refs_to_mod;
1730 btrfs_set_extent_refs(leaf, ei, refs);
1732 __run_delayed_extent_op(extent_op, leaf, ei);
1735 * If type is invalid, we should have bailed out after
1736 * lookup_inline_extent_backref().
1738 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1739 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1741 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1742 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1743 refs = btrfs_extent_data_ref_count(leaf, dref);
1744 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1745 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1746 refs = btrfs_shared_data_ref_count(leaf, sref);
1749 BUG_ON(refs_to_mod != -1);
1752 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1753 refs += refs_to_mod;
1756 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1757 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1759 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1762 size = btrfs_extent_inline_ref_size(type);
1763 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1764 ptr = (unsigned long)iref;
1765 end = (unsigned long)ei + item_size;
1766 if (ptr + size < end)
1767 memmove_extent_buffer(leaf, ptr, ptr + size,
1770 btrfs_truncate_item(path, item_size, 1);
1772 btrfs_mark_buffer_dirty(leaf);
1775 static noinline_for_stack
1776 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1777 struct btrfs_path *path,
1778 u64 bytenr, u64 num_bytes, u64 parent,
1779 u64 root_objectid, u64 owner,
1780 u64 offset, int refs_to_add,
1781 struct btrfs_delayed_extent_op *extent_op)
1783 struct btrfs_extent_inline_ref *iref;
1786 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1787 num_bytes, parent, root_objectid,
1790 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1791 update_inline_extent_backref(path, iref, refs_to_add,
1793 } else if (ret == -ENOENT) {
1794 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1795 root_objectid, owner, offset,
1796 refs_to_add, extent_op);
1802 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1803 struct btrfs_path *path,
1804 u64 bytenr, u64 parent, u64 root_objectid,
1805 u64 owner, u64 offset, int refs_to_add)
1808 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1809 BUG_ON(refs_to_add != 1);
1810 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1813 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1814 root_objectid, owner, offset,
1820 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1821 struct btrfs_path *path,
1822 struct btrfs_extent_inline_ref *iref,
1823 int refs_to_drop, int is_data, int *last_ref)
1827 BUG_ON(!is_data && refs_to_drop != 1);
1829 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1831 } else if (is_data) {
1832 ret = remove_extent_data_ref(trans, path, refs_to_drop,
1836 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1841 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1842 u64 *discarded_bytes)
1845 u64 bytes_left, end;
1846 u64 aligned_start = ALIGN(start, 1 << 9);
1848 if (WARN_ON(start != aligned_start)) {
1849 len -= aligned_start - start;
1850 len = round_down(len, 1 << 9);
1851 start = aligned_start;
1854 *discarded_bytes = 0;
1862 /* Skip any superblocks on this device. */
1863 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1864 u64 sb_start = btrfs_sb_offset(j);
1865 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1866 u64 size = sb_start - start;
1868 if (!in_range(sb_start, start, bytes_left) &&
1869 !in_range(sb_end, start, bytes_left) &&
1870 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1874 * Superblock spans beginning of range. Adjust start and
1877 if (sb_start <= start) {
1878 start += sb_end - start;
1883 bytes_left = end - start;
1888 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1891 *discarded_bytes += size;
1892 else if (ret != -EOPNOTSUPP)
1901 bytes_left = end - start;
1905 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1908 *discarded_bytes += bytes_left;
1913 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1914 u64 num_bytes, u64 *actual_bytes)
1917 u64 discarded_bytes = 0;
1918 struct btrfs_bio *bbio = NULL;
1922 * Avoid races with device replace and make sure our bbio has devices
1923 * associated to its stripes that don't go away while we are discarding.
1925 btrfs_bio_counter_inc_blocked(fs_info);
1926 /* Tell the block device(s) that the sectors can be discarded */
1927 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
1929 /* Error condition is -ENOMEM */
1931 struct btrfs_bio_stripe *stripe = bbio->stripes;
1935 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
1937 struct request_queue *req_q;
1939 if (!stripe->dev->bdev) {
1940 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1943 req_q = bdev_get_queue(stripe->dev->bdev);
1944 if (!blk_queue_discard(req_q))
1947 ret = btrfs_issue_discard(stripe->dev->bdev,
1952 discarded_bytes += bytes;
1953 else if (ret != -EOPNOTSUPP)
1954 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
1957 * Just in case we get back EOPNOTSUPP for some reason,
1958 * just ignore the return value so we don't screw up
1959 * people calling discard_extent.
1963 btrfs_put_bbio(bbio);
1965 btrfs_bio_counter_dec(fs_info);
1968 *actual_bytes = discarded_bytes;
1971 if (ret == -EOPNOTSUPP)
1976 /* Can return -ENOMEM */
1977 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1978 struct btrfs_ref *generic_ref)
1980 struct btrfs_fs_info *fs_info = trans->fs_info;
1981 int old_ref_mod, new_ref_mod;
1984 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
1985 generic_ref->action);
1986 BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
1987 generic_ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID);
1989 if (generic_ref->type == BTRFS_REF_METADATA)
1990 ret = btrfs_add_delayed_tree_ref(trans, generic_ref,
1991 NULL, &old_ref_mod, &new_ref_mod);
1993 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0,
1994 &old_ref_mod, &new_ref_mod);
1996 btrfs_ref_tree_mod(fs_info, generic_ref);
1998 if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0)
1999 sub_pinned_bytes(fs_info, generic_ref);
2005 * __btrfs_inc_extent_ref - insert backreference for a given extent
2007 * @trans: Handle of transaction
2009 * @node: The delayed ref node used to get the bytenr/length for
2010 * extent whose references are incremented.
2012 * @parent: If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
2013 * BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
2014 * bytenr of the parent block. Since new extents are always
2015 * created with indirect references, this will only be the case
2016 * when relocating a shared extent. In that case, root_objectid
2017 * will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
2020 * @root_objectid: The id of the root where this modification has originated,
2021 * this can be either one of the well-known metadata trees or
2022 * the subvolume id which references this extent.
2024 * @owner: For data extents it is the inode number of the owning file.
2025 * For metadata extents this parameter holds the level in the
2026 * tree of the extent.
2028 * @offset: For metadata extents the offset is ignored and is currently
2029 * always passed as 0. For data extents it is the fileoffset
2030 * this extent belongs to.
2032 * @refs_to_add Number of references to add
2034 * @extent_op Pointer to a structure, holding information necessary when
2035 * updating a tree block's flags
2038 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2039 struct btrfs_delayed_ref_node *node,
2040 u64 parent, u64 root_objectid,
2041 u64 owner, u64 offset, int refs_to_add,
2042 struct btrfs_delayed_extent_op *extent_op)
2044 struct btrfs_path *path;
2045 struct extent_buffer *leaf;
2046 struct btrfs_extent_item *item;
2047 struct btrfs_key key;
2048 u64 bytenr = node->bytenr;
2049 u64 num_bytes = node->num_bytes;
2053 path = btrfs_alloc_path();
2057 path->reada = READA_FORWARD;
2058 path->leave_spinning = 1;
2059 /* this will setup the path even if it fails to insert the back ref */
2060 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
2061 parent, root_objectid, owner,
2062 offset, refs_to_add, extent_op);
2063 if ((ret < 0 && ret != -EAGAIN) || !ret)
2067 * Ok we had -EAGAIN which means we didn't have space to insert and
2068 * inline extent ref, so just update the reference count and add a
2071 leaf = path->nodes[0];
2072 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2073 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2074 refs = btrfs_extent_refs(leaf, item);
2075 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2077 __run_delayed_extent_op(extent_op, leaf, item);
2079 btrfs_mark_buffer_dirty(leaf);
2080 btrfs_release_path(path);
2082 path->reada = READA_FORWARD;
2083 path->leave_spinning = 1;
2084 /* now insert the actual backref */
2085 ret = insert_extent_backref(trans, path, bytenr, parent, root_objectid,
2086 owner, offset, refs_to_add);
2088 btrfs_abort_transaction(trans, ret);
2090 btrfs_free_path(path);
2094 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2095 struct btrfs_delayed_ref_node *node,
2096 struct btrfs_delayed_extent_op *extent_op,
2097 int insert_reserved)
2100 struct btrfs_delayed_data_ref *ref;
2101 struct btrfs_key ins;
2106 ins.objectid = node->bytenr;
2107 ins.offset = node->num_bytes;
2108 ins.type = BTRFS_EXTENT_ITEM_KEY;
2110 ref = btrfs_delayed_node_to_data_ref(node);
2111 trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
2113 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2114 parent = ref->parent;
2115 ref_root = ref->root;
2117 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2119 flags |= extent_op->flags_to_set;
2120 ret = alloc_reserved_file_extent(trans, parent, ref_root,
2121 flags, ref->objectid,
2124 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2125 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2126 ref->objectid, ref->offset,
2127 node->ref_mod, extent_op);
2128 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2129 ret = __btrfs_free_extent(trans, node, parent,
2130 ref_root, ref->objectid,
2131 ref->offset, node->ref_mod,
2139 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2140 struct extent_buffer *leaf,
2141 struct btrfs_extent_item *ei)
2143 u64 flags = btrfs_extent_flags(leaf, ei);
2144 if (extent_op->update_flags) {
2145 flags |= extent_op->flags_to_set;
2146 btrfs_set_extent_flags(leaf, ei, flags);
2149 if (extent_op->update_key) {
2150 struct btrfs_tree_block_info *bi;
2151 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2152 bi = (struct btrfs_tree_block_info *)(ei + 1);
2153 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2157 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2158 struct btrfs_delayed_ref_head *head,
2159 struct btrfs_delayed_extent_op *extent_op)
2161 struct btrfs_fs_info *fs_info = trans->fs_info;
2162 struct btrfs_key key;
2163 struct btrfs_path *path;
2164 struct btrfs_extent_item *ei;
2165 struct extent_buffer *leaf;
2169 int metadata = !extent_op->is_data;
2174 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2177 path = btrfs_alloc_path();
2181 key.objectid = head->bytenr;
2184 key.type = BTRFS_METADATA_ITEM_KEY;
2185 key.offset = extent_op->level;
2187 key.type = BTRFS_EXTENT_ITEM_KEY;
2188 key.offset = head->num_bytes;
2192 path->reada = READA_FORWARD;
2193 path->leave_spinning = 1;
2194 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2201 if (path->slots[0] > 0) {
2203 btrfs_item_key_to_cpu(path->nodes[0], &key,
2205 if (key.objectid == head->bytenr &&
2206 key.type == BTRFS_EXTENT_ITEM_KEY &&
2207 key.offset == head->num_bytes)
2211 btrfs_release_path(path);
2214 key.objectid = head->bytenr;
2215 key.offset = head->num_bytes;
2216 key.type = BTRFS_EXTENT_ITEM_KEY;
2225 leaf = path->nodes[0];
2226 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2228 if (unlikely(item_size < sizeof(*ei))) {
2230 btrfs_print_v0_err(fs_info);
2231 btrfs_abort_transaction(trans, err);
2235 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2236 __run_delayed_extent_op(extent_op, leaf, ei);
2238 btrfs_mark_buffer_dirty(leaf);
2240 btrfs_free_path(path);
2244 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2245 struct btrfs_delayed_ref_node *node,
2246 struct btrfs_delayed_extent_op *extent_op,
2247 int insert_reserved)
2250 struct btrfs_delayed_tree_ref *ref;
2254 ref = btrfs_delayed_node_to_tree_ref(node);
2255 trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
2257 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2258 parent = ref->parent;
2259 ref_root = ref->root;
2261 if (node->ref_mod != 1) {
2262 btrfs_err(trans->fs_info,
2263 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2264 node->bytenr, node->ref_mod, node->action, ref_root,
2268 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2269 BUG_ON(!extent_op || !extent_op->update_flags);
2270 ret = alloc_reserved_tree_block(trans, node, extent_op);
2271 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2272 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2273 ref->level, 0, 1, extent_op);
2274 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2275 ret = __btrfs_free_extent(trans, node, parent, ref_root,
2276 ref->level, 0, 1, extent_op);
2283 /* helper function to actually process a single delayed ref entry */
2284 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2285 struct btrfs_delayed_ref_node *node,
2286 struct btrfs_delayed_extent_op *extent_op,
2287 int insert_reserved)
2291 if (trans->aborted) {
2292 if (insert_reserved)
2293 btrfs_pin_extent(trans->fs_info, node->bytenr,
2294 node->num_bytes, 1);
2298 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2299 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2300 ret = run_delayed_tree_ref(trans, node, extent_op,
2302 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2303 node->type == BTRFS_SHARED_DATA_REF_KEY)
2304 ret = run_delayed_data_ref(trans, node, extent_op,
2308 if (ret && insert_reserved)
2309 btrfs_pin_extent(trans->fs_info, node->bytenr,
2310 node->num_bytes, 1);
2314 static inline struct btrfs_delayed_ref_node *
2315 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2317 struct btrfs_delayed_ref_node *ref;
2319 if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
2323 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2324 * This is to prevent a ref count from going down to zero, which deletes
2325 * the extent item from the extent tree, when there still are references
2326 * to add, which would fail because they would not find the extent item.
2328 if (!list_empty(&head->ref_add_list))
2329 return list_first_entry(&head->ref_add_list,
2330 struct btrfs_delayed_ref_node, add_list);
2332 ref = rb_entry(rb_first_cached(&head->ref_tree),
2333 struct btrfs_delayed_ref_node, ref_node);
2334 ASSERT(list_empty(&ref->add_list));
2338 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
2339 struct btrfs_delayed_ref_head *head)
2341 spin_lock(&delayed_refs->lock);
2342 head->processing = 0;
2343 delayed_refs->num_heads_ready++;
2344 spin_unlock(&delayed_refs->lock);
2345 btrfs_delayed_ref_unlock(head);
2348 static struct btrfs_delayed_extent_op *cleanup_extent_op(
2349 struct btrfs_delayed_ref_head *head)
2351 struct btrfs_delayed_extent_op *extent_op = head->extent_op;
2356 if (head->must_insert_reserved) {
2357 head->extent_op = NULL;
2358 btrfs_free_delayed_extent_op(extent_op);
2364 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
2365 struct btrfs_delayed_ref_head *head)
2367 struct btrfs_delayed_extent_op *extent_op;
2370 extent_op = cleanup_extent_op(head);
2373 head->extent_op = NULL;
2374 spin_unlock(&head->lock);
2375 ret = run_delayed_extent_op(trans, head, extent_op);
2376 btrfs_free_delayed_extent_op(extent_op);
2377 return ret ? ret : 1;
2380 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
2381 struct btrfs_delayed_ref_root *delayed_refs,
2382 struct btrfs_delayed_ref_head *head)
2384 int nr_items = 1; /* Dropping this ref head update. */
2386 if (head->total_ref_mod < 0) {
2387 struct btrfs_space_info *space_info;
2391 flags = BTRFS_BLOCK_GROUP_DATA;
2392 else if (head->is_system)
2393 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2395 flags = BTRFS_BLOCK_GROUP_METADATA;
2396 space_info = btrfs_find_space_info(fs_info, flags);
2398 percpu_counter_add_batch(&space_info->total_bytes_pinned,
2400 BTRFS_TOTAL_BYTES_PINNED_BATCH);
2403 * We had csum deletions accounted for in our delayed refs rsv,
2404 * we need to drop the csum leaves for this update from our
2407 if (head->is_data) {
2408 spin_lock(&delayed_refs->lock);
2409 delayed_refs->pending_csums -= head->num_bytes;
2410 spin_unlock(&delayed_refs->lock);
2411 nr_items += btrfs_csum_bytes_to_leaves(fs_info,
2416 btrfs_delayed_refs_rsv_release(fs_info, nr_items);
2419 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
2420 struct btrfs_delayed_ref_head *head)
2423 struct btrfs_fs_info *fs_info = trans->fs_info;
2424 struct btrfs_delayed_ref_root *delayed_refs;
2427 delayed_refs = &trans->transaction->delayed_refs;
2429 ret = run_and_cleanup_extent_op(trans, head);
2431 unselect_delayed_ref_head(delayed_refs, head);
2432 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
2439 * Need to drop our head ref lock and re-acquire the delayed ref lock
2440 * and then re-check to make sure nobody got added.
2442 spin_unlock(&head->lock);
2443 spin_lock(&delayed_refs->lock);
2444 spin_lock(&head->lock);
2445 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
2446 spin_unlock(&head->lock);
2447 spin_unlock(&delayed_refs->lock);
2450 btrfs_delete_ref_head(delayed_refs, head);
2451 spin_unlock(&head->lock);
2452 spin_unlock(&delayed_refs->lock);
2454 if (head->must_insert_reserved) {
2455 btrfs_pin_extent(fs_info, head->bytenr,
2456 head->num_bytes, 1);
2457 if (head->is_data) {
2458 ret = btrfs_del_csums(trans, fs_info, head->bytenr,
2463 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
2465 trace_run_delayed_ref_head(fs_info, head, 0);
2466 btrfs_delayed_ref_unlock(head);
2467 btrfs_put_delayed_ref_head(head);
2471 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
2472 struct btrfs_trans_handle *trans)
2474 struct btrfs_delayed_ref_root *delayed_refs =
2475 &trans->transaction->delayed_refs;
2476 struct btrfs_delayed_ref_head *head = NULL;
2479 spin_lock(&delayed_refs->lock);
2480 head = btrfs_select_ref_head(delayed_refs);
2482 spin_unlock(&delayed_refs->lock);
2487 * Grab the lock that says we are going to process all the refs for
2490 ret = btrfs_delayed_ref_lock(delayed_refs, head);
2491 spin_unlock(&delayed_refs->lock);
2494 * We may have dropped the spin lock to get the head mutex lock, and
2495 * that might have given someone else time to free the head. If that's
2496 * true, it has been removed from our list and we can move on.
2499 head = ERR_PTR(-EAGAIN);
2504 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
2505 struct btrfs_delayed_ref_head *locked_ref,
2506 unsigned long *run_refs)
2508 struct btrfs_fs_info *fs_info = trans->fs_info;
2509 struct btrfs_delayed_ref_root *delayed_refs;
2510 struct btrfs_delayed_extent_op *extent_op;
2511 struct btrfs_delayed_ref_node *ref;
2512 int must_insert_reserved = 0;
2515 delayed_refs = &trans->transaction->delayed_refs;
2517 lockdep_assert_held(&locked_ref->mutex);
2518 lockdep_assert_held(&locked_ref->lock);
2520 while ((ref = select_delayed_ref(locked_ref))) {
2522 btrfs_check_delayed_seq(fs_info, ref->seq)) {
2523 spin_unlock(&locked_ref->lock);
2524 unselect_delayed_ref_head(delayed_refs, locked_ref);
2530 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
2531 RB_CLEAR_NODE(&ref->ref_node);
2532 if (!list_empty(&ref->add_list))
2533 list_del(&ref->add_list);
2535 * When we play the delayed ref, also correct the ref_mod on
2538 switch (ref->action) {
2539 case BTRFS_ADD_DELAYED_REF:
2540 case BTRFS_ADD_DELAYED_EXTENT:
2541 locked_ref->ref_mod -= ref->ref_mod;
2543 case BTRFS_DROP_DELAYED_REF:
2544 locked_ref->ref_mod += ref->ref_mod;
2549 atomic_dec(&delayed_refs->num_entries);
2552 * Record the must_insert_reserved flag before we drop the
2555 must_insert_reserved = locked_ref->must_insert_reserved;
2556 locked_ref->must_insert_reserved = 0;
2558 extent_op = locked_ref->extent_op;
2559 locked_ref->extent_op = NULL;
2560 spin_unlock(&locked_ref->lock);
2562 ret = run_one_delayed_ref(trans, ref, extent_op,
2563 must_insert_reserved);
2565 btrfs_free_delayed_extent_op(extent_op);
2567 unselect_delayed_ref_head(delayed_refs, locked_ref);
2568 btrfs_put_delayed_ref(ref);
2569 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2574 btrfs_put_delayed_ref(ref);
2577 spin_lock(&locked_ref->lock);
2578 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2585 * Returns 0 on success or if called with an already aborted transaction.
2586 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2588 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2591 struct btrfs_fs_info *fs_info = trans->fs_info;
2592 struct btrfs_delayed_ref_root *delayed_refs;
2593 struct btrfs_delayed_ref_head *locked_ref = NULL;
2594 ktime_t start = ktime_get();
2596 unsigned long count = 0;
2597 unsigned long actual_count = 0;
2599 delayed_refs = &trans->transaction->delayed_refs;
2602 locked_ref = btrfs_obtain_ref_head(trans);
2603 if (IS_ERR_OR_NULL(locked_ref)) {
2604 if (PTR_ERR(locked_ref) == -EAGAIN) {
2613 * We need to try and merge add/drops of the same ref since we
2614 * can run into issues with relocate dropping the implicit ref
2615 * and then it being added back again before the drop can
2616 * finish. If we merged anything we need to re-loop so we can
2618 * Or we can get node references of the same type that weren't
2619 * merged when created due to bumps in the tree mod seq, and
2620 * we need to merge them to prevent adding an inline extent
2621 * backref before dropping it (triggering a BUG_ON at
2622 * insert_inline_extent_backref()).
2624 spin_lock(&locked_ref->lock);
2625 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2627 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2629 if (ret < 0 && ret != -EAGAIN) {
2631 * Error, btrfs_run_delayed_refs_for_head already
2632 * unlocked everything so just bail out
2637 * Success, perform the usual cleanup of a processed
2640 ret = cleanup_ref_head(trans, locked_ref);
2642 /* We dropped our lock, we need to loop. */
2651 * Either success case or btrfs_run_delayed_refs_for_head
2652 * returned -EAGAIN, meaning we need to select another head
2657 } while ((nr != -1 && count < nr) || locked_ref);
2660 * We don't want to include ref heads since we can have empty ref heads
2661 * and those will drastically skew our runtime down since we just do
2662 * accounting, no actual extent tree updates.
2664 if (actual_count > 0) {
2665 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2669 * We weigh the current average higher than our current runtime
2670 * to avoid large swings in the average.
2672 spin_lock(&delayed_refs->lock);
2673 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2674 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2675 spin_unlock(&delayed_refs->lock);
2680 #ifdef SCRAMBLE_DELAYED_REFS
2682 * Normally delayed refs get processed in ascending bytenr order. This
2683 * correlates in most cases to the order added. To expose dependencies on this
2684 * order, we start to process the tree in the middle instead of the beginning
2686 static u64 find_middle(struct rb_root *root)
2688 struct rb_node *n = root->rb_node;
2689 struct btrfs_delayed_ref_node *entry;
2692 u64 first = 0, last = 0;
2696 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2697 first = entry->bytenr;
2701 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2702 last = entry->bytenr;
2707 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2708 WARN_ON(!entry->in_tree);
2710 middle = entry->bytenr;
2723 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2727 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2728 sizeof(struct btrfs_extent_inline_ref));
2729 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2730 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2733 * We don't ever fill up leaves all the way so multiply by 2 just to be
2734 * closer to what we're really going to want to use.
2736 return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2740 * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2741 * would require to store the csums for that many bytes.
2743 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2746 u64 num_csums_per_leaf;
2749 csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2750 num_csums_per_leaf = div64_u64(csum_size,
2751 (u64)btrfs_super_csum_size(fs_info->super_copy));
2752 num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2753 num_csums += num_csums_per_leaf - 1;
2754 num_csums = div64_u64(num_csums, num_csums_per_leaf);
2759 * this starts processing the delayed reference count updates and
2760 * extent insertions we have queued up so far. count can be
2761 * 0, which means to process everything in the tree at the start
2762 * of the run (but not newly added entries), or it can be some target
2763 * number you'd like to process.
2765 * Returns 0 on success or if called with an aborted transaction
2766 * Returns <0 on error and aborts the transaction
2768 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2769 unsigned long count)
2771 struct btrfs_fs_info *fs_info = trans->fs_info;
2772 struct rb_node *node;
2773 struct btrfs_delayed_ref_root *delayed_refs;
2774 struct btrfs_delayed_ref_head *head;
2776 int run_all = count == (unsigned long)-1;
2778 /* We'll clean this up in btrfs_cleanup_transaction */
2782 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2785 delayed_refs = &trans->transaction->delayed_refs;
2787 count = atomic_read(&delayed_refs->num_entries) * 2;
2790 #ifdef SCRAMBLE_DELAYED_REFS
2791 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2793 ret = __btrfs_run_delayed_refs(trans, count);
2795 btrfs_abort_transaction(trans, ret);
2800 btrfs_create_pending_block_groups(trans);
2802 spin_lock(&delayed_refs->lock);
2803 node = rb_first_cached(&delayed_refs->href_root);
2805 spin_unlock(&delayed_refs->lock);
2808 head = rb_entry(node, struct btrfs_delayed_ref_head,
2810 refcount_inc(&head->refs);
2811 spin_unlock(&delayed_refs->lock);
2813 /* Mutex was contended, block until it's released and retry. */
2814 mutex_lock(&head->mutex);
2815 mutex_unlock(&head->mutex);
2817 btrfs_put_delayed_ref_head(head);
2825 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2826 u64 bytenr, u64 num_bytes, u64 flags,
2827 int level, int is_data)
2829 struct btrfs_delayed_extent_op *extent_op;
2832 extent_op = btrfs_alloc_delayed_extent_op();
2836 extent_op->flags_to_set = flags;
2837 extent_op->update_flags = true;
2838 extent_op->update_key = false;
2839 extent_op->is_data = is_data ? true : false;
2840 extent_op->level = level;
2842 ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2844 btrfs_free_delayed_extent_op(extent_op);
2848 static noinline int check_delayed_ref(struct btrfs_root *root,
2849 struct btrfs_path *path,
2850 u64 objectid, u64 offset, u64 bytenr)
2852 struct btrfs_delayed_ref_head *head;
2853 struct btrfs_delayed_ref_node *ref;
2854 struct btrfs_delayed_data_ref *data_ref;
2855 struct btrfs_delayed_ref_root *delayed_refs;
2856 struct btrfs_transaction *cur_trans;
2857 struct rb_node *node;
2860 spin_lock(&root->fs_info->trans_lock);
2861 cur_trans = root->fs_info->running_transaction;
2863 refcount_inc(&cur_trans->use_count);
2864 spin_unlock(&root->fs_info->trans_lock);
2868 delayed_refs = &cur_trans->delayed_refs;
2869 spin_lock(&delayed_refs->lock);
2870 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2872 spin_unlock(&delayed_refs->lock);
2873 btrfs_put_transaction(cur_trans);
2877 if (!mutex_trylock(&head->mutex)) {
2878 refcount_inc(&head->refs);
2879 spin_unlock(&delayed_refs->lock);
2881 btrfs_release_path(path);
2884 * Mutex was contended, block until it's released and let
2887 mutex_lock(&head->mutex);
2888 mutex_unlock(&head->mutex);
2889 btrfs_put_delayed_ref_head(head);
2890 btrfs_put_transaction(cur_trans);
2893 spin_unlock(&delayed_refs->lock);
2895 spin_lock(&head->lock);
2897 * XXX: We should replace this with a proper search function in the
2900 for (node = rb_first_cached(&head->ref_tree); node;
2901 node = rb_next(node)) {
2902 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
2903 /* If it's a shared ref we know a cross reference exists */
2904 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2909 data_ref = btrfs_delayed_node_to_data_ref(ref);
2912 * If our ref doesn't match the one we're currently looking at
2913 * then we have a cross reference.
2915 if (data_ref->root != root->root_key.objectid ||
2916 data_ref->objectid != objectid ||
2917 data_ref->offset != offset) {
2922 spin_unlock(&head->lock);
2923 mutex_unlock(&head->mutex);
2924 btrfs_put_transaction(cur_trans);
2928 static noinline int check_committed_ref(struct btrfs_root *root,
2929 struct btrfs_path *path,
2930 u64 objectid, u64 offset, u64 bytenr)
2932 struct btrfs_fs_info *fs_info = root->fs_info;
2933 struct btrfs_root *extent_root = fs_info->extent_root;
2934 struct extent_buffer *leaf;
2935 struct btrfs_extent_data_ref *ref;
2936 struct btrfs_extent_inline_ref *iref;
2937 struct btrfs_extent_item *ei;
2938 struct btrfs_key key;
2943 key.objectid = bytenr;
2944 key.offset = (u64)-1;
2945 key.type = BTRFS_EXTENT_ITEM_KEY;
2947 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2950 BUG_ON(ret == 0); /* Corruption */
2953 if (path->slots[0] == 0)
2957 leaf = path->nodes[0];
2958 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2960 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2964 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2965 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2967 if (item_size != sizeof(*ei) +
2968 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2971 if (btrfs_extent_generation(leaf, ei) <=
2972 btrfs_root_last_snapshot(&root->root_item))
2975 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2977 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
2978 if (type != BTRFS_EXTENT_DATA_REF_KEY)
2981 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2982 if (btrfs_extent_refs(leaf, ei) !=
2983 btrfs_extent_data_ref_count(leaf, ref) ||
2984 btrfs_extent_data_ref_root(leaf, ref) !=
2985 root->root_key.objectid ||
2986 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2987 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2995 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
2998 struct btrfs_path *path;
3001 path = btrfs_alloc_path();
3006 ret = check_committed_ref(root, path, objectid,
3008 if (ret && ret != -ENOENT)
3011 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
3012 } while (ret == -EAGAIN);
3015 btrfs_free_path(path);
3016 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3021 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
3022 struct btrfs_root *root,
3023 struct extent_buffer *buf,
3024 int full_backref, int inc)
3026 struct btrfs_fs_info *fs_info = root->fs_info;
3032 struct btrfs_key key;
3033 struct btrfs_file_extent_item *fi;
3034 struct btrfs_ref generic_ref = { 0 };
3035 bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
3041 if (btrfs_is_testing(fs_info))
3044 ref_root = btrfs_header_owner(buf);
3045 nritems = btrfs_header_nritems(buf);
3046 level = btrfs_header_level(buf);
3048 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
3052 parent = buf->start;
3056 action = BTRFS_ADD_DELAYED_REF;
3058 action = BTRFS_DROP_DELAYED_REF;
3060 for (i = 0; i < nritems; i++) {
3062 btrfs_item_key_to_cpu(buf, &key, i);
3063 if (key.type != BTRFS_EXTENT_DATA_KEY)
3065 fi = btrfs_item_ptr(buf, i,
3066 struct btrfs_file_extent_item);
3067 if (btrfs_file_extent_type(buf, fi) ==
3068 BTRFS_FILE_EXTENT_INLINE)
3070 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3074 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3075 key.offset -= btrfs_file_extent_offset(buf, fi);
3076 btrfs_init_generic_ref(&generic_ref, action, bytenr,
3078 generic_ref.real_root = root->root_key.objectid;
3079 btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
3081 generic_ref.skip_qgroup = for_reloc;
3083 ret = btrfs_inc_extent_ref(trans, &generic_ref);
3085 ret = btrfs_free_extent(trans, &generic_ref);
3089 bytenr = btrfs_node_blockptr(buf, i);
3090 num_bytes = fs_info->nodesize;
3091 btrfs_init_generic_ref(&generic_ref, action, bytenr,
3093 generic_ref.real_root = root->root_key.objectid;
3094 btrfs_init_tree_ref(&generic_ref, level - 1, ref_root);
3095 generic_ref.skip_qgroup = for_reloc;
3097 ret = btrfs_inc_extent_ref(trans, &generic_ref);
3099 ret = btrfs_free_extent(trans, &generic_ref);
3109 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3110 struct extent_buffer *buf, int full_backref)
3112 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
3115 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3116 struct extent_buffer *buf, int full_backref)
3118 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
3121 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3122 struct btrfs_path *path,
3123 struct btrfs_block_group_cache *cache)
3125 struct btrfs_fs_info *fs_info = trans->fs_info;
3127 struct btrfs_root *extent_root = fs_info->extent_root;
3129 struct extent_buffer *leaf;
3131 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3138 leaf = path->nodes[0];
3139 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3140 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3141 btrfs_mark_buffer_dirty(leaf);
3143 btrfs_release_path(path);
3148 static struct btrfs_block_group_cache *next_block_group(
3149 struct btrfs_block_group_cache *cache)
3151 struct btrfs_fs_info *fs_info = cache->fs_info;
3152 struct rb_node *node;
3154 spin_lock(&fs_info->block_group_cache_lock);
3156 /* If our block group was removed, we need a full search. */
3157 if (RB_EMPTY_NODE(&cache->cache_node)) {
3158 const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3160 spin_unlock(&fs_info->block_group_cache_lock);
3161 btrfs_put_block_group(cache);
3162 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
3164 node = rb_next(&cache->cache_node);
3165 btrfs_put_block_group(cache);
3167 cache = rb_entry(node, struct btrfs_block_group_cache,
3169 btrfs_get_block_group(cache);
3172 spin_unlock(&fs_info->block_group_cache_lock);
3176 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3177 struct btrfs_trans_handle *trans,
3178 struct btrfs_path *path)
3180 struct btrfs_fs_info *fs_info = block_group->fs_info;
3181 struct btrfs_root *root = fs_info->tree_root;
3182 struct inode *inode = NULL;
3183 struct extent_changeset *data_reserved = NULL;
3185 int dcs = BTRFS_DC_ERROR;
3191 * If this block group is smaller than 100 megs don't bother caching the
3194 if (block_group->key.offset < (100 * SZ_1M)) {
3195 spin_lock(&block_group->lock);
3196 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3197 spin_unlock(&block_group->lock);
3204 inode = lookup_free_space_inode(block_group, path);
3205 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3206 ret = PTR_ERR(inode);
3207 btrfs_release_path(path);
3211 if (IS_ERR(inode)) {
3215 if (block_group->ro)
3218 ret = create_free_space_inode(trans, block_group, path);
3225 * We want to set the generation to 0, that way if anything goes wrong
3226 * from here on out we know not to trust this cache when we load up next
3229 BTRFS_I(inode)->generation = 0;
3230 ret = btrfs_update_inode(trans, root, inode);
3233 * So theoretically we could recover from this, simply set the
3234 * super cache generation to 0 so we know to invalidate the
3235 * cache, but then we'd have to keep track of the block groups
3236 * that fail this way so we know we _have_ to reset this cache
3237 * before the next commit or risk reading stale cache. So to
3238 * limit our exposure to horrible edge cases lets just abort the
3239 * transaction, this only happens in really bad situations
3242 btrfs_abort_transaction(trans, ret);
3247 /* We've already setup this transaction, go ahead and exit */
3248 if (block_group->cache_generation == trans->transid &&
3249 i_size_read(inode)) {
3250 dcs = BTRFS_DC_SETUP;
3254 if (i_size_read(inode) > 0) {
3255 ret = btrfs_check_trunc_cache_free_space(fs_info,
3256 &fs_info->global_block_rsv);
3260 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
3265 spin_lock(&block_group->lock);
3266 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3267 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3269 * don't bother trying to write stuff out _if_
3270 * a) we're not cached,
3271 * b) we're with nospace_cache mount option,
3272 * c) we're with v2 space_cache (FREE_SPACE_TREE).
3274 dcs = BTRFS_DC_WRITTEN;
3275 spin_unlock(&block_group->lock);
3278 spin_unlock(&block_group->lock);
3281 * We hit an ENOSPC when setting up the cache in this transaction, just
3282 * skip doing the setup, we've already cleared the cache so we're safe.
3284 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3290 * Try to preallocate enough space based on how big the block group is.
3291 * Keep in mind this has to include any pinned space which could end up
3292 * taking up quite a bit since it's not folded into the other space
3295 num_pages = div_u64(block_group->key.offset, SZ_256M);
3300 num_pages *= PAGE_SIZE;
3302 ret = btrfs_check_data_free_space(inode, &data_reserved, 0, num_pages);
3306 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3307 num_pages, num_pages,
3310 * Our cache requires contiguous chunks so that we don't modify a bunch
3311 * of metadata or split extents when writing the cache out, which means
3312 * we can enospc if we are heavily fragmented in addition to just normal
3313 * out of space conditions. So if we hit this just skip setting up any
3314 * other block groups for this transaction, maybe we'll unpin enough
3315 * space the next time around.
3318 dcs = BTRFS_DC_SETUP;
3319 else if (ret == -ENOSPC)
3320 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3325 btrfs_release_path(path);
3327 spin_lock(&block_group->lock);
3328 if (!ret && dcs == BTRFS_DC_SETUP)
3329 block_group->cache_generation = trans->transid;
3330 block_group->disk_cache_state = dcs;
3331 spin_unlock(&block_group->lock);
3333 extent_changeset_free(data_reserved);
3337 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
3339 struct btrfs_fs_info *fs_info = trans->fs_info;
3340 struct btrfs_block_group_cache *cache, *tmp;
3341 struct btrfs_transaction *cur_trans = trans->transaction;
3342 struct btrfs_path *path;
3344 if (list_empty(&cur_trans->dirty_bgs) ||
3345 !btrfs_test_opt(fs_info, SPACE_CACHE))
3348 path = btrfs_alloc_path();
3352 /* Could add new block groups, use _safe just in case */
3353 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3355 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3356 cache_save_setup(cache, trans, path);
3359 btrfs_free_path(path);
3364 * transaction commit does final block group cache writeback during a
3365 * critical section where nothing is allowed to change the FS. This is
3366 * required in order for the cache to actually match the block group,
3367 * but can introduce a lot of latency into the commit.
3369 * So, btrfs_start_dirty_block_groups is here to kick off block group
3370 * cache IO. There's a chance we'll have to redo some of it if the
3371 * block group changes again during the commit, but it greatly reduces
3372 * the commit latency by getting rid of the easy block groups while
3373 * we're still allowing others to join the commit.
3375 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
3377 struct btrfs_fs_info *fs_info = trans->fs_info;
3378 struct btrfs_block_group_cache *cache;
3379 struct btrfs_transaction *cur_trans = trans->transaction;
3382 struct btrfs_path *path = NULL;
3384 struct list_head *io = &cur_trans->io_bgs;
3385 int num_started = 0;
3388 spin_lock(&cur_trans->dirty_bgs_lock);
3389 if (list_empty(&cur_trans->dirty_bgs)) {
3390 spin_unlock(&cur_trans->dirty_bgs_lock);
3393 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3394 spin_unlock(&cur_trans->dirty_bgs_lock);
3398 * make sure all the block groups on our dirty list actually
3401 btrfs_create_pending_block_groups(trans);
3404 path = btrfs_alloc_path();
3410 * cache_write_mutex is here only to save us from balance or automatic
3411 * removal of empty block groups deleting this block group while we are
3412 * writing out the cache
3414 mutex_lock(&trans->transaction->cache_write_mutex);
3415 while (!list_empty(&dirty)) {
3416 bool drop_reserve = true;
3418 cache = list_first_entry(&dirty,
3419 struct btrfs_block_group_cache,
3422 * this can happen if something re-dirties a block
3423 * group that is already under IO. Just wait for it to
3424 * finish and then do it all again
3426 if (!list_empty(&cache->io_list)) {
3427 list_del_init(&cache->io_list);
3428 btrfs_wait_cache_io(trans, cache, path);
3429 btrfs_put_block_group(cache);
3434 * btrfs_wait_cache_io uses the cache->dirty_list to decide
3435 * if it should update the cache_state. Don't delete
3436 * until after we wait.
3438 * Since we're not running in the commit critical section
3439 * we need the dirty_bgs_lock to protect from update_block_group
3441 spin_lock(&cur_trans->dirty_bgs_lock);
3442 list_del_init(&cache->dirty_list);
3443 spin_unlock(&cur_trans->dirty_bgs_lock);
3447 cache_save_setup(cache, trans, path);
3449 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3450 cache->io_ctl.inode = NULL;
3451 ret = btrfs_write_out_cache(trans, cache, path);
3452 if (ret == 0 && cache->io_ctl.inode) {
3457 * The cache_write_mutex is protecting the
3458 * io_list, also refer to the definition of
3459 * btrfs_transaction::io_bgs for more details
3461 list_add_tail(&cache->io_list, io);
3464 * if we failed to write the cache, the
3465 * generation will be bad and life goes on
3471 ret = write_one_cache_group(trans, path, cache);
3473 * Our block group might still be attached to the list
3474 * of new block groups in the transaction handle of some
3475 * other task (struct btrfs_trans_handle->new_bgs). This
3476 * means its block group item isn't yet in the extent
3477 * tree. If this happens ignore the error, as we will
3478 * try again later in the critical section of the
3479 * transaction commit.
3481 if (ret == -ENOENT) {
3483 spin_lock(&cur_trans->dirty_bgs_lock);
3484 if (list_empty(&cache->dirty_list)) {
3485 list_add_tail(&cache->dirty_list,
3486 &cur_trans->dirty_bgs);
3487 btrfs_get_block_group(cache);
3488 drop_reserve = false;
3490 spin_unlock(&cur_trans->dirty_bgs_lock);
3492 btrfs_abort_transaction(trans, ret);
3496 /* if it's not on the io list, we need to put the block group */
3498 btrfs_put_block_group(cache);
3500 btrfs_delayed_refs_rsv_release(fs_info, 1);
3506 * Avoid blocking other tasks for too long. It might even save
3507 * us from writing caches for block groups that are going to be
3510 mutex_unlock(&trans->transaction->cache_write_mutex);
3511 mutex_lock(&trans->transaction->cache_write_mutex);
3513 mutex_unlock(&trans->transaction->cache_write_mutex);
3516 * go through delayed refs for all the stuff we've just kicked off
3517 * and then loop back (just once)
3519 ret = btrfs_run_delayed_refs(trans, 0);
3520 if (!ret && loops == 0) {
3522 spin_lock(&cur_trans->dirty_bgs_lock);
3523 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3525 * dirty_bgs_lock protects us from concurrent block group
3526 * deletes too (not just cache_write_mutex).
3528 if (!list_empty(&dirty)) {
3529 spin_unlock(&cur_trans->dirty_bgs_lock);
3532 spin_unlock(&cur_trans->dirty_bgs_lock);
3533 } else if (ret < 0) {
3534 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3537 btrfs_free_path(path);
3541 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
3543 struct btrfs_fs_info *fs_info = trans->fs_info;
3544 struct btrfs_block_group_cache *cache;
3545 struct btrfs_transaction *cur_trans = trans->transaction;
3548 struct btrfs_path *path;
3549 struct list_head *io = &cur_trans->io_bgs;
3550 int num_started = 0;
3552 path = btrfs_alloc_path();
3557 * Even though we are in the critical section of the transaction commit,
3558 * we can still have concurrent tasks adding elements to this
3559 * transaction's list of dirty block groups. These tasks correspond to
3560 * endio free space workers started when writeback finishes for a
3561 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3562 * allocate new block groups as a result of COWing nodes of the root
3563 * tree when updating the free space inode. The writeback for the space
3564 * caches is triggered by an earlier call to
3565 * btrfs_start_dirty_block_groups() and iterations of the following
3567 * Also we want to do the cache_save_setup first and then run the
3568 * delayed refs to make sure we have the best chance at doing this all
3571 spin_lock(&cur_trans->dirty_bgs_lock);
3572 while (!list_empty(&cur_trans->dirty_bgs)) {
3573 cache = list_first_entry(&cur_trans->dirty_bgs,
3574 struct btrfs_block_group_cache,
3578 * this can happen if cache_save_setup re-dirties a block
3579 * group that is already under IO. Just wait for it to
3580 * finish and then do it all again
3582 if (!list_empty(&cache->io_list)) {
3583 spin_unlock(&cur_trans->dirty_bgs_lock);
3584 list_del_init(&cache->io_list);
3585 btrfs_wait_cache_io(trans, cache, path);
3586 btrfs_put_block_group(cache);
3587 spin_lock(&cur_trans->dirty_bgs_lock);
3591 * don't remove from the dirty list until after we've waited
3594 list_del_init(&cache->dirty_list);
3595 spin_unlock(&cur_trans->dirty_bgs_lock);
3598 cache_save_setup(cache, trans, path);
3601 ret = btrfs_run_delayed_refs(trans,
3602 (unsigned long) -1);
3604 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3605 cache->io_ctl.inode = NULL;
3606 ret = btrfs_write_out_cache(trans, cache, path);
3607 if (ret == 0 && cache->io_ctl.inode) {
3610 list_add_tail(&cache->io_list, io);
3613 * if we failed to write the cache, the
3614 * generation will be bad and life goes on
3620 ret = write_one_cache_group(trans, path, cache);
3622 * One of the free space endio workers might have
3623 * created a new block group while updating a free space
3624 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3625 * and hasn't released its transaction handle yet, in
3626 * which case the new block group is still attached to
3627 * its transaction handle and its creation has not
3628 * finished yet (no block group item in the extent tree
3629 * yet, etc). If this is the case, wait for all free
3630 * space endio workers to finish and retry. This is a
3631 * a very rare case so no need for a more efficient and
3634 if (ret == -ENOENT) {
3635 wait_event(cur_trans->writer_wait,
3636 atomic_read(&cur_trans->num_writers) == 1);
3637 ret = write_one_cache_group(trans, path, cache);
3640 btrfs_abort_transaction(trans, ret);
3643 /* if its not on the io list, we need to put the block group */
3645 btrfs_put_block_group(cache);
3646 btrfs_delayed_refs_rsv_release(fs_info, 1);
3647 spin_lock(&cur_trans->dirty_bgs_lock);
3649 spin_unlock(&cur_trans->dirty_bgs_lock);
3652 * Refer to the definition of io_bgs member for details why it's safe
3653 * to use it without any locking
3655 while (!list_empty(io)) {
3656 cache = list_first_entry(io, struct btrfs_block_group_cache,
3658 list_del_init(&cache->io_list);
3659 btrfs_wait_cache_io(trans, cache, path);
3660 btrfs_put_block_group(cache);
3663 btrfs_free_path(path);
3667 int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
3669 struct btrfs_block_group_cache *block_group;
3672 block_group = btrfs_lookup_block_group(fs_info, bytenr);
3673 if (!block_group || block_group->ro)
3676 btrfs_put_block_group(block_group);
3680 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3682 struct btrfs_block_group_cache *bg;
3685 bg = btrfs_lookup_block_group(fs_info, bytenr);
3689 spin_lock(&bg->lock);
3693 atomic_inc(&bg->nocow_writers);
3694 spin_unlock(&bg->lock);
3696 /* no put on block group, done by btrfs_dec_nocow_writers */
3698 btrfs_put_block_group(bg);
3704 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3706 struct btrfs_block_group_cache *bg;
3708 bg = btrfs_lookup_block_group(fs_info, bytenr);
3710 if (atomic_dec_and_test(&bg->nocow_writers))
3711 wake_up_var(&bg->nocow_writers);
3713 * Once for our lookup and once for the lookup done by a previous call
3714 * to btrfs_inc_nocow_writers()
3716 btrfs_put_block_group(bg);
3717 btrfs_put_block_group(bg);
3720 void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
3722 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
3725 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3727 u64 extra_flags = chunk_to_extended(flags) &
3728 BTRFS_EXTENDED_PROFILE_MASK;
3730 write_seqlock(&fs_info->profiles_lock);
3731 if (flags & BTRFS_BLOCK_GROUP_DATA)
3732 fs_info->avail_data_alloc_bits |= extra_flags;
3733 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3734 fs_info->avail_metadata_alloc_bits |= extra_flags;
3735 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3736 fs_info->avail_system_alloc_bits |= extra_flags;
3737 write_sequnlock(&fs_info->profiles_lock);
3741 * returns target flags in extended format or 0 if restripe for this
3742 * chunk_type is not in progress
3744 * should be called with balance_lock held
3746 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3748 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3754 if (flags & BTRFS_BLOCK_GROUP_DATA &&
3755 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3756 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3757 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3758 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3759 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3760 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3761 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3762 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3769 * @flags: available profiles in extended format (see ctree.h)
3771 * Returns reduced profile in chunk format. If profile changing is in
3772 * progress (either running or paused) picks the target profile (if it's
3773 * already available), otherwise falls back to plain reducing.
3775 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
3777 u64 num_devices = fs_info->fs_devices->rw_devices;
3783 * see if restripe for this chunk_type is in progress, if so
3784 * try to reduce to the target profile
3786 spin_lock(&fs_info->balance_lock);
3787 target = get_restripe_target(fs_info, flags);
3789 /* pick target profile only if it's already available */
3790 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
3791 spin_unlock(&fs_info->balance_lock);
3792 return extended_to_chunk(target);
3795 spin_unlock(&fs_info->balance_lock);
3797 /* First, mask out the RAID levels which aren't possible */
3798 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3799 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
3800 allowed |= btrfs_raid_array[raid_type].bg_flag;
3804 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
3805 allowed = BTRFS_BLOCK_GROUP_RAID6;
3806 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
3807 allowed = BTRFS_BLOCK_GROUP_RAID5;
3808 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
3809 allowed = BTRFS_BLOCK_GROUP_RAID10;
3810 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
3811 allowed = BTRFS_BLOCK_GROUP_RAID1;
3812 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
3813 allowed = BTRFS_BLOCK_GROUP_RAID0;
3815 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
3817 return extended_to_chunk(flags | allowed);
3820 static u64 get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
3827 seq = read_seqbegin(&fs_info->profiles_lock);
3829 if (flags & BTRFS_BLOCK_GROUP_DATA)
3830 flags |= fs_info->avail_data_alloc_bits;
3831 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3832 flags |= fs_info->avail_system_alloc_bits;
3833 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3834 flags |= fs_info->avail_metadata_alloc_bits;
3835 } while (read_seqretry(&fs_info->profiles_lock, seq));
3837 return btrfs_reduce_alloc_profile(fs_info, flags);
3840 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
3842 struct btrfs_fs_info *fs_info = root->fs_info;
3847 flags = BTRFS_BLOCK_GROUP_DATA;
3848 else if (root == fs_info->chunk_root)
3849 flags = BTRFS_BLOCK_GROUP_SYSTEM;
3851 flags = BTRFS_BLOCK_GROUP_METADATA;
3853 ret = get_alloc_profile(fs_info, flags);
3857 u64 btrfs_data_alloc_profile(struct btrfs_fs_info *fs_info)
3859 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_DATA);
3862 u64 btrfs_metadata_alloc_profile(struct btrfs_fs_info *fs_info)
3864 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_METADATA);
3867 u64 btrfs_system_alloc_profile(struct btrfs_fs_info *fs_info)
3869 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3872 static void force_metadata_allocation(struct btrfs_fs_info *info)
3874 struct list_head *head = &info->space_info;
3875 struct btrfs_space_info *found;
3878 list_for_each_entry_rcu(found, head, list) {
3879 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3880 found->force_alloc = CHUNK_ALLOC_FORCE;
3885 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3886 struct btrfs_space_info *sinfo, int force)
3888 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3891 if (force == CHUNK_ALLOC_FORCE)
3895 * in limited mode, we want to have some free space up to
3896 * about 1% of the FS size.
3898 if (force == CHUNK_ALLOC_LIMITED) {
3899 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3900 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3902 if (sinfo->total_bytes - bytes_used < thresh)
3906 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3911 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3915 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3917 num_dev = fs_info->fs_devices->rw_devices;
3923 * If @is_allocation is true, reserve space in the system space info necessary
3924 * for allocating a chunk, otherwise if it's false, reserve space necessary for
3927 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3929 struct btrfs_fs_info *fs_info = trans->fs_info;
3930 struct btrfs_space_info *info;
3937 * Needed because we can end up allocating a system chunk and for an
3938 * atomic and race free space reservation in the chunk block reserve.
3940 lockdep_assert_held(&fs_info->chunk_mutex);
3942 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3943 spin_lock(&info->lock);
3944 left = info->total_bytes - btrfs_space_info_used(info, true);
3945 spin_unlock(&info->lock);
3947 num_devs = get_profile_num_devs(fs_info, type);
3949 /* num_devs device items to update and 1 chunk item to add or remove */
3950 thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
3951 btrfs_calc_trans_metadata_size(fs_info, 1);
3953 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3954 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3955 left, thresh, type);
3956 btrfs_dump_space_info(fs_info, info, 0, 0);
3959 if (left < thresh) {
3960 u64 flags = btrfs_system_alloc_profile(fs_info);
3963 * Ignore failure to create system chunk. We might end up not
3964 * needing it, as we might not need to COW all nodes/leafs from
3965 * the paths we visit in the chunk tree (they were already COWed
3966 * or created in the current transaction for example).
3968 ret = btrfs_alloc_chunk(trans, flags);
3972 ret = btrfs_block_rsv_add(fs_info->chunk_root,
3973 &fs_info->chunk_block_rsv,
3974 thresh, BTRFS_RESERVE_NO_FLUSH);
3976 trans->chunk_bytes_reserved += thresh;
3981 * If force is CHUNK_ALLOC_FORCE:
3982 * - return 1 if it successfully allocates a chunk,
3983 * - return errors including -ENOSPC otherwise.
3984 * If force is NOT CHUNK_ALLOC_FORCE:
3985 * - return 0 if it doesn't need to allocate a new chunk,
3986 * - return 1 if it successfully allocates a chunk,
3987 * - return errors including -ENOSPC otherwise.
3989 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3990 enum btrfs_chunk_alloc_enum force)
3992 struct btrfs_fs_info *fs_info = trans->fs_info;
3993 struct btrfs_space_info *space_info;
3994 bool wait_for_alloc = false;
3995 bool should_alloc = false;
3998 /* Don't re-enter if we're already allocating a chunk */
3999 if (trans->allocating_chunk)
4002 space_info = btrfs_find_space_info(fs_info, flags);
4006 spin_lock(&space_info->lock);
4007 if (force < space_info->force_alloc)
4008 force = space_info->force_alloc;
4009 should_alloc = should_alloc_chunk(fs_info, space_info, force);
4010 if (space_info->full) {
4011 /* No more free physical space */
4016 spin_unlock(&space_info->lock);
4018 } else if (!should_alloc) {
4019 spin_unlock(&space_info->lock);
4021 } else if (space_info->chunk_alloc) {
4023 * Someone is already allocating, so we need to block
4024 * until this someone is finished and then loop to
4025 * recheck if we should continue with our allocation
4028 wait_for_alloc = true;
4029 spin_unlock(&space_info->lock);
4030 mutex_lock(&fs_info->chunk_mutex);
4031 mutex_unlock(&fs_info->chunk_mutex);
4033 /* Proceed with allocation */
4034 space_info->chunk_alloc = 1;
4035 wait_for_alloc = false;
4036 spin_unlock(&space_info->lock);
4040 } while (wait_for_alloc);
4042 mutex_lock(&fs_info->chunk_mutex);
4043 trans->allocating_chunk = true;
4046 * If we have mixed data/metadata chunks we want to make sure we keep
4047 * allocating mixed chunks instead of individual chunks.
4049 if (btrfs_mixed_space_info(space_info))
4050 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4053 * if we're doing a data chunk, go ahead and make sure that
4054 * we keep a reasonable number of metadata chunks allocated in the
4057 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4058 fs_info->data_chunk_allocations++;
4059 if (!(fs_info->data_chunk_allocations %
4060 fs_info->metadata_ratio))
4061 force_metadata_allocation(fs_info);
4065 * Check if we have enough space in SYSTEM chunk because we may need
4066 * to update devices.
4068 check_system_chunk(trans, flags);
4070 ret = btrfs_alloc_chunk(trans, flags);
4071 trans->allocating_chunk = false;
4073 spin_lock(&space_info->lock);
4076 space_info->full = 1;
4081 space_info->max_extent_size = 0;
4084 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4086 space_info->chunk_alloc = 0;
4087 spin_unlock(&space_info->lock);
4088 mutex_unlock(&fs_info->chunk_mutex);
4090 * When we allocate a new chunk we reserve space in the chunk block
4091 * reserve to make sure we can COW nodes/leafs in the chunk tree or
4092 * add new nodes/leafs to it if we end up needing to do it when
4093 * inserting the chunk item and updating device items as part of the
4094 * second phase of chunk allocation, performed by
4095 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4096 * large number of new block groups to create in our transaction
4097 * handle's new_bgs list to avoid exhausting the chunk block reserve
4098 * in extreme cases - like having a single transaction create many new
4099 * block groups when starting to write out the free space caches of all
4100 * the block groups that were made dirty during the lifetime of the
4103 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
4104 btrfs_create_pending_block_groups(trans);
4109 static int update_block_group(struct btrfs_trans_handle *trans,
4110 u64 bytenr, u64 num_bytes, int alloc)
4112 struct btrfs_fs_info *info = trans->fs_info;
4113 struct btrfs_block_group_cache *cache = NULL;
4114 u64 total = num_bytes;
4120 /* block accounting for super block */
4121 spin_lock(&info->delalloc_root_lock);
4122 old_val = btrfs_super_bytes_used(info->super_copy);
4124 old_val += num_bytes;
4126 old_val -= num_bytes;
4127 btrfs_set_super_bytes_used(info->super_copy, old_val);
4128 spin_unlock(&info->delalloc_root_lock);
4131 cache = btrfs_lookup_block_group(info, bytenr);
4136 factor = btrfs_bg_type_to_factor(cache->flags);
4139 * If this block group has free space cache written out, we
4140 * need to make sure to load it if we are removing space. This
4141 * is because we need the unpinning stage to actually add the
4142 * space back to the block group, otherwise we will leak space.
4144 if (!alloc && cache->cached == BTRFS_CACHE_NO)
4145 cache_block_group(cache, 1);
4147 byte_in_group = bytenr - cache->key.objectid;
4148 WARN_ON(byte_in_group > cache->key.offset);
4150 spin_lock(&cache->space_info->lock);
4151 spin_lock(&cache->lock);
4153 if (btrfs_test_opt(info, SPACE_CACHE) &&
4154 cache->disk_cache_state < BTRFS_DC_CLEAR)
4155 cache->disk_cache_state = BTRFS_DC_CLEAR;
4157 old_val = btrfs_block_group_used(&cache->item);
4158 num_bytes = min(total, cache->key.offset - byte_in_group);
4160 old_val += num_bytes;
4161 btrfs_set_block_group_used(&cache->item, old_val);
4162 cache->reserved -= num_bytes;
4163 cache->space_info->bytes_reserved -= num_bytes;
4164 cache->space_info->bytes_used += num_bytes;
4165 cache->space_info->disk_used += num_bytes * factor;
4166 spin_unlock(&cache->lock);
4167 spin_unlock(&cache->space_info->lock);
4169 old_val -= num_bytes;
4170 btrfs_set_block_group_used(&cache->item, old_val);
4171 cache->pinned += num_bytes;
4172 btrfs_space_info_update_bytes_pinned(info,
4173 cache->space_info, num_bytes);
4174 cache->space_info->bytes_used -= num_bytes;
4175 cache->space_info->disk_used -= num_bytes * factor;
4176 spin_unlock(&cache->lock);
4177 spin_unlock(&cache->space_info->lock);
4179 trace_btrfs_space_reservation(info, "pinned",
4180 cache->space_info->flags,
4182 percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
4184 BTRFS_TOTAL_BYTES_PINNED_BATCH);
4185 set_extent_dirty(info->pinned_extents,
4186 bytenr, bytenr + num_bytes - 1,
4187 GFP_NOFS | __GFP_NOFAIL);
4190 spin_lock(&trans->transaction->dirty_bgs_lock);
4191 if (list_empty(&cache->dirty_list)) {
4192 list_add_tail(&cache->dirty_list,
4193 &trans->transaction->dirty_bgs);
4194 trans->delayed_ref_updates++;
4195 btrfs_get_block_group(cache);
4197 spin_unlock(&trans->transaction->dirty_bgs_lock);
4200 * No longer have used bytes in this block group, queue it for
4201 * deletion. We do this after adding the block group to the
4202 * dirty list to avoid races between cleaner kthread and space
4205 if (!alloc && old_val == 0)
4206 btrfs_mark_bg_unused(cache);
4208 btrfs_put_block_group(cache);
4210 bytenr += num_bytes;
4213 /* Modified block groups are accounted for in the delayed_refs_rsv. */
4214 btrfs_update_delayed_refs_rsv(trans);
4218 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
4220 struct btrfs_block_group_cache *cache;
4223 spin_lock(&fs_info->block_group_cache_lock);
4224 bytenr = fs_info->first_logical_byte;
4225 spin_unlock(&fs_info->block_group_cache_lock);
4227 if (bytenr < (u64)-1)
4230 cache = btrfs_lookup_first_block_group(fs_info, search_start);
4234 bytenr = cache->key.objectid;
4235 btrfs_put_block_group(cache);
4240 static int pin_down_extent(struct btrfs_block_group_cache *cache,
4241 u64 bytenr, u64 num_bytes, int reserved)
4243 struct btrfs_fs_info *fs_info = cache->fs_info;
4245 spin_lock(&cache->space_info->lock);
4246 spin_lock(&cache->lock);
4247 cache->pinned += num_bytes;
4248 btrfs_space_info_update_bytes_pinned(fs_info, cache->space_info,
4251 cache->reserved -= num_bytes;
4252 cache->space_info->bytes_reserved -= num_bytes;
4254 spin_unlock(&cache->lock);
4255 spin_unlock(&cache->space_info->lock);
4257 trace_btrfs_space_reservation(fs_info, "pinned",
4258 cache->space_info->flags, num_bytes, 1);
4259 percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
4260 num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
4261 set_extent_dirty(fs_info->pinned_extents, bytenr,
4262 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
4267 * this function must be called within transaction
4269 int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
4270 u64 bytenr, u64 num_bytes, int reserved)
4272 struct btrfs_block_group_cache *cache;
4274 cache = btrfs_lookup_block_group(fs_info, bytenr);
4275 BUG_ON(!cache); /* Logic error */
4277 pin_down_extent(cache, bytenr, num_bytes, reserved);
4279 btrfs_put_block_group(cache);
4284 * this function must be called within transaction
4286 int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
4287 u64 bytenr, u64 num_bytes)
4289 struct btrfs_block_group_cache *cache;
4292 cache = btrfs_lookup_block_group(fs_info, bytenr);
4297 * pull in the free space cache (if any) so that our pin
4298 * removes the free space from the cache. We have load_only set
4299 * to one because the slow code to read in the free extents does check
4300 * the pinned extents.
4302 cache_block_group(cache, 1);
4304 pin_down_extent(cache, bytenr, num_bytes, 0);
4306 /* remove us from the free space cache (if we're there at all) */
4307 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
4308 btrfs_put_block_group(cache);
4312 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
4313 u64 start, u64 num_bytes)
4316 struct btrfs_block_group_cache *block_group;
4317 struct btrfs_caching_control *caching_ctl;
4319 block_group = btrfs_lookup_block_group(fs_info, start);
4323 cache_block_group(block_group, 0);
4324 caching_ctl = get_caching_control(block_group);
4328 BUG_ON(!block_group_cache_done(block_group));
4329 ret = btrfs_remove_free_space(block_group, start, num_bytes);
4331 mutex_lock(&caching_ctl->mutex);
4333 if (start >= caching_ctl->progress) {
4334 ret = add_excluded_extent(fs_info, start, num_bytes);
4335 } else if (start + num_bytes <= caching_ctl->progress) {
4336 ret = btrfs_remove_free_space(block_group,
4339 num_bytes = caching_ctl->progress - start;
4340 ret = btrfs_remove_free_space(block_group,
4345 num_bytes = (start + num_bytes) -
4346 caching_ctl->progress;
4347 start = caching_ctl->progress;
4348 ret = add_excluded_extent(fs_info, start, num_bytes);
4351 mutex_unlock(&caching_ctl->mutex);
4352 put_caching_control(caching_ctl);
4354 btrfs_put_block_group(block_group);
4358 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
4360 struct btrfs_fs_info *fs_info = eb->fs_info;
4361 struct btrfs_file_extent_item *item;
4362 struct btrfs_key key;
4367 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
4370 for (i = 0; i < btrfs_header_nritems(eb); i++) {
4371 btrfs_item_key_to_cpu(eb, &key, i);
4372 if (key.type != BTRFS_EXTENT_DATA_KEY)
4374 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
4375 found_type = btrfs_file_extent_type(eb, item);
4376 if (found_type == BTRFS_FILE_EXTENT_INLINE)
4378 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
4380 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
4381 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
4382 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
4391 btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
4393 atomic_inc(&bg->reservations);
4396 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
4399 struct btrfs_block_group_cache *bg;
4401 bg = btrfs_lookup_block_group(fs_info, start);
4403 if (atomic_dec_and_test(&bg->reservations))
4404 wake_up_var(&bg->reservations);
4405 btrfs_put_block_group(bg);
4408 void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
4410 struct btrfs_space_info *space_info = bg->space_info;
4414 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
4418 * Our block group is read only but before we set it to read only,
4419 * some task might have had allocated an extent from it already, but it
4420 * has not yet created a respective ordered extent (and added it to a
4421 * root's list of ordered extents).
4422 * Therefore wait for any task currently allocating extents, since the
4423 * block group's reservations counter is incremented while a read lock
4424 * on the groups' semaphore is held and decremented after releasing
4425 * the read access on that semaphore and creating the ordered extent.
4427 down_write(&space_info->groups_sem);
4428 up_write(&space_info->groups_sem);
4430 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
4434 * btrfs_add_reserved_bytes - update the block_group and space info counters
4435 * @cache: The cache we are manipulating
4436 * @ram_bytes: The number of bytes of file content, and will be same to
4437 * @num_bytes except for the compress path.
4438 * @num_bytes: The number of bytes in question
4439 * @delalloc: The blocks are allocated for the delalloc write
4441 * This is called by the allocator when it reserves space. If this is a
4442 * reservation and the block group has become read only we cannot make the
4443 * reservation and return -EAGAIN, otherwise this function always succeeds.
4445 static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
4446 u64 ram_bytes, u64 num_bytes, int delalloc)
4448 struct btrfs_space_info *space_info = cache->space_info;
4451 spin_lock(&space_info->lock);
4452 spin_lock(&cache->lock);
4456 cache->reserved += num_bytes;
4457 space_info->bytes_reserved += num_bytes;
4458 btrfs_space_info_update_bytes_may_use(cache->fs_info,
4459 space_info, -ram_bytes);
4461 cache->delalloc_bytes += num_bytes;
4463 spin_unlock(&cache->lock);
4464 spin_unlock(&space_info->lock);
4469 * btrfs_free_reserved_bytes - update the block_group and space info counters
4470 * @cache: The cache we are manipulating
4471 * @num_bytes: The number of bytes in question
4472 * @delalloc: The blocks are allocated for the delalloc write
4474 * This is called by somebody who is freeing space that was never actually used
4475 * on disk. For example if you reserve some space for a new leaf in transaction
4476 * A and before transaction A commits you free that leaf, you call this with
4477 * reserve set to 0 in order to clear the reservation.
4480 static void btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
4481 u64 num_bytes, int delalloc)
4483 struct btrfs_space_info *space_info = cache->space_info;
4485 spin_lock(&space_info->lock);
4486 spin_lock(&cache->lock);
4488 space_info->bytes_readonly += num_bytes;
4489 cache->reserved -= num_bytes;
4490 space_info->bytes_reserved -= num_bytes;
4491 space_info->max_extent_size = 0;
4494 cache->delalloc_bytes -= num_bytes;
4495 spin_unlock(&cache->lock);
4496 spin_unlock(&space_info->lock);
4498 void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
4500 struct btrfs_caching_control *next;
4501 struct btrfs_caching_control *caching_ctl;
4502 struct btrfs_block_group_cache *cache;
4504 down_write(&fs_info->commit_root_sem);
4506 list_for_each_entry_safe(caching_ctl, next,
4507 &fs_info->caching_block_groups, list) {
4508 cache = caching_ctl->block_group;
4509 if (block_group_cache_done(cache)) {
4510 cache->last_byte_to_unpin = (u64)-1;
4511 list_del_init(&caching_ctl->list);
4512 put_caching_control(caching_ctl);
4514 cache->last_byte_to_unpin = caching_ctl->progress;
4518 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
4519 fs_info->pinned_extents = &fs_info->freed_extents[1];
4521 fs_info->pinned_extents = &fs_info->freed_extents[0];
4523 up_write(&fs_info->commit_root_sem);
4525 btrfs_update_global_block_rsv(fs_info);
4529 * Returns the free cluster for the given space info and sets empty_cluster to
4530 * what it should be based on the mount options.
4532 static struct btrfs_free_cluster *
4533 fetch_cluster_info(struct btrfs_fs_info *fs_info,
4534 struct btrfs_space_info *space_info, u64 *empty_cluster)
4536 struct btrfs_free_cluster *ret = NULL;
4539 if (btrfs_mixed_space_info(space_info))
4542 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
4543 ret = &fs_info->meta_alloc_cluster;
4544 if (btrfs_test_opt(fs_info, SSD))
4545 *empty_cluster = SZ_2M;
4547 *empty_cluster = SZ_64K;
4548 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
4549 btrfs_test_opt(fs_info, SSD_SPREAD)) {
4550 *empty_cluster = SZ_2M;
4551 ret = &fs_info->data_alloc_cluster;
4557 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
4559 const bool return_free_space)
4561 struct btrfs_block_group_cache *cache = NULL;
4562 struct btrfs_space_info *space_info;
4563 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4564 struct btrfs_free_cluster *cluster = NULL;
4566 u64 total_unpinned = 0;
4567 u64 empty_cluster = 0;
4570 while (start <= end) {
4573 start >= cache->key.objectid + cache->key.offset) {
4575 btrfs_put_block_group(cache);
4577 cache = btrfs_lookup_block_group(fs_info, start);
4578 BUG_ON(!cache); /* Logic error */
4580 cluster = fetch_cluster_info(fs_info,
4583 empty_cluster <<= 1;
4586 len = cache->key.objectid + cache->key.offset - start;
4587 len = min(len, end + 1 - start);
4589 if (start < cache->last_byte_to_unpin) {
4590 len = min(len, cache->last_byte_to_unpin - start);
4591 if (return_free_space)
4592 btrfs_add_free_space(cache, start, len);
4596 total_unpinned += len;
4597 space_info = cache->space_info;
4600 * If this space cluster has been marked as fragmented and we've
4601 * unpinned enough in this block group to potentially allow a
4602 * cluster to be created inside of it go ahead and clear the
4605 if (cluster && cluster->fragmented &&
4606 total_unpinned > empty_cluster) {
4607 spin_lock(&cluster->lock);
4608 cluster->fragmented = 0;
4609 spin_unlock(&cluster->lock);
4612 spin_lock(&space_info->lock);
4613 spin_lock(&cache->lock);
4614 cache->pinned -= len;
4615 btrfs_space_info_update_bytes_pinned(fs_info, space_info, -len);
4617 trace_btrfs_space_reservation(fs_info, "pinned",
4618 space_info->flags, len, 0);
4619 space_info->max_extent_size = 0;
4620 percpu_counter_add_batch(&space_info->total_bytes_pinned,
4621 -len, BTRFS_TOTAL_BYTES_PINNED_BATCH);
4623 space_info->bytes_readonly += len;
4626 spin_unlock(&cache->lock);
4627 if (!readonly && return_free_space &&
4628 global_rsv->space_info == space_info) {
4631 spin_lock(&global_rsv->lock);
4632 if (!global_rsv->full) {
4633 to_add = min(len, global_rsv->size -
4634 global_rsv->reserved);
4635 global_rsv->reserved += to_add;
4636 btrfs_space_info_update_bytes_may_use(fs_info,
4637 space_info, to_add);
4638 if (global_rsv->reserved >= global_rsv->size)
4639 global_rsv->full = 1;
4640 trace_btrfs_space_reservation(fs_info,
4646 spin_unlock(&global_rsv->lock);
4647 /* Add to any tickets we may have */
4649 btrfs_space_info_add_new_bytes(fs_info,
4652 spin_unlock(&space_info->lock);
4656 btrfs_put_block_group(cache);
4660 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
4662 struct btrfs_fs_info *fs_info = trans->fs_info;
4663 struct btrfs_block_group_cache *block_group, *tmp;
4664 struct list_head *deleted_bgs;
4665 struct extent_io_tree *unpin;
4670 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
4671 unpin = &fs_info->freed_extents[1];
4673 unpin = &fs_info->freed_extents[0];
4675 while (!trans->aborted) {
4676 struct extent_state *cached_state = NULL;
4678 mutex_lock(&fs_info->unused_bg_unpin_mutex);
4679 ret = find_first_extent_bit(unpin, 0, &start, &end,
4680 EXTENT_DIRTY, &cached_state);
4682 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4686 if (btrfs_test_opt(fs_info, DISCARD))
4687 ret = btrfs_discard_extent(fs_info, start,
4688 end + 1 - start, NULL);
4690 clear_extent_dirty(unpin, start, end, &cached_state);
4691 unpin_extent_range(fs_info, start, end, true);
4692 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4693 free_extent_state(cached_state);
4698 * Transaction is finished. We don't need the lock anymore. We
4699 * do need to clean up the block groups in case of a transaction
4702 deleted_bgs = &trans->transaction->deleted_bgs;
4703 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
4707 if (!trans->aborted)
4708 ret = btrfs_discard_extent(fs_info,
4709 block_group->key.objectid,
4710 block_group->key.offset,
4713 list_del_init(&block_group->bg_list);
4714 btrfs_put_block_group_trimming(block_group);
4715 btrfs_put_block_group(block_group);
4718 const char *errstr = btrfs_decode_error(ret);
4720 "discard failed while removing blockgroup: errno=%d %s",
4728 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
4729 struct btrfs_delayed_ref_node *node, u64 parent,
4730 u64 root_objectid, u64 owner_objectid,
4731 u64 owner_offset, int refs_to_drop,
4732 struct btrfs_delayed_extent_op *extent_op)
4734 struct btrfs_fs_info *info = trans->fs_info;
4735 struct btrfs_key key;
4736 struct btrfs_path *path;
4737 struct btrfs_root *extent_root = info->extent_root;
4738 struct extent_buffer *leaf;
4739 struct btrfs_extent_item *ei;
4740 struct btrfs_extent_inline_ref *iref;
4743 int extent_slot = 0;
4744 int found_extent = 0;
4748 u64 bytenr = node->bytenr;
4749 u64 num_bytes = node->num_bytes;
4751 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
4753 path = btrfs_alloc_path();
4757 path->reada = READA_FORWARD;
4758 path->leave_spinning = 1;
4760 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
4761 BUG_ON(!is_data && refs_to_drop != 1);
4764 skinny_metadata = false;
4766 ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
4767 parent, root_objectid, owner_objectid,
4770 extent_slot = path->slots[0];
4771 while (extent_slot >= 0) {
4772 btrfs_item_key_to_cpu(path->nodes[0], &key,
4774 if (key.objectid != bytenr)
4776 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
4777 key.offset == num_bytes) {
4781 if (key.type == BTRFS_METADATA_ITEM_KEY &&
4782 key.offset == owner_objectid) {
4786 if (path->slots[0] - extent_slot > 5)
4791 if (!found_extent) {
4793 ret = remove_extent_backref(trans, path, NULL,
4795 is_data, &last_ref);
4797 btrfs_abort_transaction(trans, ret);
4800 btrfs_release_path(path);
4801 path->leave_spinning = 1;
4803 key.objectid = bytenr;
4804 key.type = BTRFS_EXTENT_ITEM_KEY;
4805 key.offset = num_bytes;
4807 if (!is_data && skinny_metadata) {
4808 key.type = BTRFS_METADATA_ITEM_KEY;
4809 key.offset = owner_objectid;
4812 ret = btrfs_search_slot(trans, extent_root,
4814 if (ret > 0 && skinny_metadata && path->slots[0]) {
4816 * Couldn't find our skinny metadata item,
4817 * see if we have ye olde extent item.
4820 btrfs_item_key_to_cpu(path->nodes[0], &key,
4822 if (key.objectid == bytenr &&
4823 key.type == BTRFS_EXTENT_ITEM_KEY &&
4824 key.offset == num_bytes)
4828 if (ret > 0 && skinny_metadata) {
4829 skinny_metadata = false;
4830 key.objectid = bytenr;
4831 key.type = BTRFS_EXTENT_ITEM_KEY;
4832 key.offset = num_bytes;
4833 btrfs_release_path(path);
4834 ret = btrfs_search_slot(trans, extent_root,
4840 "umm, got %d back from search, was looking for %llu",
4843 btrfs_print_leaf(path->nodes[0]);
4846 btrfs_abort_transaction(trans, ret);
4849 extent_slot = path->slots[0];
4851 } else if (WARN_ON(ret == -ENOENT)) {
4852 btrfs_print_leaf(path->nodes[0]);
4854 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
4855 bytenr, parent, root_objectid, owner_objectid,
4857 btrfs_abort_transaction(trans, ret);
4860 btrfs_abort_transaction(trans, ret);
4864 leaf = path->nodes[0];
4865 item_size = btrfs_item_size_nr(leaf, extent_slot);
4866 if (unlikely(item_size < sizeof(*ei))) {
4868 btrfs_print_v0_err(info);
4869 btrfs_abort_transaction(trans, ret);
4872 ei = btrfs_item_ptr(leaf, extent_slot,
4873 struct btrfs_extent_item);
4874 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
4875 key.type == BTRFS_EXTENT_ITEM_KEY) {
4876 struct btrfs_tree_block_info *bi;
4877 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
4878 bi = (struct btrfs_tree_block_info *)(ei + 1);
4879 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
4882 refs = btrfs_extent_refs(leaf, ei);
4883 if (refs < refs_to_drop) {
4885 "trying to drop %d refs but we only have %Lu for bytenr %Lu",
4886 refs_to_drop, refs, bytenr);
4888 btrfs_abort_transaction(trans, ret);
4891 refs -= refs_to_drop;
4895 __run_delayed_extent_op(extent_op, leaf, ei);
4897 * In the case of inline back ref, reference count will
4898 * be updated by remove_extent_backref
4901 BUG_ON(!found_extent);
4903 btrfs_set_extent_refs(leaf, ei, refs);
4904 btrfs_mark_buffer_dirty(leaf);
4907 ret = remove_extent_backref(trans, path, iref,
4908 refs_to_drop, is_data,
4911 btrfs_abort_transaction(trans, ret);
4917 BUG_ON(is_data && refs_to_drop !=
4918 extent_data_ref_count(path, iref));
4920 BUG_ON(path->slots[0] != extent_slot);
4922 BUG_ON(path->slots[0] != extent_slot + 1);
4923 path->slots[0] = extent_slot;
4929 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
4932 btrfs_abort_transaction(trans, ret);
4935 btrfs_release_path(path);
4938 ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
4940 btrfs_abort_transaction(trans, ret);
4945 ret = add_to_free_space_tree(trans, bytenr, num_bytes);
4947 btrfs_abort_transaction(trans, ret);
4951 ret = update_block_group(trans, bytenr, num_bytes, 0);
4953 btrfs_abort_transaction(trans, ret);
4957 btrfs_release_path(path);
4960 btrfs_free_path(path);
4965 * when we free an block, it is possible (and likely) that we free the last
4966 * delayed ref for that extent as well. This searches the delayed ref tree for
4967 * a given extent, and if there are no other delayed refs to be processed, it
4968 * removes it from the tree.
4970 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
4973 struct btrfs_delayed_ref_head *head;
4974 struct btrfs_delayed_ref_root *delayed_refs;
4977 delayed_refs = &trans->transaction->delayed_refs;
4978 spin_lock(&delayed_refs->lock);
4979 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
4981 goto out_delayed_unlock;
4983 spin_lock(&head->lock);
4984 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
4987 if (cleanup_extent_op(head) != NULL)
4991 * waiting for the lock here would deadlock. If someone else has it
4992 * locked they are already in the process of dropping it anyway
4994 if (!mutex_trylock(&head->mutex))
4997 btrfs_delete_ref_head(delayed_refs, head);
4998 head->processing = 0;
5000 spin_unlock(&head->lock);
5001 spin_unlock(&delayed_refs->lock);
5003 BUG_ON(head->extent_op);
5004 if (head->must_insert_reserved)
5007 btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
5008 mutex_unlock(&head->mutex);
5009 btrfs_put_delayed_ref_head(head);
5012 spin_unlock(&head->lock);
5015 spin_unlock(&delayed_refs->lock);
5019 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
5020 struct btrfs_root *root,
5021 struct extent_buffer *buf,
5022 u64 parent, int last_ref)
5024 struct btrfs_fs_info *fs_info = root->fs_info;
5025 struct btrfs_ref generic_ref = { 0 };
5029 btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
5030 buf->start, buf->len, parent);
5031 btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
5032 root->root_key.objectid);
5034 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
5035 int old_ref_mod, new_ref_mod;
5037 btrfs_ref_tree_mod(fs_info, &generic_ref);
5038 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL,
5039 &old_ref_mod, &new_ref_mod);
5040 BUG_ON(ret); /* -ENOMEM */
5041 pin = old_ref_mod >= 0 && new_ref_mod < 0;
5044 if (last_ref && btrfs_header_generation(buf) == trans->transid) {
5045 struct btrfs_block_group_cache *cache;
5047 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
5048 ret = check_ref_cleanup(trans, buf->start);
5054 cache = btrfs_lookup_block_group(fs_info, buf->start);
5056 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
5057 pin_down_extent(cache, buf->start, buf->len, 1);
5058 btrfs_put_block_group(cache);
5062 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
5064 btrfs_add_free_space(cache, buf->start, buf->len);
5065 btrfs_free_reserved_bytes(cache, buf->len, 0);
5066 btrfs_put_block_group(cache);
5067 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
5071 add_pinned_bytes(fs_info, &generic_ref);
5075 * Deleting the buffer, clear the corrupt flag since it doesn't
5078 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
5082 /* Can return -ENOMEM */
5083 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
5085 struct btrfs_fs_info *fs_info = trans->fs_info;
5086 int old_ref_mod, new_ref_mod;
5089 if (btrfs_is_testing(fs_info))
5093 * tree log blocks never actually go into the extent allocation
5094 * tree, just update pinning info and exit early.
5096 if ((ref->type == BTRFS_REF_METADATA &&
5097 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
5098 (ref->type == BTRFS_REF_DATA &&
5099 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)) {
5100 /* unlocks the pinned mutex */
5101 btrfs_pin_extent(fs_info, ref->bytenr, ref->len, 1);
5102 old_ref_mod = new_ref_mod = 0;
5104 } else if (ref->type == BTRFS_REF_METADATA) {
5105 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL,
5106 &old_ref_mod, &new_ref_mod);
5108 ret = btrfs_add_delayed_data_ref(trans, ref, 0,
5109 &old_ref_mod, &new_ref_mod);
5112 if (!((ref->type == BTRFS_REF_METADATA &&
5113 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
5114 (ref->type == BTRFS_REF_DATA &&
5115 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)))
5116 btrfs_ref_tree_mod(fs_info, ref);
5118 if (ret == 0 && old_ref_mod >= 0 && new_ref_mod < 0)
5119 add_pinned_bytes(fs_info, ref);
5125 * when we wait for progress in the block group caching, its because
5126 * our allocation attempt failed at least once. So, we must sleep
5127 * and let some progress happen before we try again.
5129 * This function will sleep at least once waiting for new free space to
5130 * show up, and then it will check the block group free space numbers
5131 * for our min num_bytes. Another option is to have it go ahead
5132 * and look in the rbtree for a free extent of a given size, but this
5135 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
5136 * any of the information in this block group.
5138 static noinline void
5139 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
5142 struct btrfs_caching_control *caching_ctl;
5144 caching_ctl = get_caching_control(cache);
5148 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
5149 (cache->free_space_ctl->free_space >= num_bytes));
5151 put_caching_control(caching_ctl);
5155 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
5157 struct btrfs_caching_control *caching_ctl;
5160 caching_ctl = get_caching_control(cache);
5162 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
5164 wait_event(caching_ctl->wait, block_group_cache_done(cache));
5165 if (cache->cached == BTRFS_CACHE_ERROR)
5167 put_caching_control(caching_ctl);
5171 enum btrfs_loop_type {
5172 LOOP_CACHING_NOWAIT,
5179 btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
5183 down_read(&cache->data_rwsem);
5187 btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
5190 btrfs_get_block_group(cache);
5192 down_read(&cache->data_rwsem);
5195 static struct btrfs_block_group_cache *
5196 btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
5197 struct btrfs_free_cluster *cluster,
5200 struct btrfs_block_group_cache *used_bg = NULL;
5202 spin_lock(&cluster->refill_lock);
5204 used_bg = cluster->block_group;
5208 if (used_bg == block_group)
5211 btrfs_get_block_group(used_bg);
5216 if (down_read_trylock(&used_bg->data_rwsem))
5219 spin_unlock(&cluster->refill_lock);
5221 /* We should only have one-level nested. */
5222 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
5224 spin_lock(&cluster->refill_lock);
5225 if (used_bg == cluster->block_group)
5228 up_read(&used_bg->data_rwsem);
5229 btrfs_put_block_group(used_bg);
5234 btrfs_release_block_group(struct btrfs_block_group_cache *cache,
5238 up_read(&cache->data_rwsem);
5239 btrfs_put_block_group(cache);
5243 * Structure used internally for find_free_extent() function. Wraps needed
5246 struct find_free_extent_ctl {
5247 /* Basic allocation info */
5254 /* Where to start the search inside the bg */
5257 /* For clustered allocation */
5260 bool have_caching_bg;
5261 bool orig_have_caching_bg;
5263 /* RAID index, converted from flags */
5267 * Current loop number, check find_free_extent_update_loop() for details
5272 * Whether we're refilling a cluster, if true we need to re-search
5273 * current block group but don't try to refill the cluster again.
5275 bool retry_clustered;
5278 * Whether we're updating free space cache, if true we need to re-search
5279 * current block group but don't try updating free space cache again.
5281 bool retry_unclustered;
5283 /* If current block group is cached */
5286 /* Max contiguous hole found */
5287 u64 max_extent_size;
5289 /* Total free space from free space cache, not always contiguous */
5290 u64 total_free_space;
5298 * Helper function for find_free_extent().
5300 * Return -ENOENT to inform caller that we need fallback to unclustered mode.
5301 * Return -EAGAIN to inform caller that we need to re-search this block group
5302 * Return >0 to inform caller that we find nothing
5303 * Return 0 means we have found a location and set ffe_ctl->found_offset.
5305 static int find_free_extent_clustered(struct btrfs_block_group_cache *bg,
5306 struct btrfs_free_cluster *last_ptr,
5307 struct find_free_extent_ctl *ffe_ctl,
5308 struct btrfs_block_group_cache **cluster_bg_ret)
5310 struct btrfs_block_group_cache *cluster_bg;
5311 u64 aligned_cluster;
5315 cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
5317 goto refill_cluster;
5318 if (cluster_bg != bg && (cluster_bg->ro ||
5319 !block_group_bits(cluster_bg, ffe_ctl->flags)))
5320 goto release_cluster;
5322 offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
5323 ffe_ctl->num_bytes, cluster_bg->key.objectid,
5324 &ffe_ctl->max_extent_size);
5326 /* We have a block, we're done */
5327 spin_unlock(&last_ptr->refill_lock);
5328 trace_btrfs_reserve_extent_cluster(cluster_bg,
5329 ffe_ctl->search_start, ffe_ctl->num_bytes);
5330 *cluster_bg_ret = cluster_bg;
5331 ffe_ctl->found_offset = offset;
5334 WARN_ON(last_ptr->block_group != cluster_bg);
5338 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
5339 * lets just skip it and let the allocator find whatever block it can
5340 * find. If we reach this point, we will have tried the cluster
5341 * allocator plenty of times and not have found anything, so we are
5342 * likely way too fragmented for the clustering stuff to find anything.
5344 * However, if the cluster is taken from the current block group,
5345 * release the cluster first, so that we stand a better chance of
5346 * succeeding in the unclustered allocation.
5348 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
5349 spin_unlock(&last_ptr->refill_lock);
5350 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
5354 /* This cluster didn't work out, free it and start over */
5355 btrfs_return_cluster_to_free_space(NULL, last_ptr);
5357 if (cluster_bg != bg)
5358 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
5361 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
5362 spin_unlock(&last_ptr->refill_lock);
5366 aligned_cluster = max_t(u64,
5367 ffe_ctl->empty_cluster + ffe_ctl->empty_size,
5368 bg->full_stripe_len);
5369 ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
5370 ffe_ctl->num_bytes, aligned_cluster);
5372 /* Now pull our allocation out of this cluster */
5373 offset = btrfs_alloc_from_cluster(bg, last_ptr,
5374 ffe_ctl->num_bytes, ffe_ctl->search_start,
5375 &ffe_ctl->max_extent_size);
5377 /* We found one, proceed */
5378 spin_unlock(&last_ptr->refill_lock);
5379 trace_btrfs_reserve_extent_cluster(bg,
5380 ffe_ctl->search_start,
5381 ffe_ctl->num_bytes);
5382 ffe_ctl->found_offset = offset;
5385 } else if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
5386 !ffe_ctl->retry_clustered) {
5387 spin_unlock(&last_ptr->refill_lock);
5389 ffe_ctl->retry_clustered = true;
5390 wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
5391 ffe_ctl->empty_cluster + ffe_ctl->empty_size);
5395 * At this point we either didn't find a cluster or we weren't able to
5396 * allocate a block from our cluster. Free the cluster we've been
5397 * trying to use, and go to the next block group.
5399 btrfs_return_cluster_to_free_space(NULL, last_ptr);
5400 spin_unlock(&last_ptr->refill_lock);
5405 * Return >0 to inform caller that we find nothing
5406 * Return 0 when we found an free extent and set ffe_ctrl->found_offset
5407 * Return -EAGAIN to inform caller that we need to re-search this block group
5409 static int find_free_extent_unclustered(struct btrfs_block_group_cache *bg,
5410 struct btrfs_free_cluster *last_ptr,
5411 struct find_free_extent_ctl *ffe_ctl)
5416 * We are doing an unclustered allocation, set the fragmented flag so
5417 * we don't bother trying to setup a cluster again until we get more
5420 if (unlikely(last_ptr)) {
5421 spin_lock(&last_ptr->lock);
5422 last_ptr->fragmented = 1;
5423 spin_unlock(&last_ptr->lock);
5425 if (ffe_ctl->cached) {
5426 struct btrfs_free_space_ctl *free_space_ctl;
5428 free_space_ctl = bg->free_space_ctl;
5429 spin_lock(&free_space_ctl->tree_lock);
5430 if (free_space_ctl->free_space <
5431 ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
5432 ffe_ctl->empty_size) {
5433 ffe_ctl->total_free_space = max_t(u64,
5434 ffe_ctl->total_free_space,
5435 free_space_ctl->free_space);
5436 spin_unlock(&free_space_ctl->tree_lock);
5439 spin_unlock(&free_space_ctl->tree_lock);
5442 offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
5443 ffe_ctl->num_bytes, ffe_ctl->empty_size,
5444 &ffe_ctl->max_extent_size);
5447 * If we didn't find a chunk, and we haven't failed on this block group
5448 * before, and this block group is in the middle of caching and we are
5449 * ok with waiting, then go ahead and wait for progress to be made, and
5450 * set @retry_unclustered to true.
5452 * If @retry_unclustered is true then we've already waited on this
5453 * block group once and should move on to the next block group.
5455 if (!offset && !ffe_ctl->retry_unclustered && !ffe_ctl->cached &&
5456 ffe_ctl->loop > LOOP_CACHING_NOWAIT) {
5457 wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
5458 ffe_ctl->empty_size);
5459 ffe_ctl->retry_unclustered = true;
5461 } else if (!offset) {
5464 ffe_ctl->found_offset = offset;
5469 * Return >0 means caller needs to re-search for free extent
5470 * Return 0 means we have the needed free extent.
5471 * Return <0 means we failed to locate any free extent.
5473 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
5474 struct btrfs_free_cluster *last_ptr,
5475 struct btrfs_key *ins,
5476 struct find_free_extent_ctl *ffe_ctl,
5477 int full_search, bool use_cluster)
5479 struct btrfs_root *root = fs_info->extent_root;
5482 if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
5483 ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
5484 ffe_ctl->orig_have_caching_bg = true;
5486 if (!ins->objectid && ffe_ctl->loop >= LOOP_CACHING_WAIT &&
5487 ffe_ctl->have_caching_bg)
5490 if (!ins->objectid && ++(ffe_ctl->index) < BTRFS_NR_RAID_TYPES)
5493 if (ins->objectid) {
5494 if (!use_cluster && last_ptr) {
5495 spin_lock(&last_ptr->lock);
5496 last_ptr->window_start = ins->objectid;
5497 spin_unlock(&last_ptr->lock);
5503 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
5504 * caching kthreads as we move along
5505 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
5506 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
5507 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
5510 if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
5512 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT) {
5514 * We want to skip the LOOP_CACHING_WAIT step if we
5515 * don't have any uncached bgs and we've already done a
5516 * full search through.
5518 if (ffe_ctl->orig_have_caching_bg || !full_search)
5519 ffe_ctl->loop = LOOP_CACHING_WAIT;
5521 ffe_ctl->loop = LOOP_ALLOC_CHUNK;
5526 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
5527 struct btrfs_trans_handle *trans;
5530 trans = current->journal_info;
5534 trans = btrfs_join_transaction(root);
5536 if (IS_ERR(trans)) {
5537 ret = PTR_ERR(trans);
5541 ret = btrfs_chunk_alloc(trans, ffe_ctl->flags,
5545 * If we can't allocate a new chunk we've already looped
5546 * through at least once, move on to the NO_EMPTY_SIZE
5550 ffe_ctl->loop = LOOP_NO_EMPTY_SIZE;
5552 /* Do not bail out on ENOSPC since we can do more. */
5553 if (ret < 0 && ret != -ENOSPC)
5554 btrfs_abort_transaction(trans, ret);
5558 btrfs_end_transaction(trans);
5563 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
5565 * Don't loop again if we already have no empty_size and
5568 if (ffe_ctl->empty_size == 0 &&
5569 ffe_ctl->empty_cluster == 0)
5571 ffe_ctl->empty_size = 0;
5572 ffe_ctl->empty_cluster = 0;
5580 * walks the btree of allocated extents and find a hole of a given size.
5581 * The key ins is changed to record the hole:
5582 * ins->objectid == start position
5583 * ins->flags = BTRFS_EXTENT_ITEM_KEY
5584 * ins->offset == the size of the hole.
5585 * Any available blocks before search_start are skipped.
5587 * If there is no suitable free space, we will record the max size of
5588 * the free space extent currently.
5590 * The overall logic and call chain:
5592 * find_free_extent()
5593 * |- Iterate through all block groups
5594 * | |- Get a valid block group
5595 * | |- Try to do clustered allocation in that block group
5596 * | |- Try to do unclustered allocation in that block group
5597 * | |- Check if the result is valid
5598 * | | |- If valid, then exit
5599 * | |- Jump to next block group
5601 * |- Push harder to find free extents
5602 * |- If not found, re-iterate all block groups
5604 static noinline int find_free_extent(struct btrfs_fs_info *fs_info,
5605 u64 ram_bytes, u64 num_bytes, u64 empty_size,
5606 u64 hint_byte, struct btrfs_key *ins,
5607 u64 flags, int delalloc)
5610 struct btrfs_free_cluster *last_ptr = NULL;
5611 struct btrfs_block_group_cache *block_group = NULL;
5612 struct find_free_extent_ctl ffe_ctl = {0};
5613 struct btrfs_space_info *space_info;
5614 bool use_cluster = true;
5615 bool full_search = false;
5617 WARN_ON(num_bytes < fs_info->sectorsize);
5619 ffe_ctl.ram_bytes = ram_bytes;
5620 ffe_ctl.num_bytes = num_bytes;
5621 ffe_ctl.empty_size = empty_size;
5622 ffe_ctl.flags = flags;
5623 ffe_ctl.search_start = 0;
5624 ffe_ctl.retry_clustered = false;
5625 ffe_ctl.retry_unclustered = false;
5626 ffe_ctl.delalloc = delalloc;
5627 ffe_ctl.index = btrfs_bg_flags_to_raid_index(flags);
5628 ffe_ctl.have_caching_bg = false;
5629 ffe_ctl.orig_have_caching_bg = false;
5630 ffe_ctl.found_offset = 0;
5632 ins->type = BTRFS_EXTENT_ITEM_KEY;
5636 trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
5638 space_info = btrfs_find_space_info(fs_info, flags);
5640 btrfs_err(fs_info, "No space info for %llu", flags);
5645 * If our free space is heavily fragmented we may not be able to make
5646 * big contiguous allocations, so instead of doing the expensive search
5647 * for free space, simply return ENOSPC with our max_extent_size so we
5648 * can go ahead and search for a more manageable chunk.
5650 * If our max_extent_size is large enough for our allocation simply
5651 * disable clustering since we will likely not be able to find enough
5652 * space to create a cluster and induce latency trying.
5654 if (unlikely(space_info->max_extent_size)) {
5655 spin_lock(&space_info->lock);
5656 if (space_info->max_extent_size &&
5657 num_bytes > space_info->max_extent_size) {
5658 ins->offset = space_info->max_extent_size;
5659 spin_unlock(&space_info->lock);
5661 } else if (space_info->max_extent_size) {
5662 use_cluster = false;
5664 spin_unlock(&space_info->lock);
5667 last_ptr = fetch_cluster_info(fs_info, space_info,
5668 &ffe_ctl.empty_cluster);
5670 spin_lock(&last_ptr->lock);
5671 if (last_ptr->block_group)
5672 hint_byte = last_ptr->window_start;
5673 if (last_ptr->fragmented) {
5675 * We still set window_start so we can keep track of the
5676 * last place we found an allocation to try and save
5679 hint_byte = last_ptr->window_start;
5680 use_cluster = false;
5682 spin_unlock(&last_ptr->lock);
5685 ffe_ctl.search_start = max(ffe_ctl.search_start,
5686 first_logical_byte(fs_info, 0));
5687 ffe_ctl.search_start = max(ffe_ctl.search_start, hint_byte);
5688 if (ffe_ctl.search_start == hint_byte) {
5689 block_group = btrfs_lookup_block_group(fs_info,
5690 ffe_ctl.search_start);
5692 * we don't want to use the block group if it doesn't match our
5693 * allocation bits, or if its not cached.
5695 * However if we are re-searching with an ideal block group
5696 * picked out then we don't care that the block group is cached.
5698 if (block_group && block_group_bits(block_group, flags) &&
5699 block_group->cached != BTRFS_CACHE_NO) {
5700 down_read(&space_info->groups_sem);
5701 if (list_empty(&block_group->list) ||
5704 * someone is removing this block group,
5705 * we can't jump into the have_block_group
5706 * target because our list pointers are not
5709 btrfs_put_block_group(block_group);
5710 up_read(&space_info->groups_sem);
5712 ffe_ctl.index = btrfs_bg_flags_to_raid_index(
5713 block_group->flags);
5714 btrfs_lock_block_group(block_group, delalloc);
5715 goto have_block_group;
5717 } else if (block_group) {
5718 btrfs_put_block_group(block_group);
5722 ffe_ctl.have_caching_bg = false;
5723 if (ffe_ctl.index == btrfs_bg_flags_to_raid_index(flags) ||
5726 down_read(&space_info->groups_sem);
5727 list_for_each_entry(block_group,
5728 &space_info->block_groups[ffe_ctl.index], list) {
5729 /* If the block group is read-only, we can skip it entirely. */
5730 if (unlikely(block_group->ro))
5733 btrfs_grab_block_group(block_group, delalloc);
5734 ffe_ctl.search_start = block_group->key.objectid;
5737 * this can happen if we end up cycling through all the
5738 * raid types, but we want to make sure we only allocate
5739 * for the proper type.
5741 if (!block_group_bits(block_group, flags)) {
5742 u64 extra = BTRFS_BLOCK_GROUP_DUP |
5743 BTRFS_BLOCK_GROUP_RAID1_MASK |
5744 BTRFS_BLOCK_GROUP_RAID56_MASK |
5745 BTRFS_BLOCK_GROUP_RAID10;
5748 * if they asked for extra copies and this block group
5749 * doesn't provide them, bail. This does allow us to
5750 * fill raid0 from raid1.
5752 if ((flags & extra) && !(block_group->flags & extra))
5756 * This block group has different flags than we want.
5757 * It's possible that we have MIXED_GROUP flag but no
5758 * block group is mixed. Just skip such block group.
5760 btrfs_release_block_group(block_group, delalloc);
5765 ffe_ctl.cached = block_group_cache_done(block_group);
5766 if (unlikely(!ffe_ctl.cached)) {
5767 ffe_ctl.have_caching_bg = true;
5768 ret = cache_block_group(block_group, 0);
5773 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
5777 * Ok we want to try and use the cluster allocator, so
5780 if (last_ptr && use_cluster) {
5781 struct btrfs_block_group_cache *cluster_bg = NULL;
5783 ret = find_free_extent_clustered(block_group, last_ptr,
5784 &ffe_ctl, &cluster_bg);
5787 if (cluster_bg && cluster_bg != block_group) {
5788 btrfs_release_block_group(block_group,
5790 block_group = cluster_bg;
5793 } else if (ret == -EAGAIN) {
5794 goto have_block_group;
5795 } else if (ret > 0) {
5798 /* ret == -ENOENT case falls through */
5801 ret = find_free_extent_unclustered(block_group, last_ptr,
5804 goto have_block_group;
5807 /* ret == 0 case falls through */
5809 ffe_ctl.search_start = round_up(ffe_ctl.found_offset,
5810 fs_info->stripesize);
5812 /* move on to the next group */
5813 if (ffe_ctl.search_start + num_bytes >
5814 block_group->key.objectid + block_group->key.offset) {
5815 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
5820 if (ffe_ctl.found_offset < ffe_ctl.search_start)
5821 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
5822 ffe_ctl.search_start - ffe_ctl.found_offset);
5824 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
5825 num_bytes, delalloc);
5826 if (ret == -EAGAIN) {
5827 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
5831 btrfs_inc_block_group_reservations(block_group);
5833 /* we are all good, lets return */
5834 ins->objectid = ffe_ctl.search_start;
5835 ins->offset = num_bytes;
5837 trace_btrfs_reserve_extent(block_group, ffe_ctl.search_start,
5839 btrfs_release_block_group(block_group, delalloc);
5842 ffe_ctl.retry_clustered = false;
5843 ffe_ctl.retry_unclustered = false;
5844 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
5846 btrfs_release_block_group(block_group, delalloc);
5849 up_read(&space_info->groups_sem);
5851 ret = find_free_extent_update_loop(fs_info, last_ptr, ins, &ffe_ctl,
5852 full_search, use_cluster);
5856 if (ret == -ENOSPC) {
5858 * Use ffe_ctl->total_free_space as fallback if we can't find
5859 * any contiguous hole.
5861 if (!ffe_ctl.max_extent_size)
5862 ffe_ctl.max_extent_size = ffe_ctl.total_free_space;
5863 spin_lock(&space_info->lock);
5864 space_info->max_extent_size = ffe_ctl.max_extent_size;
5865 spin_unlock(&space_info->lock);
5866 ins->offset = ffe_ctl.max_extent_size;
5872 * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
5873 * hole that is at least as big as @num_bytes.
5875 * @root - The root that will contain this extent
5877 * @ram_bytes - The amount of space in ram that @num_bytes take. This
5878 * is used for accounting purposes. This value differs
5879 * from @num_bytes only in the case of compressed extents.
5881 * @num_bytes - Number of bytes to allocate on-disk.
5883 * @min_alloc_size - Indicates the minimum amount of space that the
5884 * allocator should try to satisfy. In some cases
5885 * @num_bytes may be larger than what is required and if
5886 * the filesystem is fragmented then allocation fails.
5887 * However, the presence of @min_alloc_size gives a
5888 * chance to try and satisfy the smaller allocation.
5890 * @empty_size - A hint that you plan on doing more COW. This is the
5891 * size in bytes the allocator should try to find free
5892 * next to the block it returns. This is just a hint and
5893 * may be ignored by the allocator.
5895 * @hint_byte - Hint to the allocator to start searching above the byte
5896 * address passed. It might be ignored.
5898 * @ins - This key is modified to record the found hole. It will
5899 * have the following values:
5900 * ins->objectid == start position
5901 * ins->flags = BTRFS_EXTENT_ITEM_KEY
5902 * ins->offset == the size of the hole.
5904 * @is_data - Boolean flag indicating whether an extent is
5905 * allocated for data (true) or metadata (false)
5907 * @delalloc - Boolean flag indicating whether this allocation is for
5908 * delalloc or not. If 'true' data_rwsem of block groups
5909 * is going to be acquired.
5912 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
5913 * case -ENOSPC is returned then @ins->offset will contain the size of the
5914 * largest available hole the allocator managed to find.
5916 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
5917 u64 num_bytes, u64 min_alloc_size,
5918 u64 empty_size, u64 hint_byte,
5919 struct btrfs_key *ins, int is_data, int delalloc)
5921 struct btrfs_fs_info *fs_info = root->fs_info;
5922 bool final_tried = num_bytes == min_alloc_size;
5926 flags = get_alloc_profile_by_root(root, is_data);
5928 WARN_ON(num_bytes < fs_info->sectorsize);
5929 ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
5930 hint_byte, ins, flags, delalloc);
5931 if (!ret && !is_data) {
5932 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
5933 } else if (ret == -ENOSPC) {
5934 if (!final_tried && ins->offset) {
5935 num_bytes = min(num_bytes >> 1, ins->offset);
5936 num_bytes = round_down(num_bytes,
5937 fs_info->sectorsize);
5938 num_bytes = max(num_bytes, min_alloc_size);
5939 ram_bytes = num_bytes;
5940 if (num_bytes == min_alloc_size)
5943 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
5944 struct btrfs_space_info *sinfo;
5946 sinfo = btrfs_find_space_info(fs_info, flags);
5948 "allocation failed flags %llu, wanted %llu",
5951 btrfs_dump_space_info(fs_info, sinfo,
5959 static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
5961 int pin, int delalloc)
5963 struct btrfs_block_group_cache *cache;
5966 cache = btrfs_lookup_block_group(fs_info, start);
5968 btrfs_err(fs_info, "Unable to find block group for %llu",
5974 pin_down_extent(cache, start, len, 1);
5976 if (btrfs_test_opt(fs_info, DISCARD))
5977 ret = btrfs_discard_extent(fs_info, start, len, NULL);
5978 btrfs_add_free_space(cache, start, len);
5979 btrfs_free_reserved_bytes(cache, len, delalloc);
5980 trace_btrfs_reserved_extent_free(fs_info, start, len);
5983 btrfs_put_block_group(cache);
5987 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
5988 u64 start, u64 len, int delalloc)
5990 return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
5993 int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
5996 return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
5999 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6000 u64 parent, u64 root_objectid,
6001 u64 flags, u64 owner, u64 offset,
6002 struct btrfs_key *ins, int ref_mod)
6004 struct btrfs_fs_info *fs_info = trans->fs_info;
6006 struct btrfs_extent_item *extent_item;
6007 struct btrfs_extent_inline_ref *iref;
6008 struct btrfs_path *path;
6009 struct extent_buffer *leaf;
6014 type = BTRFS_SHARED_DATA_REF_KEY;
6016 type = BTRFS_EXTENT_DATA_REF_KEY;
6018 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
6020 path = btrfs_alloc_path();
6024 path->leave_spinning = 1;
6025 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6028 btrfs_free_path(path);
6032 leaf = path->nodes[0];
6033 extent_item = btrfs_item_ptr(leaf, path->slots[0],
6034 struct btrfs_extent_item);
6035 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
6036 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6037 btrfs_set_extent_flags(leaf, extent_item,
6038 flags | BTRFS_EXTENT_FLAG_DATA);
6040 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
6041 btrfs_set_extent_inline_ref_type(leaf, iref, type);
6043 struct btrfs_shared_data_ref *ref;
6044 ref = (struct btrfs_shared_data_ref *)(iref + 1);
6045 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6046 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
6048 struct btrfs_extent_data_ref *ref;
6049 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
6050 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
6051 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
6052 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
6053 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
6056 btrfs_mark_buffer_dirty(path->nodes[0]);
6057 btrfs_free_path(path);
6059 ret = remove_from_free_space_tree(trans, ins->objectid, ins->offset);
6063 ret = update_block_group(trans, ins->objectid, ins->offset, 1);
6064 if (ret) { /* -ENOENT, logic error */
6065 btrfs_err(fs_info, "update block group failed for %llu %llu",
6066 ins->objectid, ins->offset);
6069 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
6073 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
6074 struct btrfs_delayed_ref_node *node,
6075 struct btrfs_delayed_extent_op *extent_op)
6077 struct btrfs_fs_info *fs_info = trans->fs_info;
6079 struct btrfs_extent_item *extent_item;
6080 struct btrfs_key extent_key;
6081 struct btrfs_tree_block_info *block_info;
6082 struct btrfs_extent_inline_ref *iref;
6083 struct btrfs_path *path;
6084 struct extent_buffer *leaf;
6085 struct btrfs_delayed_tree_ref *ref;
6086 u32 size = sizeof(*extent_item) + sizeof(*iref);
6088 u64 flags = extent_op->flags_to_set;
6089 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
6091 ref = btrfs_delayed_node_to_tree_ref(node);
6093 extent_key.objectid = node->bytenr;
6094 if (skinny_metadata) {
6095 extent_key.offset = ref->level;
6096 extent_key.type = BTRFS_METADATA_ITEM_KEY;
6097 num_bytes = fs_info->nodesize;
6099 extent_key.offset = node->num_bytes;
6100 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
6101 size += sizeof(*block_info);
6102 num_bytes = node->num_bytes;
6105 path = btrfs_alloc_path();
6109 path->leave_spinning = 1;
6110 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6113 btrfs_free_path(path);
6117 leaf = path->nodes[0];
6118 extent_item = btrfs_item_ptr(leaf, path->slots[0],
6119 struct btrfs_extent_item);
6120 btrfs_set_extent_refs(leaf, extent_item, 1);
6121 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6122 btrfs_set_extent_flags(leaf, extent_item,
6123 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
6125 if (skinny_metadata) {
6126 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
6128 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
6129 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
6130 btrfs_set_tree_block_level(leaf, block_info, ref->level);
6131 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
6134 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
6135 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
6136 btrfs_set_extent_inline_ref_type(leaf, iref,
6137 BTRFS_SHARED_BLOCK_REF_KEY);
6138 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
6140 btrfs_set_extent_inline_ref_type(leaf, iref,
6141 BTRFS_TREE_BLOCK_REF_KEY);
6142 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
6145 btrfs_mark_buffer_dirty(leaf);
6146 btrfs_free_path(path);
6148 ret = remove_from_free_space_tree(trans, extent_key.objectid,
6153 ret = update_block_group(trans, extent_key.objectid,
6154 fs_info->nodesize, 1);
6155 if (ret) { /* -ENOENT, logic error */
6156 btrfs_err(fs_info, "update block group failed for %llu %llu",
6157 extent_key.objectid, extent_key.offset);
6161 trace_btrfs_reserved_extent_alloc(fs_info, extent_key.objectid,
6166 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6167 struct btrfs_root *root, u64 owner,
6168 u64 offset, u64 ram_bytes,
6169 struct btrfs_key *ins)
6171 struct btrfs_ref generic_ref = { 0 };
6174 BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
6176 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
6177 ins->objectid, ins->offset, 0);
6178 btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner, offset);
6179 btrfs_ref_tree_mod(root->fs_info, &generic_ref);
6180 ret = btrfs_add_delayed_data_ref(trans, &generic_ref,
6181 ram_bytes, NULL, NULL);
6186 * this is used by the tree logging recovery code. It records that
6187 * an extent has been allocated and makes sure to clear the free
6188 * space cache bits as well
6190 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
6191 u64 root_objectid, u64 owner, u64 offset,
6192 struct btrfs_key *ins)
6194 struct btrfs_fs_info *fs_info = trans->fs_info;
6196 struct btrfs_block_group_cache *block_group;
6197 struct btrfs_space_info *space_info;
6200 * Mixed block groups will exclude before processing the log so we only
6201 * need to do the exclude dance if this fs isn't mixed.
6203 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
6204 ret = __exclude_logged_extent(fs_info, ins->objectid,
6210 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
6214 space_info = block_group->space_info;
6215 spin_lock(&space_info->lock);
6216 spin_lock(&block_group->lock);
6217 space_info->bytes_reserved += ins->offset;
6218 block_group->reserved += ins->offset;
6219 spin_unlock(&block_group->lock);
6220 spin_unlock(&space_info->lock);
6222 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
6224 btrfs_put_block_group(block_group);
6228 static struct extent_buffer *
6229 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
6230 u64 bytenr, int level, u64 owner)
6232 struct btrfs_fs_info *fs_info = root->fs_info;
6233 struct extent_buffer *buf;
6235 buf = btrfs_find_create_tree_block(fs_info, bytenr);
6240 * Extra safety check in case the extent tree is corrupted and extent
6241 * allocator chooses to use a tree block which is already used and
6244 if (buf->lock_owner == current->pid) {
6245 btrfs_err_rl(fs_info,
6246 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
6247 buf->start, btrfs_header_owner(buf), current->pid);
6248 free_extent_buffer(buf);
6249 return ERR_PTR(-EUCLEAN);
6252 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
6253 btrfs_tree_lock(buf);
6254 btrfs_clean_tree_block(buf);
6255 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
6257 btrfs_set_lock_blocking_write(buf);
6258 set_extent_buffer_uptodate(buf);
6260 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
6261 btrfs_set_header_level(buf, level);
6262 btrfs_set_header_bytenr(buf, buf->start);
6263 btrfs_set_header_generation(buf, trans->transid);
6264 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
6265 btrfs_set_header_owner(buf, owner);
6266 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
6267 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
6268 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
6269 buf->log_index = root->log_transid % 2;
6271 * we allow two log transactions at a time, use different
6272 * EXTENT bit to differentiate dirty pages.
6274 if (buf->log_index == 0)
6275 set_extent_dirty(&root->dirty_log_pages, buf->start,
6276 buf->start + buf->len - 1, GFP_NOFS);
6278 set_extent_new(&root->dirty_log_pages, buf->start,
6279 buf->start + buf->len - 1);
6281 buf->log_index = -1;
6282 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
6283 buf->start + buf->len - 1, GFP_NOFS);
6285 trans->dirty = true;
6286 /* this returns a buffer locked for blocking */
6291 * finds a free extent and does all the dirty work required for allocation
6292 * returns the tree buffer or an ERR_PTR on error.
6294 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
6295 struct btrfs_root *root,
6296 u64 parent, u64 root_objectid,
6297 const struct btrfs_disk_key *key,
6298 int level, u64 hint,
6301 struct btrfs_fs_info *fs_info = root->fs_info;
6302 struct btrfs_key ins;
6303 struct btrfs_block_rsv *block_rsv;
6304 struct extent_buffer *buf;
6305 struct btrfs_delayed_extent_op *extent_op;
6306 struct btrfs_ref generic_ref = { 0 };
6309 u32 blocksize = fs_info->nodesize;
6310 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
6312 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6313 if (btrfs_is_testing(fs_info)) {
6314 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
6315 level, root_objectid);
6317 root->alloc_bytenr += blocksize;
6322 block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
6323 if (IS_ERR(block_rsv))
6324 return ERR_CAST(block_rsv);
6326 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
6327 empty_size, hint, &ins, 0, 0);
6331 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
6335 goto out_free_reserved;
6338 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
6340 parent = ins.objectid;
6341 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
6345 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
6346 extent_op = btrfs_alloc_delayed_extent_op();
6352 memcpy(&extent_op->key, key, sizeof(extent_op->key));
6354 memset(&extent_op->key, 0, sizeof(extent_op->key));
6355 extent_op->flags_to_set = flags;
6356 extent_op->update_key = skinny_metadata ? false : true;
6357 extent_op->update_flags = true;
6358 extent_op->is_data = false;
6359 extent_op->level = level;
6361 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
6362 ins.objectid, ins.offset, parent);
6363 generic_ref.real_root = root->root_key.objectid;
6364 btrfs_init_tree_ref(&generic_ref, level, root_objectid);
6365 btrfs_ref_tree_mod(fs_info, &generic_ref);
6366 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref,
6367 extent_op, NULL, NULL);
6369 goto out_free_delayed;
6374 btrfs_free_delayed_extent_op(extent_op);
6376 free_extent_buffer(buf);
6378 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
6380 btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
6381 return ERR_PTR(ret);
6384 struct walk_control {
6385 u64 refs[BTRFS_MAX_LEVEL];
6386 u64 flags[BTRFS_MAX_LEVEL];
6387 struct btrfs_key update_progress;
6388 struct btrfs_key drop_progress;
6400 #define DROP_REFERENCE 1
6401 #define UPDATE_BACKREF 2
6403 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
6404 struct btrfs_root *root,
6405 struct walk_control *wc,
6406 struct btrfs_path *path)
6408 struct btrfs_fs_info *fs_info = root->fs_info;
6414 struct btrfs_key key;
6415 struct extent_buffer *eb;
6420 if (path->slots[wc->level] < wc->reada_slot) {
6421 wc->reada_count = wc->reada_count * 2 / 3;
6422 wc->reada_count = max(wc->reada_count, 2);
6424 wc->reada_count = wc->reada_count * 3 / 2;
6425 wc->reada_count = min_t(int, wc->reada_count,
6426 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
6429 eb = path->nodes[wc->level];
6430 nritems = btrfs_header_nritems(eb);
6432 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
6433 if (nread >= wc->reada_count)
6437 bytenr = btrfs_node_blockptr(eb, slot);
6438 generation = btrfs_node_ptr_generation(eb, slot);
6440 if (slot == path->slots[wc->level])
6443 if (wc->stage == UPDATE_BACKREF &&
6444 generation <= root->root_key.offset)
6447 /* We don't lock the tree block, it's OK to be racy here */
6448 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
6449 wc->level - 1, 1, &refs,
6451 /* We don't care about errors in readahead. */
6456 if (wc->stage == DROP_REFERENCE) {
6460 if (wc->level == 1 &&
6461 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6463 if (!wc->update_ref ||
6464 generation <= root->root_key.offset)
6466 btrfs_node_key_to_cpu(eb, &key, slot);
6467 ret = btrfs_comp_cpu_keys(&key,
6468 &wc->update_progress);
6472 if (wc->level == 1 &&
6473 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6477 readahead_tree_block(fs_info, bytenr);
6480 wc->reada_slot = slot;
6484 * helper to process tree block while walking down the tree.
6486 * when wc->stage == UPDATE_BACKREF, this function updates
6487 * back refs for pointers in the block.
6489 * NOTE: return value 1 means we should stop walking down.
6491 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
6492 struct btrfs_root *root,
6493 struct btrfs_path *path,
6494 struct walk_control *wc, int lookup_info)
6496 struct btrfs_fs_info *fs_info = root->fs_info;
6497 int level = wc->level;
6498 struct extent_buffer *eb = path->nodes[level];
6499 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
6502 if (wc->stage == UPDATE_BACKREF &&
6503 btrfs_header_owner(eb) != root->root_key.objectid)
6507 * when reference count of tree block is 1, it won't increase
6508 * again. once full backref flag is set, we never clear it.
6511 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
6512 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
6513 BUG_ON(!path->locks[level]);
6514 ret = btrfs_lookup_extent_info(trans, fs_info,
6515 eb->start, level, 1,
6518 BUG_ON(ret == -ENOMEM);
6521 BUG_ON(wc->refs[level] == 0);
6524 if (wc->stage == DROP_REFERENCE) {
6525 if (wc->refs[level] > 1)
6528 if (path->locks[level] && !wc->keep_locks) {
6529 btrfs_tree_unlock_rw(eb, path->locks[level]);
6530 path->locks[level] = 0;
6535 /* wc->stage == UPDATE_BACKREF */
6536 if (!(wc->flags[level] & flag)) {
6537 BUG_ON(!path->locks[level]);
6538 ret = btrfs_inc_ref(trans, root, eb, 1);
6539 BUG_ON(ret); /* -ENOMEM */
6540 ret = btrfs_dec_ref(trans, root, eb, 0);
6541 BUG_ON(ret); /* -ENOMEM */
6542 ret = btrfs_set_disk_extent_flags(trans, eb->start,
6544 btrfs_header_level(eb), 0);
6545 BUG_ON(ret); /* -ENOMEM */
6546 wc->flags[level] |= flag;
6550 * the block is shared by multiple trees, so it's not good to
6551 * keep the tree lock
6553 if (path->locks[level] && level > 0) {
6554 btrfs_tree_unlock_rw(eb, path->locks[level]);
6555 path->locks[level] = 0;
6561 * This is used to verify a ref exists for this root to deal with a bug where we
6562 * would have a drop_progress key that hadn't been updated properly.
6564 static int check_ref_exists(struct btrfs_trans_handle *trans,
6565 struct btrfs_root *root, u64 bytenr, u64 parent,
6568 struct btrfs_path *path;
6569 struct btrfs_extent_inline_ref *iref;
6572 path = btrfs_alloc_path();
6576 ret = lookup_extent_backref(trans, path, &iref, bytenr,
6577 root->fs_info->nodesize, parent,
6578 root->root_key.objectid, level, 0);
6579 btrfs_free_path(path);
6588 * helper to process tree block pointer.
6590 * when wc->stage == DROP_REFERENCE, this function checks
6591 * reference count of the block pointed to. if the block
6592 * is shared and we need update back refs for the subtree
6593 * rooted at the block, this function changes wc->stage to
6594 * UPDATE_BACKREF. if the block is shared and there is no
6595 * need to update back, this function drops the reference
6598 * NOTE: return value 1 means we should stop walking down.
6600 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
6601 struct btrfs_root *root,
6602 struct btrfs_path *path,
6603 struct walk_control *wc, int *lookup_info)
6605 struct btrfs_fs_info *fs_info = root->fs_info;
6609 struct btrfs_key key;
6610 struct btrfs_key first_key;
6611 struct btrfs_ref ref = { 0 };
6612 struct extent_buffer *next;
6613 int level = wc->level;
6616 bool need_account = false;
6618 generation = btrfs_node_ptr_generation(path->nodes[level],
6619 path->slots[level]);
6621 * if the lower level block was created before the snapshot
6622 * was created, we know there is no need to update back refs
6625 if (wc->stage == UPDATE_BACKREF &&
6626 generation <= root->root_key.offset) {
6631 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
6632 btrfs_node_key_to_cpu(path->nodes[level], &first_key,
6633 path->slots[level]);
6635 next = find_extent_buffer(fs_info, bytenr);
6637 next = btrfs_find_create_tree_block(fs_info, bytenr);
6639 return PTR_ERR(next);
6641 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
6645 btrfs_tree_lock(next);
6646 btrfs_set_lock_blocking_write(next);
6648 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
6649 &wc->refs[level - 1],
6650 &wc->flags[level - 1]);
6654 if (unlikely(wc->refs[level - 1] == 0)) {
6655 btrfs_err(fs_info, "Missing references.");
6661 if (wc->stage == DROP_REFERENCE) {
6662 if (wc->refs[level - 1] > 1) {
6663 need_account = true;
6665 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6668 if (!wc->update_ref ||
6669 generation <= root->root_key.offset)
6672 btrfs_node_key_to_cpu(path->nodes[level], &key,
6673 path->slots[level]);
6674 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
6678 wc->stage = UPDATE_BACKREF;
6679 wc->shared_level = level - 1;
6683 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6687 if (!btrfs_buffer_uptodate(next, generation, 0)) {
6688 btrfs_tree_unlock(next);
6689 free_extent_buffer(next);
6695 if (reada && level == 1)
6696 reada_walk_down(trans, root, wc, path);
6697 next = read_tree_block(fs_info, bytenr, generation, level - 1,
6700 return PTR_ERR(next);
6701 } else if (!extent_buffer_uptodate(next)) {
6702 free_extent_buffer(next);
6705 btrfs_tree_lock(next);
6706 btrfs_set_lock_blocking_write(next);
6710 ASSERT(level == btrfs_header_level(next));
6711 if (level != btrfs_header_level(next)) {
6712 btrfs_err(root->fs_info, "mismatched level");
6716 path->nodes[level] = next;
6717 path->slots[level] = 0;
6718 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
6724 wc->refs[level - 1] = 0;
6725 wc->flags[level - 1] = 0;
6726 if (wc->stage == DROP_REFERENCE) {
6727 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
6728 parent = path->nodes[level]->start;
6730 ASSERT(root->root_key.objectid ==
6731 btrfs_header_owner(path->nodes[level]));
6732 if (root->root_key.objectid !=
6733 btrfs_header_owner(path->nodes[level])) {
6734 btrfs_err(root->fs_info,
6735 "mismatched block owner");
6743 * If we had a drop_progress we need to verify the refs are set
6744 * as expected. If we find our ref then we know that from here
6745 * on out everything should be correct, and we can clear the
6748 if (wc->restarted) {
6749 ret = check_ref_exists(trans, root, bytenr, parent,
6760 * Reloc tree doesn't contribute to qgroup numbers, and we have
6761 * already accounted them at merge time (replace_path),
6762 * thus we could skip expensive subtree trace here.
6764 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
6766 ret = btrfs_qgroup_trace_subtree(trans, next,
6767 generation, level - 1);
6769 btrfs_err_rl(fs_info,
6770 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
6776 * We need to update the next key in our walk control so we can
6777 * update the drop_progress key accordingly. We don't care if
6778 * find_next_key doesn't find a key because that means we're at
6779 * the end and are going to clean up now.
6781 wc->drop_level = level;
6782 find_next_key(path, level, &wc->drop_progress);
6784 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
6785 fs_info->nodesize, parent);
6786 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid);
6787 ret = btrfs_free_extent(trans, &ref);
6796 btrfs_tree_unlock(next);
6797 free_extent_buffer(next);
6803 * helper to process tree block while walking up the tree.
6805 * when wc->stage == DROP_REFERENCE, this function drops
6806 * reference count on the block.
6808 * when wc->stage == UPDATE_BACKREF, this function changes
6809 * wc->stage back to DROP_REFERENCE if we changed wc->stage
6810 * to UPDATE_BACKREF previously while processing the block.
6812 * NOTE: return value 1 means we should stop walking up.
6814 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
6815 struct btrfs_root *root,
6816 struct btrfs_path *path,
6817 struct walk_control *wc)
6819 struct btrfs_fs_info *fs_info = root->fs_info;
6821 int level = wc->level;
6822 struct extent_buffer *eb = path->nodes[level];
6825 if (wc->stage == UPDATE_BACKREF) {
6826 BUG_ON(wc->shared_level < level);
6827 if (level < wc->shared_level)
6830 ret = find_next_key(path, level + 1, &wc->update_progress);
6834 wc->stage = DROP_REFERENCE;
6835 wc->shared_level = -1;
6836 path->slots[level] = 0;
6839 * check reference count again if the block isn't locked.
6840 * we should start walking down the tree again if reference
6843 if (!path->locks[level]) {
6845 btrfs_tree_lock(eb);
6846 btrfs_set_lock_blocking_write(eb);
6847 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
6849 ret = btrfs_lookup_extent_info(trans, fs_info,
6850 eb->start, level, 1,
6854 btrfs_tree_unlock_rw(eb, path->locks[level]);
6855 path->locks[level] = 0;
6858 BUG_ON(wc->refs[level] == 0);
6859 if (wc->refs[level] == 1) {
6860 btrfs_tree_unlock_rw(eb, path->locks[level]);
6861 path->locks[level] = 0;
6867 /* wc->stage == DROP_REFERENCE */
6868 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
6870 if (wc->refs[level] == 1) {
6872 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6873 ret = btrfs_dec_ref(trans, root, eb, 1);
6875 ret = btrfs_dec_ref(trans, root, eb, 0);
6876 BUG_ON(ret); /* -ENOMEM */
6877 if (is_fstree(root->root_key.objectid)) {
6878 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
6880 btrfs_err_rl(fs_info,
6881 "error %d accounting leaf items, quota is out of sync, rescan required",
6886 /* make block locked assertion in btrfs_clean_tree_block happy */
6887 if (!path->locks[level] &&
6888 btrfs_header_generation(eb) == trans->transid) {
6889 btrfs_tree_lock(eb);
6890 btrfs_set_lock_blocking_write(eb);
6891 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
6893 btrfs_clean_tree_block(eb);
6896 if (eb == root->node) {
6897 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6899 else if (root->root_key.objectid != btrfs_header_owner(eb))
6900 goto owner_mismatch;
6902 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6903 parent = path->nodes[level + 1]->start;
6904 else if (root->root_key.objectid !=
6905 btrfs_header_owner(path->nodes[level + 1]))
6906 goto owner_mismatch;
6909 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
6911 wc->refs[level] = 0;
6912 wc->flags[level] = 0;
6916 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
6917 btrfs_header_owner(eb), root->root_key.objectid);
6921 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
6922 struct btrfs_root *root,
6923 struct btrfs_path *path,
6924 struct walk_control *wc)
6926 int level = wc->level;
6927 int lookup_info = 1;
6930 while (level >= 0) {
6931 ret = walk_down_proc(trans, root, path, wc, lookup_info);
6938 if (path->slots[level] >=
6939 btrfs_header_nritems(path->nodes[level]))
6942 ret = do_walk_down(trans, root, path, wc, &lookup_info);
6944 path->slots[level]++;
6953 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
6954 struct btrfs_root *root,
6955 struct btrfs_path *path,
6956 struct walk_control *wc, int max_level)
6958 int level = wc->level;
6961 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
6962 while (level < max_level && path->nodes[level]) {
6964 if (path->slots[level] + 1 <
6965 btrfs_header_nritems(path->nodes[level])) {
6966 path->slots[level]++;
6969 ret = walk_up_proc(trans, root, path, wc);
6975 if (path->locks[level]) {
6976 btrfs_tree_unlock_rw(path->nodes[level],
6977 path->locks[level]);
6978 path->locks[level] = 0;
6980 free_extent_buffer(path->nodes[level]);
6981 path->nodes[level] = NULL;
6989 * drop a subvolume tree.
6991 * this function traverses the tree freeing any blocks that only
6992 * referenced by the tree.
6994 * when a shared tree block is found. this function decreases its
6995 * reference count by one. if update_ref is true, this function
6996 * also make sure backrefs for the shared block and all lower level
6997 * blocks are properly updated.
6999 * If called with for_reloc == 0, may exit early with -EAGAIN
7001 int btrfs_drop_snapshot(struct btrfs_root *root,
7002 struct btrfs_block_rsv *block_rsv, int update_ref,
7005 struct btrfs_fs_info *fs_info = root->fs_info;
7006 struct btrfs_path *path;
7007 struct btrfs_trans_handle *trans;
7008 struct btrfs_root *tree_root = fs_info->tree_root;
7009 struct btrfs_root_item *root_item = &root->root_item;
7010 struct walk_control *wc;
7011 struct btrfs_key key;
7015 bool root_dropped = false;
7017 btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
7019 path = btrfs_alloc_path();
7025 wc = kzalloc(sizeof(*wc), GFP_NOFS);
7027 btrfs_free_path(path);
7032 trans = btrfs_start_transaction(tree_root, 0);
7033 if (IS_ERR(trans)) {
7034 err = PTR_ERR(trans);
7038 err = btrfs_run_delayed_items(trans);
7043 trans->block_rsv = block_rsv;
7046 * This will help us catch people modifying the fs tree while we're
7047 * dropping it. It is unsafe to mess with the fs tree while it's being
7048 * dropped as we unlock the root node and parent nodes as we walk down
7049 * the tree, assuming nothing will change. If something does change
7050 * then we'll have stale information and drop references to blocks we've
7053 set_bit(BTRFS_ROOT_DELETING, &root->state);
7054 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
7055 level = btrfs_header_level(root->node);
7056 path->nodes[level] = btrfs_lock_root_node(root);
7057 btrfs_set_lock_blocking_write(path->nodes[level]);
7058 path->slots[level] = 0;
7059 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7060 memset(&wc->update_progress, 0,
7061 sizeof(wc->update_progress));
7063 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
7064 memcpy(&wc->update_progress, &key,
7065 sizeof(wc->update_progress));
7067 level = root_item->drop_level;
7069 path->lowest_level = level;
7070 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7071 path->lowest_level = 0;
7079 * unlock our path, this is safe because only this
7080 * function is allowed to delete this snapshot
7082 btrfs_unlock_up_safe(path, 0);
7084 level = btrfs_header_level(root->node);
7086 btrfs_tree_lock(path->nodes[level]);
7087 btrfs_set_lock_blocking_write(path->nodes[level]);
7088 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7090 ret = btrfs_lookup_extent_info(trans, fs_info,
7091 path->nodes[level]->start,
7092 level, 1, &wc->refs[level],
7098 BUG_ON(wc->refs[level] == 0);
7100 if (level == root_item->drop_level)
7103 btrfs_tree_unlock(path->nodes[level]);
7104 path->locks[level] = 0;
7105 WARN_ON(wc->refs[level] != 1);
7110 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
7112 wc->shared_level = -1;
7113 wc->stage = DROP_REFERENCE;
7114 wc->update_ref = update_ref;
7116 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
7120 ret = walk_down_tree(trans, root, path, wc);
7126 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
7133 BUG_ON(wc->stage != DROP_REFERENCE);
7137 if (wc->stage == DROP_REFERENCE) {
7138 wc->drop_level = wc->level;
7139 btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
7141 path->slots[wc->drop_level]);
7143 btrfs_cpu_key_to_disk(&root_item->drop_progress,
7144 &wc->drop_progress);
7145 root_item->drop_level = wc->drop_level;
7147 BUG_ON(wc->level == 0);
7148 if (btrfs_should_end_transaction(trans) ||
7149 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
7150 ret = btrfs_update_root(trans, tree_root,
7154 btrfs_abort_transaction(trans, ret);
7159 btrfs_end_transaction_throttle(trans);
7160 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
7161 btrfs_debug(fs_info,
7162 "drop snapshot early exit");
7167 trans = btrfs_start_transaction(tree_root, 0);
7168 if (IS_ERR(trans)) {
7169 err = PTR_ERR(trans);
7173 trans->block_rsv = block_rsv;
7176 btrfs_release_path(path);
7180 ret = btrfs_del_root(trans, &root->root_key);
7182 btrfs_abort_transaction(trans, ret);
7187 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
7188 ret = btrfs_find_root(tree_root, &root->root_key, path,
7191 btrfs_abort_transaction(trans, ret);
7194 } else if (ret > 0) {
7195 /* if we fail to delete the orphan item this time
7196 * around, it'll get picked up the next time.
7198 * The most common failure here is just -ENOENT.
7200 btrfs_del_orphan_item(trans, tree_root,
7201 root->root_key.objectid);
7205 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
7206 btrfs_add_dropped_root(trans, root);
7208 free_extent_buffer(root->node);
7209 free_extent_buffer(root->commit_root);
7210 btrfs_put_fs_root(root);
7212 root_dropped = true;
7214 btrfs_end_transaction_throttle(trans);
7217 btrfs_free_path(path);
7220 * So if we need to stop dropping the snapshot for whatever reason we
7221 * need to make sure to add it back to the dead root list so that we
7222 * keep trying to do the work later. This also cleans up roots if we
7223 * don't have it in the radix (like when we recover after a power fail
7224 * or unmount) so we don't leak memory.
7226 if (!for_reloc && !root_dropped)
7227 btrfs_add_dead_root(root);
7228 if (err && err != -EAGAIN)
7229 btrfs_handle_fs_error(fs_info, err, NULL);
7234 * drop subtree rooted at tree block 'node'.
7236 * NOTE: this function will unlock and release tree block 'node'
7237 * only used by relocation code
7239 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
7240 struct btrfs_root *root,
7241 struct extent_buffer *node,
7242 struct extent_buffer *parent)
7244 struct btrfs_fs_info *fs_info = root->fs_info;
7245 struct btrfs_path *path;
7246 struct walk_control *wc;
7252 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
7254 path = btrfs_alloc_path();
7258 wc = kzalloc(sizeof(*wc), GFP_NOFS);
7260 btrfs_free_path(path);
7264 btrfs_assert_tree_locked(parent);
7265 parent_level = btrfs_header_level(parent);
7266 extent_buffer_get(parent);
7267 path->nodes[parent_level] = parent;
7268 path->slots[parent_level] = btrfs_header_nritems(parent);
7270 btrfs_assert_tree_locked(node);
7271 level = btrfs_header_level(node);
7272 path->nodes[level] = node;
7273 path->slots[level] = 0;
7274 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7276 wc->refs[parent_level] = 1;
7277 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
7279 wc->shared_level = -1;
7280 wc->stage = DROP_REFERENCE;
7283 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
7286 wret = walk_down_tree(trans, root, path, wc);
7292 wret = walk_up_tree(trans, root, path, wc, parent_level);
7300 btrfs_free_path(path);
7304 static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
7310 * if restripe for this chunk_type is on pick target profile and
7311 * return, otherwise do the usual balance
7313 stripped = get_restripe_target(fs_info, flags);
7315 return extended_to_chunk(stripped);
7317 num_devices = fs_info->fs_devices->rw_devices;
7319 stripped = BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID56_MASK |
7320 BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10;
7322 if (num_devices == 1) {
7323 stripped |= BTRFS_BLOCK_GROUP_DUP;
7324 stripped = flags & ~stripped;
7326 /* turn raid0 into single device chunks */
7327 if (flags & BTRFS_BLOCK_GROUP_RAID0)
7330 /* turn mirroring into duplication */
7331 if (flags & (BTRFS_BLOCK_GROUP_RAID1_MASK |
7332 BTRFS_BLOCK_GROUP_RAID10))
7333 return stripped | BTRFS_BLOCK_GROUP_DUP;
7335 /* they already had raid on here, just return */
7336 if (flags & stripped)
7339 stripped |= BTRFS_BLOCK_GROUP_DUP;
7340 stripped = flags & ~stripped;
7342 /* switch duplicated blocks with raid1 */
7343 if (flags & BTRFS_BLOCK_GROUP_DUP)
7344 return stripped | BTRFS_BLOCK_GROUP_RAID1;
7346 /* this is drive concat, leave it alone */
7352 static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
7354 struct btrfs_space_info *sinfo = cache->space_info;
7357 u64 min_allocable_bytes;
7361 * We need some metadata space and system metadata space for
7362 * allocating chunks in some corner cases until we force to set
7363 * it to be readonly.
7366 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
7368 min_allocable_bytes = SZ_1M;
7370 min_allocable_bytes = 0;
7372 spin_lock(&sinfo->lock);
7373 spin_lock(&cache->lock);
7381 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
7382 cache->bytes_super - btrfs_block_group_used(&cache->item);
7383 sinfo_used = btrfs_space_info_used(sinfo, true);
7385 if (sinfo_used + num_bytes + min_allocable_bytes <=
7386 sinfo->total_bytes) {
7387 sinfo->bytes_readonly += num_bytes;
7389 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
7393 spin_unlock(&cache->lock);
7394 spin_unlock(&sinfo->lock);
7395 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
7396 btrfs_info(cache->fs_info,
7397 "unable to make block group %llu ro",
7398 cache->key.objectid);
7399 btrfs_info(cache->fs_info,
7400 "sinfo_used=%llu bg_num_bytes=%llu min_allocable=%llu",
7401 sinfo_used, num_bytes, min_allocable_bytes);
7402 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
7407 int btrfs_inc_block_group_ro(struct btrfs_block_group_cache *cache)
7410 struct btrfs_fs_info *fs_info = cache->fs_info;
7411 struct btrfs_trans_handle *trans;
7416 trans = btrfs_join_transaction(fs_info->extent_root);
7418 return PTR_ERR(trans);
7421 * we're not allowed to set block groups readonly after the dirty
7422 * block groups cache has started writing. If it already started,
7423 * back off and let this transaction commit
7425 mutex_lock(&fs_info->ro_block_group_mutex);
7426 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
7427 u64 transid = trans->transid;
7429 mutex_unlock(&fs_info->ro_block_group_mutex);
7430 btrfs_end_transaction(trans);
7432 ret = btrfs_wait_for_commit(fs_info, transid);
7439 * if we are changing raid levels, try to allocate a corresponding
7440 * block group with the new raid level.
7442 alloc_flags = update_block_group_flags(fs_info, cache->flags);
7443 if (alloc_flags != cache->flags) {
7444 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
7446 * ENOSPC is allowed here, we may have enough space
7447 * already allocated at the new raid level to
7456 ret = inc_block_group_ro(cache, 0);
7459 alloc_flags = get_alloc_profile(fs_info, cache->space_info->flags);
7460 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
7463 ret = inc_block_group_ro(cache, 0);
7465 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
7466 alloc_flags = update_block_group_flags(fs_info, cache->flags);
7467 mutex_lock(&fs_info->chunk_mutex);
7468 check_system_chunk(trans, alloc_flags);
7469 mutex_unlock(&fs_info->chunk_mutex);
7471 mutex_unlock(&fs_info->ro_block_group_mutex);
7473 btrfs_end_transaction(trans);
7477 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
7479 u64 alloc_flags = get_alloc_profile(trans->fs_info, type);
7481 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
7485 * helper to account the unused space of all the readonly block group in the
7486 * space_info. takes mirrors into account.
7488 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
7490 struct btrfs_block_group_cache *block_group;
7494 /* It's df, we don't care if it's racy */
7495 if (list_empty(&sinfo->ro_bgs))
7498 spin_lock(&sinfo->lock);
7499 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
7500 spin_lock(&block_group->lock);
7502 if (!block_group->ro) {
7503 spin_unlock(&block_group->lock);
7507 factor = btrfs_bg_type_to_factor(block_group->flags);
7508 free_bytes += (block_group->key.offset -
7509 btrfs_block_group_used(&block_group->item)) *
7512 spin_unlock(&block_group->lock);
7514 spin_unlock(&sinfo->lock);
7519 void btrfs_dec_block_group_ro(struct btrfs_block_group_cache *cache)
7521 struct btrfs_space_info *sinfo = cache->space_info;
7526 spin_lock(&sinfo->lock);
7527 spin_lock(&cache->lock);
7529 num_bytes = cache->key.offset - cache->reserved -
7530 cache->pinned - cache->bytes_super -
7531 btrfs_block_group_used(&cache->item);
7532 sinfo->bytes_readonly -= num_bytes;
7533 list_del_init(&cache->ro_list);
7535 spin_unlock(&cache->lock);
7536 spin_unlock(&sinfo->lock);
7540 * Checks to see if it's even possible to relocate this block group.
7542 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
7543 * ok to go ahead and try.
7545 int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
7547 struct btrfs_block_group_cache *block_group;
7548 struct btrfs_space_info *space_info;
7549 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7550 struct btrfs_device *device;
7560 debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
7562 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7564 /* odd, couldn't find the block group, leave it alone */
7568 "can't find block group for bytenr %llu",
7573 min_free = btrfs_block_group_used(&block_group->item);
7575 /* no bytes used, we're good */
7579 space_info = block_group->space_info;
7580 spin_lock(&space_info->lock);
7582 full = space_info->full;
7585 * if this is the last block group we have in this space, we can't
7586 * relocate it unless we're able to allocate a new chunk below.
7588 * Otherwise, we need to make sure we have room in the space to handle
7589 * all of the extents from this block group. If we can, we're good
7591 if ((space_info->total_bytes != block_group->key.offset) &&
7592 (btrfs_space_info_used(space_info, false) + min_free <
7593 space_info->total_bytes)) {
7594 spin_unlock(&space_info->lock);
7597 spin_unlock(&space_info->lock);
7600 * ok we don't have enough space, but maybe we have free space on our
7601 * devices to allocate new chunks for relocation, so loop through our
7602 * alloc devices and guess if we have enough space. if this block
7603 * group is going to be restriped, run checks against the target
7604 * profile instead of the current one.
7616 target = get_restripe_target(fs_info, block_group->flags);
7618 index = btrfs_bg_flags_to_raid_index(extended_to_chunk(target));
7621 * this is just a balance, so if we were marked as full
7622 * we know there is no space for a new chunk
7627 "no space to alloc new chunk for block group %llu",
7628 block_group->key.objectid);
7632 index = btrfs_bg_flags_to_raid_index(block_group->flags);
7635 if (index == BTRFS_RAID_RAID10) {
7639 } else if (index == BTRFS_RAID_RAID1) {
7641 } else if (index == BTRFS_RAID_DUP) {
7644 } else if (index == BTRFS_RAID_RAID0) {
7645 dev_min = fs_devices->rw_devices;
7646 min_free = div64_u64(min_free, dev_min);
7649 mutex_lock(&fs_info->chunk_mutex);
7650 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
7654 * check to make sure we can actually find a chunk with enough
7655 * space to fit our block group in.
7657 if (device->total_bytes > device->bytes_used + min_free &&
7658 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7659 ret = find_free_dev_extent(device, min_free,
7664 if (dev_nr >= dev_min)
7670 if (debug && ret == -1)
7672 "no space to allocate a new chunk for block group %llu",
7673 block_group->key.objectid);
7674 mutex_unlock(&fs_info->chunk_mutex);
7676 btrfs_put_block_group(block_group);
7680 static int find_first_block_group(struct btrfs_fs_info *fs_info,
7681 struct btrfs_path *path,
7682 struct btrfs_key *key)
7684 struct btrfs_root *root = fs_info->extent_root;
7686 struct btrfs_key found_key;
7687 struct extent_buffer *leaf;
7688 struct btrfs_block_group_item bg;
7692 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
7697 slot = path->slots[0];
7698 leaf = path->nodes[0];
7699 if (slot >= btrfs_header_nritems(leaf)) {
7700 ret = btrfs_next_leaf(root, path);
7707 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7709 if (found_key.objectid >= key->objectid &&
7710 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
7711 struct extent_map_tree *em_tree;
7712 struct extent_map *em;
7714 em_tree = &root->fs_info->mapping_tree;
7715 read_lock(&em_tree->lock);
7716 em = lookup_extent_mapping(em_tree, found_key.objectid,
7718 read_unlock(&em_tree->lock);
7721 "logical %llu len %llu found bg but no related chunk",
7722 found_key.objectid, found_key.offset);
7724 } else if (em->start != found_key.objectid ||
7725 em->len != found_key.offset) {
7727 "block group %llu len %llu mismatch with chunk %llu len %llu",
7728 found_key.objectid, found_key.offset,
7729 em->start, em->len);
7732 read_extent_buffer(leaf, &bg,
7733 btrfs_item_ptr_offset(leaf, slot),
7735 flags = btrfs_block_group_flags(&bg) &
7736 BTRFS_BLOCK_GROUP_TYPE_MASK;
7738 if (flags != (em->map_lookup->type &
7739 BTRFS_BLOCK_GROUP_TYPE_MASK)) {
7741 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
7743 found_key.offset, flags,
7744 (BTRFS_BLOCK_GROUP_TYPE_MASK &
7745 em->map_lookup->type));
7751 free_extent_map(em);
7760 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
7762 struct btrfs_block_group_cache *block_group;
7766 struct inode *inode;
7768 block_group = btrfs_lookup_first_block_group(info, last);
7769 while (block_group) {
7770 wait_block_group_cache_done(block_group);
7771 spin_lock(&block_group->lock);
7772 if (block_group->iref)
7774 spin_unlock(&block_group->lock);
7775 block_group = next_block_group(block_group);
7784 inode = block_group->inode;
7785 block_group->iref = 0;
7786 block_group->inode = NULL;
7787 spin_unlock(&block_group->lock);
7788 ASSERT(block_group->io_ctl.inode == NULL);
7790 last = block_group->key.objectid + block_group->key.offset;
7791 btrfs_put_block_group(block_group);
7796 * Must be called only after stopping all workers, since we could have block
7797 * group caching kthreads running, and therefore they could race with us if we
7798 * freed the block groups before stopping them.
7800 int btrfs_free_block_groups(struct btrfs_fs_info *info)
7802 struct btrfs_block_group_cache *block_group;
7803 struct btrfs_space_info *space_info;
7804 struct btrfs_caching_control *caching_ctl;
7807 down_write(&info->commit_root_sem);
7808 while (!list_empty(&info->caching_block_groups)) {
7809 caching_ctl = list_entry(info->caching_block_groups.next,
7810 struct btrfs_caching_control, list);
7811 list_del(&caching_ctl->list);
7812 put_caching_control(caching_ctl);
7814 up_write(&info->commit_root_sem);
7816 spin_lock(&info->unused_bgs_lock);
7817 while (!list_empty(&info->unused_bgs)) {
7818 block_group = list_first_entry(&info->unused_bgs,
7819 struct btrfs_block_group_cache,
7821 list_del_init(&block_group->bg_list);
7822 btrfs_put_block_group(block_group);
7824 spin_unlock(&info->unused_bgs_lock);
7826 spin_lock(&info->block_group_cache_lock);
7827 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
7828 block_group = rb_entry(n, struct btrfs_block_group_cache,
7830 rb_erase(&block_group->cache_node,
7831 &info->block_group_cache_tree);
7832 RB_CLEAR_NODE(&block_group->cache_node);
7833 spin_unlock(&info->block_group_cache_lock);
7835 down_write(&block_group->space_info->groups_sem);
7836 list_del(&block_group->list);
7837 up_write(&block_group->space_info->groups_sem);
7840 * We haven't cached this block group, which means we could
7841 * possibly have excluded extents on this block group.
7843 if (block_group->cached == BTRFS_CACHE_NO ||
7844 block_group->cached == BTRFS_CACHE_ERROR)
7845 free_excluded_extents(block_group);
7847 btrfs_remove_free_space_cache(block_group);
7848 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
7849 ASSERT(list_empty(&block_group->dirty_list));
7850 ASSERT(list_empty(&block_group->io_list));
7851 ASSERT(list_empty(&block_group->bg_list));
7852 ASSERT(atomic_read(&block_group->count) == 1);
7853 btrfs_put_block_group(block_group);
7855 spin_lock(&info->block_group_cache_lock);
7857 spin_unlock(&info->block_group_cache_lock);
7859 /* now that all the block groups are freed, go through and
7860 * free all the space_info structs. This is only called during
7861 * the final stages of unmount, and so we know nobody is
7862 * using them. We call synchronize_rcu() once before we start,
7863 * just to be on the safe side.
7867 btrfs_release_global_block_rsv(info);
7869 while (!list_empty(&info->space_info)) {
7872 space_info = list_entry(info->space_info.next,
7873 struct btrfs_space_info,
7877 * Do not hide this behind enospc_debug, this is actually
7878 * important and indicates a real bug if this happens.
7880 if (WARN_ON(space_info->bytes_pinned > 0 ||
7881 space_info->bytes_reserved > 0 ||
7882 space_info->bytes_may_use > 0))
7883 btrfs_dump_space_info(info, space_info, 0, 0);
7884 list_del(&space_info->list);
7885 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
7886 struct kobject *kobj;
7887 kobj = space_info->block_group_kobjs[i];
7888 space_info->block_group_kobjs[i] = NULL;
7894 kobject_del(&space_info->kobj);
7895 kobject_put(&space_info->kobj);
7900 static void link_block_group(struct btrfs_block_group_cache *cache)
7902 struct btrfs_space_info *space_info = cache->space_info;
7903 struct btrfs_fs_info *fs_info = cache->fs_info;
7904 int index = btrfs_bg_flags_to_raid_index(cache->flags);
7907 down_write(&space_info->groups_sem);
7908 if (list_empty(&space_info->block_groups[index]))
7910 list_add_tail(&cache->list, &space_info->block_groups[index]);
7911 up_write(&space_info->groups_sem);
7914 struct raid_kobject *rkobj;
7915 unsigned int nofs_flag;
7919 * Setup a NOFS context because kobject_add(), deep in its call
7920 * chain, does GFP_KERNEL allocations, and we are often called
7921 * in a context where if reclaim is triggered we can deadlock
7922 * (we are either holding a transaction handle or some lock
7923 * required for a transaction commit).
7925 nofs_flag = memalloc_nofs_save();
7926 rkobj = kzalloc(sizeof(*rkobj), GFP_KERNEL);
7928 memalloc_nofs_restore(nofs_flag);
7929 btrfs_warn(cache->fs_info,
7930 "couldn't alloc memory for raid level kobject");
7933 rkobj->flags = cache->flags;
7934 kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
7935 ret = kobject_add(&rkobj->kobj, &space_info->kobj, "%s",
7936 btrfs_bg_type_to_raid_name(rkobj->flags));
7937 memalloc_nofs_restore(nofs_flag);
7939 kobject_put(&rkobj->kobj);
7941 "failed to add kobject for block cache, ignoring");
7944 space_info->block_group_kobjs[index] = &rkobj->kobj;
7948 static struct btrfs_block_group_cache *
7949 btrfs_create_block_group_cache(struct btrfs_fs_info *fs_info,
7950 u64 start, u64 size)
7952 struct btrfs_block_group_cache *cache;
7954 cache = kzalloc(sizeof(*cache), GFP_NOFS);
7958 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
7960 if (!cache->free_space_ctl) {
7965 cache->key.objectid = start;
7966 cache->key.offset = size;
7967 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
7969 cache->fs_info = fs_info;
7970 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
7971 set_free_space_tree_thresholds(cache);
7973 atomic_set(&cache->count, 1);
7974 spin_lock_init(&cache->lock);
7975 init_rwsem(&cache->data_rwsem);
7976 INIT_LIST_HEAD(&cache->list);
7977 INIT_LIST_HEAD(&cache->cluster_list);
7978 INIT_LIST_HEAD(&cache->bg_list);
7979 INIT_LIST_HEAD(&cache->ro_list);
7980 INIT_LIST_HEAD(&cache->dirty_list);
7981 INIT_LIST_HEAD(&cache->io_list);
7982 btrfs_init_free_space_ctl(cache);
7983 atomic_set(&cache->trimming, 0);
7984 mutex_init(&cache->free_space_lock);
7985 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
7992 * Iterate all chunks and verify that each of them has the corresponding block
7995 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
7997 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7998 struct extent_map *em;
7999 struct btrfs_block_group_cache *bg;
8004 read_lock(&map_tree->lock);
8006 * lookup_extent_mapping will return the first extent map
8007 * intersecting the range, so setting @len to 1 is enough to
8008 * get the first chunk.
8010 em = lookup_extent_mapping(map_tree, start, 1);
8011 read_unlock(&map_tree->lock);
8015 bg = btrfs_lookup_block_group(fs_info, em->start);
8018 "chunk start=%llu len=%llu doesn't have corresponding block group",
8019 em->start, em->len);
8021 free_extent_map(em);
8024 if (bg->key.objectid != em->start ||
8025 bg->key.offset != em->len ||
8026 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
8027 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
8029 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
8031 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
8032 bg->key.objectid, bg->key.offset,
8033 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
8035 free_extent_map(em);
8036 btrfs_put_block_group(bg);
8039 start = em->start + em->len;
8040 free_extent_map(em);
8041 btrfs_put_block_group(bg);
8046 int btrfs_read_block_groups(struct btrfs_fs_info *info)
8048 struct btrfs_path *path;
8050 struct btrfs_block_group_cache *cache;
8051 struct btrfs_space_info *space_info;
8052 struct btrfs_key key;
8053 struct btrfs_key found_key;
8054 struct extent_buffer *leaf;
8060 feature = btrfs_super_incompat_flags(info->super_copy);
8061 mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
8065 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
8066 path = btrfs_alloc_path();
8069 path->reada = READA_FORWARD;
8071 cache_gen = btrfs_super_cache_generation(info->super_copy);
8072 if (btrfs_test_opt(info, SPACE_CACHE) &&
8073 btrfs_super_generation(info->super_copy) != cache_gen)
8075 if (btrfs_test_opt(info, CLEAR_CACHE))
8079 ret = find_first_block_group(info, path, &key);
8085 leaf = path->nodes[0];
8086 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8088 cache = btrfs_create_block_group_cache(info, found_key.objectid,
8097 * When we mount with old space cache, we need to
8098 * set BTRFS_DC_CLEAR and set dirty flag.
8100 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
8101 * truncate the old free space cache inode and
8103 * b) Setting 'dirty flag' makes sure that we flush
8104 * the new space cache info onto disk.
8106 if (btrfs_test_opt(info, SPACE_CACHE))
8107 cache->disk_cache_state = BTRFS_DC_CLEAR;
8110 read_extent_buffer(leaf, &cache->item,
8111 btrfs_item_ptr_offset(leaf, path->slots[0]),
8112 sizeof(cache->item));
8113 cache->flags = btrfs_block_group_flags(&cache->item);
8115 ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
8116 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
8118 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
8119 cache->key.objectid);
8120 btrfs_put_block_group(cache);
8125 key.objectid = found_key.objectid + found_key.offset;
8126 btrfs_release_path(path);
8129 * We need to exclude the super stripes now so that the space
8130 * info has super bytes accounted for, otherwise we'll think
8131 * we have more space than we actually do.
8133 ret = exclude_super_stripes(cache);
8136 * We may have excluded something, so call this just in
8139 free_excluded_extents(cache);
8140 btrfs_put_block_group(cache);
8145 * check for two cases, either we are full, and therefore
8146 * don't need to bother with the caching work since we won't
8147 * find any space, or we are empty, and we can just add all
8148 * the space in and be done with it. This saves us _a_lot_ of
8149 * time, particularly in the full case.
8151 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
8152 cache->last_byte_to_unpin = (u64)-1;
8153 cache->cached = BTRFS_CACHE_FINISHED;
8154 free_excluded_extents(cache);
8155 } else if (btrfs_block_group_used(&cache->item) == 0) {
8156 cache->last_byte_to_unpin = (u64)-1;
8157 cache->cached = BTRFS_CACHE_FINISHED;
8158 add_new_free_space(cache, found_key.objectid,
8159 found_key.objectid +
8161 free_excluded_extents(cache);
8164 ret = btrfs_add_block_group_cache(info, cache);
8166 btrfs_remove_free_space_cache(cache);
8167 btrfs_put_block_group(cache);
8171 trace_btrfs_add_block_group(info, cache, 0);
8172 btrfs_update_space_info(info, cache->flags, found_key.offset,
8173 btrfs_block_group_used(&cache->item),
8174 cache->bytes_super, &space_info);
8176 cache->space_info = space_info;
8178 link_block_group(cache);
8180 set_avail_alloc_bits(info, cache->flags);
8181 if (btrfs_chunk_readonly(info, cache->key.objectid)) {
8182 inc_block_group_ro(cache, 1);
8183 } else if (btrfs_block_group_used(&cache->item) == 0) {
8184 ASSERT(list_empty(&cache->bg_list));
8185 btrfs_mark_bg_unused(cache);
8189 list_for_each_entry_rcu(space_info, &info->space_info, list) {
8190 if (!(get_alloc_profile(info, space_info->flags) &
8191 (BTRFS_BLOCK_GROUP_RAID10 |
8192 BTRFS_BLOCK_GROUP_RAID1_MASK |
8193 BTRFS_BLOCK_GROUP_RAID56_MASK |
8194 BTRFS_BLOCK_GROUP_DUP)))
8197 * avoid allocating from un-mirrored block group if there are
8198 * mirrored block groups.
8200 list_for_each_entry(cache,
8201 &space_info->block_groups[BTRFS_RAID_RAID0],
8203 inc_block_group_ro(cache, 1);
8204 list_for_each_entry(cache,
8205 &space_info->block_groups[BTRFS_RAID_SINGLE],
8207 inc_block_group_ro(cache, 1);
8210 btrfs_init_global_block_rsv(info);
8211 ret = check_chunk_block_group_mappings(info);
8213 btrfs_free_path(path);
8217 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
8219 struct btrfs_fs_info *fs_info = trans->fs_info;
8220 struct btrfs_block_group_cache *block_group;
8221 struct btrfs_root *extent_root = fs_info->extent_root;
8222 struct btrfs_block_group_item item;
8223 struct btrfs_key key;
8226 if (!trans->can_flush_pending_bgs)
8229 while (!list_empty(&trans->new_bgs)) {
8230 block_group = list_first_entry(&trans->new_bgs,
8231 struct btrfs_block_group_cache,
8236 spin_lock(&block_group->lock);
8237 memcpy(&item, &block_group->item, sizeof(item));
8238 memcpy(&key, &block_group->key, sizeof(key));
8239 spin_unlock(&block_group->lock);
8241 ret = btrfs_insert_item(trans, extent_root, &key, &item,
8244 btrfs_abort_transaction(trans, ret);
8245 ret = btrfs_finish_chunk_alloc(trans, key.objectid, key.offset);
8247 btrfs_abort_transaction(trans, ret);
8248 add_block_group_free_space(trans, block_group);
8249 /* already aborted the transaction if it failed. */
8251 btrfs_delayed_refs_rsv_release(fs_info, 1);
8252 list_del_init(&block_group->bg_list);
8254 btrfs_trans_release_chunk_metadata(trans);
8257 int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
8258 u64 type, u64 chunk_offset, u64 size)
8260 struct btrfs_fs_info *fs_info = trans->fs_info;
8261 struct btrfs_block_group_cache *cache;
8264 btrfs_set_log_full_commit(trans);
8266 cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
8270 btrfs_set_block_group_used(&cache->item, bytes_used);
8271 btrfs_set_block_group_chunk_objectid(&cache->item,
8272 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
8273 btrfs_set_block_group_flags(&cache->item, type);
8275 cache->flags = type;
8276 cache->last_byte_to_unpin = (u64)-1;
8277 cache->cached = BTRFS_CACHE_FINISHED;
8278 cache->needs_free_space = 1;
8279 ret = exclude_super_stripes(cache);
8282 * We may have excluded something, so call this just in
8285 free_excluded_extents(cache);
8286 btrfs_put_block_group(cache);
8290 add_new_free_space(cache, chunk_offset, chunk_offset + size);
8292 free_excluded_extents(cache);
8294 #ifdef CONFIG_BTRFS_DEBUG
8295 if (btrfs_should_fragment_free_space(cache)) {
8296 u64 new_bytes_used = size - bytes_used;
8298 bytes_used += new_bytes_used >> 1;
8299 fragment_free_space(cache);
8303 * Ensure the corresponding space_info object is created and
8304 * assigned to our block group. We want our bg to be added to the rbtree
8305 * with its ->space_info set.
8307 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
8308 ASSERT(cache->space_info);
8310 ret = btrfs_add_block_group_cache(fs_info, cache);
8312 btrfs_remove_free_space_cache(cache);
8313 btrfs_put_block_group(cache);
8318 * Now that our block group has its ->space_info set and is inserted in
8319 * the rbtree, update the space info's counters.
8321 trace_btrfs_add_block_group(fs_info, cache, 1);
8322 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
8323 cache->bytes_super, &cache->space_info);
8324 btrfs_update_global_block_rsv(fs_info);
8326 link_block_group(cache);
8328 list_add_tail(&cache->bg_list, &trans->new_bgs);
8329 trans->delayed_ref_updates++;
8330 btrfs_update_delayed_refs_rsv(trans);
8332 set_avail_alloc_bits(fs_info, type);
8336 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
8338 u64 extra_flags = chunk_to_extended(flags) &
8339 BTRFS_EXTENDED_PROFILE_MASK;
8341 write_seqlock(&fs_info->profiles_lock);
8342 if (flags & BTRFS_BLOCK_GROUP_DATA)
8343 fs_info->avail_data_alloc_bits &= ~extra_flags;
8344 if (flags & BTRFS_BLOCK_GROUP_METADATA)
8345 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
8346 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
8347 fs_info->avail_system_alloc_bits &= ~extra_flags;
8348 write_sequnlock(&fs_info->profiles_lock);
8352 * Clear incompat bits for the following feature(s):
8354 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
8355 * in the whole filesystem
8357 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
8359 if (flags & BTRFS_BLOCK_GROUP_RAID56_MASK) {
8360 struct list_head *head = &fs_info->space_info;
8361 struct btrfs_space_info *sinfo;
8363 list_for_each_entry_rcu(sinfo, head, list) {
8366 down_read(&sinfo->groups_sem);
8367 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
8369 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
8371 up_read(&sinfo->groups_sem);
8376 btrfs_clear_fs_incompat(fs_info, RAID56);
8380 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
8381 u64 group_start, struct extent_map *em)
8383 struct btrfs_fs_info *fs_info = trans->fs_info;
8384 struct btrfs_root *root = fs_info->extent_root;
8385 struct btrfs_path *path;
8386 struct btrfs_block_group_cache *block_group;
8387 struct btrfs_free_cluster *cluster;
8388 struct btrfs_root *tree_root = fs_info->tree_root;
8389 struct btrfs_key key;
8390 struct inode *inode;
8391 struct kobject *kobj = NULL;
8395 struct btrfs_caching_control *caching_ctl = NULL;
8397 bool remove_rsv = false;
8399 block_group = btrfs_lookup_block_group(fs_info, group_start);
8400 BUG_ON(!block_group);
8401 BUG_ON(!block_group->ro);
8403 trace_btrfs_remove_block_group(block_group);
8405 * Free the reserved super bytes from this block group before
8408 free_excluded_extents(block_group);
8409 btrfs_free_ref_tree_range(fs_info, block_group->key.objectid,
8410 block_group->key.offset);
8412 memcpy(&key, &block_group->key, sizeof(key));
8413 index = btrfs_bg_flags_to_raid_index(block_group->flags);
8414 factor = btrfs_bg_type_to_factor(block_group->flags);
8416 /* make sure this block group isn't part of an allocation cluster */
8417 cluster = &fs_info->data_alloc_cluster;
8418 spin_lock(&cluster->refill_lock);
8419 btrfs_return_cluster_to_free_space(block_group, cluster);
8420 spin_unlock(&cluster->refill_lock);
8423 * make sure this block group isn't part of a metadata
8424 * allocation cluster
8426 cluster = &fs_info->meta_alloc_cluster;
8427 spin_lock(&cluster->refill_lock);
8428 btrfs_return_cluster_to_free_space(block_group, cluster);
8429 spin_unlock(&cluster->refill_lock);
8431 path = btrfs_alloc_path();
8438 * get the inode first so any iput calls done for the io_list
8439 * aren't the final iput (no unlinks allowed now)
8441 inode = lookup_free_space_inode(block_group, path);
8443 mutex_lock(&trans->transaction->cache_write_mutex);
8445 * Make sure our free space cache IO is done before removing the
8448 spin_lock(&trans->transaction->dirty_bgs_lock);
8449 if (!list_empty(&block_group->io_list)) {
8450 list_del_init(&block_group->io_list);
8452 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
8454 spin_unlock(&trans->transaction->dirty_bgs_lock);
8455 btrfs_wait_cache_io(trans, block_group, path);
8456 btrfs_put_block_group(block_group);
8457 spin_lock(&trans->transaction->dirty_bgs_lock);
8460 if (!list_empty(&block_group->dirty_list)) {
8461 list_del_init(&block_group->dirty_list);
8463 btrfs_put_block_group(block_group);
8465 spin_unlock(&trans->transaction->dirty_bgs_lock);
8466 mutex_unlock(&trans->transaction->cache_write_mutex);
8468 if (!IS_ERR(inode)) {
8469 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
8471 btrfs_add_delayed_iput(inode);
8475 /* One for the block groups ref */
8476 spin_lock(&block_group->lock);
8477 if (block_group->iref) {
8478 block_group->iref = 0;
8479 block_group->inode = NULL;
8480 spin_unlock(&block_group->lock);
8483 spin_unlock(&block_group->lock);
8485 /* One for our lookup ref */
8486 btrfs_add_delayed_iput(inode);
8489 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
8490 key.offset = block_group->key.objectid;
8493 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
8497 btrfs_release_path(path);
8499 ret = btrfs_del_item(trans, tree_root, path);
8502 btrfs_release_path(path);
8505 spin_lock(&fs_info->block_group_cache_lock);
8506 rb_erase(&block_group->cache_node,
8507 &fs_info->block_group_cache_tree);
8508 RB_CLEAR_NODE(&block_group->cache_node);
8510 if (fs_info->first_logical_byte == block_group->key.objectid)
8511 fs_info->first_logical_byte = (u64)-1;
8512 spin_unlock(&fs_info->block_group_cache_lock);
8514 down_write(&block_group->space_info->groups_sem);
8516 * we must use list_del_init so people can check to see if they
8517 * are still on the list after taking the semaphore
8519 list_del_init(&block_group->list);
8520 if (list_empty(&block_group->space_info->block_groups[index])) {
8521 kobj = block_group->space_info->block_group_kobjs[index];
8522 block_group->space_info->block_group_kobjs[index] = NULL;
8523 clear_avail_alloc_bits(fs_info, block_group->flags);
8525 up_write(&block_group->space_info->groups_sem);
8526 clear_incompat_bg_bits(fs_info, block_group->flags);
8532 if (block_group->has_caching_ctl)
8533 caching_ctl = get_caching_control(block_group);
8534 if (block_group->cached == BTRFS_CACHE_STARTED)
8535 wait_block_group_cache_done(block_group);
8536 if (block_group->has_caching_ctl) {
8537 down_write(&fs_info->commit_root_sem);
8539 struct btrfs_caching_control *ctl;
8541 list_for_each_entry(ctl,
8542 &fs_info->caching_block_groups, list)
8543 if (ctl->block_group == block_group) {
8545 refcount_inc(&caching_ctl->count);
8550 list_del_init(&caching_ctl->list);
8551 up_write(&fs_info->commit_root_sem);
8553 /* Once for the caching bgs list and once for us. */
8554 put_caching_control(caching_ctl);
8555 put_caching_control(caching_ctl);
8559 spin_lock(&trans->transaction->dirty_bgs_lock);
8560 WARN_ON(!list_empty(&block_group->dirty_list));
8561 WARN_ON(!list_empty(&block_group->io_list));
8562 spin_unlock(&trans->transaction->dirty_bgs_lock);
8564 btrfs_remove_free_space_cache(block_group);
8566 spin_lock(&block_group->space_info->lock);
8567 list_del_init(&block_group->ro_list);
8569 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8570 WARN_ON(block_group->space_info->total_bytes
8571 < block_group->key.offset);
8572 WARN_ON(block_group->space_info->bytes_readonly
8573 < block_group->key.offset);
8574 WARN_ON(block_group->space_info->disk_total
8575 < block_group->key.offset * factor);
8577 block_group->space_info->total_bytes -= block_group->key.offset;
8578 block_group->space_info->bytes_readonly -= block_group->key.offset;
8579 block_group->space_info->disk_total -= block_group->key.offset * factor;
8581 spin_unlock(&block_group->space_info->lock);
8583 memcpy(&key, &block_group->key, sizeof(key));
8585 mutex_lock(&fs_info->chunk_mutex);
8586 spin_lock(&block_group->lock);
8587 block_group->removed = 1;
8589 * At this point trimming can't start on this block group, because we
8590 * removed the block group from the tree fs_info->block_group_cache_tree
8591 * so no one can't find it anymore and even if someone already got this
8592 * block group before we removed it from the rbtree, they have already
8593 * incremented block_group->trimming - if they didn't, they won't find
8594 * any free space entries because we already removed them all when we
8595 * called btrfs_remove_free_space_cache().
8597 * And we must not remove the extent map from the fs_info->mapping_tree
8598 * to prevent the same logical address range and physical device space
8599 * ranges from being reused for a new block group. This is because our
8600 * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
8601 * completely transactionless, so while it is trimming a range the
8602 * currently running transaction might finish and a new one start,
8603 * allowing for new block groups to be created that can reuse the same
8604 * physical device locations unless we take this special care.
8606 * There may also be an implicit trim operation if the file system
8607 * is mounted with -odiscard. The same protections must remain
8608 * in place until the extents have been discarded completely when
8609 * the transaction commit has completed.
8611 remove_em = (atomic_read(&block_group->trimming) == 0);
8612 spin_unlock(&block_group->lock);
8614 mutex_unlock(&fs_info->chunk_mutex);
8616 ret = remove_block_group_free_space(trans, block_group);
8620 btrfs_put_block_group(block_group);
8621 btrfs_put_block_group(block_group);
8623 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8629 ret = btrfs_del_item(trans, root, path);
8634 struct extent_map_tree *em_tree;
8636 em_tree = &fs_info->mapping_tree;
8637 write_lock(&em_tree->lock);
8638 remove_extent_mapping(em_tree, em);
8639 write_unlock(&em_tree->lock);
8640 /* once for the tree */
8641 free_extent_map(em);
8645 btrfs_delayed_refs_rsv_release(fs_info, 1);
8646 btrfs_free_path(path);
8650 struct btrfs_trans_handle *
8651 btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
8652 const u64 chunk_offset)
8654 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
8655 struct extent_map *em;
8656 struct map_lookup *map;
8657 unsigned int num_items;
8659 read_lock(&em_tree->lock);
8660 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
8661 read_unlock(&em_tree->lock);
8662 ASSERT(em && em->start == chunk_offset);
8665 * We need to reserve 3 + N units from the metadata space info in order
8666 * to remove a block group (done at btrfs_remove_chunk() and at
8667 * btrfs_remove_block_group()), which are used for:
8669 * 1 unit for adding the free space inode's orphan (located in the tree
8671 * 1 unit for deleting the block group item (located in the extent
8673 * 1 unit for deleting the free space item (located in tree of tree
8675 * N units for deleting N device extent items corresponding to each
8676 * stripe (located in the device tree).
8678 * In order to remove a block group we also need to reserve units in the
8679 * system space info in order to update the chunk tree (update one or
8680 * more device items and remove one chunk item), but this is done at
8681 * btrfs_remove_chunk() through a call to check_system_chunk().
8683 map = em->map_lookup;
8684 num_items = 3 + map->num_stripes;
8685 free_extent_map(em);
8687 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
8692 * Process the unused_bgs list and remove any that don't have any allocated
8693 * space inside of them.
8695 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
8697 struct btrfs_block_group_cache *block_group;
8698 struct btrfs_space_info *space_info;
8699 struct btrfs_trans_handle *trans;
8702 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
8705 spin_lock(&fs_info->unused_bgs_lock);
8706 while (!list_empty(&fs_info->unused_bgs)) {
8710 block_group = list_first_entry(&fs_info->unused_bgs,
8711 struct btrfs_block_group_cache,
8713 list_del_init(&block_group->bg_list);
8715 space_info = block_group->space_info;
8717 if (ret || btrfs_mixed_space_info(space_info)) {
8718 btrfs_put_block_group(block_group);
8721 spin_unlock(&fs_info->unused_bgs_lock);
8723 mutex_lock(&fs_info->delete_unused_bgs_mutex);
8725 /* Don't want to race with allocators so take the groups_sem */
8726 down_write(&space_info->groups_sem);
8727 spin_lock(&block_group->lock);
8728 if (block_group->reserved || block_group->pinned ||
8729 btrfs_block_group_used(&block_group->item) ||
8731 list_is_singular(&block_group->list)) {
8733 * We want to bail if we made new allocations or have
8734 * outstanding allocations in this block group. We do
8735 * the ro check in case balance is currently acting on
8738 trace_btrfs_skip_unused_block_group(block_group);
8739 spin_unlock(&block_group->lock);
8740 up_write(&space_info->groups_sem);
8743 spin_unlock(&block_group->lock);
8745 /* We don't want to force the issue, only flip if it's ok. */
8746 ret = inc_block_group_ro(block_group, 0);
8747 up_write(&space_info->groups_sem);
8754 * Want to do this before we do anything else so we can recover
8755 * properly if we fail to join the transaction.
8757 trans = btrfs_start_trans_remove_block_group(fs_info,
8758 block_group->key.objectid);
8759 if (IS_ERR(trans)) {
8760 btrfs_dec_block_group_ro(block_group);
8761 ret = PTR_ERR(trans);
8766 * We could have pending pinned extents for this block group,
8767 * just delete them, we don't care about them anymore.
8769 start = block_group->key.objectid;
8770 end = start + block_group->key.offset - 1;
8772 * Hold the unused_bg_unpin_mutex lock to avoid racing with
8773 * btrfs_finish_extent_commit(). If we are at transaction N,
8774 * another task might be running finish_extent_commit() for the
8775 * previous transaction N - 1, and have seen a range belonging
8776 * to the block group in freed_extents[] before we were able to
8777 * clear the whole block group range from freed_extents[]. This
8778 * means that task can lookup for the block group after we
8779 * unpinned it from freed_extents[] and removed it, leading to
8780 * a BUG_ON() at btrfs_unpin_extent_range().
8782 mutex_lock(&fs_info->unused_bg_unpin_mutex);
8783 ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
8786 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
8787 btrfs_dec_block_group_ro(block_group);
8790 ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
8793 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
8794 btrfs_dec_block_group_ro(block_group);
8797 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
8799 /* Reset pinned so btrfs_put_block_group doesn't complain */
8800 spin_lock(&space_info->lock);
8801 spin_lock(&block_group->lock);
8803 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
8804 -block_group->pinned);
8805 space_info->bytes_readonly += block_group->pinned;
8806 percpu_counter_add_batch(&space_info->total_bytes_pinned,
8807 -block_group->pinned,
8808 BTRFS_TOTAL_BYTES_PINNED_BATCH);
8809 block_group->pinned = 0;
8811 spin_unlock(&block_group->lock);
8812 spin_unlock(&space_info->lock);
8814 /* DISCARD can flip during remount */
8815 trimming = btrfs_test_opt(fs_info, DISCARD);
8817 /* Implicit trim during transaction commit. */
8819 btrfs_get_block_group_trimming(block_group);
8822 * Btrfs_remove_chunk will abort the transaction if things go
8825 ret = btrfs_remove_chunk(trans, block_group->key.objectid);
8829 btrfs_put_block_group_trimming(block_group);
8834 * If we're not mounted with -odiscard, we can just forget
8835 * about this block group. Otherwise we'll need to wait
8836 * until transaction commit to do the actual discard.
8839 spin_lock(&fs_info->unused_bgs_lock);
8841 * A concurrent scrub might have added us to the list
8842 * fs_info->unused_bgs, so use a list_move operation
8843 * to add the block group to the deleted_bgs list.
8845 list_move(&block_group->bg_list,
8846 &trans->transaction->deleted_bgs);
8847 spin_unlock(&fs_info->unused_bgs_lock);
8848 btrfs_get_block_group(block_group);
8851 btrfs_end_transaction(trans);
8853 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
8854 btrfs_put_block_group(block_group);
8855 spin_lock(&fs_info->unused_bgs_lock);
8857 spin_unlock(&fs_info->unused_bgs_lock);
8860 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
8863 return unpin_extent_range(fs_info, start, end, false);
8867 * It used to be that old block groups would be left around forever.
8868 * Iterating over them would be enough to trim unused space. Since we
8869 * now automatically remove them, we also need to iterate over unallocated
8872 * We don't want a transaction for this since the discard may take a
8873 * substantial amount of time. We don't require that a transaction be
8874 * running, but we do need to take a running transaction into account
8875 * to ensure that we're not discarding chunks that were released or
8876 * allocated in the current transaction.
8878 * Holding the chunks lock will prevent other threads from allocating
8879 * or releasing chunks, but it won't prevent a running transaction
8880 * from committing and releasing the memory that the pending chunks
8881 * list head uses. For that, we need to take a reference to the
8882 * transaction and hold the commit root sem. We only need to hold
8883 * it while performing the free space search since we have already
8884 * held back allocations.
8886 static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
8888 u64 start = SZ_1M, len = 0, end = 0;
8893 /* Discard not supported = nothing to do. */
8894 if (!blk_queue_discard(bdev_get_queue(device->bdev)))
8897 /* Not writable = nothing to do. */
8898 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
8901 /* No free space = nothing to do. */
8902 if (device->total_bytes <= device->bytes_used)
8908 struct btrfs_fs_info *fs_info = device->fs_info;
8911 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
8915 find_first_clear_extent_bit(&device->alloc_state, start,
8917 CHUNK_TRIMMED | CHUNK_ALLOCATED);
8919 /* Ensure we skip the reserved area in the first 1M */
8920 start = max_t(u64, start, SZ_1M);
8923 * If find_first_clear_extent_bit find a range that spans the
8924 * end of the device it will set end to -1, in this case it's up
8925 * to the caller to trim the value to the size of the device.
8927 end = min(end, device->total_bytes - 1);
8929 len = end - start + 1;
8931 /* We didn't find any extents */
8933 mutex_unlock(&fs_info->chunk_mutex);
8938 ret = btrfs_issue_discard(device->bdev, start, len,
8941 set_extent_bits(&device->alloc_state, start,
8944 mutex_unlock(&fs_info->chunk_mutex);
8952 if (fatal_signal_pending(current)) {
8964 * Trim the whole filesystem by:
8965 * 1) trimming the free space in each block group
8966 * 2) trimming the unallocated space on each device
8968 * This will also continue trimming even if a block group or device encounters
8969 * an error. The return value will be the last error, or 0 if nothing bad
8972 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
8974 struct btrfs_block_group_cache *cache = NULL;
8975 struct btrfs_device *device;
8976 struct list_head *devices;
8978 u64 range_end = U64_MAX;
8989 * Check range overflow if range->len is set.
8990 * The default range->len is U64_MAX.
8992 if (range->len != U64_MAX &&
8993 check_add_overflow(range->start, range->len, &range_end))
8996 cache = btrfs_lookup_first_block_group(fs_info, range->start);
8997 for (; cache; cache = next_block_group(cache)) {
8998 if (cache->key.objectid >= range_end) {
8999 btrfs_put_block_group(cache);
9003 start = max(range->start, cache->key.objectid);
9004 end = min(range_end, cache->key.objectid + cache->key.offset);
9006 if (end - start >= range->minlen) {
9007 if (!block_group_cache_done(cache)) {
9008 ret = cache_block_group(cache, 0);
9014 ret = wait_block_group_cache_done(cache);
9021 ret = btrfs_trim_block_group(cache,
9027 trimmed += group_trimmed;
9038 "failed to trim %llu block group(s), last error %d",
9040 mutex_lock(&fs_info->fs_devices->device_list_mutex);
9041 devices = &fs_info->fs_devices->devices;
9042 list_for_each_entry(device, devices, dev_list) {
9043 ret = btrfs_trim_free_extents(device, &group_trimmed);
9050 trimmed += group_trimmed;
9052 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
9056 "failed to trim %llu device(s), last error %d",
9057 dev_failed, dev_ret);
9058 range->len = trimmed;
9065 * btrfs_{start,end}_write_no_snapshotting() are similar to
9066 * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
9067 * data into the page cache through nocow before the subvolume is snapshoted,
9068 * but flush the data into disk after the snapshot creation, or to prevent
9069 * operations while snapshotting is ongoing and that cause the snapshot to be
9070 * inconsistent (writes followed by expanding truncates for example).
9072 void btrfs_end_write_no_snapshotting(struct btrfs_root *root)
9074 percpu_counter_dec(&root->subv_writers->counter);
9075 cond_wake_up(&root->subv_writers->wait);
9078 int btrfs_start_write_no_snapshotting(struct btrfs_root *root)
9080 if (atomic_read(&root->will_be_snapshotted))
9083 percpu_counter_inc(&root->subv_writers->counter);
9085 * Make sure counter is updated before we check for snapshot creation.
9088 if (atomic_read(&root->will_be_snapshotted)) {
9089 btrfs_end_write_no_snapshotting(root);
9095 void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
9100 ret = btrfs_start_write_no_snapshotting(root);
9103 wait_var_event(&root->will_be_snapshotted,
9104 !atomic_read(&root->will_be_snapshotted));
9108 void btrfs_mark_bg_unused(struct btrfs_block_group_cache *bg)
9110 struct btrfs_fs_info *fs_info = bg->fs_info;
9112 spin_lock(&fs_info->unused_bgs_lock);
9113 if (list_empty(&bg->bg_list)) {
9114 btrfs_get_block_group(bg);
9115 trace_btrfs_add_unused_block_group(bg);
9116 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
9118 spin_unlock(&fs_info->unused_bgs_lock);