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>
22 #include "print-tree.h"
26 #include "free-space-cache.h"
27 #include "free-space-tree.h"
30 #include "ref-verify.h"
31 #include "space-info.h"
32 #include "block-rsv.h"
33 #include "delalloc-space.h"
34 #include "block-group.h"
36 #include "rcu-string.h"
38 #include "dev-replace.h"
40 #undef SCRAMBLE_DELAYED_REFS
43 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
44 struct btrfs_delayed_ref_node *node, u64 parent,
45 u64 root_objectid, u64 owner_objectid,
46 u64 owner_offset, int refs_to_drop,
47 struct btrfs_delayed_extent_op *extra_op);
48 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
49 struct extent_buffer *leaf,
50 struct btrfs_extent_item *ei);
51 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
52 u64 parent, u64 root_objectid,
53 u64 flags, u64 owner, u64 offset,
54 struct btrfs_key *ins, int ref_mod);
55 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
56 struct btrfs_delayed_ref_node *node,
57 struct btrfs_delayed_extent_op *extent_op);
58 static int find_next_key(struct btrfs_path *path, int level,
59 struct btrfs_key *key);
61 static int block_group_bits(struct btrfs_block_group *cache, u64 bits)
63 return (cache->flags & bits) == bits;
66 int btrfs_add_excluded_extent(struct btrfs_fs_info *fs_info,
67 u64 start, u64 num_bytes)
69 u64 end = start + num_bytes - 1;
70 set_extent_bits(&fs_info->excluded_extents, start, end,
75 void btrfs_free_excluded_extents(struct btrfs_block_group *cache)
77 struct btrfs_fs_info *fs_info = cache->fs_info;
81 end = start + cache->length - 1;
83 clear_extent_bits(&fs_info->excluded_extents, start, end,
87 /* simple helper to search for an existing data extent at a given offset */
88 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
92 struct btrfs_path *path;
94 path = btrfs_alloc_path();
100 key.type = BTRFS_EXTENT_ITEM_KEY;
101 ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
102 btrfs_free_path(path);
107 * helper function to lookup reference count and flags of a tree block.
109 * the head node for delayed ref is used to store the sum of all the
110 * reference count modifications queued up in the rbtree. the head
111 * node may also store the extent flags to set. This way you can check
112 * to see what the reference count and extent flags would be if all of
113 * the delayed refs are not processed.
115 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
116 struct btrfs_fs_info *fs_info, u64 bytenr,
117 u64 offset, int metadata, u64 *refs, u64 *flags)
119 struct btrfs_delayed_ref_head *head;
120 struct btrfs_delayed_ref_root *delayed_refs;
121 struct btrfs_path *path;
122 struct btrfs_extent_item *ei;
123 struct extent_buffer *leaf;
124 struct btrfs_key key;
131 * If we don't have skinny metadata, don't bother doing anything
134 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
135 offset = fs_info->nodesize;
139 path = btrfs_alloc_path();
144 path->skip_locking = 1;
145 path->search_commit_root = 1;
149 key.objectid = bytenr;
152 key.type = BTRFS_METADATA_ITEM_KEY;
154 key.type = BTRFS_EXTENT_ITEM_KEY;
156 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
160 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
161 if (path->slots[0]) {
163 btrfs_item_key_to_cpu(path->nodes[0], &key,
165 if (key.objectid == bytenr &&
166 key.type == BTRFS_EXTENT_ITEM_KEY &&
167 key.offset == fs_info->nodesize)
173 leaf = path->nodes[0];
174 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
175 if (item_size >= sizeof(*ei)) {
176 ei = btrfs_item_ptr(leaf, path->slots[0],
177 struct btrfs_extent_item);
178 num_refs = btrfs_extent_refs(leaf, ei);
179 extent_flags = btrfs_extent_flags(leaf, ei);
182 btrfs_print_v0_err(fs_info);
184 btrfs_abort_transaction(trans, ret);
186 btrfs_handle_fs_error(fs_info, ret, NULL);
191 BUG_ON(num_refs == 0);
201 delayed_refs = &trans->transaction->delayed_refs;
202 spin_lock(&delayed_refs->lock);
203 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
205 if (!mutex_trylock(&head->mutex)) {
206 refcount_inc(&head->refs);
207 spin_unlock(&delayed_refs->lock);
209 btrfs_release_path(path);
212 * Mutex was contended, block until it's released and try
215 mutex_lock(&head->mutex);
216 mutex_unlock(&head->mutex);
217 btrfs_put_delayed_ref_head(head);
220 spin_lock(&head->lock);
221 if (head->extent_op && head->extent_op->update_flags)
222 extent_flags |= head->extent_op->flags_to_set;
224 BUG_ON(num_refs == 0);
226 num_refs += head->ref_mod;
227 spin_unlock(&head->lock);
228 mutex_unlock(&head->mutex);
230 spin_unlock(&delayed_refs->lock);
232 WARN_ON(num_refs == 0);
236 *flags = extent_flags;
238 btrfs_free_path(path);
243 * Back reference rules. Back refs have three main goals:
245 * 1) differentiate between all holders of references to an extent so that
246 * when a reference is dropped we can make sure it was a valid reference
247 * before freeing the extent.
249 * 2) Provide enough information to quickly find the holders of an extent
250 * if we notice a given block is corrupted or bad.
252 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
253 * maintenance. This is actually the same as #2, but with a slightly
254 * different use case.
256 * There are two kinds of back refs. The implicit back refs is optimized
257 * for pointers in non-shared tree blocks. For a given pointer in a block,
258 * back refs of this kind provide information about the block's owner tree
259 * and the pointer's key. These information allow us to find the block by
260 * b-tree searching. The full back refs is for pointers in tree blocks not
261 * referenced by their owner trees. The location of tree block is recorded
262 * in the back refs. Actually the full back refs is generic, and can be
263 * used in all cases the implicit back refs is used. The major shortcoming
264 * of the full back refs is its overhead. Every time a tree block gets
265 * COWed, we have to update back refs entry for all pointers in it.
267 * For a newly allocated tree block, we use implicit back refs for
268 * pointers in it. This means most tree related operations only involve
269 * implicit back refs. For a tree block created in old transaction, the
270 * only way to drop a reference to it is COW it. So we can detect the
271 * event that tree block loses its owner tree's reference and do the
272 * back refs conversion.
274 * When a tree block is COWed through a tree, there are four cases:
276 * The reference count of the block is one and the tree is the block's
277 * owner tree. Nothing to do in this case.
279 * The reference count of the block is one and the tree is not the
280 * block's owner tree. In this case, full back refs is used for pointers
281 * in the block. Remove these full back refs, add implicit back refs for
282 * every pointers in the new block.
284 * The reference count of the block is greater than one and the tree is
285 * the block's owner tree. In this case, implicit back refs is used for
286 * pointers in the block. Add full back refs for every pointers in the
287 * block, increase lower level extents' reference counts. The original
288 * implicit back refs are entailed to the new block.
290 * The reference count of the block is greater than one and the tree is
291 * not the block's owner tree. Add implicit back refs for every pointer in
292 * the new block, increase lower level extents' reference count.
294 * Back Reference Key composing:
296 * The key objectid corresponds to the first byte in the extent,
297 * The key type is used to differentiate between types of back refs.
298 * There are different meanings of the key offset for different types
301 * File extents can be referenced by:
303 * - multiple snapshots, subvolumes, or different generations in one subvol
304 * - different files inside a single subvolume
305 * - different offsets inside a file (bookend extents in file.c)
307 * The extent ref structure for the implicit back refs has fields for:
309 * - Objectid of the subvolume root
310 * - objectid of the file holding the reference
311 * - original offset in the file
312 * - how many bookend extents
314 * The key offset for the implicit back refs is hash of the first
317 * The extent ref structure for the full back refs has field for:
319 * - number of pointers in the tree leaf
321 * The key offset for the implicit back refs is the first byte of
324 * When a file extent is allocated, The implicit back refs is used.
325 * the fields are filled in:
327 * (root_key.objectid, inode objectid, offset in file, 1)
329 * When a file extent is removed file truncation, we find the
330 * corresponding implicit back refs and check the following fields:
332 * (btrfs_header_owner(leaf), inode objectid, offset in file)
334 * Btree extents can be referenced by:
336 * - Different subvolumes
338 * Both the implicit back refs and the full back refs for tree blocks
339 * only consist of key. The key offset for the implicit back refs is
340 * objectid of block's owner tree. The key offset for the full back refs
341 * is the first byte of parent block.
343 * When implicit back refs is used, information about the lowest key and
344 * level of the tree block are required. These information are stored in
345 * tree block info structure.
349 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
350 * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
351 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
353 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
354 struct btrfs_extent_inline_ref *iref,
355 enum btrfs_inline_ref_type is_data)
357 int type = btrfs_extent_inline_ref_type(eb, iref);
358 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
360 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
361 type == BTRFS_SHARED_BLOCK_REF_KEY ||
362 type == BTRFS_SHARED_DATA_REF_KEY ||
363 type == BTRFS_EXTENT_DATA_REF_KEY) {
364 if (is_data == BTRFS_REF_TYPE_BLOCK) {
365 if (type == BTRFS_TREE_BLOCK_REF_KEY)
367 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
370 * Every shared one has parent tree block,
371 * which must be aligned to sector size.
374 IS_ALIGNED(offset, eb->fs_info->sectorsize))
377 } else if (is_data == BTRFS_REF_TYPE_DATA) {
378 if (type == BTRFS_EXTENT_DATA_REF_KEY)
380 if (type == BTRFS_SHARED_DATA_REF_KEY) {
383 * Every shared one has parent tree block,
384 * which must be aligned to sector size.
387 IS_ALIGNED(offset, eb->fs_info->sectorsize))
391 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
396 btrfs_print_leaf((struct extent_buffer *)eb);
397 btrfs_err(eb->fs_info,
398 "eb %llu iref 0x%lx invalid extent inline ref type %d",
399 eb->start, (unsigned long)iref, type);
402 return BTRFS_REF_TYPE_INVALID;
405 u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
407 u32 high_crc = ~(u32)0;
408 u32 low_crc = ~(u32)0;
411 lenum = cpu_to_le64(root_objectid);
412 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
413 lenum = cpu_to_le64(owner);
414 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
415 lenum = cpu_to_le64(offset);
416 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
418 return ((u64)high_crc << 31) ^ (u64)low_crc;
421 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
422 struct btrfs_extent_data_ref *ref)
424 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
425 btrfs_extent_data_ref_objectid(leaf, ref),
426 btrfs_extent_data_ref_offset(leaf, ref));
429 static int match_extent_data_ref(struct extent_buffer *leaf,
430 struct btrfs_extent_data_ref *ref,
431 u64 root_objectid, u64 owner, u64 offset)
433 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
434 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
435 btrfs_extent_data_ref_offset(leaf, ref) != offset)
440 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
441 struct btrfs_path *path,
442 u64 bytenr, u64 parent,
444 u64 owner, u64 offset)
446 struct btrfs_root *root = trans->fs_info->extent_root;
447 struct btrfs_key key;
448 struct btrfs_extent_data_ref *ref;
449 struct extent_buffer *leaf;
455 key.objectid = bytenr;
457 key.type = BTRFS_SHARED_DATA_REF_KEY;
460 key.type = BTRFS_EXTENT_DATA_REF_KEY;
461 key.offset = hash_extent_data_ref(root_objectid,
466 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
478 leaf = path->nodes[0];
479 nritems = btrfs_header_nritems(leaf);
481 if (path->slots[0] >= nritems) {
482 ret = btrfs_next_leaf(root, path);
488 leaf = path->nodes[0];
489 nritems = btrfs_header_nritems(leaf);
493 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
494 if (key.objectid != bytenr ||
495 key.type != BTRFS_EXTENT_DATA_REF_KEY)
498 ref = btrfs_item_ptr(leaf, path->slots[0],
499 struct btrfs_extent_data_ref);
501 if (match_extent_data_ref(leaf, ref, root_objectid,
504 btrfs_release_path(path);
516 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
517 struct btrfs_path *path,
518 u64 bytenr, u64 parent,
519 u64 root_objectid, u64 owner,
520 u64 offset, int refs_to_add)
522 struct btrfs_root *root = trans->fs_info->extent_root;
523 struct btrfs_key key;
524 struct extent_buffer *leaf;
529 key.objectid = bytenr;
531 key.type = BTRFS_SHARED_DATA_REF_KEY;
533 size = sizeof(struct btrfs_shared_data_ref);
535 key.type = BTRFS_EXTENT_DATA_REF_KEY;
536 key.offset = hash_extent_data_ref(root_objectid,
538 size = sizeof(struct btrfs_extent_data_ref);
541 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
542 if (ret && ret != -EEXIST)
545 leaf = path->nodes[0];
547 struct btrfs_shared_data_ref *ref;
548 ref = btrfs_item_ptr(leaf, path->slots[0],
549 struct btrfs_shared_data_ref);
551 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
553 num_refs = btrfs_shared_data_ref_count(leaf, ref);
554 num_refs += refs_to_add;
555 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
558 struct btrfs_extent_data_ref *ref;
559 while (ret == -EEXIST) {
560 ref = btrfs_item_ptr(leaf, path->slots[0],
561 struct btrfs_extent_data_ref);
562 if (match_extent_data_ref(leaf, ref, root_objectid,
565 btrfs_release_path(path);
567 ret = btrfs_insert_empty_item(trans, root, path, &key,
569 if (ret && ret != -EEXIST)
572 leaf = path->nodes[0];
574 ref = btrfs_item_ptr(leaf, path->slots[0],
575 struct btrfs_extent_data_ref);
577 btrfs_set_extent_data_ref_root(leaf, ref,
579 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
580 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
581 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
583 num_refs = btrfs_extent_data_ref_count(leaf, ref);
584 num_refs += refs_to_add;
585 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
588 btrfs_mark_buffer_dirty(leaf);
591 btrfs_release_path(path);
595 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
596 struct btrfs_path *path,
597 int refs_to_drop, int *last_ref)
599 struct btrfs_key key;
600 struct btrfs_extent_data_ref *ref1 = NULL;
601 struct btrfs_shared_data_ref *ref2 = NULL;
602 struct extent_buffer *leaf;
606 leaf = path->nodes[0];
607 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
609 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
610 ref1 = btrfs_item_ptr(leaf, path->slots[0],
611 struct btrfs_extent_data_ref);
612 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
613 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
614 ref2 = btrfs_item_ptr(leaf, path->slots[0],
615 struct btrfs_shared_data_ref);
616 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
617 } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
618 btrfs_print_v0_err(trans->fs_info);
619 btrfs_abort_transaction(trans, -EINVAL);
625 BUG_ON(num_refs < refs_to_drop);
626 num_refs -= refs_to_drop;
629 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
632 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
633 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
634 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
635 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
636 btrfs_mark_buffer_dirty(leaf);
641 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
642 struct btrfs_extent_inline_ref *iref)
644 struct btrfs_key key;
645 struct extent_buffer *leaf;
646 struct btrfs_extent_data_ref *ref1;
647 struct btrfs_shared_data_ref *ref2;
651 leaf = path->nodes[0];
652 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
654 BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
657 * If type is invalid, we should have bailed out earlier than
660 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
661 ASSERT(type != BTRFS_REF_TYPE_INVALID);
662 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
663 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
664 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
666 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
667 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
669 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
670 ref1 = btrfs_item_ptr(leaf, path->slots[0],
671 struct btrfs_extent_data_ref);
672 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
673 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
674 ref2 = btrfs_item_ptr(leaf, path->slots[0],
675 struct btrfs_shared_data_ref);
676 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
683 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
684 struct btrfs_path *path,
685 u64 bytenr, u64 parent,
688 struct btrfs_root *root = trans->fs_info->extent_root;
689 struct btrfs_key key;
692 key.objectid = bytenr;
694 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
697 key.type = BTRFS_TREE_BLOCK_REF_KEY;
698 key.offset = root_objectid;
701 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
707 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
708 struct btrfs_path *path,
709 u64 bytenr, u64 parent,
712 struct btrfs_key key;
715 key.objectid = bytenr;
717 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
720 key.type = BTRFS_TREE_BLOCK_REF_KEY;
721 key.offset = root_objectid;
724 ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
726 btrfs_release_path(path);
730 static inline int extent_ref_type(u64 parent, u64 owner)
733 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
735 type = BTRFS_SHARED_BLOCK_REF_KEY;
737 type = BTRFS_TREE_BLOCK_REF_KEY;
740 type = BTRFS_SHARED_DATA_REF_KEY;
742 type = BTRFS_EXTENT_DATA_REF_KEY;
747 static int find_next_key(struct btrfs_path *path, int level,
748 struct btrfs_key *key)
751 for (; level < BTRFS_MAX_LEVEL; level++) {
752 if (!path->nodes[level])
754 if (path->slots[level] + 1 >=
755 btrfs_header_nritems(path->nodes[level]))
758 btrfs_item_key_to_cpu(path->nodes[level], key,
759 path->slots[level] + 1);
761 btrfs_node_key_to_cpu(path->nodes[level], key,
762 path->slots[level] + 1);
769 * look for inline back ref. if back ref is found, *ref_ret is set
770 * to the address of inline back ref, and 0 is returned.
772 * if back ref isn't found, *ref_ret is set to the address where it
773 * should be inserted, and -ENOENT is returned.
775 * if insert is true and there are too many inline back refs, the path
776 * points to the extent item, and -EAGAIN is returned.
778 * NOTE: inline back refs are ordered in the same way that back ref
779 * items in the tree are ordered.
781 static noinline_for_stack
782 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
783 struct btrfs_path *path,
784 struct btrfs_extent_inline_ref **ref_ret,
785 u64 bytenr, u64 num_bytes,
786 u64 parent, u64 root_objectid,
787 u64 owner, u64 offset, int insert)
789 struct btrfs_fs_info *fs_info = trans->fs_info;
790 struct btrfs_root *root = fs_info->extent_root;
791 struct btrfs_key key;
792 struct extent_buffer *leaf;
793 struct btrfs_extent_item *ei;
794 struct btrfs_extent_inline_ref *iref;
804 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
807 key.objectid = bytenr;
808 key.type = BTRFS_EXTENT_ITEM_KEY;
809 key.offset = num_bytes;
811 want = extent_ref_type(parent, owner);
813 extra_size = btrfs_extent_inline_ref_size(want);
814 path->search_for_extension = 1;
815 path->keep_locks = 1;
820 * Owner is our level, so we can just add one to get the level for the
821 * block we are interested in.
823 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
824 key.type = BTRFS_METADATA_ITEM_KEY;
829 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
836 * We may be a newly converted file system which still has the old fat
837 * extent entries for metadata, so try and see if we have one of those.
839 if (ret > 0 && skinny_metadata) {
840 skinny_metadata = false;
841 if (path->slots[0]) {
843 btrfs_item_key_to_cpu(path->nodes[0], &key,
845 if (key.objectid == bytenr &&
846 key.type == BTRFS_EXTENT_ITEM_KEY &&
847 key.offset == num_bytes)
851 key.objectid = bytenr;
852 key.type = BTRFS_EXTENT_ITEM_KEY;
853 key.offset = num_bytes;
854 btrfs_release_path(path);
859 if (ret && !insert) {
862 } else if (WARN_ON(ret)) {
867 leaf = path->nodes[0];
868 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
869 if (unlikely(item_size < sizeof(*ei))) {
871 btrfs_print_v0_err(fs_info);
872 btrfs_abort_transaction(trans, err);
876 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
877 flags = btrfs_extent_flags(leaf, ei);
879 ptr = (unsigned long)(ei + 1);
880 end = (unsigned long)ei + item_size;
882 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
883 ptr += sizeof(struct btrfs_tree_block_info);
887 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
888 needed = BTRFS_REF_TYPE_DATA;
890 needed = BTRFS_REF_TYPE_BLOCK;
898 iref = (struct btrfs_extent_inline_ref *)ptr;
899 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
900 if (type == BTRFS_REF_TYPE_INVALID) {
908 ptr += btrfs_extent_inline_ref_size(type);
912 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
913 struct btrfs_extent_data_ref *dref;
914 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
915 if (match_extent_data_ref(leaf, dref, root_objectid,
920 if (hash_extent_data_ref_item(leaf, dref) <
921 hash_extent_data_ref(root_objectid, owner, offset))
925 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
927 if (parent == ref_offset) {
931 if (ref_offset < parent)
934 if (root_objectid == ref_offset) {
938 if (ref_offset < root_objectid)
942 ptr += btrfs_extent_inline_ref_size(type);
944 if (err == -ENOENT && insert) {
945 if (item_size + extra_size >=
946 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
951 * To add new inline back ref, we have to make sure
952 * there is no corresponding back ref item.
953 * For simplicity, we just do not add new inline back
954 * ref if there is any kind of item for this block
956 if (find_next_key(path, 0, &key) == 0 &&
957 key.objectid == bytenr &&
958 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
963 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
966 path->keep_locks = 0;
967 path->search_for_extension = 0;
968 btrfs_unlock_up_safe(path, 1);
974 * helper to add new inline back ref
976 static noinline_for_stack
977 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
978 struct btrfs_path *path,
979 struct btrfs_extent_inline_ref *iref,
980 u64 parent, u64 root_objectid,
981 u64 owner, u64 offset, int refs_to_add,
982 struct btrfs_delayed_extent_op *extent_op)
984 struct extent_buffer *leaf;
985 struct btrfs_extent_item *ei;
988 unsigned long item_offset;
993 leaf = path->nodes[0];
994 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
995 item_offset = (unsigned long)iref - (unsigned long)ei;
997 type = extent_ref_type(parent, owner);
998 size = btrfs_extent_inline_ref_size(type);
1000 btrfs_extend_item(path, size);
1002 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1003 refs = btrfs_extent_refs(leaf, ei);
1004 refs += refs_to_add;
1005 btrfs_set_extent_refs(leaf, ei, refs);
1007 __run_delayed_extent_op(extent_op, leaf, ei);
1009 ptr = (unsigned long)ei + item_offset;
1010 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1011 if (ptr < end - size)
1012 memmove_extent_buffer(leaf, ptr + size, ptr,
1015 iref = (struct btrfs_extent_inline_ref *)ptr;
1016 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1017 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1018 struct btrfs_extent_data_ref *dref;
1019 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1020 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1021 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1022 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1023 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1024 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1025 struct btrfs_shared_data_ref *sref;
1026 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1027 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1028 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1029 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1030 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1032 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1034 btrfs_mark_buffer_dirty(leaf);
1037 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1038 struct btrfs_path *path,
1039 struct btrfs_extent_inline_ref **ref_ret,
1040 u64 bytenr, u64 num_bytes, u64 parent,
1041 u64 root_objectid, u64 owner, u64 offset)
1045 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1046 num_bytes, parent, root_objectid,
1051 btrfs_release_path(path);
1054 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1055 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1058 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1059 root_objectid, owner, offset);
1065 * helper to update/remove inline back ref
1067 static noinline_for_stack
1068 void update_inline_extent_backref(struct btrfs_path *path,
1069 struct btrfs_extent_inline_ref *iref,
1071 struct btrfs_delayed_extent_op *extent_op,
1074 struct extent_buffer *leaf = path->nodes[0];
1075 struct btrfs_extent_item *ei;
1076 struct btrfs_extent_data_ref *dref = NULL;
1077 struct btrfs_shared_data_ref *sref = NULL;
1085 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1086 refs = btrfs_extent_refs(leaf, ei);
1087 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1088 refs += refs_to_mod;
1089 btrfs_set_extent_refs(leaf, ei, refs);
1091 __run_delayed_extent_op(extent_op, leaf, ei);
1094 * If type is invalid, we should have bailed out after
1095 * lookup_inline_extent_backref().
1097 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1098 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1100 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1101 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1102 refs = btrfs_extent_data_ref_count(leaf, dref);
1103 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1104 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1105 refs = btrfs_shared_data_ref_count(leaf, sref);
1108 BUG_ON(refs_to_mod != -1);
1111 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1112 refs += refs_to_mod;
1115 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1116 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1118 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1121 size = btrfs_extent_inline_ref_size(type);
1122 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1123 ptr = (unsigned long)iref;
1124 end = (unsigned long)ei + item_size;
1125 if (ptr + size < end)
1126 memmove_extent_buffer(leaf, ptr, ptr + size,
1129 btrfs_truncate_item(path, item_size, 1);
1131 btrfs_mark_buffer_dirty(leaf);
1134 static noinline_for_stack
1135 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1136 struct btrfs_path *path,
1137 u64 bytenr, u64 num_bytes, u64 parent,
1138 u64 root_objectid, u64 owner,
1139 u64 offset, int refs_to_add,
1140 struct btrfs_delayed_extent_op *extent_op)
1142 struct btrfs_extent_inline_ref *iref;
1145 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1146 num_bytes, parent, root_objectid,
1150 * We're adding refs to a tree block we already own, this
1151 * should not happen at all.
1153 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1154 btrfs_crit(trans->fs_info,
1155 "adding refs to an existing tree ref, bytenr %llu num_bytes %llu root_objectid %llu",
1156 bytenr, num_bytes, root_objectid);
1157 if (IS_ENABLED(CONFIG_BTRFS_DEBUG)) {
1159 btrfs_crit(trans->fs_info,
1160 "path->slots[0]=%d path->nodes[0]:", path->slots[0]);
1161 btrfs_print_leaf(path->nodes[0]);
1165 update_inline_extent_backref(path, iref, refs_to_add,
1167 } else if (ret == -ENOENT) {
1168 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1169 root_objectid, owner, offset,
1170 refs_to_add, extent_op);
1176 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1177 struct btrfs_path *path,
1178 struct btrfs_extent_inline_ref *iref,
1179 int refs_to_drop, int is_data, int *last_ref)
1183 BUG_ON(!is_data && refs_to_drop != 1);
1185 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1187 } else if (is_data) {
1188 ret = remove_extent_data_ref(trans, path, refs_to_drop,
1192 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1197 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1198 u64 *discarded_bytes)
1201 u64 bytes_left, end;
1202 u64 aligned_start = ALIGN(start, 1 << 9);
1204 if (WARN_ON(start != aligned_start)) {
1205 len -= aligned_start - start;
1206 len = round_down(len, 1 << 9);
1207 start = aligned_start;
1210 *discarded_bytes = 0;
1218 /* Skip any superblocks on this device. */
1219 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1220 u64 sb_start = btrfs_sb_offset(j);
1221 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1222 u64 size = sb_start - start;
1224 if (!in_range(sb_start, start, bytes_left) &&
1225 !in_range(sb_end, start, bytes_left) &&
1226 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1230 * Superblock spans beginning of range. Adjust start and
1233 if (sb_start <= start) {
1234 start += sb_end - start;
1239 bytes_left = end - start;
1244 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1247 *discarded_bytes += size;
1248 else if (ret != -EOPNOTSUPP)
1257 bytes_left = end - start;
1261 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1264 *discarded_bytes += bytes_left;
1269 static int do_discard_extent(struct btrfs_bio_stripe *stripe, u64 *bytes)
1271 struct btrfs_device *dev = stripe->dev;
1272 struct btrfs_fs_info *fs_info = dev->fs_info;
1273 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1274 u64 phys = stripe->physical;
1275 u64 len = stripe->length;
1279 /* Zone reset on a zoned filesystem */
1280 if (btrfs_can_zone_reset(dev, phys, len)) {
1283 ret = btrfs_reset_device_zone(dev, phys, len, &discarded);
1287 if (!btrfs_dev_replace_is_ongoing(dev_replace) ||
1288 dev != dev_replace->srcdev)
1291 src_disc = discarded;
1293 /* Send to replace target as well */
1294 ret = btrfs_reset_device_zone(dev_replace->tgtdev, phys, len,
1296 discarded += src_disc;
1297 } else if (blk_queue_discard(bdev_get_queue(stripe->dev->bdev))) {
1298 ret = btrfs_issue_discard(dev->bdev, phys, len, &discarded);
1309 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1310 u64 num_bytes, u64 *actual_bytes)
1313 u64 discarded_bytes = 0;
1314 u64 end = bytenr + num_bytes;
1316 struct btrfs_bio *bbio = NULL;
1320 * Avoid races with device replace and make sure our bbio has devices
1321 * associated to its stripes that don't go away while we are discarding.
1323 btrfs_bio_counter_inc_blocked(fs_info);
1325 struct btrfs_bio_stripe *stripe;
1328 num_bytes = end - cur;
1329 /* Tell the block device(s) that the sectors can be discarded */
1330 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, cur,
1331 &num_bytes, &bbio, 0);
1333 * Error can be -ENOMEM, -ENOENT (no such chunk mapping) or
1334 * -EOPNOTSUPP. For any such error, @num_bytes is not updated,
1335 * thus we can't continue anyway.
1340 stripe = bbio->stripes;
1341 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
1344 if (!stripe->dev->bdev) {
1345 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1349 ret = do_discard_extent(stripe, &bytes);
1351 discarded_bytes += bytes;
1352 } else if (ret != -EOPNOTSUPP) {
1354 * Logic errors or -ENOMEM, or -EIO, but
1355 * unlikely to happen.
1357 * And since there are two loops, explicitly
1358 * go to out to avoid confusion.
1360 btrfs_put_bbio(bbio);
1365 * Just in case we get back EOPNOTSUPP for some reason,
1366 * just ignore the return value so we don't screw up
1367 * people calling discard_extent.
1371 btrfs_put_bbio(bbio);
1375 btrfs_bio_counter_dec(fs_info);
1378 *actual_bytes = discarded_bytes;
1381 if (ret == -EOPNOTSUPP)
1386 /* Can return -ENOMEM */
1387 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1388 struct btrfs_ref *generic_ref)
1390 struct btrfs_fs_info *fs_info = trans->fs_info;
1393 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
1394 generic_ref->action);
1395 BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
1396 generic_ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID);
1398 if (generic_ref->type == BTRFS_REF_METADATA)
1399 ret = btrfs_add_delayed_tree_ref(trans, generic_ref, NULL);
1401 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0);
1403 btrfs_ref_tree_mod(fs_info, generic_ref);
1409 * __btrfs_inc_extent_ref - insert backreference for a given extent
1411 * The counterpart is in __btrfs_free_extent(), with examples and more details
1414 * @trans: Handle of transaction
1416 * @node: The delayed ref node used to get the bytenr/length for
1417 * extent whose references are incremented.
1419 * @parent: If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
1420 * BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
1421 * bytenr of the parent block. Since new extents are always
1422 * created with indirect references, this will only be the case
1423 * when relocating a shared extent. In that case, root_objectid
1424 * will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
1427 * @root_objectid: The id of the root where this modification has originated,
1428 * this can be either one of the well-known metadata trees or
1429 * the subvolume id which references this extent.
1431 * @owner: For data extents it is the inode number of the owning file.
1432 * For metadata extents this parameter holds the level in the
1433 * tree of the extent.
1435 * @offset: For metadata extents the offset is ignored and is currently
1436 * always passed as 0. For data extents it is the fileoffset
1437 * this extent belongs to.
1439 * @refs_to_add Number of references to add
1441 * @extent_op Pointer to a structure, holding information necessary when
1442 * updating a tree block's flags
1445 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1446 struct btrfs_delayed_ref_node *node,
1447 u64 parent, u64 root_objectid,
1448 u64 owner, u64 offset, int refs_to_add,
1449 struct btrfs_delayed_extent_op *extent_op)
1451 struct btrfs_path *path;
1452 struct extent_buffer *leaf;
1453 struct btrfs_extent_item *item;
1454 struct btrfs_key key;
1455 u64 bytenr = node->bytenr;
1456 u64 num_bytes = node->num_bytes;
1460 path = btrfs_alloc_path();
1464 /* this will setup the path even if it fails to insert the back ref */
1465 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
1466 parent, root_objectid, owner,
1467 offset, refs_to_add, extent_op);
1468 if ((ret < 0 && ret != -EAGAIN) || !ret)
1472 * Ok we had -EAGAIN which means we didn't have space to insert and
1473 * inline extent ref, so just update the reference count and add a
1476 leaf = path->nodes[0];
1477 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1478 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1479 refs = btrfs_extent_refs(leaf, item);
1480 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1482 __run_delayed_extent_op(extent_op, leaf, item);
1484 btrfs_mark_buffer_dirty(leaf);
1485 btrfs_release_path(path);
1487 /* now insert the actual backref */
1488 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1489 BUG_ON(refs_to_add != 1);
1490 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1493 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1494 root_objectid, owner, offset,
1498 btrfs_abort_transaction(trans, ret);
1500 btrfs_free_path(path);
1504 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1505 struct btrfs_delayed_ref_node *node,
1506 struct btrfs_delayed_extent_op *extent_op,
1507 int insert_reserved)
1510 struct btrfs_delayed_data_ref *ref;
1511 struct btrfs_key ins;
1516 ins.objectid = node->bytenr;
1517 ins.offset = node->num_bytes;
1518 ins.type = BTRFS_EXTENT_ITEM_KEY;
1520 ref = btrfs_delayed_node_to_data_ref(node);
1521 trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
1523 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1524 parent = ref->parent;
1525 ref_root = ref->root;
1527 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1529 flags |= extent_op->flags_to_set;
1530 ret = alloc_reserved_file_extent(trans, parent, ref_root,
1531 flags, ref->objectid,
1534 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1535 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
1536 ref->objectid, ref->offset,
1537 node->ref_mod, extent_op);
1538 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1539 ret = __btrfs_free_extent(trans, node, parent,
1540 ref_root, ref->objectid,
1541 ref->offset, node->ref_mod,
1549 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1550 struct extent_buffer *leaf,
1551 struct btrfs_extent_item *ei)
1553 u64 flags = btrfs_extent_flags(leaf, ei);
1554 if (extent_op->update_flags) {
1555 flags |= extent_op->flags_to_set;
1556 btrfs_set_extent_flags(leaf, ei, flags);
1559 if (extent_op->update_key) {
1560 struct btrfs_tree_block_info *bi;
1561 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1562 bi = (struct btrfs_tree_block_info *)(ei + 1);
1563 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1567 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1568 struct btrfs_delayed_ref_head *head,
1569 struct btrfs_delayed_extent_op *extent_op)
1571 struct btrfs_fs_info *fs_info = trans->fs_info;
1572 struct btrfs_key key;
1573 struct btrfs_path *path;
1574 struct btrfs_extent_item *ei;
1575 struct extent_buffer *leaf;
1579 int metadata = !extent_op->is_data;
1581 if (TRANS_ABORTED(trans))
1584 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1587 path = btrfs_alloc_path();
1591 key.objectid = head->bytenr;
1594 key.type = BTRFS_METADATA_ITEM_KEY;
1595 key.offset = extent_op->level;
1597 key.type = BTRFS_EXTENT_ITEM_KEY;
1598 key.offset = head->num_bytes;
1602 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
1609 if (path->slots[0] > 0) {
1611 btrfs_item_key_to_cpu(path->nodes[0], &key,
1613 if (key.objectid == head->bytenr &&
1614 key.type == BTRFS_EXTENT_ITEM_KEY &&
1615 key.offset == head->num_bytes)
1619 btrfs_release_path(path);
1622 key.objectid = head->bytenr;
1623 key.offset = head->num_bytes;
1624 key.type = BTRFS_EXTENT_ITEM_KEY;
1633 leaf = path->nodes[0];
1634 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1636 if (unlikely(item_size < sizeof(*ei))) {
1638 btrfs_print_v0_err(fs_info);
1639 btrfs_abort_transaction(trans, err);
1643 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1644 __run_delayed_extent_op(extent_op, leaf, ei);
1646 btrfs_mark_buffer_dirty(leaf);
1648 btrfs_free_path(path);
1652 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
1653 struct btrfs_delayed_ref_node *node,
1654 struct btrfs_delayed_extent_op *extent_op,
1655 int insert_reserved)
1658 struct btrfs_delayed_tree_ref *ref;
1662 ref = btrfs_delayed_node_to_tree_ref(node);
1663 trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
1665 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1666 parent = ref->parent;
1667 ref_root = ref->root;
1669 if (node->ref_mod != 1) {
1670 btrfs_err(trans->fs_info,
1671 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
1672 node->bytenr, node->ref_mod, node->action, ref_root,
1676 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1677 BUG_ON(!extent_op || !extent_op->update_flags);
1678 ret = alloc_reserved_tree_block(trans, node, extent_op);
1679 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1680 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
1681 ref->level, 0, 1, extent_op);
1682 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1683 ret = __btrfs_free_extent(trans, node, parent, ref_root,
1684 ref->level, 0, 1, extent_op);
1691 /* helper function to actually process a single delayed ref entry */
1692 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
1693 struct btrfs_delayed_ref_node *node,
1694 struct btrfs_delayed_extent_op *extent_op,
1695 int insert_reserved)
1699 if (TRANS_ABORTED(trans)) {
1700 if (insert_reserved)
1701 btrfs_pin_extent(trans, node->bytenr, node->num_bytes, 1);
1705 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
1706 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1707 ret = run_delayed_tree_ref(trans, node, extent_op,
1709 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
1710 node->type == BTRFS_SHARED_DATA_REF_KEY)
1711 ret = run_delayed_data_ref(trans, node, extent_op,
1715 if (ret && insert_reserved)
1716 btrfs_pin_extent(trans, node->bytenr, node->num_bytes, 1);
1720 static inline struct btrfs_delayed_ref_node *
1721 select_delayed_ref(struct btrfs_delayed_ref_head *head)
1723 struct btrfs_delayed_ref_node *ref;
1725 if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
1729 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
1730 * This is to prevent a ref count from going down to zero, which deletes
1731 * the extent item from the extent tree, when there still are references
1732 * to add, which would fail because they would not find the extent item.
1734 if (!list_empty(&head->ref_add_list))
1735 return list_first_entry(&head->ref_add_list,
1736 struct btrfs_delayed_ref_node, add_list);
1738 ref = rb_entry(rb_first_cached(&head->ref_tree),
1739 struct btrfs_delayed_ref_node, ref_node);
1740 ASSERT(list_empty(&ref->add_list));
1744 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
1745 struct btrfs_delayed_ref_head *head)
1747 spin_lock(&delayed_refs->lock);
1748 head->processing = 0;
1749 delayed_refs->num_heads_ready++;
1750 spin_unlock(&delayed_refs->lock);
1751 btrfs_delayed_ref_unlock(head);
1754 static struct btrfs_delayed_extent_op *cleanup_extent_op(
1755 struct btrfs_delayed_ref_head *head)
1757 struct btrfs_delayed_extent_op *extent_op = head->extent_op;
1762 if (head->must_insert_reserved) {
1763 head->extent_op = NULL;
1764 btrfs_free_delayed_extent_op(extent_op);
1770 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
1771 struct btrfs_delayed_ref_head *head)
1773 struct btrfs_delayed_extent_op *extent_op;
1776 extent_op = cleanup_extent_op(head);
1779 head->extent_op = NULL;
1780 spin_unlock(&head->lock);
1781 ret = run_delayed_extent_op(trans, head, extent_op);
1782 btrfs_free_delayed_extent_op(extent_op);
1783 return ret ? ret : 1;
1786 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
1787 struct btrfs_delayed_ref_root *delayed_refs,
1788 struct btrfs_delayed_ref_head *head)
1790 int nr_items = 1; /* Dropping this ref head update. */
1793 * We had csum deletions accounted for in our delayed refs rsv, we need
1794 * to drop the csum leaves for this update from our delayed_refs_rsv.
1796 if (head->total_ref_mod < 0 && head->is_data) {
1797 spin_lock(&delayed_refs->lock);
1798 delayed_refs->pending_csums -= head->num_bytes;
1799 spin_unlock(&delayed_refs->lock);
1800 nr_items += btrfs_csum_bytes_to_leaves(fs_info, head->num_bytes);
1804 * We were dropping refs, or had a new ref and dropped it, and thus must
1805 * adjust down our total_bytes_pinned, the space may or may not have
1806 * been pinned and so is accounted for properly in the pinned space by
1809 if (head->total_ref_mod < 0 ||
1810 (head->total_ref_mod == 0 && head->must_insert_reserved)) {
1811 u64 flags = btrfs_ref_head_to_space_flags(head);
1813 btrfs_mod_total_bytes_pinned(fs_info, flags, -head->num_bytes);
1816 btrfs_delayed_refs_rsv_release(fs_info, nr_items);
1819 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
1820 struct btrfs_delayed_ref_head *head)
1823 struct btrfs_fs_info *fs_info = trans->fs_info;
1824 struct btrfs_delayed_ref_root *delayed_refs;
1827 delayed_refs = &trans->transaction->delayed_refs;
1829 ret = run_and_cleanup_extent_op(trans, head);
1831 unselect_delayed_ref_head(delayed_refs, head);
1832 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
1839 * Need to drop our head ref lock and re-acquire the delayed ref lock
1840 * and then re-check to make sure nobody got added.
1842 spin_unlock(&head->lock);
1843 spin_lock(&delayed_refs->lock);
1844 spin_lock(&head->lock);
1845 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
1846 spin_unlock(&head->lock);
1847 spin_unlock(&delayed_refs->lock);
1850 btrfs_delete_ref_head(delayed_refs, head);
1851 spin_unlock(&head->lock);
1852 spin_unlock(&delayed_refs->lock);
1854 if (head->must_insert_reserved) {
1855 btrfs_pin_extent(trans, head->bytenr, head->num_bytes, 1);
1856 if (head->is_data) {
1857 ret = btrfs_del_csums(trans, fs_info->csum_root,
1858 head->bytenr, head->num_bytes);
1862 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
1864 trace_run_delayed_ref_head(fs_info, head, 0);
1865 btrfs_delayed_ref_unlock(head);
1866 btrfs_put_delayed_ref_head(head);
1870 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
1871 struct btrfs_trans_handle *trans)
1873 struct btrfs_delayed_ref_root *delayed_refs =
1874 &trans->transaction->delayed_refs;
1875 struct btrfs_delayed_ref_head *head = NULL;
1878 spin_lock(&delayed_refs->lock);
1879 head = btrfs_select_ref_head(delayed_refs);
1881 spin_unlock(&delayed_refs->lock);
1886 * Grab the lock that says we are going to process all the refs for
1889 ret = btrfs_delayed_ref_lock(delayed_refs, head);
1890 spin_unlock(&delayed_refs->lock);
1893 * We may have dropped the spin lock to get the head mutex lock, and
1894 * that might have given someone else time to free the head. If that's
1895 * true, it has been removed from our list and we can move on.
1898 head = ERR_PTR(-EAGAIN);
1903 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
1904 struct btrfs_delayed_ref_head *locked_ref,
1905 unsigned long *run_refs)
1907 struct btrfs_fs_info *fs_info = trans->fs_info;
1908 struct btrfs_delayed_ref_root *delayed_refs;
1909 struct btrfs_delayed_extent_op *extent_op;
1910 struct btrfs_delayed_ref_node *ref;
1911 int must_insert_reserved = 0;
1914 delayed_refs = &trans->transaction->delayed_refs;
1916 lockdep_assert_held(&locked_ref->mutex);
1917 lockdep_assert_held(&locked_ref->lock);
1919 while ((ref = select_delayed_ref(locked_ref))) {
1921 btrfs_check_delayed_seq(fs_info, ref->seq)) {
1922 spin_unlock(&locked_ref->lock);
1923 unselect_delayed_ref_head(delayed_refs, locked_ref);
1929 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
1930 RB_CLEAR_NODE(&ref->ref_node);
1931 if (!list_empty(&ref->add_list))
1932 list_del(&ref->add_list);
1934 * When we play the delayed ref, also correct the ref_mod on
1937 switch (ref->action) {
1938 case BTRFS_ADD_DELAYED_REF:
1939 case BTRFS_ADD_DELAYED_EXTENT:
1940 locked_ref->ref_mod -= ref->ref_mod;
1942 case BTRFS_DROP_DELAYED_REF:
1943 locked_ref->ref_mod += ref->ref_mod;
1948 atomic_dec(&delayed_refs->num_entries);
1951 * Record the must_insert_reserved flag before we drop the
1954 must_insert_reserved = locked_ref->must_insert_reserved;
1955 locked_ref->must_insert_reserved = 0;
1957 extent_op = locked_ref->extent_op;
1958 locked_ref->extent_op = NULL;
1959 spin_unlock(&locked_ref->lock);
1961 ret = run_one_delayed_ref(trans, ref, extent_op,
1962 must_insert_reserved);
1964 btrfs_free_delayed_extent_op(extent_op);
1966 unselect_delayed_ref_head(delayed_refs, locked_ref);
1967 btrfs_put_delayed_ref(ref);
1968 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
1973 btrfs_put_delayed_ref(ref);
1976 spin_lock(&locked_ref->lock);
1977 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
1984 * Returns 0 on success or if called with an already aborted transaction.
1985 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
1987 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
1990 struct btrfs_fs_info *fs_info = trans->fs_info;
1991 struct btrfs_delayed_ref_root *delayed_refs;
1992 struct btrfs_delayed_ref_head *locked_ref = NULL;
1993 ktime_t start = ktime_get();
1995 unsigned long count = 0;
1996 unsigned long actual_count = 0;
1998 delayed_refs = &trans->transaction->delayed_refs;
2001 locked_ref = btrfs_obtain_ref_head(trans);
2002 if (IS_ERR_OR_NULL(locked_ref)) {
2003 if (PTR_ERR(locked_ref) == -EAGAIN) {
2012 * We need to try and merge add/drops of the same ref since we
2013 * can run into issues with relocate dropping the implicit ref
2014 * and then it being added back again before the drop can
2015 * finish. If we merged anything we need to re-loop so we can
2017 * Or we can get node references of the same type that weren't
2018 * merged when created due to bumps in the tree mod seq, and
2019 * we need to merge them to prevent adding an inline extent
2020 * backref before dropping it (triggering a BUG_ON at
2021 * insert_inline_extent_backref()).
2023 spin_lock(&locked_ref->lock);
2024 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2026 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2028 if (ret < 0 && ret != -EAGAIN) {
2030 * Error, btrfs_run_delayed_refs_for_head already
2031 * unlocked everything so just bail out
2036 * Success, perform the usual cleanup of a processed
2039 ret = cleanup_ref_head(trans, locked_ref);
2041 /* We dropped our lock, we need to loop. */
2050 * Either success case or btrfs_run_delayed_refs_for_head
2051 * returned -EAGAIN, meaning we need to select another head
2056 } while ((nr != -1 && count < nr) || locked_ref);
2059 * We don't want to include ref heads since we can have empty ref heads
2060 * and those will drastically skew our runtime down since we just do
2061 * accounting, no actual extent tree updates.
2063 if (actual_count > 0) {
2064 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2068 * We weigh the current average higher than our current runtime
2069 * to avoid large swings in the average.
2071 spin_lock(&delayed_refs->lock);
2072 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2073 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2074 spin_unlock(&delayed_refs->lock);
2079 #ifdef SCRAMBLE_DELAYED_REFS
2081 * Normally delayed refs get processed in ascending bytenr order. This
2082 * correlates in most cases to the order added. To expose dependencies on this
2083 * order, we start to process the tree in the middle instead of the beginning
2085 static u64 find_middle(struct rb_root *root)
2087 struct rb_node *n = root->rb_node;
2088 struct btrfs_delayed_ref_node *entry;
2091 u64 first = 0, last = 0;
2095 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2096 first = entry->bytenr;
2100 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2101 last = entry->bytenr;
2106 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2107 WARN_ON(!entry->in_tree);
2109 middle = entry->bytenr;
2123 * this starts processing the delayed reference count updates and
2124 * extent insertions we have queued up so far. count can be
2125 * 0, which means to process everything in the tree at the start
2126 * of the run (but not newly added entries), or it can be some target
2127 * number you'd like to process.
2129 * Returns 0 on success or if called with an aborted transaction
2130 * Returns <0 on error and aborts the transaction
2132 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2133 unsigned long count)
2135 struct btrfs_fs_info *fs_info = trans->fs_info;
2136 struct rb_node *node;
2137 struct btrfs_delayed_ref_root *delayed_refs;
2138 struct btrfs_delayed_ref_head *head;
2140 int run_all = count == (unsigned long)-1;
2142 /* We'll clean this up in btrfs_cleanup_transaction */
2143 if (TRANS_ABORTED(trans))
2146 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2149 delayed_refs = &trans->transaction->delayed_refs;
2151 count = delayed_refs->num_heads_ready;
2154 #ifdef SCRAMBLE_DELAYED_REFS
2155 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2157 ret = __btrfs_run_delayed_refs(trans, count);
2159 btrfs_abort_transaction(trans, ret);
2164 btrfs_create_pending_block_groups(trans);
2166 spin_lock(&delayed_refs->lock);
2167 node = rb_first_cached(&delayed_refs->href_root);
2169 spin_unlock(&delayed_refs->lock);
2172 head = rb_entry(node, struct btrfs_delayed_ref_head,
2174 refcount_inc(&head->refs);
2175 spin_unlock(&delayed_refs->lock);
2177 /* Mutex was contended, block until it's released and retry. */
2178 mutex_lock(&head->mutex);
2179 mutex_unlock(&head->mutex);
2181 btrfs_put_delayed_ref_head(head);
2189 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2190 struct extent_buffer *eb, u64 flags,
2191 int level, int is_data)
2193 struct btrfs_delayed_extent_op *extent_op;
2196 extent_op = btrfs_alloc_delayed_extent_op();
2200 extent_op->flags_to_set = flags;
2201 extent_op->update_flags = true;
2202 extent_op->update_key = false;
2203 extent_op->is_data = is_data ? true : false;
2204 extent_op->level = level;
2206 ret = btrfs_add_delayed_extent_op(trans, eb->start, eb->len, extent_op);
2208 btrfs_free_delayed_extent_op(extent_op);
2212 static noinline int check_delayed_ref(struct btrfs_root *root,
2213 struct btrfs_path *path,
2214 u64 objectid, u64 offset, u64 bytenr)
2216 struct btrfs_delayed_ref_head *head;
2217 struct btrfs_delayed_ref_node *ref;
2218 struct btrfs_delayed_data_ref *data_ref;
2219 struct btrfs_delayed_ref_root *delayed_refs;
2220 struct btrfs_transaction *cur_trans;
2221 struct rb_node *node;
2224 spin_lock(&root->fs_info->trans_lock);
2225 cur_trans = root->fs_info->running_transaction;
2227 refcount_inc(&cur_trans->use_count);
2228 spin_unlock(&root->fs_info->trans_lock);
2232 delayed_refs = &cur_trans->delayed_refs;
2233 spin_lock(&delayed_refs->lock);
2234 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2236 spin_unlock(&delayed_refs->lock);
2237 btrfs_put_transaction(cur_trans);
2241 if (!mutex_trylock(&head->mutex)) {
2242 refcount_inc(&head->refs);
2243 spin_unlock(&delayed_refs->lock);
2245 btrfs_release_path(path);
2248 * Mutex was contended, block until it's released and let
2251 mutex_lock(&head->mutex);
2252 mutex_unlock(&head->mutex);
2253 btrfs_put_delayed_ref_head(head);
2254 btrfs_put_transaction(cur_trans);
2257 spin_unlock(&delayed_refs->lock);
2259 spin_lock(&head->lock);
2261 * XXX: We should replace this with a proper search function in the
2264 for (node = rb_first_cached(&head->ref_tree); node;
2265 node = rb_next(node)) {
2266 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
2267 /* If it's a shared ref we know a cross reference exists */
2268 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2273 data_ref = btrfs_delayed_node_to_data_ref(ref);
2276 * If our ref doesn't match the one we're currently looking at
2277 * then we have a cross reference.
2279 if (data_ref->root != root->root_key.objectid ||
2280 data_ref->objectid != objectid ||
2281 data_ref->offset != offset) {
2286 spin_unlock(&head->lock);
2287 mutex_unlock(&head->mutex);
2288 btrfs_put_transaction(cur_trans);
2292 static noinline int check_committed_ref(struct btrfs_root *root,
2293 struct btrfs_path *path,
2294 u64 objectid, u64 offset, u64 bytenr,
2297 struct btrfs_fs_info *fs_info = root->fs_info;
2298 struct btrfs_root *extent_root = fs_info->extent_root;
2299 struct extent_buffer *leaf;
2300 struct btrfs_extent_data_ref *ref;
2301 struct btrfs_extent_inline_ref *iref;
2302 struct btrfs_extent_item *ei;
2303 struct btrfs_key key;
2308 key.objectid = bytenr;
2309 key.offset = (u64)-1;
2310 key.type = BTRFS_EXTENT_ITEM_KEY;
2312 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2315 BUG_ON(ret == 0); /* Corruption */
2318 if (path->slots[0] == 0)
2322 leaf = path->nodes[0];
2323 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2325 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2329 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2330 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2332 /* If extent item has more than 1 inline ref then it's shared */
2333 if (item_size != sizeof(*ei) +
2334 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2338 * If extent created before last snapshot => it's shared unless the
2339 * snapshot has been deleted. Use the heuristic if strict is false.
2342 (btrfs_extent_generation(leaf, ei) <=
2343 btrfs_root_last_snapshot(&root->root_item)))
2346 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2348 /* If this extent has SHARED_DATA_REF then it's shared */
2349 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
2350 if (type != BTRFS_EXTENT_DATA_REF_KEY)
2353 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2354 if (btrfs_extent_refs(leaf, ei) !=
2355 btrfs_extent_data_ref_count(leaf, ref) ||
2356 btrfs_extent_data_ref_root(leaf, ref) !=
2357 root->root_key.objectid ||
2358 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2359 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2367 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
2368 u64 bytenr, bool strict)
2370 struct btrfs_path *path;
2373 path = btrfs_alloc_path();
2378 ret = check_committed_ref(root, path, objectid,
2379 offset, bytenr, strict);
2380 if (ret && ret != -ENOENT)
2383 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
2384 } while (ret == -EAGAIN);
2387 btrfs_free_path(path);
2388 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2393 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2394 struct btrfs_root *root,
2395 struct extent_buffer *buf,
2396 int full_backref, int inc)
2398 struct btrfs_fs_info *fs_info = root->fs_info;
2404 struct btrfs_key key;
2405 struct btrfs_file_extent_item *fi;
2406 struct btrfs_ref generic_ref = { 0 };
2407 bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
2413 if (btrfs_is_testing(fs_info))
2416 ref_root = btrfs_header_owner(buf);
2417 nritems = btrfs_header_nritems(buf);
2418 level = btrfs_header_level(buf);
2420 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state) && level == 0)
2424 parent = buf->start;
2428 action = BTRFS_ADD_DELAYED_REF;
2430 action = BTRFS_DROP_DELAYED_REF;
2432 for (i = 0; i < nritems; i++) {
2434 btrfs_item_key_to_cpu(buf, &key, i);
2435 if (key.type != BTRFS_EXTENT_DATA_KEY)
2437 fi = btrfs_item_ptr(buf, i,
2438 struct btrfs_file_extent_item);
2439 if (btrfs_file_extent_type(buf, fi) ==
2440 BTRFS_FILE_EXTENT_INLINE)
2442 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2446 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2447 key.offset -= btrfs_file_extent_offset(buf, fi);
2448 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2450 generic_ref.real_root = root->root_key.objectid;
2451 btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
2453 generic_ref.skip_qgroup = for_reloc;
2455 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2457 ret = btrfs_free_extent(trans, &generic_ref);
2461 bytenr = btrfs_node_blockptr(buf, i);
2462 num_bytes = fs_info->nodesize;
2463 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2465 generic_ref.real_root = root->root_key.objectid;
2466 btrfs_init_tree_ref(&generic_ref, level - 1, ref_root);
2467 generic_ref.skip_qgroup = for_reloc;
2469 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2471 ret = btrfs_free_extent(trans, &generic_ref);
2481 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2482 struct extent_buffer *buf, int full_backref)
2484 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
2487 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2488 struct extent_buffer *buf, int full_backref)
2490 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2493 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
2495 struct btrfs_fs_info *fs_info = root->fs_info;
2500 flags = BTRFS_BLOCK_GROUP_DATA;
2501 else if (root == fs_info->chunk_root)
2502 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2504 flags = BTRFS_BLOCK_GROUP_METADATA;
2506 ret = btrfs_get_alloc_profile(fs_info, flags);
2510 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
2512 struct btrfs_block_group *cache;
2515 spin_lock(&fs_info->block_group_cache_lock);
2516 bytenr = fs_info->first_logical_byte;
2517 spin_unlock(&fs_info->block_group_cache_lock);
2519 if (bytenr < (u64)-1)
2522 cache = btrfs_lookup_first_block_group(fs_info, search_start);
2526 bytenr = cache->start;
2527 btrfs_put_block_group(cache);
2532 static int pin_down_extent(struct btrfs_trans_handle *trans,
2533 struct btrfs_block_group *cache,
2534 u64 bytenr, u64 num_bytes, int reserved)
2536 struct btrfs_fs_info *fs_info = cache->fs_info;
2538 spin_lock(&cache->space_info->lock);
2539 spin_lock(&cache->lock);
2540 cache->pinned += num_bytes;
2541 btrfs_space_info_update_bytes_pinned(fs_info, cache->space_info,
2544 cache->reserved -= num_bytes;
2545 cache->space_info->bytes_reserved -= num_bytes;
2547 spin_unlock(&cache->lock);
2548 spin_unlock(&cache->space_info->lock);
2550 __btrfs_mod_total_bytes_pinned(cache->space_info, num_bytes);
2551 set_extent_dirty(&trans->transaction->pinned_extents, bytenr,
2552 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
2556 int btrfs_pin_extent(struct btrfs_trans_handle *trans,
2557 u64 bytenr, u64 num_bytes, int reserved)
2559 struct btrfs_block_group *cache;
2561 cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
2562 BUG_ON(!cache); /* Logic error */
2564 pin_down_extent(trans, cache, bytenr, num_bytes, reserved);
2566 btrfs_put_block_group(cache);
2571 * this function must be called within transaction
2573 int btrfs_pin_extent_for_log_replay(struct btrfs_trans_handle *trans,
2574 u64 bytenr, u64 num_bytes)
2576 struct btrfs_block_group *cache;
2579 cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
2584 * pull in the free space cache (if any) so that our pin
2585 * removes the free space from the cache. We have load_only set
2586 * to one because the slow code to read in the free extents does check
2587 * the pinned extents.
2589 btrfs_cache_block_group(cache, 1);
2591 * Make sure we wait until the cache is completely built in case it is
2592 * missing or is invalid and therefore needs to be rebuilt.
2594 ret = btrfs_wait_block_group_cache_done(cache);
2598 pin_down_extent(trans, cache, bytenr, num_bytes, 0);
2600 /* remove us from the free space cache (if we're there at all) */
2601 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
2603 btrfs_put_block_group(cache);
2607 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
2608 u64 start, u64 num_bytes)
2611 struct btrfs_block_group *block_group;
2613 block_group = btrfs_lookup_block_group(fs_info, start);
2617 btrfs_cache_block_group(block_group, 1);
2619 * Make sure we wait until the cache is completely built in case it is
2620 * missing or is invalid and therefore needs to be rebuilt.
2622 ret = btrfs_wait_block_group_cache_done(block_group);
2626 ret = btrfs_remove_free_space(block_group, start, num_bytes);
2628 btrfs_put_block_group(block_group);
2632 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
2634 struct btrfs_fs_info *fs_info = eb->fs_info;
2635 struct btrfs_file_extent_item *item;
2636 struct btrfs_key key;
2641 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
2644 for (i = 0; i < btrfs_header_nritems(eb); i++) {
2645 btrfs_item_key_to_cpu(eb, &key, i);
2646 if (key.type != BTRFS_EXTENT_DATA_KEY)
2648 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
2649 found_type = btrfs_file_extent_type(eb, item);
2650 if (found_type == BTRFS_FILE_EXTENT_INLINE)
2652 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
2654 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
2655 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
2656 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
2665 btrfs_inc_block_group_reservations(struct btrfs_block_group *bg)
2667 atomic_inc(&bg->reservations);
2671 * Returns the free cluster for the given space info and sets empty_cluster to
2672 * what it should be based on the mount options.
2674 static struct btrfs_free_cluster *
2675 fetch_cluster_info(struct btrfs_fs_info *fs_info,
2676 struct btrfs_space_info *space_info, u64 *empty_cluster)
2678 struct btrfs_free_cluster *ret = NULL;
2681 if (btrfs_mixed_space_info(space_info))
2684 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
2685 ret = &fs_info->meta_alloc_cluster;
2686 if (btrfs_test_opt(fs_info, SSD))
2687 *empty_cluster = SZ_2M;
2689 *empty_cluster = SZ_64K;
2690 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
2691 btrfs_test_opt(fs_info, SSD_SPREAD)) {
2692 *empty_cluster = SZ_2M;
2693 ret = &fs_info->data_alloc_cluster;
2699 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
2701 const bool return_free_space)
2703 struct btrfs_block_group *cache = NULL;
2704 struct btrfs_space_info *space_info;
2705 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2706 struct btrfs_free_cluster *cluster = NULL;
2708 u64 total_unpinned = 0;
2709 u64 empty_cluster = 0;
2712 while (start <= end) {
2715 start >= cache->start + cache->length) {
2717 btrfs_put_block_group(cache);
2719 cache = btrfs_lookup_block_group(fs_info, start);
2720 BUG_ON(!cache); /* Logic error */
2722 cluster = fetch_cluster_info(fs_info,
2725 empty_cluster <<= 1;
2728 len = cache->start + cache->length - start;
2729 len = min(len, end + 1 - start);
2731 down_read(&fs_info->commit_root_sem);
2732 if (start < cache->last_byte_to_unpin && return_free_space) {
2733 u64 add_len = min(len, cache->last_byte_to_unpin - start);
2735 btrfs_add_free_space(cache, start, add_len);
2737 up_read(&fs_info->commit_root_sem);
2740 total_unpinned += len;
2741 space_info = cache->space_info;
2744 * If this space cluster has been marked as fragmented and we've
2745 * unpinned enough in this block group to potentially allow a
2746 * cluster to be created inside of it go ahead and clear the
2749 if (cluster && cluster->fragmented &&
2750 total_unpinned > empty_cluster) {
2751 spin_lock(&cluster->lock);
2752 cluster->fragmented = 0;
2753 spin_unlock(&cluster->lock);
2756 spin_lock(&space_info->lock);
2757 spin_lock(&cache->lock);
2758 cache->pinned -= len;
2759 btrfs_space_info_update_bytes_pinned(fs_info, space_info, -len);
2760 space_info->max_extent_size = 0;
2761 __btrfs_mod_total_bytes_pinned(space_info, -len);
2763 space_info->bytes_readonly += len;
2765 } else if (btrfs_is_zoned(fs_info)) {
2766 /* Need reset before reusing in a zoned block group */
2767 space_info->bytes_zone_unusable += len;
2770 spin_unlock(&cache->lock);
2771 if (!readonly && return_free_space &&
2772 global_rsv->space_info == space_info) {
2775 spin_lock(&global_rsv->lock);
2776 if (!global_rsv->full) {
2777 to_add = min(len, global_rsv->size -
2778 global_rsv->reserved);
2779 global_rsv->reserved += to_add;
2780 btrfs_space_info_update_bytes_may_use(fs_info,
2781 space_info, to_add);
2782 if (global_rsv->reserved >= global_rsv->size)
2783 global_rsv->full = 1;
2786 spin_unlock(&global_rsv->lock);
2788 /* Add to any tickets we may have */
2789 if (!readonly && return_free_space && len)
2790 btrfs_try_granting_tickets(fs_info, space_info);
2791 spin_unlock(&space_info->lock);
2795 btrfs_put_block_group(cache);
2799 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
2801 struct btrfs_fs_info *fs_info = trans->fs_info;
2802 struct btrfs_block_group *block_group, *tmp;
2803 struct list_head *deleted_bgs;
2804 struct extent_io_tree *unpin;
2809 unpin = &trans->transaction->pinned_extents;
2811 while (!TRANS_ABORTED(trans)) {
2812 struct extent_state *cached_state = NULL;
2814 mutex_lock(&fs_info->unused_bg_unpin_mutex);
2815 ret = find_first_extent_bit(unpin, 0, &start, &end,
2816 EXTENT_DIRTY, &cached_state);
2818 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2822 if (btrfs_test_opt(fs_info, DISCARD_SYNC))
2823 ret = btrfs_discard_extent(fs_info, start,
2824 end + 1 - start, NULL);
2826 clear_extent_dirty(unpin, start, end, &cached_state);
2827 unpin_extent_range(fs_info, start, end, true);
2828 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2829 free_extent_state(cached_state);
2833 if (btrfs_test_opt(fs_info, DISCARD_ASYNC)) {
2834 btrfs_discard_calc_delay(&fs_info->discard_ctl);
2835 btrfs_discard_schedule_work(&fs_info->discard_ctl, true);
2839 * Transaction is finished. We don't need the lock anymore. We
2840 * do need to clean up the block groups in case of a transaction
2843 deleted_bgs = &trans->transaction->deleted_bgs;
2844 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
2848 if (!TRANS_ABORTED(trans))
2849 ret = btrfs_discard_extent(fs_info,
2851 block_group->length,
2854 list_del_init(&block_group->bg_list);
2855 btrfs_unfreeze_block_group(block_group);
2856 btrfs_put_block_group(block_group);
2859 const char *errstr = btrfs_decode_error(ret);
2861 "discard failed while removing blockgroup: errno=%d %s",
2870 * Drop one or more refs of @node.
2872 * 1. Locate the extent refs.
2873 * It's either inline in EXTENT/METADATA_ITEM or in keyed SHARED_* item.
2874 * Locate it, then reduce the refs number or remove the ref line completely.
2876 * 2. Update the refs count in EXTENT/METADATA_ITEM
2878 * Inline backref case:
2880 * in extent tree we have:
2882 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
2883 * refs 2 gen 6 flags DATA
2884 * extent data backref root FS_TREE objectid 258 offset 0 count 1
2885 * extent data backref root FS_TREE objectid 257 offset 0 count 1
2887 * This function gets called with:
2889 * node->bytenr = 13631488
2890 * node->num_bytes = 1048576
2891 * root_objectid = FS_TREE
2892 * owner_objectid = 257
2896 * Then we should get some like:
2898 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
2899 * refs 1 gen 6 flags DATA
2900 * extent data backref root FS_TREE objectid 258 offset 0 count 1
2902 * Keyed backref case:
2904 * in extent tree we have:
2906 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
2907 * refs 754 gen 6 flags DATA
2909 * item 2 key (13631488 EXTENT_DATA_REF <HASH>) itemoff 3915 itemsize 28
2910 * extent data backref root FS_TREE objectid 866 offset 0 count 1
2912 * This function get called with:
2914 * node->bytenr = 13631488
2915 * node->num_bytes = 1048576
2916 * root_objectid = FS_TREE
2917 * owner_objectid = 866
2921 * Then we should get some like:
2923 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
2924 * refs 753 gen 6 flags DATA
2926 * And that (13631488 EXTENT_DATA_REF <HASH>) gets removed.
2928 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
2929 struct btrfs_delayed_ref_node *node, u64 parent,
2930 u64 root_objectid, u64 owner_objectid,
2931 u64 owner_offset, int refs_to_drop,
2932 struct btrfs_delayed_extent_op *extent_op)
2934 struct btrfs_fs_info *info = trans->fs_info;
2935 struct btrfs_key key;
2936 struct btrfs_path *path;
2937 struct btrfs_root *extent_root = info->extent_root;
2938 struct extent_buffer *leaf;
2939 struct btrfs_extent_item *ei;
2940 struct btrfs_extent_inline_ref *iref;
2943 int extent_slot = 0;
2944 int found_extent = 0;
2948 u64 bytenr = node->bytenr;
2949 u64 num_bytes = node->num_bytes;
2951 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
2953 path = btrfs_alloc_path();
2957 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
2959 if (!is_data && refs_to_drop != 1) {
2961 "invalid refs_to_drop, dropping more than 1 refs for tree block %llu refs_to_drop %u",
2962 node->bytenr, refs_to_drop);
2964 btrfs_abort_transaction(trans, ret);
2969 skinny_metadata = false;
2971 ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
2972 parent, root_objectid, owner_objectid,
2976 * Either the inline backref or the SHARED_DATA_REF/
2977 * SHARED_BLOCK_REF is found
2979 * Here is a quick path to locate EXTENT/METADATA_ITEM.
2980 * It's possible the EXTENT/METADATA_ITEM is near current slot.
2982 extent_slot = path->slots[0];
2983 while (extent_slot >= 0) {
2984 btrfs_item_key_to_cpu(path->nodes[0], &key,
2986 if (key.objectid != bytenr)
2988 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
2989 key.offset == num_bytes) {
2993 if (key.type == BTRFS_METADATA_ITEM_KEY &&
2994 key.offset == owner_objectid) {
2999 /* Quick path didn't find the EXTEMT/METADATA_ITEM */
3000 if (path->slots[0] - extent_slot > 5)
3005 if (!found_extent) {
3008 "invalid iref, no EXTENT/METADATA_ITEM found but has inline extent ref");
3009 btrfs_abort_transaction(trans, -EUCLEAN);
3012 /* Must be SHARED_* item, remove the backref first */
3013 ret = remove_extent_backref(trans, path, NULL,
3015 is_data, &last_ref);
3017 btrfs_abort_transaction(trans, ret);
3020 btrfs_release_path(path);
3022 /* Slow path to locate EXTENT/METADATA_ITEM */
3023 key.objectid = bytenr;
3024 key.type = BTRFS_EXTENT_ITEM_KEY;
3025 key.offset = num_bytes;
3027 if (!is_data && skinny_metadata) {
3028 key.type = BTRFS_METADATA_ITEM_KEY;
3029 key.offset = owner_objectid;
3032 ret = btrfs_search_slot(trans, extent_root,
3034 if (ret > 0 && skinny_metadata && path->slots[0]) {
3036 * Couldn't find our skinny metadata item,
3037 * see if we have ye olde extent item.
3040 btrfs_item_key_to_cpu(path->nodes[0], &key,
3042 if (key.objectid == bytenr &&
3043 key.type == BTRFS_EXTENT_ITEM_KEY &&
3044 key.offset == num_bytes)
3048 if (ret > 0 && skinny_metadata) {
3049 skinny_metadata = false;
3050 key.objectid = bytenr;
3051 key.type = BTRFS_EXTENT_ITEM_KEY;
3052 key.offset = num_bytes;
3053 btrfs_release_path(path);
3054 ret = btrfs_search_slot(trans, extent_root,
3060 "umm, got %d back from search, was looking for %llu",
3063 btrfs_print_leaf(path->nodes[0]);
3066 btrfs_abort_transaction(trans, ret);
3069 extent_slot = path->slots[0];
3071 } else if (WARN_ON(ret == -ENOENT)) {
3072 btrfs_print_leaf(path->nodes[0]);
3074 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
3075 bytenr, parent, root_objectid, owner_objectid,
3077 btrfs_abort_transaction(trans, ret);
3080 btrfs_abort_transaction(trans, ret);
3084 leaf = path->nodes[0];
3085 item_size = btrfs_item_size_nr(leaf, extent_slot);
3086 if (unlikely(item_size < sizeof(*ei))) {
3088 btrfs_print_v0_err(info);
3089 btrfs_abort_transaction(trans, ret);
3092 ei = btrfs_item_ptr(leaf, extent_slot,
3093 struct btrfs_extent_item);
3094 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
3095 key.type == BTRFS_EXTENT_ITEM_KEY) {
3096 struct btrfs_tree_block_info *bi;
3097 if (item_size < sizeof(*ei) + sizeof(*bi)) {
3099 "invalid extent item size for key (%llu, %u, %llu) owner %llu, has %u expect >= %zu",
3100 key.objectid, key.type, key.offset,
3101 owner_objectid, item_size,
3102 sizeof(*ei) + sizeof(*bi));
3103 btrfs_abort_transaction(trans, -EUCLEAN);
3106 bi = (struct btrfs_tree_block_info *)(ei + 1);
3107 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
3110 refs = btrfs_extent_refs(leaf, ei);
3111 if (refs < refs_to_drop) {
3113 "trying to drop %d refs but we only have %llu for bytenr %llu",
3114 refs_to_drop, refs, bytenr);
3115 btrfs_abort_transaction(trans, -EUCLEAN);
3118 refs -= refs_to_drop;
3122 __run_delayed_extent_op(extent_op, leaf, ei);
3124 * In the case of inline back ref, reference count will
3125 * be updated by remove_extent_backref
3128 if (!found_extent) {
3130 "invalid iref, got inlined extent ref but no EXTENT/METADATA_ITEM found");
3131 btrfs_abort_transaction(trans, -EUCLEAN);
3135 btrfs_set_extent_refs(leaf, ei, refs);
3136 btrfs_mark_buffer_dirty(leaf);
3139 ret = remove_extent_backref(trans, path, iref,
3140 refs_to_drop, is_data,
3143 btrfs_abort_transaction(trans, ret);
3148 /* In this branch refs == 1 */
3150 if (is_data && refs_to_drop !=
3151 extent_data_ref_count(path, iref)) {
3153 "invalid refs_to_drop, current refs %u refs_to_drop %u",
3154 extent_data_ref_count(path, iref),
3156 btrfs_abort_transaction(trans, -EUCLEAN);
3160 if (path->slots[0] != extent_slot) {
3162 "invalid iref, extent item key (%llu %u %llu) doesn't have wanted iref",
3163 key.objectid, key.type,
3165 btrfs_abort_transaction(trans, -EUCLEAN);
3170 * No inline ref, we must be at SHARED_* item,
3171 * And it's single ref, it must be:
3172 * | extent_slot ||extent_slot + 1|
3173 * [ EXTENT/METADATA_ITEM ][ SHARED_* ITEM ]
3175 if (path->slots[0] != extent_slot + 1) {
3177 "invalid SHARED_* item, previous item is not EXTENT/METADATA_ITEM");
3178 btrfs_abort_transaction(trans, -EUCLEAN);
3181 path->slots[0] = extent_slot;
3187 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
3190 btrfs_abort_transaction(trans, ret);
3193 btrfs_release_path(path);
3196 ret = btrfs_del_csums(trans, info->csum_root, bytenr,
3199 btrfs_abort_transaction(trans, ret);
3204 ret = add_to_free_space_tree(trans, bytenr, num_bytes);
3206 btrfs_abort_transaction(trans, ret);
3210 ret = btrfs_update_block_group(trans, bytenr, num_bytes, 0);
3212 btrfs_abort_transaction(trans, ret);
3216 btrfs_release_path(path);
3219 btrfs_free_path(path);
3223 * Leaf dump can take up a lot of log buffer, so we only do full leaf
3224 * dump for debug build.
3226 if (IS_ENABLED(CONFIG_BTRFS_DEBUG)) {
3227 btrfs_crit(info, "path->slots[0]=%d extent_slot=%d",
3228 path->slots[0], extent_slot);
3229 btrfs_print_leaf(path->nodes[0]);
3232 btrfs_free_path(path);
3237 * when we free an block, it is possible (and likely) that we free the last
3238 * delayed ref for that extent as well. This searches the delayed ref tree for
3239 * a given extent, and if there are no other delayed refs to be processed, it
3240 * removes it from the tree.
3242 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
3245 struct btrfs_delayed_ref_head *head;
3246 struct btrfs_delayed_ref_root *delayed_refs;
3249 delayed_refs = &trans->transaction->delayed_refs;
3250 spin_lock(&delayed_refs->lock);
3251 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
3253 goto out_delayed_unlock;
3255 spin_lock(&head->lock);
3256 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
3259 if (cleanup_extent_op(head) != NULL)
3263 * waiting for the lock here would deadlock. If someone else has it
3264 * locked they are already in the process of dropping it anyway
3266 if (!mutex_trylock(&head->mutex))
3269 btrfs_delete_ref_head(delayed_refs, head);
3270 head->processing = 0;
3272 spin_unlock(&head->lock);
3273 spin_unlock(&delayed_refs->lock);
3275 BUG_ON(head->extent_op);
3276 if (head->must_insert_reserved)
3279 btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
3280 mutex_unlock(&head->mutex);
3281 btrfs_put_delayed_ref_head(head);
3284 spin_unlock(&head->lock);
3287 spin_unlock(&delayed_refs->lock);
3291 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
3292 struct btrfs_root *root,
3293 struct extent_buffer *buf,
3294 u64 parent, int last_ref)
3296 struct btrfs_fs_info *fs_info = root->fs_info;
3297 struct btrfs_ref generic_ref = { 0 };
3300 btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
3301 buf->start, buf->len, parent);
3302 btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
3303 root->root_key.objectid);
3305 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
3306 btrfs_ref_tree_mod(fs_info, &generic_ref);
3307 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL);
3308 BUG_ON(ret); /* -ENOMEM */
3311 if (last_ref && btrfs_header_generation(buf) == trans->transid) {
3312 struct btrfs_block_group *cache;
3313 bool must_pin = false;
3315 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
3316 ret = check_ref_cleanup(trans, buf->start);
3318 btrfs_redirty_list_add(trans->transaction, buf);
3323 cache = btrfs_lookup_block_group(fs_info, buf->start);
3325 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
3326 pin_down_extent(trans, cache, buf->start, buf->len, 1);
3327 btrfs_put_block_group(cache);
3332 * If this is a leaf and there are tree mod log users, we may
3333 * have recorded mod log operations that point to this leaf.
3334 * So we must make sure no one reuses this leaf's extent before
3335 * mod log operations are applied to a node, otherwise after
3336 * rewinding a node using the mod log operations we get an
3337 * inconsistent btree, as the leaf's extent may now be used as
3338 * a node or leaf for another different btree.
3339 * We are safe from races here because at this point no other
3340 * node or root points to this extent buffer, so if after this
3341 * check a new tree mod log user joins, it will not be able to
3342 * find a node pointing to this leaf and record operations that
3343 * point to this leaf.
3345 if (btrfs_header_level(buf) == 0 &&
3346 test_bit(BTRFS_FS_TREE_MOD_LOG_USERS, &fs_info->flags))
3349 if (must_pin || btrfs_is_zoned(fs_info)) {
3350 btrfs_redirty_list_add(trans->transaction, buf);
3351 pin_down_extent(trans, cache, buf->start, buf->len, 1);
3352 btrfs_put_block_group(cache);
3356 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
3358 btrfs_add_free_space(cache, buf->start, buf->len);
3359 btrfs_free_reserved_bytes(cache, buf->len, 0);
3360 btrfs_put_block_group(cache);
3361 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
3366 * Deleting the buffer, clear the corrupt flag since it doesn't
3369 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
3373 /* Can return -ENOMEM */
3374 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
3376 struct btrfs_fs_info *fs_info = trans->fs_info;
3379 if (btrfs_is_testing(fs_info))
3383 * tree log blocks never actually go into the extent allocation
3384 * tree, just update pinning info and exit early.
3386 if ((ref->type == BTRFS_REF_METADATA &&
3387 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
3388 (ref->type == BTRFS_REF_DATA &&
3389 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)) {
3390 /* unlocks the pinned mutex */
3391 btrfs_pin_extent(trans, ref->bytenr, ref->len, 1);
3393 } else if (ref->type == BTRFS_REF_METADATA) {
3394 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL);
3396 ret = btrfs_add_delayed_data_ref(trans, ref, 0);
3399 if (!((ref->type == BTRFS_REF_METADATA &&
3400 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
3401 (ref->type == BTRFS_REF_DATA &&
3402 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)))
3403 btrfs_ref_tree_mod(fs_info, ref);
3408 enum btrfs_loop_type {
3409 LOOP_CACHING_NOWAIT,
3416 btrfs_lock_block_group(struct btrfs_block_group *cache,
3420 down_read(&cache->data_rwsem);
3423 static inline void btrfs_grab_block_group(struct btrfs_block_group *cache,
3426 btrfs_get_block_group(cache);
3428 down_read(&cache->data_rwsem);
3431 static struct btrfs_block_group *btrfs_lock_cluster(
3432 struct btrfs_block_group *block_group,
3433 struct btrfs_free_cluster *cluster,
3435 __acquires(&cluster->refill_lock)
3437 struct btrfs_block_group *used_bg = NULL;
3439 spin_lock(&cluster->refill_lock);
3441 used_bg = cluster->block_group;
3445 if (used_bg == block_group)
3448 btrfs_get_block_group(used_bg);
3453 if (down_read_trylock(&used_bg->data_rwsem))
3456 spin_unlock(&cluster->refill_lock);
3458 /* We should only have one-level nested. */
3459 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
3461 spin_lock(&cluster->refill_lock);
3462 if (used_bg == cluster->block_group)
3465 up_read(&used_bg->data_rwsem);
3466 btrfs_put_block_group(used_bg);
3471 btrfs_release_block_group(struct btrfs_block_group *cache,
3475 up_read(&cache->data_rwsem);
3476 btrfs_put_block_group(cache);
3479 enum btrfs_extent_allocation_policy {
3480 BTRFS_EXTENT_ALLOC_CLUSTERED,
3481 BTRFS_EXTENT_ALLOC_ZONED,
3485 * Structure used internally for find_free_extent() function. Wraps needed
3488 struct find_free_extent_ctl {
3489 /* Basic allocation info */
3495 /* Where to start the search inside the bg */
3498 /* For clustered allocation */
3500 struct btrfs_free_cluster *last_ptr;
3503 bool have_caching_bg;
3504 bool orig_have_caching_bg;
3506 /* Allocation is called for tree-log */
3509 /* RAID index, converted from flags */
3513 * Current loop number, check find_free_extent_update_loop() for details
3518 * Whether we're refilling a cluster, if true we need to re-search
3519 * current block group but don't try to refill the cluster again.
3521 bool retry_clustered;
3524 * Whether we're updating free space cache, if true we need to re-search
3525 * current block group but don't try updating free space cache again.
3527 bool retry_unclustered;
3529 /* If current block group is cached */
3532 /* Max contiguous hole found */
3533 u64 max_extent_size;
3535 /* Total free space from free space cache, not always contiguous */
3536 u64 total_free_space;
3541 /* Hint where to start looking for an empty space */
3544 /* Allocation policy */
3545 enum btrfs_extent_allocation_policy policy;
3550 * Helper function for find_free_extent().
3552 * Return -ENOENT to inform caller that we need fallback to unclustered mode.
3553 * Return -EAGAIN to inform caller that we need to re-search this block group
3554 * Return >0 to inform caller that we find nothing
3555 * Return 0 means we have found a location and set ffe_ctl->found_offset.
3557 static int find_free_extent_clustered(struct btrfs_block_group *bg,
3558 struct find_free_extent_ctl *ffe_ctl,
3559 struct btrfs_block_group **cluster_bg_ret)
3561 struct btrfs_block_group *cluster_bg;
3562 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3563 u64 aligned_cluster;
3567 cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
3569 goto refill_cluster;
3570 if (cluster_bg != bg && (cluster_bg->ro ||
3571 !block_group_bits(cluster_bg, ffe_ctl->flags)))
3572 goto release_cluster;
3574 offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
3575 ffe_ctl->num_bytes, cluster_bg->start,
3576 &ffe_ctl->max_extent_size);
3578 /* We have a block, we're done */
3579 spin_unlock(&last_ptr->refill_lock);
3580 trace_btrfs_reserve_extent_cluster(cluster_bg,
3581 ffe_ctl->search_start, ffe_ctl->num_bytes);
3582 *cluster_bg_ret = cluster_bg;
3583 ffe_ctl->found_offset = offset;
3586 WARN_ON(last_ptr->block_group != cluster_bg);
3590 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
3591 * lets just skip it and let the allocator find whatever block it can
3592 * find. If we reach this point, we will have tried the cluster
3593 * allocator plenty of times and not have found anything, so we are
3594 * likely way too fragmented for the clustering stuff to find anything.
3596 * However, if the cluster is taken from the current block group,
3597 * release the cluster first, so that we stand a better chance of
3598 * succeeding in the unclustered allocation.
3600 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
3601 spin_unlock(&last_ptr->refill_lock);
3602 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3606 /* This cluster didn't work out, free it and start over */
3607 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3609 if (cluster_bg != bg)
3610 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3613 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
3614 spin_unlock(&last_ptr->refill_lock);
3618 aligned_cluster = max_t(u64,
3619 ffe_ctl->empty_cluster + ffe_ctl->empty_size,
3620 bg->full_stripe_len);
3621 ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
3622 ffe_ctl->num_bytes, aligned_cluster);
3624 /* Now pull our allocation out of this cluster */
3625 offset = btrfs_alloc_from_cluster(bg, last_ptr,
3626 ffe_ctl->num_bytes, ffe_ctl->search_start,
3627 &ffe_ctl->max_extent_size);
3629 /* We found one, proceed */
3630 spin_unlock(&last_ptr->refill_lock);
3631 trace_btrfs_reserve_extent_cluster(bg,
3632 ffe_ctl->search_start,
3633 ffe_ctl->num_bytes);
3634 ffe_ctl->found_offset = offset;
3637 } else if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
3638 !ffe_ctl->retry_clustered) {
3639 spin_unlock(&last_ptr->refill_lock);
3641 ffe_ctl->retry_clustered = true;
3642 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3643 ffe_ctl->empty_cluster + ffe_ctl->empty_size);
3647 * At this point we either didn't find a cluster or we weren't able to
3648 * allocate a block from our cluster. Free the cluster we've been
3649 * trying to use, and go to the next block group.
3651 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3652 spin_unlock(&last_ptr->refill_lock);
3657 * Return >0 to inform caller that we find nothing
3658 * Return 0 when we found an free extent and set ffe_ctrl->found_offset
3659 * Return -EAGAIN to inform caller that we need to re-search this block group
3661 static int find_free_extent_unclustered(struct btrfs_block_group *bg,
3662 struct find_free_extent_ctl *ffe_ctl)
3664 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3668 * We are doing an unclustered allocation, set the fragmented flag so
3669 * we don't bother trying to setup a cluster again until we get more
3672 if (unlikely(last_ptr)) {
3673 spin_lock(&last_ptr->lock);
3674 last_ptr->fragmented = 1;
3675 spin_unlock(&last_ptr->lock);
3677 if (ffe_ctl->cached) {
3678 struct btrfs_free_space_ctl *free_space_ctl;
3680 free_space_ctl = bg->free_space_ctl;
3681 spin_lock(&free_space_ctl->tree_lock);
3682 if (free_space_ctl->free_space <
3683 ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
3684 ffe_ctl->empty_size) {
3685 ffe_ctl->total_free_space = max_t(u64,
3686 ffe_ctl->total_free_space,
3687 free_space_ctl->free_space);
3688 spin_unlock(&free_space_ctl->tree_lock);
3691 spin_unlock(&free_space_ctl->tree_lock);
3694 offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
3695 ffe_ctl->num_bytes, ffe_ctl->empty_size,
3696 &ffe_ctl->max_extent_size);
3699 * If we didn't find a chunk, and we haven't failed on this block group
3700 * before, and this block group is in the middle of caching and we are
3701 * ok with waiting, then go ahead and wait for progress to be made, and
3702 * set @retry_unclustered to true.
3704 * If @retry_unclustered is true then we've already waited on this
3705 * block group once and should move on to the next block group.
3707 if (!offset && !ffe_ctl->retry_unclustered && !ffe_ctl->cached &&
3708 ffe_ctl->loop > LOOP_CACHING_NOWAIT) {
3709 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3710 ffe_ctl->empty_size);
3711 ffe_ctl->retry_unclustered = true;
3713 } else if (!offset) {
3716 ffe_ctl->found_offset = offset;
3720 static int do_allocation_clustered(struct btrfs_block_group *block_group,
3721 struct find_free_extent_ctl *ffe_ctl,
3722 struct btrfs_block_group **bg_ret)
3726 /* We want to try and use the cluster allocator, so lets look there */
3727 if (ffe_ctl->last_ptr && ffe_ctl->use_cluster) {
3728 ret = find_free_extent_clustered(block_group, ffe_ctl, bg_ret);
3729 if (ret >= 0 || ret == -EAGAIN)
3731 /* ret == -ENOENT case falls through */
3734 return find_free_extent_unclustered(block_group, ffe_ctl);
3738 * Tree-log block group locking
3739 * ============================
3741 * fs_info::treelog_bg_lock protects the fs_info::treelog_bg which
3742 * indicates the starting address of a block group, which is reserved only
3743 * for tree-log metadata.
3750 * fs_info::treelog_bg_lock
3754 * Simple allocator for sequential-only block group. It only allows sequential
3755 * allocation. No need to play with trees. This function also reserves the
3756 * bytes as in btrfs_add_reserved_bytes.
3758 static int do_allocation_zoned(struct btrfs_block_group *block_group,
3759 struct find_free_extent_ctl *ffe_ctl,
3760 struct btrfs_block_group **bg_ret)
3762 struct btrfs_fs_info *fs_info = block_group->fs_info;
3763 struct btrfs_space_info *space_info = block_group->space_info;
3764 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3765 u64 start = block_group->start;
3766 u64 num_bytes = ffe_ctl->num_bytes;
3768 u64 bytenr = block_group->start;
3773 ASSERT(btrfs_is_zoned(block_group->fs_info));
3776 * Do not allow non-tree-log blocks in the dedicated tree-log block
3777 * group, and vice versa.
3779 spin_lock(&fs_info->treelog_bg_lock);
3780 log_bytenr = fs_info->treelog_bg;
3781 skip = log_bytenr && ((ffe_ctl->for_treelog && bytenr != log_bytenr) ||
3782 (!ffe_ctl->for_treelog && bytenr == log_bytenr));
3783 spin_unlock(&fs_info->treelog_bg_lock);
3787 spin_lock(&space_info->lock);
3788 spin_lock(&block_group->lock);
3789 spin_lock(&fs_info->treelog_bg_lock);
3791 ASSERT(!ffe_ctl->for_treelog ||
3792 block_group->start == fs_info->treelog_bg ||
3793 fs_info->treelog_bg == 0);
3795 if (block_group->ro) {
3801 * Do not allow currently using block group to be tree-log dedicated
3804 if (ffe_ctl->for_treelog && !fs_info->treelog_bg &&
3805 (block_group->used || block_group->reserved)) {
3810 avail = block_group->length - block_group->alloc_offset;
3811 if (avail < num_bytes) {
3812 if (ffe_ctl->max_extent_size < avail) {
3814 * With sequential allocator, free space is always
3817 ffe_ctl->max_extent_size = avail;
3818 ffe_ctl->total_free_space = avail;
3824 if (ffe_ctl->for_treelog && !fs_info->treelog_bg)
3825 fs_info->treelog_bg = block_group->start;
3827 ffe_ctl->found_offset = start + block_group->alloc_offset;
3828 block_group->alloc_offset += num_bytes;
3829 spin_lock(&ctl->tree_lock);
3830 ctl->free_space -= num_bytes;
3831 spin_unlock(&ctl->tree_lock);
3834 * We do not check if found_offset is aligned to stripesize. The
3835 * address is anyway rewritten when using zone append writing.
3838 ffe_ctl->search_start = ffe_ctl->found_offset;
3841 if (ret && ffe_ctl->for_treelog)
3842 fs_info->treelog_bg = 0;
3843 spin_unlock(&fs_info->treelog_bg_lock);
3844 spin_unlock(&block_group->lock);
3845 spin_unlock(&space_info->lock);
3849 static int do_allocation(struct btrfs_block_group *block_group,
3850 struct find_free_extent_ctl *ffe_ctl,
3851 struct btrfs_block_group **bg_ret)
3853 switch (ffe_ctl->policy) {
3854 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3855 return do_allocation_clustered(block_group, ffe_ctl, bg_ret);
3856 case BTRFS_EXTENT_ALLOC_ZONED:
3857 return do_allocation_zoned(block_group, ffe_ctl, bg_ret);
3863 static void release_block_group(struct btrfs_block_group *block_group,
3864 struct find_free_extent_ctl *ffe_ctl,
3867 switch (ffe_ctl->policy) {
3868 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3869 ffe_ctl->retry_clustered = false;
3870 ffe_ctl->retry_unclustered = false;
3872 case BTRFS_EXTENT_ALLOC_ZONED:
3879 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
3881 btrfs_release_block_group(block_group, delalloc);
3884 static void found_extent_clustered(struct find_free_extent_ctl *ffe_ctl,
3885 struct btrfs_key *ins)
3887 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3889 if (!ffe_ctl->use_cluster && last_ptr) {
3890 spin_lock(&last_ptr->lock);
3891 last_ptr->window_start = ins->objectid;
3892 spin_unlock(&last_ptr->lock);
3896 static void found_extent(struct find_free_extent_ctl *ffe_ctl,
3897 struct btrfs_key *ins)
3899 switch (ffe_ctl->policy) {
3900 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3901 found_extent_clustered(ffe_ctl, ins);
3903 case BTRFS_EXTENT_ALLOC_ZONED:
3911 static int chunk_allocation_failed(struct find_free_extent_ctl *ffe_ctl)
3913 switch (ffe_ctl->policy) {
3914 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3916 * If we can't allocate a new chunk we've already looped through
3917 * at least once, move on to the NO_EMPTY_SIZE case.
3919 ffe_ctl->loop = LOOP_NO_EMPTY_SIZE;
3921 case BTRFS_EXTENT_ALLOC_ZONED:
3930 * Return >0 means caller needs to re-search for free extent
3931 * Return 0 means we have the needed free extent.
3932 * Return <0 means we failed to locate any free extent.
3934 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
3935 struct btrfs_key *ins,
3936 struct find_free_extent_ctl *ffe_ctl,
3939 struct btrfs_root *root = fs_info->extent_root;
3942 if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
3943 ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
3944 ffe_ctl->orig_have_caching_bg = true;
3946 if (!ins->objectid && ffe_ctl->loop >= LOOP_CACHING_WAIT &&
3947 ffe_ctl->have_caching_bg)
3950 if (!ins->objectid && ++(ffe_ctl->index) < BTRFS_NR_RAID_TYPES)
3953 if (ins->objectid) {
3954 found_extent(ffe_ctl, ins);
3959 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
3960 * caching kthreads as we move along
3961 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
3962 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
3963 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
3966 if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
3968 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT) {
3970 * We want to skip the LOOP_CACHING_WAIT step if we
3971 * don't have any uncached bgs and we've already done a
3972 * full search through.
3974 if (ffe_ctl->orig_have_caching_bg || !full_search)
3975 ffe_ctl->loop = LOOP_CACHING_WAIT;
3977 ffe_ctl->loop = LOOP_ALLOC_CHUNK;
3982 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
3983 struct btrfs_trans_handle *trans;
3986 trans = current->journal_info;
3990 trans = btrfs_join_transaction(root);
3992 if (IS_ERR(trans)) {
3993 ret = PTR_ERR(trans);
3997 ret = btrfs_chunk_alloc(trans, ffe_ctl->flags,
4000 /* Do not bail out on ENOSPC since we can do more. */
4002 ret = chunk_allocation_failed(ffe_ctl);
4004 btrfs_abort_transaction(trans, ret);
4008 btrfs_end_transaction(trans);
4013 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
4014 if (ffe_ctl->policy != BTRFS_EXTENT_ALLOC_CLUSTERED)
4018 * Don't loop again if we already have no empty_size and
4021 if (ffe_ctl->empty_size == 0 &&
4022 ffe_ctl->empty_cluster == 0)
4024 ffe_ctl->empty_size = 0;
4025 ffe_ctl->empty_cluster = 0;
4032 static int prepare_allocation_clustered(struct btrfs_fs_info *fs_info,
4033 struct find_free_extent_ctl *ffe_ctl,
4034 struct btrfs_space_info *space_info,
4035 struct btrfs_key *ins)
4038 * If our free space is heavily fragmented we may not be able to make
4039 * big contiguous allocations, so instead of doing the expensive search
4040 * for free space, simply return ENOSPC with our max_extent_size so we
4041 * can go ahead and search for a more manageable chunk.
4043 * If our max_extent_size is large enough for our allocation simply
4044 * disable clustering since we will likely not be able to find enough
4045 * space to create a cluster and induce latency trying.
4047 if (space_info->max_extent_size) {
4048 spin_lock(&space_info->lock);
4049 if (space_info->max_extent_size &&
4050 ffe_ctl->num_bytes > space_info->max_extent_size) {
4051 ins->offset = space_info->max_extent_size;
4052 spin_unlock(&space_info->lock);
4054 } else if (space_info->max_extent_size) {
4055 ffe_ctl->use_cluster = false;
4057 spin_unlock(&space_info->lock);
4060 ffe_ctl->last_ptr = fetch_cluster_info(fs_info, space_info,
4061 &ffe_ctl->empty_cluster);
4062 if (ffe_ctl->last_ptr) {
4063 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
4065 spin_lock(&last_ptr->lock);
4066 if (last_ptr->block_group)
4067 ffe_ctl->hint_byte = last_ptr->window_start;
4068 if (last_ptr->fragmented) {
4070 * We still set window_start so we can keep track of the
4071 * last place we found an allocation to try and save
4074 ffe_ctl->hint_byte = last_ptr->window_start;
4075 ffe_ctl->use_cluster = false;
4077 spin_unlock(&last_ptr->lock);
4083 static int prepare_allocation(struct btrfs_fs_info *fs_info,
4084 struct find_free_extent_ctl *ffe_ctl,
4085 struct btrfs_space_info *space_info,
4086 struct btrfs_key *ins)
4088 switch (ffe_ctl->policy) {
4089 case BTRFS_EXTENT_ALLOC_CLUSTERED:
4090 return prepare_allocation_clustered(fs_info, ffe_ctl,
4092 case BTRFS_EXTENT_ALLOC_ZONED:
4093 if (ffe_ctl->for_treelog) {
4094 spin_lock(&fs_info->treelog_bg_lock);
4095 if (fs_info->treelog_bg)
4096 ffe_ctl->hint_byte = fs_info->treelog_bg;
4097 spin_unlock(&fs_info->treelog_bg_lock);
4106 * walks the btree of allocated extents and find a hole of a given size.
4107 * The key ins is changed to record the hole:
4108 * ins->objectid == start position
4109 * ins->flags = BTRFS_EXTENT_ITEM_KEY
4110 * ins->offset == the size of the hole.
4111 * Any available blocks before search_start are skipped.
4113 * If there is no suitable free space, we will record the max size of
4114 * the free space extent currently.
4116 * The overall logic and call chain:
4118 * find_free_extent()
4119 * |- Iterate through all block groups
4120 * | |- Get a valid block group
4121 * | |- Try to do clustered allocation in that block group
4122 * | |- Try to do unclustered allocation in that block group
4123 * | |- Check if the result is valid
4124 * | | |- If valid, then exit
4125 * | |- Jump to next block group
4127 * |- Push harder to find free extents
4128 * |- If not found, re-iterate all block groups
4130 static noinline int find_free_extent(struct btrfs_root *root,
4131 u64 ram_bytes, u64 num_bytes, u64 empty_size,
4132 u64 hint_byte_orig, struct btrfs_key *ins,
4133 u64 flags, int delalloc)
4135 struct btrfs_fs_info *fs_info = root->fs_info;
4137 int cache_block_group_error = 0;
4138 struct btrfs_block_group *block_group = NULL;
4139 struct find_free_extent_ctl ffe_ctl = {0};
4140 struct btrfs_space_info *space_info;
4141 bool full_search = false;
4142 bool for_treelog = (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
4144 WARN_ON(num_bytes < fs_info->sectorsize);
4146 ffe_ctl.num_bytes = num_bytes;
4147 ffe_ctl.empty_size = empty_size;
4148 ffe_ctl.flags = flags;
4149 ffe_ctl.search_start = 0;
4150 ffe_ctl.delalloc = delalloc;
4151 ffe_ctl.index = btrfs_bg_flags_to_raid_index(flags);
4152 ffe_ctl.have_caching_bg = false;
4153 ffe_ctl.orig_have_caching_bg = false;
4154 ffe_ctl.found_offset = 0;
4155 ffe_ctl.hint_byte = hint_byte_orig;
4156 ffe_ctl.for_treelog = for_treelog;
4157 ffe_ctl.policy = BTRFS_EXTENT_ALLOC_CLUSTERED;
4159 /* For clustered allocation */
4160 ffe_ctl.retry_clustered = false;
4161 ffe_ctl.retry_unclustered = false;
4162 ffe_ctl.last_ptr = NULL;
4163 ffe_ctl.use_cluster = true;
4165 if (btrfs_is_zoned(fs_info))
4166 ffe_ctl.policy = BTRFS_EXTENT_ALLOC_ZONED;
4168 ins->type = BTRFS_EXTENT_ITEM_KEY;
4172 trace_find_free_extent(root, num_bytes, empty_size, flags);
4174 space_info = btrfs_find_space_info(fs_info, flags);
4176 btrfs_err(fs_info, "No space info for %llu", flags);
4180 ret = prepare_allocation(fs_info, &ffe_ctl, space_info, ins);
4184 ffe_ctl.search_start = max(ffe_ctl.search_start,
4185 first_logical_byte(fs_info, 0));
4186 ffe_ctl.search_start = max(ffe_ctl.search_start, ffe_ctl.hint_byte);
4187 if (ffe_ctl.search_start == ffe_ctl.hint_byte) {
4188 block_group = btrfs_lookup_block_group(fs_info,
4189 ffe_ctl.search_start);
4191 * we don't want to use the block group if it doesn't match our
4192 * allocation bits, or if its not cached.
4194 * However if we are re-searching with an ideal block group
4195 * picked out then we don't care that the block group is cached.
4197 if (block_group && block_group_bits(block_group, flags) &&
4198 block_group->cached != BTRFS_CACHE_NO) {
4199 down_read(&space_info->groups_sem);
4200 if (list_empty(&block_group->list) ||
4203 * someone is removing this block group,
4204 * we can't jump into the have_block_group
4205 * target because our list pointers are not
4208 btrfs_put_block_group(block_group);
4209 up_read(&space_info->groups_sem);
4211 ffe_ctl.index = btrfs_bg_flags_to_raid_index(
4212 block_group->flags);
4213 btrfs_lock_block_group(block_group, delalloc);
4214 goto have_block_group;
4216 } else if (block_group) {
4217 btrfs_put_block_group(block_group);
4221 ffe_ctl.have_caching_bg = false;
4222 if (ffe_ctl.index == btrfs_bg_flags_to_raid_index(flags) ||
4225 down_read(&space_info->groups_sem);
4226 list_for_each_entry(block_group,
4227 &space_info->block_groups[ffe_ctl.index], list) {
4228 struct btrfs_block_group *bg_ret;
4230 /* If the block group is read-only, we can skip it entirely. */
4231 if (unlikely(block_group->ro)) {
4233 btrfs_clear_treelog_bg(block_group);
4237 btrfs_grab_block_group(block_group, delalloc);
4238 ffe_ctl.search_start = block_group->start;
4241 * this can happen if we end up cycling through all the
4242 * raid types, but we want to make sure we only allocate
4243 * for the proper type.
4245 if (!block_group_bits(block_group, flags)) {
4246 u64 extra = BTRFS_BLOCK_GROUP_DUP |
4247 BTRFS_BLOCK_GROUP_RAID1_MASK |
4248 BTRFS_BLOCK_GROUP_RAID56_MASK |
4249 BTRFS_BLOCK_GROUP_RAID10;
4252 * if they asked for extra copies and this block group
4253 * doesn't provide them, bail. This does allow us to
4254 * fill raid0 from raid1.
4256 if ((flags & extra) && !(block_group->flags & extra))
4260 * This block group has different flags than we want.
4261 * It's possible that we have MIXED_GROUP flag but no
4262 * block group is mixed. Just skip such block group.
4264 btrfs_release_block_group(block_group, delalloc);
4269 ffe_ctl.cached = btrfs_block_group_done(block_group);
4270 if (unlikely(!ffe_ctl.cached)) {
4271 ffe_ctl.have_caching_bg = true;
4272 ret = btrfs_cache_block_group(block_group, 0);
4275 * If we get ENOMEM here or something else we want to
4276 * try other block groups, because it may not be fatal.
4277 * However if we can't find anything else we need to
4278 * save our return here so that we return the actual
4279 * error that caused problems, not ENOSPC.
4282 if (!cache_block_group_error)
4283 cache_block_group_error = ret;
4290 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
4294 ret = do_allocation(block_group, &ffe_ctl, &bg_ret);
4296 if (bg_ret && bg_ret != block_group) {
4297 btrfs_release_block_group(block_group, delalloc);
4298 block_group = bg_ret;
4300 } else if (ret == -EAGAIN) {
4301 goto have_block_group;
4302 } else if (ret > 0) {
4307 ffe_ctl.search_start = round_up(ffe_ctl.found_offset,
4308 fs_info->stripesize);
4310 /* move on to the next group */
4311 if (ffe_ctl.search_start + num_bytes >
4312 block_group->start + block_group->length) {
4313 btrfs_add_free_space_unused(block_group,
4314 ffe_ctl.found_offset, num_bytes);
4318 if (ffe_ctl.found_offset < ffe_ctl.search_start)
4319 btrfs_add_free_space_unused(block_group,
4320 ffe_ctl.found_offset,
4321 ffe_ctl.search_start - ffe_ctl.found_offset);
4323 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
4324 num_bytes, delalloc);
4325 if (ret == -EAGAIN) {
4326 btrfs_add_free_space_unused(block_group,
4327 ffe_ctl.found_offset, num_bytes);
4330 btrfs_inc_block_group_reservations(block_group);
4332 /* we are all good, lets return */
4333 ins->objectid = ffe_ctl.search_start;
4334 ins->offset = num_bytes;
4336 trace_btrfs_reserve_extent(block_group, ffe_ctl.search_start,
4338 btrfs_release_block_group(block_group, delalloc);
4341 release_block_group(block_group, &ffe_ctl, delalloc);
4344 up_read(&space_info->groups_sem);
4346 ret = find_free_extent_update_loop(fs_info, ins, &ffe_ctl, full_search);
4350 if (ret == -ENOSPC && !cache_block_group_error) {
4352 * Use ffe_ctl->total_free_space as fallback if we can't find
4353 * any contiguous hole.
4355 if (!ffe_ctl.max_extent_size)
4356 ffe_ctl.max_extent_size = ffe_ctl.total_free_space;
4357 spin_lock(&space_info->lock);
4358 space_info->max_extent_size = ffe_ctl.max_extent_size;
4359 spin_unlock(&space_info->lock);
4360 ins->offset = ffe_ctl.max_extent_size;
4361 } else if (ret == -ENOSPC) {
4362 ret = cache_block_group_error;
4368 * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
4369 * hole that is at least as big as @num_bytes.
4371 * @root - The root that will contain this extent
4373 * @ram_bytes - The amount of space in ram that @num_bytes take. This
4374 * is used for accounting purposes. This value differs
4375 * from @num_bytes only in the case of compressed extents.
4377 * @num_bytes - Number of bytes to allocate on-disk.
4379 * @min_alloc_size - Indicates the minimum amount of space that the
4380 * allocator should try to satisfy. In some cases
4381 * @num_bytes may be larger than what is required and if
4382 * the filesystem is fragmented then allocation fails.
4383 * However, the presence of @min_alloc_size gives a
4384 * chance to try and satisfy the smaller allocation.
4386 * @empty_size - A hint that you plan on doing more COW. This is the
4387 * size in bytes the allocator should try to find free
4388 * next to the block it returns. This is just a hint and
4389 * may be ignored by the allocator.
4391 * @hint_byte - Hint to the allocator to start searching above the byte
4392 * address passed. It might be ignored.
4394 * @ins - This key is modified to record the found hole. It will
4395 * have the following values:
4396 * ins->objectid == start position
4397 * ins->flags = BTRFS_EXTENT_ITEM_KEY
4398 * ins->offset == the size of the hole.
4400 * @is_data - Boolean flag indicating whether an extent is
4401 * allocated for data (true) or metadata (false)
4403 * @delalloc - Boolean flag indicating whether this allocation is for
4404 * delalloc or not. If 'true' data_rwsem of block groups
4405 * is going to be acquired.
4408 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
4409 * case -ENOSPC is returned then @ins->offset will contain the size of the
4410 * largest available hole the allocator managed to find.
4412 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
4413 u64 num_bytes, u64 min_alloc_size,
4414 u64 empty_size, u64 hint_byte,
4415 struct btrfs_key *ins, int is_data, int delalloc)
4417 struct btrfs_fs_info *fs_info = root->fs_info;
4418 bool final_tried = num_bytes == min_alloc_size;
4421 bool for_treelog = (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
4423 flags = get_alloc_profile_by_root(root, is_data);
4425 WARN_ON(num_bytes < fs_info->sectorsize);
4426 ret = find_free_extent(root, ram_bytes, num_bytes, empty_size,
4427 hint_byte, ins, flags, delalloc);
4428 if (!ret && !is_data) {
4429 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
4430 } else if (ret == -ENOSPC) {
4431 if (!final_tried && ins->offset) {
4432 num_bytes = min(num_bytes >> 1, ins->offset);
4433 num_bytes = round_down(num_bytes,
4434 fs_info->sectorsize);
4435 num_bytes = max(num_bytes, min_alloc_size);
4436 ram_bytes = num_bytes;
4437 if (num_bytes == min_alloc_size)
4440 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4441 struct btrfs_space_info *sinfo;
4443 sinfo = btrfs_find_space_info(fs_info, flags);
4445 "allocation failed flags %llu, wanted %llu tree-log %d",
4446 flags, num_bytes, for_treelog);
4448 btrfs_dump_space_info(fs_info, sinfo,
4456 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
4457 u64 start, u64 len, int delalloc)
4459 struct btrfs_block_group *cache;
4461 cache = btrfs_lookup_block_group(fs_info, start);
4463 btrfs_err(fs_info, "Unable to find block group for %llu",
4468 btrfs_add_free_space(cache, start, len);
4469 btrfs_free_reserved_bytes(cache, len, delalloc);
4470 trace_btrfs_reserved_extent_free(fs_info, start, len);
4472 btrfs_put_block_group(cache);
4476 int btrfs_pin_reserved_extent(struct btrfs_trans_handle *trans, u64 start,
4479 struct btrfs_block_group *cache;
4482 cache = btrfs_lookup_block_group(trans->fs_info, start);
4484 btrfs_err(trans->fs_info, "unable to find block group for %llu",
4489 ret = pin_down_extent(trans, cache, start, len, 1);
4490 btrfs_put_block_group(cache);
4494 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4495 u64 parent, u64 root_objectid,
4496 u64 flags, u64 owner, u64 offset,
4497 struct btrfs_key *ins, int ref_mod)
4499 struct btrfs_fs_info *fs_info = trans->fs_info;
4501 struct btrfs_extent_item *extent_item;
4502 struct btrfs_extent_inline_ref *iref;
4503 struct btrfs_path *path;
4504 struct extent_buffer *leaf;
4509 type = BTRFS_SHARED_DATA_REF_KEY;
4511 type = BTRFS_EXTENT_DATA_REF_KEY;
4513 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
4515 path = btrfs_alloc_path();
4519 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4522 btrfs_free_path(path);
4526 leaf = path->nodes[0];
4527 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4528 struct btrfs_extent_item);
4529 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
4530 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4531 btrfs_set_extent_flags(leaf, extent_item,
4532 flags | BTRFS_EXTENT_FLAG_DATA);
4534 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4535 btrfs_set_extent_inline_ref_type(leaf, iref, type);
4537 struct btrfs_shared_data_ref *ref;
4538 ref = (struct btrfs_shared_data_ref *)(iref + 1);
4539 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
4540 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
4542 struct btrfs_extent_data_ref *ref;
4543 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
4544 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
4545 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
4546 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
4547 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
4550 btrfs_mark_buffer_dirty(path->nodes[0]);
4551 btrfs_free_path(path);
4553 ret = remove_from_free_space_tree(trans, ins->objectid, ins->offset);
4557 ret = btrfs_update_block_group(trans, ins->objectid, ins->offset, 1);
4558 if (ret) { /* -ENOENT, logic error */
4559 btrfs_err(fs_info, "update block group failed for %llu %llu",
4560 ins->objectid, ins->offset);
4563 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
4567 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
4568 struct btrfs_delayed_ref_node *node,
4569 struct btrfs_delayed_extent_op *extent_op)
4571 struct btrfs_fs_info *fs_info = trans->fs_info;
4573 struct btrfs_extent_item *extent_item;
4574 struct btrfs_key extent_key;
4575 struct btrfs_tree_block_info *block_info;
4576 struct btrfs_extent_inline_ref *iref;
4577 struct btrfs_path *path;
4578 struct extent_buffer *leaf;
4579 struct btrfs_delayed_tree_ref *ref;
4580 u32 size = sizeof(*extent_item) + sizeof(*iref);
4582 u64 flags = extent_op->flags_to_set;
4583 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4585 ref = btrfs_delayed_node_to_tree_ref(node);
4587 extent_key.objectid = node->bytenr;
4588 if (skinny_metadata) {
4589 extent_key.offset = ref->level;
4590 extent_key.type = BTRFS_METADATA_ITEM_KEY;
4591 num_bytes = fs_info->nodesize;
4593 extent_key.offset = node->num_bytes;
4594 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
4595 size += sizeof(*block_info);
4596 num_bytes = node->num_bytes;
4599 path = btrfs_alloc_path();
4603 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4606 btrfs_free_path(path);
4610 leaf = path->nodes[0];
4611 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4612 struct btrfs_extent_item);
4613 btrfs_set_extent_refs(leaf, extent_item, 1);
4614 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4615 btrfs_set_extent_flags(leaf, extent_item,
4616 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
4618 if (skinny_metadata) {
4619 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4621 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
4622 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
4623 btrfs_set_tree_block_level(leaf, block_info, ref->level);
4624 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
4627 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
4628 btrfs_set_extent_inline_ref_type(leaf, iref,
4629 BTRFS_SHARED_BLOCK_REF_KEY);
4630 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
4632 btrfs_set_extent_inline_ref_type(leaf, iref,
4633 BTRFS_TREE_BLOCK_REF_KEY);
4634 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
4637 btrfs_mark_buffer_dirty(leaf);
4638 btrfs_free_path(path);
4640 ret = remove_from_free_space_tree(trans, extent_key.objectid,
4645 ret = btrfs_update_block_group(trans, extent_key.objectid,
4646 fs_info->nodesize, 1);
4647 if (ret) { /* -ENOENT, logic error */
4648 btrfs_err(fs_info, "update block group failed for %llu %llu",
4649 extent_key.objectid, extent_key.offset);
4653 trace_btrfs_reserved_extent_alloc(fs_info, extent_key.objectid,
4658 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4659 struct btrfs_root *root, u64 owner,
4660 u64 offset, u64 ram_bytes,
4661 struct btrfs_key *ins)
4663 struct btrfs_ref generic_ref = { 0 };
4665 BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
4667 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4668 ins->objectid, ins->offset, 0);
4669 btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner, offset);
4670 btrfs_ref_tree_mod(root->fs_info, &generic_ref);
4672 return btrfs_add_delayed_data_ref(trans, &generic_ref, ram_bytes);
4676 * this is used by the tree logging recovery code. It records that
4677 * an extent has been allocated and makes sure to clear the free
4678 * space cache bits as well
4680 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
4681 u64 root_objectid, u64 owner, u64 offset,
4682 struct btrfs_key *ins)
4684 struct btrfs_fs_info *fs_info = trans->fs_info;
4686 struct btrfs_block_group *block_group;
4687 struct btrfs_space_info *space_info;
4690 * Mixed block groups will exclude before processing the log so we only
4691 * need to do the exclude dance if this fs isn't mixed.
4693 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
4694 ret = __exclude_logged_extent(fs_info, ins->objectid,
4700 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
4704 space_info = block_group->space_info;
4705 spin_lock(&space_info->lock);
4706 spin_lock(&block_group->lock);
4707 space_info->bytes_reserved += ins->offset;
4708 block_group->reserved += ins->offset;
4709 spin_unlock(&block_group->lock);
4710 spin_unlock(&space_info->lock);
4712 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
4715 btrfs_pin_extent(trans, ins->objectid, ins->offset, 1);
4716 btrfs_put_block_group(block_group);
4720 static struct extent_buffer *
4721 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4722 u64 bytenr, int level, u64 owner,
4723 enum btrfs_lock_nesting nest)
4725 struct btrfs_fs_info *fs_info = root->fs_info;
4726 struct extent_buffer *buf;
4728 buf = btrfs_find_create_tree_block(fs_info, bytenr, owner, level);
4733 * Extra safety check in case the extent tree is corrupted and extent
4734 * allocator chooses to use a tree block which is already used and
4737 if (buf->lock_owner == current->pid) {
4738 btrfs_err_rl(fs_info,
4739 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
4740 buf->start, btrfs_header_owner(buf), current->pid);
4741 free_extent_buffer(buf);
4742 return ERR_PTR(-EUCLEAN);
4746 * This needs to stay, because we could allocate a freed block from an
4747 * old tree into a new tree, so we need to make sure this new block is
4748 * set to the appropriate level and owner.
4750 btrfs_set_buffer_lockdep_class(owner, buf, level);
4751 __btrfs_tree_lock(buf, nest);
4752 btrfs_clean_tree_block(buf);
4753 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
4754 clear_bit(EXTENT_BUFFER_NO_CHECK, &buf->bflags);
4756 set_extent_buffer_uptodate(buf);
4758 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
4759 btrfs_set_header_level(buf, level);
4760 btrfs_set_header_bytenr(buf, buf->start);
4761 btrfs_set_header_generation(buf, trans->transid);
4762 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
4763 btrfs_set_header_owner(buf, owner);
4764 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
4765 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
4766 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
4767 buf->log_index = root->log_transid % 2;
4769 * we allow two log transactions at a time, use different
4770 * EXTENT bit to differentiate dirty pages.
4772 if (buf->log_index == 0)
4773 set_extent_dirty(&root->dirty_log_pages, buf->start,
4774 buf->start + buf->len - 1, GFP_NOFS);
4776 set_extent_new(&root->dirty_log_pages, buf->start,
4777 buf->start + buf->len - 1);
4779 buf->log_index = -1;
4780 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
4781 buf->start + buf->len - 1, GFP_NOFS);
4783 trans->dirty = true;
4784 /* this returns a buffer locked for blocking */
4789 * finds a free extent and does all the dirty work required for allocation
4790 * returns the tree buffer or an ERR_PTR on error.
4792 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
4793 struct btrfs_root *root,
4794 u64 parent, u64 root_objectid,
4795 const struct btrfs_disk_key *key,
4796 int level, u64 hint,
4798 enum btrfs_lock_nesting nest)
4800 struct btrfs_fs_info *fs_info = root->fs_info;
4801 struct btrfs_key ins;
4802 struct btrfs_block_rsv *block_rsv;
4803 struct extent_buffer *buf;
4804 struct btrfs_delayed_extent_op *extent_op;
4805 struct btrfs_ref generic_ref = { 0 };
4808 u32 blocksize = fs_info->nodesize;
4809 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4811 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4812 if (btrfs_is_testing(fs_info)) {
4813 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
4814 level, root_objectid, nest);
4816 root->alloc_bytenr += blocksize;
4821 block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
4822 if (IS_ERR(block_rsv))
4823 return ERR_CAST(block_rsv);
4825 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
4826 empty_size, hint, &ins, 0, 0);
4830 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
4831 root_objectid, nest);
4834 goto out_free_reserved;
4837 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
4839 parent = ins.objectid;
4840 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4844 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
4845 extent_op = btrfs_alloc_delayed_extent_op();
4851 memcpy(&extent_op->key, key, sizeof(extent_op->key));
4853 memset(&extent_op->key, 0, sizeof(extent_op->key));
4854 extent_op->flags_to_set = flags;
4855 extent_op->update_key = skinny_metadata ? false : true;
4856 extent_op->update_flags = true;
4857 extent_op->is_data = false;
4858 extent_op->level = level;
4860 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4861 ins.objectid, ins.offset, parent);
4862 generic_ref.real_root = root->root_key.objectid;
4863 btrfs_init_tree_ref(&generic_ref, level, root_objectid);
4864 btrfs_ref_tree_mod(fs_info, &generic_ref);
4865 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, extent_op);
4867 goto out_free_delayed;
4872 btrfs_free_delayed_extent_op(extent_op);
4874 free_extent_buffer(buf);
4876 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
4878 btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
4879 return ERR_PTR(ret);
4882 struct walk_control {
4883 u64 refs[BTRFS_MAX_LEVEL];
4884 u64 flags[BTRFS_MAX_LEVEL];
4885 struct btrfs_key update_progress;
4886 struct btrfs_key drop_progress;
4898 #define DROP_REFERENCE 1
4899 #define UPDATE_BACKREF 2
4901 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
4902 struct btrfs_root *root,
4903 struct walk_control *wc,
4904 struct btrfs_path *path)
4906 struct btrfs_fs_info *fs_info = root->fs_info;
4912 struct btrfs_key key;
4913 struct extent_buffer *eb;
4918 if (path->slots[wc->level] < wc->reada_slot) {
4919 wc->reada_count = wc->reada_count * 2 / 3;
4920 wc->reada_count = max(wc->reada_count, 2);
4922 wc->reada_count = wc->reada_count * 3 / 2;
4923 wc->reada_count = min_t(int, wc->reada_count,
4924 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
4927 eb = path->nodes[wc->level];
4928 nritems = btrfs_header_nritems(eb);
4930 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
4931 if (nread >= wc->reada_count)
4935 bytenr = btrfs_node_blockptr(eb, slot);
4936 generation = btrfs_node_ptr_generation(eb, slot);
4938 if (slot == path->slots[wc->level])
4941 if (wc->stage == UPDATE_BACKREF &&
4942 generation <= root->root_key.offset)
4945 /* We don't lock the tree block, it's OK to be racy here */
4946 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
4947 wc->level - 1, 1, &refs,
4949 /* We don't care about errors in readahead. */
4954 if (wc->stage == DROP_REFERENCE) {
4958 if (wc->level == 1 &&
4959 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4961 if (!wc->update_ref ||
4962 generation <= root->root_key.offset)
4964 btrfs_node_key_to_cpu(eb, &key, slot);
4965 ret = btrfs_comp_cpu_keys(&key,
4966 &wc->update_progress);
4970 if (wc->level == 1 &&
4971 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4975 btrfs_readahead_node_child(eb, slot);
4978 wc->reada_slot = slot;
4982 * helper to process tree block while walking down the tree.
4984 * when wc->stage == UPDATE_BACKREF, this function updates
4985 * back refs for pointers in the block.
4987 * NOTE: return value 1 means we should stop walking down.
4989 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
4990 struct btrfs_root *root,
4991 struct btrfs_path *path,
4992 struct walk_control *wc, int lookup_info)
4994 struct btrfs_fs_info *fs_info = root->fs_info;
4995 int level = wc->level;
4996 struct extent_buffer *eb = path->nodes[level];
4997 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5000 if (wc->stage == UPDATE_BACKREF &&
5001 btrfs_header_owner(eb) != root->root_key.objectid)
5005 * when reference count of tree block is 1, it won't increase
5006 * again. once full backref flag is set, we never clear it.
5009 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
5010 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
5011 BUG_ON(!path->locks[level]);
5012 ret = btrfs_lookup_extent_info(trans, fs_info,
5013 eb->start, level, 1,
5016 BUG_ON(ret == -ENOMEM);
5019 BUG_ON(wc->refs[level] == 0);
5022 if (wc->stage == DROP_REFERENCE) {
5023 if (wc->refs[level] > 1)
5026 if (path->locks[level] && !wc->keep_locks) {
5027 btrfs_tree_unlock_rw(eb, path->locks[level]);
5028 path->locks[level] = 0;
5033 /* wc->stage == UPDATE_BACKREF */
5034 if (!(wc->flags[level] & flag)) {
5035 BUG_ON(!path->locks[level]);
5036 ret = btrfs_inc_ref(trans, root, eb, 1);
5037 BUG_ON(ret); /* -ENOMEM */
5038 ret = btrfs_dec_ref(trans, root, eb, 0);
5039 BUG_ON(ret); /* -ENOMEM */
5040 ret = btrfs_set_disk_extent_flags(trans, eb, flag,
5041 btrfs_header_level(eb), 0);
5042 BUG_ON(ret); /* -ENOMEM */
5043 wc->flags[level] |= flag;
5047 * the block is shared by multiple trees, so it's not good to
5048 * keep the tree lock
5050 if (path->locks[level] && level > 0) {
5051 btrfs_tree_unlock_rw(eb, path->locks[level]);
5052 path->locks[level] = 0;
5058 * This is used to verify a ref exists for this root to deal with a bug where we
5059 * would have a drop_progress key that hadn't been updated properly.
5061 static int check_ref_exists(struct btrfs_trans_handle *trans,
5062 struct btrfs_root *root, u64 bytenr, u64 parent,
5065 struct btrfs_path *path;
5066 struct btrfs_extent_inline_ref *iref;
5069 path = btrfs_alloc_path();
5073 ret = lookup_extent_backref(trans, path, &iref, bytenr,
5074 root->fs_info->nodesize, parent,
5075 root->root_key.objectid, level, 0);
5076 btrfs_free_path(path);
5085 * helper to process tree block pointer.
5087 * when wc->stage == DROP_REFERENCE, this function checks
5088 * reference count of the block pointed to. if the block
5089 * is shared and we need update back refs for the subtree
5090 * rooted at the block, this function changes wc->stage to
5091 * UPDATE_BACKREF. if the block is shared and there is no
5092 * need to update back, this function drops the reference
5095 * NOTE: return value 1 means we should stop walking down.
5097 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
5098 struct btrfs_root *root,
5099 struct btrfs_path *path,
5100 struct walk_control *wc, int *lookup_info)
5102 struct btrfs_fs_info *fs_info = root->fs_info;
5106 struct btrfs_key key;
5107 struct btrfs_key first_key;
5108 struct btrfs_ref ref = { 0 };
5109 struct extent_buffer *next;
5110 int level = wc->level;
5113 bool need_account = false;
5115 generation = btrfs_node_ptr_generation(path->nodes[level],
5116 path->slots[level]);
5118 * if the lower level block was created before the snapshot
5119 * was created, we know there is no need to update back refs
5122 if (wc->stage == UPDATE_BACKREF &&
5123 generation <= root->root_key.offset) {
5128 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
5129 btrfs_node_key_to_cpu(path->nodes[level], &first_key,
5130 path->slots[level]);
5132 next = find_extent_buffer(fs_info, bytenr);
5134 next = btrfs_find_create_tree_block(fs_info, bytenr,
5135 root->root_key.objectid, level - 1);
5137 return PTR_ERR(next);
5140 btrfs_tree_lock(next);
5142 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
5143 &wc->refs[level - 1],
5144 &wc->flags[level - 1]);
5148 if (unlikely(wc->refs[level - 1] == 0)) {
5149 btrfs_err(fs_info, "Missing references.");
5155 if (wc->stage == DROP_REFERENCE) {
5156 if (wc->refs[level - 1] > 1) {
5157 need_account = true;
5159 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5162 if (!wc->update_ref ||
5163 generation <= root->root_key.offset)
5166 btrfs_node_key_to_cpu(path->nodes[level], &key,
5167 path->slots[level]);
5168 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
5172 wc->stage = UPDATE_BACKREF;
5173 wc->shared_level = level - 1;
5177 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5181 if (!btrfs_buffer_uptodate(next, generation, 0)) {
5182 btrfs_tree_unlock(next);
5183 free_extent_buffer(next);
5189 if (reada && level == 1)
5190 reada_walk_down(trans, root, wc, path);
5191 next = read_tree_block(fs_info, bytenr, root->root_key.objectid,
5192 generation, level - 1, &first_key);
5194 return PTR_ERR(next);
5195 } else if (!extent_buffer_uptodate(next)) {
5196 free_extent_buffer(next);
5199 btrfs_tree_lock(next);
5203 ASSERT(level == btrfs_header_level(next));
5204 if (level != btrfs_header_level(next)) {
5205 btrfs_err(root->fs_info, "mismatched level");
5209 path->nodes[level] = next;
5210 path->slots[level] = 0;
5211 path->locks[level] = BTRFS_WRITE_LOCK;
5217 wc->refs[level - 1] = 0;
5218 wc->flags[level - 1] = 0;
5219 if (wc->stage == DROP_REFERENCE) {
5220 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5221 parent = path->nodes[level]->start;
5223 ASSERT(root->root_key.objectid ==
5224 btrfs_header_owner(path->nodes[level]));
5225 if (root->root_key.objectid !=
5226 btrfs_header_owner(path->nodes[level])) {
5227 btrfs_err(root->fs_info,
5228 "mismatched block owner");
5236 * If we had a drop_progress we need to verify the refs are set
5237 * as expected. If we find our ref then we know that from here
5238 * on out everything should be correct, and we can clear the
5241 if (wc->restarted) {
5242 ret = check_ref_exists(trans, root, bytenr, parent,
5253 * Reloc tree doesn't contribute to qgroup numbers, and we have
5254 * already accounted them at merge time (replace_path),
5255 * thus we could skip expensive subtree trace here.
5257 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
5259 ret = btrfs_qgroup_trace_subtree(trans, next,
5260 generation, level - 1);
5262 btrfs_err_rl(fs_info,
5263 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
5269 * We need to update the next key in our walk control so we can
5270 * update the drop_progress key accordingly. We don't care if
5271 * find_next_key doesn't find a key because that means we're at
5272 * the end and are going to clean up now.
5274 wc->drop_level = level;
5275 find_next_key(path, level, &wc->drop_progress);
5277 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
5278 fs_info->nodesize, parent);
5279 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid);
5280 ret = btrfs_free_extent(trans, &ref);
5289 btrfs_tree_unlock(next);
5290 free_extent_buffer(next);
5296 * helper to process tree block while walking up the tree.
5298 * when wc->stage == DROP_REFERENCE, this function drops
5299 * reference count on the block.
5301 * when wc->stage == UPDATE_BACKREF, this function changes
5302 * wc->stage back to DROP_REFERENCE if we changed wc->stage
5303 * to UPDATE_BACKREF previously while processing the block.
5305 * NOTE: return value 1 means we should stop walking up.
5307 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
5308 struct btrfs_root *root,
5309 struct btrfs_path *path,
5310 struct walk_control *wc)
5312 struct btrfs_fs_info *fs_info = root->fs_info;
5314 int level = wc->level;
5315 struct extent_buffer *eb = path->nodes[level];
5318 if (wc->stage == UPDATE_BACKREF) {
5319 BUG_ON(wc->shared_level < level);
5320 if (level < wc->shared_level)
5323 ret = find_next_key(path, level + 1, &wc->update_progress);
5327 wc->stage = DROP_REFERENCE;
5328 wc->shared_level = -1;
5329 path->slots[level] = 0;
5332 * check reference count again if the block isn't locked.
5333 * we should start walking down the tree again if reference
5336 if (!path->locks[level]) {
5338 btrfs_tree_lock(eb);
5339 path->locks[level] = BTRFS_WRITE_LOCK;
5341 ret = btrfs_lookup_extent_info(trans, fs_info,
5342 eb->start, level, 1,
5346 btrfs_tree_unlock_rw(eb, path->locks[level]);
5347 path->locks[level] = 0;
5350 BUG_ON(wc->refs[level] == 0);
5351 if (wc->refs[level] == 1) {
5352 btrfs_tree_unlock_rw(eb, path->locks[level]);
5353 path->locks[level] = 0;
5359 /* wc->stage == DROP_REFERENCE */
5360 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5362 if (wc->refs[level] == 1) {
5364 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5365 ret = btrfs_dec_ref(trans, root, eb, 1);
5367 ret = btrfs_dec_ref(trans, root, eb, 0);
5368 BUG_ON(ret); /* -ENOMEM */
5369 if (is_fstree(root->root_key.objectid)) {
5370 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
5372 btrfs_err_rl(fs_info,
5373 "error %d accounting leaf items, quota is out of sync, rescan required",
5378 /* make block locked assertion in btrfs_clean_tree_block happy */
5379 if (!path->locks[level] &&
5380 btrfs_header_generation(eb) == trans->transid) {
5381 btrfs_tree_lock(eb);
5382 path->locks[level] = BTRFS_WRITE_LOCK;
5384 btrfs_clean_tree_block(eb);
5387 if (eb == root->node) {
5388 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5390 else if (root->root_key.objectid != btrfs_header_owner(eb))
5391 goto owner_mismatch;
5393 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5394 parent = path->nodes[level + 1]->start;
5395 else if (root->root_key.objectid !=
5396 btrfs_header_owner(path->nodes[level + 1]))
5397 goto owner_mismatch;
5400 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
5402 wc->refs[level] = 0;
5403 wc->flags[level] = 0;
5407 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
5408 btrfs_header_owner(eb), root->root_key.objectid);
5412 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
5413 struct btrfs_root *root,
5414 struct btrfs_path *path,
5415 struct walk_control *wc)
5417 int level = wc->level;
5418 int lookup_info = 1;
5421 while (level >= 0) {
5422 ret = walk_down_proc(trans, root, path, wc, lookup_info);
5429 if (path->slots[level] >=
5430 btrfs_header_nritems(path->nodes[level]))
5433 ret = do_walk_down(trans, root, path, wc, &lookup_info);
5435 path->slots[level]++;
5444 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
5445 struct btrfs_root *root,
5446 struct btrfs_path *path,
5447 struct walk_control *wc, int max_level)
5449 int level = wc->level;
5452 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
5453 while (level < max_level && path->nodes[level]) {
5455 if (path->slots[level] + 1 <
5456 btrfs_header_nritems(path->nodes[level])) {
5457 path->slots[level]++;
5460 ret = walk_up_proc(trans, root, path, wc);
5466 if (path->locks[level]) {
5467 btrfs_tree_unlock_rw(path->nodes[level],
5468 path->locks[level]);
5469 path->locks[level] = 0;
5471 free_extent_buffer(path->nodes[level]);
5472 path->nodes[level] = NULL;
5480 * drop a subvolume tree.
5482 * this function traverses the tree freeing any blocks that only
5483 * referenced by the tree.
5485 * when a shared tree block is found. this function decreases its
5486 * reference count by one. if update_ref is true, this function
5487 * also make sure backrefs for the shared block and all lower level
5488 * blocks are properly updated.
5490 * If called with for_reloc == 0, may exit early with -EAGAIN
5492 int btrfs_drop_snapshot(struct btrfs_root *root, int update_ref, int for_reloc)
5494 struct btrfs_fs_info *fs_info = root->fs_info;
5495 struct btrfs_path *path;
5496 struct btrfs_trans_handle *trans;
5497 struct btrfs_root *tree_root = fs_info->tree_root;
5498 struct btrfs_root_item *root_item = &root->root_item;
5499 struct walk_control *wc;
5500 struct btrfs_key key;
5504 bool root_dropped = false;
5506 btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
5508 path = btrfs_alloc_path();
5514 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5516 btrfs_free_path(path);
5522 * Use join to avoid potential EINTR from transaction start. See
5523 * wait_reserve_ticket and the whole reservation callchain.
5526 trans = btrfs_join_transaction(tree_root);
5528 trans = btrfs_start_transaction(tree_root, 0);
5529 if (IS_ERR(trans)) {
5530 err = PTR_ERR(trans);
5534 err = btrfs_run_delayed_items(trans);
5539 * This will help us catch people modifying the fs tree while we're
5540 * dropping it. It is unsafe to mess with the fs tree while it's being
5541 * dropped as we unlock the root node and parent nodes as we walk down
5542 * the tree, assuming nothing will change. If something does change
5543 * then we'll have stale information and drop references to blocks we've
5546 set_bit(BTRFS_ROOT_DELETING, &root->state);
5547 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
5548 level = btrfs_header_level(root->node);
5549 path->nodes[level] = btrfs_lock_root_node(root);
5550 path->slots[level] = 0;
5551 path->locks[level] = BTRFS_WRITE_LOCK;
5552 memset(&wc->update_progress, 0,
5553 sizeof(wc->update_progress));
5555 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
5556 memcpy(&wc->update_progress, &key,
5557 sizeof(wc->update_progress));
5559 level = btrfs_root_drop_level(root_item);
5561 path->lowest_level = level;
5562 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5563 path->lowest_level = 0;
5571 * unlock our path, this is safe because only this
5572 * function is allowed to delete this snapshot
5574 btrfs_unlock_up_safe(path, 0);
5576 level = btrfs_header_level(root->node);
5578 btrfs_tree_lock(path->nodes[level]);
5579 path->locks[level] = BTRFS_WRITE_LOCK;
5581 ret = btrfs_lookup_extent_info(trans, fs_info,
5582 path->nodes[level]->start,
5583 level, 1, &wc->refs[level],
5589 BUG_ON(wc->refs[level] == 0);
5591 if (level == btrfs_root_drop_level(root_item))
5594 btrfs_tree_unlock(path->nodes[level]);
5595 path->locks[level] = 0;
5596 WARN_ON(wc->refs[level] != 1);
5601 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
5603 wc->shared_level = -1;
5604 wc->stage = DROP_REFERENCE;
5605 wc->update_ref = update_ref;
5607 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5611 ret = walk_down_tree(trans, root, path, wc);
5617 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
5624 BUG_ON(wc->stage != DROP_REFERENCE);
5628 if (wc->stage == DROP_REFERENCE) {
5629 wc->drop_level = wc->level;
5630 btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
5632 path->slots[wc->drop_level]);
5634 btrfs_cpu_key_to_disk(&root_item->drop_progress,
5635 &wc->drop_progress);
5636 btrfs_set_root_drop_level(root_item, wc->drop_level);
5638 BUG_ON(wc->level == 0);
5639 if (btrfs_should_end_transaction(trans) ||
5640 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
5641 ret = btrfs_update_root(trans, tree_root,
5645 btrfs_abort_transaction(trans, ret);
5650 btrfs_end_transaction_throttle(trans);
5651 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
5652 btrfs_debug(fs_info,
5653 "drop snapshot early exit");
5659 * Use join to avoid potential EINTR from transaction
5660 * start. See wait_reserve_ticket and the whole
5661 * reservation callchain.
5664 trans = btrfs_join_transaction(tree_root);
5666 trans = btrfs_start_transaction(tree_root, 0);
5667 if (IS_ERR(trans)) {
5668 err = PTR_ERR(trans);
5673 btrfs_release_path(path);
5677 ret = btrfs_del_root(trans, &root->root_key);
5679 btrfs_abort_transaction(trans, ret);
5684 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
5685 ret = btrfs_find_root(tree_root, &root->root_key, path,
5688 btrfs_abort_transaction(trans, ret);
5691 } else if (ret > 0) {
5692 /* if we fail to delete the orphan item this time
5693 * around, it'll get picked up the next time.
5695 * The most common failure here is just -ENOENT.
5697 btrfs_del_orphan_item(trans, tree_root,
5698 root->root_key.objectid);
5703 * This subvolume is going to be completely dropped, and won't be
5704 * recorded as dirty roots, thus pertrans meta rsv will not be freed at
5705 * commit transaction time. So free it here manually.
5707 btrfs_qgroup_convert_reserved_meta(root, INT_MAX);
5708 btrfs_qgroup_free_meta_all_pertrans(root);
5710 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state))
5711 btrfs_add_dropped_root(trans, root);
5713 btrfs_put_root(root);
5714 root_dropped = true;
5716 btrfs_end_transaction_throttle(trans);
5719 btrfs_free_path(path);
5722 * So if we need to stop dropping the snapshot for whatever reason we
5723 * need to make sure to add it back to the dead root list so that we
5724 * keep trying to do the work later. This also cleans up roots if we
5725 * don't have it in the radix (like when we recover after a power fail
5726 * or unmount) so we don't leak memory.
5728 if (!for_reloc && !root_dropped)
5729 btrfs_add_dead_root(root);
5734 * drop subtree rooted at tree block 'node'.
5736 * NOTE: this function will unlock and release tree block 'node'
5737 * only used by relocation code
5739 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
5740 struct btrfs_root *root,
5741 struct extent_buffer *node,
5742 struct extent_buffer *parent)
5744 struct btrfs_fs_info *fs_info = root->fs_info;
5745 struct btrfs_path *path;
5746 struct walk_control *wc;
5752 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
5754 path = btrfs_alloc_path();
5758 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5760 btrfs_free_path(path);
5764 btrfs_assert_tree_locked(parent);
5765 parent_level = btrfs_header_level(parent);
5766 atomic_inc(&parent->refs);
5767 path->nodes[parent_level] = parent;
5768 path->slots[parent_level] = btrfs_header_nritems(parent);
5770 btrfs_assert_tree_locked(node);
5771 level = btrfs_header_level(node);
5772 path->nodes[level] = node;
5773 path->slots[level] = 0;
5774 path->locks[level] = BTRFS_WRITE_LOCK;
5776 wc->refs[parent_level] = 1;
5777 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5779 wc->shared_level = -1;
5780 wc->stage = DROP_REFERENCE;
5783 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5786 wret = walk_down_tree(trans, root, path, wc);
5792 wret = walk_up_tree(trans, root, path, wc, parent_level);
5800 btrfs_free_path(path);
5805 * helper to account the unused space of all the readonly block group in the
5806 * space_info. takes mirrors into account.
5808 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
5810 struct btrfs_block_group *block_group;
5814 /* It's df, we don't care if it's racy */
5815 if (list_empty(&sinfo->ro_bgs))
5818 spin_lock(&sinfo->lock);
5819 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
5820 spin_lock(&block_group->lock);
5822 if (!block_group->ro) {
5823 spin_unlock(&block_group->lock);
5827 factor = btrfs_bg_type_to_factor(block_group->flags);
5828 free_bytes += (block_group->length -
5829 block_group->used) * factor;
5831 spin_unlock(&block_group->lock);
5833 spin_unlock(&sinfo->lock);
5838 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
5841 return unpin_extent_range(fs_info, start, end, false);
5845 * It used to be that old block groups would be left around forever.
5846 * Iterating over them would be enough to trim unused space. Since we
5847 * now automatically remove them, we also need to iterate over unallocated
5850 * We don't want a transaction for this since the discard may take a
5851 * substantial amount of time. We don't require that a transaction be
5852 * running, but we do need to take a running transaction into account
5853 * to ensure that we're not discarding chunks that were released or
5854 * allocated in the current transaction.
5856 * Holding the chunks lock will prevent other threads from allocating
5857 * or releasing chunks, but it won't prevent a running transaction
5858 * from committing and releasing the memory that the pending chunks
5859 * list head uses. For that, we need to take a reference to the
5860 * transaction and hold the commit root sem. We only need to hold
5861 * it while performing the free space search since we have already
5862 * held back allocations.
5864 static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
5866 u64 start = SZ_1M, len = 0, end = 0;
5871 /* Discard not supported = nothing to do. */
5872 if (!blk_queue_discard(bdev_get_queue(device->bdev)))
5875 /* Not writable = nothing to do. */
5876 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
5879 /* No free space = nothing to do. */
5880 if (device->total_bytes <= device->bytes_used)
5886 struct btrfs_fs_info *fs_info = device->fs_info;
5889 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
5893 find_first_clear_extent_bit(&device->alloc_state, start,
5895 CHUNK_TRIMMED | CHUNK_ALLOCATED);
5897 /* Check if there are any CHUNK_* bits left */
5898 if (start > device->total_bytes) {
5899 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
5900 btrfs_warn_in_rcu(fs_info,
5901 "ignoring attempt to trim beyond device size: offset %llu length %llu device %s device size %llu",
5902 start, end - start + 1,
5903 rcu_str_deref(device->name),
5904 device->total_bytes);
5905 mutex_unlock(&fs_info->chunk_mutex);
5910 /* Ensure we skip the reserved area in the first 1M */
5911 start = max_t(u64, start, SZ_1M);
5914 * If find_first_clear_extent_bit find a range that spans the
5915 * end of the device it will set end to -1, in this case it's up
5916 * to the caller to trim the value to the size of the device.
5918 end = min(end, device->total_bytes - 1);
5920 len = end - start + 1;
5922 /* We didn't find any extents */
5924 mutex_unlock(&fs_info->chunk_mutex);
5929 ret = btrfs_issue_discard(device->bdev, start, len,
5932 set_extent_bits(&device->alloc_state, start,
5935 mutex_unlock(&fs_info->chunk_mutex);
5943 if (fatal_signal_pending(current)) {
5955 * Trim the whole filesystem by:
5956 * 1) trimming the free space in each block group
5957 * 2) trimming the unallocated space on each device
5959 * This will also continue trimming even if a block group or device encounters
5960 * an error. The return value will be the last error, or 0 if nothing bad
5963 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
5965 struct btrfs_block_group *cache = NULL;
5966 struct btrfs_device *device;
5967 struct list_head *devices;
5969 u64 range_end = U64_MAX;
5980 * Check range overflow if range->len is set.
5981 * The default range->len is U64_MAX.
5983 if (range->len != U64_MAX &&
5984 check_add_overflow(range->start, range->len, &range_end))
5987 cache = btrfs_lookup_first_block_group(fs_info, range->start);
5988 for (; cache; cache = btrfs_next_block_group(cache)) {
5989 if (cache->start >= range_end) {
5990 btrfs_put_block_group(cache);
5994 start = max(range->start, cache->start);
5995 end = min(range_end, cache->start + cache->length);
5997 if (end - start >= range->minlen) {
5998 if (!btrfs_block_group_done(cache)) {
5999 ret = btrfs_cache_block_group(cache, 0);
6005 ret = btrfs_wait_block_group_cache_done(cache);
6012 ret = btrfs_trim_block_group(cache,
6018 trimmed += group_trimmed;
6029 "failed to trim %llu block group(s), last error %d",
6031 mutex_lock(&fs_info->fs_devices->device_list_mutex);
6032 devices = &fs_info->fs_devices->devices;
6033 list_for_each_entry(device, devices, dev_list) {
6034 ret = btrfs_trim_free_extents(device, &group_trimmed);
6041 trimmed += group_trimmed;
6043 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
6047 "failed to trim %llu device(s), last error %d",
6048 dev_failed, dev_ret);
6049 range->len = trimmed;