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"
32 #undef SCRAMBLE_DELAYED_REFS
35 * control flags for do_chunk_alloc's force field
36 * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
37 * if we really need one.
39 * CHUNK_ALLOC_LIMITED means to only try and allocate one
40 * if we have very few chunks already allocated. This is
41 * used as part of the clustering code to help make sure
42 * we have a good pool of storage to cluster in, without
43 * filling the FS with empty chunks
45 * CHUNK_ALLOC_FORCE means it must try to allocate one
49 CHUNK_ALLOC_NO_FORCE = 0,
50 CHUNK_ALLOC_LIMITED = 1,
51 CHUNK_ALLOC_FORCE = 2,
55 * Declare a helper function to detect underflow of various space info members
57 #define DECLARE_SPACE_INFO_UPDATE(name) \
58 static inline void update_##name(struct btrfs_space_info *sinfo, \
61 if (bytes < 0 && sinfo->name < -bytes) { \
66 sinfo->name += bytes; \
69 DECLARE_SPACE_INFO_UPDATE(bytes_may_use);
70 DECLARE_SPACE_INFO_UPDATE(bytes_pinned);
72 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
73 struct btrfs_delayed_ref_node *node, u64 parent,
74 u64 root_objectid, u64 owner_objectid,
75 u64 owner_offset, int refs_to_drop,
76 struct btrfs_delayed_extent_op *extra_op);
77 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
78 struct extent_buffer *leaf,
79 struct btrfs_extent_item *ei);
80 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
81 u64 parent, u64 root_objectid,
82 u64 flags, u64 owner, u64 offset,
83 struct btrfs_key *ins, int ref_mod);
84 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
85 struct btrfs_delayed_ref_node *node,
86 struct btrfs_delayed_extent_op *extent_op);
87 static int do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
89 static int find_next_key(struct btrfs_path *path, int level,
90 struct btrfs_key *key);
91 static void dump_space_info(struct btrfs_fs_info *fs_info,
92 struct btrfs_space_info *info, u64 bytes,
93 int dump_block_groups);
94 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
96 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
97 struct btrfs_space_info *space_info,
99 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
100 struct btrfs_space_info *space_info,
104 block_group_cache_done(struct btrfs_block_group_cache *cache)
107 return cache->cached == BTRFS_CACHE_FINISHED ||
108 cache->cached == BTRFS_CACHE_ERROR;
111 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
113 return (cache->flags & bits) == bits;
116 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
118 atomic_inc(&cache->count);
121 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
123 if (atomic_dec_and_test(&cache->count)) {
124 WARN_ON(cache->pinned > 0);
125 WARN_ON(cache->reserved > 0);
128 * If not empty, someone is still holding mutex of
129 * full_stripe_lock, which can only be released by caller.
130 * And it will definitely cause use-after-free when caller
131 * tries to release full stripe lock.
133 * No better way to resolve, but only to warn.
135 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
136 kfree(cache->free_space_ctl);
142 * this adds the block group to the fs_info rb tree for the block group
145 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
146 struct btrfs_block_group_cache *block_group)
149 struct rb_node *parent = NULL;
150 struct btrfs_block_group_cache *cache;
152 spin_lock(&info->block_group_cache_lock);
153 p = &info->block_group_cache_tree.rb_node;
157 cache = rb_entry(parent, struct btrfs_block_group_cache,
159 if (block_group->key.objectid < cache->key.objectid) {
161 } else if (block_group->key.objectid > cache->key.objectid) {
164 spin_unlock(&info->block_group_cache_lock);
169 rb_link_node(&block_group->cache_node, parent, p);
170 rb_insert_color(&block_group->cache_node,
171 &info->block_group_cache_tree);
173 if (info->first_logical_byte > block_group->key.objectid)
174 info->first_logical_byte = block_group->key.objectid;
176 spin_unlock(&info->block_group_cache_lock);
182 * This will return the block group at or after bytenr if contains is 0, else
183 * it will return the block group that contains the bytenr
185 static struct btrfs_block_group_cache *
186 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
189 struct btrfs_block_group_cache *cache, *ret = NULL;
193 spin_lock(&info->block_group_cache_lock);
194 n = info->block_group_cache_tree.rb_node;
197 cache = rb_entry(n, struct btrfs_block_group_cache,
199 end = cache->key.objectid + cache->key.offset - 1;
200 start = cache->key.objectid;
202 if (bytenr < start) {
203 if (!contains && (!ret || start < ret->key.objectid))
206 } else if (bytenr > start) {
207 if (contains && bytenr <= end) {
218 btrfs_get_block_group(ret);
219 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
220 info->first_logical_byte = ret->key.objectid;
222 spin_unlock(&info->block_group_cache_lock);
227 static int add_excluded_extent(struct btrfs_fs_info *fs_info,
228 u64 start, u64 num_bytes)
230 u64 end = start + num_bytes - 1;
231 set_extent_bits(&fs_info->freed_extents[0],
232 start, end, EXTENT_UPTODATE);
233 set_extent_bits(&fs_info->freed_extents[1],
234 start, end, EXTENT_UPTODATE);
238 static void free_excluded_extents(struct btrfs_block_group_cache *cache)
240 struct btrfs_fs_info *fs_info = cache->fs_info;
243 start = cache->key.objectid;
244 end = start + cache->key.offset - 1;
246 clear_extent_bits(&fs_info->freed_extents[0],
247 start, end, EXTENT_UPTODATE);
248 clear_extent_bits(&fs_info->freed_extents[1],
249 start, end, EXTENT_UPTODATE);
252 static int exclude_super_stripes(struct btrfs_block_group_cache *cache)
254 struct btrfs_fs_info *fs_info = cache->fs_info;
260 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
261 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
262 cache->bytes_super += stripe_len;
263 ret = add_excluded_extent(fs_info, cache->key.objectid,
269 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
270 bytenr = btrfs_sb_offset(i);
271 ret = btrfs_rmap_block(fs_info, cache->key.objectid,
272 bytenr, &logical, &nr, &stripe_len);
279 if (logical[nr] > cache->key.objectid +
283 if (logical[nr] + stripe_len <= cache->key.objectid)
287 if (start < cache->key.objectid) {
288 start = cache->key.objectid;
289 len = (logical[nr] + stripe_len) - start;
291 len = min_t(u64, stripe_len,
292 cache->key.objectid +
293 cache->key.offset - start);
296 cache->bytes_super += len;
297 ret = add_excluded_extent(fs_info, start, len);
309 static struct btrfs_caching_control *
310 get_caching_control(struct btrfs_block_group_cache *cache)
312 struct btrfs_caching_control *ctl;
314 spin_lock(&cache->lock);
315 if (!cache->caching_ctl) {
316 spin_unlock(&cache->lock);
320 ctl = cache->caching_ctl;
321 refcount_inc(&ctl->count);
322 spin_unlock(&cache->lock);
326 static void put_caching_control(struct btrfs_caching_control *ctl)
328 if (refcount_dec_and_test(&ctl->count))
332 #ifdef CONFIG_BTRFS_DEBUG
333 static void fragment_free_space(struct btrfs_block_group_cache *block_group)
335 struct btrfs_fs_info *fs_info = block_group->fs_info;
336 u64 start = block_group->key.objectid;
337 u64 len = block_group->key.offset;
338 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
339 fs_info->nodesize : fs_info->sectorsize;
340 u64 step = chunk << 1;
342 while (len > chunk) {
343 btrfs_remove_free_space(block_group, start, chunk);
354 * this is only called by cache_block_group, since we could have freed extents
355 * we need to check the pinned_extents for any extents that can't be used yet
356 * since their free space will be released as soon as the transaction commits.
358 u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
361 struct btrfs_fs_info *info = block_group->fs_info;
362 u64 extent_start, extent_end, size, total_added = 0;
365 while (start < end) {
366 ret = find_first_extent_bit(info->pinned_extents, start,
367 &extent_start, &extent_end,
368 EXTENT_DIRTY | EXTENT_UPTODATE,
373 if (extent_start <= start) {
374 start = extent_end + 1;
375 } else if (extent_start > start && extent_start < end) {
376 size = extent_start - start;
378 ret = btrfs_add_free_space(block_group, start,
380 BUG_ON(ret); /* -ENOMEM or logic error */
381 start = extent_end + 1;
390 ret = btrfs_add_free_space(block_group, start, size);
391 BUG_ON(ret); /* -ENOMEM or logic error */
397 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
399 struct btrfs_block_group_cache *block_group = caching_ctl->block_group;
400 struct btrfs_fs_info *fs_info = block_group->fs_info;
401 struct btrfs_root *extent_root = fs_info->extent_root;
402 struct btrfs_path *path;
403 struct extent_buffer *leaf;
404 struct btrfs_key key;
411 path = btrfs_alloc_path();
415 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
417 #ifdef CONFIG_BTRFS_DEBUG
419 * If we're fragmenting we don't want to make anybody think we can
420 * allocate from this block group until we've had a chance to fragment
423 if (btrfs_should_fragment_free_space(block_group))
427 * We don't want to deadlock with somebody trying to allocate a new
428 * extent for the extent root while also trying to search the extent
429 * root to add free space. So we skip locking and search the commit
430 * root, since its read-only
432 path->skip_locking = 1;
433 path->search_commit_root = 1;
434 path->reada = READA_FORWARD;
438 key.type = BTRFS_EXTENT_ITEM_KEY;
441 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
445 leaf = path->nodes[0];
446 nritems = btrfs_header_nritems(leaf);
449 if (btrfs_fs_closing(fs_info) > 1) {
454 if (path->slots[0] < nritems) {
455 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
457 ret = find_next_key(path, 0, &key);
461 if (need_resched() ||
462 rwsem_is_contended(&fs_info->commit_root_sem)) {
464 caching_ctl->progress = last;
465 btrfs_release_path(path);
466 up_read(&fs_info->commit_root_sem);
467 mutex_unlock(&caching_ctl->mutex);
469 mutex_lock(&caching_ctl->mutex);
470 down_read(&fs_info->commit_root_sem);
474 ret = btrfs_next_leaf(extent_root, path);
479 leaf = path->nodes[0];
480 nritems = btrfs_header_nritems(leaf);
484 if (key.objectid < last) {
487 key.type = BTRFS_EXTENT_ITEM_KEY;
490 caching_ctl->progress = last;
491 btrfs_release_path(path);
495 if (key.objectid < block_group->key.objectid) {
500 if (key.objectid >= block_group->key.objectid +
501 block_group->key.offset)
504 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
505 key.type == BTRFS_METADATA_ITEM_KEY) {
506 total_found += add_new_free_space(block_group, last,
508 if (key.type == BTRFS_METADATA_ITEM_KEY)
509 last = key.objectid +
512 last = key.objectid + key.offset;
514 if (total_found > CACHING_CTL_WAKE_UP) {
517 wake_up(&caching_ctl->wait);
524 total_found += add_new_free_space(block_group, last,
525 block_group->key.objectid +
526 block_group->key.offset);
527 caching_ctl->progress = (u64)-1;
530 btrfs_free_path(path);
534 static noinline void caching_thread(struct btrfs_work *work)
536 struct btrfs_block_group_cache *block_group;
537 struct btrfs_fs_info *fs_info;
538 struct btrfs_caching_control *caching_ctl;
541 caching_ctl = container_of(work, struct btrfs_caching_control, work);
542 block_group = caching_ctl->block_group;
543 fs_info = block_group->fs_info;
545 mutex_lock(&caching_ctl->mutex);
546 down_read(&fs_info->commit_root_sem);
548 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
549 ret = load_free_space_tree(caching_ctl);
551 ret = load_extent_tree_free(caching_ctl);
553 spin_lock(&block_group->lock);
554 block_group->caching_ctl = NULL;
555 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
556 spin_unlock(&block_group->lock);
558 #ifdef CONFIG_BTRFS_DEBUG
559 if (btrfs_should_fragment_free_space(block_group)) {
562 spin_lock(&block_group->space_info->lock);
563 spin_lock(&block_group->lock);
564 bytes_used = block_group->key.offset -
565 btrfs_block_group_used(&block_group->item);
566 block_group->space_info->bytes_used += bytes_used >> 1;
567 spin_unlock(&block_group->lock);
568 spin_unlock(&block_group->space_info->lock);
569 fragment_free_space(block_group);
573 caching_ctl->progress = (u64)-1;
575 up_read(&fs_info->commit_root_sem);
576 free_excluded_extents(block_group);
577 mutex_unlock(&caching_ctl->mutex);
579 wake_up(&caching_ctl->wait);
581 put_caching_control(caching_ctl);
582 btrfs_put_block_group(block_group);
585 static int cache_block_group(struct btrfs_block_group_cache *cache,
589 struct btrfs_fs_info *fs_info = cache->fs_info;
590 struct btrfs_caching_control *caching_ctl;
593 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
597 INIT_LIST_HEAD(&caching_ctl->list);
598 mutex_init(&caching_ctl->mutex);
599 init_waitqueue_head(&caching_ctl->wait);
600 caching_ctl->block_group = cache;
601 caching_ctl->progress = cache->key.objectid;
602 refcount_set(&caching_ctl->count, 1);
603 btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
604 caching_thread, NULL, NULL);
606 spin_lock(&cache->lock);
608 * This should be a rare occasion, but this could happen I think in the
609 * case where one thread starts to load the space cache info, and then
610 * some other thread starts a transaction commit which tries to do an
611 * allocation while the other thread is still loading the space cache
612 * info. The previous loop should have kept us from choosing this block
613 * group, but if we've moved to the state where we will wait on caching
614 * block groups we need to first check if we're doing a fast load here,
615 * so we can wait for it to finish, otherwise we could end up allocating
616 * from a block group who's cache gets evicted for one reason or
619 while (cache->cached == BTRFS_CACHE_FAST) {
620 struct btrfs_caching_control *ctl;
622 ctl = cache->caching_ctl;
623 refcount_inc(&ctl->count);
624 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
625 spin_unlock(&cache->lock);
629 finish_wait(&ctl->wait, &wait);
630 put_caching_control(ctl);
631 spin_lock(&cache->lock);
634 if (cache->cached != BTRFS_CACHE_NO) {
635 spin_unlock(&cache->lock);
639 WARN_ON(cache->caching_ctl);
640 cache->caching_ctl = caching_ctl;
641 cache->cached = BTRFS_CACHE_FAST;
642 spin_unlock(&cache->lock);
644 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
645 mutex_lock(&caching_ctl->mutex);
646 ret = load_free_space_cache(cache);
648 spin_lock(&cache->lock);
650 cache->caching_ctl = NULL;
651 cache->cached = BTRFS_CACHE_FINISHED;
652 cache->last_byte_to_unpin = (u64)-1;
653 caching_ctl->progress = (u64)-1;
655 if (load_cache_only) {
656 cache->caching_ctl = NULL;
657 cache->cached = BTRFS_CACHE_NO;
659 cache->cached = BTRFS_CACHE_STARTED;
660 cache->has_caching_ctl = 1;
663 spin_unlock(&cache->lock);
664 #ifdef CONFIG_BTRFS_DEBUG
666 btrfs_should_fragment_free_space(cache)) {
669 spin_lock(&cache->space_info->lock);
670 spin_lock(&cache->lock);
671 bytes_used = cache->key.offset -
672 btrfs_block_group_used(&cache->item);
673 cache->space_info->bytes_used += bytes_used >> 1;
674 spin_unlock(&cache->lock);
675 spin_unlock(&cache->space_info->lock);
676 fragment_free_space(cache);
679 mutex_unlock(&caching_ctl->mutex);
681 wake_up(&caching_ctl->wait);
683 put_caching_control(caching_ctl);
684 free_excluded_extents(cache);
689 * We're either using the free space tree or no caching at all.
690 * Set cached to the appropriate value and wakeup any waiters.
692 spin_lock(&cache->lock);
693 if (load_cache_only) {
694 cache->caching_ctl = NULL;
695 cache->cached = BTRFS_CACHE_NO;
697 cache->cached = BTRFS_CACHE_STARTED;
698 cache->has_caching_ctl = 1;
700 spin_unlock(&cache->lock);
701 wake_up(&caching_ctl->wait);
704 if (load_cache_only) {
705 put_caching_control(caching_ctl);
709 down_write(&fs_info->commit_root_sem);
710 refcount_inc(&caching_ctl->count);
711 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
712 up_write(&fs_info->commit_root_sem);
714 btrfs_get_block_group(cache);
716 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
722 * return the block group that starts at or after bytenr
724 static struct btrfs_block_group_cache *
725 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
727 return block_group_cache_tree_search(info, bytenr, 0);
731 * return the block group that contains the given bytenr
733 struct btrfs_block_group_cache *btrfs_lookup_block_group(
734 struct btrfs_fs_info *info,
737 return block_group_cache_tree_search(info, bytenr, 1);
740 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
743 struct list_head *head = &info->space_info;
744 struct btrfs_space_info *found;
746 flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
749 list_for_each_entry_rcu(found, head, list) {
750 if (found->flags & flags) {
759 static u64 generic_ref_to_space_flags(struct btrfs_ref *ref)
761 if (ref->type == BTRFS_REF_METADATA) {
762 if (ref->tree_ref.root == BTRFS_CHUNK_TREE_OBJECTID)
763 return BTRFS_BLOCK_GROUP_SYSTEM;
765 return BTRFS_BLOCK_GROUP_METADATA;
767 return BTRFS_BLOCK_GROUP_DATA;
770 static void add_pinned_bytes(struct btrfs_fs_info *fs_info,
771 struct btrfs_ref *ref)
773 struct btrfs_space_info *space_info;
774 u64 flags = generic_ref_to_space_flags(ref);
776 space_info = __find_space_info(fs_info, flags);
778 percpu_counter_add_batch(&space_info->total_bytes_pinned, ref->len,
779 BTRFS_TOTAL_BYTES_PINNED_BATCH);
782 static void sub_pinned_bytes(struct btrfs_fs_info *fs_info,
783 struct btrfs_ref *ref)
785 struct btrfs_space_info *space_info;
786 u64 flags = generic_ref_to_space_flags(ref);
788 space_info = __find_space_info(fs_info, flags);
790 percpu_counter_add_batch(&space_info->total_bytes_pinned, -ref->len,
791 BTRFS_TOTAL_BYTES_PINNED_BATCH);
795 * after adding space to the filesystem, we need to clear the full flags
796 * on all the space infos.
798 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
800 struct list_head *head = &info->space_info;
801 struct btrfs_space_info *found;
804 list_for_each_entry_rcu(found, head, list)
809 /* simple helper to search for an existing data extent at a given offset */
810 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
813 struct btrfs_key key;
814 struct btrfs_path *path;
816 path = btrfs_alloc_path();
820 key.objectid = start;
822 key.type = BTRFS_EXTENT_ITEM_KEY;
823 ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
824 btrfs_free_path(path);
829 * helper function to lookup reference count and flags of a tree block.
831 * the head node for delayed ref is used to store the sum of all the
832 * reference count modifications queued up in the rbtree. the head
833 * node may also store the extent flags to set. This way you can check
834 * to see what the reference count and extent flags would be if all of
835 * the delayed refs are not processed.
837 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
838 struct btrfs_fs_info *fs_info, u64 bytenr,
839 u64 offset, int metadata, u64 *refs, u64 *flags)
841 struct btrfs_delayed_ref_head *head;
842 struct btrfs_delayed_ref_root *delayed_refs;
843 struct btrfs_path *path;
844 struct btrfs_extent_item *ei;
845 struct extent_buffer *leaf;
846 struct btrfs_key key;
853 * If we don't have skinny metadata, don't bother doing anything
856 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
857 offset = fs_info->nodesize;
861 path = btrfs_alloc_path();
866 path->skip_locking = 1;
867 path->search_commit_root = 1;
871 key.objectid = bytenr;
874 key.type = BTRFS_METADATA_ITEM_KEY;
876 key.type = BTRFS_EXTENT_ITEM_KEY;
878 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
882 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
883 if (path->slots[0]) {
885 btrfs_item_key_to_cpu(path->nodes[0], &key,
887 if (key.objectid == bytenr &&
888 key.type == BTRFS_EXTENT_ITEM_KEY &&
889 key.offset == fs_info->nodesize)
895 leaf = path->nodes[0];
896 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
897 if (item_size >= sizeof(*ei)) {
898 ei = btrfs_item_ptr(leaf, path->slots[0],
899 struct btrfs_extent_item);
900 num_refs = btrfs_extent_refs(leaf, ei);
901 extent_flags = btrfs_extent_flags(leaf, ei);
904 btrfs_print_v0_err(fs_info);
906 btrfs_abort_transaction(trans, ret);
908 btrfs_handle_fs_error(fs_info, ret, NULL);
913 BUG_ON(num_refs == 0);
923 delayed_refs = &trans->transaction->delayed_refs;
924 spin_lock(&delayed_refs->lock);
925 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
927 if (!mutex_trylock(&head->mutex)) {
928 refcount_inc(&head->refs);
929 spin_unlock(&delayed_refs->lock);
931 btrfs_release_path(path);
934 * Mutex was contended, block until it's released and try
937 mutex_lock(&head->mutex);
938 mutex_unlock(&head->mutex);
939 btrfs_put_delayed_ref_head(head);
942 spin_lock(&head->lock);
943 if (head->extent_op && head->extent_op->update_flags)
944 extent_flags |= head->extent_op->flags_to_set;
946 BUG_ON(num_refs == 0);
948 num_refs += head->ref_mod;
949 spin_unlock(&head->lock);
950 mutex_unlock(&head->mutex);
952 spin_unlock(&delayed_refs->lock);
954 WARN_ON(num_refs == 0);
958 *flags = extent_flags;
960 btrfs_free_path(path);
965 * Back reference rules. Back refs have three main goals:
967 * 1) differentiate between all holders of references to an extent so that
968 * when a reference is dropped we can make sure it was a valid reference
969 * before freeing the extent.
971 * 2) Provide enough information to quickly find the holders of an extent
972 * if we notice a given block is corrupted or bad.
974 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
975 * maintenance. This is actually the same as #2, but with a slightly
976 * different use case.
978 * There are two kinds of back refs. The implicit back refs is optimized
979 * for pointers in non-shared tree blocks. For a given pointer in a block,
980 * back refs of this kind provide information about the block's owner tree
981 * and the pointer's key. These information allow us to find the block by
982 * b-tree searching. The full back refs is for pointers in tree blocks not
983 * referenced by their owner trees. The location of tree block is recorded
984 * in the back refs. Actually the full back refs is generic, and can be
985 * used in all cases the implicit back refs is used. The major shortcoming
986 * of the full back refs is its overhead. Every time a tree block gets
987 * COWed, we have to update back refs entry for all pointers in it.
989 * For a newly allocated tree block, we use implicit back refs for
990 * pointers in it. This means most tree related operations only involve
991 * implicit back refs. For a tree block created in old transaction, the
992 * only way to drop a reference to it is COW it. So we can detect the
993 * event that tree block loses its owner tree's reference and do the
994 * back refs conversion.
996 * When a tree block is COWed through a tree, there are four cases:
998 * The reference count of the block is one and the tree is the block's
999 * owner tree. Nothing to do in this case.
1001 * The reference count of the block is one and the tree is not the
1002 * block's owner tree. In this case, full back refs is used for pointers
1003 * in the block. Remove these full back refs, add implicit back refs for
1004 * every pointers in the new block.
1006 * The reference count of the block is greater than one and the tree is
1007 * the block's owner tree. In this case, implicit back refs is used for
1008 * pointers in the block. Add full back refs for every pointers in the
1009 * block, increase lower level extents' reference counts. The original
1010 * implicit back refs are entailed to the new block.
1012 * The reference count of the block is greater than one and the tree is
1013 * not the block's owner tree. Add implicit back refs for every pointer in
1014 * the new block, increase lower level extents' reference count.
1016 * Back Reference Key composing:
1018 * The key objectid corresponds to the first byte in the extent,
1019 * The key type is used to differentiate between types of back refs.
1020 * There are different meanings of the key offset for different types
1023 * File extents can be referenced by:
1025 * - multiple snapshots, subvolumes, or different generations in one subvol
1026 * - different files inside a single subvolume
1027 * - different offsets inside a file (bookend extents in file.c)
1029 * The extent ref structure for the implicit back refs has fields for:
1031 * - Objectid of the subvolume root
1032 * - objectid of the file holding the reference
1033 * - original offset in the file
1034 * - how many bookend extents
1036 * The key offset for the implicit back refs is hash of the first
1039 * The extent ref structure for the full back refs has field for:
1041 * - number of pointers in the tree leaf
1043 * The key offset for the implicit back refs is the first byte of
1046 * When a file extent is allocated, The implicit back refs is used.
1047 * the fields are filled in:
1049 * (root_key.objectid, inode objectid, offset in file, 1)
1051 * When a file extent is removed file truncation, we find the
1052 * corresponding implicit back refs and check the following fields:
1054 * (btrfs_header_owner(leaf), inode objectid, offset in file)
1056 * Btree extents can be referenced by:
1058 * - Different subvolumes
1060 * Both the implicit back refs and the full back refs for tree blocks
1061 * only consist of key. The key offset for the implicit back refs is
1062 * objectid of block's owner tree. The key offset for the full back refs
1063 * is the first byte of parent block.
1065 * When implicit back refs is used, information about the lowest key and
1066 * level of the tree block are required. These information are stored in
1067 * tree block info structure.
1071 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
1072 * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
1073 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
1075 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
1076 struct btrfs_extent_inline_ref *iref,
1077 enum btrfs_inline_ref_type is_data)
1079 int type = btrfs_extent_inline_ref_type(eb, iref);
1080 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
1082 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
1083 type == BTRFS_SHARED_BLOCK_REF_KEY ||
1084 type == BTRFS_SHARED_DATA_REF_KEY ||
1085 type == BTRFS_EXTENT_DATA_REF_KEY) {
1086 if (is_data == BTRFS_REF_TYPE_BLOCK) {
1087 if (type == BTRFS_TREE_BLOCK_REF_KEY)
1089 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1090 ASSERT(eb->fs_info);
1092 * Every shared one has parent tree
1093 * block, which must be aligned to
1097 IS_ALIGNED(offset, eb->fs_info->nodesize))
1100 } else if (is_data == BTRFS_REF_TYPE_DATA) {
1101 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1103 if (type == BTRFS_SHARED_DATA_REF_KEY) {
1104 ASSERT(eb->fs_info);
1106 * Every shared one has parent tree
1107 * block, which must be aligned to
1111 IS_ALIGNED(offset, eb->fs_info->nodesize))
1115 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
1120 btrfs_print_leaf((struct extent_buffer *)eb);
1121 btrfs_err(eb->fs_info, "eb %llu invalid extent inline ref type %d",
1125 return BTRFS_REF_TYPE_INVALID;
1128 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1130 u32 high_crc = ~(u32)0;
1131 u32 low_crc = ~(u32)0;
1134 lenum = cpu_to_le64(root_objectid);
1135 high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
1136 lenum = cpu_to_le64(owner);
1137 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1138 lenum = cpu_to_le64(offset);
1139 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1141 return ((u64)high_crc << 31) ^ (u64)low_crc;
1144 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1145 struct btrfs_extent_data_ref *ref)
1147 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1148 btrfs_extent_data_ref_objectid(leaf, ref),
1149 btrfs_extent_data_ref_offset(leaf, ref));
1152 static int match_extent_data_ref(struct extent_buffer *leaf,
1153 struct btrfs_extent_data_ref *ref,
1154 u64 root_objectid, u64 owner, u64 offset)
1156 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1157 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1158 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1163 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1164 struct btrfs_path *path,
1165 u64 bytenr, u64 parent,
1167 u64 owner, u64 offset)
1169 struct btrfs_root *root = trans->fs_info->extent_root;
1170 struct btrfs_key key;
1171 struct btrfs_extent_data_ref *ref;
1172 struct extent_buffer *leaf;
1178 key.objectid = bytenr;
1180 key.type = BTRFS_SHARED_DATA_REF_KEY;
1181 key.offset = parent;
1183 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1184 key.offset = hash_extent_data_ref(root_objectid,
1189 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1201 leaf = path->nodes[0];
1202 nritems = btrfs_header_nritems(leaf);
1204 if (path->slots[0] >= nritems) {
1205 ret = btrfs_next_leaf(root, path);
1211 leaf = path->nodes[0];
1212 nritems = btrfs_header_nritems(leaf);
1216 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1217 if (key.objectid != bytenr ||
1218 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1221 ref = btrfs_item_ptr(leaf, path->slots[0],
1222 struct btrfs_extent_data_ref);
1224 if (match_extent_data_ref(leaf, ref, root_objectid,
1227 btrfs_release_path(path);
1239 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1240 struct btrfs_path *path,
1241 u64 bytenr, u64 parent,
1242 u64 root_objectid, u64 owner,
1243 u64 offset, int refs_to_add)
1245 struct btrfs_root *root = trans->fs_info->extent_root;
1246 struct btrfs_key key;
1247 struct extent_buffer *leaf;
1252 key.objectid = bytenr;
1254 key.type = BTRFS_SHARED_DATA_REF_KEY;
1255 key.offset = parent;
1256 size = sizeof(struct btrfs_shared_data_ref);
1258 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1259 key.offset = hash_extent_data_ref(root_objectid,
1261 size = sizeof(struct btrfs_extent_data_ref);
1264 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1265 if (ret && ret != -EEXIST)
1268 leaf = path->nodes[0];
1270 struct btrfs_shared_data_ref *ref;
1271 ref = btrfs_item_ptr(leaf, path->slots[0],
1272 struct btrfs_shared_data_ref);
1274 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1276 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1277 num_refs += refs_to_add;
1278 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1281 struct btrfs_extent_data_ref *ref;
1282 while (ret == -EEXIST) {
1283 ref = btrfs_item_ptr(leaf, path->slots[0],
1284 struct btrfs_extent_data_ref);
1285 if (match_extent_data_ref(leaf, ref, root_objectid,
1288 btrfs_release_path(path);
1290 ret = btrfs_insert_empty_item(trans, root, path, &key,
1292 if (ret && ret != -EEXIST)
1295 leaf = path->nodes[0];
1297 ref = btrfs_item_ptr(leaf, path->slots[0],
1298 struct btrfs_extent_data_ref);
1300 btrfs_set_extent_data_ref_root(leaf, ref,
1302 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1303 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1304 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1306 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1307 num_refs += refs_to_add;
1308 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1311 btrfs_mark_buffer_dirty(leaf);
1314 btrfs_release_path(path);
1318 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1319 struct btrfs_path *path,
1320 int refs_to_drop, int *last_ref)
1322 struct btrfs_key key;
1323 struct btrfs_extent_data_ref *ref1 = NULL;
1324 struct btrfs_shared_data_ref *ref2 = NULL;
1325 struct extent_buffer *leaf;
1329 leaf = path->nodes[0];
1330 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1332 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1333 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1334 struct btrfs_extent_data_ref);
1335 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1336 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1337 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1338 struct btrfs_shared_data_ref);
1339 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1340 } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
1341 btrfs_print_v0_err(trans->fs_info);
1342 btrfs_abort_transaction(trans, -EINVAL);
1348 BUG_ON(num_refs < refs_to_drop);
1349 num_refs -= refs_to_drop;
1351 if (num_refs == 0) {
1352 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1355 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1356 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1357 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1358 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1359 btrfs_mark_buffer_dirty(leaf);
1364 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1365 struct btrfs_extent_inline_ref *iref)
1367 struct btrfs_key key;
1368 struct extent_buffer *leaf;
1369 struct btrfs_extent_data_ref *ref1;
1370 struct btrfs_shared_data_ref *ref2;
1374 leaf = path->nodes[0];
1375 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1377 BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
1380 * If type is invalid, we should have bailed out earlier than
1383 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
1384 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1385 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1386 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1387 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1389 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1390 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1392 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1393 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1394 struct btrfs_extent_data_ref);
1395 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1396 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1397 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1398 struct btrfs_shared_data_ref);
1399 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1406 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1407 struct btrfs_path *path,
1408 u64 bytenr, u64 parent,
1411 struct btrfs_root *root = trans->fs_info->extent_root;
1412 struct btrfs_key key;
1415 key.objectid = bytenr;
1417 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1418 key.offset = parent;
1420 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1421 key.offset = root_objectid;
1424 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1430 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1431 struct btrfs_path *path,
1432 u64 bytenr, u64 parent,
1435 struct btrfs_key key;
1438 key.objectid = bytenr;
1440 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1441 key.offset = parent;
1443 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1444 key.offset = root_objectid;
1447 ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
1449 btrfs_release_path(path);
1453 static inline int extent_ref_type(u64 parent, u64 owner)
1456 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1458 type = BTRFS_SHARED_BLOCK_REF_KEY;
1460 type = BTRFS_TREE_BLOCK_REF_KEY;
1463 type = BTRFS_SHARED_DATA_REF_KEY;
1465 type = BTRFS_EXTENT_DATA_REF_KEY;
1470 static int find_next_key(struct btrfs_path *path, int level,
1471 struct btrfs_key *key)
1474 for (; level < BTRFS_MAX_LEVEL; level++) {
1475 if (!path->nodes[level])
1477 if (path->slots[level] + 1 >=
1478 btrfs_header_nritems(path->nodes[level]))
1481 btrfs_item_key_to_cpu(path->nodes[level], key,
1482 path->slots[level] + 1);
1484 btrfs_node_key_to_cpu(path->nodes[level], key,
1485 path->slots[level] + 1);
1492 * look for inline back ref. if back ref is found, *ref_ret is set
1493 * to the address of inline back ref, and 0 is returned.
1495 * if back ref isn't found, *ref_ret is set to the address where it
1496 * should be inserted, and -ENOENT is returned.
1498 * if insert is true and there are too many inline back refs, the path
1499 * points to the extent item, and -EAGAIN is returned.
1501 * NOTE: inline back refs are ordered in the same way that back ref
1502 * items in the tree are ordered.
1504 static noinline_for_stack
1505 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1506 struct btrfs_path *path,
1507 struct btrfs_extent_inline_ref **ref_ret,
1508 u64 bytenr, u64 num_bytes,
1509 u64 parent, u64 root_objectid,
1510 u64 owner, u64 offset, int insert)
1512 struct btrfs_fs_info *fs_info = trans->fs_info;
1513 struct btrfs_root *root = fs_info->extent_root;
1514 struct btrfs_key key;
1515 struct extent_buffer *leaf;
1516 struct btrfs_extent_item *ei;
1517 struct btrfs_extent_inline_ref *iref;
1527 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1530 key.objectid = bytenr;
1531 key.type = BTRFS_EXTENT_ITEM_KEY;
1532 key.offset = num_bytes;
1534 want = extent_ref_type(parent, owner);
1536 extra_size = btrfs_extent_inline_ref_size(want);
1537 path->keep_locks = 1;
1542 * Owner is our level, so we can just add one to get the level for the
1543 * block we are interested in.
1545 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1546 key.type = BTRFS_METADATA_ITEM_KEY;
1551 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1558 * We may be a newly converted file system which still has the old fat
1559 * extent entries for metadata, so try and see if we have one of those.
1561 if (ret > 0 && skinny_metadata) {
1562 skinny_metadata = false;
1563 if (path->slots[0]) {
1565 btrfs_item_key_to_cpu(path->nodes[0], &key,
1567 if (key.objectid == bytenr &&
1568 key.type == BTRFS_EXTENT_ITEM_KEY &&
1569 key.offset == num_bytes)
1573 key.objectid = bytenr;
1574 key.type = BTRFS_EXTENT_ITEM_KEY;
1575 key.offset = num_bytes;
1576 btrfs_release_path(path);
1581 if (ret && !insert) {
1584 } else if (WARN_ON(ret)) {
1589 leaf = path->nodes[0];
1590 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1591 if (unlikely(item_size < sizeof(*ei))) {
1593 btrfs_print_v0_err(fs_info);
1594 btrfs_abort_transaction(trans, err);
1598 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1599 flags = btrfs_extent_flags(leaf, ei);
1601 ptr = (unsigned long)(ei + 1);
1602 end = (unsigned long)ei + item_size;
1604 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1605 ptr += sizeof(struct btrfs_tree_block_info);
1609 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
1610 needed = BTRFS_REF_TYPE_DATA;
1612 needed = BTRFS_REF_TYPE_BLOCK;
1620 iref = (struct btrfs_extent_inline_ref *)ptr;
1621 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
1622 if (type == BTRFS_REF_TYPE_INVALID) {
1630 ptr += btrfs_extent_inline_ref_size(type);
1634 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1635 struct btrfs_extent_data_ref *dref;
1636 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1637 if (match_extent_data_ref(leaf, dref, root_objectid,
1642 if (hash_extent_data_ref_item(leaf, dref) <
1643 hash_extent_data_ref(root_objectid, owner, offset))
1647 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1649 if (parent == ref_offset) {
1653 if (ref_offset < parent)
1656 if (root_objectid == ref_offset) {
1660 if (ref_offset < root_objectid)
1664 ptr += btrfs_extent_inline_ref_size(type);
1666 if (err == -ENOENT && insert) {
1667 if (item_size + extra_size >=
1668 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1673 * To add new inline back ref, we have to make sure
1674 * there is no corresponding back ref item.
1675 * For simplicity, we just do not add new inline back
1676 * ref if there is any kind of item for this block
1678 if (find_next_key(path, 0, &key) == 0 &&
1679 key.objectid == bytenr &&
1680 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1685 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1688 path->keep_locks = 0;
1689 btrfs_unlock_up_safe(path, 1);
1695 * helper to add new inline back ref
1697 static noinline_for_stack
1698 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1699 struct btrfs_path *path,
1700 struct btrfs_extent_inline_ref *iref,
1701 u64 parent, u64 root_objectid,
1702 u64 owner, u64 offset, int refs_to_add,
1703 struct btrfs_delayed_extent_op *extent_op)
1705 struct extent_buffer *leaf;
1706 struct btrfs_extent_item *ei;
1709 unsigned long item_offset;
1714 leaf = path->nodes[0];
1715 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1716 item_offset = (unsigned long)iref - (unsigned long)ei;
1718 type = extent_ref_type(parent, owner);
1719 size = btrfs_extent_inline_ref_size(type);
1721 btrfs_extend_item(path, size);
1723 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1724 refs = btrfs_extent_refs(leaf, ei);
1725 refs += refs_to_add;
1726 btrfs_set_extent_refs(leaf, ei, refs);
1728 __run_delayed_extent_op(extent_op, leaf, ei);
1730 ptr = (unsigned long)ei + item_offset;
1731 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1732 if (ptr < end - size)
1733 memmove_extent_buffer(leaf, ptr + size, ptr,
1736 iref = (struct btrfs_extent_inline_ref *)ptr;
1737 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1738 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1739 struct btrfs_extent_data_ref *dref;
1740 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1741 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1742 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1743 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1744 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1745 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1746 struct btrfs_shared_data_ref *sref;
1747 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1748 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1749 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1750 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1751 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1753 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1755 btrfs_mark_buffer_dirty(leaf);
1758 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1759 struct btrfs_path *path,
1760 struct btrfs_extent_inline_ref **ref_ret,
1761 u64 bytenr, u64 num_bytes, u64 parent,
1762 u64 root_objectid, u64 owner, u64 offset)
1766 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1767 num_bytes, parent, root_objectid,
1772 btrfs_release_path(path);
1775 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1776 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1779 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1780 root_objectid, owner, offset);
1786 * helper to update/remove inline back ref
1788 static noinline_for_stack
1789 void update_inline_extent_backref(struct btrfs_path *path,
1790 struct btrfs_extent_inline_ref *iref,
1792 struct btrfs_delayed_extent_op *extent_op,
1795 struct extent_buffer *leaf = path->nodes[0];
1796 struct btrfs_extent_item *ei;
1797 struct btrfs_extent_data_ref *dref = NULL;
1798 struct btrfs_shared_data_ref *sref = NULL;
1806 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1807 refs = btrfs_extent_refs(leaf, ei);
1808 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1809 refs += refs_to_mod;
1810 btrfs_set_extent_refs(leaf, ei, refs);
1812 __run_delayed_extent_op(extent_op, leaf, ei);
1815 * If type is invalid, we should have bailed out after
1816 * lookup_inline_extent_backref().
1818 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1819 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1821 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1822 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1823 refs = btrfs_extent_data_ref_count(leaf, dref);
1824 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1825 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1826 refs = btrfs_shared_data_ref_count(leaf, sref);
1829 BUG_ON(refs_to_mod != -1);
1832 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1833 refs += refs_to_mod;
1836 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1837 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1839 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1842 size = btrfs_extent_inline_ref_size(type);
1843 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1844 ptr = (unsigned long)iref;
1845 end = (unsigned long)ei + item_size;
1846 if (ptr + size < end)
1847 memmove_extent_buffer(leaf, ptr, ptr + size,
1850 btrfs_truncate_item(path, item_size, 1);
1852 btrfs_mark_buffer_dirty(leaf);
1855 static noinline_for_stack
1856 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1857 struct btrfs_path *path,
1858 u64 bytenr, u64 num_bytes, u64 parent,
1859 u64 root_objectid, u64 owner,
1860 u64 offset, int refs_to_add,
1861 struct btrfs_delayed_extent_op *extent_op)
1863 struct btrfs_extent_inline_ref *iref;
1866 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1867 num_bytes, parent, root_objectid,
1870 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1871 update_inline_extent_backref(path, iref, refs_to_add,
1873 } else if (ret == -ENOENT) {
1874 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1875 root_objectid, owner, offset,
1876 refs_to_add, extent_op);
1882 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1883 struct btrfs_path *path,
1884 u64 bytenr, u64 parent, u64 root_objectid,
1885 u64 owner, u64 offset, int refs_to_add)
1888 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1889 BUG_ON(refs_to_add != 1);
1890 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1893 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1894 root_objectid, owner, offset,
1900 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1901 struct btrfs_path *path,
1902 struct btrfs_extent_inline_ref *iref,
1903 int refs_to_drop, int is_data, int *last_ref)
1907 BUG_ON(!is_data && refs_to_drop != 1);
1909 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1911 } else if (is_data) {
1912 ret = remove_extent_data_ref(trans, path, refs_to_drop,
1916 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1921 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1922 u64 *discarded_bytes)
1925 u64 bytes_left, end;
1926 u64 aligned_start = ALIGN(start, 1 << 9);
1928 if (WARN_ON(start != aligned_start)) {
1929 len -= aligned_start - start;
1930 len = round_down(len, 1 << 9);
1931 start = aligned_start;
1934 *discarded_bytes = 0;
1942 /* Skip any superblocks on this device. */
1943 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1944 u64 sb_start = btrfs_sb_offset(j);
1945 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1946 u64 size = sb_start - start;
1948 if (!in_range(sb_start, start, bytes_left) &&
1949 !in_range(sb_end, start, bytes_left) &&
1950 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1954 * Superblock spans beginning of range. Adjust start and
1957 if (sb_start <= start) {
1958 start += sb_end - start;
1963 bytes_left = end - start;
1968 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1971 *discarded_bytes += size;
1972 else if (ret != -EOPNOTSUPP)
1981 bytes_left = end - start;
1985 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1988 *discarded_bytes += bytes_left;
1993 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1994 u64 num_bytes, u64 *actual_bytes)
1997 u64 discarded_bytes = 0;
1998 struct btrfs_bio *bbio = NULL;
2002 * Avoid races with device replace and make sure our bbio has devices
2003 * associated to its stripes that don't go away while we are discarding.
2005 btrfs_bio_counter_inc_blocked(fs_info);
2006 /* Tell the block device(s) that the sectors can be discarded */
2007 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
2009 /* Error condition is -ENOMEM */
2011 struct btrfs_bio_stripe *stripe = bbio->stripes;
2015 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
2017 struct request_queue *req_q;
2019 if (!stripe->dev->bdev) {
2020 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
2023 req_q = bdev_get_queue(stripe->dev->bdev);
2024 if (!blk_queue_discard(req_q))
2027 ret = btrfs_issue_discard(stripe->dev->bdev,
2032 discarded_bytes += bytes;
2033 else if (ret != -EOPNOTSUPP)
2034 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
2037 * Just in case we get back EOPNOTSUPP for some reason,
2038 * just ignore the return value so we don't screw up
2039 * people calling discard_extent.
2043 btrfs_put_bbio(bbio);
2045 btrfs_bio_counter_dec(fs_info);
2048 *actual_bytes = discarded_bytes;
2051 if (ret == -EOPNOTSUPP)
2056 /* Can return -ENOMEM */
2057 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2058 struct btrfs_ref *generic_ref)
2060 struct btrfs_fs_info *fs_info = trans->fs_info;
2061 int old_ref_mod, new_ref_mod;
2064 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
2065 generic_ref->action);
2066 BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
2067 generic_ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID);
2069 if (generic_ref->type == BTRFS_REF_METADATA)
2070 ret = btrfs_add_delayed_tree_ref(trans, generic_ref,
2071 NULL, &old_ref_mod, &new_ref_mod);
2073 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0,
2074 &old_ref_mod, &new_ref_mod);
2076 btrfs_ref_tree_mod(fs_info, generic_ref);
2078 if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0)
2079 sub_pinned_bytes(fs_info, generic_ref);
2085 * __btrfs_inc_extent_ref - insert backreference for a given extent
2087 * @trans: Handle of transaction
2089 * @node: The delayed ref node used to get the bytenr/length for
2090 * extent whose references are incremented.
2092 * @parent: If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
2093 * BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
2094 * bytenr of the parent block. Since new extents are always
2095 * created with indirect references, this will only be the case
2096 * when relocating a shared extent. In that case, root_objectid
2097 * will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
2100 * @root_objectid: The id of the root where this modification has originated,
2101 * this can be either one of the well-known metadata trees or
2102 * the subvolume id which references this extent.
2104 * @owner: For data extents it is the inode number of the owning file.
2105 * For metadata extents this parameter holds the level in the
2106 * tree of the extent.
2108 * @offset: For metadata extents the offset is ignored and is currently
2109 * always passed as 0. For data extents it is the fileoffset
2110 * this extent belongs to.
2112 * @refs_to_add Number of references to add
2114 * @extent_op Pointer to a structure, holding information necessary when
2115 * updating a tree block's flags
2118 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2119 struct btrfs_delayed_ref_node *node,
2120 u64 parent, u64 root_objectid,
2121 u64 owner, u64 offset, int refs_to_add,
2122 struct btrfs_delayed_extent_op *extent_op)
2124 struct btrfs_path *path;
2125 struct extent_buffer *leaf;
2126 struct btrfs_extent_item *item;
2127 struct btrfs_key key;
2128 u64 bytenr = node->bytenr;
2129 u64 num_bytes = node->num_bytes;
2133 path = btrfs_alloc_path();
2137 path->reada = READA_FORWARD;
2138 path->leave_spinning = 1;
2139 /* this will setup the path even if it fails to insert the back ref */
2140 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
2141 parent, root_objectid, owner,
2142 offset, refs_to_add, extent_op);
2143 if ((ret < 0 && ret != -EAGAIN) || !ret)
2147 * Ok we had -EAGAIN which means we didn't have space to insert and
2148 * inline extent ref, so just update the reference count and add a
2151 leaf = path->nodes[0];
2152 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2153 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2154 refs = btrfs_extent_refs(leaf, item);
2155 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2157 __run_delayed_extent_op(extent_op, leaf, item);
2159 btrfs_mark_buffer_dirty(leaf);
2160 btrfs_release_path(path);
2162 path->reada = READA_FORWARD;
2163 path->leave_spinning = 1;
2164 /* now insert the actual backref */
2165 ret = insert_extent_backref(trans, path, bytenr, parent, root_objectid,
2166 owner, offset, refs_to_add);
2168 btrfs_abort_transaction(trans, ret);
2170 btrfs_free_path(path);
2174 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2175 struct btrfs_delayed_ref_node *node,
2176 struct btrfs_delayed_extent_op *extent_op,
2177 int insert_reserved)
2180 struct btrfs_delayed_data_ref *ref;
2181 struct btrfs_key ins;
2186 ins.objectid = node->bytenr;
2187 ins.offset = node->num_bytes;
2188 ins.type = BTRFS_EXTENT_ITEM_KEY;
2190 ref = btrfs_delayed_node_to_data_ref(node);
2191 trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
2193 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2194 parent = ref->parent;
2195 ref_root = ref->root;
2197 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2199 flags |= extent_op->flags_to_set;
2200 ret = alloc_reserved_file_extent(trans, parent, ref_root,
2201 flags, ref->objectid,
2204 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2205 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2206 ref->objectid, ref->offset,
2207 node->ref_mod, extent_op);
2208 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2209 ret = __btrfs_free_extent(trans, node, parent,
2210 ref_root, ref->objectid,
2211 ref->offset, node->ref_mod,
2219 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2220 struct extent_buffer *leaf,
2221 struct btrfs_extent_item *ei)
2223 u64 flags = btrfs_extent_flags(leaf, ei);
2224 if (extent_op->update_flags) {
2225 flags |= extent_op->flags_to_set;
2226 btrfs_set_extent_flags(leaf, ei, flags);
2229 if (extent_op->update_key) {
2230 struct btrfs_tree_block_info *bi;
2231 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2232 bi = (struct btrfs_tree_block_info *)(ei + 1);
2233 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2237 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2238 struct btrfs_delayed_ref_head *head,
2239 struct btrfs_delayed_extent_op *extent_op)
2241 struct btrfs_fs_info *fs_info = trans->fs_info;
2242 struct btrfs_key key;
2243 struct btrfs_path *path;
2244 struct btrfs_extent_item *ei;
2245 struct extent_buffer *leaf;
2249 int metadata = !extent_op->is_data;
2254 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2257 path = btrfs_alloc_path();
2261 key.objectid = head->bytenr;
2264 key.type = BTRFS_METADATA_ITEM_KEY;
2265 key.offset = extent_op->level;
2267 key.type = BTRFS_EXTENT_ITEM_KEY;
2268 key.offset = head->num_bytes;
2272 path->reada = READA_FORWARD;
2273 path->leave_spinning = 1;
2274 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2281 if (path->slots[0] > 0) {
2283 btrfs_item_key_to_cpu(path->nodes[0], &key,
2285 if (key.objectid == head->bytenr &&
2286 key.type == BTRFS_EXTENT_ITEM_KEY &&
2287 key.offset == head->num_bytes)
2291 btrfs_release_path(path);
2294 key.objectid = head->bytenr;
2295 key.offset = head->num_bytes;
2296 key.type = BTRFS_EXTENT_ITEM_KEY;
2305 leaf = path->nodes[0];
2306 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2308 if (unlikely(item_size < sizeof(*ei))) {
2310 btrfs_print_v0_err(fs_info);
2311 btrfs_abort_transaction(trans, err);
2315 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2316 __run_delayed_extent_op(extent_op, leaf, ei);
2318 btrfs_mark_buffer_dirty(leaf);
2320 btrfs_free_path(path);
2324 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2325 struct btrfs_delayed_ref_node *node,
2326 struct btrfs_delayed_extent_op *extent_op,
2327 int insert_reserved)
2330 struct btrfs_delayed_tree_ref *ref;
2334 ref = btrfs_delayed_node_to_tree_ref(node);
2335 trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
2337 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2338 parent = ref->parent;
2339 ref_root = ref->root;
2341 if (node->ref_mod != 1) {
2342 btrfs_err(trans->fs_info,
2343 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2344 node->bytenr, node->ref_mod, node->action, ref_root,
2348 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2349 BUG_ON(!extent_op || !extent_op->update_flags);
2350 ret = alloc_reserved_tree_block(trans, node, extent_op);
2351 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2352 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2353 ref->level, 0, 1, extent_op);
2354 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2355 ret = __btrfs_free_extent(trans, node, parent, ref_root,
2356 ref->level, 0, 1, extent_op);
2363 /* helper function to actually process a single delayed ref entry */
2364 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2365 struct btrfs_delayed_ref_node *node,
2366 struct btrfs_delayed_extent_op *extent_op,
2367 int insert_reserved)
2371 if (trans->aborted) {
2372 if (insert_reserved)
2373 btrfs_pin_extent(trans->fs_info, node->bytenr,
2374 node->num_bytes, 1);
2378 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2379 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2380 ret = run_delayed_tree_ref(trans, node, extent_op,
2382 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2383 node->type == BTRFS_SHARED_DATA_REF_KEY)
2384 ret = run_delayed_data_ref(trans, node, extent_op,
2388 if (ret && insert_reserved)
2389 btrfs_pin_extent(trans->fs_info, node->bytenr,
2390 node->num_bytes, 1);
2394 static inline struct btrfs_delayed_ref_node *
2395 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2397 struct btrfs_delayed_ref_node *ref;
2399 if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
2403 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2404 * This is to prevent a ref count from going down to zero, which deletes
2405 * the extent item from the extent tree, when there still are references
2406 * to add, which would fail because they would not find the extent item.
2408 if (!list_empty(&head->ref_add_list))
2409 return list_first_entry(&head->ref_add_list,
2410 struct btrfs_delayed_ref_node, add_list);
2412 ref = rb_entry(rb_first_cached(&head->ref_tree),
2413 struct btrfs_delayed_ref_node, ref_node);
2414 ASSERT(list_empty(&ref->add_list));
2418 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
2419 struct btrfs_delayed_ref_head *head)
2421 spin_lock(&delayed_refs->lock);
2422 head->processing = 0;
2423 delayed_refs->num_heads_ready++;
2424 spin_unlock(&delayed_refs->lock);
2425 btrfs_delayed_ref_unlock(head);
2428 static struct btrfs_delayed_extent_op *cleanup_extent_op(
2429 struct btrfs_delayed_ref_head *head)
2431 struct btrfs_delayed_extent_op *extent_op = head->extent_op;
2436 if (head->must_insert_reserved) {
2437 head->extent_op = NULL;
2438 btrfs_free_delayed_extent_op(extent_op);
2444 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
2445 struct btrfs_delayed_ref_head *head)
2447 struct btrfs_delayed_extent_op *extent_op;
2450 extent_op = cleanup_extent_op(head);
2453 head->extent_op = NULL;
2454 spin_unlock(&head->lock);
2455 ret = run_delayed_extent_op(trans, head, extent_op);
2456 btrfs_free_delayed_extent_op(extent_op);
2457 return ret ? ret : 1;
2460 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
2461 struct btrfs_delayed_ref_root *delayed_refs,
2462 struct btrfs_delayed_ref_head *head)
2464 int nr_items = 1; /* Dropping this ref head update. */
2466 if (head->total_ref_mod < 0) {
2467 struct btrfs_space_info *space_info;
2471 flags = BTRFS_BLOCK_GROUP_DATA;
2472 else if (head->is_system)
2473 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2475 flags = BTRFS_BLOCK_GROUP_METADATA;
2476 space_info = __find_space_info(fs_info, flags);
2478 percpu_counter_add_batch(&space_info->total_bytes_pinned,
2480 BTRFS_TOTAL_BYTES_PINNED_BATCH);
2483 * We had csum deletions accounted for in our delayed refs rsv,
2484 * we need to drop the csum leaves for this update from our
2487 if (head->is_data) {
2488 spin_lock(&delayed_refs->lock);
2489 delayed_refs->pending_csums -= head->num_bytes;
2490 spin_unlock(&delayed_refs->lock);
2491 nr_items += btrfs_csum_bytes_to_leaves(fs_info,
2496 btrfs_delayed_refs_rsv_release(fs_info, nr_items);
2499 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
2500 struct btrfs_delayed_ref_head *head)
2503 struct btrfs_fs_info *fs_info = trans->fs_info;
2504 struct btrfs_delayed_ref_root *delayed_refs;
2507 delayed_refs = &trans->transaction->delayed_refs;
2509 ret = run_and_cleanup_extent_op(trans, head);
2511 unselect_delayed_ref_head(delayed_refs, head);
2512 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
2519 * Need to drop our head ref lock and re-acquire the delayed ref lock
2520 * and then re-check to make sure nobody got added.
2522 spin_unlock(&head->lock);
2523 spin_lock(&delayed_refs->lock);
2524 spin_lock(&head->lock);
2525 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
2526 spin_unlock(&head->lock);
2527 spin_unlock(&delayed_refs->lock);
2530 btrfs_delete_ref_head(delayed_refs, head);
2531 spin_unlock(&head->lock);
2532 spin_unlock(&delayed_refs->lock);
2534 if (head->must_insert_reserved) {
2535 btrfs_pin_extent(fs_info, head->bytenr,
2536 head->num_bytes, 1);
2537 if (head->is_data) {
2538 ret = btrfs_del_csums(trans, fs_info, head->bytenr,
2543 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
2545 trace_run_delayed_ref_head(fs_info, head, 0);
2546 btrfs_delayed_ref_unlock(head);
2547 btrfs_put_delayed_ref_head(head);
2551 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
2552 struct btrfs_trans_handle *trans)
2554 struct btrfs_delayed_ref_root *delayed_refs =
2555 &trans->transaction->delayed_refs;
2556 struct btrfs_delayed_ref_head *head = NULL;
2559 spin_lock(&delayed_refs->lock);
2560 head = btrfs_select_ref_head(delayed_refs);
2562 spin_unlock(&delayed_refs->lock);
2567 * Grab the lock that says we are going to process all the refs for
2570 ret = btrfs_delayed_ref_lock(delayed_refs, head);
2571 spin_unlock(&delayed_refs->lock);
2574 * We may have dropped the spin lock to get the head mutex lock, and
2575 * that might have given someone else time to free the head. If that's
2576 * true, it has been removed from our list and we can move on.
2579 head = ERR_PTR(-EAGAIN);
2584 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
2585 struct btrfs_delayed_ref_head *locked_ref,
2586 unsigned long *run_refs)
2588 struct btrfs_fs_info *fs_info = trans->fs_info;
2589 struct btrfs_delayed_ref_root *delayed_refs;
2590 struct btrfs_delayed_extent_op *extent_op;
2591 struct btrfs_delayed_ref_node *ref;
2592 int must_insert_reserved = 0;
2595 delayed_refs = &trans->transaction->delayed_refs;
2597 lockdep_assert_held(&locked_ref->mutex);
2598 lockdep_assert_held(&locked_ref->lock);
2600 while ((ref = select_delayed_ref(locked_ref))) {
2602 btrfs_check_delayed_seq(fs_info, ref->seq)) {
2603 spin_unlock(&locked_ref->lock);
2604 unselect_delayed_ref_head(delayed_refs, locked_ref);
2610 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
2611 RB_CLEAR_NODE(&ref->ref_node);
2612 if (!list_empty(&ref->add_list))
2613 list_del(&ref->add_list);
2615 * When we play the delayed ref, also correct the ref_mod on
2618 switch (ref->action) {
2619 case BTRFS_ADD_DELAYED_REF:
2620 case BTRFS_ADD_DELAYED_EXTENT:
2621 locked_ref->ref_mod -= ref->ref_mod;
2623 case BTRFS_DROP_DELAYED_REF:
2624 locked_ref->ref_mod += ref->ref_mod;
2629 atomic_dec(&delayed_refs->num_entries);
2632 * Record the must_insert_reserved flag before we drop the
2635 must_insert_reserved = locked_ref->must_insert_reserved;
2636 locked_ref->must_insert_reserved = 0;
2638 extent_op = locked_ref->extent_op;
2639 locked_ref->extent_op = NULL;
2640 spin_unlock(&locked_ref->lock);
2642 ret = run_one_delayed_ref(trans, ref, extent_op,
2643 must_insert_reserved);
2645 btrfs_free_delayed_extent_op(extent_op);
2647 unselect_delayed_ref_head(delayed_refs, locked_ref);
2648 btrfs_put_delayed_ref(ref);
2649 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2654 btrfs_put_delayed_ref(ref);
2657 spin_lock(&locked_ref->lock);
2658 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2665 * Returns 0 on success or if called with an already aborted transaction.
2666 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2668 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2671 struct btrfs_fs_info *fs_info = trans->fs_info;
2672 struct btrfs_delayed_ref_root *delayed_refs;
2673 struct btrfs_delayed_ref_head *locked_ref = NULL;
2674 ktime_t start = ktime_get();
2676 unsigned long count = 0;
2677 unsigned long actual_count = 0;
2679 delayed_refs = &trans->transaction->delayed_refs;
2682 locked_ref = btrfs_obtain_ref_head(trans);
2683 if (IS_ERR_OR_NULL(locked_ref)) {
2684 if (PTR_ERR(locked_ref) == -EAGAIN) {
2693 * We need to try and merge add/drops of the same ref since we
2694 * can run into issues with relocate dropping the implicit ref
2695 * and then it being added back again before the drop can
2696 * finish. If we merged anything we need to re-loop so we can
2698 * Or we can get node references of the same type that weren't
2699 * merged when created due to bumps in the tree mod seq, and
2700 * we need to merge them to prevent adding an inline extent
2701 * backref before dropping it (triggering a BUG_ON at
2702 * insert_inline_extent_backref()).
2704 spin_lock(&locked_ref->lock);
2705 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2707 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2709 if (ret < 0 && ret != -EAGAIN) {
2711 * Error, btrfs_run_delayed_refs_for_head already
2712 * unlocked everything so just bail out
2717 * Success, perform the usual cleanup of a processed
2720 ret = cleanup_ref_head(trans, locked_ref);
2722 /* We dropped our lock, we need to loop. */
2731 * Either success case or btrfs_run_delayed_refs_for_head
2732 * returned -EAGAIN, meaning we need to select another head
2737 } while ((nr != -1 && count < nr) || locked_ref);
2740 * We don't want to include ref heads since we can have empty ref heads
2741 * and those will drastically skew our runtime down since we just do
2742 * accounting, no actual extent tree updates.
2744 if (actual_count > 0) {
2745 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2749 * We weigh the current average higher than our current runtime
2750 * to avoid large swings in the average.
2752 spin_lock(&delayed_refs->lock);
2753 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2754 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2755 spin_unlock(&delayed_refs->lock);
2760 #ifdef SCRAMBLE_DELAYED_REFS
2762 * Normally delayed refs get processed in ascending bytenr order. This
2763 * correlates in most cases to the order added. To expose dependencies on this
2764 * order, we start to process the tree in the middle instead of the beginning
2766 static u64 find_middle(struct rb_root *root)
2768 struct rb_node *n = root->rb_node;
2769 struct btrfs_delayed_ref_node *entry;
2772 u64 first = 0, last = 0;
2776 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2777 first = entry->bytenr;
2781 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2782 last = entry->bytenr;
2787 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2788 WARN_ON(!entry->in_tree);
2790 middle = entry->bytenr;
2803 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2807 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2808 sizeof(struct btrfs_extent_inline_ref));
2809 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2810 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2813 * We don't ever fill up leaves all the way so multiply by 2 just to be
2814 * closer to what we're really going to want to use.
2816 return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2820 * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2821 * would require to store the csums for that many bytes.
2823 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2826 u64 num_csums_per_leaf;
2829 csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2830 num_csums_per_leaf = div64_u64(csum_size,
2831 (u64)btrfs_super_csum_size(fs_info->super_copy));
2832 num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2833 num_csums += num_csums_per_leaf - 1;
2834 num_csums = div64_u64(num_csums, num_csums_per_leaf);
2838 bool btrfs_check_space_for_delayed_refs(struct btrfs_fs_info *fs_info)
2840 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
2841 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2845 spin_lock(&global_rsv->lock);
2846 reserved = global_rsv->reserved;
2847 spin_unlock(&global_rsv->lock);
2850 * Since the global reserve is just kind of magic we don't really want
2851 * to rely on it to save our bacon, so if our size is more than the
2852 * delayed_refs_rsv and the global rsv then it's time to think about
2855 spin_lock(&delayed_refs_rsv->lock);
2856 reserved += delayed_refs_rsv->reserved;
2857 if (delayed_refs_rsv->size >= reserved)
2859 spin_unlock(&delayed_refs_rsv->lock);
2863 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans)
2866 atomic_read(&trans->transaction->delayed_refs.num_entries);
2871 avg_runtime = trans->fs_info->avg_delayed_ref_runtime;
2872 val = num_entries * avg_runtime;
2873 if (val >= NSEC_PER_SEC)
2875 if (val >= NSEC_PER_SEC / 2)
2878 return btrfs_check_space_for_delayed_refs(trans->fs_info);
2882 * this starts processing the delayed reference count updates and
2883 * extent insertions we have queued up so far. count can be
2884 * 0, which means to process everything in the tree at the start
2885 * of the run (but not newly added entries), or it can be some target
2886 * number you'd like to process.
2888 * Returns 0 on success or if called with an aborted transaction
2889 * Returns <0 on error and aborts the transaction
2891 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2892 unsigned long count)
2894 struct btrfs_fs_info *fs_info = trans->fs_info;
2895 struct rb_node *node;
2896 struct btrfs_delayed_ref_root *delayed_refs;
2897 struct btrfs_delayed_ref_head *head;
2899 int run_all = count == (unsigned long)-1;
2901 /* We'll clean this up in btrfs_cleanup_transaction */
2905 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2908 delayed_refs = &trans->transaction->delayed_refs;
2910 count = atomic_read(&delayed_refs->num_entries) * 2;
2913 #ifdef SCRAMBLE_DELAYED_REFS
2914 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2916 ret = __btrfs_run_delayed_refs(trans, count);
2918 btrfs_abort_transaction(trans, ret);
2923 btrfs_create_pending_block_groups(trans);
2925 spin_lock(&delayed_refs->lock);
2926 node = rb_first_cached(&delayed_refs->href_root);
2928 spin_unlock(&delayed_refs->lock);
2931 head = rb_entry(node, struct btrfs_delayed_ref_head,
2933 refcount_inc(&head->refs);
2934 spin_unlock(&delayed_refs->lock);
2936 /* Mutex was contended, block until it's released and retry. */
2937 mutex_lock(&head->mutex);
2938 mutex_unlock(&head->mutex);
2940 btrfs_put_delayed_ref_head(head);
2948 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2949 u64 bytenr, u64 num_bytes, u64 flags,
2950 int level, int is_data)
2952 struct btrfs_delayed_extent_op *extent_op;
2955 extent_op = btrfs_alloc_delayed_extent_op();
2959 extent_op->flags_to_set = flags;
2960 extent_op->update_flags = true;
2961 extent_op->update_key = false;
2962 extent_op->is_data = is_data ? true : false;
2963 extent_op->level = level;
2965 ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2967 btrfs_free_delayed_extent_op(extent_op);
2971 static noinline int check_delayed_ref(struct btrfs_root *root,
2972 struct btrfs_path *path,
2973 u64 objectid, u64 offset, u64 bytenr)
2975 struct btrfs_delayed_ref_head *head;
2976 struct btrfs_delayed_ref_node *ref;
2977 struct btrfs_delayed_data_ref *data_ref;
2978 struct btrfs_delayed_ref_root *delayed_refs;
2979 struct btrfs_transaction *cur_trans;
2980 struct rb_node *node;
2983 spin_lock(&root->fs_info->trans_lock);
2984 cur_trans = root->fs_info->running_transaction;
2986 refcount_inc(&cur_trans->use_count);
2987 spin_unlock(&root->fs_info->trans_lock);
2991 delayed_refs = &cur_trans->delayed_refs;
2992 spin_lock(&delayed_refs->lock);
2993 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2995 spin_unlock(&delayed_refs->lock);
2996 btrfs_put_transaction(cur_trans);
3000 if (!mutex_trylock(&head->mutex)) {
3001 refcount_inc(&head->refs);
3002 spin_unlock(&delayed_refs->lock);
3004 btrfs_release_path(path);
3007 * Mutex was contended, block until it's released and let
3010 mutex_lock(&head->mutex);
3011 mutex_unlock(&head->mutex);
3012 btrfs_put_delayed_ref_head(head);
3013 btrfs_put_transaction(cur_trans);
3016 spin_unlock(&delayed_refs->lock);
3018 spin_lock(&head->lock);
3020 * XXX: We should replace this with a proper search function in the
3023 for (node = rb_first_cached(&head->ref_tree); node;
3024 node = rb_next(node)) {
3025 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
3026 /* If it's a shared ref we know a cross reference exists */
3027 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
3032 data_ref = btrfs_delayed_node_to_data_ref(ref);
3035 * If our ref doesn't match the one we're currently looking at
3036 * then we have a cross reference.
3038 if (data_ref->root != root->root_key.objectid ||
3039 data_ref->objectid != objectid ||
3040 data_ref->offset != offset) {
3045 spin_unlock(&head->lock);
3046 mutex_unlock(&head->mutex);
3047 btrfs_put_transaction(cur_trans);
3051 static noinline int check_committed_ref(struct btrfs_root *root,
3052 struct btrfs_path *path,
3053 u64 objectid, u64 offset, u64 bytenr)
3055 struct btrfs_fs_info *fs_info = root->fs_info;
3056 struct btrfs_root *extent_root = fs_info->extent_root;
3057 struct extent_buffer *leaf;
3058 struct btrfs_extent_data_ref *ref;
3059 struct btrfs_extent_inline_ref *iref;
3060 struct btrfs_extent_item *ei;
3061 struct btrfs_key key;
3066 key.objectid = bytenr;
3067 key.offset = (u64)-1;
3068 key.type = BTRFS_EXTENT_ITEM_KEY;
3070 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3073 BUG_ON(ret == 0); /* Corruption */
3076 if (path->slots[0] == 0)
3080 leaf = path->nodes[0];
3081 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3083 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
3087 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3088 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);