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))
5757 ffe_ctl.cached = block_group_cache_done(block_group);
5758 if (unlikely(!ffe_ctl.cached)) {
5759 ffe_ctl.have_caching_bg = true;
5760 ret = cache_block_group(block_group, 0);
5765 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
5769 * Ok we want to try and use the cluster allocator, so
5772 if (last_ptr && use_cluster) {
5773 struct btrfs_block_group_cache *cluster_bg = NULL;
5775 ret = find_free_extent_clustered(block_group, last_ptr,
5776 &ffe_ctl, &cluster_bg);
5779 if (cluster_bg && cluster_bg != block_group) {
5780 btrfs_release_block_group(block_group,
5782 block_group = cluster_bg;
5785 } else if (ret == -EAGAIN) {
5786 goto have_block_group;
5787 } else if (ret > 0) {
5790 /* ret == -ENOENT case falls through */
5793 ret = find_free_extent_unclustered(block_group, last_ptr,
5796 goto have_block_group;
5799 /* ret == 0 case falls through */
5801 ffe_ctl.search_start = round_up(ffe_ctl.found_offset,
5802 fs_info->stripesize);
5804 /* move on to the next group */
5805 if (ffe_ctl.search_start + num_bytes >
5806 block_group->key.objectid + block_group->key.offset) {
5807 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
5812 if (ffe_ctl.found_offset < ffe_ctl.search_start)
5813 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
5814 ffe_ctl.search_start - ffe_ctl.found_offset);
5816 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
5817 num_bytes, delalloc);
5818 if (ret == -EAGAIN) {
5819 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
5823 btrfs_inc_block_group_reservations(block_group);
5825 /* we are all good, lets return */
5826 ins->objectid = ffe_ctl.search_start;
5827 ins->offset = num_bytes;
5829 trace_btrfs_reserve_extent(block_group, ffe_ctl.search_start,
5831 btrfs_release_block_group(block_group, delalloc);
5834 ffe_ctl.retry_clustered = false;
5835 ffe_ctl.retry_unclustered = false;
5836 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
5838 btrfs_release_block_group(block_group, delalloc);
5841 up_read(&space_info->groups_sem);
5843 ret = find_free_extent_update_loop(fs_info, last_ptr, ins, &ffe_ctl,
5844 full_search, use_cluster);
5848 if (ret == -ENOSPC) {
5850 * Use ffe_ctl->total_free_space as fallback if we can't find
5851 * any contiguous hole.
5853 if (!ffe_ctl.max_extent_size)
5854 ffe_ctl.max_extent_size = ffe_ctl.total_free_space;
5855 spin_lock(&space_info->lock);
5856 space_info->max_extent_size = ffe_ctl.max_extent_size;
5857 spin_unlock(&space_info->lock);
5858 ins->offset = ffe_ctl.max_extent_size;
5864 * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
5865 * hole that is at least as big as @num_bytes.
5867 * @root - The root that will contain this extent
5869 * @ram_bytes - The amount of space in ram that @num_bytes take. This
5870 * is used for accounting purposes. This value differs
5871 * from @num_bytes only in the case of compressed extents.
5873 * @num_bytes - Number of bytes to allocate on-disk.
5875 * @min_alloc_size - Indicates the minimum amount of space that the
5876 * allocator should try to satisfy. In some cases
5877 * @num_bytes may be larger than what is required and if
5878 * the filesystem is fragmented then allocation fails.
5879 * However, the presence of @min_alloc_size gives a
5880 * chance to try and satisfy the smaller allocation.
5882 * @empty_size - A hint that you plan on doing more COW. This is the
5883 * size in bytes the allocator should try to find free
5884 * next to the block it returns. This is just a hint and
5885 * may be ignored by the allocator.
5887 * @hint_byte - Hint to the allocator to start searching above the byte
5888 * address passed. It might be ignored.
5890 * @ins - This key is modified to record the found hole. It will
5891 * have the following values:
5892 * ins->objectid == start position
5893 * ins->flags = BTRFS_EXTENT_ITEM_KEY
5894 * ins->offset == the size of the hole.
5896 * @is_data - Boolean flag indicating whether an extent is
5897 * allocated for data (true) or metadata (false)
5899 * @delalloc - Boolean flag indicating whether this allocation is for
5900 * delalloc or not. If 'true' data_rwsem of block groups
5901 * is going to be acquired.
5904 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
5905 * case -ENOSPC is returned then @ins->offset will contain the size of the
5906 * largest available hole the allocator managed to find.
5908 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
5909 u64 num_bytes, u64 min_alloc_size,
5910 u64 empty_size, u64 hint_byte,
5911 struct btrfs_key *ins, int is_data, int delalloc)
5913 struct btrfs_fs_info *fs_info = root->fs_info;
5914 bool final_tried = num_bytes == min_alloc_size;
5918 flags = get_alloc_profile_by_root(root, is_data);
5920 WARN_ON(num_bytes < fs_info->sectorsize);
5921 ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
5922 hint_byte, ins, flags, delalloc);
5923 if (!ret && !is_data) {
5924 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
5925 } else if (ret == -ENOSPC) {
5926 if (!final_tried && ins->offset) {
5927 num_bytes = min(num_bytes >> 1, ins->offset);
5928 num_bytes = round_down(num_bytes,
5929 fs_info->sectorsize);
5930 num_bytes = max(num_bytes, min_alloc_size);
5931 ram_bytes = num_bytes;
5932 if (num_bytes == min_alloc_size)
5935 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
5936 struct btrfs_space_info *sinfo;
5938 sinfo = btrfs_find_space_info(fs_info, flags);
5940 "allocation failed flags %llu, wanted %llu",
5943 btrfs_dump_space_info(fs_info, sinfo,
5951 static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
5953 int pin, int delalloc)
5955 struct btrfs_block_group_cache *cache;
5958 cache = btrfs_lookup_block_group(fs_info, start);
5960 btrfs_err(fs_info, "Unable to find block group for %llu",
5966 pin_down_extent(cache, start, len, 1);
5968 if (btrfs_test_opt(fs_info, DISCARD))
5969 ret = btrfs_discard_extent(fs_info, start, len, NULL);
5970 btrfs_add_free_space(cache, start, len);
5971 btrfs_free_reserved_bytes(cache, len, delalloc);
5972 trace_btrfs_reserved_extent_free(fs_info, start, len);
5975 btrfs_put_block_group(cache);
5979 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
5980 u64 start, u64 len, int delalloc)
5982 return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
5985 int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
5988 return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
5991 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
5992 u64 parent, u64 root_objectid,
5993 u64 flags, u64 owner, u64 offset,
5994 struct btrfs_key *ins, int ref_mod)
5996 struct btrfs_fs_info *fs_info = trans->fs_info;
5998 struct btrfs_extent_item *extent_item;
5999 struct btrfs_extent_inline_ref *iref;
6000 struct btrfs_path *path;
6001 struct extent_buffer *leaf;
6006 type = BTRFS_SHARED_DATA_REF_KEY;
6008 type = BTRFS_EXTENT_DATA_REF_KEY;
6010 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
6012 path = btrfs_alloc_path();
6016 path->leave_spinning = 1;
6017 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6020 btrfs_free_path(path);
6024 leaf = path->nodes[0];
6025 extent_item = btrfs_item_ptr(leaf, path->slots[0],
6026 struct btrfs_extent_item);
6027 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
6028 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6029 btrfs_set_extent_flags(leaf, extent_item,
6030 flags | BTRFS_EXTENT_FLAG_DATA);
6032 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
6033 btrfs_set_extent_inline_ref_type(leaf, iref, type);
6035 struct btrfs_shared_data_ref *ref;
6036 ref = (struct btrfs_shared_data_ref *)(iref + 1);
6037 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6038 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
6040 struct btrfs_extent_data_ref *ref;
6041 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
6042 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
6043 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
6044 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
6045 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
6048 btrfs_mark_buffer_dirty(path->nodes[0]);
6049 btrfs_free_path(path);
6051 ret = remove_from_free_space_tree(trans, ins->objectid, ins->offset);
6055 ret = update_block_group(trans, ins->objectid, ins->offset, 1);
6056 if (ret) { /* -ENOENT, logic error */
6057 btrfs_err(fs_info, "update block group failed for %llu %llu",
6058 ins->objectid, ins->offset);
6061 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
6065 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
6066 struct btrfs_delayed_ref_node *node,
6067 struct btrfs_delayed_extent_op *extent_op)
6069 struct btrfs_fs_info *fs_info = trans->fs_info;
6071 struct btrfs_extent_item *extent_item;
6072 struct btrfs_key extent_key;
6073 struct btrfs_tree_block_info *block_info;
6074 struct btrfs_extent_inline_ref *iref;
6075 struct btrfs_path *path;
6076 struct extent_buffer *leaf;
6077 struct btrfs_delayed_tree_ref *ref;
6078 u32 size = sizeof(*extent_item) + sizeof(*iref);
6080 u64 flags = extent_op->flags_to_set;
6081 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
6083 ref = btrfs_delayed_node_to_tree_ref(node);
6085 extent_key.objectid = node->bytenr;
6086 if (skinny_metadata) {
6087 extent_key.offset = ref->level;
6088 extent_key.type = BTRFS_METADATA_ITEM_KEY;
6089 num_bytes = fs_info->nodesize;
6091 extent_key.offset = node->num_bytes;
6092 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
6093 size += sizeof(*block_info);
6094 num_bytes = node->num_bytes;
6097 path = btrfs_alloc_path();
6101 path->leave_spinning = 1;
6102 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6105 btrfs_free_path(path);
6109 leaf = path->nodes[0];
6110 extent_item = btrfs_item_ptr(leaf, path->slots[0],
6111 struct btrfs_extent_item);
6112 btrfs_set_extent_refs(leaf, extent_item, 1);
6113 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6114 btrfs_set_extent_flags(leaf, extent_item,
6115 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
6117 if (skinny_metadata) {
6118 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
6120 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
6121 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
6122 btrfs_set_tree_block_level(leaf, block_info, ref->level);
6123 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
6126 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
6127 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
6128 btrfs_set_extent_inline_ref_type(leaf, iref,
6129 BTRFS_SHARED_BLOCK_REF_KEY);
6130 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
6132 btrfs_set_extent_inline_ref_type(leaf, iref,
6133 BTRFS_TREE_BLOCK_REF_KEY);
6134 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
6137 btrfs_mark_buffer_dirty(leaf);
6138 btrfs_free_path(path);
6140 ret = remove_from_free_space_tree(trans, extent_key.objectid,
6145 ret = update_block_group(trans, extent_key.objectid,
6146 fs_info->nodesize, 1);
6147 if (ret) { /* -ENOENT, logic error */
6148 btrfs_err(fs_info, "update block group failed for %llu %llu",
6149 extent_key.objectid, extent_key.offset);
6153 trace_btrfs_reserved_extent_alloc(fs_info, extent_key.objectid,
6158 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6159 struct btrfs_root *root, u64 owner,
6160 u64 offset, u64 ram_bytes,
6161 struct btrfs_key *ins)
6163 struct btrfs_ref generic_ref = { 0 };
6166 BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
6168 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
6169 ins->objectid, ins->offset, 0);
6170 btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner, offset);
6171 btrfs_ref_tree_mod(root->fs_info, &generic_ref);
6172 ret = btrfs_add_delayed_data_ref(trans, &generic_ref,
6173 ram_bytes, NULL, NULL);
6178 * this is used by the tree logging recovery code. It records that
6179 * an extent has been allocated and makes sure to clear the free
6180 * space cache bits as well
6182 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
6183 u64 root_objectid, u64 owner, u64 offset,
6184 struct btrfs_key *ins)
6186 struct btrfs_fs_info *fs_info = trans->fs_info;
6188 struct btrfs_block_group_cache *block_group;
6189 struct btrfs_space_info *space_info;
6192 * Mixed block groups will exclude before processing the log so we only
6193 * need to do the exclude dance if this fs isn't mixed.
6195 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
6196 ret = __exclude_logged_extent(fs_info, ins->objectid,
6202 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
6206 space_info = block_group->space_info;
6207 spin_lock(&space_info->lock);
6208 spin_lock(&block_group->lock);
6209 space_info->bytes_reserved += ins->offset;
6210 block_group->reserved += ins->offset;
6211 spin_unlock(&block_group->lock);
6212 spin_unlock(&space_info->lock);
6214 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
6216 btrfs_put_block_group(block_group);
6220 static struct extent_buffer *
6221 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
6222 u64 bytenr, int level, u64 owner)
6224 struct btrfs_fs_info *fs_info = root->fs_info;
6225 struct extent_buffer *buf;
6227 buf = btrfs_find_create_tree_block(fs_info, bytenr);
6232 * Extra safety check in case the extent tree is corrupted and extent
6233 * allocator chooses to use a tree block which is already used and
6236 if (buf->lock_owner == current->pid) {
6237 btrfs_err_rl(fs_info,
6238 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
6239 buf->start, btrfs_header_owner(buf), current->pid);
6240 free_extent_buffer(buf);
6241 return ERR_PTR(-EUCLEAN);
6244 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
6245 btrfs_tree_lock(buf);
6246 btrfs_clean_tree_block(buf);
6247 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
6249 btrfs_set_lock_blocking_write(buf);
6250 set_extent_buffer_uptodate(buf);
6252 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
6253 btrfs_set_header_level(buf, level);
6254 btrfs_set_header_bytenr(buf, buf->start);
6255 btrfs_set_header_generation(buf, trans->transid);
6256 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
6257 btrfs_set_header_owner(buf, owner);
6258 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
6259 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
6260 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
6261 buf->log_index = root->log_transid % 2;
6263 * we allow two log transactions at a time, use different
6264 * EXTENT bit to differentiate dirty pages.
6266 if (buf->log_index == 0)
6267 set_extent_dirty(&root->dirty_log_pages, buf->start,
6268 buf->start + buf->len - 1, GFP_NOFS);
6270 set_extent_new(&root->dirty_log_pages, buf->start,
6271 buf->start + buf->len - 1);
6273 buf->log_index = -1;
6274 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
6275 buf->start + buf->len - 1, GFP_NOFS);
6277 trans->dirty = true;
6278 /* this returns a buffer locked for blocking */
6283 * finds a free extent and does all the dirty work required for allocation
6284 * returns the tree buffer or an ERR_PTR on error.
6286 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
6287 struct btrfs_root *root,
6288 u64 parent, u64 root_objectid,
6289 const struct btrfs_disk_key *key,
6290 int level, u64 hint,
6293 struct btrfs_fs_info *fs_info = root->fs_info;
6294 struct btrfs_key ins;
6295 struct btrfs_block_rsv *block_rsv;
6296 struct extent_buffer *buf;
6297 struct btrfs_delayed_extent_op *extent_op;
6298 struct btrfs_ref generic_ref = { 0 };
6301 u32 blocksize = fs_info->nodesize;
6302 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
6304 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6305 if (btrfs_is_testing(fs_info)) {
6306 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
6307 level, root_objectid);
6309 root->alloc_bytenr += blocksize;
6314 block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
6315 if (IS_ERR(block_rsv))
6316 return ERR_CAST(block_rsv);
6318 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
6319 empty_size, hint, &ins, 0, 0);
6323 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
6327 goto out_free_reserved;
6330 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
6332 parent = ins.objectid;
6333 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
6337 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
6338 extent_op = btrfs_alloc_delayed_extent_op();
6344 memcpy(&extent_op->key, key, sizeof(extent_op->key));
6346 memset(&extent_op->key, 0, sizeof(extent_op->key));
6347 extent_op->flags_to_set = flags;
6348 extent_op->update_key = skinny_metadata ? false : true;
6349 extent_op->update_flags = true;
6350 extent_op->is_data = false;
6351 extent_op->level = level;
6353 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
6354 ins.objectid, ins.offset, parent);
6355 generic_ref.real_root = root->root_key.objectid;
6356 btrfs_init_tree_ref(&generic_ref, level, root_objectid);
6357 btrfs_ref_tree_mod(fs_info, &generic_ref);
6358 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref,
6359 extent_op, NULL, NULL);
6361 goto out_free_delayed;
6366 btrfs_free_delayed_extent_op(extent_op);
6368 free_extent_buffer(buf);
6370 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
6372 btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
6373 return ERR_PTR(ret);
6376 struct walk_control {
6377 u64 refs[BTRFS_MAX_LEVEL];
6378 u64 flags[BTRFS_MAX_LEVEL];
6379 struct btrfs_key update_progress;
6380 struct btrfs_key drop_progress;
6392 #define DROP_REFERENCE 1
6393 #define UPDATE_BACKREF 2
6395 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
6396 struct btrfs_root *root,
6397 struct walk_control *wc,
6398 struct btrfs_path *path)
6400 struct btrfs_fs_info *fs_info = root->fs_info;
6406 struct btrfs_key key;
6407 struct extent_buffer *eb;
6412 if (path->slots[wc->level] < wc->reada_slot) {
6413 wc->reada_count = wc->reada_count * 2 / 3;
6414 wc->reada_count = max(wc->reada_count, 2);
6416 wc->reada_count = wc->reada_count * 3 / 2;
6417 wc->reada_count = min_t(int, wc->reada_count,
6418 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
6421 eb = path->nodes[wc->level];
6422 nritems = btrfs_header_nritems(eb);
6424 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
6425 if (nread >= wc->reada_count)
6429 bytenr = btrfs_node_blockptr(eb, slot);
6430 generation = btrfs_node_ptr_generation(eb, slot);
6432 if (slot == path->slots[wc->level])
6435 if (wc->stage == UPDATE_BACKREF &&
6436 generation <= root->root_key.offset)
6439 /* We don't lock the tree block, it's OK to be racy here */
6440 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
6441 wc->level - 1, 1, &refs,
6443 /* We don't care about errors in readahead. */
6448 if (wc->stage == DROP_REFERENCE) {
6452 if (wc->level == 1 &&
6453 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6455 if (!wc->update_ref ||
6456 generation <= root->root_key.offset)
6458 btrfs_node_key_to_cpu(eb, &key, slot);
6459 ret = btrfs_comp_cpu_keys(&key,
6460 &wc->update_progress);
6464 if (wc->level == 1 &&
6465 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6469 readahead_tree_block(fs_info, bytenr);
6472 wc->reada_slot = slot;
6476 * helper to process tree block while walking down the tree.
6478 * when wc->stage == UPDATE_BACKREF, this function updates
6479 * back refs for pointers in the block.
6481 * NOTE: return value 1 means we should stop walking down.
6483 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
6484 struct btrfs_root *root,
6485 struct btrfs_path *path,
6486 struct walk_control *wc, int lookup_info)
6488 struct btrfs_fs_info *fs_info = root->fs_info;
6489 int level = wc->level;
6490 struct extent_buffer *eb = path->nodes[level];
6491 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
6494 if (wc->stage == UPDATE_BACKREF &&
6495 btrfs_header_owner(eb) != root->root_key.objectid)
6499 * when reference count of tree block is 1, it won't increase
6500 * again. once full backref flag is set, we never clear it.
6503 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
6504 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
6505 BUG_ON(!path->locks[level]);
6506 ret = btrfs_lookup_extent_info(trans, fs_info,
6507 eb->start, level, 1,
6510 BUG_ON(ret == -ENOMEM);
6513 BUG_ON(wc->refs[level] == 0);
6516 if (wc->stage == DROP_REFERENCE) {
6517 if (wc->refs[level] > 1)
6520 if (path->locks[level] && !wc->keep_locks) {
6521 btrfs_tree_unlock_rw(eb, path->locks[level]);
6522 path->locks[level] = 0;
6527 /* wc->stage == UPDATE_BACKREF */
6528 if (!(wc->flags[level] & flag)) {
6529 BUG_ON(!path->locks[level]);
6530 ret = btrfs_inc_ref(trans, root, eb, 1);
6531 BUG_ON(ret); /* -ENOMEM */
6532 ret = btrfs_dec_ref(trans, root, eb, 0);
6533 BUG_ON(ret); /* -ENOMEM */
6534 ret = btrfs_set_disk_extent_flags(trans, eb->start,
6536 btrfs_header_level(eb), 0);
6537 BUG_ON(ret); /* -ENOMEM */
6538 wc->flags[level] |= flag;
6542 * the block is shared by multiple trees, so it's not good to
6543 * keep the tree lock
6545 if (path->locks[level] && level > 0) {
6546 btrfs_tree_unlock_rw(eb, path->locks[level]);
6547 path->locks[level] = 0;
6553 * This is used to verify a ref exists for this root to deal with a bug where we
6554 * would have a drop_progress key that hadn't been updated properly.
6556 static int check_ref_exists(struct btrfs_trans_handle *trans,
6557 struct btrfs_root *root, u64 bytenr, u64 parent,
6560 struct btrfs_path *path;
6561 struct btrfs_extent_inline_ref *iref;
6564 path = btrfs_alloc_path();
6568 ret = lookup_extent_backref(trans, path, &iref, bytenr,
6569 root->fs_info->nodesize, parent,
6570 root->root_key.objectid, level, 0);
6571 btrfs_free_path(path);
6580 * helper to process tree block pointer.
6582 * when wc->stage == DROP_REFERENCE, this function checks
6583 * reference count of the block pointed to. if the block
6584 * is shared and we need update back refs for the subtree
6585 * rooted at the block, this function changes wc->stage to
6586 * UPDATE_BACKREF. if the block is shared and there is no
6587 * need to update back, this function drops the reference
6590 * NOTE: return value 1 means we should stop walking down.
6592 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
6593 struct btrfs_root *root,
6594 struct btrfs_path *path,
6595 struct walk_control *wc, int *lookup_info)
6597 struct btrfs_fs_info *fs_info = root->fs_info;
6601 struct btrfs_key key;
6602 struct btrfs_key first_key;
6603 struct btrfs_ref ref = { 0 };
6604 struct extent_buffer *next;
6605 int level = wc->level;
6608 bool need_account = false;
6610 generation = btrfs_node_ptr_generation(path->nodes[level],
6611 path->slots[level]);
6613 * if the lower level block was created before the snapshot
6614 * was created, we know there is no need to update back refs
6617 if (wc->stage == UPDATE_BACKREF &&
6618 generation <= root->root_key.offset) {
6623 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
6624 btrfs_node_key_to_cpu(path->nodes[level], &first_key,
6625 path->slots[level]);
6627 next = find_extent_buffer(fs_info, bytenr);
6629 next = btrfs_find_create_tree_block(fs_info, bytenr);
6631 return PTR_ERR(next);
6633 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
6637 btrfs_tree_lock(next);
6638 btrfs_set_lock_blocking_write(next);
6640 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
6641 &wc->refs[level - 1],
6642 &wc->flags[level - 1]);
6646 if (unlikely(wc->refs[level - 1] == 0)) {
6647 btrfs_err(fs_info, "Missing references.");
6653 if (wc->stage == DROP_REFERENCE) {
6654 if (wc->refs[level - 1] > 1) {
6655 need_account = true;
6657 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6660 if (!wc->update_ref ||
6661 generation <= root->root_key.offset)
6664 btrfs_node_key_to_cpu(path->nodes[level], &key,
6665 path->slots[level]);
6666 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
6670 wc->stage = UPDATE_BACKREF;
6671 wc->shared_level = level - 1;
6675 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6679 if (!btrfs_buffer_uptodate(next, generation, 0)) {
6680 btrfs_tree_unlock(next);
6681 free_extent_buffer(next);
6687 if (reada && level == 1)
6688 reada_walk_down(trans, root, wc, path);
6689 next = read_tree_block(fs_info, bytenr, generation, level - 1,
6692 return PTR_ERR(next);
6693 } else if (!extent_buffer_uptodate(next)) {
6694 free_extent_buffer(next);
6697 btrfs_tree_lock(next);
6698 btrfs_set_lock_blocking_write(next);
6702 ASSERT(level == btrfs_header_level(next));
6703 if (level != btrfs_header_level(next)) {
6704 btrfs_err(root->fs_info, "mismatched level");
6708 path->nodes[level] = next;
6709 path->slots[level] = 0;
6710 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
6716 wc->refs[level - 1] = 0;
6717 wc->flags[level - 1] = 0;
6718 if (wc->stage == DROP_REFERENCE) {
6719 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
6720 parent = path->nodes[level]->start;
6722 ASSERT(root->root_key.objectid ==
6723 btrfs_header_owner(path->nodes[level]));
6724 if (root->root_key.objectid !=
6725 btrfs_header_owner(path->nodes[level])) {
6726 btrfs_err(root->fs_info,
6727 "mismatched block owner");
6735 * If we had a drop_progress we need to verify the refs are set
6736 * as expected. If we find our ref then we know that from here
6737 * on out everything should be correct, and we can clear the
6740 if (wc->restarted) {
6741 ret = check_ref_exists(trans, root, bytenr, parent,
6752 * Reloc tree doesn't contribute to qgroup numbers, and we have
6753 * already accounted them at merge time (replace_path),
6754 * thus we could skip expensive subtree trace here.
6756 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
6758 ret = btrfs_qgroup_trace_subtree(trans, next,
6759 generation, level - 1);
6761 btrfs_err_rl(fs_info,
6762 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
6768 * We need to update the next key in our walk control so we can
6769 * update the drop_progress key accordingly. We don't care if
6770 * find_next_key doesn't find a key because that means we're at
6771 * the end and are going to clean up now.
6773 wc->drop_level = level;
6774 find_next_key(path, level, &wc->drop_progress);
6776 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
6777 fs_info->nodesize, parent);
6778 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid);
6779 ret = btrfs_free_extent(trans, &ref);
6788 btrfs_tree_unlock(next);
6789 free_extent_buffer(next);
6795 * helper to process tree block while walking up the tree.
6797 * when wc->stage == DROP_REFERENCE, this function drops
6798 * reference count on the block.
6800 * when wc->stage == UPDATE_BACKREF, this function changes
6801 * wc->stage back to DROP_REFERENCE if we changed wc->stage
6802 * to UPDATE_BACKREF previously while processing the block.
6804 * NOTE: return value 1 means we should stop walking up.
6806 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
6807 struct btrfs_root *root,
6808 struct btrfs_path *path,
6809 struct walk_control *wc)
6811 struct btrfs_fs_info *fs_info = root->fs_info;
6813 int level = wc->level;
6814 struct extent_buffer *eb = path->nodes[level];
6817 if (wc->stage == UPDATE_BACKREF) {
6818 BUG_ON(wc->shared_level < level);
6819 if (level < wc->shared_level)
6822 ret = find_next_key(path, level + 1, &wc->update_progress);
6826 wc->stage = DROP_REFERENCE;
6827 wc->shared_level = -1;
6828 path->slots[level] = 0;
6831 * check reference count again if the block isn't locked.
6832 * we should start walking down the tree again if reference
6835 if (!path->locks[level]) {
6837 btrfs_tree_lock(eb);
6838 btrfs_set_lock_blocking_write(eb);
6839 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
6841 ret = btrfs_lookup_extent_info(trans, fs_info,
6842 eb->start, level, 1,
6846 btrfs_tree_unlock_rw(eb, path->locks[level]);
6847 path->locks[level] = 0;
6850 BUG_ON(wc->refs[level] == 0);
6851 if (wc->refs[level] == 1) {
6852 btrfs_tree_unlock_rw(eb, path->locks[level]);
6853 path->locks[level] = 0;
6859 /* wc->stage == DROP_REFERENCE */
6860 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
6862 if (wc->refs[level] == 1) {
6864 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6865 ret = btrfs_dec_ref(trans, root, eb, 1);
6867 ret = btrfs_dec_ref(trans, root, eb, 0);
6868 BUG_ON(ret); /* -ENOMEM */
6869 if (is_fstree(root->root_key.objectid)) {
6870 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
6872 btrfs_err_rl(fs_info,
6873 "error %d accounting leaf items, quota is out of sync, rescan required",
6878 /* make block locked assertion in btrfs_clean_tree_block happy */
6879 if (!path->locks[level] &&
6880 btrfs_header_generation(eb) == trans->transid) {
6881 btrfs_tree_lock(eb);
6882 btrfs_set_lock_blocking_write(eb);
6883 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
6885 btrfs_clean_tree_block(eb);
6888 if (eb == root->node) {
6889 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6891 else if (root->root_key.objectid != btrfs_header_owner(eb))
6892 goto owner_mismatch;
6894 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6895 parent = path->nodes[level + 1]->start;
6896 else if (root->root_key.objectid !=
6897 btrfs_header_owner(path->nodes[level + 1]))
6898 goto owner_mismatch;
6901 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
6903 wc->refs[level] = 0;
6904 wc->flags[level] = 0;
6908 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
6909 btrfs_header_owner(eb), root->root_key.objectid);
6913 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
6914 struct btrfs_root *root,
6915 struct btrfs_path *path,
6916 struct walk_control *wc)
6918 int level = wc->level;
6919 int lookup_info = 1;
6922 while (level >= 0) {
6923 ret = walk_down_proc(trans, root, path, wc, lookup_info);
6930 if (path->slots[level] >=
6931 btrfs_header_nritems(path->nodes[level]))
6934 ret = do_walk_down(trans, root, path, wc, &lookup_info);
6936 path->slots[level]++;
6945 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
6946 struct btrfs_root *root,
6947 struct btrfs_path *path,
6948 struct walk_control *wc, int max_level)
6950 int level = wc->level;
6953 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
6954 while (level < max_level && path->nodes[level]) {
6956 if (path->slots[level] + 1 <
6957 btrfs_header_nritems(path->nodes[level])) {
6958 path->slots[level]++;
6961 ret = walk_up_proc(trans, root, path, wc);
6967 if (path->locks[level]) {
6968 btrfs_tree_unlock_rw(path->nodes[level],
6969 path->locks[level]);
6970 path->locks[level] = 0;
6972 free_extent_buffer(path->nodes[level]);
6973 path->nodes[level] = NULL;
6981 * drop a subvolume tree.
6983 * this function traverses the tree freeing any blocks that only
6984 * referenced by the tree.
6986 * when a shared tree block is found. this function decreases its
6987 * reference count by one. if update_ref is true, this function
6988 * also make sure backrefs for the shared block and all lower level
6989 * blocks are properly updated.
6991 * If called with for_reloc == 0, may exit early with -EAGAIN
6993 int btrfs_drop_snapshot(struct btrfs_root *root,
6994 struct btrfs_block_rsv *block_rsv, int update_ref,
6997 struct btrfs_fs_info *fs_info = root->fs_info;
6998 struct btrfs_path *path;
6999 struct btrfs_trans_handle *trans;
7000 struct btrfs_root *tree_root = fs_info->tree_root;
7001 struct btrfs_root_item *root_item = &root->root_item;
7002 struct walk_control *wc;
7003 struct btrfs_key key;
7007 bool root_dropped = false;
7009 btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
7011 path = btrfs_alloc_path();
7017 wc = kzalloc(sizeof(*wc), GFP_NOFS);
7019 btrfs_free_path(path);
7024 trans = btrfs_start_transaction(tree_root, 0);
7025 if (IS_ERR(trans)) {
7026 err = PTR_ERR(trans);
7030 err = btrfs_run_delayed_items(trans);
7035 trans->block_rsv = block_rsv;
7038 * This will help us catch people modifying the fs tree while we're
7039 * dropping it. It is unsafe to mess with the fs tree while it's being
7040 * dropped as we unlock the root node and parent nodes as we walk down
7041 * the tree, assuming nothing will change. If something does change
7042 * then we'll have stale information and drop references to blocks we've
7045 set_bit(BTRFS_ROOT_DELETING, &root->state);
7046 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
7047 level = btrfs_header_level(root->node);
7048 path->nodes[level] = btrfs_lock_root_node(root);
7049 btrfs_set_lock_blocking_write(path->nodes[level]);
7050 path->slots[level] = 0;
7051 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7052 memset(&wc->update_progress, 0,
7053 sizeof(wc->update_progress));
7055 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
7056 memcpy(&wc->update_progress, &key,
7057 sizeof(wc->update_progress));
7059 level = root_item->drop_level;
7061 path->lowest_level = level;
7062 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7063 path->lowest_level = 0;
7071 * unlock our path, this is safe because only this
7072 * function is allowed to delete this snapshot
7074 btrfs_unlock_up_safe(path, 0);
7076 level = btrfs_header_level(root->node);
7078 btrfs_tree_lock(path->nodes[level]);
7079 btrfs_set_lock_blocking_write(path->nodes[level]);
7080 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7082 ret = btrfs_lookup_extent_info(trans, fs_info,
7083 path->nodes[level]->start,
7084 level, 1, &wc->refs[level],
7090 BUG_ON(wc->refs[level] == 0);
7092 if (level == root_item->drop_level)
7095 btrfs_tree_unlock(path->nodes[level]);
7096 path->locks[level] = 0;
7097 WARN_ON(wc->refs[level] != 1);
7102 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
7104 wc->shared_level = -1;
7105 wc->stage = DROP_REFERENCE;
7106 wc->update_ref = update_ref;
7108 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
7112 ret = walk_down_tree(trans, root, path, wc);
7118 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
7125 BUG_ON(wc->stage != DROP_REFERENCE);
7129 if (wc->stage == DROP_REFERENCE) {
7130 wc->drop_level = wc->level;
7131 btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
7133 path->slots[wc->drop_level]);
7135 btrfs_cpu_key_to_disk(&root_item->drop_progress,
7136 &wc->drop_progress);
7137 root_item->drop_level = wc->drop_level;
7139 BUG_ON(wc->level == 0);
7140 if (btrfs_should_end_transaction(trans) ||
7141 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
7142 ret = btrfs_update_root(trans, tree_root,
7146 btrfs_abort_transaction(trans, ret);
7151 btrfs_end_transaction_throttle(trans);
7152 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
7153 btrfs_debug(fs_info,
7154 "drop snapshot early exit");
7159 trans = btrfs_start_transaction(tree_root, 0);
7160 if (IS_ERR(trans)) {
7161 err = PTR_ERR(trans);
7165 trans->block_rsv = block_rsv;
7168 btrfs_release_path(path);
7172 ret = btrfs_del_root(trans, &root->root_key);
7174 btrfs_abort_transaction(trans, ret);
7179 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
7180 ret = btrfs_find_root(tree_root, &root->root_key, path,
7183 btrfs_abort_transaction(trans, ret);
7186 } else if (ret > 0) {
7187 /* if we fail to delete the orphan item this time
7188 * around, it'll get picked up the next time.
7190 * The most common failure here is just -ENOENT.
7192 btrfs_del_orphan_item(trans, tree_root,
7193 root->root_key.objectid);
7197 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
7198 btrfs_add_dropped_root(trans, root);
7200 free_extent_buffer(root->node);
7201 free_extent_buffer(root->commit_root);
7202 btrfs_put_fs_root(root);
7204 root_dropped = true;
7206 btrfs_end_transaction_throttle(trans);
7209 btrfs_free_path(path);
7212 * So if we need to stop dropping the snapshot for whatever reason we
7213 * need to make sure to add it back to the dead root list so that we
7214 * keep trying to do the work later. This also cleans up roots if we
7215 * don't have it in the radix (like when we recover after a power fail
7216 * or unmount) so we don't leak memory.
7218 if (!for_reloc && !root_dropped)
7219 btrfs_add_dead_root(root);
7220 if (err && err != -EAGAIN)
7221 btrfs_handle_fs_error(fs_info, err, NULL);
7226 * drop subtree rooted at tree block 'node'.
7228 * NOTE: this function will unlock and release tree block 'node'
7229 * only used by relocation code
7231 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
7232 struct btrfs_root *root,
7233 struct extent_buffer *node,
7234 struct extent_buffer *parent)
7236 struct btrfs_fs_info *fs_info = root->fs_info;
7237 struct btrfs_path *path;
7238 struct walk_control *wc;
7244 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
7246 path = btrfs_alloc_path();
7250 wc = kzalloc(sizeof(*wc), GFP_NOFS);
7252 btrfs_free_path(path);
7256 btrfs_assert_tree_locked(parent);
7257 parent_level = btrfs_header_level(parent);
7258 extent_buffer_get(parent);
7259 path->nodes[parent_level] = parent;
7260 path->slots[parent_level] = btrfs_header_nritems(parent);
7262 btrfs_assert_tree_locked(node);
7263 level = btrfs_header_level(node);
7264 path->nodes[level] = node;
7265 path->slots[level] = 0;
7266 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7268 wc->refs[parent_level] = 1;
7269 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
7271 wc->shared_level = -1;
7272 wc->stage = DROP_REFERENCE;
7275 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
7278 wret = walk_down_tree(trans, root, path, wc);
7284 wret = walk_up_tree(trans, root, path, wc, parent_level);
7292 btrfs_free_path(path);
7296 static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
7302 * if restripe for this chunk_type is on pick target profile and
7303 * return, otherwise do the usual balance
7305 stripped = get_restripe_target(fs_info, flags);
7307 return extended_to_chunk(stripped);
7309 num_devices = fs_info->fs_devices->rw_devices;
7311 stripped = BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID56_MASK |
7312 BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10;
7314 if (num_devices == 1) {
7315 stripped |= BTRFS_BLOCK_GROUP_DUP;
7316 stripped = flags & ~stripped;
7318 /* turn raid0 into single device chunks */
7319 if (flags & BTRFS_BLOCK_GROUP_RAID0)
7322 /* turn mirroring into duplication */
7323 if (flags & (BTRFS_BLOCK_GROUP_RAID1_MASK |
7324 BTRFS_BLOCK_GROUP_RAID10))
7325 return stripped | BTRFS_BLOCK_GROUP_DUP;
7327 /* they already had raid on here, just return */
7328 if (flags & stripped)
7331 stripped |= BTRFS_BLOCK_GROUP_DUP;
7332 stripped = flags & ~stripped;
7334 /* switch duplicated blocks with raid1 */
7335 if (flags & BTRFS_BLOCK_GROUP_DUP)
7336 return stripped | BTRFS_BLOCK_GROUP_RAID1;
7338 /* this is drive concat, leave it alone */
7344 static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
7346 struct btrfs_space_info *sinfo = cache->space_info;
7349 u64 min_allocable_bytes;
7353 * We need some metadata space and system metadata space for
7354 * allocating chunks in some corner cases until we force to set
7355 * it to be readonly.
7358 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
7360 min_allocable_bytes = SZ_1M;
7362 min_allocable_bytes = 0;
7364 spin_lock(&sinfo->lock);
7365 spin_lock(&cache->lock);
7373 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
7374 cache->bytes_super - btrfs_block_group_used(&cache->item);
7375 sinfo_used = btrfs_space_info_used(sinfo, true);
7377 if (sinfo_used + num_bytes + min_allocable_bytes <=
7378 sinfo->total_bytes) {
7379 sinfo->bytes_readonly += num_bytes;
7381 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
7385 spin_unlock(&cache->lock);
7386 spin_unlock(&sinfo->lock);
7387 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
7388 btrfs_info(cache->fs_info,
7389 "unable to make block group %llu ro",
7390 cache->key.objectid);
7391 btrfs_info(cache->fs_info,
7392 "sinfo_used=%llu bg_num_bytes=%llu min_allocable=%llu",
7393 sinfo_used, num_bytes, min_allocable_bytes);
7394 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
7399 int btrfs_inc_block_group_ro(struct btrfs_block_group_cache *cache)
7402 struct btrfs_fs_info *fs_info = cache->fs_info;
7403 struct btrfs_trans_handle *trans;
7408 trans = btrfs_join_transaction(fs_info->extent_root);
7410 return PTR_ERR(trans);
7413 * we're not allowed to set block groups readonly after the dirty
7414 * block groups cache has started writing. If it already started,
7415 * back off and let this transaction commit
7417 mutex_lock(&fs_info->ro_block_group_mutex);
7418 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
7419 u64 transid = trans->transid;
7421 mutex_unlock(&fs_info->ro_block_group_mutex);
7422 btrfs_end_transaction(trans);
7424 ret = btrfs_wait_for_commit(fs_info, transid);
7431 * if we are changing raid levels, try to allocate a corresponding
7432 * block group with the new raid level.
7434 alloc_flags = update_block_group_flags(fs_info, cache->flags);
7435 if (alloc_flags != cache->flags) {
7436 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
7438 * ENOSPC is allowed here, we may have enough space
7439 * already allocated at the new raid level to
7448 ret = inc_block_group_ro(cache, 0);
7451 alloc_flags = get_alloc_profile(fs_info, cache->space_info->flags);
7452 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
7455 ret = inc_block_group_ro(cache, 0);
7457 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
7458 alloc_flags = update_block_group_flags(fs_info, cache->flags);
7459 mutex_lock(&fs_info->chunk_mutex);
7460 check_system_chunk(trans, alloc_flags);
7461 mutex_unlock(&fs_info->chunk_mutex);
7463 mutex_unlock(&fs_info->ro_block_group_mutex);
7465 btrfs_end_transaction(trans);
7469 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
7471 u64 alloc_flags = get_alloc_profile(trans->fs_info, type);
7473 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
7477 * helper to account the unused space of all the readonly block group in the
7478 * space_info. takes mirrors into account.
7480 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
7482 struct btrfs_block_group_cache *block_group;
7486 /* It's df, we don't care if it's racy */
7487 if (list_empty(&sinfo->ro_bgs))
7490 spin_lock(&sinfo->lock);
7491 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
7492 spin_lock(&block_group->lock);
7494 if (!block_group->ro) {
7495 spin_unlock(&block_group->lock);
7499 factor = btrfs_bg_type_to_factor(block_group->flags);
7500 free_bytes += (block_group->key.offset -
7501 btrfs_block_group_used(&block_group->item)) *
7504 spin_unlock(&block_group->lock);
7506 spin_unlock(&sinfo->lock);
7511 void btrfs_dec_block_group_ro(struct btrfs_block_group_cache *cache)
7513 struct btrfs_space_info *sinfo = cache->space_info;
7518 spin_lock(&sinfo->lock);
7519 spin_lock(&cache->lock);
7521 num_bytes = cache->key.offset - cache->reserved -
7522 cache->pinned - cache->bytes_super -
7523 btrfs_block_group_used(&cache->item);
7524 sinfo->bytes_readonly -= num_bytes;
7525 list_del_init(&cache->ro_list);
7527 spin_unlock(&cache->lock);
7528 spin_unlock(&sinfo->lock);
7532 * Checks to see if it's even possible to relocate this block group.
7534 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
7535 * ok to go ahead and try.
7537 int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
7539 struct btrfs_block_group_cache *block_group;
7540 struct btrfs_space_info *space_info;
7541 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7542 struct btrfs_device *device;
7552 debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
7554 block_group = btrfs_lookup_block_group(fs_info, bytenr);
7556 /* odd, couldn't find the block group, leave it alone */
7560 "can't find block group for bytenr %llu",
7565 min_free = btrfs_block_group_used(&block_group->item);
7567 /* no bytes used, we're good */
7571 space_info = block_group->space_info;
7572 spin_lock(&space_info->lock);
7574 full = space_info->full;
7577 * if this is the last block group we have in this space, we can't
7578 * relocate it unless we're able to allocate a new chunk below.
7580 * Otherwise, we need to make sure we have room in the space to handle
7581 * all of the extents from this block group. If we can, we're good
7583 if ((space_info->total_bytes != block_group->key.offset) &&
7584 (btrfs_space_info_used(space_info, false) + min_free <
7585 space_info->total_bytes)) {
7586 spin_unlock(&space_info->lock);
7589 spin_unlock(&space_info->lock);
7592 * ok we don't have enough space, but maybe we have free space on our
7593 * devices to allocate new chunks for relocation, so loop through our
7594 * alloc devices and guess if we have enough space. if this block
7595 * group is going to be restriped, run checks against the target
7596 * profile instead of the current one.
7608 target = get_restripe_target(fs_info, block_group->flags);
7610 index = btrfs_bg_flags_to_raid_index(extended_to_chunk(target));
7613 * this is just a balance, so if we were marked as full
7614 * we know there is no space for a new chunk
7619 "no space to alloc new chunk for block group %llu",
7620 block_group->key.objectid);
7624 index = btrfs_bg_flags_to_raid_index(block_group->flags);
7627 if (index == BTRFS_RAID_RAID10) {
7631 } else if (index == BTRFS_RAID_RAID1) {
7633 } else if (index == BTRFS_RAID_DUP) {
7636 } else if (index == BTRFS_RAID_RAID0) {
7637 dev_min = fs_devices->rw_devices;
7638 min_free = div64_u64(min_free, dev_min);
7641 mutex_lock(&fs_info->chunk_mutex);
7642 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
7646 * check to make sure we can actually find a chunk with enough
7647 * space to fit our block group in.
7649 if (device->total_bytes > device->bytes_used + min_free &&
7650 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7651 ret = find_free_dev_extent(device, min_free,
7656 if (dev_nr >= dev_min)
7662 if (debug && ret == -1)
7664 "no space to allocate a new chunk for block group %llu",
7665 block_group->key.objectid);
7666 mutex_unlock(&fs_info->chunk_mutex);
7668 btrfs_put_block_group(block_group);
7672 static int find_first_block_group(struct btrfs_fs_info *fs_info,
7673 struct btrfs_path *path,
7674 struct btrfs_key *key)
7676 struct btrfs_root *root = fs_info->extent_root;
7678 struct btrfs_key found_key;
7679 struct extent_buffer *leaf;
7680 struct btrfs_block_group_item bg;
7684 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
7689 slot = path->slots[0];
7690 leaf = path->nodes[0];
7691 if (slot >= btrfs_header_nritems(leaf)) {
7692 ret = btrfs_next_leaf(root, path);
7699 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7701 if (found_key.objectid >= key->objectid &&
7702 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
7703 struct extent_map_tree *em_tree;
7704 struct extent_map *em;
7706 em_tree = &root->fs_info->mapping_tree;
7707 read_lock(&em_tree->lock);
7708 em = lookup_extent_mapping(em_tree, found_key.objectid,
7710 read_unlock(&em_tree->lock);
7713 "logical %llu len %llu found bg but no related chunk",
7714 found_key.objectid, found_key.offset);
7716 } else if (em->start != found_key.objectid ||
7717 em->len != found_key.offset) {
7719 "block group %llu len %llu mismatch with chunk %llu len %llu",
7720 found_key.objectid, found_key.offset,
7721 em->start, em->len);
7724 read_extent_buffer(leaf, &bg,
7725 btrfs_item_ptr_offset(leaf, slot),
7727 flags = btrfs_block_group_flags(&bg) &
7728 BTRFS_BLOCK_GROUP_TYPE_MASK;
7730 if (flags != (em->map_lookup->type &
7731 BTRFS_BLOCK_GROUP_TYPE_MASK)) {
7733 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
7735 found_key.offset, flags,
7736 (BTRFS_BLOCK_GROUP_TYPE_MASK &
7737 em->map_lookup->type));
7743 free_extent_map(em);
7752 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
7754 struct btrfs_block_group_cache *block_group;
7758 struct inode *inode;
7760 block_group = btrfs_lookup_first_block_group(info, last);
7761 while (block_group) {
7762 wait_block_group_cache_done(block_group);
7763 spin_lock(&block_group->lock);
7764 if (block_group->iref)
7766 spin_unlock(&block_group->lock);
7767 block_group = next_block_group(block_group);
7776 inode = block_group->inode;
7777 block_group->iref = 0;
7778 block_group->inode = NULL;
7779 spin_unlock(&block_group->lock);
7780 ASSERT(block_group->io_ctl.inode == NULL);
7782 last = block_group->key.objectid + block_group->key.offset;
7783 btrfs_put_block_group(block_group);
7788 * Must be called only after stopping all workers, since we could have block
7789 * group caching kthreads running, and therefore they could race with us if we
7790 * freed the block groups before stopping them.
7792 int btrfs_free_block_groups(struct btrfs_fs_info *info)
7794 struct btrfs_block_group_cache *block_group;
7795 struct btrfs_space_info *space_info;
7796 struct btrfs_caching_control *caching_ctl;
7799 down_write(&info->commit_root_sem);
7800 while (!list_empty(&info->caching_block_groups)) {
7801 caching_ctl = list_entry(info->caching_block_groups.next,
7802 struct btrfs_caching_control, list);
7803 list_del(&caching_ctl->list);
7804 put_caching_control(caching_ctl);
7806 up_write(&info->commit_root_sem);
7808 spin_lock(&info->unused_bgs_lock);
7809 while (!list_empty(&info->unused_bgs)) {
7810 block_group = list_first_entry(&info->unused_bgs,
7811 struct btrfs_block_group_cache,
7813 list_del_init(&block_group->bg_list);
7814 btrfs_put_block_group(block_group);
7816 spin_unlock(&info->unused_bgs_lock);
7818 spin_lock(&info->block_group_cache_lock);
7819 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
7820 block_group = rb_entry(n, struct btrfs_block_group_cache,
7822 rb_erase(&block_group->cache_node,
7823 &info->block_group_cache_tree);
7824 RB_CLEAR_NODE(&block_group->cache_node);
7825 spin_unlock(&info->block_group_cache_lock);
7827 down_write(&block_group->space_info->groups_sem);
7828 list_del(&block_group->list);
7829 up_write(&block_group->space_info->groups_sem);
7832 * We haven't cached this block group, which means we could
7833 * possibly have excluded extents on this block group.
7835 if (block_group->cached == BTRFS_CACHE_NO ||
7836 block_group->cached == BTRFS_CACHE_ERROR)
7837 free_excluded_extents(block_group);
7839 btrfs_remove_free_space_cache(block_group);
7840 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
7841 ASSERT(list_empty(&block_group->dirty_list));
7842 ASSERT(list_empty(&block_group->io_list));
7843 ASSERT(list_empty(&block_group->bg_list));
7844 ASSERT(atomic_read(&block_group->count) == 1);
7845 btrfs_put_block_group(block_group);
7847 spin_lock(&info->block_group_cache_lock);
7849 spin_unlock(&info->block_group_cache_lock);
7851 /* now that all the block groups are freed, go through and
7852 * free all the space_info structs. This is only called during
7853 * the final stages of unmount, and so we know nobody is
7854 * using them. We call synchronize_rcu() once before we start,
7855 * just to be on the safe side.
7859 btrfs_release_global_block_rsv(info);
7861 while (!list_empty(&info->space_info)) {
7864 space_info = list_entry(info->space_info.next,
7865 struct btrfs_space_info,
7869 * Do not hide this behind enospc_debug, this is actually
7870 * important and indicates a real bug if this happens.
7872 if (WARN_ON(space_info->bytes_pinned > 0 ||
7873 space_info->bytes_reserved > 0 ||
7874 space_info->bytes_may_use > 0))
7875 btrfs_dump_space_info(info, space_info, 0, 0);
7876 list_del(&space_info->list);
7877 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
7878 struct kobject *kobj;
7879 kobj = space_info->block_group_kobjs[i];
7880 space_info->block_group_kobjs[i] = NULL;
7886 kobject_del(&space_info->kobj);
7887 kobject_put(&space_info->kobj);
7892 static void link_block_group(struct btrfs_block_group_cache *cache)
7894 struct btrfs_space_info *space_info = cache->space_info;
7895 struct btrfs_fs_info *fs_info = cache->fs_info;
7896 int index = btrfs_bg_flags_to_raid_index(cache->flags);
7899 down_write(&space_info->groups_sem);
7900 if (list_empty(&space_info->block_groups[index]))
7902 list_add_tail(&cache->list, &space_info->block_groups[index]);
7903 up_write(&space_info->groups_sem);
7906 struct raid_kobject *rkobj;
7907 unsigned int nofs_flag;
7911 * Setup a NOFS context because kobject_add(), deep in its call
7912 * chain, does GFP_KERNEL allocations, and we are often called
7913 * in a context where if reclaim is triggered we can deadlock
7914 * (we are either holding a transaction handle or some lock
7915 * required for a transaction commit).
7917 nofs_flag = memalloc_nofs_save();
7918 rkobj = kzalloc(sizeof(*rkobj), GFP_KERNEL);
7920 memalloc_nofs_restore(nofs_flag);
7921 btrfs_warn(cache->fs_info,
7922 "couldn't alloc memory for raid level kobject");
7925 rkobj->flags = cache->flags;
7926 kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
7927 ret = kobject_add(&rkobj->kobj, &space_info->kobj, "%s",
7928 btrfs_bg_type_to_raid_name(rkobj->flags));
7929 memalloc_nofs_restore(nofs_flag);
7931 kobject_put(&rkobj->kobj);
7933 "failed to add kobject for block cache, ignoring");
7936 space_info->block_group_kobjs[index] = &rkobj->kobj;
7940 static struct btrfs_block_group_cache *
7941 btrfs_create_block_group_cache(struct btrfs_fs_info *fs_info,
7942 u64 start, u64 size)
7944 struct btrfs_block_group_cache *cache;
7946 cache = kzalloc(sizeof(*cache), GFP_NOFS);
7950 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
7952 if (!cache->free_space_ctl) {
7957 cache->key.objectid = start;
7958 cache->key.offset = size;
7959 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
7961 cache->fs_info = fs_info;
7962 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
7963 set_free_space_tree_thresholds(cache);
7965 atomic_set(&cache->count, 1);
7966 spin_lock_init(&cache->lock);
7967 init_rwsem(&cache->data_rwsem);
7968 INIT_LIST_HEAD(&cache->list);
7969 INIT_LIST_HEAD(&cache->cluster_list);
7970 INIT_LIST_HEAD(&cache->bg_list);
7971 INIT_LIST_HEAD(&cache->ro_list);
7972 INIT_LIST_HEAD(&cache->dirty_list);
7973 INIT_LIST_HEAD(&cache->io_list);
7974 btrfs_init_free_space_ctl(cache);
7975 atomic_set(&cache->trimming, 0);
7976 mutex_init(&cache->free_space_lock);
7977 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
7984 * Iterate all chunks and verify that each of them has the corresponding block
7987 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
7989 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7990 struct extent_map *em;
7991 struct btrfs_block_group_cache *bg;
7996 read_lock(&map_tree->lock);
7998 * lookup_extent_mapping will return the first extent map
7999 * intersecting the range, so setting @len to 1 is enough to
8000 * get the first chunk.
8002 em = lookup_extent_mapping(map_tree, start, 1);
8003 read_unlock(&map_tree->lock);
8007 bg = btrfs_lookup_block_group(fs_info, em->start);
8010 "chunk start=%llu len=%llu doesn't have corresponding block group",
8011 em->start, em->len);
8013 free_extent_map(em);
8016 if (bg->key.objectid != em->start ||
8017 bg->key.offset != em->len ||
8018 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
8019 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
8021 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
8023 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
8024 bg->key.objectid, bg->key.offset,
8025 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
8027 free_extent_map(em);
8028 btrfs_put_block_group(bg);
8031 start = em->start + em->len;
8032 free_extent_map(em);
8033 btrfs_put_block_group(bg);
8038 int btrfs_read_block_groups(struct btrfs_fs_info *info)
8040 struct btrfs_path *path;
8042 struct btrfs_block_group_cache *cache;
8043 struct btrfs_space_info *space_info;
8044 struct btrfs_key key;
8045 struct btrfs_key found_key;
8046 struct extent_buffer *leaf;
8052 feature = btrfs_super_incompat_flags(info->super_copy);
8053 mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
8057 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
8058 path = btrfs_alloc_path();
8061 path->reada = READA_FORWARD;
8063 cache_gen = btrfs_super_cache_generation(info->super_copy);
8064 if (btrfs_test_opt(info, SPACE_CACHE) &&
8065 btrfs_super_generation(info->super_copy) != cache_gen)
8067 if (btrfs_test_opt(info, CLEAR_CACHE))
8071 ret = find_first_block_group(info, path, &key);
8077 leaf = path->nodes[0];
8078 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8080 cache = btrfs_create_block_group_cache(info, found_key.objectid,
8089 * When we mount with old space cache, we need to
8090 * set BTRFS_DC_CLEAR and set dirty flag.
8092 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
8093 * truncate the old free space cache inode and
8095 * b) Setting 'dirty flag' makes sure that we flush
8096 * the new space cache info onto disk.
8098 if (btrfs_test_opt(info, SPACE_CACHE))
8099 cache->disk_cache_state = BTRFS_DC_CLEAR;
8102 read_extent_buffer(leaf, &cache->item,
8103 btrfs_item_ptr_offset(leaf, path->slots[0]),
8104 sizeof(cache->item));
8105 cache->flags = btrfs_block_group_flags(&cache->item);
8107 ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
8108 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
8110 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
8111 cache->key.objectid);
8116 key.objectid = found_key.objectid + found_key.offset;
8117 btrfs_release_path(path);
8120 * We need to exclude the super stripes now so that the space
8121 * info has super bytes accounted for, otherwise we'll think
8122 * we have more space than we actually do.
8124 ret = exclude_super_stripes(cache);
8127 * We may have excluded something, so call this just in
8130 free_excluded_extents(cache);
8131 btrfs_put_block_group(cache);
8136 * check for two cases, either we are full, and therefore
8137 * don't need to bother with the caching work since we won't
8138 * find any space, or we are empty, and we can just add all
8139 * the space in and be done with it. This saves us _a_lot_ of
8140 * time, particularly in the full case.
8142 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
8143 cache->last_byte_to_unpin = (u64)-1;
8144 cache->cached = BTRFS_CACHE_FINISHED;
8145 free_excluded_extents(cache);
8146 } else if (btrfs_block_group_used(&cache->item) == 0) {
8147 cache->last_byte_to_unpin = (u64)-1;
8148 cache->cached = BTRFS_CACHE_FINISHED;
8149 add_new_free_space(cache, found_key.objectid,
8150 found_key.objectid +
8152 free_excluded_extents(cache);
8155 ret = btrfs_add_block_group_cache(info, cache);
8157 btrfs_remove_free_space_cache(cache);
8158 btrfs_put_block_group(cache);
8162 trace_btrfs_add_block_group(info, cache, 0);
8163 btrfs_update_space_info(info, cache->flags, found_key.offset,
8164 btrfs_block_group_used(&cache->item),
8165 cache->bytes_super, &space_info);
8167 cache->space_info = space_info;
8169 link_block_group(cache);
8171 set_avail_alloc_bits(info, cache->flags);
8172 if (btrfs_chunk_readonly(info, cache->key.objectid)) {
8173 inc_block_group_ro(cache, 1);
8174 } else if (btrfs_block_group_used(&cache->item) == 0) {
8175 ASSERT(list_empty(&cache->bg_list));
8176 btrfs_mark_bg_unused(cache);
8180 list_for_each_entry_rcu(space_info, &info->space_info, list) {
8181 if (!(get_alloc_profile(info, space_info->flags) &
8182 (BTRFS_BLOCK_GROUP_RAID10 |
8183 BTRFS_BLOCK_GROUP_RAID1_MASK |
8184 BTRFS_BLOCK_GROUP_RAID56_MASK |
8185 BTRFS_BLOCK_GROUP_DUP)))
8188 * avoid allocating from un-mirrored block group if there are
8189 * mirrored block groups.
8191 list_for_each_entry(cache,
8192 &space_info->block_groups[BTRFS_RAID_RAID0],
8194 inc_block_group_ro(cache, 1);
8195 list_for_each_entry(cache,
8196 &space_info->block_groups[BTRFS_RAID_SINGLE],
8198 inc_block_group_ro(cache, 1);
8201 btrfs_init_global_block_rsv(info);
8202 ret = check_chunk_block_group_mappings(info);
8204 btrfs_free_path(path);
8208 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
8210 struct btrfs_fs_info *fs_info = trans->fs_info;
8211 struct btrfs_block_group_cache *block_group;
8212 struct btrfs_root *extent_root = fs_info->extent_root;
8213 struct btrfs_block_group_item item;
8214 struct btrfs_key key;
8217 if (!trans->can_flush_pending_bgs)
8220 while (!list_empty(&trans->new_bgs)) {
8221 block_group = list_first_entry(&trans->new_bgs,
8222 struct btrfs_block_group_cache,
8227 spin_lock(&block_group->lock);
8228 memcpy(&item, &block_group->item, sizeof(item));
8229 memcpy(&key, &block_group->key, sizeof(key));
8230 spin_unlock(&block_group->lock);
8232 ret = btrfs_insert_item(trans, extent_root, &key, &item,
8235 btrfs_abort_transaction(trans, ret);
8236 ret = btrfs_finish_chunk_alloc(trans, key.objectid, key.offset);
8238 btrfs_abort_transaction(trans, ret);
8239 add_block_group_free_space(trans, block_group);
8240 /* already aborted the transaction if it failed. */
8242 btrfs_delayed_refs_rsv_release(fs_info, 1);
8243 list_del_init(&block_group->bg_list);
8245 btrfs_trans_release_chunk_metadata(trans);
8248 int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
8249 u64 type, u64 chunk_offset, u64 size)
8251 struct btrfs_fs_info *fs_info = trans->fs_info;
8252 struct btrfs_block_group_cache *cache;
8255 btrfs_set_log_full_commit(trans);
8257 cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
8261 btrfs_set_block_group_used(&cache->item, bytes_used);
8262 btrfs_set_block_group_chunk_objectid(&cache->item,
8263 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
8264 btrfs_set_block_group_flags(&cache->item, type);
8266 cache->flags = type;
8267 cache->last_byte_to_unpin = (u64)-1;
8268 cache->cached = BTRFS_CACHE_FINISHED;
8269 cache->needs_free_space = 1;
8270 ret = exclude_super_stripes(cache);
8273 * We may have excluded something, so call this just in
8276 free_excluded_extents(cache);
8277 btrfs_put_block_group(cache);
8281 add_new_free_space(cache, chunk_offset, chunk_offset + size);
8283 free_excluded_extents(cache);
8285 #ifdef CONFIG_BTRFS_DEBUG
8286 if (btrfs_should_fragment_free_space(cache)) {
8287 u64 new_bytes_used = size - bytes_used;
8289 bytes_used += new_bytes_used >> 1;
8290 fragment_free_space(cache);
8294 * Ensure the corresponding space_info object is created and
8295 * assigned to our block group. We want our bg to be added to the rbtree
8296 * with its ->space_info set.
8298 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
8299 ASSERT(cache->space_info);
8301 ret = btrfs_add_block_group_cache(fs_info, cache);
8303 btrfs_remove_free_space_cache(cache);
8304 btrfs_put_block_group(cache);
8309 * Now that our block group has its ->space_info set and is inserted in
8310 * the rbtree, update the space info's counters.
8312 trace_btrfs_add_block_group(fs_info, cache, 1);
8313 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
8314 cache->bytes_super, &cache->space_info);
8315 btrfs_update_global_block_rsv(fs_info);
8317 link_block_group(cache);
8319 list_add_tail(&cache->bg_list, &trans->new_bgs);
8320 trans->delayed_ref_updates++;
8321 btrfs_update_delayed_refs_rsv(trans);
8323 set_avail_alloc_bits(fs_info, type);
8327 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
8329 u64 extra_flags = chunk_to_extended(flags) &
8330 BTRFS_EXTENDED_PROFILE_MASK;
8332 write_seqlock(&fs_info->profiles_lock);
8333 if (flags & BTRFS_BLOCK_GROUP_DATA)
8334 fs_info->avail_data_alloc_bits &= ~extra_flags;
8335 if (flags & BTRFS_BLOCK_GROUP_METADATA)
8336 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
8337 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
8338 fs_info->avail_system_alloc_bits &= ~extra_flags;
8339 write_sequnlock(&fs_info->profiles_lock);
8343 * Clear incompat bits for the following feature(s):
8345 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
8346 * in the whole filesystem
8348 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
8350 if (flags & BTRFS_BLOCK_GROUP_RAID56_MASK) {
8351 struct list_head *head = &fs_info->space_info;
8352 struct btrfs_space_info *sinfo;
8354 list_for_each_entry_rcu(sinfo, head, list) {
8357 down_read(&sinfo->groups_sem);
8358 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
8360 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
8362 up_read(&sinfo->groups_sem);
8367 btrfs_clear_fs_incompat(fs_info, RAID56);
8371 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
8372 u64 group_start, struct extent_map *em)
8374 struct btrfs_fs_info *fs_info = trans->fs_info;
8375 struct btrfs_root *root = fs_info->extent_root;
8376 struct btrfs_path *path;
8377 struct btrfs_block_group_cache *block_group;
8378 struct btrfs_free_cluster *cluster;
8379 struct btrfs_root *tree_root = fs_info->tree_root;
8380 struct btrfs_key key;
8381 struct inode *inode;
8382 struct kobject *kobj = NULL;
8386 struct btrfs_caching_control *caching_ctl = NULL;
8388 bool remove_rsv = false;
8390 block_group = btrfs_lookup_block_group(fs_info, group_start);
8391 BUG_ON(!block_group);
8392 BUG_ON(!block_group->ro);
8394 trace_btrfs_remove_block_group(block_group);
8396 * Free the reserved super bytes from this block group before
8399 free_excluded_extents(block_group);
8400 btrfs_free_ref_tree_range(fs_info, block_group->key.objectid,
8401 block_group->key.offset);
8403 memcpy(&key, &block_group->key, sizeof(key));
8404 index = btrfs_bg_flags_to_raid_index(block_group->flags);
8405 factor = btrfs_bg_type_to_factor(block_group->flags);
8407 /* make sure this block group isn't part of an allocation cluster */
8408 cluster = &fs_info->data_alloc_cluster;
8409 spin_lock(&cluster->refill_lock);
8410 btrfs_return_cluster_to_free_space(block_group, cluster);
8411 spin_unlock(&cluster->refill_lock);
8414 * make sure this block group isn't part of a metadata
8415 * allocation cluster
8417 cluster = &fs_info->meta_alloc_cluster;
8418 spin_lock(&cluster->refill_lock);
8419 btrfs_return_cluster_to_free_space(block_group, cluster);
8420 spin_unlock(&cluster->refill_lock);
8422 path = btrfs_alloc_path();
8429 * get the inode first so any iput calls done for the io_list
8430 * aren't the final iput (no unlinks allowed now)
8432 inode = lookup_free_space_inode(block_group, path);
8434 mutex_lock(&trans->transaction->cache_write_mutex);
8436 * Make sure our free space cache IO is done before removing the
8439 spin_lock(&trans->transaction->dirty_bgs_lock);
8440 if (!list_empty(&block_group->io_list)) {
8441 list_del_init(&block_group->io_list);
8443 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
8445 spin_unlock(&trans->transaction->dirty_bgs_lock);
8446 btrfs_wait_cache_io(trans, block_group, path);
8447 btrfs_put_block_group(block_group);
8448 spin_lock(&trans->transaction->dirty_bgs_lock);
8451 if (!list_empty(&block_group->dirty_list)) {
8452 list_del_init(&block_group->dirty_list);
8454 btrfs_put_block_group(block_group);
8456 spin_unlock(&trans->transaction->dirty_bgs_lock);
8457 mutex_unlock(&trans->transaction->cache_write_mutex);
8459 if (!IS_ERR(inode)) {
8460 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
8462 btrfs_add_delayed_iput(inode);
8466 /* One for the block groups ref */
8467 spin_lock(&block_group->lock);
8468 if (block_group->iref) {
8469 block_group->iref = 0;
8470 block_group->inode = NULL;
8471 spin_unlock(&block_group->lock);
8474 spin_unlock(&block_group->lock);
8476 /* One for our lookup ref */
8477 btrfs_add_delayed_iput(inode);
8480 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
8481 key.offset = block_group->key.objectid;
8484 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
8488 btrfs_release_path(path);
8490 ret = btrfs_del_item(trans, tree_root, path);
8493 btrfs_release_path(path);
8496 spin_lock(&fs_info->block_group_cache_lock);
8497 rb_erase(&block_group->cache_node,
8498 &fs_info->block_group_cache_tree);
8499 RB_CLEAR_NODE(&block_group->cache_node);
8501 if (fs_info->first_logical_byte == block_group->key.objectid)
8502 fs_info->first_logical_byte = (u64)-1;
8503 spin_unlock(&fs_info->block_group_cache_lock);
8505 down_write(&block_group->space_info->groups_sem);
8507 * we must use list_del_init so people can check to see if they
8508 * are still on the list after taking the semaphore
8510 list_del_init(&block_group->list);
8511 if (list_empty(&block_group->space_info->block_groups[index])) {
8512 kobj = block_group->space_info->block_group_kobjs[index];
8513 block_group->space_info->block_group_kobjs[index] = NULL;
8514 clear_avail_alloc_bits(fs_info, block_group->flags);
8516 up_write(&block_group->space_info->groups_sem);
8517 clear_incompat_bg_bits(fs_info, block_group->flags);
8523 if (block_group->has_caching_ctl)
8524 caching_ctl = get_caching_control(block_group);
8525 if (block_group->cached == BTRFS_CACHE_STARTED)
8526 wait_block_group_cache_done(block_group);
8527 if (block_group->has_caching_ctl) {
8528 down_write(&fs_info->commit_root_sem);
8530 struct btrfs_caching_control *ctl;
8532 list_for_each_entry(ctl,
8533 &fs_info->caching_block_groups, list)
8534 if (ctl->block_group == block_group) {
8536 refcount_inc(&caching_ctl->count);
8541 list_del_init(&caching_ctl->list);
8542 up_write(&fs_info->commit_root_sem);
8544 /* Once for the caching bgs list and once for us. */
8545 put_caching_control(caching_ctl);
8546 put_caching_control(caching_ctl);
8550 spin_lock(&trans->transaction->dirty_bgs_lock);
8551 WARN_ON(!list_empty(&block_group->dirty_list));
8552 WARN_ON(!list_empty(&block_group->io_list));
8553 spin_unlock(&trans->transaction->dirty_bgs_lock);
8555 btrfs_remove_free_space_cache(block_group);
8557 spin_lock(&block_group->space_info->lock);
8558 list_del_init(&block_group->ro_list);
8560 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8561 WARN_ON(block_group->space_info->total_bytes
8562 < block_group->key.offset);
8563 WARN_ON(block_group->space_info->bytes_readonly
8564 < block_group->key.offset);
8565 WARN_ON(block_group->space_info->disk_total
8566 < block_group->key.offset * factor);
8568 block_group->space_info->total_bytes -= block_group->key.offset;
8569 block_group->space_info->bytes_readonly -= block_group->key.offset;
8570 block_group->space_info->disk_total -= block_group->key.offset * factor;
8572 spin_unlock(&block_group->space_info->lock);
8574 memcpy(&key, &block_group->key, sizeof(key));
8576 mutex_lock(&fs_info->chunk_mutex);
8577 spin_lock(&block_group->lock);
8578 block_group->removed = 1;
8580 * At this point trimming can't start on this block group, because we
8581 * removed the block group from the tree fs_info->block_group_cache_tree
8582 * so no one can't find it anymore and even if someone already got this
8583 * block group before we removed it from the rbtree, they have already
8584 * incremented block_group->trimming - if they didn't, they won't find
8585 * any free space entries because we already removed them all when we
8586 * called btrfs_remove_free_space_cache().
8588 * And we must not remove the extent map from the fs_info->mapping_tree
8589 * to prevent the same logical address range and physical device space
8590 * ranges from being reused for a new block group. This is because our
8591 * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
8592 * completely transactionless, so while it is trimming a range the
8593 * currently running transaction might finish and a new one start,
8594 * allowing for new block groups to be created that can reuse the same
8595 * physical device locations unless we take this special care.
8597 * There may also be an implicit trim operation if the file system
8598 * is mounted with -odiscard. The same protections must remain
8599 * in place until the extents have been discarded completely when
8600 * the transaction commit has completed.
8602 remove_em = (atomic_read(&block_group->trimming) == 0);
8603 spin_unlock(&block_group->lock);
8605 mutex_unlock(&fs_info->chunk_mutex);
8607 ret = remove_block_group_free_space(trans, block_group);
8611 btrfs_put_block_group(block_group);
8612 btrfs_put_block_group(block_group);
8614 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8620 ret = btrfs_del_item(trans, root, path);
8625 struct extent_map_tree *em_tree;
8627 em_tree = &fs_info->mapping_tree;
8628 write_lock(&em_tree->lock);
8629 remove_extent_mapping(em_tree, em);
8630 write_unlock(&em_tree->lock);
8631 /* once for the tree */
8632 free_extent_map(em);
8636 btrfs_delayed_refs_rsv_release(fs_info, 1);
8637 btrfs_free_path(path);
8641 struct btrfs_trans_handle *
8642 btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
8643 const u64 chunk_offset)
8645 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
8646 struct extent_map *em;
8647 struct map_lookup *map;
8648 unsigned int num_items;
8650 read_lock(&em_tree->lock);
8651 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
8652 read_unlock(&em_tree->lock);
8653 ASSERT(em && em->start == chunk_offset);
8656 * We need to reserve 3 + N units from the metadata space info in order
8657 * to remove a block group (done at btrfs_remove_chunk() and at
8658 * btrfs_remove_block_group()), which are used for:
8660 * 1 unit for adding the free space inode's orphan (located in the tree
8662 * 1 unit for deleting the block group item (located in the extent
8664 * 1 unit for deleting the free space item (located in tree of tree
8666 * N units for deleting N device extent items corresponding to each
8667 * stripe (located in the device tree).
8669 * In order to remove a block group we also need to reserve units in the
8670 * system space info in order to update the chunk tree (update one or
8671 * more device items and remove one chunk item), but this is done at
8672 * btrfs_remove_chunk() through a call to check_system_chunk().
8674 map = em->map_lookup;
8675 num_items = 3 + map->num_stripes;
8676 free_extent_map(em);
8678 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
8683 * Process the unused_bgs list and remove any that don't have any allocated
8684 * space inside of them.
8686 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
8688 struct btrfs_block_group_cache *block_group;
8689 struct btrfs_space_info *space_info;
8690 struct btrfs_trans_handle *trans;
8693 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
8696 spin_lock(&fs_info->unused_bgs_lock);
8697 while (!list_empty(&fs_info->unused_bgs)) {
8701 block_group = list_first_entry(&fs_info->unused_bgs,
8702 struct btrfs_block_group_cache,
8704 list_del_init(&block_group->bg_list);
8706 space_info = block_group->space_info;
8708 if (ret || btrfs_mixed_space_info(space_info)) {
8709 btrfs_put_block_group(block_group);
8712 spin_unlock(&fs_info->unused_bgs_lock);
8714 mutex_lock(&fs_info->delete_unused_bgs_mutex);
8716 /* Don't want to race with allocators so take the groups_sem */
8717 down_write(&space_info->groups_sem);
8718 spin_lock(&block_group->lock);
8719 if (block_group->reserved || block_group->pinned ||
8720 btrfs_block_group_used(&block_group->item) ||
8722 list_is_singular(&block_group->list)) {
8724 * We want to bail if we made new allocations or have
8725 * outstanding allocations in this block group. We do
8726 * the ro check in case balance is currently acting on
8729 trace_btrfs_skip_unused_block_group(block_group);
8730 spin_unlock(&block_group->lock);
8731 up_write(&space_info->groups_sem);
8734 spin_unlock(&block_group->lock);
8736 /* We don't want to force the issue, only flip if it's ok. */
8737 ret = inc_block_group_ro(block_group, 0);
8738 up_write(&space_info->groups_sem);
8745 * Want to do this before we do anything else so we can recover
8746 * properly if we fail to join the transaction.
8748 trans = btrfs_start_trans_remove_block_group(fs_info,
8749 block_group->key.objectid);
8750 if (IS_ERR(trans)) {
8751 btrfs_dec_block_group_ro(block_group);
8752 ret = PTR_ERR(trans);
8757 * We could have pending pinned extents for this block group,
8758 * just delete them, we don't care about them anymore.
8760 start = block_group->key.objectid;
8761 end = start + block_group->key.offset - 1;
8763 * Hold the unused_bg_unpin_mutex lock to avoid racing with
8764 * btrfs_finish_extent_commit(). If we are at transaction N,
8765 * another task might be running finish_extent_commit() for the
8766 * previous transaction N - 1, and have seen a range belonging
8767 * to the block group in freed_extents[] before we were able to
8768 * clear the whole block group range from freed_extents[]. This
8769 * means that task can lookup for the block group after we
8770 * unpinned it from freed_extents[] and removed it, leading to
8771 * a BUG_ON() at btrfs_unpin_extent_range().
8773 mutex_lock(&fs_info->unused_bg_unpin_mutex);
8774 ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
8777 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
8778 btrfs_dec_block_group_ro(block_group);
8781 ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
8784 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
8785 btrfs_dec_block_group_ro(block_group);
8788 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
8790 /* Reset pinned so btrfs_put_block_group doesn't complain */
8791 spin_lock(&space_info->lock);
8792 spin_lock(&block_group->lock);
8794 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
8795 -block_group->pinned);
8796 space_info->bytes_readonly += block_group->pinned;
8797 percpu_counter_add_batch(&space_info->total_bytes_pinned,
8798 -block_group->pinned,
8799 BTRFS_TOTAL_BYTES_PINNED_BATCH);
8800 block_group->pinned = 0;
8802 spin_unlock(&block_group->lock);
8803 spin_unlock(&space_info->lock);
8805 /* DISCARD can flip during remount */
8806 trimming = btrfs_test_opt(fs_info, DISCARD);
8808 /* Implicit trim during transaction commit. */
8810 btrfs_get_block_group_trimming(block_group);
8813 * Btrfs_remove_chunk will abort the transaction if things go
8816 ret = btrfs_remove_chunk(trans, block_group->key.objectid);
8820 btrfs_put_block_group_trimming(block_group);
8825 * If we're not mounted with -odiscard, we can just forget
8826 * about this block group. Otherwise we'll need to wait
8827 * until transaction commit to do the actual discard.
8830 spin_lock(&fs_info->unused_bgs_lock);
8832 * A concurrent scrub might have added us to the list
8833 * fs_info->unused_bgs, so use a list_move operation
8834 * to add the block group to the deleted_bgs list.
8836 list_move(&block_group->bg_list,
8837 &trans->transaction->deleted_bgs);
8838 spin_unlock(&fs_info->unused_bgs_lock);
8839 btrfs_get_block_group(block_group);
8842 btrfs_end_transaction(trans);
8844 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
8845 btrfs_put_block_group(block_group);
8846 spin_lock(&fs_info->unused_bgs_lock);
8848 spin_unlock(&fs_info->unused_bgs_lock);
8851 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
8854 return unpin_extent_range(fs_info, start, end, false);
8858 * It used to be that old block groups would be left around forever.
8859 * Iterating over them would be enough to trim unused space. Since we
8860 * now automatically remove them, we also need to iterate over unallocated
8863 * We don't want a transaction for this since the discard may take a
8864 * substantial amount of time. We don't require that a transaction be
8865 * running, but we do need to take a running transaction into account
8866 * to ensure that we're not discarding chunks that were released or
8867 * allocated in the current transaction.
8869 * Holding the chunks lock will prevent other threads from allocating
8870 * or releasing chunks, but it won't prevent a running transaction
8871 * from committing and releasing the memory that the pending chunks
8872 * list head uses. For that, we need to take a reference to the
8873 * transaction and hold the commit root sem. We only need to hold
8874 * it while performing the free space search since we have already
8875 * held back allocations.
8877 static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
8879 u64 start = SZ_1M, len = 0, end = 0;
8884 /* Discard not supported = nothing to do. */
8885 if (!blk_queue_discard(bdev_get_queue(device->bdev)))
8888 /* Not writable = nothing to do. */
8889 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
8892 /* No free space = nothing to do. */
8893 if (device->total_bytes <= device->bytes_used)
8899 struct btrfs_fs_info *fs_info = device->fs_info;
8902 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
8906 find_first_clear_extent_bit(&device->alloc_state, start,
8908 CHUNK_TRIMMED | CHUNK_ALLOCATED);
8910 /* Ensure we skip the reserved area in the first 1M */
8911 start = max_t(u64, start, SZ_1M);
8914 * If find_first_clear_extent_bit find a range that spans the
8915 * end of the device it will set end to -1, in this case it's up
8916 * to the caller to trim the value to the size of the device.
8918 end = min(end, device->total_bytes - 1);
8920 len = end - start + 1;
8922 /* We didn't find any extents */
8924 mutex_unlock(&fs_info->chunk_mutex);
8929 ret = btrfs_issue_discard(device->bdev, start, len,
8932 set_extent_bits(&device->alloc_state, start,
8935 mutex_unlock(&fs_info->chunk_mutex);
8943 if (fatal_signal_pending(current)) {
8955 * Trim the whole filesystem by:
8956 * 1) trimming the free space in each block group
8957 * 2) trimming the unallocated space on each device
8959 * This will also continue trimming even if a block group or device encounters
8960 * an error. The return value will be the last error, or 0 if nothing bad
8963 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
8965 struct btrfs_block_group_cache *cache = NULL;
8966 struct btrfs_device *device;
8967 struct list_head *devices;
8969 u64 range_end = U64_MAX;
8980 * Check range overflow if range->len is set.
8981 * The default range->len is U64_MAX.
8983 if (range->len != U64_MAX &&
8984 check_add_overflow(range->start, range->len, &range_end))
8987 cache = btrfs_lookup_first_block_group(fs_info, range->start);
8988 for (; cache; cache = next_block_group(cache)) {
8989 if (cache->key.objectid >= range_end) {
8990 btrfs_put_block_group(cache);
8994 start = max(range->start, cache->key.objectid);
8995 end = min(range_end, cache->key.objectid + cache->key.offset);
8997 if (end - start >= range->minlen) {
8998 if (!block_group_cache_done(cache)) {
8999 ret = cache_block_group(cache, 0);
9005 ret = wait_block_group_cache_done(cache);
9012 ret = btrfs_trim_block_group(cache,
9018 trimmed += group_trimmed;
9029 "failed to trim %llu block group(s), last error %d",
9031 mutex_lock(&fs_info->fs_devices->device_list_mutex);
9032 devices = &fs_info->fs_devices->devices;
9033 list_for_each_entry(device, devices, dev_list) {
9034 ret = btrfs_trim_free_extents(device, &group_trimmed);
9041 trimmed += group_trimmed;
9043 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
9047 "failed to trim %llu device(s), last error %d",
9048 dev_failed, dev_ret);
9049 range->len = trimmed;
9056 * btrfs_{start,end}_write_no_snapshotting() are similar to
9057 * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
9058 * data into the page cache through nocow before the subvolume is snapshoted,
9059 * but flush the data into disk after the snapshot creation, or to prevent
9060 * operations while snapshotting is ongoing and that cause the snapshot to be
9061 * inconsistent (writes followed by expanding truncates for example).
9063 void btrfs_end_write_no_snapshotting(struct btrfs_root *root)
9065 percpu_counter_dec(&root->subv_writers->counter);
9066 cond_wake_up(&root->subv_writers->wait);
9069 int btrfs_start_write_no_snapshotting(struct btrfs_root *root)
9071 if (atomic_read(&root->will_be_snapshotted))
9074 percpu_counter_inc(&root->subv_writers->counter);
9076 * Make sure counter is updated before we check for snapshot creation.
9079 if (atomic_read(&root->will_be_snapshotted)) {
9080 btrfs_end_write_no_snapshotting(root);
9086 void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
9091 ret = btrfs_start_write_no_snapshotting(root);
9094 wait_var_event(&root->will_be_snapshotted,
9095 !atomic_read(&root->will_be_snapshotted));
9099 void btrfs_mark_bg_unused(struct btrfs_block_group_cache *bg)
9101 struct btrfs_fs_info *fs_info = bg->fs_info;
9103 spin_lock(&fs_info->unused_bgs_lock);
9104 if (list_empty(&bg->bg_list)) {
9105 btrfs_get_block_group(bg);
9106 trace_btrfs_add_unused_block_group(bg);
9107 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
9109 spin_unlock(&fs_info->unused_bgs_lock);