1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/sched/signal.h>
8 #include <linux/pagemap.h>
9 #include <linux/writeback.h>
10 #include <linux/blkdev.h>
11 #include <linux/sort.h>
12 #include <linux/rcupdate.h>
13 #include <linux/kthread.h>
14 #include <linux/slab.h>
15 #include <linux/ratelimit.h>
16 #include <linux/percpu_counter.h>
17 #include <linux/lockdep.h>
18 #include <linux/crc32c.h>
21 #include "print-tree.h"
25 #include "free-space-cache.h"
26 #include "free-space-tree.h"
30 #include "ref-verify.h"
31 #include "space-info.h"
33 #undef SCRAMBLE_DELAYED_REFS
36 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
37 struct btrfs_delayed_ref_node *node, u64 parent,
38 u64 root_objectid, u64 owner_objectid,
39 u64 owner_offset, int refs_to_drop,
40 struct btrfs_delayed_extent_op *extra_op);
41 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
42 struct extent_buffer *leaf,
43 struct btrfs_extent_item *ei);
44 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
45 u64 parent, u64 root_objectid,
46 u64 flags, u64 owner, u64 offset,
47 struct btrfs_key *ins, int ref_mod);
48 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
49 struct btrfs_delayed_ref_node *node,
50 struct btrfs_delayed_extent_op *extent_op);
51 static int find_next_key(struct btrfs_path *path, int level,
52 struct btrfs_key *key);
55 block_group_cache_done(struct btrfs_block_group_cache *cache)
58 return cache->cached == BTRFS_CACHE_FINISHED ||
59 cache->cached == BTRFS_CACHE_ERROR;
62 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
64 return (cache->flags & bits) == bits;
67 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
69 atomic_inc(&cache->count);
72 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
74 if (atomic_dec_and_test(&cache->count)) {
75 WARN_ON(cache->pinned > 0);
76 WARN_ON(cache->reserved > 0);
79 * If not empty, someone is still holding mutex of
80 * full_stripe_lock, which can only be released by caller.
81 * And it will definitely cause use-after-free when caller
82 * tries to release full stripe lock.
84 * No better way to resolve, but only to warn.
86 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
87 kfree(cache->free_space_ctl);
93 * this adds the block group to the fs_info rb tree for the block group
96 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
97 struct btrfs_block_group_cache *block_group)
100 struct rb_node *parent = NULL;
101 struct btrfs_block_group_cache *cache;
103 spin_lock(&info->block_group_cache_lock);
104 p = &info->block_group_cache_tree.rb_node;
108 cache = rb_entry(parent, struct btrfs_block_group_cache,
110 if (block_group->key.objectid < cache->key.objectid) {
112 } else if (block_group->key.objectid > cache->key.objectid) {
115 spin_unlock(&info->block_group_cache_lock);
120 rb_link_node(&block_group->cache_node, parent, p);
121 rb_insert_color(&block_group->cache_node,
122 &info->block_group_cache_tree);
124 if (info->first_logical_byte > block_group->key.objectid)
125 info->first_logical_byte = block_group->key.objectid;
127 spin_unlock(&info->block_group_cache_lock);
133 * This will return the block group at or after bytenr if contains is 0, else
134 * it will return the block group that contains the bytenr
136 static struct btrfs_block_group_cache *
137 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
140 struct btrfs_block_group_cache *cache, *ret = NULL;
144 spin_lock(&info->block_group_cache_lock);
145 n = info->block_group_cache_tree.rb_node;
148 cache = rb_entry(n, struct btrfs_block_group_cache,
150 end = cache->key.objectid + cache->key.offset - 1;
151 start = cache->key.objectid;
153 if (bytenr < start) {
154 if (!contains && (!ret || start < ret->key.objectid))
157 } else if (bytenr > start) {
158 if (contains && bytenr <= end) {
169 btrfs_get_block_group(ret);
170 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
171 info->first_logical_byte = ret->key.objectid;
173 spin_unlock(&info->block_group_cache_lock);
178 static int add_excluded_extent(struct btrfs_fs_info *fs_info,
179 u64 start, u64 num_bytes)
181 u64 end = start + num_bytes - 1;
182 set_extent_bits(&fs_info->freed_extents[0],
183 start, end, EXTENT_UPTODATE);
184 set_extent_bits(&fs_info->freed_extents[1],
185 start, end, EXTENT_UPTODATE);
189 static void free_excluded_extents(struct btrfs_block_group_cache *cache)
191 struct btrfs_fs_info *fs_info = cache->fs_info;
194 start = cache->key.objectid;
195 end = start + cache->key.offset - 1;
197 clear_extent_bits(&fs_info->freed_extents[0],
198 start, end, EXTENT_UPTODATE);
199 clear_extent_bits(&fs_info->freed_extents[1],
200 start, end, EXTENT_UPTODATE);
203 static int exclude_super_stripes(struct btrfs_block_group_cache *cache)
205 struct btrfs_fs_info *fs_info = cache->fs_info;
211 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
212 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
213 cache->bytes_super += stripe_len;
214 ret = add_excluded_extent(fs_info, cache->key.objectid,
220 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
221 bytenr = btrfs_sb_offset(i);
222 ret = btrfs_rmap_block(fs_info, cache->key.objectid,
223 bytenr, &logical, &nr, &stripe_len);
230 if (logical[nr] > cache->key.objectid +
234 if (logical[nr] + stripe_len <= cache->key.objectid)
238 if (start < cache->key.objectid) {
239 start = cache->key.objectid;
240 len = (logical[nr] + stripe_len) - start;
242 len = min_t(u64, stripe_len,
243 cache->key.objectid +
244 cache->key.offset - start);
247 cache->bytes_super += len;
248 ret = add_excluded_extent(fs_info, start, len);
260 static struct btrfs_caching_control *
261 get_caching_control(struct btrfs_block_group_cache *cache)
263 struct btrfs_caching_control *ctl;
265 spin_lock(&cache->lock);
266 if (!cache->caching_ctl) {
267 spin_unlock(&cache->lock);
271 ctl = cache->caching_ctl;
272 refcount_inc(&ctl->count);
273 spin_unlock(&cache->lock);
277 static void put_caching_control(struct btrfs_caching_control *ctl)
279 if (refcount_dec_and_test(&ctl->count))
283 #ifdef CONFIG_BTRFS_DEBUG
284 static void fragment_free_space(struct btrfs_block_group_cache *block_group)
286 struct btrfs_fs_info *fs_info = block_group->fs_info;
287 u64 start = block_group->key.objectid;
288 u64 len = block_group->key.offset;
289 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
290 fs_info->nodesize : fs_info->sectorsize;
291 u64 step = chunk << 1;
293 while (len > chunk) {
294 btrfs_remove_free_space(block_group, start, chunk);
305 * this is only called by cache_block_group, since we could have freed extents
306 * we need to check the pinned_extents for any extents that can't be used yet
307 * since their free space will be released as soon as the transaction commits.
309 u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
312 struct btrfs_fs_info *info = block_group->fs_info;
313 u64 extent_start, extent_end, size, total_added = 0;
316 while (start < end) {
317 ret = find_first_extent_bit(info->pinned_extents, start,
318 &extent_start, &extent_end,
319 EXTENT_DIRTY | EXTENT_UPTODATE,
324 if (extent_start <= start) {
325 start = extent_end + 1;
326 } else if (extent_start > start && extent_start < end) {
327 size = extent_start - start;
329 ret = btrfs_add_free_space(block_group, start,
331 BUG_ON(ret); /* -ENOMEM or logic error */
332 start = extent_end + 1;
341 ret = btrfs_add_free_space(block_group, start, size);
342 BUG_ON(ret); /* -ENOMEM or logic error */
348 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
350 struct btrfs_block_group_cache *block_group = caching_ctl->block_group;
351 struct btrfs_fs_info *fs_info = block_group->fs_info;
352 struct btrfs_root *extent_root = fs_info->extent_root;
353 struct btrfs_path *path;
354 struct extent_buffer *leaf;
355 struct btrfs_key key;
362 path = btrfs_alloc_path();
366 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
368 #ifdef CONFIG_BTRFS_DEBUG
370 * If we're fragmenting we don't want to make anybody think we can
371 * allocate from this block group until we've had a chance to fragment
374 if (btrfs_should_fragment_free_space(block_group))
378 * We don't want to deadlock with somebody trying to allocate a new
379 * extent for the extent root while also trying to search the extent
380 * root to add free space. So we skip locking and search the commit
381 * root, since its read-only
383 path->skip_locking = 1;
384 path->search_commit_root = 1;
385 path->reada = READA_FORWARD;
389 key.type = BTRFS_EXTENT_ITEM_KEY;
392 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
396 leaf = path->nodes[0];
397 nritems = btrfs_header_nritems(leaf);
400 if (btrfs_fs_closing(fs_info) > 1) {
405 if (path->slots[0] < nritems) {
406 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
408 ret = find_next_key(path, 0, &key);
412 if (need_resched() ||
413 rwsem_is_contended(&fs_info->commit_root_sem)) {
415 caching_ctl->progress = last;
416 btrfs_release_path(path);
417 up_read(&fs_info->commit_root_sem);
418 mutex_unlock(&caching_ctl->mutex);
420 mutex_lock(&caching_ctl->mutex);
421 down_read(&fs_info->commit_root_sem);
425 ret = btrfs_next_leaf(extent_root, path);
430 leaf = path->nodes[0];
431 nritems = btrfs_header_nritems(leaf);
435 if (key.objectid < last) {
438 key.type = BTRFS_EXTENT_ITEM_KEY;
441 caching_ctl->progress = last;
442 btrfs_release_path(path);
446 if (key.objectid < block_group->key.objectid) {
451 if (key.objectid >= block_group->key.objectid +
452 block_group->key.offset)
455 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
456 key.type == BTRFS_METADATA_ITEM_KEY) {
457 total_found += add_new_free_space(block_group, last,
459 if (key.type == BTRFS_METADATA_ITEM_KEY)
460 last = key.objectid +
463 last = key.objectid + key.offset;
465 if (total_found > CACHING_CTL_WAKE_UP) {
468 wake_up(&caching_ctl->wait);
475 total_found += add_new_free_space(block_group, last,
476 block_group->key.objectid +
477 block_group->key.offset);
478 caching_ctl->progress = (u64)-1;
481 btrfs_free_path(path);
485 static noinline void caching_thread(struct btrfs_work *work)
487 struct btrfs_block_group_cache *block_group;
488 struct btrfs_fs_info *fs_info;
489 struct btrfs_caching_control *caching_ctl;
492 caching_ctl = container_of(work, struct btrfs_caching_control, work);
493 block_group = caching_ctl->block_group;
494 fs_info = block_group->fs_info;
496 mutex_lock(&caching_ctl->mutex);
497 down_read(&fs_info->commit_root_sem);
499 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
500 ret = load_free_space_tree(caching_ctl);
502 ret = load_extent_tree_free(caching_ctl);
504 spin_lock(&block_group->lock);
505 block_group->caching_ctl = NULL;
506 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
507 spin_unlock(&block_group->lock);
509 #ifdef CONFIG_BTRFS_DEBUG
510 if (btrfs_should_fragment_free_space(block_group)) {
513 spin_lock(&block_group->space_info->lock);
514 spin_lock(&block_group->lock);
515 bytes_used = block_group->key.offset -
516 btrfs_block_group_used(&block_group->item);
517 block_group->space_info->bytes_used += bytes_used >> 1;
518 spin_unlock(&block_group->lock);
519 spin_unlock(&block_group->space_info->lock);
520 fragment_free_space(block_group);
524 caching_ctl->progress = (u64)-1;
526 up_read(&fs_info->commit_root_sem);
527 free_excluded_extents(block_group);
528 mutex_unlock(&caching_ctl->mutex);
530 wake_up(&caching_ctl->wait);
532 put_caching_control(caching_ctl);
533 btrfs_put_block_group(block_group);
536 static int cache_block_group(struct btrfs_block_group_cache *cache,
540 struct btrfs_fs_info *fs_info = cache->fs_info;
541 struct btrfs_caching_control *caching_ctl;
544 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
548 INIT_LIST_HEAD(&caching_ctl->list);
549 mutex_init(&caching_ctl->mutex);
550 init_waitqueue_head(&caching_ctl->wait);
551 caching_ctl->block_group = cache;
552 caching_ctl->progress = cache->key.objectid;
553 refcount_set(&caching_ctl->count, 1);
554 btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
555 caching_thread, NULL, NULL);
557 spin_lock(&cache->lock);
559 * This should be a rare occasion, but this could happen I think in the
560 * case where one thread starts to load the space cache info, and then
561 * some other thread starts a transaction commit which tries to do an
562 * allocation while the other thread is still loading the space cache
563 * info. The previous loop should have kept us from choosing this block
564 * group, but if we've moved to the state where we will wait on caching
565 * block groups we need to first check if we're doing a fast load here,
566 * so we can wait for it to finish, otherwise we could end up allocating
567 * from a block group who's cache gets evicted for one reason or
570 while (cache->cached == BTRFS_CACHE_FAST) {
571 struct btrfs_caching_control *ctl;
573 ctl = cache->caching_ctl;
574 refcount_inc(&ctl->count);
575 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
576 spin_unlock(&cache->lock);
580 finish_wait(&ctl->wait, &wait);
581 put_caching_control(ctl);
582 spin_lock(&cache->lock);
585 if (cache->cached != BTRFS_CACHE_NO) {
586 spin_unlock(&cache->lock);
590 WARN_ON(cache->caching_ctl);
591 cache->caching_ctl = caching_ctl;
592 cache->cached = BTRFS_CACHE_FAST;
593 spin_unlock(&cache->lock);
595 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
596 mutex_lock(&caching_ctl->mutex);
597 ret = load_free_space_cache(cache);
599 spin_lock(&cache->lock);
601 cache->caching_ctl = NULL;
602 cache->cached = BTRFS_CACHE_FINISHED;
603 cache->last_byte_to_unpin = (u64)-1;
604 caching_ctl->progress = (u64)-1;
606 if (load_cache_only) {
607 cache->caching_ctl = NULL;
608 cache->cached = BTRFS_CACHE_NO;
610 cache->cached = BTRFS_CACHE_STARTED;
611 cache->has_caching_ctl = 1;
614 spin_unlock(&cache->lock);
615 #ifdef CONFIG_BTRFS_DEBUG
617 btrfs_should_fragment_free_space(cache)) {
620 spin_lock(&cache->space_info->lock);
621 spin_lock(&cache->lock);
622 bytes_used = cache->key.offset -
623 btrfs_block_group_used(&cache->item);
624 cache->space_info->bytes_used += bytes_used >> 1;
625 spin_unlock(&cache->lock);
626 spin_unlock(&cache->space_info->lock);
627 fragment_free_space(cache);
630 mutex_unlock(&caching_ctl->mutex);
632 wake_up(&caching_ctl->wait);
634 put_caching_control(caching_ctl);
635 free_excluded_extents(cache);
640 * We're either using the free space tree or no caching at all.
641 * Set cached to the appropriate value and wakeup any waiters.
643 spin_lock(&cache->lock);
644 if (load_cache_only) {
645 cache->caching_ctl = NULL;
646 cache->cached = BTRFS_CACHE_NO;
648 cache->cached = BTRFS_CACHE_STARTED;
649 cache->has_caching_ctl = 1;
651 spin_unlock(&cache->lock);
652 wake_up(&caching_ctl->wait);
655 if (load_cache_only) {
656 put_caching_control(caching_ctl);
660 down_write(&fs_info->commit_root_sem);
661 refcount_inc(&caching_ctl->count);
662 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
663 up_write(&fs_info->commit_root_sem);
665 btrfs_get_block_group(cache);
667 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
673 * return the block group that starts at or after bytenr
675 static struct btrfs_block_group_cache *
676 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
678 return block_group_cache_tree_search(info, bytenr, 0);
682 * return the block group that contains the given bytenr
684 struct btrfs_block_group_cache *btrfs_lookup_block_group(
685 struct btrfs_fs_info *info,
688 return block_group_cache_tree_search(info, bytenr, 1);
691 static u64 generic_ref_to_space_flags(struct btrfs_ref *ref)
693 if (ref->type == BTRFS_REF_METADATA) {
694 if (ref->tree_ref.root == BTRFS_CHUNK_TREE_OBJECTID)
695 return BTRFS_BLOCK_GROUP_SYSTEM;
697 return BTRFS_BLOCK_GROUP_METADATA;
699 return BTRFS_BLOCK_GROUP_DATA;
702 static void add_pinned_bytes(struct btrfs_fs_info *fs_info,
703 struct btrfs_ref *ref)
705 struct btrfs_space_info *space_info;
706 u64 flags = generic_ref_to_space_flags(ref);
708 space_info = btrfs_find_space_info(fs_info, flags);
710 percpu_counter_add_batch(&space_info->total_bytes_pinned, ref->len,
711 BTRFS_TOTAL_BYTES_PINNED_BATCH);
714 static void sub_pinned_bytes(struct btrfs_fs_info *fs_info,
715 struct btrfs_ref *ref)
717 struct btrfs_space_info *space_info;
718 u64 flags = generic_ref_to_space_flags(ref);
720 space_info = btrfs_find_space_info(fs_info, flags);
722 percpu_counter_add_batch(&space_info->total_bytes_pinned, -ref->len,
723 BTRFS_TOTAL_BYTES_PINNED_BATCH);
726 /* simple helper to search for an existing data extent at a given offset */
727 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
730 struct btrfs_key key;
731 struct btrfs_path *path;
733 path = btrfs_alloc_path();
737 key.objectid = start;
739 key.type = BTRFS_EXTENT_ITEM_KEY;
740 ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
741 btrfs_free_path(path);
746 * helper function to lookup reference count and flags of a tree block.
748 * the head node for delayed ref is used to store the sum of all the
749 * reference count modifications queued up in the rbtree. the head
750 * node may also store the extent flags to set. This way you can check
751 * to see what the reference count and extent flags would be if all of
752 * the delayed refs are not processed.
754 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
755 struct btrfs_fs_info *fs_info, u64 bytenr,
756 u64 offset, int metadata, u64 *refs, u64 *flags)
758 struct btrfs_delayed_ref_head *head;
759 struct btrfs_delayed_ref_root *delayed_refs;
760 struct btrfs_path *path;
761 struct btrfs_extent_item *ei;
762 struct extent_buffer *leaf;
763 struct btrfs_key key;
770 * If we don't have skinny metadata, don't bother doing anything
773 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
774 offset = fs_info->nodesize;
778 path = btrfs_alloc_path();
783 path->skip_locking = 1;
784 path->search_commit_root = 1;
788 key.objectid = bytenr;
791 key.type = BTRFS_METADATA_ITEM_KEY;
793 key.type = BTRFS_EXTENT_ITEM_KEY;
795 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
799 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
800 if (path->slots[0]) {
802 btrfs_item_key_to_cpu(path->nodes[0], &key,
804 if (key.objectid == bytenr &&
805 key.type == BTRFS_EXTENT_ITEM_KEY &&
806 key.offset == fs_info->nodesize)
812 leaf = path->nodes[0];
813 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
814 if (item_size >= sizeof(*ei)) {
815 ei = btrfs_item_ptr(leaf, path->slots[0],
816 struct btrfs_extent_item);
817 num_refs = btrfs_extent_refs(leaf, ei);
818 extent_flags = btrfs_extent_flags(leaf, ei);
821 btrfs_print_v0_err(fs_info);
823 btrfs_abort_transaction(trans, ret);
825 btrfs_handle_fs_error(fs_info, ret, NULL);
830 BUG_ON(num_refs == 0);
840 delayed_refs = &trans->transaction->delayed_refs;
841 spin_lock(&delayed_refs->lock);
842 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
844 if (!mutex_trylock(&head->mutex)) {
845 refcount_inc(&head->refs);
846 spin_unlock(&delayed_refs->lock);
848 btrfs_release_path(path);
851 * Mutex was contended, block until it's released and try
854 mutex_lock(&head->mutex);
855 mutex_unlock(&head->mutex);
856 btrfs_put_delayed_ref_head(head);
859 spin_lock(&head->lock);
860 if (head->extent_op && head->extent_op->update_flags)
861 extent_flags |= head->extent_op->flags_to_set;
863 BUG_ON(num_refs == 0);
865 num_refs += head->ref_mod;
866 spin_unlock(&head->lock);
867 mutex_unlock(&head->mutex);
869 spin_unlock(&delayed_refs->lock);
871 WARN_ON(num_refs == 0);
875 *flags = extent_flags;
877 btrfs_free_path(path);
882 * Back reference rules. Back refs have three main goals:
884 * 1) differentiate between all holders of references to an extent so that
885 * when a reference is dropped we can make sure it was a valid reference
886 * before freeing the extent.
888 * 2) Provide enough information to quickly find the holders of an extent
889 * if we notice a given block is corrupted or bad.
891 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
892 * maintenance. This is actually the same as #2, but with a slightly
893 * different use case.
895 * There are two kinds of back refs. The implicit back refs is optimized
896 * for pointers in non-shared tree blocks. For a given pointer in a block,
897 * back refs of this kind provide information about the block's owner tree
898 * and the pointer's key. These information allow us to find the block by
899 * b-tree searching. The full back refs is for pointers in tree blocks not
900 * referenced by their owner trees. The location of tree block is recorded
901 * in the back refs. Actually the full back refs is generic, and can be
902 * used in all cases the implicit back refs is used. The major shortcoming
903 * of the full back refs is its overhead. Every time a tree block gets
904 * COWed, we have to update back refs entry for all pointers in it.
906 * For a newly allocated tree block, we use implicit back refs for
907 * pointers in it. This means most tree related operations only involve
908 * implicit back refs. For a tree block created in old transaction, the
909 * only way to drop a reference to it is COW it. So we can detect the
910 * event that tree block loses its owner tree's reference and do the
911 * back refs conversion.
913 * When a tree block is COWed through a tree, there are four cases:
915 * The reference count of the block is one and the tree is the block's
916 * owner tree. Nothing to do in this case.
918 * The reference count of the block is one and the tree is not the
919 * block's owner tree. In this case, full back refs is used for pointers
920 * in the block. Remove these full back refs, add implicit back refs for
921 * every pointers in the new block.
923 * The reference count of the block is greater than one and the tree is
924 * the block's owner tree. In this case, implicit back refs is used for
925 * pointers in the block. Add full back refs for every pointers in the
926 * block, increase lower level extents' reference counts. The original
927 * implicit back refs are entailed to the new block.
929 * The reference count of the block is greater than one and the tree is
930 * not the block's owner tree. Add implicit back refs for every pointer in
931 * the new block, increase lower level extents' reference count.
933 * Back Reference Key composing:
935 * The key objectid corresponds to the first byte in the extent,
936 * The key type is used to differentiate between types of back refs.
937 * There are different meanings of the key offset for different types
940 * File extents can be referenced by:
942 * - multiple snapshots, subvolumes, or different generations in one subvol
943 * - different files inside a single subvolume
944 * - different offsets inside a file (bookend extents in file.c)
946 * The extent ref structure for the implicit back refs has fields for:
948 * - Objectid of the subvolume root
949 * - objectid of the file holding the reference
950 * - original offset in the file
951 * - how many bookend extents
953 * The key offset for the implicit back refs is hash of the first
956 * The extent ref structure for the full back refs has field for:
958 * - number of pointers in the tree leaf
960 * The key offset for the implicit back refs is the first byte of
963 * When a file extent is allocated, The implicit back refs is used.
964 * the fields are filled in:
966 * (root_key.objectid, inode objectid, offset in file, 1)
968 * When a file extent is removed file truncation, we find the
969 * corresponding implicit back refs and check the following fields:
971 * (btrfs_header_owner(leaf), inode objectid, offset in file)
973 * Btree extents can be referenced by:
975 * - Different subvolumes
977 * Both the implicit back refs and the full back refs for tree blocks
978 * only consist of key. The key offset for the implicit back refs is
979 * objectid of block's owner tree. The key offset for the full back refs
980 * is the first byte of parent block.
982 * When implicit back refs is used, information about the lowest key and
983 * level of the tree block are required. These information are stored in
984 * tree block info structure.
988 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
989 * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
990 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
992 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
993 struct btrfs_extent_inline_ref *iref,
994 enum btrfs_inline_ref_type is_data)
996 int type = btrfs_extent_inline_ref_type(eb, iref);
997 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
999 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
1000 type == BTRFS_SHARED_BLOCK_REF_KEY ||
1001 type == BTRFS_SHARED_DATA_REF_KEY ||
1002 type == BTRFS_EXTENT_DATA_REF_KEY) {
1003 if (is_data == BTRFS_REF_TYPE_BLOCK) {
1004 if (type == BTRFS_TREE_BLOCK_REF_KEY)
1006 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1007 ASSERT(eb->fs_info);
1009 * Every shared one has parent tree
1010 * block, which must be aligned to
1014 IS_ALIGNED(offset, eb->fs_info->nodesize))
1017 } else if (is_data == BTRFS_REF_TYPE_DATA) {
1018 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1020 if (type == BTRFS_SHARED_DATA_REF_KEY) {
1021 ASSERT(eb->fs_info);
1023 * Every shared one has parent tree
1024 * block, which must be aligned to
1028 IS_ALIGNED(offset, eb->fs_info->nodesize))
1032 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
1037 btrfs_print_leaf((struct extent_buffer *)eb);
1038 btrfs_err(eb->fs_info, "eb %llu invalid extent inline ref type %d",
1042 return BTRFS_REF_TYPE_INVALID;
1045 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1047 u32 high_crc = ~(u32)0;
1048 u32 low_crc = ~(u32)0;
1051 lenum = cpu_to_le64(root_objectid);
1052 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
1053 lenum = cpu_to_le64(owner);
1054 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1055 lenum = cpu_to_le64(offset);
1056 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1058 return ((u64)high_crc << 31) ^ (u64)low_crc;
1061 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1062 struct btrfs_extent_data_ref *ref)
1064 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1065 btrfs_extent_data_ref_objectid(leaf, ref),
1066 btrfs_extent_data_ref_offset(leaf, ref));
1069 static int match_extent_data_ref(struct extent_buffer *leaf,
1070 struct btrfs_extent_data_ref *ref,
1071 u64 root_objectid, u64 owner, u64 offset)
1073 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1074 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1075 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1080 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1081 struct btrfs_path *path,
1082 u64 bytenr, u64 parent,
1084 u64 owner, u64 offset)
1086 struct btrfs_root *root = trans->fs_info->extent_root;
1087 struct btrfs_key key;
1088 struct btrfs_extent_data_ref *ref;
1089 struct extent_buffer *leaf;
1095 key.objectid = bytenr;
1097 key.type = BTRFS_SHARED_DATA_REF_KEY;
1098 key.offset = parent;
1100 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1101 key.offset = hash_extent_data_ref(root_objectid,
1106 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1118 leaf = path->nodes[0];
1119 nritems = btrfs_header_nritems(leaf);
1121 if (path->slots[0] >= nritems) {
1122 ret = btrfs_next_leaf(root, path);
1128 leaf = path->nodes[0];
1129 nritems = btrfs_header_nritems(leaf);
1133 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1134 if (key.objectid != bytenr ||
1135 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1138 ref = btrfs_item_ptr(leaf, path->slots[0],
1139 struct btrfs_extent_data_ref);
1141 if (match_extent_data_ref(leaf, ref, root_objectid,
1144 btrfs_release_path(path);
1156 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1157 struct btrfs_path *path,
1158 u64 bytenr, u64 parent,
1159 u64 root_objectid, u64 owner,
1160 u64 offset, int refs_to_add)
1162 struct btrfs_root *root = trans->fs_info->extent_root;
1163 struct btrfs_key key;
1164 struct extent_buffer *leaf;
1169 key.objectid = bytenr;
1171 key.type = BTRFS_SHARED_DATA_REF_KEY;
1172 key.offset = parent;
1173 size = sizeof(struct btrfs_shared_data_ref);
1175 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1176 key.offset = hash_extent_data_ref(root_objectid,
1178 size = sizeof(struct btrfs_extent_data_ref);
1181 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1182 if (ret && ret != -EEXIST)
1185 leaf = path->nodes[0];
1187 struct btrfs_shared_data_ref *ref;
1188 ref = btrfs_item_ptr(leaf, path->slots[0],
1189 struct btrfs_shared_data_ref);
1191 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1193 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1194 num_refs += refs_to_add;
1195 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1198 struct btrfs_extent_data_ref *ref;
1199 while (ret == -EEXIST) {
1200 ref = btrfs_item_ptr(leaf, path->slots[0],
1201 struct btrfs_extent_data_ref);
1202 if (match_extent_data_ref(leaf, ref, root_objectid,
1205 btrfs_release_path(path);
1207 ret = btrfs_insert_empty_item(trans, root, path, &key,
1209 if (ret && ret != -EEXIST)
1212 leaf = path->nodes[0];
1214 ref = btrfs_item_ptr(leaf, path->slots[0],
1215 struct btrfs_extent_data_ref);
1217 btrfs_set_extent_data_ref_root(leaf, ref,
1219 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1220 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1221 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1223 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1224 num_refs += refs_to_add;
1225 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1228 btrfs_mark_buffer_dirty(leaf);
1231 btrfs_release_path(path);
1235 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1236 struct btrfs_path *path,
1237 int refs_to_drop, int *last_ref)
1239 struct btrfs_key key;
1240 struct btrfs_extent_data_ref *ref1 = NULL;
1241 struct btrfs_shared_data_ref *ref2 = NULL;
1242 struct extent_buffer *leaf;
1246 leaf = path->nodes[0];
1247 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1249 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1250 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1251 struct btrfs_extent_data_ref);
1252 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1253 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1254 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1255 struct btrfs_shared_data_ref);
1256 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1257 } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
1258 btrfs_print_v0_err(trans->fs_info);
1259 btrfs_abort_transaction(trans, -EINVAL);
1265 BUG_ON(num_refs < refs_to_drop);
1266 num_refs -= refs_to_drop;
1268 if (num_refs == 0) {
1269 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1272 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1273 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1274 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1275 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1276 btrfs_mark_buffer_dirty(leaf);
1281 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1282 struct btrfs_extent_inline_ref *iref)
1284 struct btrfs_key key;
1285 struct extent_buffer *leaf;
1286 struct btrfs_extent_data_ref *ref1;
1287 struct btrfs_shared_data_ref *ref2;
1291 leaf = path->nodes[0];
1292 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1294 BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
1297 * If type is invalid, we should have bailed out earlier than
1300 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
1301 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1302 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1303 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1304 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1306 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1307 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1309 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1310 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1311 struct btrfs_extent_data_ref);
1312 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1313 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1314 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1315 struct btrfs_shared_data_ref);
1316 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1323 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1324 struct btrfs_path *path,
1325 u64 bytenr, u64 parent,
1328 struct btrfs_root *root = trans->fs_info->extent_root;
1329 struct btrfs_key key;
1332 key.objectid = bytenr;
1334 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1335 key.offset = parent;
1337 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1338 key.offset = root_objectid;
1341 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1347 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1348 struct btrfs_path *path,
1349 u64 bytenr, u64 parent,
1352 struct btrfs_key key;
1355 key.objectid = bytenr;
1357 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1358 key.offset = parent;
1360 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1361 key.offset = root_objectid;
1364 ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
1366 btrfs_release_path(path);
1370 static inline int extent_ref_type(u64 parent, u64 owner)
1373 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1375 type = BTRFS_SHARED_BLOCK_REF_KEY;
1377 type = BTRFS_TREE_BLOCK_REF_KEY;
1380 type = BTRFS_SHARED_DATA_REF_KEY;
1382 type = BTRFS_EXTENT_DATA_REF_KEY;
1387 static int find_next_key(struct btrfs_path *path, int level,
1388 struct btrfs_key *key)
1391 for (; level < BTRFS_MAX_LEVEL; level++) {
1392 if (!path->nodes[level])
1394 if (path->slots[level] + 1 >=
1395 btrfs_header_nritems(path->nodes[level]))
1398 btrfs_item_key_to_cpu(path->nodes[level], key,
1399 path->slots[level] + 1);
1401 btrfs_node_key_to_cpu(path->nodes[level], key,
1402 path->slots[level] + 1);
1409 * look for inline back ref. if back ref is found, *ref_ret is set
1410 * to the address of inline back ref, and 0 is returned.
1412 * if back ref isn't found, *ref_ret is set to the address where it
1413 * should be inserted, and -ENOENT is returned.
1415 * if insert is true and there are too many inline back refs, the path
1416 * points to the extent item, and -EAGAIN is returned.
1418 * NOTE: inline back refs are ordered in the same way that back ref
1419 * items in the tree are ordered.
1421 static noinline_for_stack
1422 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1423 struct btrfs_path *path,
1424 struct btrfs_extent_inline_ref **ref_ret,
1425 u64 bytenr, u64 num_bytes,
1426 u64 parent, u64 root_objectid,
1427 u64 owner, u64 offset, int insert)
1429 struct btrfs_fs_info *fs_info = trans->fs_info;
1430 struct btrfs_root *root = fs_info->extent_root;
1431 struct btrfs_key key;
1432 struct extent_buffer *leaf;
1433 struct btrfs_extent_item *ei;
1434 struct btrfs_extent_inline_ref *iref;
1444 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1447 key.objectid = bytenr;
1448 key.type = BTRFS_EXTENT_ITEM_KEY;
1449 key.offset = num_bytes;
1451 want = extent_ref_type(parent, owner);
1453 extra_size = btrfs_extent_inline_ref_size(want);
1454 path->keep_locks = 1;
1459 * Owner is our level, so we can just add one to get the level for the
1460 * block we are interested in.
1462 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1463 key.type = BTRFS_METADATA_ITEM_KEY;
1468 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1475 * We may be a newly converted file system which still has the old fat
1476 * extent entries for metadata, so try and see if we have one of those.
1478 if (ret > 0 && skinny_metadata) {
1479 skinny_metadata = false;
1480 if (path->slots[0]) {
1482 btrfs_item_key_to_cpu(path->nodes[0], &key,
1484 if (key.objectid == bytenr &&
1485 key.type == BTRFS_EXTENT_ITEM_KEY &&
1486 key.offset == num_bytes)
1490 key.objectid = bytenr;
1491 key.type = BTRFS_EXTENT_ITEM_KEY;
1492 key.offset = num_bytes;
1493 btrfs_release_path(path);
1498 if (ret && !insert) {
1501 } else if (WARN_ON(ret)) {
1506 leaf = path->nodes[0];
1507 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1508 if (unlikely(item_size < sizeof(*ei))) {
1510 btrfs_print_v0_err(fs_info);
1511 btrfs_abort_transaction(trans, err);
1515 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1516 flags = btrfs_extent_flags(leaf, ei);
1518 ptr = (unsigned long)(ei + 1);
1519 end = (unsigned long)ei + item_size;
1521 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1522 ptr += sizeof(struct btrfs_tree_block_info);
1526 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
1527 needed = BTRFS_REF_TYPE_DATA;
1529 needed = BTRFS_REF_TYPE_BLOCK;
1537 iref = (struct btrfs_extent_inline_ref *)ptr;
1538 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
1539 if (type == BTRFS_REF_TYPE_INVALID) {
1547 ptr += btrfs_extent_inline_ref_size(type);
1551 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1552 struct btrfs_extent_data_ref *dref;
1553 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1554 if (match_extent_data_ref(leaf, dref, root_objectid,
1559 if (hash_extent_data_ref_item(leaf, dref) <
1560 hash_extent_data_ref(root_objectid, owner, offset))
1564 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1566 if (parent == ref_offset) {
1570 if (ref_offset < parent)
1573 if (root_objectid == ref_offset) {
1577 if (ref_offset < root_objectid)
1581 ptr += btrfs_extent_inline_ref_size(type);
1583 if (err == -ENOENT && insert) {
1584 if (item_size + extra_size >=
1585 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1590 * To add new inline back ref, we have to make sure
1591 * there is no corresponding back ref item.
1592 * For simplicity, we just do not add new inline back
1593 * ref if there is any kind of item for this block
1595 if (find_next_key(path, 0, &key) == 0 &&
1596 key.objectid == bytenr &&
1597 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1602 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1605 path->keep_locks = 0;
1606 btrfs_unlock_up_safe(path, 1);
1612 * helper to add new inline back ref
1614 static noinline_for_stack
1615 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1616 struct btrfs_path *path,
1617 struct btrfs_extent_inline_ref *iref,
1618 u64 parent, u64 root_objectid,
1619 u64 owner, u64 offset, int refs_to_add,
1620 struct btrfs_delayed_extent_op *extent_op)
1622 struct extent_buffer *leaf;
1623 struct btrfs_extent_item *ei;
1626 unsigned long item_offset;
1631 leaf = path->nodes[0];
1632 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1633 item_offset = (unsigned long)iref - (unsigned long)ei;
1635 type = extent_ref_type(parent, owner);
1636 size = btrfs_extent_inline_ref_size(type);
1638 btrfs_extend_item(path, size);
1640 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1641 refs = btrfs_extent_refs(leaf, ei);
1642 refs += refs_to_add;
1643 btrfs_set_extent_refs(leaf, ei, refs);
1645 __run_delayed_extent_op(extent_op, leaf, ei);
1647 ptr = (unsigned long)ei + item_offset;
1648 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1649 if (ptr < end - size)
1650 memmove_extent_buffer(leaf, ptr + size, ptr,
1653 iref = (struct btrfs_extent_inline_ref *)ptr;
1654 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1655 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1656 struct btrfs_extent_data_ref *dref;
1657 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1658 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1659 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1660 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1661 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1662 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1663 struct btrfs_shared_data_ref *sref;
1664 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1665 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1666 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1667 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1668 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1670 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1672 btrfs_mark_buffer_dirty(leaf);
1675 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1676 struct btrfs_path *path,
1677 struct btrfs_extent_inline_ref **ref_ret,
1678 u64 bytenr, u64 num_bytes, u64 parent,
1679 u64 root_objectid, u64 owner, u64 offset)
1683 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1684 num_bytes, parent, root_objectid,
1689 btrfs_release_path(path);
1692 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1693 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1696 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1697 root_objectid, owner, offset);
1703 * helper to update/remove inline back ref
1705 static noinline_for_stack
1706 void update_inline_extent_backref(struct btrfs_path *path,
1707 struct btrfs_extent_inline_ref *iref,
1709 struct btrfs_delayed_extent_op *extent_op,
1712 struct extent_buffer *leaf = path->nodes[0];
1713 struct btrfs_extent_item *ei;
1714 struct btrfs_extent_data_ref *dref = NULL;
1715 struct btrfs_shared_data_ref *sref = NULL;
1723 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1724 refs = btrfs_extent_refs(leaf, ei);
1725 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1726 refs += refs_to_mod;
1727 btrfs_set_extent_refs(leaf, ei, refs);
1729 __run_delayed_extent_op(extent_op, leaf, ei);
1732 * If type is invalid, we should have bailed out after
1733 * lookup_inline_extent_backref().
1735 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1736 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1738 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1739 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1740 refs = btrfs_extent_data_ref_count(leaf, dref);
1741 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1742 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1743 refs = btrfs_shared_data_ref_count(leaf, sref);
1746 BUG_ON(refs_to_mod != -1);
1749 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1750 refs += refs_to_mod;
1753 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1754 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1756 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1759 size = btrfs_extent_inline_ref_size(type);
1760 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1761 ptr = (unsigned long)iref;
1762 end = (unsigned long)ei + item_size;
1763 if (ptr + size < end)
1764 memmove_extent_buffer(leaf, ptr, ptr + size,
1767 btrfs_truncate_item(path, item_size, 1);
1769 btrfs_mark_buffer_dirty(leaf);
1772 static noinline_for_stack
1773 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1774 struct btrfs_path *path,
1775 u64 bytenr, u64 num_bytes, u64 parent,
1776 u64 root_objectid, u64 owner,
1777 u64 offset, int refs_to_add,
1778 struct btrfs_delayed_extent_op *extent_op)
1780 struct btrfs_extent_inline_ref *iref;
1783 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1784 num_bytes, parent, root_objectid,
1787 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1788 update_inline_extent_backref(path, iref, refs_to_add,
1790 } else if (ret == -ENOENT) {
1791 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1792 root_objectid, owner, offset,
1793 refs_to_add, extent_op);
1799 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1800 struct btrfs_path *path,
1801 u64 bytenr, u64 parent, u64 root_objectid,
1802 u64 owner, u64 offset, int refs_to_add)
1805 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1806 BUG_ON(refs_to_add != 1);
1807 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1810 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1811 root_objectid, owner, offset,
1817 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1818 struct btrfs_path *path,
1819 struct btrfs_extent_inline_ref *iref,
1820 int refs_to_drop, int is_data, int *last_ref)
1824 BUG_ON(!is_data && refs_to_drop != 1);
1826 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1828 } else if (is_data) {
1829 ret = remove_extent_data_ref(trans, path, refs_to_drop,
1833 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1838 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1839 u64 *discarded_bytes)
1842 u64 bytes_left, end;
1843 u64 aligned_start = ALIGN(start, 1 << 9);
1845 if (WARN_ON(start != aligned_start)) {
1846 len -= aligned_start - start;
1847 len = round_down(len, 1 << 9);
1848 start = aligned_start;
1851 *discarded_bytes = 0;
1859 /* Skip any superblocks on this device. */
1860 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1861 u64 sb_start = btrfs_sb_offset(j);
1862 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1863 u64 size = sb_start - start;
1865 if (!in_range(sb_start, start, bytes_left) &&
1866 !in_range(sb_end, start, bytes_left) &&
1867 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1871 * Superblock spans beginning of range. Adjust start and
1874 if (sb_start <= start) {
1875 start += sb_end - start;
1880 bytes_left = end - start;
1885 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1888 *discarded_bytes += size;
1889 else if (ret != -EOPNOTSUPP)
1898 bytes_left = end - start;
1902 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1905 *discarded_bytes += bytes_left;
1910 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1911 u64 num_bytes, u64 *actual_bytes)
1914 u64 discarded_bytes = 0;
1915 struct btrfs_bio *bbio = NULL;
1919 * Avoid races with device replace and make sure our bbio has devices
1920 * associated to its stripes that don't go away while we are discarding.
1922 btrfs_bio_counter_inc_blocked(fs_info);
1923 /* Tell the block device(s) that the sectors can be discarded */
1924 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
1926 /* Error condition is -ENOMEM */
1928 struct btrfs_bio_stripe *stripe = bbio->stripes;
1932 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
1934 struct request_queue *req_q;
1936 if (!stripe->dev->bdev) {
1937 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1940 req_q = bdev_get_queue(stripe->dev->bdev);
1941 if (!blk_queue_discard(req_q))
1944 ret = btrfs_issue_discard(stripe->dev->bdev,
1949 discarded_bytes += bytes;
1950 else if (ret != -EOPNOTSUPP)
1951 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
1954 * Just in case we get back EOPNOTSUPP for some reason,
1955 * just ignore the return value so we don't screw up
1956 * people calling discard_extent.
1960 btrfs_put_bbio(bbio);
1962 btrfs_bio_counter_dec(fs_info);
1965 *actual_bytes = discarded_bytes;
1968 if (ret == -EOPNOTSUPP)
1973 /* Can return -ENOMEM */
1974 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1975 struct btrfs_ref *generic_ref)
1977 struct btrfs_fs_info *fs_info = trans->fs_info;
1978 int old_ref_mod, new_ref_mod;
1981 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
1982 generic_ref->action);
1983 BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
1984 generic_ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID);
1986 if (generic_ref->type == BTRFS_REF_METADATA)
1987 ret = btrfs_add_delayed_tree_ref(trans, generic_ref,
1988 NULL, &old_ref_mod, &new_ref_mod);
1990 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0,
1991 &old_ref_mod, &new_ref_mod);
1993 btrfs_ref_tree_mod(fs_info, generic_ref);
1995 if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0)
1996 sub_pinned_bytes(fs_info, generic_ref);
2002 * __btrfs_inc_extent_ref - insert backreference for a given extent
2004 * @trans: Handle of transaction
2006 * @node: The delayed ref node used to get the bytenr/length for
2007 * extent whose references are incremented.
2009 * @parent: If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
2010 * BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
2011 * bytenr of the parent block. Since new extents are always
2012 * created with indirect references, this will only be the case
2013 * when relocating a shared extent. In that case, root_objectid
2014 * will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
2017 * @root_objectid: The id of the root where this modification has originated,
2018 * this can be either one of the well-known metadata trees or
2019 * the subvolume id which references this extent.
2021 * @owner: For data extents it is the inode number of the owning file.
2022 * For metadata extents this parameter holds the level in the
2023 * tree of the extent.
2025 * @offset: For metadata extents the offset is ignored and is currently
2026 * always passed as 0. For data extents it is the fileoffset
2027 * this extent belongs to.
2029 * @refs_to_add Number of references to add
2031 * @extent_op Pointer to a structure, holding information necessary when
2032 * updating a tree block's flags
2035 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2036 struct btrfs_delayed_ref_node *node,
2037 u64 parent, u64 root_objectid,
2038 u64 owner, u64 offset, int refs_to_add,
2039 struct btrfs_delayed_extent_op *extent_op)
2041 struct btrfs_path *path;
2042 struct extent_buffer *leaf;
2043 struct btrfs_extent_item *item;
2044 struct btrfs_key key;
2045 u64 bytenr = node->bytenr;
2046 u64 num_bytes = node->num_bytes;
2050 path = btrfs_alloc_path();
2054 path->reada = READA_FORWARD;
2055 path->leave_spinning = 1;
2056 /* this will setup the path even if it fails to insert the back ref */
2057 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
2058 parent, root_objectid, owner,
2059 offset, refs_to_add, extent_op);
2060 if ((ret < 0 && ret != -EAGAIN) || !ret)
2064 * Ok we had -EAGAIN which means we didn't have space to insert and
2065 * inline extent ref, so just update the reference count and add a
2068 leaf = path->nodes[0];
2069 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2070 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2071 refs = btrfs_extent_refs(leaf, item);
2072 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2074 __run_delayed_extent_op(extent_op, leaf, item);
2076 btrfs_mark_buffer_dirty(leaf);
2077 btrfs_release_path(path);
2079 path->reada = READA_FORWARD;
2080 path->leave_spinning = 1;
2081 /* now insert the actual backref */
2082 ret = insert_extent_backref(trans, path, bytenr, parent, root_objectid,
2083 owner, offset, refs_to_add);
2085 btrfs_abort_transaction(trans, ret);
2087 btrfs_free_path(path);
2091 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2092 struct btrfs_delayed_ref_node *node,
2093 struct btrfs_delayed_extent_op *extent_op,
2094 int insert_reserved)
2097 struct btrfs_delayed_data_ref *ref;
2098 struct btrfs_key ins;
2103 ins.objectid = node->bytenr;
2104 ins.offset = node->num_bytes;
2105 ins.type = BTRFS_EXTENT_ITEM_KEY;
2107 ref = btrfs_delayed_node_to_data_ref(node);
2108 trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
2110 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2111 parent = ref->parent;
2112 ref_root = ref->root;
2114 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2116 flags |= extent_op->flags_to_set;
2117 ret = alloc_reserved_file_extent(trans, parent, ref_root,
2118 flags, ref->objectid,
2121 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2122 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2123 ref->objectid, ref->offset,
2124 node->ref_mod, extent_op);
2125 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2126 ret = __btrfs_free_extent(trans, node, parent,
2127 ref_root, ref->objectid,
2128 ref->offset, node->ref_mod,
2136 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2137 struct extent_buffer *leaf,
2138 struct btrfs_extent_item *ei)
2140 u64 flags = btrfs_extent_flags(leaf, ei);
2141 if (extent_op->update_flags) {
2142 flags |= extent_op->flags_to_set;
2143 btrfs_set_extent_flags(leaf, ei, flags);
2146 if (extent_op->update_key) {
2147 struct btrfs_tree_block_info *bi;
2148 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2149 bi = (struct btrfs_tree_block_info *)(ei + 1);
2150 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2154 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2155 struct btrfs_delayed_ref_head *head,
2156 struct btrfs_delayed_extent_op *extent_op)
2158 struct btrfs_fs_info *fs_info = trans->fs_info;
2159 struct btrfs_key key;
2160 struct btrfs_path *path;
2161 struct btrfs_extent_item *ei;
2162 struct extent_buffer *leaf;
2166 int metadata = !extent_op->is_data;
2171 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2174 path = btrfs_alloc_path();
2178 key.objectid = head->bytenr;
2181 key.type = BTRFS_METADATA_ITEM_KEY;
2182 key.offset = extent_op->level;
2184 key.type = BTRFS_EXTENT_ITEM_KEY;
2185 key.offset = head->num_bytes;
2189 path->reada = READA_FORWARD;
2190 path->leave_spinning = 1;
2191 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2198 if (path->slots[0] > 0) {
2200 btrfs_item_key_to_cpu(path->nodes[0], &key,
2202 if (key.objectid == head->bytenr &&
2203 key.type == BTRFS_EXTENT_ITEM_KEY &&
2204 key.offset == head->num_bytes)
2208 btrfs_release_path(path);
2211 key.objectid = head->bytenr;
2212 key.offset = head->num_bytes;
2213 key.type = BTRFS_EXTENT_ITEM_KEY;
2222 leaf = path->nodes[0];
2223 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2225 if (unlikely(item_size < sizeof(*ei))) {
2227 btrfs_print_v0_err(fs_info);
2228 btrfs_abort_transaction(trans, err);
2232 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2233 __run_delayed_extent_op(extent_op, leaf, ei);
2235 btrfs_mark_buffer_dirty(leaf);
2237 btrfs_free_path(path);
2241 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2242 struct btrfs_delayed_ref_node *node,
2243 struct btrfs_delayed_extent_op *extent_op,
2244 int insert_reserved)
2247 struct btrfs_delayed_tree_ref *ref;
2251 ref = btrfs_delayed_node_to_tree_ref(node);
2252 trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
2254 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2255 parent = ref->parent;
2256 ref_root = ref->root;
2258 if (node->ref_mod != 1) {
2259 btrfs_err(trans->fs_info,
2260 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2261 node->bytenr, node->ref_mod, node->action, ref_root,
2265 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2266 BUG_ON(!extent_op || !extent_op->update_flags);
2267 ret = alloc_reserved_tree_block(trans, node, extent_op);
2268 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2269 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2270 ref->level, 0, 1, extent_op);
2271 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2272 ret = __btrfs_free_extent(trans, node, parent, ref_root,
2273 ref->level, 0, 1, extent_op);
2280 /* helper function to actually process a single delayed ref entry */
2281 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2282 struct btrfs_delayed_ref_node *node,
2283 struct btrfs_delayed_extent_op *extent_op,
2284 int insert_reserved)
2288 if (trans->aborted) {
2289 if (insert_reserved)
2290 btrfs_pin_extent(trans->fs_info, node->bytenr,
2291 node->num_bytes, 1);
2295 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2296 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2297 ret = run_delayed_tree_ref(trans, node, extent_op,
2299 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2300 node->type == BTRFS_SHARED_DATA_REF_KEY)
2301 ret = run_delayed_data_ref(trans, node, extent_op,
2305 if (ret && insert_reserved)
2306 btrfs_pin_extent(trans->fs_info, node->bytenr,
2307 node->num_bytes, 1);
2311 static inline struct btrfs_delayed_ref_node *
2312 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2314 struct btrfs_delayed_ref_node *ref;
2316 if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
2320 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2321 * This is to prevent a ref count from going down to zero, which deletes
2322 * the extent item from the extent tree, when there still are references
2323 * to add, which would fail because they would not find the extent item.
2325 if (!list_empty(&head->ref_add_list))
2326 return list_first_entry(&head->ref_add_list,
2327 struct btrfs_delayed_ref_node, add_list);
2329 ref = rb_entry(rb_first_cached(&head->ref_tree),
2330 struct btrfs_delayed_ref_node, ref_node);
2331 ASSERT(list_empty(&ref->add_list));
2335 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
2336 struct btrfs_delayed_ref_head *head)
2338 spin_lock(&delayed_refs->lock);
2339 head->processing = 0;
2340 delayed_refs->num_heads_ready++;
2341 spin_unlock(&delayed_refs->lock);
2342 btrfs_delayed_ref_unlock(head);
2345 static struct btrfs_delayed_extent_op *cleanup_extent_op(
2346 struct btrfs_delayed_ref_head *head)
2348 struct btrfs_delayed_extent_op *extent_op = head->extent_op;
2353 if (head->must_insert_reserved) {
2354 head->extent_op = NULL;
2355 btrfs_free_delayed_extent_op(extent_op);
2361 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
2362 struct btrfs_delayed_ref_head *head)
2364 struct btrfs_delayed_extent_op *extent_op;
2367 extent_op = cleanup_extent_op(head);
2370 head->extent_op = NULL;
2371 spin_unlock(&head->lock);
2372 ret = run_delayed_extent_op(trans, head, extent_op);
2373 btrfs_free_delayed_extent_op(extent_op);
2374 return ret ? ret : 1;
2377 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
2378 struct btrfs_delayed_ref_root *delayed_refs,
2379 struct btrfs_delayed_ref_head *head)
2381 int nr_items = 1; /* Dropping this ref head update. */
2383 if (head->total_ref_mod < 0) {
2384 struct btrfs_space_info *space_info;
2388 flags = BTRFS_BLOCK_GROUP_DATA;
2389 else if (head->is_system)
2390 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2392 flags = BTRFS_BLOCK_GROUP_METADATA;
2393 space_info = btrfs_find_space_info(fs_info, flags);
2395 percpu_counter_add_batch(&space_info->total_bytes_pinned,
2397 BTRFS_TOTAL_BYTES_PINNED_BATCH);
2400 * We had csum deletions accounted for in our delayed refs rsv,
2401 * we need to drop the csum leaves for this update from our
2404 if (head->is_data) {
2405 spin_lock(&delayed_refs->lock);
2406 delayed_refs->pending_csums -= head->num_bytes;
2407 spin_unlock(&delayed_refs->lock);
2408 nr_items += btrfs_csum_bytes_to_leaves(fs_info,
2413 btrfs_delayed_refs_rsv_release(fs_info, nr_items);
2416 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
2417 struct btrfs_delayed_ref_head *head)
2420 struct btrfs_fs_info *fs_info = trans->fs_info;
2421 struct btrfs_delayed_ref_root *delayed_refs;
2424 delayed_refs = &trans->transaction->delayed_refs;
2426 ret = run_and_cleanup_extent_op(trans, head);
2428 unselect_delayed_ref_head(delayed_refs, head);
2429 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
2436 * Need to drop our head ref lock and re-acquire the delayed ref lock
2437 * and then re-check to make sure nobody got added.
2439 spin_unlock(&head->lock);
2440 spin_lock(&delayed_refs->lock);
2441 spin_lock(&head->lock);
2442 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
2443 spin_unlock(&head->lock);
2444 spin_unlock(&delayed_refs->lock);
2447 btrfs_delete_ref_head(delayed_refs, head);
2448 spin_unlock(&head->lock);
2449 spin_unlock(&delayed_refs->lock);
2451 if (head->must_insert_reserved) {
2452 btrfs_pin_extent(fs_info, head->bytenr,
2453 head->num_bytes, 1);
2454 if (head->is_data) {
2455 ret = btrfs_del_csums(trans, fs_info, head->bytenr,
2460 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
2462 trace_run_delayed_ref_head(fs_info, head, 0);
2463 btrfs_delayed_ref_unlock(head);
2464 btrfs_put_delayed_ref_head(head);
2468 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
2469 struct btrfs_trans_handle *trans)
2471 struct btrfs_delayed_ref_root *delayed_refs =
2472 &trans->transaction->delayed_refs;
2473 struct btrfs_delayed_ref_head *head = NULL;
2476 spin_lock(&delayed_refs->lock);
2477 head = btrfs_select_ref_head(delayed_refs);
2479 spin_unlock(&delayed_refs->lock);
2484 * Grab the lock that says we are going to process all the refs for
2487 ret = btrfs_delayed_ref_lock(delayed_refs, head);
2488 spin_unlock(&delayed_refs->lock);
2491 * We may have dropped the spin lock to get the head mutex lock, and
2492 * that might have given someone else time to free the head. If that's
2493 * true, it has been removed from our list and we can move on.
2496 head = ERR_PTR(-EAGAIN);
2501 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
2502 struct btrfs_delayed_ref_head *locked_ref,
2503 unsigned long *run_refs)
2505 struct btrfs_fs_info *fs_info = trans->fs_info;
2506 struct btrfs_delayed_ref_root *delayed_refs;
2507 struct btrfs_delayed_extent_op *extent_op;
2508 struct btrfs_delayed_ref_node *ref;
2509 int must_insert_reserved = 0;
2512 delayed_refs = &trans->transaction->delayed_refs;
2514 lockdep_assert_held(&locked_ref->mutex);
2515 lockdep_assert_held(&locked_ref->lock);
2517 while ((ref = select_delayed_ref(locked_ref))) {
2519 btrfs_check_delayed_seq(fs_info, ref->seq)) {
2520 spin_unlock(&locked_ref->lock);
2521 unselect_delayed_ref_head(delayed_refs, locked_ref);
2527 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
2528 RB_CLEAR_NODE(&ref->ref_node);
2529 if (!list_empty(&ref->add_list))
2530 list_del(&ref->add_list);
2532 * When we play the delayed ref, also correct the ref_mod on
2535 switch (ref->action) {
2536 case BTRFS_ADD_DELAYED_REF:
2537 case BTRFS_ADD_DELAYED_EXTENT:
2538 locked_ref->ref_mod -= ref->ref_mod;
2540 case BTRFS_DROP_DELAYED_REF:
2541 locked_ref->ref_mod += ref->ref_mod;
2546 atomic_dec(&delayed_refs->num_entries);
2549 * Record the must_insert_reserved flag before we drop the
2552 must_insert_reserved = locked_ref->must_insert_reserved;
2553 locked_ref->must_insert_reserved = 0;
2555 extent_op = locked_ref->extent_op;
2556 locked_ref->extent_op = NULL;
2557 spin_unlock(&locked_ref->lock);
2559 ret = run_one_delayed_ref(trans, ref, extent_op,
2560 must_insert_reserved);
2562 btrfs_free_delayed_extent_op(extent_op);
2564 unselect_delayed_ref_head(delayed_refs, locked_ref);
2565 btrfs_put_delayed_ref(ref);
2566 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2571 btrfs_put_delayed_ref(ref);
2574 spin_lock(&locked_ref->lock);
2575 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2582 * Returns 0 on success or if called with an already aborted transaction.
2583 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2585 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2588 struct btrfs_fs_info *fs_info = trans->fs_info;
2589 struct btrfs_delayed_ref_root *delayed_refs;
2590 struct btrfs_delayed_ref_head *locked_ref = NULL;
2591 ktime_t start = ktime_get();
2593 unsigned long count = 0;
2594 unsigned long actual_count = 0;
2596 delayed_refs = &trans->transaction->delayed_refs;
2599 locked_ref = btrfs_obtain_ref_head(trans);
2600 if (IS_ERR_OR_NULL(locked_ref)) {
2601 if (PTR_ERR(locked_ref) == -EAGAIN) {
2610 * We need to try and merge add/drops of the same ref since we
2611 * can run into issues with relocate dropping the implicit ref
2612 * and then it being added back again before the drop can
2613 * finish. If we merged anything we need to re-loop so we can
2615 * Or we can get node references of the same type that weren't
2616 * merged when created due to bumps in the tree mod seq, and
2617 * we need to merge them to prevent adding an inline extent
2618 * backref before dropping it (triggering a BUG_ON at
2619 * insert_inline_extent_backref()).
2621 spin_lock(&locked_ref->lock);
2622 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2624 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2626 if (ret < 0 && ret != -EAGAIN) {
2628 * Error, btrfs_run_delayed_refs_for_head already
2629 * unlocked everything so just bail out
2634 * Success, perform the usual cleanup of a processed
2637 ret = cleanup_ref_head(trans, locked_ref);
2639 /* We dropped our lock, we need to loop. */
2648 * Either success case or btrfs_run_delayed_refs_for_head
2649 * returned -EAGAIN, meaning we need to select another head
2654 } while ((nr != -1 && count < nr) || locked_ref);
2657 * We don't want to include ref heads since we can have empty ref heads
2658 * and those will drastically skew our runtime down since we just do
2659 * accounting, no actual extent tree updates.
2661 if (actual_count > 0) {
2662 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2666 * We weigh the current average higher than our current runtime
2667 * to avoid large swings in the average.
2669 spin_lock(&delayed_refs->lock);
2670 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2671 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2672 spin_unlock(&delayed_refs->lock);
2677 #ifdef SCRAMBLE_DELAYED_REFS
2679 * Normally delayed refs get processed in ascending bytenr order. This
2680 * correlates in most cases to the order added. To expose dependencies on this
2681 * order, we start to process the tree in the middle instead of the beginning
2683 static u64 find_middle(struct rb_root *root)
2685 struct rb_node *n = root->rb_node;
2686 struct btrfs_delayed_ref_node *entry;
2689 u64 first = 0, last = 0;
2693 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2694 first = entry->bytenr;
2698 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2699 last = entry->bytenr;
2704 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2705 WARN_ON(!entry->in_tree);
2707 middle = entry->bytenr;
2720 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2724 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2725 sizeof(struct btrfs_extent_inline_ref));
2726 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2727 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2730 * We don't ever fill up leaves all the way so multiply by 2 just to be
2731 * closer to what we're really going to want to use.
2733 return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2737 * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2738 * would require to store the csums for that many bytes.
2740 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2743 u64 num_csums_per_leaf;
2746 csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2747 num_csums_per_leaf = div64_u64(csum_size,
2748 (u64)btrfs_super_csum_size(fs_info->super_copy));
2749 num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2750 num_csums += num_csums_per_leaf - 1;
2751 num_csums = div64_u64(num_csums, num_csums_per_leaf);
2755 bool btrfs_check_space_for_delayed_refs(struct btrfs_fs_info *fs_info)
2757 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
2758 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2762 spin_lock(&global_rsv->lock);
2763 reserved = global_rsv->reserved;
2764 spin_unlock(&global_rsv->lock);
2767 * Since the global reserve is just kind of magic we don't really want
2768 * to rely on it to save our bacon, so if our size is more than the
2769 * delayed_refs_rsv and the global rsv then it's time to think about
2772 spin_lock(&delayed_refs_rsv->lock);
2773 reserved += delayed_refs_rsv->reserved;
2774 if (delayed_refs_rsv->size >= reserved)
2776 spin_unlock(&delayed_refs_rsv->lock);
2780 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans)
2783 atomic_read(&trans->transaction->delayed_refs.num_entries);
2788 avg_runtime = trans->fs_info->avg_delayed_ref_runtime;
2789 val = num_entries * avg_runtime;
2790 if (val >= NSEC_PER_SEC)
2792 if (val >= NSEC_PER_SEC / 2)
2795 return btrfs_check_space_for_delayed_refs(trans->fs_info);
2799 * this starts processing the delayed reference count updates and
2800 * extent insertions we have queued up so far. count can be
2801 * 0, which means to process everything in the tree at the start
2802 * of the run (but not newly added entries), or it can be some target
2803 * number you'd like to process.
2805 * Returns 0 on success or if called with an aborted transaction
2806 * Returns <0 on error and aborts the transaction
2808 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2809 unsigned long count)
2811 struct btrfs_fs_info *fs_info = trans->fs_info;
2812 struct rb_node *node;
2813 struct btrfs_delayed_ref_root *delayed_refs;
2814 struct btrfs_delayed_ref_head *head;
2816 int run_all = count == (unsigned long)-1;
2818 /* We'll clean this up in btrfs_cleanup_transaction */
2822 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2825 delayed_refs = &trans->transaction->delayed_refs;
2827 count = atomic_read(&delayed_refs->num_entries) * 2;
2830 #ifdef SCRAMBLE_DELAYED_REFS
2831 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2833 ret = __btrfs_run_delayed_refs(trans, count);
2835 btrfs_abort_transaction(trans, ret);
2840 btrfs_create_pending_block_groups(trans);
2842 spin_lock(&delayed_refs->lock);
2843 node = rb_first_cached(&delayed_refs->href_root);
2845 spin_unlock(&delayed_refs->lock);
2848 head = rb_entry(node, struct btrfs_delayed_ref_head,
2850 refcount_inc(&head->refs);
2851 spin_unlock(&delayed_refs->lock);
2853 /* Mutex was contended, block until it's released and retry. */
2854 mutex_lock(&head->mutex);
2855 mutex_unlock(&head->mutex);
2857 btrfs_put_delayed_ref_head(head);
2865 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2866 u64 bytenr, u64 num_bytes, u64 flags,
2867 int level, int is_data)
2869 struct btrfs_delayed_extent_op *extent_op;
2872 extent_op = btrfs_alloc_delayed_extent_op();
2876 extent_op->flags_to_set = flags;
2877 extent_op->update_flags = true;
2878 extent_op->update_key = false;
2879 extent_op->is_data = is_data ? true : false;
2880 extent_op->level = level;
2882 ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2884 btrfs_free_delayed_extent_op(extent_op);
2888 static noinline int check_delayed_ref(struct btrfs_root *root,
2889 struct btrfs_path *path,
2890 u64 objectid, u64 offset, u64 bytenr)
2892 struct btrfs_delayed_ref_head *head;
2893 struct btrfs_delayed_ref_node *ref;
2894 struct btrfs_delayed_data_ref *data_ref;
2895 struct btrfs_delayed_ref_root *delayed_refs;
2896 struct btrfs_transaction *cur_trans;
2897 struct rb_node *node;
2900 spin_lock(&root->fs_info->trans_lock);
2901 cur_trans = root->fs_info->running_transaction;
2903 refcount_inc(&cur_trans->use_count);
2904 spin_unlock(&root->fs_info->trans_lock);
2908 delayed_refs = &cur_trans->delayed_refs;
2909 spin_lock(&delayed_refs->lock);
2910 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2912 spin_unlock(&delayed_refs->lock);
2913 btrfs_put_transaction(cur_trans);
2917 if (!mutex_trylock(&head->mutex)) {
2918 refcount_inc(&head->refs);
2919 spin_unlock(&delayed_refs->lock);
2921 btrfs_release_path(path);
2924 * Mutex was contended, block until it's released and let
2927 mutex_lock(&head->mutex);
2928 mutex_unlock(&head->mutex);
2929 btrfs_put_delayed_ref_head(head);
2930 btrfs_put_transaction(cur_trans);
2933 spin_unlock(&delayed_refs->lock);
2935 spin_lock(&head->lock);
2937 * XXX: We should replace this with a proper search function in the
2940 for (node = rb_first_cached(&head->ref_tree); node;
2941 node = rb_next(node)) {
2942 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
2943 /* If it's a shared ref we know a cross reference exists */
2944 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2949 data_ref = btrfs_delayed_node_to_data_ref(ref);
2952 * If our ref doesn't match the one we're currently looking at
2953 * then we have a cross reference.
2955 if (data_ref->root != root->root_key.objectid ||
2956 data_ref->objectid != objectid ||
2957 data_ref->offset != offset) {
2962 spin_unlock(&head->lock);
2963 mutex_unlock(&head->mutex);
2964 btrfs_put_transaction(cur_trans);
2968 static noinline int check_committed_ref(struct btrfs_root *root,
2969 struct btrfs_path *path,
2970 u64 objectid, u64 offset, u64 bytenr)
2972 struct btrfs_fs_info *fs_info = root->fs_info;
2973 struct btrfs_root *extent_root = fs_info->extent_root;
2974 struct extent_buffer *leaf;
2975 struct btrfs_extent_data_ref *ref;
2976 struct btrfs_extent_inline_ref *iref;
2977 struct btrfs_extent_item *ei;
2978 struct btrfs_key key;
2983 key.objectid = bytenr;
2984 key.offset = (u64)-1;
2985 key.type = BTRFS_EXTENT_ITEM_KEY;
2987 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2990 BUG_ON(ret == 0); /* Corruption */
2993 if (path->slots[0] == 0)
2997 leaf = path->nodes[0];
2998 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3000 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
3004 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3005 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
3007 if (item_size != sizeof(*ei) +
3008 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
3011 if (btrfs_extent_generation(leaf, ei) <=
3012 btrfs_root_last_snapshot(&root->root_item))
3015 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
3017 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
3018 if (type != BTRFS_EXTENT_DATA_REF_KEY)
3021 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
3022 if (btrfs_extent_refs(leaf, ei) !=
3023 btrfs_extent_data_ref_count(leaf, ref) ||
3024 btrfs_extent_data_ref_root(leaf, ref) !=
3025 root->root_key.objectid ||
3026 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
3027 btrfs_extent_data_ref_offset(leaf, ref) != offset)
3035 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
3038 struct btrfs_path *path;
3041 path = btrfs_alloc_path();
3046 ret = check_committed_ref(root, path, objectid,
3048 if (ret && ret != -ENOENT)
3051 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
3052 } while (ret == -EAGAIN);
3055 btrfs_free_path(path);
3056 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3061 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
3062 struct btrfs_root *root,
3063 struct extent_buffer *buf,
3064 int full_backref, int inc)
3066 struct btrfs_fs_info *fs_info = root->fs_info;
3072 struct btrfs_key key;
3073 struct btrfs_file_extent_item *fi;
3074 struct btrfs_ref generic_ref = { 0 };
3075 bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
3081 if (btrfs_is_testing(fs_info))
3084 ref_root = btrfs_header_owner(buf);
3085 nritems = btrfs_header_nritems(buf);
3086 level = btrfs_header_level(buf);
3088 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
3092 parent = buf->start;
3096 action = BTRFS_ADD_DELAYED_REF;
3098 action = BTRFS_DROP_DELAYED_REF;
3100 for (i = 0; i < nritems; i++) {
3102 btrfs_item_key_to_cpu(buf, &key, i);
3103 if (key.type != BTRFS_EXTENT_DATA_KEY)
3105 fi = btrfs_item_ptr(buf, i,
3106 struct btrfs_file_extent_item);
3107 if (btrfs_file_extent_type(buf, fi) ==
3108 BTRFS_FILE_EXTENT_INLINE)
3110 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3114 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3115 key.offset -= btrfs_file_extent_offset(buf, fi);
3116 btrfs_init_generic_ref(&generic_ref, action, bytenr,
3118 generic_ref.real_root = root->root_key.objectid;
3119 btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
3121 generic_ref.skip_qgroup = for_reloc;
3123 ret = btrfs_inc_extent_ref(trans, &generic_ref);
3125 ret = btrfs_free_extent(trans, &generic_ref);
3129 bytenr = btrfs_node_blockptr(buf, i);
3130 num_bytes = fs_info->nodesize;
3131 btrfs_init_generic_ref(&generic_ref, action, bytenr,
3133 generic_ref.real_root = root->root_key.objectid;
3134 btrfs_init_tree_ref(&generic_ref, level - 1, ref_root);
3135 generic_ref.skip_qgroup = for_reloc;
3137 ret = btrfs_inc_extent_ref(trans, &generic_ref);
3139 ret = btrfs_free_extent(trans, &generic_ref);
3149 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3150 struct extent_buffer *buf, int full_backref)
3152 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
3155 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3156 struct extent_buffer *buf, int full_backref)
3158 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
3161 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3162 struct btrfs_path *path,
3163 struct btrfs_block_group_cache *cache)
3165 struct btrfs_fs_info *fs_info = trans->fs_info;
3167 struct btrfs_root *extent_root = fs_info->extent_root;
3169 struct extent_buffer *leaf;
3171 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3178 leaf = path->nodes[0];
3179 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3180 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3181 btrfs_mark_buffer_dirty(leaf);
3183 btrfs_release_path(path);
3188 static struct btrfs_block_group_cache *next_block_group(
3189 struct btrfs_block_group_cache *cache)
3191 struct btrfs_fs_info *fs_info = cache->fs_info;
3192 struct rb_node *node;
3194 spin_lock(&fs_info->block_group_cache_lock);
3196 /* If our block group was removed, we need a full search. */
3197 if (RB_EMPTY_NODE(&cache->cache_node)) {
3198 const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3200 spin_unlock(&fs_info->block_group_cache_lock);
3201 btrfs_put_block_group(cache);
3202 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
3204 node = rb_next(&cache->cache_node);
3205 btrfs_put_block_group(cache);
3207 cache = rb_entry(node, struct btrfs_block_group_cache,
3209 btrfs_get_block_group(cache);
3212 spin_unlock(&fs_info->block_group_cache_lock);
3216 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3217 struct btrfs_trans_handle *trans,
3218 struct btrfs_path *path)
3220 struct btrfs_fs_info *fs_info = block_group->fs_info;
3221 struct btrfs_root *root = fs_info->tree_root;
3222 struct inode *inode = NULL;
3223 struct extent_changeset *data_reserved = NULL;
3225 int dcs = BTRFS_DC_ERROR;
3231 * If this block group is smaller than 100 megs don't bother caching the
3234 if (block_group->key.offset < (100 * SZ_1M)) {
3235 spin_lock(&block_group->lock);
3236 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3237 spin_unlock(&block_group->lock);
3244 inode = lookup_free_space_inode(block_group, path);
3245 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3246 ret = PTR_ERR(inode);
3247 btrfs_release_path(path);
3251 if (IS_ERR(inode)) {
3255 if (block_group->ro)
3258 ret = create_free_space_inode(trans, block_group, path);
3265 * We want to set the generation to 0, that way if anything goes wrong
3266 * from here on out we know not to trust this cache when we load up next
3269 BTRFS_I(inode)->generation = 0;
3270 ret = btrfs_update_inode(trans, root, inode);
3273 * So theoretically we could recover from this, simply set the
3274 * super cache generation to 0 so we know to invalidate the
3275 * cache, but then we'd have to keep track of the block groups
3276 * that fail this way so we know we _have_ to reset this cache
3277 * before the next commit or risk reading stale cache. So to
3278 * limit our exposure to horrible edge cases lets just abort the
3279 * transaction, this only happens in really bad situations
3282 btrfs_abort_transaction(trans, ret);
3287 /* We've already setup this transaction, go ahead and exit */
3288 if (block_group->cache_generation == trans->transid &&
3289 i_size_read(inode)) {
3290 dcs = BTRFS_DC_SETUP;
3294 if (i_size_read(inode) > 0) {
3295 ret = btrfs_check_trunc_cache_free_space(fs_info,
3296 &fs_info->global_block_rsv);
3300 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
3305 spin_lock(&block_group->lock);
3306 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3307 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3309 * don't bother trying to write stuff out _if_
3310 * a) we're not cached,
3311 * b) we're with nospace_cache mount option,
3312 * c) we're with v2 space_cache (FREE_SPACE_TREE).
3314 dcs = BTRFS_DC_WRITTEN;
3315 spin_unlock(&block_group->lock);
3318 spin_unlock(&block_group->lock);
3321 * We hit an ENOSPC when setting up the cache in this transaction, just
3322 * skip doing the setup, we've already cleared the cache so we're safe.
3324 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3330 * Try to preallocate enough space based on how big the block group is.
3331 * Keep in mind this has to include any pinned space which could end up
3332 * taking up quite a bit since it's not folded into the other space
3335 num_pages = div_u64(block_group->key.offset, SZ_256M);
3340 num_pages *= PAGE_SIZE;
3342 ret = btrfs_check_data_free_space(inode, &data_reserved, 0, num_pages);
3346 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3347 num_pages, num_pages,
3350 * Our cache requires contiguous chunks so that we don't modify a bunch
3351 * of metadata or split extents when writing the cache out, which means
3352 * we can enospc if we are heavily fragmented in addition to just normal
3353 * out of space conditions. So if we hit this just skip setting up any
3354 * other block groups for this transaction, maybe we'll unpin enough
3355 * space the next time around.
3358 dcs = BTRFS_DC_SETUP;
3359 else if (ret == -ENOSPC)
3360 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3365 btrfs_release_path(path);
3367 spin_lock(&block_group->lock);
3368 if (!ret && dcs == BTRFS_DC_SETUP)
3369 block_group->cache_generation = trans->transid;
3370 block_group->disk_cache_state = dcs;
3371 spin_unlock(&block_group->lock);
3373 extent_changeset_free(data_reserved);
3377 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
3379 struct btrfs_fs_info *fs_info = trans->fs_info;
3380 struct btrfs_block_group_cache *cache, *tmp;
3381 struct btrfs_transaction *cur_trans = trans->transaction;
3382 struct btrfs_path *path;
3384 if (list_empty(&cur_trans->dirty_bgs) ||
3385 !btrfs_test_opt(fs_info, SPACE_CACHE))
3388 path = btrfs_alloc_path();
3392 /* Could add new block groups, use _safe just in case */
3393 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3395 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3396 cache_save_setup(cache, trans, path);
3399 btrfs_free_path(path);
3404 * transaction commit does final block group cache writeback during a
3405 * critical section where nothing is allowed to change the FS. This is
3406 * required in order for the cache to actually match the block group,
3407 * but can introduce a lot of latency into the commit.
3409 * So, btrfs_start_dirty_block_groups is here to kick off block group
3410 * cache IO. There's a chance we'll have to redo some of it if the
3411 * block group changes again during the commit, but it greatly reduces
3412 * the commit latency by getting rid of the easy block groups while
3413 * we're still allowing others to join the commit.
3415 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
3417 struct btrfs_fs_info *fs_info = trans->fs_info;
3418 struct btrfs_block_group_cache *cache;
3419 struct btrfs_transaction *cur_trans = trans->transaction;
3422 struct btrfs_path *path = NULL;
3424 struct list_head *io = &cur_trans->io_bgs;
3425 int num_started = 0;
3428 spin_lock(&cur_trans->dirty_bgs_lock);
3429 if (list_empty(&cur_trans->dirty_bgs)) {
3430 spin_unlock(&cur_trans->dirty_bgs_lock);
3433 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3434 spin_unlock(&cur_trans->dirty_bgs_lock);
3438 * make sure all the block groups on our dirty list actually
3441 btrfs_create_pending_block_groups(trans);
3444 path = btrfs_alloc_path();
3450 * cache_write_mutex is here only to save us from balance or automatic
3451 * removal of empty block groups deleting this block group while we are
3452 * writing out the cache
3454 mutex_lock(&trans->transaction->cache_write_mutex);
3455 while (!list_empty(&dirty)) {
3456 bool drop_reserve = true;
3458 cache = list_first_entry(&dirty,
3459 struct btrfs_block_group_cache,
3462 * this can happen if something re-dirties a block
3463 * group that is already under IO. Just wait for it to
3464 * finish and then do it all again
3466 if (!list_empty(&cache->io_list)) {
3467 list_del_init(&cache->io_list);
3468 btrfs_wait_cache_io(trans, cache, path);
3469 btrfs_put_block_group(cache);
3474 * btrfs_wait_cache_io uses the cache->dirty_list to decide
3475 * if it should update the cache_state. Don't delete
3476 * until after we wait.
3478 * Since we're not running in the commit critical section
3479 * we need the dirty_bgs_lock to protect from update_block_group
3481 spin_lock(&cur_trans->dirty_bgs_lock);
3482 list_del_init(&cache->dirty_list);
3483 spin_unlock(&cur_trans->dirty_bgs_lock);
3487 cache_save_setup(cache, trans, path);
3489 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3490 cache->io_ctl.inode = NULL;
3491 ret = btrfs_write_out_cache(trans, cache, path);
3492 if (ret == 0 && cache->io_ctl.inode) {
3497 * The cache_write_mutex is protecting the
3498 * io_list, also refer to the definition of
3499 * btrfs_transaction::io_bgs for more details
3501 list_add_tail(&cache->io_list, io);
3504 * if we failed to write the cache, the
3505 * generation will be bad and life goes on
3511 ret = write_one_cache_group(trans, path, cache);
3513 * Our block group might still be attached to the list
3514 * of new block groups in the transaction handle of some
3515 * other task (struct btrfs_trans_handle->new_bgs). This
3516 * means its block group item isn't yet in the extent
3517 * tree. If this happens ignore the error, as we will
3518 * try again later in the critical section of the
3519 * transaction commit.
3521 if (ret == -ENOENT) {
3523 spin_lock(&cur_trans->dirty_bgs_lock);
3524 if (list_empty(&cache->dirty_list)) {
3525 list_add_tail(&cache->dirty_list,
3526 &cur_trans->dirty_bgs);
3527 btrfs_get_block_group(cache);
3528 drop_reserve = false;
3530 spin_unlock(&cur_trans->dirty_bgs_lock);
3532 btrfs_abort_transaction(trans, ret);
3536 /* if it's not on the io list, we need to put the block group */
3538 btrfs_put_block_group(cache);
3540 btrfs_delayed_refs_rsv_release(fs_info, 1);
3546 * Avoid blocking other tasks for too long. It might even save
3547 * us from writing caches for block groups that are going to be
3550 mutex_unlock(&trans->transaction->cache_write_mutex);
3551 mutex_lock(&trans->transaction->cache_write_mutex);
3553 mutex_unlock(&trans->transaction->cache_write_mutex);
3556 * go through delayed refs for all the stuff we've just kicked off
3557 * and then loop back (just once)
3559 ret = btrfs_run_delayed_refs(trans, 0);
3560 if (!ret && loops == 0) {
3562 spin_lock(&cur_trans->dirty_bgs_lock);
3563 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3565 * dirty_bgs_lock protects us from concurrent block group
3566 * deletes too (not just cache_write_mutex).
3568 if (!list_empty(&dirty)) {
3569 spin_unlock(&cur_trans->dirty_bgs_lock);
3572 spin_unlock(&cur_trans->dirty_bgs_lock);
3573 } else if (ret < 0) {
3574 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3577 btrfs_free_path(path);
3581 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
3583 struct btrfs_fs_info *fs_info = trans->fs_info;
3584 struct btrfs_block_group_cache *cache;
3585 struct btrfs_transaction *cur_trans = trans->transaction;
3588 struct btrfs_path *path;
3589 struct list_head *io = &cur_trans->io_bgs;
3590 int num_started = 0;
3592 path = btrfs_alloc_path();
3597 * Even though we are in the critical section of the transaction commit,
3598 * we can still have concurrent tasks adding elements to this
3599 * transaction's list of dirty block groups. These tasks correspond to
3600 * endio free space workers started when writeback finishes for a
3601 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3602 * allocate new block groups as a result of COWing nodes of the root
3603 * tree when updating the free space inode. The writeback for the space
3604 * caches is triggered by an earlier call to
3605 * btrfs_start_dirty_block_groups() and iterations of the following
3607 * Also we want to do the cache_save_setup first and then run the
3608 * delayed refs to make sure we have the best chance at doing this all
3611 spin_lock(&cur_trans->dirty_bgs_lock);
3612 while (!list_empty(&cur_trans->dirty_bgs)) {
3613 cache = list_first_entry(&cur_trans->dirty_bgs,
3614 struct btrfs_block_group_cache,
3618 * this can happen if cache_save_setup re-dirties a block
3619 * group that is already under IO. Just wait for it to
3620 * finish and then do it all again
3622 if (!list_empty(&cache->io_list)) {
3623 spin_unlock(&cur_trans->dirty_bgs_lock);
3624 list_del_init(&cache->io_list);
3625 btrfs_wait_cache_io(trans, cache, path);
3626 btrfs_put_block_group(cache);
3627 spin_lock(&cur_trans->dirty_bgs_lock);
3631 * don't remove from the dirty list until after we've waited
3634 list_del_init(&cache->dirty_list);
3635 spin_unlock(&cur_trans->dirty_bgs_lock);
3638 cache_save_setup(cache, trans, path);
3641 ret = btrfs_run_delayed_refs(trans,
3642 (unsigned long) -1);
3644 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3645 cache->io_ctl.inode = NULL;
3646 ret = btrfs_write_out_cache(trans, cache, path);
3647 if (ret == 0 && cache->io_ctl.inode) {
3650 list_add_tail(&cache->io_list, io);
3653 * if we failed to write the cache, the
3654 * generation will be bad and life goes on
3660 ret = write_one_cache_group(trans, path, cache);
3662 * One of the free space endio workers might have
3663 * created a new block group while updating a free space
3664 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3665 * and hasn't released its transaction handle yet, in
3666 * which case the new block group is still attached to
3667 * its transaction handle and its creation has not
3668 * finished yet (no block group item in the extent tree
3669 * yet, etc). If this is the case, wait for all free
3670 * space endio workers to finish and retry. This is a
3671 * a very rare case so no need for a more efficient and
3674 if (ret == -ENOENT) {
3675 wait_event(cur_trans->writer_wait,
3676 atomic_read(&cur_trans->num_writers) == 1);
3677 ret = write_one_cache_group(trans, path, cache);
3680 btrfs_abort_transaction(trans, ret);
3683 /* if its not on the io list, we need to put the block group */
3685 btrfs_put_block_group(cache);
3686 btrfs_delayed_refs_rsv_release(fs_info, 1);
3687 spin_lock(&cur_trans->dirty_bgs_lock);
3689 spin_unlock(&cur_trans->dirty_bgs_lock);
3692 * Refer to the definition of io_bgs member for details why it's safe
3693 * to use it without any locking
3695 while (!list_empty(io)) {
3696 cache = list_first_entry(io, struct btrfs_block_group_cache,
3698 list_del_init(&cache->io_list);
3699 btrfs_wait_cache_io(trans, cache, path);
3700 btrfs_put_block_group(cache);
3703 btrfs_free_path(path);
3707 int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
3709 struct btrfs_block_group_cache *block_group;
3712 block_group = btrfs_lookup_block_group(fs_info, bytenr);
3713 if (!block_group || block_group->ro)
3716 btrfs_put_block_group(block_group);
3720 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3722 struct btrfs_block_group_cache *bg;
3725 bg = btrfs_lookup_block_group(fs_info, bytenr);
3729 spin_lock(&bg->lock);
3733 atomic_inc(&bg->nocow_writers);
3734 spin_unlock(&bg->lock);
3736 /* no put on block group, done by btrfs_dec_nocow_writers */
3738 btrfs_put_block_group(bg);
3744 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3746 struct btrfs_block_group_cache *bg;
3748 bg = btrfs_lookup_block_group(fs_info, bytenr);
3750 if (atomic_dec_and_test(&bg->nocow_writers))
3751 wake_up_var(&bg->nocow_writers);
3753 * Once for our lookup and once for the lookup done by a previous call
3754 * to btrfs_inc_nocow_writers()
3756 btrfs_put_block_group(bg);
3757 btrfs_put_block_group(bg);
3760 void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
3762 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
3765 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3767 u64 extra_flags = chunk_to_extended(flags) &
3768 BTRFS_EXTENDED_PROFILE_MASK;
3770 write_seqlock(&fs_info->profiles_lock);
3771 if (flags & BTRFS_BLOCK_GROUP_DATA)
3772 fs_info->avail_data_alloc_bits |= extra_flags;
3773 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3774 fs_info->avail_metadata_alloc_bits |= extra_flags;
3775 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3776 fs_info->avail_system_alloc_bits |= extra_flags;
3777 write_sequnlock(&fs_info->profiles_lock);
3781 * returns target flags in extended format or 0 if restripe for this
3782 * chunk_type is not in progress
3784 * should be called with balance_lock held
3786 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3788 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3794 if (flags & BTRFS_BLOCK_GROUP_DATA &&
3795 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3796 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3797 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3798 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3799 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3800 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3801 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3802 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3809 * @flags: available profiles in extended format (see ctree.h)
3811 * Returns reduced profile in chunk format. If profile changing is in
3812 * progress (either running or paused) picks the target profile (if it's
3813 * already available), otherwise falls back to plain reducing.
3815 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
3817 u64 num_devices = fs_info->fs_devices->rw_devices;
3823 * see if restripe for this chunk_type is in progress, if so
3824 * try to reduce to the target profile
3826 spin_lock(&fs_info->balance_lock);
3827 target = get_restripe_target(fs_info, flags);
3829 /* pick target profile only if it's already available */
3830 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
3831 spin_unlock(&fs_info->balance_lock);
3832 return extended_to_chunk(target);
3835 spin_unlock(&fs_info->balance_lock);
3837 /* First, mask out the RAID levels which aren't possible */
3838 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3839 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
3840 allowed |= btrfs_raid_array[raid_type].bg_flag;
3844 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
3845 allowed = BTRFS_BLOCK_GROUP_RAID6;
3846 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
3847 allowed = BTRFS_BLOCK_GROUP_RAID5;
3848 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
3849 allowed = BTRFS_BLOCK_GROUP_RAID10;
3850 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
3851 allowed = BTRFS_BLOCK_GROUP_RAID1;
3852 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
3853 allowed = BTRFS_BLOCK_GROUP_RAID0;
3855 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
3857 return extended_to_chunk(flags | allowed);
3860 static u64 get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
3867 seq = read_seqbegin(&fs_info->profiles_lock);
3869 if (flags & BTRFS_BLOCK_GROUP_DATA)
3870 flags |= fs_info->avail_data_alloc_bits;
3871 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3872 flags |= fs_info->avail_system_alloc_bits;
3873 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3874 flags |= fs_info->avail_metadata_alloc_bits;
3875 } while (read_seqretry(&fs_info->profiles_lock, seq));
3877 return btrfs_reduce_alloc_profile(fs_info, flags);
3880 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
3882 struct btrfs_fs_info *fs_info = root->fs_info;
3887 flags = BTRFS_BLOCK_GROUP_DATA;
3888 else if (root == fs_info->chunk_root)
3889 flags = BTRFS_BLOCK_GROUP_SYSTEM;
3891 flags = BTRFS_BLOCK_GROUP_METADATA;
3893 ret = get_alloc_profile(fs_info, flags);
3897 u64 btrfs_data_alloc_profile(struct btrfs_fs_info *fs_info)
3899 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_DATA);
3902 u64 btrfs_metadata_alloc_profile(struct btrfs_fs_info *fs_info)
3904 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_METADATA);
3907 u64 btrfs_system_alloc_profile(struct btrfs_fs_info *fs_info)
3909 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3912 int btrfs_alloc_data_chunk_ondemand(struct btrfs_inode *inode, u64 bytes)
3914 struct btrfs_root *root = inode->root;
3915 struct btrfs_fs_info *fs_info = root->fs_info;
3916 struct btrfs_space_info *data_sinfo = fs_info->data_sinfo;
3919 int need_commit = 2;
3920 int have_pinned_space;
3922 /* make sure bytes are sectorsize aligned */
3923 bytes = ALIGN(bytes, fs_info->sectorsize);
3925 if (btrfs_is_free_space_inode(inode)) {
3927 ASSERT(current->journal_info);
3931 /* make sure we have enough space to handle the data first */
3932 spin_lock(&data_sinfo->lock);
3933 used = btrfs_space_info_used(data_sinfo, true);
3935 if (used + bytes > data_sinfo->total_bytes) {
3936 struct btrfs_trans_handle *trans;
3939 * if we don't have enough free bytes in this space then we need
3940 * to alloc a new chunk.
3942 if (!data_sinfo->full) {
3945 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
3946 spin_unlock(&data_sinfo->lock);
3948 alloc_target = btrfs_data_alloc_profile(fs_info);
3950 * It is ugly that we don't call nolock join
3951 * transaction for the free space inode case here.
3952 * But it is safe because we only do the data space
3953 * reservation for the free space cache in the
3954 * transaction context, the common join transaction
3955 * just increase the counter of the current transaction
3956 * handler, doesn't try to acquire the trans_lock of
3959 trans = btrfs_join_transaction(root);
3961 return PTR_ERR(trans);
3963 ret = btrfs_chunk_alloc(trans, alloc_target,
3964 CHUNK_ALLOC_NO_FORCE);
3965 btrfs_end_transaction(trans);
3970 have_pinned_space = 1;
3979 * If we don't have enough pinned space to deal with this
3980 * allocation, and no removed chunk in current transaction,
3981 * don't bother committing the transaction.
3983 have_pinned_space = __percpu_counter_compare(
3984 &data_sinfo->total_bytes_pinned,
3985 used + bytes - data_sinfo->total_bytes,
3986 BTRFS_TOTAL_BYTES_PINNED_BATCH);
3987 spin_unlock(&data_sinfo->lock);
3989 /* commit the current transaction and try again */
3994 if (need_commit > 0) {
3995 btrfs_start_delalloc_roots(fs_info, -1);
3996 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0,
4000 trans = btrfs_join_transaction(root);
4002 return PTR_ERR(trans);
4003 if (have_pinned_space >= 0 ||
4004 test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
4005 &trans->transaction->flags) ||
4007 ret = btrfs_commit_transaction(trans);
4011 * The cleaner kthread might still be doing iput
4012 * operations. Wait for it to finish so that
4013 * more space is released. We don't need to
4014 * explicitly run the delayed iputs here because
4015 * the commit_transaction would have woken up
4018 ret = btrfs_wait_on_delayed_iputs(fs_info);
4023 btrfs_end_transaction(trans);
4027 trace_btrfs_space_reservation(fs_info,
4028 "space_info:enospc",
4029 data_sinfo->flags, bytes, 1);
4032 btrfs_space_info_update_bytes_may_use(fs_info, data_sinfo, bytes);
4033 trace_btrfs_space_reservation(fs_info, "space_info",
4034 data_sinfo->flags, bytes, 1);
4035 spin_unlock(&data_sinfo->lock);
4040 int btrfs_check_data_free_space(struct inode *inode,
4041 struct extent_changeset **reserved, u64 start, u64 len)
4043 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4046 /* align the range */
4047 len = round_up(start + len, fs_info->sectorsize) -
4048 round_down(start, fs_info->sectorsize);
4049 start = round_down(start, fs_info->sectorsize);
4051 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode), len);
4055 /* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
4056 ret = btrfs_qgroup_reserve_data(inode, reserved, start, len);
4058 btrfs_free_reserved_data_space_noquota(inode, start, len);
4065 * Called if we need to clear a data reservation for this inode
4066 * Normally in a error case.
4068 * This one will *NOT* use accurate qgroup reserved space API, just for case
4069 * which we can't sleep and is sure it won't affect qgroup reserved space.
4070 * Like clear_bit_hook().
4072 void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
4075 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4076 struct btrfs_space_info *data_sinfo;
4078 /* Make sure the range is aligned to sectorsize */
4079 len = round_up(start + len, fs_info->sectorsize) -
4080 round_down(start, fs_info->sectorsize);
4081 start = round_down(start, fs_info->sectorsize);
4083 data_sinfo = fs_info->data_sinfo;
4084 spin_lock(&data_sinfo->lock);
4085 btrfs_space_info_update_bytes_may_use(fs_info, data_sinfo, -len);
4086 trace_btrfs_space_reservation(fs_info, "space_info",
4087 data_sinfo->flags, len, 0);
4088 spin_unlock(&data_sinfo->lock);
4092 * Called if we need to clear a data reservation for this inode
4093 * Normally in a error case.
4095 * This one will handle the per-inode data rsv map for accurate reserved
4098 void btrfs_free_reserved_data_space(struct inode *inode,
4099 struct extent_changeset *reserved, u64 start, u64 len)
4101 struct btrfs_root *root = BTRFS_I(inode)->root;
4103 /* Make sure the range is aligned to sectorsize */
4104 len = round_up(start + len, root->fs_info->sectorsize) -
4105 round_down(start, root->fs_info->sectorsize);
4106 start = round_down(start, root->fs_info->sectorsize);
4108 btrfs_free_reserved_data_space_noquota(inode, start, len);
4109 btrfs_qgroup_free_data(inode, reserved, start, len);
4112 static void force_metadata_allocation(struct btrfs_fs_info *info)
4114 struct list_head *head = &info->space_info;
4115 struct btrfs_space_info *found;
4118 list_for_each_entry_rcu(found, head, list) {
4119 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
4120 found->force_alloc = CHUNK_ALLOC_FORCE;
4125 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
4126 struct btrfs_space_info *sinfo, int force)
4128 u64 bytes_used = btrfs_space_info_used(sinfo, false);
4131 if (force == CHUNK_ALLOC_FORCE)
4135 * in limited mode, we want to have some free space up to
4136 * about 1% of the FS size.
4138 if (force == CHUNK_ALLOC_LIMITED) {
4139 thresh = btrfs_super_total_bytes(fs_info->super_copy);
4140 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
4142 if (sinfo->total_bytes - bytes_used < thresh)
4146 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
4151 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
4155 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
4157 num_dev = fs_info->fs_devices->rw_devices;
4163 * If @is_allocation is true, reserve space in the system space info necessary
4164 * for allocating a chunk, otherwise if it's false, reserve space necessary for
4167 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
4169 struct btrfs_fs_info *fs_info = trans->fs_info;
4170 struct btrfs_space_info *info;
4177 * Needed because we can end up allocating a system chunk and for an
4178 * atomic and race free space reservation in the chunk block reserve.
4180 lockdep_assert_held(&fs_info->chunk_mutex);
4182 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4183 spin_lock(&info->lock);
4184 left = info->total_bytes - btrfs_space_info_used(info, true);
4185 spin_unlock(&info->lock);
4187 num_devs = get_profile_num_devs(fs_info, type);
4189 /* num_devs device items to update and 1 chunk item to add or remove */
4190 thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
4191 btrfs_calc_trans_metadata_size(fs_info, 1);
4193 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4194 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
4195 left, thresh, type);
4196 btrfs_dump_space_info(fs_info, info, 0, 0);
4199 if (left < thresh) {
4200 u64 flags = btrfs_system_alloc_profile(fs_info);
4203 * Ignore failure to create system chunk. We might end up not
4204 * needing it, as we might not need to COW all nodes/leafs from
4205 * the paths we visit in the chunk tree (they were already COWed
4206 * or created in the current transaction for example).
4208 ret = btrfs_alloc_chunk(trans, flags);
4212 ret = btrfs_block_rsv_add(fs_info->chunk_root,
4213 &fs_info->chunk_block_rsv,
4214 thresh, BTRFS_RESERVE_NO_FLUSH);
4216 trans->chunk_bytes_reserved += thresh;
4221 * If force is CHUNK_ALLOC_FORCE:
4222 * - return 1 if it successfully allocates a chunk,
4223 * - return errors including -ENOSPC otherwise.
4224 * If force is NOT CHUNK_ALLOC_FORCE:
4225 * - return 0 if it doesn't need to allocate a new chunk,
4226 * - return 1 if it successfully allocates a chunk,
4227 * - return errors including -ENOSPC otherwise.
4229 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
4230 enum btrfs_chunk_alloc_enum force)
4232 struct btrfs_fs_info *fs_info = trans->fs_info;
4233 struct btrfs_space_info *space_info;
4234 bool wait_for_alloc = false;
4235 bool should_alloc = false;
4238 /* Don't re-enter if we're already allocating a chunk */
4239 if (trans->allocating_chunk)
4242 space_info = btrfs_find_space_info(fs_info, flags);
4246 spin_lock(&space_info->lock);
4247 if (force < space_info->force_alloc)
4248 force = space_info->force_alloc;
4249 should_alloc = should_alloc_chunk(fs_info, space_info, force);
4250 if (space_info->full) {
4251 /* No more free physical space */
4256 spin_unlock(&space_info->lock);
4258 } else if (!should_alloc) {
4259 spin_unlock(&space_info->lock);
4261 } else if (space_info->chunk_alloc) {
4263 * Someone is already allocating, so we need to block
4264 * until this someone is finished and then loop to
4265 * recheck if we should continue with our allocation
4268 wait_for_alloc = true;
4269 spin_unlock(&space_info->lock);
4270 mutex_lock(&fs_info->chunk_mutex);
4271 mutex_unlock(&fs_info->chunk_mutex);
4273 /* Proceed with allocation */
4274 space_info->chunk_alloc = 1;
4275 wait_for_alloc = false;
4276 spin_unlock(&space_info->lock);
4280 } while (wait_for_alloc);
4282 mutex_lock(&fs_info->chunk_mutex);
4283 trans->allocating_chunk = true;
4286 * If we have mixed data/metadata chunks we want to make sure we keep
4287 * allocating mixed chunks instead of individual chunks.
4289 if (btrfs_mixed_space_info(space_info))
4290 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4293 * if we're doing a data chunk, go ahead and make sure that
4294 * we keep a reasonable number of metadata chunks allocated in the
4297 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4298 fs_info->data_chunk_allocations++;
4299 if (!(fs_info->data_chunk_allocations %
4300 fs_info->metadata_ratio))
4301 force_metadata_allocation(fs_info);
4305 * Check if we have enough space in SYSTEM chunk because we may need
4306 * to update devices.
4308 check_system_chunk(trans, flags);
4310 ret = btrfs_alloc_chunk(trans, flags);
4311 trans->allocating_chunk = false;
4313 spin_lock(&space_info->lock);
4316 space_info->full = 1;
4321 space_info->max_extent_size = 0;
4324 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4326 space_info->chunk_alloc = 0;
4327 spin_unlock(&space_info->lock);
4328 mutex_unlock(&fs_info->chunk_mutex);
4330 * When we allocate a new chunk we reserve space in the chunk block
4331 * reserve to make sure we can COW nodes/leafs in the chunk tree or
4332 * add new nodes/leafs to it if we end up needing to do it when
4333 * inserting the chunk item and updating device items as part of the
4334 * second phase of chunk allocation, performed by
4335 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4336 * large number of new block groups to create in our transaction
4337 * handle's new_bgs list to avoid exhausting the chunk block reserve
4338 * in extreme cases - like having a single transaction create many new
4339 * block groups when starting to write out the free space caches of all
4340 * the block groups that were made dirty during the lifetime of the
4343 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
4344 btrfs_create_pending_block_groups(trans);
4349 static struct btrfs_block_rsv *get_block_rsv(
4350 const struct btrfs_trans_handle *trans,
4351 const struct btrfs_root *root)
4353 struct btrfs_fs_info *fs_info = root->fs_info;
4354 struct btrfs_block_rsv *block_rsv = NULL;
4356 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4357 (root == fs_info->csum_root && trans->adding_csums) ||
4358 (root == fs_info->uuid_root))
4359 block_rsv = trans->block_rsv;
4362 block_rsv = root->block_rsv;
4365 block_rsv = &fs_info->empty_block_rsv;
4370 int btrfs_block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv, u64 num_bytes)
4373 spin_lock(&block_rsv->lock);
4374 if (block_rsv->reserved >= num_bytes) {
4375 block_rsv->reserved -= num_bytes;
4376 if (block_rsv->reserved < block_rsv->size)
4377 block_rsv->full = 0;
4380 spin_unlock(&block_rsv->lock);
4384 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
4385 u64 num_bytes, bool update_size)
4387 spin_lock(&block_rsv->lock);
4388 block_rsv->reserved += num_bytes;
4390 block_rsv->size += num_bytes;
4391 else if (block_rsv->reserved >= block_rsv->size)
4392 block_rsv->full = 1;
4393 spin_unlock(&block_rsv->lock);
4396 int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
4397 struct btrfs_block_rsv *dest, u64 num_bytes,
4400 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4403 if (global_rsv->space_info != dest->space_info)
4406 spin_lock(&global_rsv->lock);
4407 min_bytes = div_factor(global_rsv->size, min_factor);
4408 if (global_rsv->reserved < min_bytes + num_bytes) {
4409 spin_unlock(&global_rsv->lock);
4412 global_rsv->reserved -= num_bytes;
4413 if (global_rsv->reserved < global_rsv->size)
4414 global_rsv->full = 0;
4415 spin_unlock(&global_rsv->lock);
4417 block_rsv_add_bytes(dest, num_bytes, true);
4422 * btrfs_migrate_to_delayed_refs_rsv - transfer bytes to our delayed refs rsv.
4423 * @fs_info - the fs info for our fs.
4424 * @src - the source block rsv to transfer from.
4425 * @num_bytes - the number of bytes to transfer.
4427 * This transfers up to the num_bytes amount from the src rsv to the
4428 * delayed_refs_rsv. Any extra bytes are returned to the space info.
4430 void btrfs_migrate_to_delayed_refs_rsv(struct btrfs_fs_info *fs_info,
4431 struct btrfs_block_rsv *src,
4434 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
4437 spin_lock(&src->lock);
4438 src->reserved -= num_bytes;
4439 src->size -= num_bytes;
4440 spin_unlock(&src->lock);
4442 spin_lock(&delayed_refs_rsv->lock);
4443 if (delayed_refs_rsv->size > delayed_refs_rsv->reserved) {
4444 u64 delta = delayed_refs_rsv->size -
4445 delayed_refs_rsv->reserved;
4446 if (num_bytes > delta) {
4447 to_free = num_bytes - delta;
4451 to_free = num_bytes;
4456 delayed_refs_rsv->reserved += num_bytes;
4457 if (delayed_refs_rsv->reserved >= delayed_refs_rsv->size)
4458 delayed_refs_rsv->full = 1;
4459 spin_unlock(&delayed_refs_rsv->lock);
4462 trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
4465 btrfs_space_info_add_old_bytes(fs_info,
4466 delayed_refs_rsv->space_info, to_free);
4470 * btrfs_delayed_refs_rsv_refill - refill based on our delayed refs usage.
4471 * @fs_info - the fs_info for our fs.
4472 * @flush - control how we can flush for this reservation.
4474 * This will refill the delayed block_rsv up to 1 items size worth of space and
4475 * will return -ENOSPC if we can't make the reservation.
4477 int btrfs_delayed_refs_rsv_refill(struct btrfs_fs_info *fs_info,
4478 enum btrfs_reserve_flush_enum flush)
4480 struct btrfs_block_rsv *block_rsv = &fs_info->delayed_refs_rsv;
4481 u64 limit = btrfs_calc_trans_metadata_size(fs_info, 1);
4485 spin_lock(&block_rsv->lock);
4486 if (block_rsv->reserved < block_rsv->size) {
4487 num_bytes = block_rsv->size - block_rsv->reserved;
4488 num_bytes = min(num_bytes, limit);
4490 spin_unlock(&block_rsv->lock);
4495 ret = btrfs_reserve_metadata_bytes(fs_info->extent_root, block_rsv,
4499 block_rsv_add_bytes(block_rsv, num_bytes, 0);
4500 trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
4505 static u64 block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
4506 struct btrfs_block_rsv *block_rsv,
4507 struct btrfs_block_rsv *dest, u64 num_bytes,
4508 u64 *qgroup_to_release_ret)
4510 struct btrfs_space_info *space_info = block_rsv->space_info;
4511 u64 qgroup_to_release = 0;
4514 spin_lock(&block_rsv->lock);
4515 if (num_bytes == (u64)-1) {
4516 num_bytes = block_rsv->size;
4517 qgroup_to_release = block_rsv->qgroup_rsv_size;
4519 block_rsv->size -= num_bytes;
4520 if (block_rsv->reserved >= block_rsv->size) {
4521 num_bytes = block_rsv->reserved - block_rsv->size;
4522 block_rsv->reserved = block_rsv->size;
4523 block_rsv->full = 1;
4527 if (block_rsv->qgroup_rsv_reserved >= block_rsv->qgroup_rsv_size) {
4528 qgroup_to_release = block_rsv->qgroup_rsv_reserved -
4529 block_rsv->qgroup_rsv_size;
4530 block_rsv->qgroup_rsv_reserved = block_rsv->qgroup_rsv_size;
4532 qgroup_to_release = 0;
4534 spin_unlock(&block_rsv->lock);
4537 if (num_bytes > 0) {
4539 spin_lock(&dest->lock);
4543 bytes_to_add = dest->size - dest->reserved;
4544 bytes_to_add = min(num_bytes, bytes_to_add);
4545 dest->reserved += bytes_to_add;
4546 if (dest->reserved >= dest->size)
4548 num_bytes -= bytes_to_add;
4550 spin_unlock(&dest->lock);
4553 btrfs_space_info_add_old_bytes(fs_info, space_info,
4556 if (qgroup_to_release_ret)
4557 *qgroup_to_release_ret = qgroup_to_release;
4561 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
4562 struct btrfs_block_rsv *dst, u64 num_bytes,
4567 ret = btrfs_block_rsv_use_bytes(src, num_bytes);
4571 block_rsv_add_bytes(dst, num_bytes, update_size);
4575 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
4577 memset(rsv, 0, sizeof(*rsv));
4578 spin_lock_init(&rsv->lock);
4582 void btrfs_init_metadata_block_rsv(struct btrfs_fs_info *fs_info,
4583 struct btrfs_block_rsv *rsv,
4584 unsigned short type)
4586 btrfs_init_block_rsv(rsv, type);
4587 rsv->space_info = btrfs_find_space_info(fs_info,
4588 BTRFS_BLOCK_GROUP_METADATA);
4591 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_fs_info *fs_info,
4592 unsigned short type)
4594 struct btrfs_block_rsv *block_rsv;
4596 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
4600 btrfs_init_metadata_block_rsv(fs_info, block_rsv, type);
4604 void btrfs_free_block_rsv(struct btrfs_fs_info *fs_info,
4605 struct btrfs_block_rsv *rsv)
4609 btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
4613 int btrfs_block_rsv_add(struct btrfs_root *root,
4614 struct btrfs_block_rsv *block_rsv, u64 num_bytes,
4615 enum btrfs_reserve_flush_enum flush)
4622 ret = btrfs_reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
4624 block_rsv_add_bytes(block_rsv, num_bytes, true);
4629 int btrfs_block_rsv_check(struct btrfs_block_rsv *block_rsv, int min_factor)
4637 spin_lock(&block_rsv->lock);
4638 num_bytes = div_factor(block_rsv->size, min_factor);
4639 if (block_rsv->reserved >= num_bytes)
4641 spin_unlock(&block_rsv->lock);
4646 int btrfs_block_rsv_refill(struct btrfs_root *root,
4647 struct btrfs_block_rsv *block_rsv, u64 min_reserved,
4648 enum btrfs_reserve_flush_enum flush)
4656 spin_lock(&block_rsv->lock);
4657 num_bytes = min_reserved;
4658 if (block_rsv->reserved >= num_bytes)
4661 num_bytes -= block_rsv->reserved;
4662 spin_unlock(&block_rsv->lock);
4667 ret = btrfs_reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
4669 block_rsv_add_bytes(block_rsv, num_bytes, false);
4676 static u64 __btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
4677 struct btrfs_block_rsv *block_rsv,
4678 u64 num_bytes, u64 *qgroup_to_release)
4680 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4681 struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
4682 struct btrfs_block_rsv *target = delayed_rsv;
4684 if (target->full || target == block_rsv)
4685 target = global_rsv;
4687 if (block_rsv->space_info != target->space_info)
4690 return block_rsv_release_bytes(fs_info, block_rsv, target, num_bytes,
4694 void btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
4695 struct btrfs_block_rsv *block_rsv,
4698 __btrfs_block_rsv_release(fs_info, block_rsv, num_bytes, NULL);
4702 * btrfs_inode_rsv_release - release any excessive reservation.
4703 * @inode - the inode we need to release from.
4704 * @qgroup_free - free or convert qgroup meta.
4705 * Unlike normal operation, qgroup meta reservation needs to know if we are
4706 * freeing qgroup reservation or just converting it into per-trans. Normally
4707 * @qgroup_free is true for error handling, and false for normal release.
4709 * This is the same as btrfs_block_rsv_release, except that it handles the
4710 * tracepoint for the reservation.
4712 static void btrfs_inode_rsv_release(struct btrfs_inode *inode, bool qgroup_free)
4714 struct btrfs_fs_info *fs_info = inode->root->fs_info;
4715 struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
4717 u64 qgroup_to_release = 0;
4720 * Since we statically set the block_rsv->size we just want to say we
4721 * are releasing 0 bytes, and then we'll just get the reservation over
4724 released = __btrfs_block_rsv_release(fs_info, block_rsv, 0,
4725 &qgroup_to_release);
4727 trace_btrfs_space_reservation(fs_info, "delalloc",
4728 btrfs_ino(inode), released, 0);
4730 btrfs_qgroup_free_meta_prealloc(inode->root, qgroup_to_release);
4732 btrfs_qgroup_convert_reserved_meta(inode->root,
4737 * btrfs_delayed_refs_rsv_release - release a ref head's reservation.
4738 * @fs_info - the fs_info for our fs.
4739 * @nr - the number of items to drop.
4741 * This drops the delayed ref head's count from the delayed refs rsv and frees
4742 * any excess reservation we had.
4744 void btrfs_delayed_refs_rsv_release(struct btrfs_fs_info *fs_info, int nr)
4746 struct btrfs_block_rsv *block_rsv = &fs_info->delayed_refs_rsv;
4747 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4748 u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, nr);
4751 released = block_rsv_release_bytes(fs_info, block_rsv, global_rsv,
4754 trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
4758 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
4760 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
4761 struct btrfs_space_info *sinfo = block_rsv->space_info;
4765 * The global block rsv is based on the size of the extent tree, the
4766 * checksum tree and the root tree. If the fs is empty we want to set
4767 * it to a minimal amount for safety.
4769 num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
4770 btrfs_root_used(&fs_info->csum_root->root_item) +
4771 btrfs_root_used(&fs_info->tree_root->root_item);
4772 num_bytes = max_t(u64, num_bytes, SZ_16M);
4774 spin_lock(&sinfo->lock);
4775 spin_lock(&block_rsv->lock);
4777 block_rsv->size = min_t(u64, num_bytes, SZ_512M);
4779 if (block_rsv->reserved < block_rsv->size) {
4780 num_bytes = btrfs_space_info_used(sinfo, true);
4781 if (sinfo->total_bytes > num_bytes) {
4782 num_bytes = sinfo->total_bytes - num_bytes;
4783 num_bytes = min(num_bytes,
4784 block_rsv->size - block_rsv->reserved);
4785 block_rsv->reserved += num_bytes;
4786 btrfs_space_info_update_bytes_may_use(fs_info, sinfo,
4788 trace_btrfs_space_reservation(fs_info, "space_info",
4789 sinfo->flags, num_bytes,
4792 } else if (block_rsv->reserved > block_rsv->size) {
4793 num_bytes = block_rsv->reserved - block_rsv->size;
4794 btrfs_space_info_update_bytes_may_use(fs_info, sinfo,
4796 trace_btrfs_space_reservation(fs_info, "space_info",
4797 sinfo->flags, num_bytes, 0);
4798 block_rsv->reserved = block_rsv->size;
4801 if (block_rsv->reserved == block_rsv->size)
4802 block_rsv->full = 1;
4804 block_rsv->full = 0;
4806 spin_unlock(&block_rsv->lock);
4807 spin_unlock(&sinfo->lock);
4810 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
4812 struct btrfs_space_info *space_info;
4814 space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4815 fs_info->chunk_block_rsv.space_info = space_info;
4817 space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4818 fs_info->global_block_rsv.space_info = space_info;
4819 fs_info->trans_block_rsv.space_info = space_info;
4820 fs_info->empty_block_rsv.space_info = space_info;
4821 fs_info->delayed_block_rsv.space_info = space_info;
4822 fs_info->delayed_refs_rsv.space_info = space_info;
4824 fs_info->extent_root->block_rsv = &fs_info->delayed_refs_rsv;
4825 fs_info->csum_root->block_rsv = &fs_info->delayed_refs_rsv;
4826 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
4827 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
4828 if (fs_info->quota_root)
4829 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
4830 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
4832 update_global_block_rsv(fs_info);
4835 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
4837 block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
4839 WARN_ON(fs_info->trans_block_rsv.size > 0);
4840 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
4841 WARN_ON(fs_info->chunk_block_rsv.size > 0);
4842 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
4843 WARN_ON(fs_info->delayed_block_rsv.size > 0);
4844 WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
4845 WARN_ON(fs_info->delayed_refs_rsv.reserved > 0);
4846 WARN_ON(fs_info->delayed_refs_rsv.size > 0);
4850 * btrfs_update_delayed_refs_rsv - adjust the size of the delayed refs rsv
4851 * @trans - the trans that may have generated delayed refs
4853 * This is to be called anytime we may have adjusted trans->delayed_ref_updates,
4854 * it'll calculate the additional size and add it to the delayed_refs_rsv.
4856 void btrfs_update_delayed_refs_rsv(struct btrfs_trans_handle *trans)
4858 struct btrfs_fs_info *fs_info = trans->fs_info;
4859 struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
4862 if (!trans->delayed_ref_updates)
4865 num_bytes = btrfs_calc_trans_metadata_size(fs_info,
4866 trans->delayed_ref_updates);
4867 spin_lock(&delayed_rsv->lock);
4868 delayed_rsv->size += num_bytes;
4869 delayed_rsv->full = 0;
4870 spin_unlock(&delayed_rsv->lock);
4871 trans->delayed_ref_updates = 0;
4875 * To be called after all the new block groups attached to the transaction
4876 * handle have been created (btrfs_create_pending_block_groups()).
4878 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
4880 struct btrfs_fs_info *fs_info = trans->fs_info;
4882 if (!trans->chunk_bytes_reserved)
4885 WARN_ON_ONCE(!list_empty(&trans->new_bgs));
4887 block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
4888 trans->chunk_bytes_reserved, NULL);
4889 trans->chunk_bytes_reserved = 0;
4893 * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
4894 * root: the root of the parent directory
4895 * rsv: block reservation
4896 * items: the number of items that we need do reservation
4897 * use_global_rsv: allow fallback to the global block reservation
4899 * This function is used to reserve the space for snapshot/subvolume
4900 * creation and deletion. Those operations are different with the
4901 * common file/directory operations, they change two fs/file trees
4902 * and root tree, the number of items that the qgroup reserves is
4903 * different with the free space reservation. So we can not use
4904 * the space reservation mechanism in start_transaction().
4906 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
4907 struct btrfs_block_rsv *rsv, int items,
4908 bool use_global_rsv)
4910 u64 qgroup_num_bytes = 0;
4913 struct btrfs_fs_info *fs_info = root->fs_info;
4914 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4916 if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
4917 /* One for parent inode, two for dir entries */
4918 qgroup_num_bytes = 3 * fs_info->nodesize;
4919 ret = btrfs_qgroup_reserve_meta_prealloc(root,
4920 qgroup_num_bytes, true);
4925 num_bytes = btrfs_calc_trans_metadata_size(fs_info, items);
4926 rsv->space_info = btrfs_find_space_info(fs_info,
4927 BTRFS_BLOCK_GROUP_METADATA);
4928 ret = btrfs_block_rsv_add(root, rsv, num_bytes,
4929 BTRFS_RESERVE_FLUSH_ALL);
4931 if (ret == -ENOSPC && use_global_rsv)
4932 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, true);
4934 if (ret && qgroup_num_bytes)
4935 btrfs_qgroup_free_meta_prealloc(root, qgroup_num_bytes);
4940 void btrfs_subvolume_release_metadata(struct btrfs_fs_info *fs_info,
4941 struct btrfs_block_rsv *rsv)
4943 btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
4946 static void btrfs_calculate_inode_block_rsv_size(struct btrfs_fs_info *fs_info,
4947 struct btrfs_inode *inode)
4949 struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
4950 u64 reserve_size = 0;
4951 u64 qgroup_rsv_size = 0;
4953 unsigned outstanding_extents;
4955 lockdep_assert_held(&inode->lock);
4956 outstanding_extents = inode->outstanding_extents;
4957 if (outstanding_extents)
4958 reserve_size = btrfs_calc_trans_metadata_size(fs_info,
4959 outstanding_extents + 1);
4960 csum_leaves = btrfs_csum_bytes_to_leaves(fs_info,
4962 reserve_size += btrfs_calc_trans_metadata_size(fs_info,
4965 * For qgroup rsv, the calculation is very simple:
4966 * account one nodesize for each outstanding extent
4968 * This is overestimating in most cases.
4970 qgroup_rsv_size = (u64)outstanding_extents * fs_info->nodesize;
4972 spin_lock(&block_rsv->lock);
4973 block_rsv->size = reserve_size;
4974 block_rsv->qgroup_rsv_size = qgroup_rsv_size;
4975 spin_unlock(&block_rsv->lock);
4978 static void calc_inode_reservations(struct btrfs_fs_info *fs_info,
4979 u64 num_bytes, u64 *meta_reserve,
4980 u64 *qgroup_reserve)
4982 u64 nr_extents = count_max_extents(num_bytes);
4983 u64 csum_leaves = btrfs_csum_bytes_to_leaves(fs_info, num_bytes);
4985 /* We add one for the inode update at finish ordered time */
4986 *meta_reserve = btrfs_calc_trans_metadata_size(fs_info,
4987 nr_extents + csum_leaves + 1);
4988 *qgroup_reserve = nr_extents * fs_info->nodesize;
4991 int btrfs_delalloc_reserve_metadata(struct btrfs_inode *inode, u64 num_bytes)
4993 struct btrfs_root *root = inode->root;
4994 struct btrfs_fs_info *fs_info = root->fs_info;
4995 struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
4996 u64 meta_reserve, qgroup_reserve;
4997 unsigned nr_extents;
4998 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
5000 bool delalloc_lock = true;
5002 /* If we are a free space inode we need to not flush since we will be in
5003 * the middle of a transaction commit. We also don't need the delalloc
5004 * mutex since we won't race with anybody. We need this mostly to make
5005 * lockdep shut its filthy mouth.
5007 * If we have a transaction open (can happen if we call truncate_block
5008 * from truncate), then we need FLUSH_LIMIT so we don't deadlock.
5010 if (btrfs_is_free_space_inode(inode)) {
5011 flush = BTRFS_RESERVE_NO_FLUSH;
5012 delalloc_lock = false;
5014 if (current->journal_info)
5015 flush = BTRFS_RESERVE_FLUSH_LIMIT;
5017 if (btrfs_transaction_in_commit(fs_info))
5018 schedule_timeout(1);
5022 mutex_lock(&inode->delalloc_mutex);
5024 num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
5027 * We always want to do it this way, every other way is wrong and ends
5028 * in tears. Pre-reserving the amount we are going to add will always
5029 * be the right way, because otherwise if we have enough parallelism we
5030 * could end up with thousands of inodes all holding little bits of
5031 * reservations they were able to make previously and the only way to
5032 * reclaim that space is to ENOSPC out the operations and clear
5033 * everything out and try again, which is bad. This way we just
5034 * over-reserve slightly, and clean up the mess when we are done.
5036 calc_inode_reservations(fs_info, num_bytes, &meta_reserve,
5038 ret = btrfs_qgroup_reserve_meta_prealloc(root, qgroup_reserve, true);
5041 ret = btrfs_reserve_metadata_bytes(root, block_rsv, meta_reserve, flush);
5046 * Now we need to update our outstanding extents and csum bytes _first_
5047 * and then add the reservation to the block_rsv. This keeps us from
5048 * racing with an ordered completion or some such that would think it
5049 * needs to free the reservation we just made.
5051 spin_lock(&inode->lock);
5052 nr_extents = count_max_extents(num_bytes);
5053 btrfs_mod_outstanding_extents(inode, nr_extents);
5054 inode->csum_bytes += num_bytes;
5055 btrfs_calculate_inode_block_rsv_size(fs_info, inode);
5056 spin_unlock(&inode->lock);
5058 /* Now we can safely add our space to our block rsv */
5059 block_rsv_add_bytes(block_rsv, meta_reserve, false);
5060 trace_btrfs_space_reservation(root->fs_info, "delalloc",
5061 btrfs_ino(inode), meta_reserve, 1);
5063 spin_lock(&block_rsv->lock);
5064 block_rsv->qgroup_rsv_reserved += qgroup_reserve;
5065 spin_unlock(&block_rsv->lock);
5068 mutex_unlock(&inode->delalloc_mutex);
5071 btrfs_qgroup_free_meta_prealloc(root, qgroup_reserve);
5073 btrfs_inode_rsv_release(inode, true);
5075 mutex_unlock(&inode->delalloc_mutex);
5080 * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
5081 * @inode: the inode to release the reservation for.
5082 * @num_bytes: the number of bytes we are releasing.
5083 * @qgroup_free: free qgroup reservation or convert it to per-trans reservation
5085 * This will release the metadata reservation for an inode. This can be called
5086 * once we complete IO for a given set of bytes to release their metadata
5087 * reservations, or on error for the same reason.
5089 void btrfs_delalloc_release_metadata(struct btrfs_inode *inode, u64 num_bytes,
5092 struct btrfs_fs_info *fs_info = inode->root->fs_info;
5094 num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
5095 spin_lock(&inode->lock);
5096 inode->csum_bytes -= num_bytes;
5097 btrfs_calculate_inode_block_rsv_size(fs_info, inode);
5098 spin_unlock(&inode->lock);
5100 if (btrfs_is_testing(fs_info))
5103 btrfs_inode_rsv_release(inode, qgroup_free);
5107 * btrfs_delalloc_release_extents - release our outstanding_extents
5108 * @inode: the inode to balance the reservation for.
5109 * @num_bytes: the number of bytes we originally reserved with
5110 * @qgroup_free: do we need to free qgroup meta reservation or convert them.
5112 * When we reserve space we increase outstanding_extents for the extents we may
5113 * add. Once we've set the range as delalloc or created our ordered extents we
5114 * have outstanding_extents to track the real usage, so we use this to free our
5115 * temporarily tracked outstanding_extents. This _must_ be used in conjunction
5116 * with btrfs_delalloc_reserve_metadata.
5118 void btrfs_delalloc_release_extents(struct btrfs_inode *inode, u64 num_bytes,
5121 struct btrfs_fs_info *fs_info = inode->root->fs_info;
5122 unsigned num_extents;
5124 spin_lock(&inode->lock);
5125 num_extents = count_max_extents(num_bytes);
5126 btrfs_mod_outstanding_extents(inode, -num_extents);
5127 btrfs_calculate_inode_block_rsv_size(fs_info, inode);
5128 spin_unlock(&inode->lock);
5130 if (btrfs_is_testing(fs_info))
5133 btrfs_inode_rsv_release(inode, qgroup_free);
5137 * btrfs_delalloc_reserve_space - reserve data and metadata space for
5139 * @inode: inode we're writing to
5140 * @start: start range we are writing to
5141 * @len: how long the range we are writing to
5142 * @reserved: mandatory parameter, record actually reserved qgroup ranges of
5143 * current reservation.
5145 * This will do the following things
5147 * o reserve space in data space info for num bytes
5148 * and reserve precious corresponding qgroup space
5149 * (Done in check_data_free_space)
5151 * o reserve space for metadata space, based on the number of outstanding
5152 * extents and how much csums will be needed
5153 * also reserve metadata space in a per root over-reserve method.
5154 * o add to the inodes->delalloc_bytes
5155 * o add it to the fs_info's delalloc inodes list.
5156 * (Above 3 all done in delalloc_reserve_metadata)
5158 * Return 0 for success
5159 * Return <0 for error(-ENOSPC or -EQUOT)
5161 int btrfs_delalloc_reserve_space(struct inode *inode,
5162 struct extent_changeset **reserved, u64 start, u64 len)
5166 ret = btrfs_check_data_free_space(inode, reserved, start, len);
5169 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len);
5171 btrfs_free_reserved_data_space(inode, *reserved, start, len);
5176 * btrfs_delalloc_release_space - release data and metadata space for delalloc
5177 * @inode: inode we're releasing space for
5178 * @start: start position of the space already reserved
5179 * @len: the len of the space already reserved
5180 * @release_bytes: the len of the space we consumed or didn't use
5182 * This function will release the metadata space that was not used and will
5183 * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
5184 * list if there are no delalloc bytes left.
5185 * Also it will handle the qgroup reserved space.
5187 void btrfs_delalloc_release_space(struct inode *inode,
5188 struct extent_changeset *reserved,
5189 u64 start, u64 len, bool qgroup_free)
5191 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, qgroup_free);
5192 btrfs_free_reserved_data_space(inode, reserved, start, len);
5195 static int update_block_group(struct btrfs_trans_handle *trans,
5196 u64 bytenr, u64 num_bytes, int alloc)
5198 struct btrfs_fs_info *info = trans->fs_info;
5199 struct btrfs_block_group_cache *cache = NULL;
5200 u64 total = num_bytes;
5206 /* block accounting for super block */
5207 spin_lock(&info->delalloc_root_lock);
5208 old_val = btrfs_super_bytes_used(info->super_copy);
5210 old_val += num_bytes;
5212 old_val -= num_bytes;
5213 btrfs_set_super_bytes_used(info->super_copy, old_val);
5214 spin_unlock(&info->delalloc_root_lock);
5217 cache = btrfs_lookup_block_group(info, bytenr);
5222 factor = btrfs_bg_type_to_factor(cache->flags);
5225 * If this block group has free space cache written out, we
5226 * need to make sure to load it if we are removing space. This
5227 * is because we need the unpinning stage to actually add the
5228 * space back to the block group, otherwise we will leak space.
5230 if (!alloc && cache->cached == BTRFS_CACHE_NO)
5231 cache_block_group(cache, 1);
5233 byte_in_group = bytenr - cache->key.objectid;
5234 WARN_ON(byte_in_group > cache->key.offset);
5236 spin_lock(&cache->space_info->lock);
5237 spin_lock(&cache->lock);
5239 if (btrfs_test_opt(info, SPACE_CACHE) &&
5240 cache->disk_cache_state < BTRFS_DC_CLEAR)
5241 cache->disk_cache_state = BTRFS_DC_CLEAR;
5243 old_val = btrfs_block_group_used(&cache->item);
5244 num_bytes = min(total, cache->key.offset - byte_in_group);
5246 old_val += num_bytes;
5247 btrfs_set_block_group_used(&cache->item, old_val);
5248 cache->reserved -= num_bytes;
5249 cache->space_info->bytes_reserved -= num_bytes;
5250 cache->space_info->bytes_used += num_bytes;
5251 cache->space_info->disk_used += num_bytes * factor;
5252 spin_unlock(&cache->lock);
5253 spin_unlock(&cache->space_info->lock);
5255 old_val -= num_bytes;
5256 btrfs_set_block_group_used(&cache->item, old_val);
5257 cache->pinned += num_bytes;
5258 btrfs_space_info_update_bytes_pinned(info,
5259 cache->space_info, num_bytes);
5260 cache->space_info->bytes_used -= num_bytes;
5261 cache->space_info->disk_used -= num_bytes * factor;
5262 spin_unlock(&cache->lock);
5263 spin_unlock(&cache->space_info->lock);
5265 trace_btrfs_space_reservation(info, "pinned",
5266 cache->space_info->flags,
5268 percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
5270 BTRFS_TOTAL_BYTES_PINNED_BATCH);
5271 set_extent_dirty(info->pinned_extents,
5272 bytenr, bytenr + num_bytes - 1,
5273 GFP_NOFS | __GFP_NOFAIL);
5276 spin_lock(&trans->transaction->dirty_bgs_lock);
5277 if (list_empty(&cache->dirty_list)) {
5278 list_add_tail(&cache->dirty_list,
5279 &trans->transaction->dirty_bgs);
5280 trans->delayed_ref_updates++;
5281 btrfs_get_block_group(cache);
5283 spin_unlock(&trans->transaction->dirty_bgs_lock);
5286 * No longer have used bytes in this block group, queue it for
5287 * deletion. We do this after adding the block group to the
5288 * dirty list to avoid races between cleaner kthread and space
5291 if (!alloc && old_val == 0)
5292 btrfs_mark_bg_unused(cache);
5294 btrfs_put_block_group(cache);
5296 bytenr += num_bytes;
5299 /* Modified block groups are accounted for in the delayed_refs_rsv. */
5300 btrfs_update_delayed_refs_rsv(trans);
5304 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
5306 struct btrfs_block_group_cache *cache;
5309 spin_lock(&fs_info->block_group_cache_lock);
5310 bytenr = fs_info->first_logical_byte;
5311 spin_unlock(&fs_info->block_group_cache_lock);
5313 if (bytenr < (u64)-1)
5316 cache = btrfs_lookup_first_block_group(fs_info, search_start);
5320 bytenr = cache->key.objectid;
5321 btrfs_put_block_group(cache);
5326 static int pin_down_extent(struct btrfs_block_group_cache *cache,
5327 u64 bytenr, u64 num_bytes, int reserved)
5329 struct btrfs_fs_info *fs_info = cache->fs_info;
5331 spin_lock(&cache->space_info->lock);
5332 spin_lock(&cache->lock);
5333 cache->pinned += num_bytes;
5334 btrfs_space_info_update_bytes_pinned(fs_info, cache->space_info,
5337 cache->reserved -= num_bytes;
5338 cache->space_info->bytes_reserved -= num_bytes;
5340 spin_unlock(&cache->lock);
5341 spin_unlock(&cache->space_info->lock);
5343 trace_btrfs_space_reservation(fs_info, "pinned",
5344 cache->space_info->flags, num_bytes, 1);
5345 percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
5346 num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
5347 set_extent_dirty(fs_info->pinned_extents, bytenr,
5348 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
5353 * this function must be called within transaction
5355 int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
5356 u64 bytenr, u64 num_bytes, int reserved)
5358 struct btrfs_block_group_cache *cache;
5360 cache = btrfs_lookup_block_group(fs_info, bytenr);
5361 BUG_ON(!cache); /* Logic error */
5363 pin_down_extent(cache, bytenr, num_bytes, reserved);
5365 btrfs_put_block_group(cache);
5370 * this function must be called within transaction
5372 int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
5373 u64 bytenr, u64 num_bytes)
5375 struct btrfs_block_group_cache *cache;
5378 cache = btrfs_lookup_block_group(fs_info, bytenr);
5383 * pull in the free space cache (if any) so that our pin
5384 * removes the free space from the cache. We have load_only set
5385 * to one because the slow code to read in the free extents does check
5386 * the pinned extents.
5388 cache_block_group(cache, 1);
5390 pin_down_extent(cache, bytenr, num_bytes, 0);
5392 /* remove us from the free space cache (if we're there at all) */
5393 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
5394 btrfs_put_block_group(cache);
5398 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
5399 u64 start, u64 num_bytes)
5402 struct btrfs_block_group_cache *block_group;
5403 struct btrfs_caching_control *caching_ctl;
5405 block_group = btrfs_lookup_block_group(fs_info, start);
5409 cache_block_group(block_group, 0);
5410 caching_ctl = get_caching_control(block_group);
5414 BUG_ON(!block_group_cache_done(block_group));
5415 ret = btrfs_remove_free_space(block_group, start, num_bytes);
5417 mutex_lock(&caching_ctl->mutex);
5419 if (start >= caching_ctl->progress) {
5420 ret = add_excluded_extent(fs_info, start, num_bytes);
5421 } else if (start + num_bytes <= caching_ctl->progress) {
5422 ret = btrfs_remove_free_space(block_group,
5425 num_bytes = caching_ctl->progress - start;
5426 ret = btrfs_remove_free_space(block_group,
5431 num_bytes = (start + num_bytes) -
5432 caching_ctl->progress;
5433 start = caching_ctl->progress;
5434 ret = add_excluded_extent(fs_info, start, num_bytes);
5437 mutex_unlock(&caching_ctl->mutex);
5438 put_caching_control(caching_ctl);
5440 btrfs_put_block_group(block_group);
5444 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
5446 struct btrfs_fs_info *fs_info = eb->fs_info;
5447 struct btrfs_file_extent_item *item;
5448 struct btrfs_key key;
5453 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
5456 for (i = 0; i < btrfs_header_nritems(eb); i++) {
5457 btrfs_item_key_to_cpu(eb, &key, i);
5458 if (key.type != BTRFS_EXTENT_DATA_KEY)
5460 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
5461 found_type = btrfs_file_extent_type(eb, item);
5462 if (found_type == BTRFS_FILE_EXTENT_INLINE)
5464 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
5466 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
5467 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
5468 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
5477 btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
5479 atomic_inc(&bg->reservations);
5482 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
5485 struct btrfs_block_group_cache *bg;
5487 bg = btrfs_lookup_block_group(fs_info, start);
5489 if (atomic_dec_and_test(&bg->reservations))
5490 wake_up_var(&bg->reservations);
5491 btrfs_put_block_group(bg);
5494 void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
5496 struct btrfs_space_info *space_info = bg->space_info;
5500 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
5504 * Our block group is read only but before we set it to read only,
5505 * some task might have had allocated an extent from it already, but it
5506 * has not yet created a respective ordered extent (and added it to a
5507 * root's list of ordered extents).
5508 * Therefore wait for any task currently allocating extents, since the
5509 * block group's reservations counter is incremented while a read lock
5510 * on the groups' semaphore is held and decremented after releasing
5511 * the read access on that semaphore and creating the ordered extent.
5513 down_write(&space_info->groups_sem);
5514 up_write(&space_info->groups_sem);
5516 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
5520 * btrfs_add_reserved_bytes - update the block_group and space info counters
5521 * @cache: The cache we are manipulating
5522 * @ram_bytes: The number of bytes of file content, and will be same to
5523 * @num_bytes except for the compress path.
5524 * @num_bytes: The number of bytes in question
5525 * @delalloc: The blocks are allocated for the delalloc write
5527 * This is called by the allocator when it reserves space. If this is a
5528 * reservation and the block group has become read only we cannot make the
5529 * reservation and return -EAGAIN, otherwise this function always succeeds.
5531 static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
5532 u64 ram_bytes, u64 num_bytes, int delalloc)
5534 struct btrfs_space_info *space_info = cache->space_info;
5537 spin_lock(&space_info->lock);
5538 spin_lock(&cache->lock);
5542 cache->reserved += num_bytes;
5543 space_info->bytes_reserved += num_bytes;
5544 btrfs_space_info_update_bytes_may_use(cache->fs_info,
5545 space_info, -ram_bytes);
5547 cache->delalloc_bytes += num_bytes;
5549 spin_unlock(&cache->lock);
5550 spin_unlock(&space_info->lock);
5555 * btrfs_free_reserved_bytes - update the block_group and space info counters
5556 * @cache: The cache we are manipulating
5557 * @num_bytes: The number of bytes in question
5558 * @delalloc: The blocks are allocated for the delalloc write
5560 * This is called by somebody who is freeing space that was never actually used
5561 * on disk. For example if you reserve some space for a new leaf in transaction
5562 * A and before transaction A commits you free that leaf, you call this with
5563 * reserve set to 0 in order to clear the reservation.
5566 static void btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
5567 u64 num_bytes, int delalloc)
5569 struct btrfs_space_info *space_info = cache->space_info;
5571 spin_lock(&space_info->lock);
5572 spin_lock(&cache->lock);
5574 space_info->bytes_readonly += num_bytes;
5575 cache->reserved -= num_bytes;
5576 space_info->bytes_reserved -= num_bytes;
5577 space_info->max_extent_size = 0;
5580 cache->delalloc_bytes -= num_bytes;
5581 spin_unlock(&cache->lock);
5582 spin_unlock(&space_info->lock);
5584 void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
5586 struct btrfs_caching_control *next;
5587 struct btrfs_caching_control *caching_ctl;
5588 struct btrfs_block_group_cache *cache;
5590 down_write(&fs_info->commit_root_sem);
5592 list_for_each_entry_safe(caching_ctl, next,
5593 &fs_info->caching_block_groups, list) {
5594 cache = caching_ctl->block_group;
5595 if (block_group_cache_done(cache)) {
5596 cache->last_byte_to_unpin = (u64)-1;
5597 list_del_init(&caching_ctl->list);
5598 put_caching_control(caching_ctl);
5600 cache->last_byte_to_unpin = caching_ctl->progress;
5604 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5605 fs_info->pinned_extents = &fs_info->freed_extents[1];
5607 fs_info->pinned_extents = &fs_info->freed_extents[0];
5609 up_write(&fs_info->commit_root_sem);
5611 update_global_block_rsv(fs_info);
5615 * Returns the free cluster for the given space info and sets empty_cluster to
5616 * what it should be based on the mount options.
5618 static struct btrfs_free_cluster *
5619 fetch_cluster_info(struct btrfs_fs_info *fs_info,
5620 struct btrfs_space_info *space_info, u64 *empty_cluster)
5622 struct btrfs_free_cluster *ret = NULL;
5625 if (btrfs_mixed_space_info(space_info))
5628 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
5629 ret = &fs_info->meta_alloc_cluster;
5630 if (btrfs_test_opt(fs_info, SSD))
5631 *empty_cluster = SZ_2M;
5633 *empty_cluster = SZ_64K;
5634 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
5635 btrfs_test_opt(fs_info, SSD_SPREAD)) {
5636 *empty_cluster = SZ_2M;
5637 ret = &fs_info->data_alloc_cluster;
5643 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
5645 const bool return_free_space)
5647 struct btrfs_block_group_cache *cache = NULL;
5648 struct btrfs_space_info *space_info;
5649 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5650 struct btrfs_free_cluster *cluster = NULL;
5652 u64 total_unpinned = 0;
5653 u64 empty_cluster = 0;
5656 while (start <= end) {
5659 start >= cache->key.objectid + cache->key.offset) {
5661 btrfs_put_block_group(cache);
5663 cache = btrfs_lookup_block_group(fs_info, start);
5664 BUG_ON(!cache); /* Logic error */
5666 cluster = fetch_cluster_info(fs_info,
5669 empty_cluster <<= 1;
5672 len = cache->key.objectid + cache->key.offset - start;
5673 len = min(len, end + 1 - start);
5675 if (start < cache->last_byte_to_unpin) {
5676 len = min(len, cache->last_byte_to_unpin - start);
5677 if (return_free_space)
5678 btrfs_add_free_space(cache, start, len);
5682 total_unpinned += len;
5683 space_info = cache->space_info;
5686 * If this space cluster has been marked as fragmented and we've
5687 * unpinned enough in this block group to potentially allow a
5688 * cluster to be created inside of it go ahead and clear the
5691 if (cluster && cluster->fragmented &&
5692 total_unpinned > empty_cluster) {
5693 spin_lock(&cluster->lock);
5694 cluster->fragmented = 0;
5695 spin_unlock(&cluster->lock);
5698 spin_lock(&space_info->lock);
5699 spin_lock(&cache->lock);
5700 cache->pinned -= len;
5701 btrfs_space_info_update_bytes_pinned(fs_info, space_info, -len);
5703 trace_btrfs_space_reservation(fs_info, "pinned",
5704 space_info->flags, len, 0);
5705 space_info->max_extent_size = 0;
5706 percpu_counter_add_batch(&space_info->total_bytes_pinned,
5707 -len, BTRFS_TOTAL_BYTES_PINNED_BATCH);
5709 space_info->bytes_readonly += len;
5712 spin_unlock(&cache->lock);
5713 if (!readonly && return_free_space &&
5714 global_rsv->space_info == space_info) {
5717 spin_lock(&global_rsv->lock);
5718 if (!global_rsv->full) {
5719 to_add = min(len, global_rsv->size -
5720 global_rsv->reserved);
5721 global_rsv->reserved += to_add;
5722 btrfs_space_info_update_bytes_may_use(fs_info,
5723 space_info, to_add);
5724 if (global_rsv->reserved >= global_rsv->size)
5725 global_rsv->full = 1;
5726 trace_btrfs_space_reservation(fs_info,
5732 spin_unlock(&global_rsv->lock);
5733 /* Add to any tickets we may have */
5735 btrfs_space_info_add_new_bytes(fs_info,
5738 spin_unlock(&space_info->lock);
5742 btrfs_put_block_group(cache);
5746 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
5748 struct btrfs_fs_info *fs_info = trans->fs_info;
5749 struct btrfs_block_group_cache *block_group, *tmp;
5750 struct list_head *deleted_bgs;
5751 struct extent_io_tree *unpin;
5756 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5757 unpin = &fs_info->freed_extents[1];
5759 unpin = &fs_info->freed_extents[0];
5761 while (!trans->aborted) {
5762 struct extent_state *cached_state = NULL;
5764 mutex_lock(&fs_info->unused_bg_unpin_mutex);
5765 ret = find_first_extent_bit(unpin, 0, &start, &end,
5766 EXTENT_DIRTY, &cached_state);
5768 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5772 if (btrfs_test_opt(fs_info, DISCARD))
5773 ret = btrfs_discard_extent(fs_info, start,
5774 end + 1 - start, NULL);
5776 clear_extent_dirty(unpin, start, end, &cached_state);
5777 unpin_extent_range(fs_info, start, end, true);
5778 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5779 free_extent_state(cached_state);
5784 * Transaction is finished. We don't need the lock anymore. We
5785 * do need to clean up the block groups in case of a transaction
5788 deleted_bgs = &trans->transaction->deleted_bgs;
5789 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
5793 if (!trans->aborted)
5794 ret = btrfs_discard_extent(fs_info,
5795 block_group->key.objectid,
5796 block_group->key.offset,
5799 list_del_init(&block_group->bg_list);
5800 btrfs_put_block_group_trimming(block_group);
5801 btrfs_put_block_group(block_group);
5804 const char *errstr = btrfs_decode_error(ret);
5806 "discard failed while removing blockgroup: errno=%d %s",
5814 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
5815 struct btrfs_delayed_ref_node *node, u64 parent,
5816 u64 root_objectid, u64 owner_objectid,
5817 u64 owner_offset, int refs_to_drop,
5818 struct btrfs_delayed_extent_op *extent_op)
5820 struct btrfs_fs_info *info = trans->fs_info;
5821 struct btrfs_key key;
5822 struct btrfs_path *path;
5823 struct btrfs_root *extent_root = info->extent_root;
5824 struct extent_buffer *leaf;
5825 struct btrfs_extent_item *ei;
5826 struct btrfs_extent_inline_ref *iref;
5829 int extent_slot = 0;
5830 int found_extent = 0;
5834 u64 bytenr = node->bytenr;
5835 u64 num_bytes = node->num_bytes;
5837 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
5839 path = btrfs_alloc_path();
5843 path->reada = READA_FORWARD;
5844 path->leave_spinning = 1;
5846 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
5847 BUG_ON(!is_data && refs_to_drop != 1);
5850 skinny_metadata = false;
5852 ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
5853 parent, root_objectid, owner_objectid,
5856 extent_slot = path->slots[0];
5857 while (extent_slot >= 0) {
5858 btrfs_item_key_to_cpu(path->nodes[0], &key,
5860 if (key.objectid != bytenr)
5862 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
5863 key.offset == num_bytes) {
5867 if (key.type == BTRFS_METADATA_ITEM_KEY &&
5868 key.offset == owner_objectid) {
5872 if (path->slots[0] - extent_slot > 5)
5877 if (!found_extent) {
5879 ret = remove_extent_backref(trans, path, NULL,
5881 is_data, &last_ref);
5883 btrfs_abort_transaction(trans, ret);
5886 btrfs_release_path(path);
5887 path->leave_spinning = 1;
5889 key.objectid = bytenr;
5890 key.type = BTRFS_EXTENT_ITEM_KEY;
5891 key.offset = num_bytes;
5893 if (!is_data && skinny_metadata) {
5894 key.type = BTRFS_METADATA_ITEM_KEY;
5895 key.offset = owner_objectid;
5898 ret = btrfs_search_slot(trans, extent_root,
5900 if (ret > 0 && skinny_metadata && path->slots[0]) {
5902 * Couldn't find our skinny metadata item,
5903 * see if we have ye olde extent item.
5906 btrfs_item_key_to_cpu(path->nodes[0], &key,
5908 if (key.objectid == bytenr &&
5909 key.type == BTRFS_EXTENT_ITEM_KEY &&
5910 key.offset == num_bytes)
5914 if (ret > 0 && skinny_metadata) {
5915 skinny_metadata = false;
5916 key.objectid = bytenr;
5917 key.type = BTRFS_EXTENT_ITEM_KEY;
5918 key.offset = num_bytes;
5919 btrfs_release_path(path);
5920 ret = btrfs_search_slot(trans, extent_root,
5926 "umm, got %d back from search, was looking for %llu",
5929 btrfs_print_leaf(path->nodes[0]);
5932 btrfs_abort_transaction(trans, ret);
5935 extent_slot = path->slots[0];
5937 } else if (WARN_ON(ret == -ENOENT)) {
5938 btrfs_print_leaf(path->nodes[0]);
5940 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
5941 bytenr, parent, root_objectid, owner_objectid,
5943 btrfs_abort_transaction(trans, ret);
5946 btrfs_abort_transaction(trans, ret);
5950 leaf = path->nodes[0];
5951 item_size = btrfs_item_size_nr(leaf, extent_slot);
5952 if (unlikely(item_size < sizeof(*ei))) {
5954 btrfs_print_v0_err(info);
5955 btrfs_abort_transaction(trans, ret);
5958 ei = btrfs_item_ptr(leaf, extent_slot,
5959 struct btrfs_extent_item);
5960 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
5961 key.type == BTRFS_EXTENT_ITEM_KEY) {
5962 struct btrfs_tree_block_info *bi;
5963 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
5964 bi = (struct btrfs_tree_block_info *)(ei + 1);
5965 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
5968 refs = btrfs_extent_refs(leaf, ei);
5969 if (refs < refs_to_drop) {
5971 "trying to drop %d refs but we only have %Lu for bytenr %Lu",
5972 refs_to_drop, refs, bytenr);
5974 btrfs_abort_transaction(trans, ret);
5977 refs -= refs_to_drop;
5981 __run_delayed_extent_op(extent_op, leaf, ei);
5983 * In the case of inline back ref, reference count will
5984 * be updated by remove_extent_backref
5987 BUG_ON(!found_extent);
5989 btrfs_set_extent_refs(leaf, ei, refs);
5990 btrfs_mark_buffer_dirty(leaf);
5993 ret = remove_extent_backref(trans, path, iref,
5994 refs_to_drop, is_data,
5997 btrfs_abort_transaction(trans, ret);
6003 BUG_ON(is_data && refs_to_drop !=
6004 extent_data_ref_count(path, iref));
6006 BUG_ON(path->slots[0] != extent_slot);
6008 BUG_ON(path->slots[0] != extent_slot + 1);
6009 path->slots[0] = extent_slot;
6015 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
6018 btrfs_abort_transaction(trans, ret);
6021 btrfs_release_path(path);
6024 ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
6026 btrfs_abort_transaction(trans, ret);
6031 ret = add_to_free_space_tree(trans, bytenr, num_bytes);
6033 btrfs_abort_transaction(trans, ret);
6037 ret = update_block_group(trans, bytenr, num_bytes, 0);
6039 btrfs_abort_transaction(trans, ret);
6043 btrfs_release_path(path);
6046 btrfs_free_path(path);
6051 * when we free an block, it is possible (and likely) that we free the last
6052 * delayed ref for that extent as well. This searches the delayed ref tree for
6053 * a given extent, and if there are no other delayed refs to be processed, it
6054 * removes it from the tree.
6056 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
6059 struct btrfs_delayed_ref_head *head;
6060 struct btrfs_delayed_ref_root *delayed_refs;
6063 delayed_refs = &trans->transaction->delayed_refs;
6064 spin_lock(&delayed_refs->lock);
6065 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
6067 goto out_delayed_unlock;
6069 spin_lock(&head->lock);
6070 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
6073 if (cleanup_extent_op(head) != NULL)
6077 * waiting for the lock here would deadlock. If someone else has it
6078 * locked they are already in the process of dropping it anyway
6080 if (!mutex_trylock(&head->mutex))
6083 btrfs_delete_ref_head(delayed_refs, head);
6084 head->processing = 0;
6086 spin_unlock(&head->lock);
6087 spin_unlock(&delayed_refs->lock);
6089 BUG_ON(head->extent_op);
6090 if (head->must_insert_reserved)
6093 btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
6094 mutex_unlock(&head->mutex);
6095 btrfs_put_delayed_ref_head(head);
6098 spin_unlock(&head->lock);
6101 spin_unlock(&delayed_refs->lock);
6105 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
6106 struct btrfs_root *root,
6107 struct extent_buffer *buf,
6108 u64 parent, int last_ref)
6110 struct btrfs_fs_info *fs_info = root->fs_info;
6111 struct btrfs_ref generic_ref = { 0 };
6115 btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
6116 buf->start, buf->len, parent);
6117 btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
6118 root->root_key.objectid);
6120 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
6121 int old_ref_mod, new_ref_mod;
6123 btrfs_ref_tree_mod(fs_info, &generic_ref);
6124 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL,
6125 &old_ref_mod, &new_ref_mod);
6126 BUG_ON(ret); /* -ENOMEM */
6127 pin = old_ref_mod >= 0 && new_ref_mod < 0;
6130 if (last_ref && btrfs_header_generation(buf) == trans->transid) {
6131 struct btrfs_block_group_cache *cache;
6133 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
6134 ret = check_ref_cleanup(trans, buf->start);
6140 cache = btrfs_lookup_block_group(fs_info, buf->start);
6142 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
6143 pin_down_extent(cache, buf->start, buf->len, 1);
6144 btrfs_put_block_group(cache);
6148 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
6150 btrfs_add_free_space(cache, buf->start, buf->len);
6151 btrfs_free_reserved_bytes(cache, buf->len, 0);
6152 btrfs_put_block_group(cache);
6153 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
6157 add_pinned_bytes(fs_info, &generic_ref);
6161 * Deleting the buffer, clear the corrupt flag since it doesn't
6164 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
6168 /* Can return -ENOMEM */
6169 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
6171 struct btrfs_fs_info *fs_info = trans->fs_info;
6172 int old_ref_mod, new_ref_mod;
6175 if (btrfs_is_testing(fs_info))
6179 * tree log blocks never actually go into the extent allocation
6180 * tree, just update pinning info and exit early.
6182 if ((ref->type == BTRFS_REF_METADATA &&
6183 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
6184 (ref->type == BTRFS_REF_DATA &&
6185 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)) {
6186 /* unlocks the pinned mutex */
6187 btrfs_pin_extent(fs_info, ref->bytenr, ref->len, 1);
6188 old_ref_mod = new_ref_mod = 0;
6190 } else if (ref->type == BTRFS_REF_METADATA) {
6191 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL,
6192 &old_ref_mod, &new_ref_mod);
6194 ret = btrfs_add_delayed_data_ref(trans, ref, 0,
6195 &old_ref_mod, &new_ref_mod);
6198 if (!((ref->type == BTRFS_REF_METADATA &&
6199 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
6200 (ref->type == BTRFS_REF_DATA &&
6201 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)))
6202 btrfs_ref_tree_mod(fs_info, ref);
6204 if (ret == 0 && old_ref_mod >= 0 && new_ref_mod < 0)
6205 add_pinned_bytes(fs_info, ref);
6211 * when we wait for progress in the block group caching, its because
6212 * our allocation attempt failed at least once. So, we must sleep
6213 * and let some progress happen before we try again.
6215 * This function will sleep at least once waiting for new free space to
6216 * show up, and then it will check the block group free space numbers
6217 * for our min num_bytes. Another option is to have it go ahead
6218 * and look in the rbtree for a free extent of a given size, but this
6221 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
6222 * any of the information in this block group.
6224 static noinline void
6225 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
6228 struct btrfs_caching_control *caching_ctl;
6230 caching_ctl = get_caching_control(cache);
6234 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
6235 (cache->free_space_ctl->free_space >= num_bytes));
6237 put_caching_control(caching_ctl);
6241 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
6243 struct btrfs_caching_control *caching_ctl;
6246 caching_ctl = get_caching_control(cache);
6248 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
6250 wait_event(caching_ctl->wait, block_group_cache_done(cache));
6251 if (cache->cached == BTRFS_CACHE_ERROR)
6253 put_caching_control(caching_ctl);
6257 enum btrfs_loop_type {
6258 LOOP_CACHING_NOWAIT,
6265 btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
6269 down_read(&cache->data_rwsem);
6273 btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
6276 btrfs_get_block_group(cache);
6278 down_read(&cache->data_rwsem);
6281 static struct btrfs_block_group_cache *
6282 btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
6283 struct btrfs_free_cluster *cluster,
6286 struct btrfs_block_group_cache *used_bg = NULL;
6288 spin_lock(&cluster->refill_lock);
6290 used_bg = cluster->block_group;
6294 if (used_bg == block_group)
6297 btrfs_get_block_group(used_bg);
6302 if (down_read_trylock(&used_bg->data_rwsem))
6305 spin_unlock(&cluster->refill_lock);
6307 /* We should only have one-level nested. */
6308 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
6310 spin_lock(&cluster->refill_lock);
6311 if (used_bg == cluster->block_group)
6314 up_read(&used_bg->data_rwsem);
6315 btrfs_put_block_group(used_bg);
6320 btrfs_release_block_group(struct btrfs_block_group_cache *cache,
6324 up_read(&cache->data_rwsem);
6325 btrfs_put_block_group(cache);
6329 * Structure used internally for find_free_extent() function. Wraps needed
6332 struct find_free_extent_ctl {
6333 /* Basic allocation info */
6340 /* Where to start the search inside the bg */
6343 /* For clustered allocation */
6346 bool have_caching_bg;
6347 bool orig_have_caching_bg;
6349 /* RAID index, converted from flags */
6353 * Current loop number, check find_free_extent_update_loop() for details
6358 * Whether we're refilling a cluster, if true we need to re-search
6359 * current block group but don't try to refill the cluster again.
6361 bool retry_clustered;
6364 * Whether we're updating free space cache, if true we need to re-search
6365 * current block group but don't try updating free space cache again.
6367 bool retry_unclustered;
6369 /* If current block group is cached */
6372 /* Max contiguous hole found */
6373 u64 max_extent_size;
6375 /* Total free space from free space cache, not always contiguous */
6376 u64 total_free_space;
6384 * Helper function for find_free_extent().
6386 * Return -ENOENT to inform caller that we need fallback to unclustered mode.
6387 * Return -EAGAIN to inform caller that we need to re-search this block group
6388 * Return >0 to inform caller that we find nothing
6389 * Return 0 means we have found a location and set ffe_ctl->found_offset.
6391 static int find_free_extent_clustered(struct btrfs_block_group_cache *bg,
6392 struct btrfs_free_cluster *last_ptr,
6393 struct find_free_extent_ctl *ffe_ctl,
6394 struct btrfs_block_group_cache **cluster_bg_ret)
6396 struct btrfs_block_group_cache *cluster_bg;
6397 u64 aligned_cluster;
6401 cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
6403 goto refill_cluster;
6404 if (cluster_bg != bg && (cluster_bg->ro ||
6405 !block_group_bits(cluster_bg, ffe_ctl->flags)))
6406 goto release_cluster;
6408 offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
6409 ffe_ctl->num_bytes, cluster_bg->key.objectid,
6410 &ffe_ctl->max_extent_size);
6412 /* We have a block, we're done */
6413 spin_unlock(&last_ptr->refill_lock);
6414 trace_btrfs_reserve_extent_cluster(cluster_bg,
6415 ffe_ctl->search_start, ffe_ctl->num_bytes);
6416 *cluster_bg_ret = cluster_bg;
6417 ffe_ctl->found_offset = offset;
6420 WARN_ON(last_ptr->block_group != cluster_bg);
6424 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
6425 * lets just skip it and let the allocator find whatever block it can
6426 * find. If we reach this point, we will have tried the cluster
6427 * allocator plenty of times and not have found anything, so we are
6428 * likely way too fragmented for the clustering stuff to find anything.
6430 * However, if the cluster is taken from the current block group,
6431 * release the cluster first, so that we stand a better chance of
6432 * succeeding in the unclustered allocation.
6434 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
6435 spin_unlock(&last_ptr->refill_lock);
6436 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
6440 /* This cluster didn't work out, free it and start over */
6441 btrfs_return_cluster_to_free_space(NULL, last_ptr);
6443 if (cluster_bg != bg)
6444 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
6447 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
6448 spin_unlock(&last_ptr->refill_lock);
6452 aligned_cluster = max_t(u64,
6453 ffe_ctl->empty_cluster + ffe_ctl->empty_size,
6454 bg->full_stripe_len);
6455 ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
6456 ffe_ctl->num_bytes, aligned_cluster);
6458 /* Now pull our allocation out of this cluster */
6459 offset = btrfs_alloc_from_cluster(bg, last_ptr,
6460 ffe_ctl->num_bytes, ffe_ctl->search_start,
6461 &ffe_ctl->max_extent_size);
6463 /* We found one, proceed */
6464 spin_unlock(&last_ptr->refill_lock);
6465 trace_btrfs_reserve_extent_cluster(bg,
6466 ffe_ctl->search_start,
6467 ffe_ctl->num_bytes);
6468 ffe_ctl->found_offset = offset;
6471 } else if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
6472 !ffe_ctl->retry_clustered) {
6473 spin_unlock(&last_ptr->refill_lock);
6475 ffe_ctl->retry_clustered = true;
6476 wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
6477 ffe_ctl->empty_cluster + ffe_ctl->empty_size);
6481 * At this point we either didn't find a cluster or we weren't able to
6482 * allocate a block from our cluster. Free the cluster we've been
6483 * trying to use, and go to the next block group.
6485 btrfs_return_cluster_to_free_space(NULL, last_ptr);
6486 spin_unlock(&last_ptr->refill_lock);
6491 * Return >0 to inform caller that we find nothing
6492 * Return 0 when we found an free extent and set ffe_ctrl->found_offset
6493 * Return -EAGAIN to inform caller that we need to re-search this block group
6495 static int find_free_extent_unclustered(struct btrfs_block_group_cache *bg,
6496 struct btrfs_free_cluster *last_ptr,
6497 struct find_free_extent_ctl *ffe_ctl)
6502 * We are doing an unclustered allocation, set the fragmented flag so
6503 * we don't bother trying to setup a cluster again until we get more
6506 if (unlikely(last_ptr)) {
6507 spin_lock(&last_ptr->lock);
6508 last_ptr->fragmented = 1;
6509 spin_unlock(&last_ptr->lock);
6511 if (ffe_ctl->cached) {
6512 struct btrfs_free_space_ctl *free_space_ctl;
6514 free_space_ctl = bg->free_space_ctl;
6515 spin_lock(&free_space_ctl->tree_lock);
6516 if (free_space_ctl->free_space <
6517 ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
6518 ffe_ctl->empty_size) {
6519 ffe_ctl->total_free_space = max_t(u64,
6520 ffe_ctl->total_free_space,
6521 free_space_ctl->free_space);
6522 spin_unlock(&free_space_ctl->tree_lock);
6525 spin_unlock(&free_space_ctl->tree_lock);
6528 offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
6529 ffe_ctl->num_bytes, ffe_ctl->empty_size,
6530 &ffe_ctl->max_extent_size);
6533 * If we didn't find a chunk, and we haven't failed on this block group
6534 * before, and this block group is in the middle of caching and we are
6535 * ok with waiting, then go ahead and wait for progress to be made, and
6536 * set @retry_unclustered to true.
6538 * If @retry_unclustered is true then we've already waited on this
6539 * block group once and should move on to the next block group.
6541 if (!offset && !ffe_ctl->retry_unclustered && !ffe_ctl->cached &&
6542 ffe_ctl->loop > LOOP_CACHING_NOWAIT) {
6543 wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
6544 ffe_ctl->empty_size);
6545 ffe_ctl->retry_unclustered = true;
6547 } else if (!offset) {
6550 ffe_ctl->found_offset = offset;
6555 * Return >0 means caller needs to re-search for free extent
6556 * Return 0 means we have the needed free extent.
6557 * Return <0 means we failed to locate any free extent.
6559 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
6560 struct btrfs_free_cluster *last_ptr,
6561 struct btrfs_key *ins,
6562 struct find_free_extent_ctl *ffe_ctl,
6563 int full_search, bool use_cluster)
6565 struct btrfs_root *root = fs_info->extent_root;
6568 if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
6569 ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
6570 ffe_ctl->orig_have_caching_bg = true;
6572 if (!ins->objectid && ffe_ctl->loop >= LOOP_CACHING_WAIT &&
6573 ffe_ctl->have_caching_bg)
6576 if (!ins->objectid && ++(ffe_ctl->index) < BTRFS_NR_RAID_TYPES)
6579 if (ins->objectid) {
6580 if (!use_cluster && last_ptr) {
6581 spin_lock(&last_ptr->lock);
6582 last_ptr->window_start = ins->objectid;
6583 spin_unlock(&last_ptr->lock);
6589 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
6590 * caching kthreads as we move along
6591 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
6592 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
6593 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
6596 if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
6598 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT) {
6600 * We want to skip the LOOP_CACHING_WAIT step if we
6601 * don't have any uncached bgs and we've already done a
6602 * full search through.
6604 if (ffe_ctl->orig_have_caching_bg || !full_search)
6605 ffe_ctl->loop = LOOP_CACHING_WAIT;
6607 ffe_ctl->loop = LOOP_ALLOC_CHUNK;
6612 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
6613 struct btrfs_trans_handle *trans;
6616 trans = current->journal_info;
6620 trans = btrfs_join_transaction(root);
6622 if (IS_ERR(trans)) {
6623 ret = PTR_ERR(trans);
6627 ret = btrfs_chunk_alloc(trans, ffe_ctl->flags,
6631 * If we can't allocate a new chunk we've already looped
6632 * through at least once, move on to the NO_EMPTY_SIZE
6636 ffe_ctl->loop = LOOP_NO_EMPTY_SIZE;
6638 /* Do not bail out on ENOSPC since we can do more. */
6639 if (ret < 0 && ret != -ENOSPC)
6640 btrfs_abort_transaction(trans, ret);
6644 btrfs_end_transaction(trans);
6649 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
6651 * Don't loop again if we already have no empty_size and
6654 if (ffe_ctl->empty_size == 0 &&
6655 ffe_ctl->empty_cluster == 0)
6657 ffe_ctl->empty_size = 0;
6658 ffe_ctl->empty_cluster = 0;
6666 * walks the btree of allocated extents and find a hole of a given size.
6667 * The key ins is changed to record the hole:
6668 * ins->objectid == start position
6669 * ins->flags = BTRFS_EXTENT_ITEM_KEY
6670 * ins->offset == the size of the hole.
6671 * Any available blocks before search_start are skipped.
6673 * If there is no suitable free space, we will record the max size of
6674 * the free space extent currently.
6676 * The overall logic and call chain:
6678 * find_free_extent()
6679 * |- Iterate through all block groups
6680 * | |- Get a valid block group
6681 * | |- Try to do clustered allocation in that block group
6682 * | |- Try to do unclustered allocation in that block group
6683 * | |- Check if the result is valid
6684 * | | |- If valid, then exit
6685 * | |- Jump to next block group
6687 * |- Push harder to find free extents
6688 * |- If not found, re-iterate all block groups
6690 static noinline int find_free_extent(struct btrfs_fs_info *fs_info,
6691 u64 ram_bytes, u64 num_bytes, u64 empty_size,
6692 u64 hint_byte, struct btrfs_key *ins,
6693 u64 flags, int delalloc)
6696 struct btrfs_free_cluster *last_ptr = NULL;
6697 struct btrfs_block_group_cache *block_group = NULL;
6698 struct find_free_extent_ctl ffe_ctl = {0};
6699 struct btrfs_space_info *space_info;
6700 bool use_cluster = true;
6701 bool full_search = false;
6703 WARN_ON(num_bytes < fs_info->sectorsize);
6705 ffe_ctl.ram_bytes = ram_bytes;
6706 ffe_ctl.num_bytes = num_bytes;
6707 ffe_ctl.empty_size = empty_size;
6708 ffe_ctl.flags = flags;
6709 ffe_ctl.search_start = 0;
6710 ffe_ctl.retry_clustered = false;
6711 ffe_ctl.retry_unclustered = false;
6712 ffe_ctl.delalloc = delalloc;
6713 ffe_ctl.index = btrfs_bg_flags_to_raid_index(flags);
6714 ffe_ctl.have_caching_bg = false;
6715 ffe_ctl.orig_have_caching_bg = false;
6716 ffe_ctl.found_offset = 0;
6718 ins->type = BTRFS_EXTENT_ITEM_KEY;
6722 trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
6724 space_info = btrfs_find_space_info(fs_info, flags);
6726 btrfs_err(fs_info, "No space info for %llu", flags);
6731 * If our free space is heavily fragmented we may not be able to make
6732 * big contiguous allocations, so instead of doing the expensive search
6733 * for free space, simply return ENOSPC with our max_extent_size so we
6734 * can go ahead and search for a more manageable chunk.
6736 * If our max_extent_size is large enough for our allocation simply
6737 * disable clustering since we will likely not be able to find enough
6738 * space to create a cluster and induce latency trying.
6740 if (unlikely(space_info->max_extent_size)) {
6741 spin_lock(&space_info->lock);
6742 if (space_info->max_extent_size &&
6743 num_bytes > space_info->max_extent_size) {
6744 ins->offset = space_info->max_extent_size;
6745 spin_unlock(&space_info->lock);
6747 } else if (space_info->max_extent_size) {
6748 use_cluster = false;
6750 spin_unlock(&space_info->lock);
6753 last_ptr = fetch_cluster_info(fs_info, space_info,
6754 &ffe_ctl.empty_cluster);
6756 spin_lock(&last_ptr->lock);
6757 if (last_ptr->block_group)
6758 hint_byte = last_ptr->window_start;
6759 if (last_ptr->fragmented) {
6761 * We still set window_start so we can keep track of the
6762 * last place we found an allocation to try and save
6765 hint_byte = last_ptr->window_start;
6766 use_cluster = false;
6768 spin_unlock(&last_ptr->lock);
6771 ffe_ctl.search_start = max(ffe_ctl.search_start,
6772 first_logical_byte(fs_info, 0));
6773 ffe_ctl.search_start = max(ffe_ctl.search_start, hint_byte);
6774 if (ffe_ctl.search_start == hint_byte) {
6775 block_group = btrfs_lookup_block_group(fs_info,
6776 ffe_ctl.search_start);
6778 * we don't want to use the block group if it doesn't match our
6779 * allocation bits, or if its not cached.
6781 * However if we are re-searching with an ideal block group
6782 * picked out then we don't care that the block group is cached.
6784 if (block_group && block_group_bits(block_group, flags) &&
6785 block_group->cached != BTRFS_CACHE_NO) {
6786 down_read(&space_info->groups_sem);
6787 if (list_empty(&block_group->list) ||
6790 * someone is removing this block group,
6791 * we can't jump into the have_block_group
6792 * target because our list pointers are not
6795 btrfs_put_block_group(block_group);
6796 up_read(&space_info->groups_sem);
6798 ffe_ctl.index = btrfs_bg_flags_to_raid_index(
6799 block_group->flags);
6800 btrfs_lock_block_group(block_group, delalloc);
6801 goto have_block_group;
6803 } else if (block_group) {
6804 btrfs_put_block_group(block_group);
6808 ffe_ctl.have_caching_bg = false;
6809 if (ffe_ctl.index == btrfs_bg_flags_to_raid_index(flags) ||
6812 down_read(&space_info->groups_sem);
6813 list_for_each_entry(block_group,
6814 &space_info->block_groups[ffe_ctl.index], list) {
6815 /* If the block group is read-only, we can skip it entirely. */
6816 if (unlikely(block_group->ro))
6819 btrfs_grab_block_group(block_group, delalloc);
6820 ffe_ctl.search_start = block_group->key.objectid;
6823 * this can happen if we end up cycling through all the
6824 * raid types, but we want to make sure we only allocate
6825 * for the proper type.
6827 if (!block_group_bits(block_group, flags)) {
6828 u64 extra = BTRFS_BLOCK_GROUP_DUP |
6829 BTRFS_BLOCK_GROUP_RAID1_MASK |
6830 BTRFS_BLOCK_GROUP_RAID56_MASK |
6831 BTRFS_BLOCK_GROUP_RAID10;
6834 * if they asked for extra copies and this block group
6835 * doesn't provide them, bail. This does allow us to
6836 * fill raid0 from raid1.
6838 if ((flags & extra) && !(block_group->flags & extra))
6843 ffe_ctl.cached = block_group_cache_done(block_group);
6844 if (unlikely(!ffe_ctl.cached)) {
6845 ffe_ctl.have_caching_bg = true;
6846 ret = cache_block_group(block_group, 0);
6851 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
6855 * Ok we want to try and use the cluster allocator, so
6858 if (last_ptr && use_cluster) {
6859 struct btrfs_block_group_cache *cluster_bg = NULL;
6861 ret = find_free_extent_clustered(block_group, last_ptr,
6862 &ffe_ctl, &cluster_bg);
6865 if (cluster_bg && cluster_bg != block_group) {
6866 btrfs_release_block_group(block_group,
6868 block_group = cluster_bg;
6871 } else if (ret == -EAGAIN) {
6872 goto have_block_group;
6873 } else if (ret > 0) {
6876 /* ret == -ENOENT case falls through */
6879 ret = find_free_extent_unclustered(block_group, last_ptr,
6882 goto have_block_group;
6885 /* ret == 0 case falls through */
6887 ffe_ctl.search_start = round_up(ffe_ctl.found_offset,
6888 fs_info->stripesize);
6890 /* move on to the next group */
6891 if (ffe_ctl.search_start + num_bytes >
6892 block_group->key.objectid + block_group->key.offset) {
6893 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
6898 if (ffe_ctl.found_offset < ffe_ctl.search_start)
6899 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
6900 ffe_ctl.search_start - ffe_ctl.found_offset);
6902 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
6903 num_bytes, delalloc);
6904 if (ret == -EAGAIN) {
6905 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
6909 btrfs_inc_block_group_reservations(block_group);
6911 /* we are all good, lets return */
6912 ins->objectid = ffe_ctl.search_start;
6913 ins->offset = num_bytes;
6915 trace_btrfs_reserve_extent(block_group, ffe_ctl.search_start,
6917 btrfs_release_block_group(block_group, delalloc);
6920 ffe_ctl.retry_clustered = false;
6921 ffe_ctl.retry_unclustered = false;
6922 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
6924 btrfs_release_block_group(block_group, delalloc);
6927 up_read(&space_info->groups_sem);
6929 ret = find_free_extent_update_loop(fs_info, last_ptr, ins, &ffe_ctl,
6930 full_search, use_cluster);
6934 if (ret == -ENOSPC) {
6936 * Use ffe_ctl->total_free_space as fallback if we can't find
6937 * any contiguous hole.
6939 if (!ffe_ctl.max_extent_size)
6940 ffe_ctl.max_extent_size = ffe_ctl.total_free_space;
6941 spin_lock(&space_info->lock);
6942 space_info->max_extent_size = ffe_ctl.max_extent_size;
6943 spin_unlock(&space_info->lock);
6944 ins->offset = ffe_ctl.max_extent_size;
6950 * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
6951 * hole that is at least as big as @num_bytes.
6953 * @root - The root that will contain this extent
6955 * @ram_bytes - The amount of space in ram that @num_bytes take. This
6956 * is used for accounting purposes. This value differs
6957 * from @num_bytes only in the case of compressed extents.
6959 * @num_bytes - Number of bytes to allocate on-disk.
6961 * @min_alloc_size - Indicates the minimum amount of space that the
6962 * allocator should try to satisfy. In some cases
6963 * @num_bytes may be larger than what is required and if
6964 * the filesystem is fragmented then allocation fails.
6965 * However, the presence of @min_alloc_size gives a
6966 * chance to try and satisfy the smaller allocation.
6968 * @empty_size - A hint that you plan on doing more COW. This is the
6969 * size in bytes the allocator should try to find free
6970 * next to the block it returns. This is just a hint and
6971 * may be ignored by the allocator.
6973 * @hint_byte - Hint to the allocator to start searching above the byte
6974 * address passed. It might be ignored.
6976 * @ins - This key is modified to record the found hole. It will
6977 * have the following values:
6978 * ins->objectid == start position
6979 * ins->flags = BTRFS_EXTENT_ITEM_KEY
6980 * ins->offset == the size of the hole.
6982 * @is_data - Boolean flag indicating whether an extent is
6983 * allocated for data (true) or metadata (false)
6985 * @delalloc - Boolean flag indicating whether this allocation is for
6986 * delalloc or not. If 'true' data_rwsem of block groups
6987 * is going to be acquired.
6990 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
6991 * case -ENOSPC is returned then @ins->offset will contain the size of the
6992 * largest available hole the allocator managed to find.
6994 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
6995 u64 num_bytes, u64 min_alloc_size,
6996 u64 empty_size, u64 hint_byte,
6997 struct btrfs_key *ins, int is_data, int delalloc)
6999 struct btrfs_fs_info *fs_info = root->fs_info;
7000 bool final_tried = num_bytes == min_alloc_size;
7004 flags = get_alloc_profile_by_root(root, is_data);
7006 WARN_ON(num_bytes < fs_info->sectorsize);
7007 ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
7008 hint_byte, ins, flags, delalloc);
7009 if (!ret && !is_data) {
7010 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
7011 } else if (ret == -ENOSPC) {
7012 if (!final_tried && ins->offset) {
7013 num_bytes = min(num_bytes >> 1, ins->offset);
7014 num_bytes = round_down(num_bytes,
7015 fs_info->sectorsize);
7016 num_bytes = max(num_bytes, min_alloc_size);
7017 ram_bytes = num_bytes;
7018 if (num_bytes == min_alloc_size)
7021 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
7022 struct btrfs_space_info *sinfo;
7024 sinfo = btrfs_find_space_info(fs_info, flags);
7026 "allocation failed flags %llu, wanted %llu",
7029 btrfs_dump_space_info(fs_info, sinfo,
7037 static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
7039 int pin, int delalloc)
7041 struct btrfs_block_group_cache *cache;
7044 cache = btrfs_lookup_block_group(fs_info, start);
7046 btrfs_err(fs_info, "Unable to find block group for %llu",
7052 pin_down_extent(cache, start, len, 1);
7054 if (btrfs_test_opt(fs_info, DISCARD))
7055 ret = btrfs_discard_extent(fs_info, start, len, NULL);
7056 btrfs_add_free_space(cache, start, len);
7057 btrfs_free_reserved_bytes(cache, len, delalloc);
7058 trace_btrfs_reserved_extent_free(fs_info, start, len);
7061 btrfs_put_block_group(cache);
7065 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
7066 u64 start, u64 len, int delalloc)
7068 return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
7071 int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
7074 return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
7077 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
7078 u64 parent, u64 root_objectid,
7079 u64 flags, u64 owner, u64 offset,
7080 struct btrfs_key *ins, int ref_mod)
7082 struct btrfs_fs_info *fs_info = trans->fs_info;
7084 struct btrfs_extent_item *extent_item;
7085 struct btrfs_extent_inline_ref *iref;
7086 struct btrfs_path *path;
7087 struct extent_buffer *leaf;
7092 type = BTRFS_SHARED_DATA_REF_KEY;
7094 type = BTRFS_EXTENT_DATA_REF_KEY;
7096 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
7098 path = btrfs_alloc_path();
7102 path->leave_spinning = 1;
7103 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
7106 btrfs_free_path(path);
7110 leaf = path->nodes[0];
7111 extent_item = btrfs_item_ptr(leaf, path->slots[0],
7112 struct btrfs_extent_item);
7113 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
7114 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
7115 btrfs_set_extent_flags(leaf, extent_item,
7116 flags | BTRFS_EXTENT_FLAG_DATA);
7118 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
7119 btrfs_set_extent_inline_ref_type(leaf, iref, type);
7121 struct btrfs_shared_data_ref *ref;
7122 ref = (struct btrfs_shared_data_ref *)(iref + 1);
7123 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
7124 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
7126 struct btrfs_extent_data_ref *ref;
7127 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
7128 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
7129 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
7130 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
7131 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
7134 btrfs_mark_buffer_dirty(path->nodes[0]);
7135 btrfs_free_path(path);
7137 ret = remove_from_free_space_tree(trans, ins->objectid, ins->offset);
7141 ret = update_block_group(trans, ins->objectid, ins->offset, 1);
7142 if (ret) { /* -ENOENT, logic error */
7143 btrfs_err(fs_info, "update block group failed for %llu %llu",
7144 ins->objectid, ins->offset);
7147 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
7151 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
7152 struct btrfs_delayed_ref_node *node,
7153 struct btrfs_delayed_extent_op *extent_op)
7155 struct btrfs_fs_info *fs_info = trans->fs_info;
7157 struct btrfs_extent_item *extent_item;
7158 struct btrfs_key extent_key;
7159 struct btrfs_tree_block_info *block_info;
7160 struct btrfs_extent_inline_ref *iref;
7161 struct btrfs_path *path;
7162 struct extent_buffer *leaf;
7163 struct btrfs_delayed_tree_ref *ref;
7164 u32 size = sizeof(*extent_item) + sizeof(*iref);
7166 u64 flags = extent_op->flags_to_set;
7167 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
7169 ref = btrfs_delayed_node_to_tree_ref(node);
7171 extent_key.objectid = node->bytenr;
7172 if (skinny_metadata) {
7173 extent_key.offset = ref->level;
7174 extent_key.type = BTRFS_METADATA_ITEM_KEY;
7175 num_bytes = fs_info->nodesize;
7177 extent_key.offset = node->num_bytes;
7178 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
7179 size += sizeof(*block_info);
7180 num_bytes = node->num_bytes;
7183 path = btrfs_alloc_path();
7187 path->leave_spinning = 1;
7188 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
7191 btrfs_free_path(path);
7195 leaf = path->nodes[0];
7196 extent_item = btrfs_item_ptr(leaf, path->slots[0],
7197 struct btrfs_extent_item);
7198 btrfs_set_extent_refs(leaf, extent_item, 1);
7199 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
7200 btrfs_set_extent_flags(leaf, extent_item,
7201 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
7203 if (skinny_metadata) {
7204 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
7206 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
7207 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
7208 btrfs_set_tree_block_level(leaf, block_info, ref->level);
7209 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
7212 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
7213 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
7214 btrfs_set_extent_inline_ref_type(leaf, iref,
7215 BTRFS_SHARED_BLOCK_REF_KEY);
7216 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
7218 btrfs_set_extent_inline_ref_type(leaf, iref,
7219 BTRFS_TREE_BLOCK_REF_KEY);
7220 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
7223 btrfs_mark_buffer_dirty(leaf);
7224 btrfs_free_path(path);
7226 ret = remove_from_free_space_tree(trans, extent_key.objectid,
7231 ret = update_block_group(trans, extent_key.objectid,
7232 fs_info->nodesize, 1);
7233 if (ret) { /* -ENOENT, logic error */
7234 btrfs_err(fs_info, "update block group failed for %llu %llu",
7235 extent_key.objectid, extent_key.offset);
7239 trace_btrfs_reserved_extent_alloc(fs_info, extent_key.objectid,
7244 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
7245 struct btrfs_root *root, u64 owner,
7246 u64 offset, u64 ram_bytes,
7247 struct btrfs_key *ins)
7249 struct btrfs_ref generic_ref = { 0 };
7252 BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
7254 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
7255 ins->objectid, ins->offset, 0);
7256 btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner, offset);
7257 btrfs_ref_tree_mod(root->fs_info, &generic_ref);
7258 ret = btrfs_add_delayed_data_ref(trans, &generic_ref,
7259 ram_bytes, NULL, NULL);
7264 * this is used by the tree logging recovery code. It records that
7265 * an extent has been allocated and makes sure to clear the free
7266 * space cache bits as well
7268 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
7269 u64 root_objectid, u64 owner, u64 offset,
7270 struct btrfs_key *ins)
7272 struct btrfs_fs_info *fs_info = trans->fs_info;
7274 struct btrfs_block_group_cache *block_group;
7275 struct btrfs_space_info *space_info;
7278 * Mixed block groups will exclude before processing the log so we only
7279 * need to do the exclude dance if this fs isn't mixed.
7281 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
7282 ret = __exclude_logged_extent(fs_info, ins->objectid,
7288 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
7292 space_info = block_group->space_info;
7293 spin_lock(&space_info->lock);
7294 spin_lock(&block_group->lock);
7295 space_info->bytes_reserved += ins->offset;
7296 block_group->reserved += ins->offset;
7297 spin_unlock(&block_group->lock);
7298 spin_unlock(&space_info->lock);
7300 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
7302 btrfs_put_block_group(block_group);
7306 static struct extent_buffer *
7307 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
7308 u64 bytenr, int level, u64 owner)
7310 struct btrfs_fs_info *fs_info = root->fs_info;
7311 struct extent_buffer *buf;
7313 buf = btrfs_find_create_tree_block(fs_info, bytenr);
7318 * Extra safety check in case the extent tree is corrupted and extent
7319 * allocator chooses to use a tree block which is already used and
7322 if (buf->lock_owner == current->pid) {
7323 btrfs_err_rl(fs_info,
7324 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
7325 buf->start, btrfs_header_owner(buf), current->pid);
7326 free_extent_buffer(buf);
7327 return ERR_PTR(-EUCLEAN);
7330 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
7331 btrfs_tree_lock(buf);
7332 btrfs_clean_tree_block(buf);
7333 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
7335 btrfs_set_lock_blocking_write(buf);
7336 set_extent_buffer_uptodate(buf);
7338 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
7339 btrfs_set_header_level(buf, level);
7340 btrfs_set_header_bytenr(buf, buf->start);
7341 btrfs_set_header_generation(buf, trans->transid);
7342 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
7343 btrfs_set_header_owner(buf, owner);
7344 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
7345 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
7346 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
7347 buf->log_index = root->log_transid % 2;
7349 * we allow two log transactions at a time, use different
7350 * EXTENT bit to differentiate dirty pages.
7352 if (buf->log_index == 0)
7353 set_extent_dirty(&root->dirty_log_pages, buf->start,
7354 buf->start + buf->len - 1, GFP_NOFS);
7356 set_extent_new(&root->dirty_log_pages, buf->start,
7357 buf->start + buf->len - 1);
7359 buf->log_index = -1;
7360 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
7361 buf->start + buf->len - 1, GFP_NOFS);
7363 trans->dirty = true;
7364 /* this returns a buffer locked for blocking */
7368 static struct btrfs_block_rsv *
7369 use_block_rsv(struct btrfs_trans_handle *trans,
7370 struct btrfs_root *root, u32 blocksize)
7372 struct btrfs_fs_info *fs_info = root->fs_info;
7373 struct btrfs_block_rsv *block_rsv;
7374 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
7376 bool global_updated = false;
7378 block_rsv = get_block_rsv(trans, root);
7380 if (unlikely(block_rsv->size == 0))
7383 ret = btrfs_block_rsv_use_bytes(block_rsv, blocksize);
7387 if (block_rsv->failfast)
7388 return ERR_PTR(ret);
7390 if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
7391 global_updated = true;
7392 update_global_block_rsv(fs_info);
7397 * The global reserve still exists to save us from ourselves, so don't
7398 * warn_on if we are short on our delayed refs reserve.
7400 if (block_rsv->type != BTRFS_BLOCK_RSV_DELREFS &&
7401 btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
7402 static DEFINE_RATELIMIT_STATE(_rs,
7403 DEFAULT_RATELIMIT_INTERVAL * 10,
7404 /*DEFAULT_RATELIMIT_BURST*/ 1);
7405 if (__ratelimit(&_rs))
7407 "BTRFS: block rsv returned %d\n", ret);
7410 ret = btrfs_reserve_metadata_bytes(root, block_rsv, blocksize,
7411 BTRFS_RESERVE_NO_FLUSH);
7415 * If we couldn't reserve metadata bytes try and use some from
7416 * the global reserve if its space type is the same as the global
7419 if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
7420 block_rsv->space_info == global_rsv->space_info) {
7421 ret = btrfs_block_rsv_use_bytes(global_rsv, blocksize);
7425 return ERR_PTR(ret);
7428 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
7429 struct btrfs_block_rsv *block_rsv, u32 blocksize)
7431 block_rsv_add_bytes(block_rsv, blocksize, false);
7432 block_rsv_release_bytes(fs_info, block_rsv, NULL, 0, NULL);
7436 * finds a free extent and does all the dirty work required for allocation
7437 * returns the tree buffer or an ERR_PTR on error.
7439 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
7440 struct btrfs_root *root,
7441 u64 parent, u64 root_objectid,
7442 const struct btrfs_disk_key *key,
7443 int level, u64 hint,
7446 struct btrfs_fs_info *fs_info = root->fs_info;
7447 struct btrfs_key ins;
7448 struct btrfs_block_rsv *block_rsv;
7449 struct extent_buffer *buf;
7450 struct btrfs_delayed_extent_op *extent_op;
7451 struct btrfs_ref generic_ref = { 0 };
7454 u32 blocksize = fs_info->nodesize;
7455 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
7457 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
7458 if (btrfs_is_testing(fs_info)) {
7459 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
7460 level, root_objectid);
7462 root->alloc_bytenr += blocksize;
7467 block_rsv = use_block_rsv(trans, root, blocksize);
7468 if (IS_ERR(block_rsv))
7469 return ERR_CAST(block_rsv);
7471 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
7472 empty_size, hint, &ins, 0, 0);
7476 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
7480 goto out_free_reserved;
7483 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
7485 parent = ins.objectid;
7486 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7490 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
7491 extent_op = btrfs_alloc_delayed_extent_op();
7497 memcpy(&extent_op->key, key, sizeof(extent_op->key));
7499 memset(&extent_op->key, 0, sizeof(extent_op->key));
7500 extent_op->flags_to_set = flags;
7501 extent_op->update_key = skinny_metadata ? false : true;
7502 extent_op->update_flags = true;
7503 extent_op->is_data = false;
7504 extent_op->level = level;
7506 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
7507 ins.objectid, ins.offset, parent);
7508 generic_ref.real_root = root->root_key.objectid;
7509 btrfs_init_tree_ref(&generic_ref, level, root_objectid);
7510 btrfs_ref_tree_mod(fs_info, &generic_ref);
7511 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref,
7512 extent_op, NULL, NULL);
7514 goto out_free_delayed;
7519 btrfs_free_delayed_extent_op(extent_op);
7521 free_extent_buffer(buf);
7523 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
7525 unuse_block_rsv(fs_info, block_rsv, blocksize);
7526 return ERR_PTR(ret);
7529 struct walk_control {
7530 u64 refs[BTRFS_MAX_LEVEL];
7531 u64 flags[BTRFS_MAX_LEVEL];
7532 struct btrfs_key update_progress;
7533 struct btrfs_key drop_progress;
7545 #define DROP_REFERENCE 1
7546 #define UPDATE_BACKREF 2
7548 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
7549 struct btrfs_root *root,
7550 struct walk_control *wc,
7551 struct btrfs_path *path)
7553 struct btrfs_fs_info *fs_info = root->fs_info;
7559 struct btrfs_key key;
7560 struct extent_buffer *eb;
7565 if (path->slots[wc->level] < wc->reada_slot) {
7566 wc->reada_count = wc->reada_count * 2 / 3;
7567 wc->reada_count = max(wc->reada_count, 2);
7569 wc->reada_count = wc->reada_count * 3 / 2;
7570 wc->reada_count = min_t(int, wc->reada_count,
7571 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
7574 eb = path->nodes[wc->level];
7575 nritems = btrfs_header_nritems(eb);
7577 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
7578 if (nread >= wc->reada_count)
7582 bytenr = btrfs_node_blockptr(eb, slot);
7583 generation = btrfs_node_ptr_generation(eb, slot);
7585 if (slot == path->slots[wc->level])
7588 if (wc->stage == UPDATE_BACKREF &&
7589 generation <= root->root_key.offset)
7592 /* We don't lock the tree block, it's OK to be racy here */
7593 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
7594 wc->level - 1, 1, &refs,
7596 /* We don't care about errors in readahead. */
7601 if (wc->stage == DROP_REFERENCE) {
7605 if (wc->level == 1 &&
7606 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7608 if (!wc->update_ref ||
7609 generation <= root->root_key.offset)
7611 btrfs_node_key_to_cpu(eb, &key, slot);
7612 ret = btrfs_comp_cpu_keys(&key,
7613 &wc->update_progress);
7617 if (wc->level == 1 &&
7618 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7622 readahead_tree_block(fs_info, bytenr);
7625 wc->reada_slot = slot;
7629 * helper to process tree block while walking down the tree.
7631 * when wc->stage == UPDATE_BACKREF, this function updates
7632 * back refs for pointers in the block.
7634 * NOTE: return value 1 means we should stop walking down.
7636 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
7637 struct btrfs_root *root,
7638 struct btrfs_path *path,
7639 struct walk_control *wc, int lookup_info)
7641 struct btrfs_fs_info *fs_info = root->fs_info;
7642 int level = wc->level;
7643 struct extent_buffer *eb = path->nodes[level];
7644 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
7647 if (wc->stage == UPDATE_BACKREF &&
7648 btrfs_header_owner(eb) != root->root_key.objectid)
7652 * when reference count of tree block is 1, it won't increase
7653 * again. once full backref flag is set, we never clear it.
7656 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
7657 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
7658 BUG_ON(!path->locks[level]);
7659 ret = btrfs_lookup_extent_info(trans, fs_info,
7660 eb->start, level, 1,
7663 BUG_ON(ret == -ENOMEM);
7666 BUG_ON(wc->refs[level] == 0);
7669 if (wc->stage == DROP_REFERENCE) {
7670 if (wc->refs[level] > 1)
7673 if (path->locks[level] && !wc->keep_locks) {
7674 btrfs_tree_unlock_rw(eb, path->locks[level]);
7675 path->locks[level] = 0;
7680 /* wc->stage == UPDATE_BACKREF */
7681 if (!(wc->flags[level] & flag)) {
7682 BUG_ON(!path->locks[level]);
7683 ret = btrfs_inc_ref(trans, root, eb, 1);
7684 BUG_ON(ret); /* -ENOMEM */
7685 ret = btrfs_dec_ref(trans, root, eb, 0);
7686 BUG_ON(ret); /* -ENOMEM */
7687 ret = btrfs_set_disk_extent_flags(trans, eb->start,
7689 btrfs_header_level(eb), 0);
7690 BUG_ON(ret); /* -ENOMEM */
7691 wc->flags[level] |= flag;
7695 * the block is shared by multiple trees, so it's not good to
7696 * keep the tree lock
7698 if (path->locks[level] && level > 0) {
7699 btrfs_tree_unlock_rw(eb, path->locks[level]);
7700 path->locks[level] = 0;
7706 * This is used to verify a ref exists for this root to deal with a bug where we
7707 * would have a drop_progress key that hadn't been updated properly.
7709 static int check_ref_exists(struct btrfs_trans_handle *trans,
7710 struct btrfs_root *root, u64 bytenr, u64 parent,
7713 struct btrfs_path *path;
7714 struct btrfs_extent_inline_ref *iref;
7717 path = btrfs_alloc_path();
7721 ret = lookup_extent_backref(trans, path, &iref, bytenr,
7722 root->fs_info->nodesize, parent,
7723 root->root_key.objectid, level, 0);
7724 btrfs_free_path(path);
7733 * helper to process tree block pointer.
7735 * when wc->stage == DROP_REFERENCE, this function checks
7736 * reference count of the block pointed to. if the block
7737 * is shared and we need update back refs for the subtree
7738 * rooted at the block, this function changes wc->stage to
7739 * UPDATE_BACKREF. if the block is shared and there is no
7740 * need to update back, this function drops the reference
7743 * NOTE: return value 1 means we should stop walking down.
7745 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
7746 struct btrfs_root *root,
7747 struct btrfs_path *path,
7748 struct walk_control *wc, int *lookup_info)
7750 struct btrfs_fs_info *fs_info = root->fs_info;
7754 struct btrfs_key key;
7755 struct btrfs_key first_key;
7756 struct btrfs_ref ref = { 0 };
7757 struct extent_buffer *next;
7758 int level = wc->level;
7761 bool need_account = false;
7763 generation = btrfs_node_ptr_generation(path->nodes[level],
7764 path->slots[level]);
7766 * if the lower level block was created before the snapshot
7767 * was created, we know there is no need to update back refs
7770 if (wc->stage == UPDATE_BACKREF &&
7771 generation <= root->root_key.offset) {
7776 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
7777 btrfs_node_key_to_cpu(path->nodes[level], &first_key,
7778 path->slots[level]);
7780 next = find_extent_buffer(fs_info, bytenr);
7782 next = btrfs_find_create_tree_block(fs_info, bytenr);
7784 return PTR_ERR(next);
7786 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
7790 btrfs_tree_lock(next);
7791 btrfs_set_lock_blocking_write(next);
7793 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
7794 &wc->refs[level - 1],
7795 &wc->flags[level - 1]);
7799 if (unlikely(wc->refs[level - 1] == 0)) {
7800 btrfs_err(fs_info, "Missing references.");
7806 if (wc->stage == DROP_REFERENCE) {
7807 if (wc->refs[level - 1] > 1) {
7808 need_account = true;
7810 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7813 if (!wc->update_ref ||
7814 generation <= root->root_key.offset)
7817 btrfs_node_key_to_cpu(path->nodes[level], &key,
7818 path->slots[level]);
7819 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
7823 wc->stage = UPDATE_BACKREF;
7824 wc->shared_level = level - 1;
7828 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7832 if (!btrfs_buffer_uptodate(next, generation, 0)) {
7833 btrfs_tree_unlock(next);
7834 free_extent_buffer(next);
7840 if (reada && level == 1)
7841 reada_walk_down(trans, root, wc, path);
7842 next = read_tree_block(fs_info, bytenr, generation, level - 1,
7845 return PTR_ERR(next);
7846 } else if (!extent_buffer_uptodate(next)) {
7847 free_extent_buffer(next);
7850 btrfs_tree_lock(next);
7851 btrfs_set_lock_blocking_write(next);
7855 ASSERT(level == btrfs_header_level(next));
7856 if (level != btrfs_header_level(next)) {
7857 btrfs_err(root->fs_info, "mismatched level");
7861 path->nodes[level] = next;
7862 path->slots[level] = 0;
7863 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7869 wc->refs[level - 1] = 0;
7870 wc->flags[level - 1] = 0;
7871 if (wc->stage == DROP_REFERENCE) {
7872 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
7873 parent = path->nodes[level]->start;
7875 ASSERT(root->root_key.objectid ==
7876 btrfs_header_owner(path->nodes[level]));
7877 if (root->root_key.objectid !=
7878 btrfs_header_owner(path->nodes[level])) {
7879 btrfs_err(root->fs_info,
7880 "mismatched block owner");
7888 * If we had a drop_progress we need to verify the refs are set
7889 * as expected. If we find our ref then we know that from here
7890 * on out everything should be correct, and we can clear the
7893 if (wc->restarted) {
7894 ret = check_ref_exists(trans, root, bytenr, parent,
7905 * Reloc tree doesn't contribute to qgroup numbers, and we have
7906 * already accounted them at merge time (replace_path),
7907 * thus we could skip expensive subtree trace here.
7909 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
7911 ret = btrfs_qgroup_trace_subtree(trans, next,
7912 generation, level - 1);
7914 btrfs_err_rl(fs_info,
7915 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
7921 * We need to update the next key in our walk control so we can
7922 * update the drop_progress key accordingly. We don't care if
7923 * find_next_key doesn't find a key because that means we're at
7924 * the end and are going to clean up now.
7926 wc->drop_level = level;
7927 find_next_key(path, level, &wc->drop_progress);
7929 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
7930 fs_info->nodesize, parent);
7931 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid);
7932 ret = btrfs_free_extent(trans, &ref);
7941 btrfs_tree_unlock(next);
7942 free_extent_buffer(next);
7948 * helper to process tree block while walking up the tree.
7950 * when wc->stage == DROP_REFERENCE, this function drops
7951 * reference count on the block.
7953 * when wc->stage == UPDATE_BACKREF, this function changes
7954 * wc->stage back to DROP_REFERENCE if we changed wc->stage
7955 * to UPDATE_BACKREF previously while processing the block.
7957 * NOTE: return value 1 means we should stop walking up.
7959 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
7960 struct btrfs_root *root,
7961 struct btrfs_path *path,
7962 struct walk_control *wc)
7964 struct btrfs_fs_info *fs_info = root->fs_info;
7966 int level = wc->level;
7967 struct extent_buffer *eb = path->nodes[level];
7970 if (wc->stage == UPDATE_BACKREF) {
7971 BUG_ON(wc->shared_level < level);
7972 if (level < wc->shared_level)
7975 ret = find_next_key(path, level + 1, &wc->update_progress);
7979 wc->stage = DROP_REFERENCE;
7980 wc->shared_level = -1;
7981 path->slots[level] = 0;
7984 * check reference count again if the block isn't locked.
7985 * we should start walking down the tree again if reference
7988 if (!path->locks[level]) {
7990 btrfs_tree_lock(eb);
7991 btrfs_set_lock_blocking_write(eb);
7992 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7994 ret = btrfs_lookup_extent_info(trans, fs_info,
7995 eb->start, level, 1,
7999 btrfs_tree_unlock_rw(eb, path->locks[level]);
8000 path->locks[level] = 0;
8003 BUG_ON(wc->refs[level] == 0);
8004 if (wc->refs[level] == 1) {
8005 btrfs_tree_unlock_rw(eb, path->locks[level]);
8006 path->locks[level] = 0;
8012 /* wc->stage == DROP_REFERENCE */
8013 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
8015 if (wc->refs[level] == 1) {
8017 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8018 ret = btrfs_dec_ref(trans, root, eb, 1);
8020 ret = btrfs_dec_ref(trans, root, eb, 0);
8021 BUG_ON(ret); /* -ENOMEM */
8022 if (is_fstree(root->root_key.objectid)) {
8023 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
8025 btrfs_err_rl(fs_info,
8026 "error %d accounting leaf items, quota is out of sync, rescan required",
8031 /* make block locked assertion in btrfs_clean_tree_block happy */
8032 if (!path->locks[level] &&
8033 btrfs_header_generation(eb) == trans->transid) {
8034 btrfs_tree_lock(eb);
8035 btrfs_set_lock_blocking_write(eb);
8036 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8038 btrfs_clean_tree_block(eb);
8041 if (eb == root->node) {
8042 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8044 else if (root->root_key.objectid != btrfs_header_owner(eb))
8045 goto owner_mismatch;
8047 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8048 parent = path->nodes[level + 1]->start;
8049 else if (root->root_key.objectid !=
8050 btrfs_header_owner(path->nodes[level + 1]))
8051 goto owner_mismatch;
8054 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
8056 wc->refs[level] = 0;
8057 wc->flags[level] = 0;
8061 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
8062 btrfs_header_owner(eb), root->root_key.objectid);
8066 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
8067 struct btrfs_root *root,
8068 struct btrfs_path *path,
8069 struct walk_control *wc)
8071 int level = wc->level;
8072 int lookup_info = 1;
8075 while (level >= 0) {
8076 ret = walk_down_proc(trans, root, path, wc, lookup_info);
8083 if (path->slots[level] >=
8084 btrfs_header_nritems(path->nodes[level]))
8087 ret = do_walk_down(trans, root, path, wc, &lookup_info);
8089 path->slots[level]++;
8098 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
8099 struct btrfs_root *root,
8100 struct btrfs_path *path,
8101 struct walk_control *wc, int max_level)
8103 int level = wc->level;
8106 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
8107 while (level < max_level && path->nodes[level]) {
8109 if (path->slots[level] + 1 <
8110 btrfs_header_nritems(path->nodes[level])) {
8111 path->slots[level]++;
8114 ret = walk_up_proc(trans, root, path, wc);
8120 if (path->locks[level]) {
8121 btrfs_tree_unlock_rw(path->nodes[level],
8122 path->locks[level]);
8123 path->locks[level] = 0;
8125 free_extent_buffer(path->nodes[level]);
8126 path->nodes[level] = NULL;
8134 * drop a subvolume tree.
8136 * this function traverses the tree freeing any blocks that only
8137 * referenced by the tree.
8139 * when a shared tree block is found. this function decreases its
8140 * reference count by one. if update_ref is true, this function
8141 * also make sure backrefs for the shared block and all lower level
8142 * blocks are properly updated.
8144 * If called with for_reloc == 0, may exit early with -EAGAIN
8146 int btrfs_drop_snapshot(struct btrfs_root *root,
8147 struct btrfs_block_rsv *block_rsv, int update_ref,
8150 struct btrfs_fs_info *fs_info = root->fs_info;
8151 struct btrfs_path *path;
8152 struct btrfs_trans_handle *trans;
8153 struct btrfs_root *tree_root = fs_info->tree_root;
8154 struct btrfs_root_item *root_item = &root->root_item;
8155 struct walk_control *wc;
8156 struct btrfs_key key;
8160 bool root_dropped = false;
8162 btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
8164 path = btrfs_alloc_path();
8170 wc = kzalloc(sizeof(*wc), GFP_NOFS);
8172 btrfs_free_path(path);
8177 trans = btrfs_start_transaction(tree_root, 0);
8178 if (IS_ERR(trans)) {
8179 err = PTR_ERR(trans);
8183 err = btrfs_run_delayed_items(trans);
8188 trans->block_rsv = block_rsv;
8191 * This will help us catch people modifying the fs tree while we're
8192 * dropping it. It is unsafe to mess with the fs tree while it's being
8193 * dropped as we unlock the root node and parent nodes as we walk down
8194 * the tree, assuming nothing will change. If something does change
8195 * then we'll have stale information and drop references to blocks we've
8198 set_bit(BTRFS_ROOT_DELETING, &root->state);
8199 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
8200 level = btrfs_header_level(root->node);
8201 path->nodes[level] = btrfs_lock_root_node(root);
8202 btrfs_set_lock_blocking_write(path->nodes[level]);
8203 path->slots[level] = 0;
8204 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8205 memset(&wc->update_progress, 0,
8206 sizeof(wc->update_progress));
8208 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
8209 memcpy(&wc->update_progress, &key,
8210 sizeof(wc->update_progress));
8212 level = root_item->drop_level;
8214 path->lowest_level = level;
8215 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8216 path->lowest_level = 0;
8224 * unlock our path, this is safe because only this
8225 * function is allowed to delete this snapshot
8227 btrfs_unlock_up_safe(path, 0);
8229 level = btrfs_header_level(root->node);
8231 btrfs_tree_lock(path->nodes[level]);
8232 btrfs_set_lock_blocking_write(path->nodes[level]);
8233 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8235 ret = btrfs_lookup_extent_info(trans, fs_info,
8236 path->nodes[level]->start,
8237 level, 1, &wc->refs[level],
8243 BUG_ON(wc->refs[level] == 0);
8245 if (level == root_item->drop_level)
8248 btrfs_tree_unlock(path->nodes[level]);
8249 path->locks[level] = 0;
8250 WARN_ON(wc->refs[level] != 1);
8255 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
8257 wc->shared_level = -1;
8258 wc->stage = DROP_REFERENCE;
8259 wc->update_ref = update_ref;
8261 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
8265 ret = walk_down_tree(trans, root, path, wc);
8271 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
8278 BUG_ON(wc->stage != DROP_REFERENCE);
8282 if (wc->stage == DROP_REFERENCE) {
8283 wc->drop_level = wc->level;
8284 btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
8286 path->slots[wc->drop_level]);
8288 btrfs_cpu_key_to_disk(&root_item->drop_progress,
8289 &wc->drop_progress);
8290 root_item->drop_level = wc->drop_level;
8292 BUG_ON(wc->level == 0);
8293 if (btrfs_should_end_transaction(trans) ||
8294 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
8295 ret = btrfs_update_root(trans, tree_root,
8299 btrfs_abort_transaction(trans, ret);
8304 btrfs_end_transaction_throttle(trans);
8305 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
8306 btrfs_debug(fs_info,
8307 "drop snapshot early exit");
8312 trans = btrfs_start_transaction(tree_root, 0);
8313 if (IS_ERR(trans)) {
8314 err = PTR_ERR(trans);
8318 trans->block_rsv = block_rsv;
8321 btrfs_release_path(path);
8325 ret = btrfs_del_root(trans, &root->root_key);
8327 btrfs_abort_transaction(trans, ret);
8332 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
8333 ret = btrfs_find_root(tree_root, &root->root_key, path,
8336 btrfs_abort_transaction(trans, ret);
8339 } else if (ret > 0) {
8340 /* if we fail to delete the orphan item this time
8341 * around, it'll get picked up the next time.
8343 * The most common failure here is just -ENOENT.
8345 btrfs_del_orphan_item(trans, tree_root,
8346 root->root_key.objectid);
8350 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
8351 btrfs_add_dropped_root(trans, root);
8353 free_extent_buffer(root->node);
8354 free_extent_buffer(root->commit_root);
8355 btrfs_put_fs_root(root);
8357 root_dropped = true;
8359 btrfs_end_transaction_throttle(trans);
8362 btrfs_free_path(path);
8365 * So if we need to stop dropping the snapshot for whatever reason we
8366 * need to make sure to add it back to the dead root list so that we
8367 * keep trying to do the work later. This also cleans up roots if we
8368 * don't have it in the radix (like when we recover after a power fail
8369 * or unmount) so we don't leak memory.
8371 if (!for_reloc && !root_dropped)
8372 btrfs_add_dead_root(root);
8373 if (err && err != -EAGAIN)
8374 btrfs_handle_fs_error(fs_info, err, NULL);
8379 * drop subtree rooted at tree block 'node'.
8381 * NOTE: this function will unlock and release tree block 'node'
8382 * only used by relocation code
8384 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
8385 struct btrfs_root *root,
8386 struct extent_buffer *node,
8387 struct extent_buffer *parent)
8389 struct btrfs_fs_info *fs_info = root->fs_info;
8390 struct btrfs_path *path;
8391 struct walk_control *wc;
8397 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
8399 path = btrfs_alloc_path();
8403 wc = kzalloc(sizeof(*wc), GFP_NOFS);
8405 btrfs_free_path(path);
8409 btrfs_assert_tree_locked(parent);
8410 parent_level = btrfs_header_level(parent);
8411 extent_buffer_get(parent);
8412 path->nodes[parent_level] = parent;
8413 path->slots[parent_level] = btrfs_header_nritems(parent);
8415 btrfs_assert_tree_locked(node);
8416 level = btrfs_header_level(node);
8417 path->nodes[level] = node;
8418 path->slots[level] = 0;
8419 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8421 wc->refs[parent_level] = 1;
8422 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8424 wc->shared_level = -1;
8425 wc->stage = DROP_REFERENCE;
8428 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
8431 wret = walk_down_tree(trans, root, path, wc);
8437 wret = walk_up_tree(trans, root, path, wc, parent_level);
8445 btrfs_free_path(path);
8449 static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
8455 * if restripe for this chunk_type is on pick target profile and
8456 * return, otherwise do the usual balance
8458 stripped = get_restripe_target(fs_info, flags);
8460 return extended_to_chunk(stripped);
8462 num_devices = fs_info->fs_devices->rw_devices;
8464 stripped = BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID56_MASK |
8465 BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10;
8467 if (num_devices == 1) {
8468 stripped |= BTRFS_BLOCK_GROUP_DUP;
8469 stripped = flags & ~stripped;
8471 /* turn raid0 into single device chunks */
8472 if (flags & BTRFS_BLOCK_GROUP_RAID0)
8475 /* turn mirroring into duplication */
8476 if (flags & (BTRFS_BLOCK_GROUP_RAID1_MASK |
8477 BTRFS_BLOCK_GROUP_RAID10))
8478 return stripped | BTRFS_BLOCK_GROUP_DUP;
8480 /* they already had raid on here, just return */
8481 if (flags & stripped)
8484 stripped |= BTRFS_BLOCK_GROUP_DUP;
8485 stripped = flags & ~stripped;
8487 /* switch duplicated blocks with raid1 */
8488 if (flags & BTRFS_BLOCK_GROUP_DUP)
8489 return stripped | BTRFS_BLOCK_GROUP_RAID1;
8491 /* this is drive concat, leave it alone */
8497 static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
8499 struct btrfs_space_info *sinfo = cache->space_info;
8502 u64 min_allocable_bytes;
8506 * We need some metadata space and system metadata space for
8507 * allocating chunks in some corner cases until we force to set
8508 * it to be readonly.
8511 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
8513 min_allocable_bytes = SZ_1M;
8515 min_allocable_bytes = 0;
8517 spin_lock(&sinfo->lock);
8518 spin_lock(&cache->lock);
8526 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
8527 cache->bytes_super - btrfs_block_group_used(&cache->item);
8528 sinfo_used = btrfs_space_info_used(sinfo, true);
8530 if (sinfo_used + num_bytes + min_allocable_bytes <=
8531 sinfo->total_bytes) {
8532 sinfo->bytes_readonly += num_bytes;
8534 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
8538 spin_unlock(&cache->lock);
8539 spin_unlock(&sinfo->lock);
8540 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
8541 btrfs_info(cache->fs_info,
8542 "unable to make block group %llu ro",
8543 cache->key.objectid);
8544 btrfs_info(cache->fs_info,
8545 "sinfo_used=%llu bg_num_bytes=%llu min_allocable=%llu",
8546 sinfo_used, num_bytes, min_allocable_bytes);
8547 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
8552 int btrfs_inc_block_group_ro(struct btrfs_block_group_cache *cache)
8555 struct btrfs_fs_info *fs_info = cache->fs_info;
8556 struct btrfs_trans_handle *trans;
8561 trans = btrfs_join_transaction(fs_info->extent_root);
8563 return PTR_ERR(trans);
8566 * we're not allowed to set block groups readonly after the dirty
8567 * block groups cache has started writing. If it already started,
8568 * back off and let this transaction commit
8570 mutex_lock(&fs_info->ro_block_group_mutex);
8571 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
8572 u64 transid = trans->transid;
8574 mutex_unlock(&fs_info->ro_block_group_mutex);
8575 btrfs_end_transaction(trans);
8577 ret = btrfs_wait_for_commit(fs_info, transid);
8584 * if we are changing raid levels, try to allocate a corresponding
8585 * block group with the new raid level.
8587 alloc_flags = update_block_group_flags(fs_info, cache->flags);
8588 if (alloc_flags != cache->flags) {
8589 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
8591 * ENOSPC is allowed here, we may have enough space
8592 * already allocated at the new raid level to
8601 ret = inc_block_group_ro(cache, 0);
8604 alloc_flags = get_alloc_profile(fs_info, cache->space_info->flags);
8605 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
8608 ret = inc_block_group_ro(cache, 0);
8610 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
8611 alloc_flags = update_block_group_flags(fs_info, cache->flags);
8612 mutex_lock(&fs_info->chunk_mutex);
8613 check_system_chunk(trans, alloc_flags);
8614 mutex_unlock(&fs_info->chunk_mutex);
8616 mutex_unlock(&fs_info->ro_block_group_mutex);
8618 btrfs_end_transaction(trans);
8622 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
8624 u64 alloc_flags = get_alloc_profile(trans->fs_info, type);
8626 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
8630 * helper to account the unused space of all the readonly block group in the
8631 * space_info. takes mirrors into account.
8633 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
8635 struct btrfs_block_group_cache *block_group;
8639 /* It's df, we don't care if it's racy */
8640 if (list_empty(&sinfo->ro_bgs))
8643 spin_lock(&sinfo->lock);
8644 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
8645 spin_lock(&block_group->lock);
8647 if (!block_group->ro) {
8648 spin_unlock(&block_group->lock);
8652 factor = btrfs_bg_type_to_factor(block_group->flags);
8653 free_bytes += (block_group->key.offset -
8654 btrfs_block_group_used(&block_group->item)) *
8657 spin_unlock(&block_group->lock);
8659 spin_unlock(&sinfo->lock);
8664 void btrfs_dec_block_group_ro(struct btrfs_block_group_cache *cache)
8666 struct btrfs_space_info *sinfo = cache->space_info;
8671 spin_lock(&sinfo->lock);
8672 spin_lock(&cache->lock);
8674 num_bytes = cache->key.offset - cache->reserved -
8675 cache->pinned - cache->bytes_super -
8676 btrfs_block_group_used(&cache->item);
8677 sinfo->bytes_readonly -= num_bytes;
8678 list_del_init(&cache->ro_list);
8680 spin_unlock(&cache->lock);
8681 spin_unlock(&sinfo->lock);
8685 * Checks to see if it's even possible to relocate this block group.
8687 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
8688 * ok to go ahead and try.
8690 int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
8692 struct btrfs_block_group_cache *block_group;
8693 struct btrfs_space_info *space_info;
8694 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
8695 struct btrfs_device *device;
8705 debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
8707 block_group = btrfs_lookup_block_group(fs_info, bytenr);
8709 /* odd, couldn't find the block group, leave it alone */
8713 "can't find block group for bytenr %llu",
8718 min_free = btrfs_block_group_used(&block_group->item);
8720 /* no bytes used, we're good */
8724 space_info = block_group->space_info;
8725 spin_lock(&space_info->lock);
8727 full = space_info->full;
8730 * if this is the last block group we have in this space, we can't
8731 * relocate it unless we're able to allocate a new chunk below.
8733 * Otherwise, we need to make sure we have room in the space to handle
8734 * all of the extents from this block group. If we can, we're good
8736 if ((space_info->total_bytes != block_group->key.offset) &&
8737 (btrfs_space_info_used(space_info, false) + min_free <
8738 space_info->total_bytes)) {
8739 spin_unlock(&space_info->lock);
8742 spin_unlock(&space_info->lock);
8745 * ok we don't have enough space, but maybe we have free space on our
8746 * devices to allocate new chunks for relocation, so loop through our
8747 * alloc devices and guess if we have enough space. if this block
8748 * group is going to be restriped, run checks against the target
8749 * profile instead of the current one.
8761 target = get_restripe_target(fs_info, block_group->flags);
8763 index = btrfs_bg_flags_to_raid_index(extended_to_chunk(target));
8766 * this is just a balance, so if we were marked as full
8767 * we know there is no space for a new chunk
8772 "no space to alloc new chunk for block group %llu",
8773 block_group->key.objectid);
8777 index = btrfs_bg_flags_to_raid_index(block_group->flags);
8780 if (index == BTRFS_RAID_RAID10) {
8784 } else if (index == BTRFS_RAID_RAID1) {
8786 } else if (index == BTRFS_RAID_DUP) {
8789 } else if (index == BTRFS_RAID_RAID0) {
8790 dev_min = fs_devices->rw_devices;
8791 min_free = div64_u64(min_free, dev_min);
8794 mutex_lock(&fs_info->chunk_mutex);
8795 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
8799 * check to make sure we can actually find a chunk with enough
8800 * space to fit our block group in.
8802 if (device->total_bytes > device->bytes_used + min_free &&
8803 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
8804 ret = find_free_dev_extent(device, min_free,
8809 if (dev_nr >= dev_min)
8815 if (debug && ret == -1)
8817 "no space to allocate a new chunk for block group %llu",
8818 block_group->key.objectid);
8819 mutex_unlock(&fs_info->chunk_mutex);
8821 btrfs_put_block_group(block_group);
8825 static int find_first_block_group(struct btrfs_fs_info *fs_info,
8826 struct btrfs_path *path,
8827 struct btrfs_key *key)
8829 struct btrfs_root *root = fs_info->extent_root;
8831 struct btrfs_key found_key;
8832 struct extent_buffer *leaf;
8833 struct btrfs_block_group_item bg;
8837 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
8842 slot = path->slots[0];
8843 leaf = path->nodes[0];
8844 if (slot >= btrfs_header_nritems(leaf)) {
8845 ret = btrfs_next_leaf(root, path);
8852 btrfs_item_key_to_cpu(leaf, &found_key, slot);
8854 if (found_key.objectid >= key->objectid &&
8855 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
8856 struct extent_map_tree *em_tree;
8857 struct extent_map *em;
8859 em_tree = &root->fs_info->mapping_tree;
8860 read_lock(&em_tree->lock);
8861 em = lookup_extent_mapping(em_tree, found_key.objectid,
8863 read_unlock(&em_tree->lock);
8866 "logical %llu len %llu found bg but no related chunk",
8867 found_key.objectid, found_key.offset);
8869 } else if (em->start != found_key.objectid ||
8870 em->len != found_key.offset) {
8872 "block group %llu len %llu mismatch with chunk %llu len %llu",
8873 found_key.objectid, found_key.offset,
8874 em->start, em->len);
8877 read_extent_buffer(leaf, &bg,
8878 btrfs_item_ptr_offset(leaf, slot),
8880 flags = btrfs_block_group_flags(&bg) &
8881 BTRFS_BLOCK_GROUP_TYPE_MASK;
8883 if (flags != (em->map_lookup->type &
8884 BTRFS_BLOCK_GROUP_TYPE_MASK)) {
8886 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
8888 found_key.offset, flags,
8889 (BTRFS_BLOCK_GROUP_TYPE_MASK &
8890 em->map_lookup->type));
8896 free_extent_map(em);
8905 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
8907 struct btrfs_block_group_cache *block_group;
8911 struct inode *inode;
8913 block_group = btrfs_lookup_first_block_group(info, last);
8914 while (block_group) {
8915 wait_block_group_cache_done(block_group);
8916 spin_lock(&block_group->lock);
8917 if (block_group->iref)
8919 spin_unlock(&block_group->lock);
8920 block_group = next_block_group(block_group);
8929 inode = block_group->inode;
8930 block_group->iref = 0;
8931 block_group->inode = NULL;
8932 spin_unlock(&block_group->lock);
8933 ASSERT(block_group->io_ctl.inode == NULL);
8935 last = block_group->key.objectid + block_group->key.offset;
8936 btrfs_put_block_group(block_group);
8941 * Must be called only after stopping all workers, since we could have block
8942 * group caching kthreads running, and therefore they could race with us if we
8943 * freed the block groups before stopping them.
8945 int btrfs_free_block_groups(struct btrfs_fs_info *info)
8947 struct btrfs_block_group_cache *block_group;
8948 struct btrfs_space_info *space_info;
8949 struct btrfs_caching_control *caching_ctl;
8952 down_write(&info->commit_root_sem);
8953 while (!list_empty(&info->caching_block_groups)) {
8954 caching_ctl = list_entry(info->caching_block_groups.next,
8955 struct btrfs_caching_control, list);
8956 list_del(&caching_ctl->list);
8957 put_caching_control(caching_ctl);
8959 up_write(&info->commit_root_sem);
8961 spin_lock(&info->unused_bgs_lock);
8962 while (!list_empty(&info->unused_bgs)) {
8963 block_group = list_first_entry(&info->unused_bgs,
8964 struct btrfs_block_group_cache,
8966 list_del_init(&block_group->bg_list);
8967 btrfs_put_block_group(block_group);
8969 spin_unlock(&info->unused_bgs_lock);
8971 spin_lock(&info->block_group_cache_lock);
8972 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
8973 block_group = rb_entry(n, struct btrfs_block_group_cache,
8975 rb_erase(&block_group->cache_node,
8976 &info->block_group_cache_tree);
8977 RB_CLEAR_NODE(&block_group->cache_node);
8978 spin_unlock(&info->block_group_cache_lock);
8980 down_write(&block_group->space_info->groups_sem);
8981 list_del(&block_group->list);
8982 up_write(&block_group->space_info->groups_sem);
8985 * We haven't cached this block group, which means we could
8986 * possibly have excluded extents on this block group.
8988 if (block_group->cached == BTRFS_CACHE_NO ||
8989 block_group->cached == BTRFS_CACHE_ERROR)
8990 free_excluded_extents(block_group);
8992 btrfs_remove_free_space_cache(block_group);
8993 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
8994 ASSERT(list_empty(&block_group->dirty_list));
8995 ASSERT(list_empty(&block_group->io_list));
8996 ASSERT(list_empty(&block_group->bg_list));
8997 ASSERT(atomic_read(&block_group->count) == 1);
8998 btrfs_put_block_group(block_group);
9000 spin_lock(&info->block_group_cache_lock);
9002 spin_unlock(&info->block_group_cache_lock);
9004 /* now that all the block groups are freed, go through and
9005 * free all the space_info structs. This is only called during
9006 * the final stages of unmount, and so we know nobody is
9007 * using them. We call synchronize_rcu() once before we start,
9008 * just to be on the safe side.
9012 release_global_block_rsv(info);
9014 while (!list_empty(&info->space_info)) {
9017 space_info = list_entry(info->space_info.next,
9018 struct btrfs_space_info,
9022 * Do not hide this behind enospc_debug, this is actually
9023 * important and indicates a real bug if this happens.
9025 if (WARN_ON(space_info->bytes_pinned > 0 ||
9026 space_info->bytes_reserved > 0 ||
9027 space_info->bytes_may_use > 0))
9028 btrfs_dump_space_info(info, space_info, 0, 0);
9029 list_del(&space_info->list);
9030 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
9031 struct kobject *kobj;
9032 kobj = space_info->block_group_kobjs[i];
9033 space_info->block_group_kobjs[i] = NULL;
9039 kobject_del(&space_info->kobj);
9040 kobject_put(&space_info->kobj);
9045 /* link_block_group will queue up kobjects to add when we're reclaim-safe */
9046 void btrfs_add_raid_kobjects(struct btrfs_fs_info *fs_info)
9048 struct btrfs_space_info *space_info;
9049 struct raid_kobject *rkobj;
9053 spin_lock(&fs_info->pending_raid_kobjs_lock);
9054 list_splice_init(&fs_info->pending_raid_kobjs, &list);
9055 spin_unlock(&fs_info->pending_raid_kobjs_lock);
9057 list_for_each_entry(rkobj, &list, list) {
9058 space_info = btrfs_find_space_info(fs_info, rkobj->flags);
9060 ret = kobject_add(&rkobj->kobj, &space_info->kobj,
9061 "%s", btrfs_bg_type_to_raid_name(rkobj->flags));
9063 kobject_put(&rkobj->kobj);
9069 "failed to add kobject for block cache, ignoring");
9072 static void link_block_group(struct btrfs_block_group_cache *cache)
9074 struct btrfs_space_info *space_info = cache->space_info;
9075 struct btrfs_fs_info *fs_info = cache->fs_info;
9076 int index = btrfs_bg_flags_to_raid_index(cache->flags);
9079 down_write(&space_info->groups_sem);
9080 if (list_empty(&space_info->block_groups[index]))
9082 list_add_tail(&cache->list, &space_info->block_groups[index]);
9083 up_write(&space_info->groups_sem);
9086 struct raid_kobject *rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
9088 btrfs_warn(cache->fs_info,
9089 "couldn't alloc memory for raid level kobject");
9092 rkobj->flags = cache->flags;
9093 kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
9095 spin_lock(&fs_info->pending_raid_kobjs_lock);
9096 list_add_tail(&rkobj->list, &fs_info->pending_raid_kobjs);
9097 spin_unlock(&fs_info->pending_raid_kobjs_lock);
9098 space_info->block_group_kobjs[index] = &rkobj->kobj;
9102 static struct btrfs_block_group_cache *
9103 btrfs_create_block_group_cache(struct btrfs_fs_info *fs_info,
9104 u64 start, u64 size)
9106 struct btrfs_block_group_cache *cache;
9108 cache = kzalloc(sizeof(*cache), GFP_NOFS);
9112 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
9114 if (!cache->free_space_ctl) {
9119 cache->key.objectid = start;
9120 cache->key.offset = size;
9121 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9123 cache->fs_info = fs_info;
9124 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
9125 set_free_space_tree_thresholds(cache);
9127 atomic_set(&cache->count, 1);
9128 spin_lock_init(&cache->lock);
9129 init_rwsem(&cache->data_rwsem);
9130 INIT_LIST_HEAD(&cache->list);
9131 INIT_LIST_HEAD(&cache->cluster_list);
9132 INIT_LIST_HEAD(&cache->bg_list);
9133 INIT_LIST_HEAD(&cache->ro_list);
9134 INIT_LIST_HEAD(&cache->dirty_list);
9135 INIT_LIST_HEAD(&cache->io_list);
9136 btrfs_init_free_space_ctl(cache);
9137 atomic_set(&cache->trimming, 0);
9138 mutex_init(&cache->free_space_lock);
9139 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
9146 * Iterate all chunks and verify that each of them has the corresponding block
9149 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
9151 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
9152 struct extent_map *em;
9153 struct btrfs_block_group_cache *bg;
9158 read_lock(&map_tree->lock);
9160 * lookup_extent_mapping will return the first extent map
9161 * intersecting the range, so setting @len to 1 is enough to
9162 * get the first chunk.
9164 em = lookup_extent_mapping(map_tree, start, 1);
9165 read_unlock(&map_tree->lock);
9169 bg = btrfs_lookup_block_group(fs_info, em->start);
9172 "chunk start=%llu len=%llu doesn't have corresponding block group",
9173 em->start, em->len);
9175 free_extent_map(em);
9178 if (bg->key.objectid != em->start ||
9179 bg->key.offset != em->len ||
9180 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
9181 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
9183 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
9185 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
9186 bg->key.objectid, bg->key.offset,
9187 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
9189 free_extent_map(em);
9190 btrfs_put_block_group(bg);
9193 start = em->start + em->len;
9194 free_extent_map(em);
9195 btrfs_put_block_group(bg);
9200 int btrfs_read_block_groups(struct btrfs_fs_info *info)
9202 struct btrfs_path *path;
9204 struct btrfs_block_group_cache *cache;
9205 struct btrfs_space_info *space_info;
9206 struct btrfs_key key;
9207 struct btrfs_key found_key;
9208 struct extent_buffer *leaf;
9214 feature = btrfs_super_incompat_flags(info->super_copy);
9215 mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
9219 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9220 path = btrfs_alloc_path();
9223 path->reada = READA_FORWARD;
9225 cache_gen = btrfs_super_cache_generation(info->super_copy);
9226 if (btrfs_test_opt(info, SPACE_CACHE) &&
9227 btrfs_super_generation(info->super_copy) != cache_gen)
9229 if (btrfs_test_opt(info, CLEAR_CACHE))
9233 ret = find_first_block_group(info, path, &key);
9239 leaf = path->nodes[0];
9240 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
9242 cache = btrfs_create_block_group_cache(info, found_key.objectid,
9251 * When we mount with old space cache, we need to
9252 * set BTRFS_DC_CLEAR and set dirty flag.
9254 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
9255 * truncate the old free space cache inode and
9257 * b) Setting 'dirty flag' makes sure that we flush
9258 * the new space cache info onto disk.
9260 if (btrfs_test_opt(info, SPACE_CACHE))
9261 cache->disk_cache_state = BTRFS_DC_CLEAR;
9264 read_extent_buffer(leaf, &cache->item,
9265 btrfs_item_ptr_offset(leaf, path->slots[0]),
9266 sizeof(cache->item));
9267 cache->flags = btrfs_block_group_flags(&cache->item);
9269 ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
9270 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
9272 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
9273 cache->key.objectid);
9278 key.objectid = found_key.objectid + found_key.offset;
9279 btrfs_release_path(path);
9282 * We need to exclude the super stripes now so that the space
9283 * info has super bytes accounted for, otherwise we'll think
9284 * we have more space than we actually do.
9286 ret = exclude_super_stripes(cache);
9289 * We may have excluded something, so call this just in
9292 free_excluded_extents(cache);
9293 btrfs_put_block_group(cache);
9298 * check for two cases, either we are full, and therefore
9299 * don't need to bother with the caching work since we won't
9300 * find any space, or we are empty, and we can just add all
9301 * the space in and be done with it. This saves us _a_lot_ of
9302 * time, particularly in the full case.
9304 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
9305 cache->last_byte_to_unpin = (u64)-1;
9306 cache->cached = BTRFS_CACHE_FINISHED;
9307 free_excluded_extents(cache);
9308 } else if (btrfs_block_group_used(&cache->item) == 0) {
9309 cache->last_byte_to_unpin = (u64)-1;
9310 cache->cached = BTRFS_CACHE_FINISHED;
9311 add_new_free_space(cache, found_key.objectid,
9312 found_key.objectid +
9314 free_excluded_extents(cache);
9317 ret = btrfs_add_block_group_cache(info, cache);
9319 btrfs_remove_free_space_cache(cache);
9320 btrfs_put_block_group(cache);
9324 trace_btrfs_add_block_group(info, cache, 0);
9325 btrfs_update_space_info(info, cache->flags, found_key.offset,
9326 btrfs_block_group_used(&cache->item),
9327 cache->bytes_super, &space_info);
9329 cache->space_info = space_info;
9331 link_block_group(cache);
9333 set_avail_alloc_bits(info, cache->flags);
9334 if (btrfs_chunk_readonly(info, cache->key.objectid)) {
9335 inc_block_group_ro(cache, 1);
9336 } else if (btrfs_block_group_used(&cache->item) == 0) {
9337 ASSERT(list_empty(&cache->bg_list));
9338 btrfs_mark_bg_unused(cache);
9342 list_for_each_entry_rcu(space_info, &info->space_info, list) {
9343 if (!(get_alloc_profile(info, space_info->flags) &
9344 (BTRFS_BLOCK_GROUP_RAID10 |
9345 BTRFS_BLOCK_GROUP_RAID1_MASK |
9346 BTRFS_BLOCK_GROUP_RAID56_MASK |
9347 BTRFS_BLOCK_GROUP_DUP)))
9350 * avoid allocating from un-mirrored block group if there are
9351 * mirrored block groups.
9353 list_for_each_entry(cache,
9354 &space_info->block_groups[BTRFS_RAID_RAID0],
9356 inc_block_group_ro(cache, 1);
9357 list_for_each_entry(cache,
9358 &space_info->block_groups[BTRFS_RAID_SINGLE],
9360 inc_block_group_ro(cache, 1);
9363 btrfs_add_raid_kobjects(info);
9364 init_global_block_rsv(info);
9365 ret = check_chunk_block_group_mappings(info);
9367 btrfs_free_path(path);
9371 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
9373 struct btrfs_fs_info *fs_info = trans->fs_info;
9374 struct btrfs_block_group_cache *block_group;
9375 struct btrfs_root *extent_root = fs_info->extent_root;
9376 struct btrfs_block_group_item item;
9377 struct btrfs_key key;
9380 if (!trans->can_flush_pending_bgs)
9383 while (!list_empty(&trans->new_bgs)) {
9384 block_group = list_first_entry(&trans->new_bgs,
9385 struct btrfs_block_group_cache,
9390 spin_lock(&block_group->lock);
9391 memcpy(&item, &block_group->item, sizeof(item));
9392 memcpy(&key, &block_group->key, sizeof(key));
9393 spin_unlock(&block_group->lock);
9395 ret = btrfs_insert_item(trans, extent_root, &key, &item,
9398 btrfs_abort_transaction(trans, ret);
9399 ret = btrfs_finish_chunk_alloc(trans, key.objectid, key.offset);
9401 btrfs_abort_transaction(trans, ret);
9402 add_block_group_free_space(trans, block_group);
9403 /* already aborted the transaction if it failed. */
9405 btrfs_delayed_refs_rsv_release(fs_info, 1);
9406 list_del_init(&block_group->bg_list);
9408 btrfs_trans_release_chunk_metadata(trans);
9411 int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
9412 u64 type, u64 chunk_offset, u64 size)
9414 struct btrfs_fs_info *fs_info = trans->fs_info;
9415 struct btrfs_block_group_cache *cache;
9418 btrfs_set_log_full_commit(trans);
9420 cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
9424 btrfs_set_block_group_used(&cache->item, bytes_used);
9425 btrfs_set_block_group_chunk_objectid(&cache->item,
9426 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
9427 btrfs_set_block_group_flags(&cache->item, type);
9429 cache->flags = type;
9430 cache->last_byte_to_unpin = (u64)-1;
9431 cache->cached = BTRFS_CACHE_FINISHED;
9432 cache->needs_free_space = 1;
9433 ret = exclude_super_stripes(cache);
9436 * We may have excluded something, so call this just in
9439 free_excluded_extents(cache);
9440 btrfs_put_block_group(cache);
9444 add_new_free_space(cache, chunk_offset, chunk_offset + size);
9446 free_excluded_extents(cache);
9448 #ifdef CONFIG_BTRFS_DEBUG
9449 if (btrfs_should_fragment_free_space(cache)) {
9450 u64 new_bytes_used = size - bytes_used;
9452 bytes_used += new_bytes_used >> 1;
9453 fragment_free_space(cache);
9457 * Ensure the corresponding space_info object is created and
9458 * assigned to our block group. We want our bg to be added to the rbtree
9459 * with its ->space_info set.
9461 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
9462 ASSERT(cache->space_info);
9464 ret = btrfs_add_block_group_cache(fs_info, cache);
9466 btrfs_remove_free_space_cache(cache);
9467 btrfs_put_block_group(cache);
9472 * Now that our block group has its ->space_info set and is inserted in
9473 * the rbtree, update the space info's counters.
9475 trace_btrfs_add_block_group(fs_info, cache, 1);
9476 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
9477 cache->bytes_super, &cache->space_info);
9478 update_global_block_rsv(fs_info);
9480 link_block_group(cache);
9482 list_add_tail(&cache->bg_list, &trans->new_bgs);
9483 trans->delayed_ref_updates++;
9484 btrfs_update_delayed_refs_rsv(trans);
9486 set_avail_alloc_bits(fs_info, type);
9490 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
9492 u64 extra_flags = chunk_to_extended(flags) &
9493 BTRFS_EXTENDED_PROFILE_MASK;
9495 write_seqlock(&fs_info->profiles_lock);
9496 if (flags & BTRFS_BLOCK_GROUP_DATA)
9497 fs_info->avail_data_alloc_bits &= ~extra_flags;
9498 if (flags & BTRFS_BLOCK_GROUP_METADATA)
9499 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
9500 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
9501 fs_info->avail_system_alloc_bits &= ~extra_flags;
9502 write_sequnlock(&fs_info->profiles_lock);
9506 * Clear incompat bits for the following feature(s):
9508 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
9509 * in the whole filesystem
9511 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
9513 if (flags & BTRFS_BLOCK_GROUP_RAID56_MASK) {
9514 struct list_head *head = &fs_info->space_info;
9515 struct btrfs_space_info *sinfo;
9517 list_for_each_entry_rcu(sinfo, head, list) {
9520 down_read(&sinfo->groups_sem);
9521 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
9523 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
9525 up_read(&sinfo->groups_sem);
9530 btrfs_clear_fs_incompat(fs_info, RAID56);
9534 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
9535 u64 group_start, struct extent_map *em)
9537 struct btrfs_fs_info *fs_info = trans->fs_info;
9538 struct btrfs_root *root = fs_info->extent_root;
9539 struct btrfs_path *path;
9540 struct btrfs_block_group_cache *block_group;
9541 struct btrfs_free_cluster *cluster;
9542 struct btrfs_root *tree_root = fs_info->tree_root;
9543 struct btrfs_key key;
9544 struct inode *inode;
9545 struct kobject *kobj = NULL;
9549 struct btrfs_caching_control *caching_ctl = NULL;
9551 bool remove_rsv = false;
9553 block_group = btrfs_lookup_block_group(fs_info, group_start);
9554 BUG_ON(!block_group);
9555 BUG_ON(!block_group->ro);
9557 trace_btrfs_remove_block_group(block_group);
9559 * Free the reserved super bytes from this block group before
9562 free_excluded_extents(block_group);
9563 btrfs_free_ref_tree_range(fs_info, block_group->key.objectid,
9564 block_group->key.offset);
9566 memcpy(&key, &block_group->key, sizeof(key));
9567 index = btrfs_bg_flags_to_raid_index(block_group->flags);
9568 factor = btrfs_bg_type_to_factor(block_group->flags);
9570 /* make sure this block group isn't part of an allocation cluster */
9571 cluster = &fs_info->data_alloc_cluster;
9572 spin_lock(&cluster->refill_lock);
9573 btrfs_return_cluster_to_free_space(block_group, cluster);
9574 spin_unlock(&cluster->refill_lock);
9577 * make sure this block group isn't part of a metadata
9578 * allocation cluster
9580 cluster = &fs_info->meta_alloc_cluster;
9581 spin_lock(&cluster->refill_lock);
9582 btrfs_return_cluster_to_free_space(block_group, cluster);
9583 spin_unlock(&cluster->refill_lock);
9585 path = btrfs_alloc_path();
9592 * get the inode first so any iput calls done for the io_list
9593 * aren't the final iput (no unlinks allowed now)
9595 inode = lookup_free_space_inode(block_group, path);
9597 mutex_lock(&trans->transaction->cache_write_mutex);
9599 * Make sure our free space cache IO is done before removing the
9602 spin_lock(&trans->transaction->dirty_bgs_lock);
9603 if (!list_empty(&block_group->io_list)) {
9604 list_del_init(&block_group->io_list);
9606 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
9608 spin_unlock(&trans->transaction->dirty_bgs_lock);
9609 btrfs_wait_cache_io(trans, block_group, path);
9610 btrfs_put_block_group(block_group);
9611 spin_lock(&trans->transaction->dirty_bgs_lock);
9614 if (!list_empty(&block_group->dirty_list)) {
9615 list_del_init(&block_group->dirty_list);
9617 btrfs_put_block_group(block_group);
9619 spin_unlock(&trans->transaction->dirty_bgs_lock);
9620 mutex_unlock(&trans->transaction->cache_write_mutex);
9622 if (!IS_ERR(inode)) {
9623 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
9625 btrfs_add_delayed_iput(inode);
9629 /* One for the block groups ref */
9630 spin_lock(&block_group->lock);
9631 if (block_group->iref) {
9632 block_group->iref = 0;
9633 block_group->inode = NULL;
9634 spin_unlock(&block_group->lock);
9637 spin_unlock(&block_group->lock);
9639 /* One for our lookup ref */
9640 btrfs_add_delayed_iput(inode);
9643 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
9644 key.offset = block_group->key.objectid;
9647 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
9651 btrfs_release_path(path);
9653 ret = btrfs_del_item(trans, tree_root, path);
9656 btrfs_release_path(path);
9659 spin_lock(&fs_info->block_group_cache_lock);
9660 rb_erase(&block_group->cache_node,
9661 &fs_info->block_group_cache_tree);
9662 RB_CLEAR_NODE(&block_group->cache_node);
9664 if (fs_info->first_logical_byte == block_group->key.objectid)
9665 fs_info->first_logical_byte = (u64)-1;
9666 spin_unlock(&fs_info->block_group_cache_lock);
9668 down_write(&block_group->space_info->groups_sem);
9670 * we must use list_del_init so people can check to see if they
9671 * are still on the list after taking the semaphore
9673 list_del_init(&block_group->list);
9674 if (list_empty(&block_group->space_info->block_groups[index])) {
9675 kobj = block_group->space_info->block_group_kobjs[index];
9676 block_group->space_info->block_group_kobjs[index] = NULL;
9677 clear_avail_alloc_bits(fs_info, block_group->flags);
9679 up_write(&block_group->space_info->groups_sem);
9680 clear_incompat_bg_bits(fs_info, block_group->flags);
9686 if (block_group->has_caching_ctl)
9687 caching_ctl = get_caching_control(block_group);
9688 if (block_group->cached == BTRFS_CACHE_STARTED)
9689 wait_block_group_cache_done(block_group);
9690 if (block_group->has_caching_ctl) {
9691 down_write(&fs_info->commit_root_sem);
9693 struct btrfs_caching_control *ctl;
9695 list_for_each_entry(ctl,
9696 &fs_info->caching_block_groups, list)
9697 if (ctl->block_group == block_group) {
9699 refcount_inc(&caching_ctl->count);
9704 list_del_init(&caching_ctl->list);
9705 up_write(&fs_info->commit_root_sem);
9707 /* Once for the caching bgs list and once for us. */
9708 put_caching_control(caching_ctl);
9709 put_caching_control(caching_ctl);
9713 spin_lock(&trans->transaction->dirty_bgs_lock);
9714 WARN_ON(!list_empty(&block_group->dirty_list));
9715 WARN_ON(!list_empty(&block_group->io_list));
9716 spin_unlock(&trans->transaction->dirty_bgs_lock);
9718 btrfs_remove_free_space_cache(block_group);
9720 spin_lock(&block_group->space_info->lock);
9721 list_del_init(&block_group->ro_list);
9723 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
9724 WARN_ON(block_group->space_info->total_bytes
9725 < block_group->key.offset);
9726 WARN_ON(block_group->space_info->bytes_readonly
9727 < block_group->key.offset);
9728 WARN_ON(block_group->space_info->disk_total
9729 < block_group->key.offset * factor);
9731 block_group->space_info->total_bytes -= block_group->key.offset;
9732 block_group->space_info->bytes_readonly -= block_group->key.offset;
9733 block_group->space_info->disk_total -= block_group->key.offset * factor;
9735 spin_unlock(&block_group->space_info->lock);
9737 memcpy(&key, &block_group->key, sizeof(key));
9739 mutex_lock(&fs_info->chunk_mutex);
9740 spin_lock(&block_group->lock);
9741 block_group->removed = 1;
9743 * At this point trimming can't start on this block group, because we
9744 * removed the block group from the tree fs_info->block_group_cache_tree
9745 * so no one can't find it anymore and even if someone already got this
9746 * block group before we removed it from the rbtree, they have already
9747 * incremented block_group->trimming - if they didn't, they won't find
9748 * any free space entries because we already removed them all when we
9749 * called btrfs_remove_free_space_cache().
9751 * And we must not remove the extent map from the fs_info->mapping_tree
9752 * to prevent the same logical address range and physical device space
9753 * ranges from being reused for a new block group. This is because our
9754 * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
9755 * completely transactionless, so while it is trimming a range the
9756 * currently running transaction might finish and a new one start,
9757 * allowing for new block groups to be created that can reuse the same
9758 * physical device locations unless we take this special care.
9760 * There may also be an implicit trim operation if the file system
9761 * is mounted with -odiscard. The same protections must remain
9762 * in place until the extents have been discarded completely when
9763 * the transaction commit has completed.
9765 remove_em = (atomic_read(&block_group->trimming) == 0);
9766 spin_unlock(&block_group->lock);
9768 mutex_unlock(&fs_info->chunk_mutex);
9770 ret = remove_block_group_free_space(trans, block_group);
9774 btrfs_put_block_group(block_group);
9775 btrfs_put_block_group(block_group);
9777 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
9783 ret = btrfs_del_item(trans, root, path);
9788 struct extent_map_tree *em_tree;
9790 em_tree = &fs_info->mapping_tree;
9791 write_lock(&em_tree->lock);
9792 remove_extent_mapping(em_tree, em);
9793 write_unlock(&em_tree->lock);
9794 /* once for the tree */
9795 free_extent_map(em);
9799 btrfs_delayed_refs_rsv_release(fs_info, 1);
9800 btrfs_free_path(path);
9804 struct btrfs_trans_handle *
9805 btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
9806 const u64 chunk_offset)
9808 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
9809 struct extent_map *em;
9810 struct map_lookup *map;
9811 unsigned int num_items;
9813 read_lock(&em_tree->lock);
9814 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
9815 read_unlock(&em_tree->lock);
9816 ASSERT(em && em->start == chunk_offset);
9819 * We need to reserve 3 + N units from the metadata space info in order
9820 * to remove a block group (done at btrfs_remove_chunk() and at
9821 * btrfs_remove_block_group()), which are used for:
9823 * 1 unit for adding the free space inode's orphan (located in the tree
9825 * 1 unit for deleting the block group item (located in the extent
9827 * 1 unit for deleting the free space item (located in tree of tree
9829 * N units for deleting N device extent items corresponding to each
9830 * stripe (located in the device tree).
9832 * In order to remove a block group we also need to reserve units in the
9833 * system space info in order to update the chunk tree (update one or
9834 * more device items and remove one chunk item), but this is done at
9835 * btrfs_remove_chunk() through a call to check_system_chunk().
9837 map = em->map_lookup;
9838 num_items = 3 + map->num_stripes;
9839 free_extent_map(em);
9841 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
9846 * Process the unused_bgs list and remove any that don't have any allocated
9847 * space inside of them.
9849 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
9851 struct btrfs_block_group_cache *block_group;
9852 struct btrfs_space_info *space_info;
9853 struct btrfs_trans_handle *trans;
9856 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
9859 spin_lock(&fs_info->unused_bgs_lock);
9860 while (!list_empty(&fs_info->unused_bgs)) {
9864 block_group = list_first_entry(&fs_info->unused_bgs,
9865 struct btrfs_block_group_cache,
9867 list_del_init(&block_group->bg_list);
9869 space_info = block_group->space_info;
9871 if (ret || btrfs_mixed_space_info(space_info)) {
9872 btrfs_put_block_group(block_group);
9875 spin_unlock(&fs_info->unused_bgs_lock);
9877 mutex_lock(&fs_info->delete_unused_bgs_mutex);
9879 /* Don't want to race with allocators so take the groups_sem */
9880 down_write(&space_info->groups_sem);
9881 spin_lock(&block_group->lock);
9882 if (block_group->reserved || block_group->pinned ||
9883 btrfs_block_group_used(&block_group->item) ||
9885 list_is_singular(&block_group->list)) {
9887 * We want to bail if we made new allocations or have
9888 * outstanding allocations in this block group. We do
9889 * the ro check in case balance is currently acting on
9892 trace_btrfs_skip_unused_block_group(block_group);
9893 spin_unlock(&block_group->lock);
9894 up_write(&space_info->groups_sem);
9897 spin_unlock(&block_group->lock);
9899 /* We don't want to force the issue, only flip if it's ok. */
9900 ret = inc_block_group_ro(block_group, 0);
9901 up_write(&space_info->groups_sem);
9908 * Want to do this before we do anything else so we can recover
9909 * properly if we fail to join the transaction.
9911 trans = btrfs_start_trans_remove_block_group(fs_info,
9912 block_group->key.objectid);
9913 if (IS_ERR(trans)) {
9914 btrfs_dec_block_group_ro(block_group);
9915 ret = PTR_ERR(trans);
9920 * We could have pending pinned extents for this block group,
9921 * just delete them, we don't care about them anymore.
9923 start = block_group->key.objectid;
9924 end = start + block_group->key.offset - 1;
9926 * Hold the unused_bg_unpin_mutex lock to avoid racing with
9927 * btrfs_finish_extent_commit(). If we are at transaction N,
9928 * another task might be running finish_extent_commit() for the
9929 * previous transaction N - 1, and have seen a range belonging
9930 * to the block group in freed_extents[] before we were able to
9931 * clear the whole block group range from freed_extents[]. This
9932 * means that task can lookup for the block group after we
9933 * unpinned it from freed_extents[] and removed it, leading to
9934 * a BUG_ON() at btrfs_unpin_extent_range().
9936 mutex_lock(&fs_info->unused_bg_unpin_mutex);
9937 ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
9940 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
9941 btrfs_dec_block_group_ro(block_group);
9944 ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
9947 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
9948 btrfs_dec_block_group_ro(block_group);
9951 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
9953 /* Reset pinned so btrfs_put_block_group doesn't complain */
9954 spin_lock(&space_info->lock);
9955 spin_lock(&block_group->lock);
9957 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
9958 -block_group->pinned);
9959 space_info->bytes_readonly += block_group->pinned;
9960 percpu_counter_add_batch(&space_info->total_bytes_pinned,
9961 -block_group->pinned,
9962 BTRFS_TOTAL_BYTES_PINNED_BATCH);
9963 block_group->pinned = 0;
9965 spin_unlock(&block_group->lock);
9966 spin_unlock(&space_info->lock);
9968 /* DISCARD can flip during remount */
9969 trimming = btrfs_test_opt(fs_info, DISCARD);
9971 /* Implicit trim during transaction commit. */
9973 btrfs_get_block_group_trimming(block_group);
9976 * Btrfs_remove_chunk will abort the transaction if things go
9979 ret = btrfs_remove_chunk(trans, block_group->key.objectid);
9983 btrfs_put_block_group_trimming(block_group);
9988 * If we're not mounted with -odiscard, we can just forget
9989 * about this block group. Otherwise we'll need to wait
9990 * until transaction commit to do the actual discard.
9993 spin_lock(&fs_info->unused_bgs_lock);
9995 * A concurrent scrub might have added us to the list
9996 * fs_info->unused_bgs, so use a list_move operation
9997 * to add the block group to the deleted_bgs list.
9999 list_move(&block_group->bg_list,
10000 &trans->transaction->deleted_bgs);
10001 spin_unlock(&fs_info->unused_bgs_lock);
10002 btrfs_get_block_group(block_group);
10005 btrfs_end_transaction(trans);
10007 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
10008 btrfs_put_block_group(block_group);
10009 spin_lock(&fs_info->unused_bgs_lock);
10011 spin_unlock(&fs_info->unused_bgs_lock);
10014 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
10015 u64 start, u64 end)
10017 return unpin_extent_range(fs_info, start, end, false);
10021 * It used to be that old block groups would be left around forever.
10022 * Iterating over them would be enough to trim unused space. Since we
10023 * now automatically remove them, we also need to iterate over unallocated
10026 * We don't want a transaction for this since the discard may take a
10027 * substantial amount of time. We don't require that a transaction be
10028 * running, but we do need to take a running transaction into account
10029 * to ensure that we're not discarding chunks that were released or
10030 * allocated in the current transaction.
10032 * Holding the chunks lock will prevent other threads from allocating
10033 * or releasing chunks, but it won't prevent a running transaction
10034 * from committing and releasing the memory that the pending chunks
10035 * list head uses. For that, we need to take a reference to the
10036 * transaction and hold the commit root sem. We only need to hold
10037 * it while performing the free space search since we have already
10038 * held back allocations.
10040 static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
10042 u64 start = SZ_1M, len = 0, end = 0;
10047 /* Discard not supported = nothing to do. */
10048 if (!blk_queue_discard(bdev_get_queue(device->bdev)))
10051 /* Not writable = nothing to do. */
10052 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
10055 /* No free space = nothing to do. */
10056 if (device->total_bytes <= device->bytes_used)
10062 struct btrfs_fs_info *fs_info = device->fs_info;
10065 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
10069 find_first_clear_extent_bit(&device->alloc_state, start,
10071 CHUNK_TRIMMED | CHUNK_ALLOCATED);
10073 /* Ensure we skip the reserved area in the first 1M */
10074 start = max_t(u64, start, SZ_1M);
10077 * If find_first_clear_extent_bit find a range that spans the
10078 * end of the device it will set end to -1, in this case it's up
10079 * to the caller to trim the value to the size of the device.
10081 end = min(end, device->total_bytes - 1);
10083 len = end - start + 1;
10085 /* We didn't find any extents */
10087 mutex_unlock(&fs_info->chunk_mutex);
10092 ret = btrfs_issue_discard(device->bdev, start, len,
10095 set_extent_bits(&device->alloc_state, start,
10098 mutex_unlock(&fs_info->chunk_mutex);
10106 if (fatal_signal_pending(current)) {
10107 ret = -ERESTARTSYS;
10118 * Trim the whole filesystem by:
10119 * 1) trimming the free space in each block group
10120 * 2) trimming the unallocated space on each device
10122 * This will also continue trimming even if a block group or device encounters
10123 * an error. The return value will be the last error, or 0 if nothing bad
10126 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
10128 struct btrfs_block_group_cache *cache = NULL;
10129 struct btrfs_device *device;
10130 struct list_head *devices;
10136 u64 dev_failed = 0;
10141 cache = btrfs_lookup_first_block_group(fs_info, range->start);
10142 for (; cache; cache = next_block_group(cache)) {
10143 if (cache->key.objectid >= (range->start + range->len)) {
10144 btrfs_put_block_group(cache);
10148 start = max(range->start, cache->key.objectid);
10149 end = min(range->start + range->len,
10150 cache->key.objectid + cache->key.offset);
10152 if (end - start >= range->minlen) {
10153 if (!block_group_cache_done(cache)) {
10154 ret = cache_block_group(cache, 0);
10160 ret = wait_block_group_cache_done(cache);
10167 ret = btrfs_trim_block_group(cache,
10173 trimmed += group_trimmed;
10183 btrfs_warn(fs_info,
10184 "failed to trim %llu block group(s), last error %d",
10185 bg_failed, bg_ret);
10186 mutex_lock(&fs_info->fs_devices->device_list_mutex);
10187 devices = &fs_info->fs_devices->devices;
10188 list_for_each_entry(device, devices, dev_list) {
10189 ret = btrfs_trim_free_extents(device, &group_trimmed);
10196 trimmed += group_trimmed;
10198 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
10201 btrfs_warn(fs_info,
10202 "failed to trim %llu device(s), last error %d",
10203 dev_failed, dev_ret);
10204 range->len = trimmed;
10211 * btrfs_{start,end}_write_no_snapshotting() are similar to
10212 * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
10213 * data into the page cache through nocow before the subvolume is snapshoted,
10214 * but flush the data into disk after the snapshot creation, or to prevent
10215 * operations while snapshotting is ongoing and that cause the snapshot to be
10216 * inconsistent (writes followed by expanding truncates for example).
10218 void btrfs_end_write_no_snapshotting(struct btrfs_root *root)
10220 percpu_counter_dec(&root->subv_writers->counter);
10221 cond_wake_up(&root->subv_writers->wait);
10224 int btrfs_start_write_no_snapshotting(struct btrfs_root *root)
10226 if (atomic_read(&root->will_be_snapshotted))
10229 percpu_counter_inc(&root->subv_writers->counter);
10231 * Make sure counter is updated before we check for snapshot creation.
10234 if (atomic_read(&root->will_be_snapshotted)) {
10235 btrfs_end_write_no_snapshotting(root);
10241 void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
10246 ret = btrfs_start_write_no_snapshotting(root);
10249 wait_var_event(&root->will_be_snapshotted,
10250 !atomic_read(&root->will_be_snapshotted));
10254 void btrfs_mark_bg_unused(struct btrfs_block_group_cache *bg)
10256 struct btrfs_fs_info *fs_info = bg->fs_info;
10258 spin_lock(&fs_info->unused_bgs_lock);
10259 if (list_empty(&bg->bg_list)) {
10260 btrfs_get_block_group(bg);
10261 trace_btrfs_add_unused_block_group(bg);
10262 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
10264 spin_unlock(&fs_info->unused_bgs_lock);