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"
37 #undef SCRAMBLE_DELAYED_REFS
40 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
41 struct btrfs_delayed_ref_node *node, u64 parent,
42 u64 root_objectid, u64 owner_objectid,
43 u64 owner_offset, int refs_to_drop,
44 struct btrfs_delayed_extent_op *extra_op);
45 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
46 struct extent_buffer *leaf,
47 struct btrfs_extent_item *ei);
48 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
49 u64 parent, u64 root_objectid,
50 u64 flags, u64 owner, u64 offset,
51 struct btrfs_key *ins, int ref_mod);
52 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
53 struct btrfs_delayed_ref_node *node,
54 struct btrfs_delayed_extent_op *extent_op);
55 static int find_next_key(struct btrfs_path *path, int level,
56 struct btrfs_key *key);
58 static int block_group_bits(struct btrfs_block_group *cache, u64 bits)
60 return (cache->flags & bits) == bits;
63 int btrfs_add_excluded_extent(struct btrfs_fs_info *fs_info,
64 u64 start, u64 num_bytes)
66 u64 end = start + num_bytes - 1;
67 set_extent_bits(&fs_info->excluded_extents, start, end,
72 void btrfs_free_excluded_extents(struct btrfs_block_group *cache)
74 struct btrfs_fs_info *fs_info = cache->fs_info;
78 end = start + cache->length - 1;
80 clear_extent_bits(&fs_info->excluded_extents, start, end,
84 static u64 generic_ref_to_space_flags(struct btrfs_ref *ref)
86 if (ref->type == BTRFS_REF_METADATA) {
87 if (ref->tree_ref.root == BTRFS_CHUNK_TREE_OBJECTID)
88 return BTRFS_BLOCK_GROUP_SYSTEM;
90 return BTRFS_BLOCK_GROUP_METADATA;
92 return BTRFS_BLOCK_GROUP_DATA;
95 static void add_pinned_bytes(struct btrfs_fs_info *fs_info,
96 struct btrfs_ref *ref)
98 struct btrfs_space_info *space_info;
99 u64 flags = generic_ref_to_space_flags(ref);
101 space_info = btrfs_find_space_info(fs_info, flags);
103 percpu_counter_add_batch(&space_info->total_bytes_pinned, ref->len,
104 BTRFS_TOTAL_BYTES_PINNED_BATCH);
107 static void sub_pinned_bytes(struct btrfs_fs_info *fs_info,
108 struct btrfs_ref *ref)
110 struct btrfs_space_info *space_info;
111 u64 flags = generic_ref_to_space_flags(ref);
113 space_info = btrfs_find_space_info(fs_info, flags);
115 percpu_counter_add_batch(&space_info->total_bytes_pinned, -ref->len,
116 BTRFS_TOTAL_BYTES_PINNED_BATCH);
119 /* simple helper to search for an existing data extent at a given offset */
120 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
123 struct btrfs_key key;
124 struct btrfs_path *path;
126 path = btrfs_alloc_path();
130 key.objectid = start;
132 key.type = BTRFS_EXTENT_ITEM_KEY;
133 ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
134 btrfs_free_path(path);
139 * helper function to lookup reference count and flags of a tree block.
141 * the head node for delayed ref is used to store the sum of all the
142 * reference count modifications queued up in the rbtree. the head
143 * node may also store the extent flags to set. This way you can check
144 * to see what the reference count and extent flags would be if all of
145 * the delayed refs are not processed.
147 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
148 struct btrfs_fs_info *fs_info, u64 bytenr,
149 u64 offset, int metadata, u64 *refs, u64 *flags)
151 struct btrfs_delayed_ref_head *head;
152 struct btrfs_delayed_ref_root *delayed_refs;
153 struct btrfs_path *path;
154 struct btrfs_extent_item *ei;
155 struct extent_buffer *leaf;
156 struct btrfs_key key;
163 * If we don't have skinny metadata, don't bother doing anything
166 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
167 offset = fs_info->nodesize;
171 path = btrfs_alloc_path();
176 path->skip_locking = 1;
177 path->search_commit_root = 1;
181 key.objectid = bytenr;
184 key.type = BTRFS_METADATA_ITEM_KEY;
186 key.type = BTRFS_EXTENT_ITEM_KEY;
188 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
192 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
193 if (path->slots[0]) {
195 btrfs_item_key_to_cpu(path->nodes[0], &key,
197 if (key.objectid == bytenr &&
198 key.type == BTRFS_EXTENT_ITEM_KEY &&
199 key.offset == fs_info->nodesize)
205 leaf = path->nodes[0];
206 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
207 if (item_size >= sizeof(*ei)) {
208 ei = btrfs_item_ptr(leaf, path->slots[0],
209 struct btrfs_extent_item);
210 num_refs = btrfs_extent_refs(leaf, ei);
211 extent_flags = btrfs_extent_flags(leaf, ei);
214 btrfs_print_v0_err(fs_info);
216 btrfs_abort_transaction(trans, ret);
218 btrfs_handle_fs_error(fs_info, ret, NULL);
223 BUG_ON(num_refs == 0);
233 delayed_refs = &trans->transaction->delayed_refs;
234 spin_lock(&delayed_refs->lock);
235 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
237 if (!mutex_trylock(&head->mutex)) {
238 refcount_inc(&head->refs);
239 spin_unlock(&delayed_refs->lock);
241 btrfs_release_path(path);
244 * Mutex was contended, block until it's released and try
247 mutex_lock(&head->mutex);
248 mutex_unlock(&head->mutex);
249 btrfs_put_delayed_ref_head(head);
252 spin_lock(&head->lock);
253 if (head->extent_op && head->extent_op->update_flags)
254 extent_flags |= head->extent_op->flags_to_set;
256 BUG_ON(num_refs == 0);
258 num_refs += head->ref_mod;
259 spin_unlock(&head->lock);
260 mutex_unlock(&head->mutex);
262 spin_unlock(&delayed_refs->lock);
264 WARN_ON(num_refs == 0);
268 *flags = extent_flags;
270 btrfs_free_path(path);
275 * Back reference rules. Back refs have three main goals:
277 * 1) differentiate between all holders of references to an extent so that
278 * when a reference is dropped we can make sure it was a valid reference
279 * before freeing the extent.
281 * 2) Provide enough information to quickly find the holders of an extent
282 * if we notice a given block is corrupted or bad.
284 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
285 * maintenance. This is actually the same as #2, but with a slightly
286 * different use case.
288 * There are two kinds of back refs. The implicit back refs is optimized
289 * for pointers in non-shared tree blocks. For a given pointer in a block,
290 * back refs of this kind provide information about the block's owner tree
291 * and the pointer's key. These information allow us to find the block by
292 * b-tree searching. The full back refs is for pointers in tree blocks not
293 * referenced by their owner trees. The location of tree block is recorded
294 * in the back refs. Actually the full back refs is generic, and can be
295 * used in all cases the implicit back refs is used. The major shortcoming
296 * of the full back refs is its overhead. Every time a tree block gets
297 * COWed, we have to update back refs entry for all pointers in it.
299 * For a newly allocated tree block, we use implicit back refs for
300 * pointers in it. This means most tree related operations only involve
301 * implicit back refs. For a tree block created in old transaction, the
302 * only way to drop a reference to it is COW it. So we can detect the
303 * event that tree block loses its owner tree's reference and do the
304 * back refs conversion.
306 * When a tree block is COWed through a tree, there are four cases:
308 * The reference count of the block is one and the tree is the block's
309 * owner tree. Nothing to do in this case.
311 * The reference count of the block is one and the tree is not the
312 * block's owner tree. In this case, full back refs is used for pointers
313 * in the block. Remove these full back refs, add implicit back refs for
314 * every pointers in the new block.
316 * The reference count of the block is greater than one and the tree is
317 * the block's owner tree. In this case, implicit back refs is used for
318 * pointers in the block. Add full back refs for every pointers in the
319 * block, increase lower level extents' reference counts. The original
320 * implicit back refs are entailed to the new block.
322 * The reference count of the block is greater than one and the tree is
323 * not the block's owner tree. Add implicit back refs for every pointer in
324 * the new block, increase lower level extents' reference count.
326 * Back Reference Key composing:
328 * The key objectid corresponds to the first byte in the extent,
329 * The key type is used to differentiate between types of back refs.
330 * There are different meanings of the key offset for different types
333 * File extents can be referenced by:
335 * - multiple snapshots, subvolumes, or different generations in one subvol
336 * - different files inside a single subvolume
337 * - different offsets inside a file (bookend extents in file.c)
339 * The extent ref structure for the implicit back refs has fields for:
341 * - Objectid of the subvolume root
342 * - objectid of the file holding the reference
343 * - original offset in the file
344 * - how many bookend extents
346 * The key offset for the implicit back refs is hash of the first
349 * The extent ref structure for the full back refs has field for:
351 * - number of pointers in the tree leaf
353 * The key offset for the implicit back refs is the first byte of
356 * When a file extent is allocated, The implicit back refs is used.
357 * the fields are filled in:
359 * (root_key.objectid, inode objectid, offset in file, 1)
361 * When a file extent is removed file truncation, we find the
362 * corresponding implicit back refs and check the following fields:
364 * (btrfs_header_owner(leaf), inode objectid, offset in file)
366 * Btree extents can be referenced by:
368 * - Different subvolumes
370 * Both the implicit back refs and the full back refs for tree blocks
371 * only consist of key. The key offset for the implicit back refs is
372 * objectid of block's owner tree. The key offset for the full back refs
373 * is the first byte of parent block.
375 * When implicit back refs is used, information about the lowest key and
376 * level of the tree block are required. These information are stored in
377 * tree block info structure.
381 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
382 * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
383 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
385 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
386 struct btrfs_extent_inline_ref *iref,
387 enum btrfs_inline_ref_type is_data)
389 int type = btrfs_extent_inline_ref_type(eb, iref);
390 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
392 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
393 type == BTRFS_SHARED_BLOCK_REF_KEY ||
394 type == BTRFS_SHARED_DATA_REF_KEY ||
395 type == BTRFS_EXTENT_DATA_REF_KEY) {
396 if (is_data == BTRFS_REF_TYPE_BLOCK) {
397 if (type == BTRFS_TREE_BLOCK_REF_KEY)
399 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
402 * Every shared one has parent tree
403 * block, which must be aligned to
407 IS_ALIGNED(offset, eb->fs_info->nodesize))
410 } else if (is_data == BTRFS_REF_TYPE_DATA) {
411 if (type == BTRFS_EXTENT_DATA_REF_KEY)
413 if (type == BTRFS_SHARED_DATA_REF_KEY) {
416 * Every shared one has parent tree
417 * block, which must be aligned to
421 IS_ALIGNED(offset, eb->fs_info->nodesize))
425 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
430 btrfs_print_leaf((struct extent_buffer *)eb);
431 btrfs_err(eb->fs_info, "eb %llu invalid extent inline ref type %d",
435 return BTRFS_REF_TYPE_INVALID;
438 u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
440 u32 high_crc = ~(u32)0;
441 u32 low_crc = ~(u32)0;
444 lenum = cpu_to_le64(root_objectid);
445 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
446 lenum = cpu_to_le64(owner);
447 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
448 lenum = cpu_to_le64(offset);
449 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
451 return ((u64)high_crc << 31) ^ (u64)low_crc;
454 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
455 struct btrfs_extent_data_ref *ref)
457 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
458 btrfs_extent_data_ref_objectid(leaf, ref),
459 btrfs_extent_data_ref_offset(leaf, ref));
462 static int match_extent_data_ref(struct extent_buffer *leaf,
463 struct btrfs_extent_data_ref *ref,
464 u64 root_objectid, u64 owner, u64 offset)
466 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
467 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
468 btrfs_extent_data_ref_offset(leaf, ref) != offset)
473 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
474 struct btrfs_path *path,
475 u64 bytenr, u64 parent,
477 u64 owner, u64 offset)
479 struct btrfs_root *root = trans->fs_info->extent_root;
480 struct btrfs_key key;
481 struct btrfs_extent_data_ref *ref;
482 struct extent_buffer *leaf;
488 key.objectid = bytenr;
490 key.type = BTRFS_SHARED_DATA_REF_KEY;
493 key.type = BTRFS_EXTENT_DATA_REF_KEY;
494 key.offset = hash_extent_data_ref(root_objectid,
499 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
511 leaf = path->nodes[0];
512 nritems = btrfs_header_nritems(leaf);
514 if (path->slots[0] >= nritems) {
515 ret = btrfs_next_leaf(root, path);
521 leaf = path->nodes[0];
522 nritems = btrfs_header_nritems(leaf);
526 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
527 if (key.objectid != bytenr ||
528 key.type != BTRFS_EXTENT_DATA_REF_KEY)
531 ref = btrfs_item_ptr(leaf, path->slots[0],
532 struct btrfs_extent_data_ref);
534 if (match_extent_data_ref(leaf, ref, root_objectid,
537 btrfs_release_path(path);
549 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
550 struct btrfs_path *path,
551 u64 bytenr, u64 parent,
552 u64 root_objectid, u64 owner,
553 u64 offset, int refs_to_add)
555 struct btrfs_root *root = trans->fs_info->extent_root;
556 struct btrfs_key key;
557 struct extent_buffer *leaf;
562 key.objectid = bytenr;
564 key.type = BTRFS_SHARED_DATA_REF_KEY;
566 size = sizeof(struct btrfs_shared_data_ref);
568 key.type = BTRFS_EXTENT_DATA_REF_KEY;
569 key.offset = hash_extent_data_ref(root_objectid,
571 size = sizeof(struct btrfs_extent_data_ref);
574 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
575 if (ret && ret != -EEXIST)
578 leaf = path->nodes[0];
580 struct btrfs_shared_data_ref *ref;
581 ref = btrfs_item_ptr(leaf, path->slots[0],
582 struct btrfs_shared_data_ref);
584 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
586 num_refs = btrfs_shared_data_ref_count(leaf, ref);
587 num_refs += refs_to_add;
588 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
591 struct btrfs_extent_data_ref *ref;
592 while (ret == -EEXIST) {
593 ref = btrfs_item_ptr(leaf, path->slots[0],
594 struct btrfs_extent_data_ref);
595 if (match_extent_data_ref(leaf, ref, root_objectid,
598 btrfs_release_path(path);
600 ret = btrfs_insert_empty_item(trans, root, path, &key,
602 if (ret && ret != -EEXIST)
605 leaf = path->nodes[0];
607 ref = btrfs_item_ptr(leaf, path->slots[0],
608 struct btrfs_extent_data_ref);
610 btrfs_set_extent_data_ref_root(leaf, ref,
612 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
613 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
614 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
616 num_refs = btrfs_extent_data_ref_count(leaf, ref);
617 num_refs += refs_to_add;
618 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
621 btrfs_mark_buffer_dirty(leaf);
624 btrfs_release_path(path);
628 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
629 struct btrfs_path *path,
630 int refs_to_drop, int *last_ref)
632 struct btrfs_key key;
633 struct btrfs_extent_data_ref *ref1 = NULL;
634 struct btrfs_shared_data_ref *ref2 = NULL;
635 struct extent_buffer *leaf;
639 leaf = path->nodes[0];
640 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
642 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
643 ref1 = btrfs_item_ptr(leaf, path->slots[0],
644 struct btrfs_extent_data_ref);
645 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
646 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
647 ref2 = btrfs_item_ptr(leaf, path->slots[0],
648 struct btrfs_shared_data_ref);
649 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
650 } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
651 btrfs_print_v0_err(trans->fs_info);
652 btrfs_abort_transaction(trans, -EINVAL);
658 BUG_ON(num_refs < refs_to_drop);
659 num_refs -= refs_to_drop;
662 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
665 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
666 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
667 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
668 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
669 btrfs_mark_buffer_dirty(leaf);
674 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
675 struct btrfs_extent_inline_ref *iref)
677 struct btrfs_key key;
678 struct extent_buffer *leaf;
679 struct btrfs_extent_data_ref *ref1;
680 struct btrfs_shared_data_ref *ref2;
684 leaf = path->nodes[0];
685 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
687 BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
690 * If type is invalid, we should have bailed out earlier than
693 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
694 ASSERT(type != BTRFS_REF_TYPE_INVALID);
695 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
696 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
697 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
699 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
700 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
702 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
703 ref1 = btrfs_item_ptr(leaf, path->slots[0],
704 struct btrfs_extent_data_ref);
705 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
706 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
707 ref2 = btrfs_item_ptr(leaf, path->slots[0],
708 struct btrfs_shared_data_ref);
709 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
716 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
717 struct btrfs_path *path,
718 u64 bytenr, u64 parent,
721 struct btrfs_root *root = trans->fs_info->extent_root;
722 struct btrfs_key key;
725 key.objectid = bytenr;
727 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
730 key.type = BTRFS_TREE_BLOCK_REF_KEY;
731 key.offset = root_objectid;
734 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
740 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
741 struct btrfs_path *path,
742 u64 bytenr, u64 parent,
745 struct btrfs_key key;
748 key.objectid = bytenr;
750 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
753 key.type = BTRFS_TREE_BLOCK_REF_KEY;
754 key.offset = root_objectid;
757 ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
759 btrfs_release_path(path);
763 static inline int extent_ref_type(u64 parent, u64 owner)
766 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
768 type = BTRFS_SHARED_BLOCK_REF_KEY;
770 type = BTRFS_TREE_BLOCK_REF_KEY;
773 type = BTRFS_SHARED_DATA_REF_KEY;
775 type = BTRFS_EXTENT_DATA_REF_KEY;
780 static int find_next_key(struct btrfs_path *path, int level,
781 struct btrfs_key *key)
784 for (; level < BTRFS_MAX_LEVEL; level++) {
785 if (!path->nodes[level])
787 if (path->slots[level] + 1 >=
788 btrfs_header_nritems(path->nodes[level]))
791 btrfs_item_key_to_cpu(path->nodes[level], key,
792 path->slots[level] + 1);
794 btrfs_node_key_to_cpu(path->nodes[level], key,
795 path->slots[level] + 1);
802 * look for inline back ref. if back ref is found, *ref_ret is set
803 * to the address of inline back ref, and 0 is returned.
805 * if back ref isn't found, *ref_ret is set to the address where it
806 * should be inserted, and -ENOENT is returned.
808 * if insert is true and there are too many inline back refs, the path
809 * points to the extent item, and -EAGAIN is returned.
811 * NOTE: inline back refs are ordered in the same way that back ref
812 * items in the tree are ordered.
814 static noinline_for_stack
815 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
816 struct btrfs_path *path,
817 struct btrfs_extent_inline_ref **ref_ret,
818 u64 bytenr, u64 num_bytes,
819 u64 parent, u64 root_objectid,
820 u64 owner, u64 offset, int insert)
822 struct btrfs_fs_info *fs_info = trans->fs_info;
823 struct btrfs_root *root = fs_info->extent_root;
824 struct btrfs_key key;
825 struct extent_buffer *leaf;
826 struct btrfs_extent_item *ei;
827 struct btrfs_extent_inline_ref *iref;
837 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
840 key.objectid = bytenr;
841 key.type = BTRFS_EXTENT_ITEM_KEY;
842 key.offset = num_bytes;
844 want = extent_ref_type(parent, owner);
846 extra_size = btrfs_extent_inline_ref_size(want);
847 path->keep_locks = 1;
852 * Owner is our level, so we can just add one to get the level for the
853 * block we are interested in.
855 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
856 key.type = BTRFS_METADATA_ITEM_KEY;
861 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
868 * We may be a newly converted file system which still has the old fat
869 * extent entries for metadata, so try and see if we have one of those.
871 if (ret > 0 && skinny_metadata) {
872 skinny_metadata = false;
873 if (path->slots[0]) {
875 btrfs_item_key_to_cpu(path->nodes[0], &key,
877 if (key.objectid == bytenr &&
878 key.type == BTRFS_EXTENT_ITEM_KEY &&
879 key.offset == num_bytes)
883 key.objectid = bytenr;
884 key.type = BTRFS_EXTENT_ITEM_KEY;
885 key.offset = num_bytes;
886 btrfs_release_path(path);
891 if (ret && !insert) {
894 } else if (WARN_ON(ret)) {
899 leaf = path->nodes[0];
900 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
901 if (unlikely(item_size < sizeof(*ei))) {
903 btrfs_print_v0_err(fs_info);
904 btrfs_abort_transaction(trans, err);
908 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
909 flags = btrfs_extent_flags(leaf, ei);
911 ptr = (unsigned long)(ei + 1);
912 end = (unsigned long)ei + item_size;
914 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
915 ptr += sizeof(struct btrfs_tree_block_info);
919 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
920 needed = BTRFS_REF_TYPE_DATA;
922 needed = BTRFS_REF_TYPE_BLOCK;
930 iref = (struct btrfs_extent_inline_ref *)ptr;
931 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
932 if (type == BTRFS_REF_TYPE_INVALID) {
940 ptr += btrfs_extent_inline_ref_size(type);
944 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
945 struct btrfs_extent_data_ref *dref;
946 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
947 if (match_extent_data_ref(leaf, dref, root_objectid,
952 if (hash_extent_data_ref_item(leaf, dref) <
953 hash_extent_data_ref(root_objectid, owner, offset))
957 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
959 if (parent == ref_offset) {
963 if (ref_offset < parent)
966 if (root_objectid == ref_offset) {
970 if (ref_offset < root_objectid)
974 ptr += btrfs_extent_inline_ref_size(type);
976 if (err == -ENOENT && insert) {
977 if (item_size + extra_size >=
978 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
983 * To add new inline back ref, we have to make sure
984 * there is no corresponding back ref item.
985 * For simplicity, we just do not add new inline back
986 * ref if there is any kind of item for this block
988 if (find_next_key(path, 0, &key) == 0 &&
989 key.objectid == bytenr &&
990 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
995 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
998 path->keep_locks = 0;
999 btrfs_unlock_up_safe(path, 1);
1005 * helper to add new inline back ref
1007 static noinline_for_stack
1008 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1009 struct btrfs_path *path,
1010 struct btrfs_extent_inline_ref *iref,
1011 u64 parent, u64 root_objectid,
1012 u64 owner, u64 offset, int refs_to_add,
1013 struct btrfs_delayed_extent_op *extent_op)
1015 struct extent_buffer *leaf;
1016 struct btrfs_extent_item *ei;
1019 unsigned long item_offset;
1024 leaf = path->nodes[0];
1025 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1026 item_offset = (unsigned long)iref - (unsigned long)ei;
1028 type = extent_ref_type(parent, owner);
1029 size = btrfs_extent_inline_ref_size(type);
1031 btrfs_extend_item(path, size);
1033 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1034 refs = btrfs_extent_refs(leaf, ei);
1035 refs += refs_to_add;
1036 btrfs_set_extent_refs(leaf, ei, refs);
1038 __run_delayed_extent_op(extent_op, leaf, ei);
1040 ptr = (unsigned long)ei + item_offset;
1041 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1042 if (ptr < end - size)
1043 memmove_extent_buffer(leaf, ptr + size, ptr,
1046 iref = (struct btrfs_extent_inline_ref *)ptr;
1047 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1048 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1049 struct btrfs_extent_data_ref *dref;
1050 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1051 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1052 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1053 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1054 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1055 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1056 struct btrfs_shared_data_ref *sref;
1057 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1058 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1059 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1060 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1061 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1063 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1065 btrfs_mark_buffer_dirty(leaf);
1068 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1069 struct btrfs_path *path,
1070 struct btrfs_extent_inline_ref **ref_ret,
1071 u64 bytenr, u64 num_bytes, u64 parent,
1072 u64 root_objectid, u64 owner, u64 offset)
1076 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1077 num_bytes, parent, root_objectid,
1082 btrfs_release_path(path);
1085 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1086 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1089 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1090 root_objectid, owner, offset);
1096 * helper to update/remove inline back ref
1098 static noinline_for_stack
1099 void update_inline_extent_backref(struct btrfs_path *path,
1100 struct btrfs_extent_inline_ref *iref,
1102 struct btrfs_delayed_extent_op *extent_op,
1105 struct extent_buffer *leaf = path->nodes[0];
1106 struct btrfs_extent_item *ei;
1107 struct btrfs_extent_data_ref *dref = NULL;
1108 struct btrfs_shared_data_ref *sref = NULL;
1116 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1117 refs = btrfs_extent_refs(leaf, ei);
1118 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1119 refs += refs_to_mod;
1120 btrfs_set_extent_refs(leaf, ei, refs);
1122 __run_delayed_extent_op(extent_op, leaf, ei);
1125 * If type is invalid, we should have bailed out after
1126 * lookup_inline_extent_backref().
1128 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1129 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1131 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1132 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1133 refs = btrfs_extent_data_ref_count(leaf, dref);
1134 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1135 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1136 refs = btrfs_shared_data_ref_count(leaf, sref);
1139 BUG_ON(refs_to_mod != -1);
1142 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1143 refs += refs_to_mod;
1146 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1147 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1149 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1152 size = btrfs_extent_inline_ref_size(type);
1153 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1154 ptr = (unsigned long)iref;
1155 end = (unsigned long)ei + item_size;
1156 if (ptr + size < end)
1157 memmove_extent_buffer(leaf, ptr, ptr + size,
1160 btrfs_truncate_item(path, item_size, 1);
1162 btrfs_mark_buffer_dirty(leaf);
1165 static noinline_for_stack
1166 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1167 struct btrfs_path *path,
1168 u64 bytenr, u64 num_bytes, u64 parent,
1169 u64 root_objectid, u64 owner,
1170 u64 offset, int refs_to_add,
1171 struct btrfs_delayed_extent_op *extent_op)
1173 struct btrfs_extent_inline_ref *iref;
1176 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1177 num_bytes, parent, root_objectid,
1180 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1181 update_inline_extent_backref(path, iref, refs_to_add,
1183 } else if (ret == -ENOENT) {
1184 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1185 root_objectid, owner, offset,
1186 refs_to_add, extent_op);
1192 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1193 struct btrfs_path *path,
1194 u64 bytenr, u64 parent, u64 root_objectid,
1195 u64 owner, u64 offset, int refs_to_add)
1198 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1199 BUG_ON(refs_to_add != 1);
1200 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1203 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1204 root_objectid, owner, offset,
1210 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1211 struct btrfs_path *path,
1212 struct btrfs_extent_inline_ref *iref,
1213 int refs_to_drop, int is_data, int *last_ref)
1217 BUG_ON(!is_data && refs_to_drop != 1);
1219 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1221 } else if (is_data) {
1222 ret = remove_extent_data_ref(trans, path, refs_to_drop,
1226 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1231 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1232 u64 *discarded_bytes)
1235 u64 bytes_left, end;
1236 u64 aligned_start = ALIGN(start, 1 << 9);
1238 if (WARN_ON(start != aligned_start)) {
1239 len -= aligned_start - start;
1240 len = round_down(len, 1 << 9);
1241 start = aligned_start;
1244 *discarded_bytes = 0;
1252 /* Skip any superblocks on this device. */
1253 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1254 u64 sb_start = btrfs_sb_offset(j);
1255 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1256 u64 size = sb_start - start;
1258 if (!in_range(sb_start, start, bytes_left) &&
1259 !in_range(sb_end, start, bytes_left) &&
1260 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1264 * Superblock spans beginning of range. Adjust start and
1267 if (sb_start <= start) {
1268 start += sb_end - start;
1273 bytes_left = end - start;
1278 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1281 *discarded_bytes += size;
1282 else if (ret != -EOPNOTSUPP)
1291 bytes_left = end - start;
1295 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1298 *discarded_bytes += bytes_left;
1303 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1304 u64 num_bytes, u64 *actual_bytes)
1307 u64 discarded_bytes = 0;
1308 u64 end = bytenr + num_bytes;
1310 struct btrfs_bio *bbio = NULL;
1314 * Avoid races with device replace and make sure our bbio has devices
1315 * associated to its stripes that don't go away while we are discarding.
1317 btrfs_bio_counter_inc_blocked(fs_info);
1319 struct btrfs_bio_stripe *stripe;
1322 num_bytes = end - cur;
1323 /* Tell the block device(s) that the sectors can be discarded */
1324 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, cur,
1325 &num_bytes, &bbio, 0);
1327 * Error can be -ENOMEM, -ENOENT (no such chunk mapping) or
1328 * -EOPNOTSUPP. For any such error, @num_bytes is not updated,
1329 * thus we can't continue anyway.
1334 stripe = bbio->stripes;
1335 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
1337 struct request_queue *req_q;
1339 if (!stripe->dev->bdev) {
1340 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1343 req_q = bdev_get_queue(stripe->dev->bdev);
1344 if (!blk_queue_discard(req_q))
1347 ret = btrfs_issue_discard(stripe->dev->bdev,
1352 discarded_bytes += bytes;
1353 } else if (ret != -EOPNOTSUPP) {
1355 * Logic errors or -ENOMEM, or -EIO, but
1356 * unlikely to happen.
1358 * And since there are two loops, explicitly
1359 * go to out to avoid confusion.
1361 btrfs_put_bbio(bbio);
1366 * Just in case we get back EOPNOTSUPP for some reason,
1367 * just ignore the return value so we don't screw up
1368 * people calling discard_extent.
1372 btrfs_put_bbio(bbio);
1376 btrfs_bio_counter_dec(fs_info);
1379 *actual_bytes = discarded_bytes;
1382 if (ret == -EOPNOTSUPP)
1387 /* Can return -ENOMEM */
1388 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1389 struct btrfs_ref *generic_ref)
1391 struct btrfs_fs_info *fs_info = trans->fs_info;
1392 int old_ref_mod, new_ref_mod;
1395 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
1396 generic_ref->action);
1397 BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
1398 generic_ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID);
1400 if (generic_ref->type == BTRFS_REF_METADATA)
1401 ret = btrfs_add_delayed_tree_ref(trans, generic_ref,
1402 NULL, &old_ref_mod, &new_ref_mod);
1404 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0,
1405 &old_ref_mod, &new_ref_mod);
1407 btrfs_ref_tree_mod(fs_info, generic_ref);
1409 if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0)
1410 sub_pinned_bytes(fs_info, generic_ref);
1416 * __btrfs_inc_extent_ref - insert backreference for a given extent
1418 * @trans: Handle of transaction
1420 * @node: The delayed ref node used to get the bytenr/length for
1421 * extent whose references are incremented.
1423 * @parent: If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
1424 * BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
1425 * bytenr of the parent block. Since new extents are always
1426 * created with indirect references, this will only be the case
1427 * when relocating a shared extent. In that case, root_objectid
1428 * will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
1431 * @root_objectid: The id of the root where this modification has originated,
1432 * this can be either one of the well-known metadata trees or
1433 * the subvolume id which references this extent.
1435 * @owner: For data extents it is the inode number of the owning file.
1436 * For metadata extents this parameter holds the level in the
1437 * tree of the extent.
1439 * @offset: For metadata extents the offset is ignored and is currently
1440 * always passed as 0. For data extents it is the fileoffset
1441 * this extent belongs to.
1443 * @refs_to_add Number of references to add
1445 * @extent_op Pointer to a structure, holding information necessary when
1446 * updating a tree block's flags
1449 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1450 struct btrfs_delayed_ref_node *node,
1451 u64 parent, u64 root_objectid,
1452 u64 owner, u64 offset, int refs_to_add,
1453 struct btrfs_delayed_extent_op *extent_op)
1455 struct btrfs_path *path;
1456 struct extent_buffer *leaf;
1457 struct btrfs_extent_item *item;
1458 struct btrfs_key key;
1459 u64 bytenr = node->bytenr;
1460 u64 num_bytes = node->num_bytes;
1464 path = btrfs_alloc_path();
1468 path->reada = READA_FORWARD;
1469 path->leave_spinning = 1;
1470 /* this will setup the path even if it fails to insert the back ref */
1471 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
1472 parent, root_objectid, owner,
1473 offset, refs_to_add, extent_op);
1474 if ((ret < 0 && ret != -EAGAIN) || !ret)
1478 * Ok we had -EAGAIN which means we didn't have space to insert and
1479 * inline extent ref, so just update the reference count and add a
1482 leaf = path->nodes[0];
1483 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1484 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1485 refs = btrfs_extent_refs(leaf, item);
1486 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1488 __run_delayed_extent_op(extent_op, leaf, item);
1490 btrfs_mark_buffer_dirty(leaf);
1491 btrfs_release_path(path);
1493 path->reada = READA_FORWARD;
1494 path->leave_spinning = 1;
1495 /* now insert the actual backref */
1496 ret = insert_extent_backref(trans, path, bytenr, parent, root_objectid,
1497 owner, offset, refs_to_add);
1499 btrfs_abort_transaction(trans, ret);
1501 btrfs_free_path(path);
1505 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1506 struct btrfs_delayed_ref_node *node,
1507 struct btrfs_delayed_extent_op *extent_op,
1508 int insert_reserved)
1511 struct btrfs_delayed_data_ref *ref;
1512 struct btrfs_key ins;
1517 ins.objectid = node->bytenr;
1518 ins.offset = node->num_bytes;
1519 ins.type = BTRFS_EXTENT_ITEM_KEY;
1521 ref = btrfs_delayed_node_to_data_ref(node);
1522 trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
1524 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1525 parent = ref->parent;
1526 ref_root = ref->root;
1528 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1530 flags |= extent_op->flags_to_set;
1531 ret = alloc_reserved_file_extent(trans, parent, ref_root,
1532 flags, ref->objectid,
1535 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1536 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
1537 ref->objectid, ref->offset,
1538 node->ref_mod, extent_op);
1539 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1540 ret = __btrfs_free_extent(trans, node, parent,
1541 ref_root, ref->objectid,
1542 ref->offset, node->ref_mod,
1550 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1551 struct extent_buffer *leaf,
1552 struct btrfs_extent_item *ei)
1554 u64 flags = btrfs_extent_flags(leaf, ei);
1555 if (extent_op->update_flags) {
1556 flags |= extent_op->flags_to_set;
1557 btrfs_set_extent_flags(leaf, ei, flags);
1560 if (extent_op->update_key) {
1561 struct btrfs_tree_block_info *bi;
1562 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1563 bi = (struct btrfs_tree_block_info *)(ei + 1);
1564 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1568 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1569 struct btrfs_delayed_ref_head *head,
1570 struct btrfs_delayed_extent_op *extent_op)
1572 struct btrfs_fs_info *fs_info = trans->fs_info;
1573 struct btrfs_key key;
1574 struct btrfs_path *path;
1575 struct btrfs_extent_item *ei;
1576 struct extent_buffer *leaf;
1580 int metadata = !extent_op->is_data;
1582 if (TRANS_ABORTED(trans))
1585 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1588 path = btrfs_alloc_path();
1592 key.objectid = head->bytenr;
1595 key.type = BTRFS_METADATA_ITEM_KEY;
1596 key.offset = extent_op->level;
1598 key.type = BTRFS_EXTENT_ITEM_KEY;
1599 key.offset = head->num_bytes;
1603 path->reada = READA_FORWARD;
1604 path->leave_spinning = 1;
1605 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
1612 if (path->slots[0] > 0) {
1614 btrfs_item_key_to_cpu(path->nodes[0], &key,
1616 if (key.objectid == head->bytenr &&
1617 key.type == BTRFS_EXTENT_ITEM_KEY &&
1618 key.offset == head->num_bytes)
1622 btrfs_release_path(path);
1625 key.objectid = head->bytenr;
1626 key.offset = head->num_bytes;
1627 key.type = BTRFS_EXTENT_ITEM_KEY;
1636 leaf = path->nodes[0];
1637 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1639 if (unlikely(item_size < sizeof(*ei))) {
1641 btrfs_print_v0_err(fs_info);
1642 btrfs_abort_transaction(trans, err);
1646 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1647 __run_delayed_extent_op(extent_op, leaf, ei);
1649 btrfs_mark_buffer_dirty(leaf);
1651 btrfs_free_path(path);
1655 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
1656 struct btrfs_delayed_ref_node *node,
1657 struct btrfs_delayed_extent_op *extent_op,
1658 int insert_reserved)
1661 struct btrfs_delayed_tree_ref *ref;
1665 ref = btrfs_delayed_node_to_tree_ref(node);
1666 trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
1668 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1669 parent = ref->parent;
1670 ref_root = ref->root;
1672 if (node->ref_mod != 1) {
1673 btrfs_err(trans->fs_info,
1674 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
1675 node->bytenr, node->ref_mod, node->action, ref_root,
1679 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1680 BUG_ON(!extent_op || !extent_op->update_flags);
1681 ret = alloc_reserved_tree_block(trans, node, extent_op);
1682 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1683 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
1684 ref->level, 0, 1, extent_op);
1685 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1686 ret = __btrfs_free_extent(trans, node, parent, ref_root,
1687 ref->level, 0, 1, extent_op);
1694 /* helper function to actually process a single delayed ref entry */
1695 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
1696 struct btrfs_delayed_ref_node *node,
1697 struct btrfs_delayed_extent_op *extent_op,
1698 int insert_reserved)
1702 if (TRANS_ABORTED(trans)) {
1703 if (insert_reserved)
1704 btrfs_pin_extent(trans, node->bytenr, node->num_bytes, 1);
1708 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
1709 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1710 ret = run_delayed_tree_ref(trans, node, extent_op,
1712 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
1713 node->type == BTRFS_SHARED_DATA_REF_KEY)
1714 ret = run_delayed_data_ref(trans, node, extent_op,
1718 if (ret && insert_reserved)
1719 btrfs_pin_extent(trans, node->bytenr, node->num_bytes, 1);
1723 static inline struct btrfs_delayed_ref_node *
1724 select_delayed_ref(struct btrfs_delayed_ref_head *head)
1726 struct btrfs_delayed_ref_node *ref;
1728 if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
1732 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
1733 * This is to prevent a ref count from going down to zero, which deletes
1734 * the extent item from the extent tree, when there still are references
1735 * to add, which would fail because they would not find the extent item.
1737 if (!list_empty(&head->ref_add_list))
1738 return list_first_entry(&head->ref_add_list,
1739 struct btrfs_delayed_ref_node, add_list);
1741 ref = rb_entry(rb_first_cached(&head->ref_tree),
1742 struct btrfs_delayed_ref_node, ref_node);
1743 ASSERT(list_empty(&ref->add_list));
1747 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
1748 struct btrfs_delayed_ref_head *head)
1750 spin_lock(&delayed_refs->lock);
1751 head->processing = 0;
1752 delayed_refs->num_heads_ready++;
1753 spin_unlock(&delayed_refs->lock);
1754 btrfs_delayed_ref_unlock(head);
1757 static struct btrfs_delayed_extent_op *cleanup_extent_op(
1758 struct btrfs_delayed_ref_head *head)
1760 struct btrfs_delayed_extent_op *extent_op = head->extent_op;
1765 if (head->must_insert_reserved) {
1766 head->extent_op = NULL;
1767 btrfs_free_delayed_extent_op(extent_op);
1773 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
1774 struct btrfs_delayed_ref_head *head)
1776 struct btrfs_delayed_extent_op *extent_op;
1779 extent_op = cleanup_extent_op(head);
1782 head->extent_op = NULL;
1783 spin_unlock(&head->lock);
1784 ret = run_delayed_extent_op(trans, head, extent_op);
1785 btrfs_free_delayed_extent_op(extent_op);
1786 return ret ? ret : 1;
1789 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
1790 struct btrfs_delayed_ref_root *delayed_refs,
1791 struct btrfs_delayed_ref_head *head)
1793 int nr_items = 1; /* Dropping this ref head update. */
1795 if (head->total_ref_mod < 0) {
1796 struct btrfs_space_info *space_info;
1800 flags = BTRFS_BLOCK_GROUP_DATA;
1801 else if (head->is_system)
1802 flags = BTRFS_BLOCK_GROUP_SYSTEM;
1804 flags = BTRFS_BLOCK_GROUP_METADATA;
1805 space_info = btrfs_find_space_info(fs_info, flags);
1807 percpu_counter_add_batch(&space_info->total_bytes_pinned,
1809 BTRFS_TOTAL_BYTES_PINNED_BATCH);
1812 * We had csum deletions accounted for in our delayed refs rsv,
1813 * we need to drop the csum leaves for this update from our
1816 if (head->is_data) {
1817 spin_lock(&delayed_refs->lock);
1818 delayed_refs->pending_csums -= head->num_bytes;
1819 spin_unlock(&delayed_refs->lock);
1820 nr_items += btrfs_csum_bytes_to_leaves(fs_info,
1825 btrfs_delayed_refs_rsv_release(fs_info, nr_items);
1828 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
1829 struct btrfs_delayed_ref_head *head)
1832 struct btrfs_fs_info *fs_info = trans->fs_info;
1833 struct btrfs_delayed_ref_root *delayed_refs;
1836 delayed_refs = &trans->transaction->delayed_refs;
1838 ret = run_and_cleanup_extent_op(trans, head);
1840 unselect_delayed_ref_head(delayed_refs, head);
1841 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
1848 * Need to drop our head ref lock and re-acquire the delayed ref lock
1849 * and then re-check to make sure nobody got added.
1851 spin_unlock(&head->lock);
1852 spin_lock(&delayed_refs->lock);
1853 spin_lock(&head->lock);
1854 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
1855 spin_unlock(&head->lock);
1856 spin_unlock(&delayed_refs->lock);
1859 btrfs_delete_ref_head(delayed_refs, head);
1860 spin_unlock(&head->lock);
1861 spin_unlock(&delayed_refs->lock);
1863 if (head->must_insert_reserved) {
1864 btrfs_pin_extent(trans, head->bytenr, head->num_bytes, 1);
1865 if (head->is_data) {
1866 ret = btrfs_del_csums(trans, fs_info->csum_root,
1867 head->bytenr, head->num_bytes);
1871 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
1873 trace_run_delayed_ref_head(fs_info, head, 0);
1874 btrfs_delayed_ref_unlock(head);
1875 btrfs_put_delayed_ref_head(head);
1879 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
1880 struct btrfs_trans_handle *trans)
1882 struct btrfs_delayed_ref_root *delayed_refs =
1883 &trans->transaction->delayed_refs;
1884 struct btrfs_delayed_ref_head *head = NULL;
1887 spin_lock(&delayed_refs->lock);
1888 head = btrfs_select_ref_head(delayed_refs);
1890 spin_unlock(&delayed_refs->lock);
1895 * Grab the lock that says we are going to process all the refs for
1898 ret = btrfs_delayed_ref_lock(delayed_refs, head);
1899 spin_unlock(&delayed_refs->lock);
1902 * We may have dropped the spin lock to get the head mutex lock, and
1903 * that might have given someone else time to free the head. If that's
1904 * true, it has been removed from our list and we can move on.
1907 head = ERR_PTR(-EAGAIN);
1912 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
1913 struct btrfs_delayed_ref_head *locked_ref,
1914 unsigned long *run_refs)
1916 struct btrfs_fs_info *fs_info = trans->fs_info;
1917 struct btrfs_delayed_ref_root *delayed_refs;
1918 struct btrfs_delayed_extent_op *extent_op;
1919 struct btrfs_delayed_ref_node *ref;
1920 int must_insert_reserved = 0;
1923 delayed_refs = &trans->transaction->delayed_refs;
1925 lockdep_assert_held(&locked_ref->mutex);
1926 lockdep_assert_held(&locked_ref->lock);
1928 while ((ref = select_delayed_ref(locked_ref))) {
1930 btrfs_check_delayed_seq(fs_info, ref->seq)) {
1931 spin_unlock(&locked_ref->lock);
1932 unselect_delayed_ref_head(delayed_refs, locked_ref);
1938 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
1939 RB_CLEAR_NODE(&ref->ref_node);
1940 if (!list_empty(&ref->add_list))
1941 list_del(&ref->add_list);
1943 * When we play the delayed ref, also correct the ref_mod on
1946 switch (ref->action) {
1947 case BTRFS_ADD_DELAYED_REF:
1948 case BTRFS_ADD_DELAYED_EXTENT:
1949 locked_ref->ref_mod -= ref->ref_mod;
1951 case BTRFS_DROP_DELAYED_REF:
1952 locked_ref->ref_mod += ref->ref_mod;
1957 atomic_dec(&delayed_refs->num_entries);
1960 * Record the must_insert_reserved flag before we drop the
1963 must_insert_reserved = locked_ref->must_insert_reserved;
1964 locked_ref->must_insert_reserved = 0;
1966 extent_op = locked_ref->extent_op;
1967 locked_ref->extent_op = NULL;
1968 spin_unlock(&locked_ref->lock);
1970 ret = run_one_delayed_ref(trans, ref, extent_op,
1971 must_insert_reserved);
1973 btrfs_free_delayed_extent_op(extent_op);
1975 unselect_delayed_ref_head(delayed_refs, locked_ref);
1976 btrfs_put_delayed_ref(ref);
1977 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
1982 btrfs_put_delayed_ref(ref);
1985 spin_lock(&locked_ref->lock);
1986 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
1993 * Returns 0 on success or if called with an already aborted transaction.
1994 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
1996 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
1999 struct btrfs_fs_info *fs_info = trans->fs_info;
2000 struct btrfs_delayed_ref_root *delayed_refs;
2001 struct btrfs_delayed_ref_head *locked_ref = NULL;
2002 ktime_t start = ktime_get();
2004 unsigned long count = 0;
2005 unsigned long actual_count = 0;
2007 delayed_refs = &trans->transaction->delayed_refs;
2010 locked_ref = btrfs_obtain_ref_head(trans);
2011 if (IS_ERR_OR_NULL(locked_ref)) {
2012 if (PTR_ERR(locked_ref) == -EAGAIN) {
2021 * We need to try and merge add/drops of the same ref since we
2022 * can run into issues with relocate dropping the implicit ref
2023 * and then it being added back again before the drop can
2024 * finish. If we merged anything we need to re-loop so we can
2026 * Or we can get node references of the same type that weren't
2027 * merged when created due to bumps in the tree mod seq, and
2028 * we need to merge them to prevent adding an inline extent
2029 * backref before dropping it (triggering a BUG_ON at
2030 * insert_inline_extent_backref()).
2032 spin_lock(&locked_ref->lock);
2033 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2035 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2037 if (ret < 0 && ret != -EAGAIN) {
2039 * Error, btrfs_run_delayed_refs_for_head already
2040 * unlocked everything so just bail out
2045 * Success, perform the usual cleanup of a processed
2048 ret = cleanup_ref_head(trans, locked_ref);
2050 /* We dropped our lock, we need to loop. */
2059 * Either success case or btrfs_run_delayed_refs_for_head
2060 * returned -EAGAIN, meaning we need to select another head
2065 } while ((nr != -1 && count < nr) || locked_ref);
2068 * We don't want to include ref heads since we can have empty ref heads
2069 * and those will drastically skew our runtime down since we just do
2070 * accounting, no actual extent tree updates.
2072 if (actual_count > 0) {
2073 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2077 * We weigh the current average higher than our current runtime
2078 * to avoid large swings in the average.
2080 spin_lock(&delayed_refs->lock);
2081 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2082 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2083 spin_unlock(&delayed_refs->lock);
2088 #ifdef SCRAMBLE_DELAYED_REFS
2090 * Normally delayed refs get processed in ascending bytenr order. This
2091 * correlates in most cases to the order added. To expose dependencies on this
2092 * order, we start to process the tree in the middle instead of the beginning
2094 static u64 find_middle(struct rb_root *root)
2096 struct rb_node *n = root->rb_node;
2097 struct btrfs_delayed_ref_node *entry;
2100 u64 first = 0, last = 0;
2104 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2105 first = entry->bytenr;
2109 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2110 last = entry->bytenr;
2115 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2116 WARN_ON(!entry->in_tree);
2118 middle = entry->bytenr;
2131 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2135 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2136 sizeof(struct btrfs_extent_inline_ref));
2137 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2138 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2141 * We don't ever fill up leaves all the way so multiply by 2 just to be
2142 * closer to what we're really going to want to use.
2144 return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2148 * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2149 * would require to store the csums for that many bytes.
2151 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2154 u64 num_csums_per_leaf;
2157 csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2158 num_csums_per_leaf = div64_u64(csum_size,
2159 (u64)btrfs_super_csum_size(fs_info->super_copy));
2160 num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2161 num_csums += num_csums_per_leaf - 1;
2162 num_csums = div64_u64(num_csums, num_csums_per_leaf);
2167 * this starts processing the delayed reference count updates and
2168 * extent insertions we have queued up so far. count can be
2169 * 0, which means to process everything in the tree at the start
2170 * of the run (but not newly added entries), or it can be some target
2171 * number you'd like to process.
2173 * Returns 0 on success or if called with an aborted transaction
2174 * Returns <0 on error and aborts the transaction
2176 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2177 unsigned long count)
2179 struct btrfs_fs_info *fs_info = trans->fs_info;
2180 struct rb_node *node;
2181 struct btrfs_delayed_ref_root *delayed_refs;
2182 struct btrfs_delayed_ref_head *head;
2184 int run_all = count == (unsigned long)-1;
2186 /* We'll clean this up in btrfs_cleanup_transaction */
2187 if (TRANS_ABORTED(trans))
2190 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2193 delayed_refs = &trans->transaction->delayed_refs;
2195 count = atomic_read(&delayed_refs->num_entries) * 2;
2198 #ifdef SCRAMBLE_DELAYED_REFS
2199 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2201 ret = __btrfs_run_delayed_refs(trans, count);
2203 btrfs_abort_transaction(trans, ret);
2208 btrfs_create_pending_block_groups(trans);
2210 spin_lock(&delayed_refs->lock);
2211 node = rb_first_cached(&delayed_refs->href_root);
2213 spin_unlock(&delayed_refs->lock);
2216 head = rb_entry(node, struct btrfs_delayed_ref_head,
2218 refcount_inc(&head->refs);
2219 spin_unlock(&delayed_refs->lock);
2221 /* Mutex was contended, block until it's released and retry. */
2222 mutex_lock(&head->mutex);
2223 mutex_unlock(&head->mutex);
2225 btrfs_put_delayed_ref_head(head);
2233 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2234 struct extent_buffer *eb, u64 flags,
2235 int level, int is_data)
2237 struct btrfs_delayed_extent_op *extent_op;
2240 extent_op = btrfs_alloc_delayed_extent_op();
2244 extent_op->flags_to_set = flags;
2245 extent_op->update_flags = true;
2246 extent_op->update_key = false;
2247 extent_op->is_data = is_data ? true : false;
2248 extent_op->level = level;
2250 ret = btrfs_add_delayed_extent_op(trans, eb->start, eb->len, extent_op);
2252 btrfs_free_delayed_extent_op(extent_op);
2256 static noinline int check_delayed_ref(struct btrfs_root *root,
2257 struct btrfs_path *path,
2258 u64 objectid, u64 offset, u64 bytenr)
2260 struct btrfs_delayed_ref_head *head;
2261 struct btrfs_delayed_ref_node *ref;
2262 struct btrfs_delayed_data_ref *data_ref;
2263 struct btrfs_delayed_ref_root *delayed_refs;
2264 struct btrfs_transaction *cur_trans;
2265 struct rb_node *node;
2268 spin_lock(&root->fs_info->trans_lock);
2269 cur_trans = root->fs_info->running_transaction;
2271 refcount_inc(&cur_trans->use_count);
2272 spin_unlock(&root->fs_info->trans_lock);
2276 delayed_refs = &cur_trans->delayed_refs;
2277 spin_lock(&delayed_refs->lock);
2278 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2280 spin_unlock(&delayed_refs->lock);
2281 btrfs_put_transaction(cur_trans);
2285 if (!mutex_trylock(&head->mutex)) {
2286 refcount_inc(&head->refs);
2287 spin_unlock(&delayed_refs->lock);
2289 btrfs_release_path(path);
2292 * Mutex was contended, block until it's released and let
2295 mutex_lock(&head->mutex);
2296 mutex_unlock(&head->mutex);
2297 btrfs_put_delayed_ref_head(head);
2298 btrfs_put_transaction(cur_trans);
2301 spin_unlock(&delayed_refs->lock);
2303 spin_lock(&head->lock);
2305 * XXX: We should replace this with a proper search function in the
2308 for (node = rb_first_cached(&head->ref_tree); node;
2309 node = rb_next(node)) {
2310 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
2311 /* If it's a shared ref we know a cross reference exists */
2312 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2317 data_ref = btrfs_delayed_node_to_data_ref(ref);
2320 * If our ref doesn't match the one we're currently looking at
2321 * then we have a cross reference.
2323 if (data_ref->root != root->root_key.objectid ||
2324 data_ref->objectid != objectid ||
2325 data_ref->offset != offset) {
2330 spin_unlock(&head->lock);
2331 mutex_unlock(&head->mutex);
2332 btrfs_put_transaction(cur_trans);
2336 static noinline int check_committed_ref(struct btrfs_root *root,
2337 struct btrfs_path *path,
2338 u64 objectid, u64 offset, u64 bytenr)
2340 struct btrfs_fs_info *fs_info = root->fs_info;
2341 struct btrfs_root *extent_root = fs_info->extent_root;
2342 struct extent_buffer *leaf;
2343 struct btrfs_extent_data_ref *ref;
2344 struct btrfs_extent_inline_ref *iref;
2345 struct btrfs_extent_item *ei;
2346 struct btrfs_key key;
2351 key.objectid = bytenr;
2352 key.offset = (u64)-1;
2353 key.type = BTRFS_EXTENT_ITEM_KEY;
2355 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2358 BUG_ON(ret == 0); /* Corruption */
2361 if (path->slots[0] == 0)
2365 leaf = path->nodes[0];
2366 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2368 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2372 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2373 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2375 /* If extent item has more than 1 inline ref then it's shared */
2376 if (item_size != sizeof(*ei) +
2377 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2380 /* If extent created before last snapshot => it's definitely shared */
2381 if (btrfs_extent_generation(leaf, ei) <=
2382 btrfs_root_last_snapshot(&root->root_item))
2385 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2387 /* If this extent has SHARED_DATA_REF then it's shared */
2388 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
2389 if (type != BTRFS_EXTENT_DATA_REF_KEY)
2392 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2393 if (btrfs_extent_refs(leaf, ei) !=
2394 btrfs_extent_data_ref_count(leaf, ref) ||
2395 btrfs_extent_data_ref_root(leaf, ref) !=
2396 root->root_key.objectid ||
2397 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2398 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2406 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
2409 struct btrfs_path *path;
2412 path = btrfs_alloc_path();
2417 ret = check_committed_ref(root, path, objectid,
2419 if (ret && ret != -ENOENT)
2422 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
2423 } while (ret == -EAGAIN);
2426 btrfs_free_path(path);
2427 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2432 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2433 struct btrfs_root *root,
2434 struct extent_buffer *buf,
2435 int full_backref, int inc)
2437 struct btrfs_fs_info *fs_info = root->fs_info;
2443 struct btrfs_key key;
2444 struct btrfs_file_extent_item *fi;
2445 struct btrfs_ref generic_ref = { 0 };
2446 bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
2452 if (btrfs_is_testing(fs_info))
2455 ref_root = btrfs_header_owner(buf);
2456 nritems = btrfs_header_nritems(buf);
2457 level = btrfs_header_level(buf);
2459 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
2463 parent = buf->start;
2467 action = BTRFS_ADD_DELAYED_REF;
2469 action = BTRFS_DROP_DELAYED_REF;
2471 for (i = 0; i < nritems; i++) {
2473 btrfs_item_key_to_cpu(buf, &key, i);
2474 if (key.type != BTRFS_EXTENT_DATA_KEY)
2476 fi = btrfs_item_ptr(buf, i,
2477 struct btrfs_file_extent_item);
2478 if (btrfs_file_extent_type(buf, fi) ==
2479 BTRFS_FILE_EXTENT_INLINE)
2481 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2485 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2486 key.offset -= btrfs_file_extent_offset(buf, fi);
2487 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2489 generic_ref.real_root = root->root_key.objectid;
2490 btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
2492 generic_ref.skip_qgroup = for_reloc;
2494 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2496 ret = btrfs_free_extent(trans, &generic_ref);
2500 bytenr = btrfs_node_blockptr(buf, i);
2501 num_bytes = fs_info->nodesize;
2502 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2504 generic_ref.real_root = root->root_key.objectid;
2505 btrfs_init_tree_ref(&generic_ref, level - 1, ref_root);
2506 generic_ref.skip_qgroup = for_reloc;
2508 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2510 ret = btrfs_free_extent(trans, &generic_ref);
2520 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2521 struct extent_buffer *buf, int full_backref)
2523 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
2526 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2527 struct extent_buffer *buf, int full_backref)
2529 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2532 int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
2534 struct btrfs_block_group *block_group;
2537 block_group = btrfs_lookup_block_group(fs_info, bytenr);
2538 if (!block_group || block_group->ro)
2541 btrfs_put_block_group(block_group);
2545 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
2547 struct btrfs_fs_info *fs_info = root->fs_info;
2552 flags = BTRFS_BLOCK_GROUP_DATA;
2553 else if (root == fs_info->chunk_root)
2554 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2556 flags = BTRFS_BLOCK_GROUP_METADATA;
2558 ret = btrfs_get_alloc_profile(fs_info, flags);
2562 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
2564 struct btrfs_block_group *cache;
2567 spin_lock(&fs_info->block_group_cache_lock);
2568 bytenr = fs_info->first_logical_byte;
2569 spin_unlock(&fs_info->block_group_cache_lock);
2571 if (bytenr < (u64)-1)
2574 cache = btrfs_lookup_first_block_group(fs_info, search_start);
2578 bytenr = cache->start;
2579 btrfs_put_block_group(cache);
2584 static int pin_down_extent(struct btrfs_trans_handle *trans,
2585 struct btrfs_block_group *cache,
2586 u64 bytenr, u64 num_bytes, int reserved)
2588 struct btrfs_fs_info *fs_info = cache->fs_info;
2590 spin_lock(&cache->space_info->lock);
2591 spin_lock(&cache->lock);
2592 cache->pinned += num_bytes;
2593 btrfs_space_info_update_bytes_pinned(fs_info, cache->space_info,
2596 cache->reserved -= num_bytes;
2597 cache->space_info->bytes_reserved -= num_bytes;
2599 spin_unlock(&cache->lock);
2600 spin_unlock(&cache->space_info->lock);
2602 percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
2603 num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
2604 set_extent_dirty(&trans->transaction->pinned_extents, bytenr,
2605 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
2609 int btrfs_pin_extent(struct btrfs_trans_handle *trans,
2610 u64 bytenr, u64 num_bytes, int reserved)
2612 struct btrfs_block_group *cache;
2614 cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
2615 BUG_ON(!cache); /* Logic error */
2617 pin_down_extent(trans, cache, bytenr, num_bytes, reserved);
2619 btrfs_put_block_group(cache);
2624 * this function must be called within transaction
2626 int btrfs_pin_extent_for_log_replay(struct btrfs_trans_handle *trans,
2627 u64 bytenr, u64 num_bytes)
2629 struct btrfs_block_group *cache;
2632 btrfs_add_excluded_extent(trans->fs_info, bytenr, num_bytes);
2634 cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
2639 * pull in the free space cache (if any) so that our pin
2640 * removes the free space from the cache. We have load_only set
2641 * to one because the slow code to read in the free extents does check
2642 * the pinned extents.
2644 btrfs_cache_block_group(cache, 1);
2646 pin_down_extent(trans, cache, bytenr, num_bytes, 0);
2648 /* remove us from the free space cache (if we're there at all) */
2649 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
2650 btrfs_put_block_group(cache);
2654 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
2655 u64 start, u64 num_bytes)
2658 struct btrfs_block_group *block_group;
2659 struct btrfs_caching_control *caching_ctl;
2661 block_group = btrfs_lookup_block_group(fs_info, start);
2665 btrfs_cache_block_group(block_group, 0);
2666 caching_ctl = btrfs_get_caching_control(block_group);
2670 BUG_ON(!btrfs_block_group_done(block_group));
2671 ret = btrfs_remove_free_space(block_group, start, num_bytes);
2673 mutex_lock(&caching_ctl->mutex);
2675 if (start >= caching_ctl->progress) {
2676 ret = btrfs_add_excluded_extent(fs_info, start,
2678 } else if (start + num_bytes <= caching_ctl->progress) {
2679 ret = btrfs_remove_free_space(block_group,
2682 num_bytes = caching_ctl->progress - start;
2683 ret = btrfs_remove_free_space(block_group,
2688 num_bytes = (start + num_bytes) -
2689 caching_ctl->progress;
2690 start = caching_ctl->progress;
2691 ret = btrfs_add_excluded_extent(fs_info, start,
2695 mutex_unlock(&caching_ctl->mutex);
2696 btrfs_put_caching_control(caching_ctl);
2698 btrfs_put_block_group(block_group);
2702 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
2704 struct btrfs_fs_info *fs_info = eb->fs_info;
2705 struct btrfs_file_extent_item *item;
2706 struct btrfs_key key;
2711 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
2714 for (i = 0; i < btrfs_header_nritems(eb); i++) {
2715 btrfs_item_key_to_cpu(eb, &key, i);
2716 if (key.type != BTRFS_EXTENT_DATA_KEY)
2718 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
2719 found_type = btrfs_file_extent_type(eb, item);
2720 if (found_type == BTRFS_FILE_EXTENT_INLINE)
2722 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
2724 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
2725 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
2726 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
2735 btrfs_inc_block_group_reservations(struct btrfs_block_group *bg)
2737 atomic_inc(&bg->reservations);
2740 void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
2742 struct btrfs_caching_control *next;
2743 struct btrfs_caching_control *caching_ctl;
2744 struct btrfs_block_group *cache;
2746 down_write(&fs_info->commit_root_sem);
2748 list_for_each_entry_safe(caching_ctl, next,
2749 &fs_info->caching_block_groups, list) {
2750 cache = caching_ctl->block_group;
2751 if (btrfs_block_group_done(cache)) {
2752 cache->last_byte_to_unpin = (u64)-1;
2753 list_del_init(&caching_ctl->list);
2754 btrfs_put_caching_control(caching_ctl);
2756 cache->last_byte_to_unpin = caching_ctl->progress;
2760 up_write(&fs_info->commit_root_sem);
2762 btrfs_update_global_block_rsv(fs_info);
2766 * Returns the free cluster for the given space info and sets empty_cluster to
2767 * what it should be based on the mount options.
2769 static struct btrfs_free_cluster *
2770 fetch_cluster_info(struct btrfs_fs_info *fs_info,
2771 struct btrfs_space_info *space_info, u64 *empty_cluster)
2773 struct btrfs_free_cluster *ret = NULL;
2776 if (btrfs_mixed_space_info(space_info))
2779 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
2780 ret = &fs_info->meta_alloc_cluster;
2781 if (btrfs_test_opt(fs_info, SSD))
2782 *empty_cluster = SZ_2M;
2784 *empty_cluster = SZ_64K;
2785 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
2786 btrfs_test_opt(fs_info, SSD_SPREAD)) {
2787 *empty_cluster = SZ_2M;
2788 ret = &fs_info->data_alloc_cluster;
2794 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
2796 const bool return_free_space)
2798 struct btrfs_block_group *cache = NULL;
2799 struct btrfs_space_info *space_info;
2800 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2801 struct btrfs_free_cluster *cluster = NULL;
2803 u64 total_unpinned = 0;
2804 u64 empty_cluster = 0;
2807 while (start <= end) {
2810 start >= cache->start + cache->length) {
2812 btrfs_put_block_group(cache);
2814 cache = btrfs_lookup_block_group(fs_info, start);
2815 BUG_ON(!cache); /* Logic error */
2817 cluster = fetch_cluster_info(fs_info,
2820 empty_cluster <<= 1;
2823 len = cache->start + cache->length - start;
2824 len = min(len, end + 1 - start);
2826 if (start < cache->last_byte_to_unpin) {
2827 len = min(len, cache->last_byte_to_unpin - start);
2828 if (return_free_space)
2829 btrfs_add_free_space(cache, start, len);
2833 total_unpinned += len;
2834 space_info = cache->space_info;
2837 * If this space cluster has been marked as fragmented and we've
2838 * unpinned enough in this block group to potentially allow a
2839 * cluster to be created inside of it go ahead and clear the
2842 if (cluster && cluster->fragmented &&
2843 total_unpinned > empty_cluster) {
2844 spin_lock(&cluster->lock);
2845 cluster->fragmented = 0;
2846 spin_unlock(&cluster->lock);
2849 spin_lock(&space_info->lock);
2850 spin_lock(&cache->lock);
2851 cache->pinned -= len;
2852 btrfs_space_info_update_bytes_pinned(fs_info, space_info, -len);
2853 space_info->max_extent_size = 0;
2854 percpu_counter_add_batch(&space_info->total_bytes_pinned,
2855 -len, BTRFS_TOTAL_BYTES_PINNED_BATCH);
2857 space_info->bytes_readonly += len;
2860 spin_unlock(&cache->lock);
2861 if (!readonly && return_free_space &&
2862 global_rsv->space_info == space_info) {
2865 spin_lock(&global_rsv->lock);
2866 if (!global_rsv->full) {
2867 to_add = min(len, global_rsv->size -
2868 global_rsv->reserved);
2869 global_rsv->reserved += to_add;
2870 btrfs_space_info_update_bytes_may_use(fs_info,
2871 space_info, to_add);
2872 if (global_rsv->reserved >= global_rsv->size)
2873 global_rsv->full = 1;
2876 spin_unlock(&global_rsv->lock);
2877 /* Add to any tickets we may have */
2879 btrfs_try_granting_tickets(fs_info,
2882 spin_unlock(&space_info->lock);
2886 btrfs_put_block_group(cache);
2890 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
2892 struct btrfs_fs_info *fs_info = trans->fs_info;
2893 struct btrfs_block_group *block_group, *tmp;
2894 struct list_head *deleted_bgs;
2895 struct extent_io_tree *unpin;
2900 unpin = &trans->transaction->pinned_extents;
2902 while (!TRANS_ABORTED(trans)) {
2903 struct extent_state *cached_state = NULL;
2905 mutex_lock(&fs_info->unused_bg_unpin_mutex);
2906 ret = find_first_extent_bit(unpin, 0, &start, &end,
2907 EXTENT_DIRTY, &cached_state);
2909 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2912 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
2913 clear_extent_bits(&fs_info->excluded_extents, start,
2914 end, EXTENT_UPTODATE);
2916 if (btrfs_test_opt(fs_info, DISCARD_SYNC))
2917 ret = btrfs_discard_extent(fs_info, start,
2918 end + 1 - start, NULL);
2920 clear_extent_dirty(unpin, start, end, &cached_state);
2921 unpin_extent_range(fs_info, start, end, true);
2922 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2923 free_extent_state(cached_state);
2927 if (btrfs_test_opt(fs_info, DISCARD_ASYNC)) {
2928 btrfs_discard_calc_delay(&fs_info->discard_ctl);
2929 btrfs_discard_schedule_work(&fs_info->discard_ctl, true);
2933 * Transaction is finished. We don't need the lock anymore. We
2934 * do need to clean up the block groups in case of a transaction
2937 deleted_bgs = &trans->transaction->deleted_bgs;
2938 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
2942 if (!TRANS_ABORTED(trans))
2943 ret = btrfs_discard_extent(fs_info,
2945 block_group->length,
2948 list_del_init(&block_group->bg_list);
2949 btrfs_put_block_group_trimming(block_group);
2950 btrfs_put_block_group(block_group);
2953 const char *errstr = btrfs_decode_error(ret);
2955 "discard failed while removing blockgroup: errno=%d %s",
2963 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
2964 struct btrfs_delayed_ref_node *node, u64 parent,
2965 u64 root_objectid, u64 owner_objectid,
2966 u64 owner_offset, int refs_to_drop,
2967 struct btrfs_delayed_extent_op *extent_op)
2969 struct btrfs_fs_info *info = trans->fs_info;
2970 struct btrfs_key key;
2971 struct btrfs_path *path;
2972 struct btrfs_root *extent_root = info->extent_root;
2973 struct extent_buffer *leaf;
2974 struct btrfs_extent_item *ei;
2975 struct btrfs_extent_inline_ref *iref;
2978 int extent_slot = 0;
2979 int found_extent = 0;
2983 u64 bytenr = node->bytenr;
2984 u64 num_bytes = node->num_bytes;
2986 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
2988 path = btrfs_alloc_path();
2992 path->reada = READA_FORWARD;
2993 path->leave_spinning = 1;
2995 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
2996 BUG_ON(!is_data && refs_to_drop != 1);
2999 skinny_metadata = false;
3001 ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
3002 parent, root_objectid, owner_objectid,
3005 extent_slot = path->slots[0];
3006 while (extent_slot >= 0) {
3007 btrfs_item_key_to_cpu(path->nodes[0], &key,
3009 if (key.objectid != bytenr)
3011 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
3012 key.offset == num_bytes) {
3016 if (key.type == BTRFS_METADATA_ITEM_KEY &&
3017 key.offset == owner_objectid) {
3021 if (path->slots[0] - extent_slot > 5)
3026 if (!found_extent) {
3028 ret = remove_extent_backref(trans, path, NULL,
3030 is_data, &last_ref);
3032 btrfs_abort_transaction(trans, ret);
3035 btrfs_release_path(path);
3036 path->leave_spinning = 1;
3038 key.objectid = bytenr;
3039 key.type = BTRFS_EXTENT_ITEM_KEY;
3040 key.offset = num_bytes;
3042 if (!is_data && skinny_metadata) {
3043 key.type = BTRFS_METADATA_ITEM_KEY;
3044 key.offset = owner_objectid;
3047 ret = btrfs_search_slot(trans, extent_root,
3049 if (ret > 0 && skinny_metadata && path->slots[0]) {
3051 * Couldn't find our skinny metadata item,
3052 * see if we have ye olde extent item.
3055 btrfs_item_key_to_cpu(path->nodes[0], &key,
3057 if (key.objectid == bytenr &&
3058 key.type == BTRFS_EXTENT_ITEM_KEY &&
3059 key.offset == num_bytes)
3063 if (ret > 0 && skinny_metadata) {
3064 skinny_metadata = false;
3065 key.objectid = bytenr;
3066 key.type = BTRFS_EXTENT_ITEM_KEY;
3067 key.offset = num_bytes;
3068 btrfs_release_path(path);
3069 ret = btrfs_search_slot(trans, extent_root,
3075 "umm, got %d back from search, was looking for %llu",
3078 btrfs_print_leaf(path->nodes[0]);
3081 btrfs_abort_transaction(trans, ret);
3084 extent_slot = path->slots[0];
3086 } else if (WARN_ON(ret == -ENOENT)) {
3087 btrfs_print_leaf(path->nodes[0]);
3089 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
3090 bytenr, parent, root_objectid, owner_objectid,
3092 btrfs_abort_transaction(trans, ret);
3095 btrfs_abort_transaction(trans, ret);
3099 leaf = path->nodes[0];
3100 item_size = btrfs_item_size_nr(leaf, extent_slot);
3101 if (unlikely(item_size < sizeof(*ei))) {
3103 btrfs_print_v0_err(info);
3104 btrfs_abort_transaction(trans, ret);
3107 ei = btrfs_item_ptr(leaf, extent_slot,
3108 struct btrfs_extent_item);
3109 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
3110 key.type == BTRFS_EXTENT_ITEM_KEY) {
3111 struct btrfs_tree_block_info *bi;
3112 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
3113 bi = (struct btrfs_tree_block_info *)(ei + 1);
3114 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
3117 refs = btrfs_extent_refs(leaf, ei);
3118 if (refs < refs_to_drop) {
3120 "trying to drop %d refs but we only have %Lu for bytenr %Lu",
3121 refs_to_drop, refs, bytenr);
3123 btrfs_abort_transaction(trans, ret);
3126 refs -= refs_to_drop;
3130 __run_delayed_extent_op(extent_op, leaf, ei);
3132 * In the case of inline back ref, reference count will
3133 * be updated by remove_extent_backref
3136 BUG_ON(!found_extent);
3138 btrfs_set_extent_refs(leaf, ei, refs);
3139 btrfs_mark_buffer_dirty(leaf);
3142 ret = remove_extent_backref(trans, path, iref,
3143 refs_to_drop, is_data,
3146 btrfs_abort_transaction(trans, ret);
3152 BUG_ON(is_data && refs_to_drop !=
3153 extent_data_ref_count(path, iref));
3155 BUG_ON(path->slots[0] != extent_slot);
3157 BUG_ON(path->slots[0] != extent_slot + 1);
3158 path->slots[0] = extent_slot;
3164 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
3167 btrfs_abort_transaction(trans, ret);
3170 btrfs_release_path(path);
3173 ret = btrfs_del_csums(trans, info->csum_root, bytenr,
3176 btrfs_abort_transaction(trans, ret);
3181 ret = add_to_free_space_tree(trans, bytenr, num_bytes);
3183 btrfs_abort_transaction(trans, ret);
3187 ret = btrfs_update_block_group(trans, bytenr, num_bytes, 0);
3189 btrfs_abort_transaction(trans, ret);
3193 btrfs_release_path(path);
3196 btrfs_free_path(path);
3201 * when we free an block, it is possible (and likely) that we free the last
3202 * delayed ref for that extent as well. This searches the delayed ref tree for
3203 * a given extent, and if there are no other delayed refs to be processed, it
3204 * removes it from the tree.
3206 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
3209 struct btrfs_delayed_ref_head *head;
3210 struct btrfs_delayed_ref_root *delayed_refs;
3213 delayed_refs = &trans->transaction->delayed_refs;
3214 spin_lock(&delayed_refs->lock);
3215 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
3217 goto out_delayed_unlock;
3219 spin_lock(&head->lock);
3220 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
3223 if (cleanup_extent_op(head) != NULL)
3227 * waiting for the lock here would deadlock. If someone else has it
3228 * locked they are already in the process of dropping it anyway
3230 if (!mutex_trylock(&head->mutex))
3233 btrfs_delete_ref_head(delayed_refs, head);
3234 head->processing = 0;
3236 spin_unlock(&head->lock);
3237 spin_unlock(&delayed_refs->lock);
3239 BUG_ON(head->extent_op);
3240 if (head->must_insert_reserved)
3243 btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
3244 mutex_unlock(&head->mutex);
3245 btrfs_put_delayed_ref_head(head);
3248 spin_unlock(&head->lock);
3251 spin_unlock(&delayed_refs->lock);
3255 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
3256 struct btrfs_root *root,
3257 struct extent_buffer *buf,
3258 u64 parent, int last_ref)
3260 struct btrfs_fs_info *fs_info = root->fs_info;
3261 struct btrfs_ref generic_ref = { 0 };
3265 btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
3266 buf->start, buf->len, parent);
3267 btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
3268 root->root_key.objectid);
3270 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
3271 int old_ref_mod, new_ref_mod;
3273 btrfs_ref_tree_mod(fs_info, &generic_ref);
3274 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL,
3275 &old_ref_mod, &new_ref_mod);
3276 BUG_ON(ret); /* -ENOMEM */
3277 pin = old_ref_mod >= 0 && new_ref_mod < 0;
3280 if (last_ref && btrfs_header_generation(buf) == trans->transid) {
3281 struct btrfs_block_group *cache;
3283 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
3284 ret = check_ref_cleanup(trans, buf->start);
3290 cache = btrfs_lookup_block_group(fs_info, buf->start);
3292 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
3293 pin_down_extent(trans, cache, buf->start, buf->len, 1);
3294 btrfs_put_block_group(cache);
3298 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
3300 btrfs_add_free_space(cache, buf->start, buf->len);
3301 btrfs_free_reserved_bytes(cache, buf->len, 0);
3302 btrfs_put_block_group(cache);
3303 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
3307 add_pinned_bytes(fs_info, &generic_ref);
3311 * Deleting the buffer, clear the corrupt flag since it doesn't
3314 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
3318 /* Can return -ENOMEM */
3319 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
3321 struct btrfs_fs_info *fs_info = trans->fs_info;
3322 int old_ref_mod, new_ref_mod;
3325 if (btrfs_is_testing(fs_info))
3329 * tree log blocks never actually go into the extent allocation
3330 * tree, just update pinning info and exit early.
3332 if ((ref->type == BTRFS_REF_METADATA &&
3333 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
3334 (ref->type == BTRFS_REF_DATA &&
3335 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)) {
3336 /* unlocks the pinned mutex */
3337 btrfs_pin_extent(trans, ref->bytenr, ref->len, 1);
3338 old_ref_mod = new_ref_mod = 0;
3340 } else if (ref->type == BTRFS_REF_METADATA) {
3341 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL,
3342 &old_ref_mod, &new_ref_mod);
3344 ret = btrfs_add_delayed_data_ref(trans, ref, 0,
3345 &old_ref_mod, &new_ref_mod);
3348 if (!((ref->type == BTRFS_REF_METADATA &&
3349 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
3350 (ref->type == BTRFS_REF_DATA &&
3351 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)))
3352 btrfs_ref_tree_mod(fs_info, ref);
3354 if (ret == 0 && old_ref_mod >= 0 && new_ref_mod < 0)
3355 add_pinned_bytes(fs_info, ref);
3360 enum btrfs_loop_type {
3361 LOOP_CACHING_NOWAIT,
3368 btrfs_lock_block_group(struct btrfs_block_group *cache,
3372 down_read(&cache->data_rwsem);
3375 static inline void btrfs_grab_block_group(struct btrfs_block_group *cache,
3378 btrfs_get_block_group(cache);
3380 down_read(&cache->data_rwsem);
3383 static struct btrfs_block_group *btrfs_lock_cluster(
3384 struct btrfs_block_group *block_group,
3385 struct btrfs_free_cluster *cluster,
3388 struct btrfs_block_group *used_bg = NULL;
3390 spin_lock(&cluster->refill_lock);
3392 used_bg = cluster->block_group;
3396 if (used_bg == block_group)
3399 btrfs_get_block_group(used_bg);
3404 if (down_read_trylock(&used_bg->data_rwsem))
3407 spin_unlock(&cluster->refill_lock);
3409 /* We should only have one-level nested. */
3410 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
3412 spin_lock(&cluster->refill_lock);
3413 if (used_bg == cluster->block_group)
3416 up_read(&used_bg->data_rwsem);
3417 btrfs_put_block_group(used_bg);
3422 btrfs_release_block_group(struct btrfs_block_group *cache,
3426 up_read(&cache->data_rwsem);
3427 btrfs_put_block_group(cache);
3430 enum btrfs_extent_allocation_policy {
3431 BTRFS_EXTENT_ALLOC_CLUSTERED,
3435 * Structure used internally for find_free_extent() function. Wraps needed
3438 struct find_free_extent_ctl {
3439 /* Basic allocation info */
3445 /* Where to start the search inside the bg */
3448 /* For clustered allocation */
3450 struct btrfs_free_cluster *last_ptr;
3453 bool have_caching_bg;
3454 bool orig_have_caching_bg;
3456 /* RAID index, converted from flags */
3460 * Current loop number, check find_free_extent_update_loop() for details
3465 * Whether we're refilling a cluster, if true we need to re-search
3466 * current block group but don't try to refill the cluster again.
3468 bool retry_clustered;
3471 * Whether we're updating free space cache, if true we need to re-search
3472 * current block group but don't try updating free space cache again.
3474 bool retry_unclustered;
3476 /* If current block group is cached */
3479 /* Max contiguous hole found */
3480 u64 max_extent_size;
3482 /* Total free space from free space cache, not always contiguous */
3483 u64 total_free_space;
3488 /* Hint where to start looking for an empty space */
3491 /* Allocation policy */
3492 enum btrfs_extent_allocation_policy policy;
3497 * Helper function for find_free_extent().
3499 * Return -ENOENT to inform caller that we need fallback to unclustered mode.
3500 * Return -EAGAIN to inform caller that we need to re-search this block group
3501 * Return >0 to inform caller that we find nothing
3502 * Return 0 means we have found a location and set ffe_ctl->found_offset.
3504 static int find_free_extent_clustered(struct btrfs_block_group *bg,
3505 struct btrfs_free_cluster *last_ptr,
3506 struct find_free_extent_ctl *ffe_ctl,
3507 struct btrfs_block_group **cluster_bg_ret)
3509 struct btrfs_block_group *cluster_bg;
3510 u64 aligned_cluster;
3514 cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
3516 goto refill_cluster;
3517 if (cluster_bg != bg && (cluster_bg->ro ||
3518 !block_group_bits(cluster_bg, ffe_ctl->flags)))
3519 goto release_cluster;
3521 offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
3522 ffe_ctl->num_bytes, cluster_bg->start,
3523 &ffe_ctl->max_extent_size);
3525 /* We have a block, we're done */
3526 spin_unlock(&last_ptr->refill_lock);
3527 trace_btrfs_reserve_extent_cluster(cluster_bg,
3528 ffe_ctl->search_start, ffe_ctl->num_bytes);
3529 *cluster_bg_ret = cluster_bg;
3530 ffe_ctl->found_offset = offset;
3533 WARN_ON(last_ptr->block_group != cluster_bg);
3537 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
3538 * lets just skip it and let the allocator find whatever block it can
3539 * find. If we reach this point, we will have tried the cluster
3540 * allocator plenty of times and not have found anything, so we are
3541 * likely way too fragmented for the clustering stuff to find anything.
3543 * However, if the cluster is taken from the current block group,
3544 * release the cluster first, so that we stand a better chance of
3545 * succeeding in the unclustered allocation.
3547 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
3548 spin_unlock(&last_ptr->refill_lock);
3549 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3553 /* This cluster didn't work out, free it and start over */
3554 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3556 if (cluster_bg != bg)
3557 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3560 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
3561 spin_unlock(&last_ptr->refill_lock);
3565 aligned_cluster = max_t(u64,
3566 ffe_ctl->empty_cluster + ffe_ctl->empty_size,
3567 bg->full_stripe_len);
3568 ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
3569 ffe_ctl->num_bytes, aligned_cluster);
3571 /* Now pull our allocation out of this cluster */
3572 offset = btrfs_alloc_from_cluster(bg, last_ptr,
3573 ffe_ctl->num_bytes, ffe_ctl->search_start,
3574 &ffe_ctl->max_extent_size);
3576 /* We found one, proceed */
3577 spin_unlock(&last_ptr->refill_lock);
3578 trace_btrfs_reserve_extent_cluster(bg,
3579 ffe_ctl->search_start,
3580 ffe_ctl->num_bytes);
3581 ffe_ctl->found_offset = offset;
3584 } else if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
3585 !ffe_ctl->retry_clustered) {
3586 spin_unlock(&last_ptr->refill_lock);
3588 ffe_ctl->retry_clustered = true;
3589 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3590 ffe_ctl->empty_cluster + ffe_ctl->empty_size);
3594 * At this point we either didn't find a cluster or we weren't able to
3595 * allocate a block from our cluster. Free the cluster we've been
3596 * trying to use, and go to the next block group.
3598 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3599 spin_unlock(&last_ptr->refill_lock);
3604 * Return >0 to inform caller that we find nothing
3605 * Return 0 when we found an free extent and set ffe_ctrl->found_offset
3606 * Return -EAGAIN to inform caller that we need to re-search this block group
3608 static int find_free_extent_unclustered(struct btrfs_block_group *bg,
3609 struct btrfs_free_cluster *last_ptr,
3610 struct find_free_extent_ctl *ffe_ctl)
3615 * We are doing an unclustered allocation, set the fragmented flag so
3616 * we don't bother trying to setup a cluster again until we get more
3619 if (unlikely(last_ptr)) {
3620 spin_lock(&last_ptr->lock);
3621 last_ptr->fragmented = 1;
3622 spin_unlock(&last_ptr->lock);
3624 if (ffe_ctl->cached) {
3625 struct btrfs_free_space_ctl *free_space_ctl;
3627 free_space_ctl = bg->free_space_ctl;
3628 spin_lock(&free_space_ctl->tree_lock);
3629 if (free_space_ctl->free_space <
3630 ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
3631 ffe_ctl->empty_size) {
3632 ffe_ctl->total_free_space = max_t(u64,
3633 ffe_ctl->total_free_space,
3634 free_space_ctl->free_space);
3635 spin_unlock(&free_space_ctl->tree_lock);
3638 spin_unlock(&free_space_ctl->tree_lock);
3641 offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
3642 ffe_ctl->num_bytes, ffe_ctl->empty_size,
3643 &ffe_ctl->max_extent_size);
3646 * If we didn't find a chunk, and we haven't failed on this block group
3647 * before, and this block group is in the middle of caching and we are
3648 * ok with waiting, then go ahead and wait for progress to be made, and
3649 * set @retry_unclustered to true.
3651 * If @retry_unclustered is true then we've already waited on this
3652 * block group once and should move on to the next block group.
3654 if (!offset && !ffe_ctl->retry_unclustered && !ffe_ctl->cached &&
3655 ffe_ctl->loop > LOOP_CACHING_NOWAIT) {
3656 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3657 ffe_ctl->empty_size);
3658 ffe_ctl->retry_unclustered = true;
3660 } else if (!offset) {
3663 ffe_ctl->found_offset = offset;
3668 * Return >0 means caller needs to re-search for free extent
3669 * Return 0 means we have the needed free extent.
3670 * Return <0 means we failed to locate any free extent.
3672 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
3673 struct btrfs_free_cluster *last_ptr,
3674 struct btrfs_key *ins,
3675 struct find_free_extent_ctl *ffe_ctl,
3676 bool full_search, bool use_cluster)
3678 struct btrfs_root *root = fs_info->extent_root;
3681 if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
3682 ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
3683 ffe_ctl->orig_have_caching_bg = true;
3685 if (!ins->objectid && ffe_ctl->loop >= LOOP_CACHING_WAIT &&
3686 ffe_ctl->have_caching_bg)
3689 if (!ins->objectid && ++(ffe_ctl->index) < BTRFS_NR_RAID_TYPES)
3692 if (ins->objectid) {
3693 if (!use_cluster && last_ptr) {
3694 spin_lock(&last_ptr->lock);
3695 last_ptr->window_start = ins->objectid;
3696 spin_unlock(&last_ptr->lock);
3702 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
3703 * caching kthreads as we move along
3704 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
3705 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
3706 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
3709 if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
3711 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT) {
3713 * We want to skip the LOOP_CACHING_WAIT step if we
3714 * don't have any uncached bgs and we've already done a
3715 * full search through.
3717 if (ffe_ctl->orig_have_caching_bg || !full_search)
3718 ffe_ctl->loop = LOOP_CACHING_WAIT;
3720 ffe_ctl->loop = LOOP_ALLOC_CHUNK;
3725 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
3726 struct btrfs_trans_handle *trans;
3729 trans = current->journal_info;
3733 trans = btrfs_join_transaction(root);
3735 if (IS_ERR(trans)) {
3736 ret = PTR_ERR(trans);
3740 ret = btrfs_chunk_alloc(trans, ffe_ctl->flags,
3744 * If we can't allocate a new chunk we've already looped
3745 * through at least once, move on to the NO_EMPTY_SIZE
3749 ffe_ctl->loop = LOOP_NO_EMPTY_SIZE;
3751 /* Do not bail out on ENOSPC since we can do more. */
3752 if (ret < 0 && ret != -ENOSPC)
3753 btrfs_abort_transaction(trans, ret);
3757 btrfs_end_transaction(trans);
3762 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
3764 * Don't loop again if we already have no empty_size and
3767 if (ffe_ctl->empty_size == 0 &&
3768 ffe_ctl->empty_cluster == 0)
3770 ffe_ctl->empty_size = 0;
3771 ffe_ctl->empty_cluster = 0;
3779 * walks the btree of allocated extents and find a hole of a given size.
3780 * The key ins is changed to record the hole:
3781 * ins->objectid == start position
3782 * ins->flags = BTRFS_EXTENT_ITEM_KEY
3783 * ins->offset == the size of the hole.
3784 * Any available blocks before search_start are skipped.
3786 * If there is no suitable free space, we will record the max size of
3787 * the free space extent currently.
3789 * The overall logic and call chain:
3791 * find_free_extent()
3792 * |- Iterate through all block groups
3793 * | |- Get a valid block group
3794 * | |- Try to do clustered allocation in that block group
3795 * | |- Try to do unclustered allocation in that block group
3796 * | |- Check if the result is valid
3797 * | | |- If valid, then exit
3798 * | |- Jump to next block group
3800 * |- Push harder to find free extents
3801 * |- If not found, re-iterate all block groups
3803 static noinline int find_free_extent(struct btrfs_fs_info *fs_info,
3804 u64 ram_bytes, u64 num_bytes, u64 empty_size,
3805 u64 hint_byte_orig, struct btrfs_key *ins,
3806 u64 flags, int delalloc)
3809 int cache_block_group_error = 0;
3810 struct btrfs_block_group *block_group = NULL;
3811 struct find_free_extent_ctl ffe_ctl = {0};
3812 struct btrfs_space_info *space_info;
3813 bool full_search = false;
3815 WARN_ON(num_bytes < fs_info->sectorsize);
3817 ffe_ctl.num_bytes = num_bytes;
3818 ffe_ctl.empty_size = empty_size;
3819 ffe_ctl.flags = flags;
3820 ffe_ctl.search_start = 0;
3821 ffe_ctl.delalloc = delalloc;
3822 ffe_ctl.index = btrfs_bg_flags_to_raid_index(flags);
3823 ffe_ctl.have_caching_bg = false;
3824 ffe_ctl.orig_have_caching_bg = false;
3825 ffe_ctl.found_offset = 0;
3826 ffe_ctl.hint_byte = hint_byte_orig;
3827 ffe_ctl.policy = BTRFS_EXTENT_ALLOC_CLUSTERED;
3829 /* For clustered allocation */
3830 ffe_ctl.retry_clustered = false;
3831 ffe_ctl.retry_unclustered = false;
3832 ffe_ctl.last_ptr = NULL;
3833 ffe_ctl.use_cluster = true;
3835 ins->type = BTRFS_EXTENT_ITEM_KEY;
3839 trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
3841 space_info = btrfs_find_space_info(fs_info, flags);
3843 btrfs_err(fs_info, "No space info for %llu", flags);
3848 * If our free space is heavily fragmented we may not be able to make
3849 * big contiguous allocations, so instead of doing the expensive search
3850 * for free space, simply return ENOSPC with our max_extent_size so we
3851 * can go ahead and search for a more manageable chunk.
3853 * If our max_extent_size is large enough for our allocation simply
3854 * disable clustering since we will likely not be able to find enough
3855 * space to create a cluster and induce latency trying.
3857 if (unlikely(space_info->max_extent_size)) {
3858 spin_lock(&space_info->lock);
3859 if (space_info->max_extent_size &&
3860 num_bytes > space_info->max_extent_size) {
3861 ins->offset = space_info->max_extent_size;
3862 spin_unlock(&space_info->lock);
3864 } else if (space_info->max_extent_size) {
3865 ffe_ctl.use_cluster = false;
3867 spin_unlock(&space_info->lock);
3870 ffe_ctl.last_ptr = fetch_cluster_info(fs_info, space_info,
3871 &ffe_ctl.empty_cluster);
3872 if (ffe_ctl.last_ptr) {
3873 struct btrfs_free_cluster *last_ptr = ffe_ctl.last_ptr;
3875 spin_lock(&last_ptr->lock);
3876 if (last_ptr->block_group)
3877 ffe_ctl.hint_byte = last_ptr->window_start;
3878 if (last_ptr->fragmented) {
3880 * We still set window_start so we can keep track of the
3881 * last place we found an allocation to try and save
3884 ffe_ctl.hint_byte = last_ptr->window_start;
3885 ffe_ctl.use_cluster = false;
3887 spin_unlock(&last_ptr->lock);
3890 ffe_ctl.search_start = max(ffe_ctl.search_start,
3891 first_logical_byte(fs_info, 0));
3892 ffe_ctl.search_start = max(ffe_ctl.search_start, ffe_ctl.hint_byte);
3893 if (ffe_ctl.search_start == ffe_ctl.hint_byte) {
3894 block_group = btrfs_lookup_block_group(fs_info,
3895 ffe_ctl.search_start);
3897 * we don't want to use the block group if it doesn't match our
3898 * allocation bits, or if its not cached.
3900 * However if we are re-searching with an ideal block group
3901 * picked out then we don't care that the block group is cached.
3903 if (block_group && block_group_bits(block_group, flags) &&
3904 block_group->cached != BTRFS_CACHE_NO) {
3905 down_read(&space_info->groups_sem);
3906 if (list_empty(&block_group->list) ||
3909 * someone is removing this block group,
3910 * we can't jump into the have_block_group
3911 * target because our list pointers are not
3914 btrfs_put_block_group(block_group);
3915 up_read(&space_info->groups_sem);
3917 ffe_ctl.index = btrfs_bg_flags_to_raid_index(
3918 block_group->flags);
3919 btrfs_lock_block_group(block_group, delalloc);
3920 goto have_block_group;
3922 } else if (block_group) {
3923 btrfs_put_block_group(block_group);
3927 ffe_ctl.have_caching_bg = false;
3928 if (ffe_ctl.index == btrfs_bg_flags_to_raid_index(flags) ||
3931 down_read(&space_info->groups_sem);
3932 list_for_each_entry(block_group,
3933 &space_info->block_groups[ffe_ctl.index], list) {
3934 /* If the block group is read-only, we can skip it entirely. */
3935 if (unlikely(block_group->ro))
3938 btrfs_grab_block_group(block_group, delalloc);
3939 ffe_ctl.search_start = block_group->start;
3942 * this can happen if we end up cycling through all the
3943 * raid types, but we want to make sure we only allocate
3944 * for the proper type.
3946 if (!block_group_bits(block_group, flags)) {
3947 u64 extra = BTRFS_BLOCK_GROUP_DUP |
3948 BTRFS_BLOCK_GROUP_RAID1_MASK |
3949 BTRFS_BLOCK_GROUP_RAID56_MASK |
3950 BTRFS_BLOCK_GROUP_RAID10;
3953 * if they asked for extra copies and this block group
3954 * doesn't provide them, bail. This does allow us to
3955 * fill raid0 from raid1.
3957 if ((flags & extra) && !(block_group->flags & extra))
3961 * This block group has different flags than we want.
3962 * It's possible that we have MIXED_GROUP flag but no
3963 * block group is mixed. Just skip such block group.
3965 btrfs_release_block_group(block_group, delalloc);
3970 ffe_ctl.cached = btrfs_block_group_done(block_group);
3971 if (unlikely(!ffe_ctl.cached)) {
3972 ffe_ctl.have_caching_bg = true;
3973 ret = btrfs_cache_block_group(block_group, 0);
3976 * If we get ENOMEM here or something else we want to
3977 * try other block groups, because it may not be fatal.
3978 * However if we can't find anything else we need to
3979 * save our return here so that we return the actual
3980 * error that caused problems, not ENOSPC.
3983 if (!cache_block_group_error)
3984 cache_block_group_error = ret;
3991 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
3995 * Ok we want to try and use the cluster allocator, so
3998 if (ffe_ctl.last_ptr && ffe_ctl.use_cluster) {
3999 struct btrfs_block_group *cluster_bg = NULL;
4001 ret = find_free_extent_clustered(block_group,
4003 &ffe_ctl, &cluster_bg);
4006 if (cluster_bg && cluster_bg != block_group) {
4007 btrfs_release_block_group(block_group,
4009 block_group = cluster_bg;
4012 } else if (ret == -EAGAIN) {
4013 goto have_block_group;
4014 } else if (ret > 0) {
4017 /* ret == -ENOENT case falls through */
4020 ret = find_free_extent_unclustered(block_group,
4021 ffe_ctl.last_ptr, &ffe_ctl);
4023 goto have_block_group;
4026 /* ret == 0 case falls through */
4028 ffe_ctl.search_start = round_up(ffe_ctl.found_offset,
4029 fs_info->stripesize);
4031 /* move on to the next group */
4032 if (ffe_ctl.search_start + num_bytes >
4033 block_group->start + block_group->length) {
4034 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
4039 if (ffe_ctl.found_offset < ffe_ctl.search_start)
4040 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
4041 ffe_ctl.search_start - ffe_ctl.found_offset);
4043 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
4044 num_bytes, delalloc);
4045 if (ret == -EAGAIN) {
4046 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
4050 btrfs_inc_block_group_reservations(block_group);
4052 /* we are all good, lets return */
4053 ins->objectid = ffe_ctl.search_start;
4054 ins->offset = num_bytes;
4056 trace_btrfs_reserve_extent(block_group, ffe_ctl.search_start,
4058 btrfs_release_block_group(block_group, delalloc);
4061 ffe_ctl.retry_clustered = false;
4062 ffe_ctl.retry_unclustered = false;
4063 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
4065 btrfs_release_block_group(block_group, delalloc);
4068 up_read(&space_info->groups_sem);
4070 ret = find_free_extent_update_loop(fs_info, ffe_ctl.last_ptr, ins,
4071 &ffe_ctl, full_search,
4072 ffe_ctl.use_cluster);
4076 if (ret == -ENOSPC && !cache_block_group_error) {
4078 * Use ffe_ctl->total_free_space as fallback if we can't find
4079 * any contiguous hole.
4081 if (!ffe_ctl.max_extent_size)
4082 ffe_ctl.max_extent_size = ffe_ctl.total_free_space;
4083 spin_lock(&space_info->lock);
4084 space_info->max_extent_size = ffe_ctl.max_extent_size;
4085 spin_unlock(&space_info->lock);
4086 ins->offset = ffe_ctl.max_extent_size;
4087 } else if (ret == -ENOSPC) {
4088 ret = cache_block_group_error;
4094 * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
4095 * hole that is at least as big as @num_bytes.
4097 * @root - The root that will contain this extent
4099 * @ram_bytes - The amount of space in ram that @num_bytes take. This
4100 * is used for accounting purposes. This value differs
4101 * from @num_bytes only in the case of compressed extents.
4103 * @num_bytes - Number of bytes to allocate on-disk.
4105 * @min_alloc_size - Indicates the minimum amount of space that the
4106 * allocator should try to satisfy. In some cases
4107 * @num_bytes may be larger than what is required and if
4108 * the filesystem is fragmented then allocation fails.
4109 * However, the presence of @min_alloc_size gives a
4110 * chance to try and satisfy the smaller allocation.
4112 * @empty_size - A hint that you plan on doing more COW. This is the
4113 * size in bytes the allocator should try to find free
4114 * next to the block it returns. This is just a hint and
4115 * may be ignored by the allocator.
4117 * @hint_byte - Hint to the allocator to start searching above the byte
4118 * address passed. It might be ignored.
4120 * @ins - This key is modified to record the found hole. It will
4121 * have the following values:
4122 * ins->objectid == start position
4123 * ins->flags = BTRFS_EXTENT_ITEM_KEY
4124 * ins->offset == the size of the hole.
4126 * @is_data - Boolean flag indicating whether an extent is
4127 * allocated for data (true) or metadata (false)
4129 * @delalloc - Boolean flag indicating whether this allocation is for
4130 * delalloc or not. If 'true' data_rwsem of block groups
4131 * is going to be acquired.
4134 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
4135 * case -ENOSPC is returned then @ins->offset will contain the size of the
4136 * largest available hole the allocator managed to find.
4138 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
4139 u64 num_bytes, u64 min_alloc_size,
4140 u64 empty_size, u64 hint_byte,
4141 struct btrfs_key *ins, int is_data, int delalloc)
4143 struct btrfs_fs_info *fs_info = root->fs_info;
4144 bool final_tried = num_bytes == min_alloc_size;
4148 flags = get_alloc_profile_by_root(root, is_data);
4150 WARN_ON(num_bytes < fs_info->sectorsize);
4151 ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
4152 hint_byte, ins, flags, delalloc);
4153 if (!ret && !is_data) {
4154 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
4155 } else if (ret == -ENOSPC) {
4156 if (!final_tried && ins->offset) {
4157 num_bytes = min(num_bytes >> 1, ins->offset);
4158 num_bytes = round_down(num_bytes,
4159 fs_info->sectorsize);
4160 num_bytes = max(num_bytes, min_alloc_size);
4161 ram_bytes = num_bytes;
4162 if (num_bytes == min_alloc_size)
4165 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4166 struct btrfs_space_info *sinfo;
4168 sinfo = btrfs_find_space_info(fs_info, flags);
4170 "allocation failed flags %llu, wanted %llu",
4173 btrfs_dump_space_info(fs_info, sinfo,
4181 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
4182 u64 start, u64 len, int delalloc)
4184 struct btrfs_block_group *cache;
4186 cache = btrfs_lookup_block_group(fs_info, start);
4188 btrfs_err(fs_info, "Unable to find block group for %llu",
4193 btrfs_add_free_space(cache, start, len);
4194 btrfs_free_reserved_bytes(cache, len, delalloc);
4195 trace_btrfs_reserved_extent_free(fs_info, start, len);
4197 btrfs_put_block_group(cache);
4201 int btrfs_pin_reserved_extent(struct btrfs_trans_handle *trans, u64 start,
4204 struct btrfs_block_group *cache;
4207 cache = btrfs_lookup_block_group(trans->fs_info, start);
4209 btrfs_err(trans->fs_info, "unable to find block group for %llu",
4214 ret = pin_down_extent(trans, cache, start, len, 1);
4215 btrfs_put_block_group(cache);
4219 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4220 u64 parent, u64 root_objectid,
4221 u64 flags, u64 owner, u64 offset,
4222 struct btrfs_key *ins, int ref_mod)
4224 struct btrfs_fs_info *fs_info = trans->fs_info;
4226 struct btrfs_extent_item *extent_item;
4227 struct btrfs_extent_inline_ref *iref;
4228 struct btrfs_path *path;
4229 struct extent_buffer *leaf;
4234 type = BTRFS_SHARED_DATA_REF_KEY;
4236 type = BTRFS_EXTENT_DATA_REF_KEY;
4238 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
4240 path = btrfs_alloc_path();
4244 path->leave_spinning = 1;
4245 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4248 btrfs_free_path(path);
4252 leaf = path->nodes[0];
4253 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4254 struct btrfs_extent_item);
4255 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
4256 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4257 btrfs_set_extent_flags(leaf, extent_item,
4258 flags | BTRFS_EXTENT_FLAG_DATA);
4260 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4261 btrfs_set_extent_inline_ref_type(leaf, iref, type);
4263 struct btrfs_shared_data_ref *ref;
4264 ref = (struct btrfs_shared_data_ref *)(iref + 1);
4265 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
4266 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
4268 struct btrfs_extent_data_ref *ref;
4269 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
4270 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
4271 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
4272 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
4273 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
4276 btrfs_mark_buffer_dirty(path->nodes[0]);
4277 btrfs_free_path(path);
4279 ret = remove_from_free_space_tree(trans, ins->objectid, ins->offset);
4283 ret = btrfs_update_block_group(trans, ins->objectid, ins->offset, 1);
4284 if (ret) { /* -ENOENT, logic error */
4285 btrfs_err(fs_info, "update block group failed for %llu %llu",
4286 ins->objectid, ins->offset);
4289 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
4293 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
4294 struct btrfs_delayed_ref_node *node,
4295 struct btrfs_delayed_extent_op *extent_op)
4297 struct btrfs_fs_info *fs_info = trans->fs_info;
4299 struct btrfs_extent_item *extent_item;
4300 struct btrfs_key extent_key;
4301 struct btrfs_tree_block_info *block_info;
4302 struct btrfs_extent_inline_ref *iref;
4303 struct btrfs_path *path;
4304 struct extent_buffer *leaf;
4305 struct btrfs_delayed_tree_ref *ref;
4306 u32 size = sizeof(*extent_item) + sizeof(*iref);
4308 u64 flags = extent_op->flags_to_set;
4309 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4311 ref = btrfs_delayed_node_to_tree_ref(node);
4313 extent_key.objectid = node->bytenr;
4314 if (skinny_metadata) {
4315 extent_key.offset = ref->level;
4316 extent_key.type = BTRFS_METADATA_ITEM_KEY;
4317 num_bytes = fs_info->nodesize;
4319 extent_key.offset = node->num_bytes;
4320 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
4321 size += sizeof(*block_info);
4322 num_bytes = node->num_bytes;
4325 path = btrfs_alloc_path();
4329 path->leave_spinning = 1;
4330 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4333 btrfs_free_path(path);
4337 leaf = path->nodes[0];
4338 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4339 struct btrfs_extent_item);
4340 btrfs_set_extent_refs(leaf, extent_item, 1);
4341 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4342 btrfs_set_extent_flags(leaf, extent_item,
4343 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
4345 if (skinny_metadata) {
4346 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4348 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
4349 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
4350 btrfs_set_tree_block_level(leaf, block_info, ref->level);
4351 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
4354 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
4355 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
4356 btrfs_set_extent_inline_ref_type(leaf, iref,
4357 BTRFS_SHARED_BLOCK_REF_KEY);
4358 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
4360 btrfs_set_extent_inline_ref_type(leaf, iref,
4361 BTRFS_TREE_BLOCK_REF_KEY);
4362 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
4365 btrfs_mark_buffer_dirty(leaf);
4366 btrfs_free_path(path);
4368 ret = remove_from_free_space_tree(trans, extent_key.objectid,
4373 ret = btrfs_update_block_group(trans, extent_key.objectid,
4374 fs_info->nodesize, 1);
4375 if (ret) { /* -ENOENT, logic error */
4376 btrfs_err(fs_info, "update block group failed for %llu %llu",
4377 extent_key.objectid, extent_key.offset);
4381 trace_btrfs_reserved_extent_alloc(fs_info, extent_key.objectid,
4386 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4387 struct btrfs_root *root, u64 owner,
4388 u64 offset, u64 ram_bytes,
4389 struct btrfs_key *ins)
4391 struct btrfs_ref generic_ref = { 0 };
4394 BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
4396 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4397 ins->objectid, ins->offset, 0);
4398 btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner, offset);
4399 btrfs_ref_tree_mod(root->fs_info, &generic_ref);
4400 ret = btrfs_add_delayed_data_ref(trans, &generic_ref,
4401 ram_bytes, NULL, NULL);
4406 * this is used by the tree logging recovery code. It records that
4407 * an extent has been allocated and makes sure to clear the free
4408 * space cache bits as well
4410 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
4411 u64 root_objectid, u64 owner, u64 offset,
4412 struct btrfs_key *ins)
4414 struct btrfs_fs_info *fs_info = trans->fs_info;
4416 struct btrfs_block_group *block_group;
4417 struct btrfs_space_info *space_info;
4420 * Mixed block groups will exclude before processing the log so we only
4421 * need to do the exclude dance if this fs isn't mixed.
4423 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
4424 ret = __exclude_logged_extent(fs_info, ins->objectid,
4430 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
4434 space_info = block_group->space_info;
4435 spin_lock(&space_info->lock);
4436 spin_lock(&block_group->lock);
4437 space_info->bytes_reserved += ins->offset;
4438 block_group->reserved += ins->offset;
4439 spin_unlock(&block_group->lock);
4440 spin_unlock(&space_info->lock);
4442 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
4445 btrfs_pin_extent(trans, ins->objectid, ins->offset, 1);
4446 btrfs_put_block_group(block_group);
4450 static struct extent_buffer *
4451 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4452 u64 bytenr, int level, u64 owner)
4454 struct btrfs_fs_info *fs_info = root->fs_info;
4455 struct extent_buffer *buf;
4457 buf = btrfs_find_create_tree_block(fs_info, bytenr);
4462 * Extra safety check in case the extent tree is corrupted and extent
4463 * allocator chooses to use a tree block which is already used and
4466 if (buf->lock_owner == current->pid) {
4467 btrfs_err_rl(fs_info,
4468 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
4469 buf->start, btrfs_header_owner(buf), current->pid);
4470 free_extent_buffer(buf);
4471 return ERR_PTR(-EUCLEAN);
4474 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
4475 btrfs_tree_lock(buf);
4476 btrfs_clean_tree_block(buf);
4477 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
4479 btrfs_set_lock_blocking_write(buf);
4480 set_extent_buffer_uptodate(buf);
4482 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
4483 btrfs_set_header_level(buf, level);
4484 btrfs_set_header_bytenr(buf, buf->start);
4485 btrfs_set_header_generation(buf, trans->transid);
4486 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
4487 btrfs_set_header_owner(buf, owner);
4488 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
4489 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
4490 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
4491 buf->log_index = root->log_transid % 2;
4493 * we allow two log transactions at a time, use different
4494 * EXTENT bit to differentiate dirty pages.
4496 if (buf->log_index == 0)
4497 set_extent_dirty(&root->dirty_log_pages, buf->start,
4498 buf->start + buf->len - 1, GFP_NOFS);
4500 set_extent_new(&root->dirty_log_pages, buf->start,
4501 buf->start + buf->len - 1);
4503 buf->log_index = -1;
4504 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
4505 buf->start + buf->len - 1, GFP_NOFS);
4507 trans->dirty = true;
4508 /* this returns a buffer locked for blocking */
4513 * finds a free extent and does all the dirty work required for allocation
4514 * returns the tree buffer or an ERR_PTR on error.
4516 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
4517 struct btrfs_root *root,
4518 u64 parent, u64 root_objectid,
4519 const struct btrfs_disk_key *key,
4520 int level, u64 hint,
4523 struct btrfs_fs_info *fs_info = root->fs_info;
4524 struct btrfs_key ins;
4525 struct btrfs_block_rsv *block_rsv;
4526 struct extent_buffer *buf;
4527 struct btrfs_delayed_extent_op *extent_op;
4528 struct btrfs_ref generic_ref = { 0 };
4531 u32 blocksize = fs_info->nodesize;
4532 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4534 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4535 if (btrfs_is_testing(fs_info)) {
4536 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
4537 level, root_objectid);
4539 root->alloc_bytenr += blocksize;
4544 block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
4545 if (IS_ERR(block_rsv))
4546 return ERR_CAST(block_rsv);
4548 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
4549 empty_size, hint, &ins, 0, 0);
4553 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
4557 goto out_free_reserved;
4560 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
4562 parent = ins.objectid;
4563 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4567 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
4568 extent_op = btrfs_alloc_delayed_extent_op();
4574 memcpy(&extent_op->key, key, sizeof(extent_op->key));
4576 memset(&extent_op->key, 0, sizeof(extent_op->key));
4577 extent_op->flags_to_set = flags;
4578 extent_op->update_key = skinny_metadata ? false : true;
4579 extent_op->update_flags = true;
4580 extent_op->is_data = false;
4581 extent_op->level = level;
4583 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4584 ins.objectid, ins.offset, parent);
4585 generic_ref.real_root = root->root_key.objectid;
4586 btrfs_init_tree_ref(&generic_ref, level, root_objectid);
4587 btrfs_ref_tree_mod(fs_info, &generic_ref);
4588 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref,
4589 extent_op, NULL, NULL);
4591 goto out_free_delayed;
4596 btrfs_free_delayed_extent_op(extent_op);
4598 free_extent_buffer(buf);
4600 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
4602 btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
4603 return ERR_PTR(ret);
4606 struct walk_control {
4607 u64 refs[BTRFS_MAX_LEVEL];
4608 u64 flags[BTRFS_MAX_LEVEL];
4609 struct btrfs_key update_progress;
4610 struct btrfs_key drop_progress;
4622 #define DROP_REFERENCE 1
4623 #define UPDATE_BACKREF 2
4625 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
4626 struct btrfs_root *root,
4627 struct walk_control *wc,
4628 struct btrfs_path *path)
4630 struct btrfs_fs_info *fs_info = root->fs_info;
4636 struct btrfs_key key;
4637 struct extent_buffer *eb;
4642 if (path->slots[wc->level] < wc->reada_slot) {
4643 wc->reada_count = wc->reada_count * 2 / 3;
4644 wc->reada_count = max(wc->reada_count, 2);
4646 wc->reada_count = wc->reada_count * 3 / 2;
4647 wc->reada_count = min_t(int, wc->reada_count,
4648 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
4651 eb = path->nodes[wc->level];
4652 nritems = btrfs_header_nritems(eb);
4654 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
4655 if (nread >= wc->reada_count)
4659 bytenr = btrfs_node_blockptr(eb, slot);
4660 generation = btrfs_node_ptr_generation(eb, slot);
4662 if (slot == path->slots[wc->level])
4665 if (wc->stage == UPDATE_BACKREF &&
4666 generation <= root->root_key.offset)
4669 /* We don't lock the tree block, it's OK to be racy here */
4670 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
4671 wc->level - 1, 1, &refs,
4673 /* We don't care about errors in readahead. */
4678 if (wc->stage == DROP_REFERENCE) {
4682 if (wc->level == 1 &&
4683 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4685 if (!wc->update_ref ||
4686 generation <= root->root_key.offset)
4688 btrfs_node_key_to_cpu(eb, &key, slot);
4689 ret = btrfs_comp_cpu_keys(&key,
4690 &wc->update_progress);
4694 if (wc->level == 1 &&
4695 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4699 readahead_tree_block(fs_info, bytenr);
4702 wc->reada_slot = slot;
4706 * helper to process tree block while walking down the tree.
4708 * when wc->stage == UPDATE_BACKREF, this function updates
4709 * back refs for pointers in the block.
4711 * NOTE: return value 1 means we should stop walking down.
4713 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
4714 struct btrfs_root *root,
4715 struct btrfs_path *path,
4716 struct walk_control *wc, int lookup_info)
4718 struct btrfs_fs_info *fs_info = root->fs_info;
4719 int level = wc->level;
4720 struct extent_buffer *eb = path->nodes[level];
4721 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
4724 if (wc->stage == UPDATE_BACKREF &&
4725 btrfs_header_owner(eb) != root->root_key.objectid)
4729 * when reference count of tree block is 1, it won't increase
4730 * again. once full backref flag is set, we never clear it.
4733 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
4734 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
4735 BUG_ON(!path->locks[level]);
4736 ret = btrfs_lookup_extent_info(trans, fs_info,
4737 eb->start, level, 1,
4740 BUG_ON(ret == -ENOMEM);
4743 BUG_ON(wc->refs[level] == 0);
4746 if (wc->stage == DROP_REFERENCE) {
4747 if (wc->refs[level] > 1)
4750 if (path->locks[level] && !wc->keep_locks) {
4751 btrfs_tree_unlock_rw(eb, path->locks[level]);
4752 path->locks[level] = 0;
4757 /* wc->stage == UPDATE_BACKREF */
4758 if (!(wc->flags[level] & flag)) {
4759 BUG_ON(!path->locks[level]);
4760 ret = btrfs_inc_ref(trans, root, eb, 1);
4761 BUG_ON(ret); /* -ENOMEM */
4762 ret = btrfs_dec_ref(trans, root, eb, 0);
4763 BUG_ON(ret); /* -ENOMEM */
4764 ret = btrfs_set_disk_extent_flags(trans, eb, flag,
4765 btrfs_header_level(eb), 0);
4766 BUG_ON(ret); /* -ENOMEM */
4767 wc->flags[level] |= flag;
4771 * the block is shared by multiple trees, so it's not good to
4772 * keep the tree lock
4774 if (path->locks[level] && level > 0) {
4775 btrfs_tree_unlock_rw(eb, path->locks[level]);
4776 path->locks[level] = 0;
4782 * This is used to verify a ref exists for this root to deal with a bug where we
4783 * would have a drop_progress key that hadn't been updated properly.
4785 static int check_ref_exists(struct btrfs_trans_handle *trans,
4786 struct btrfs_root *root, u64 bytenr, u64 parent,
4789 struct btrfs_path *path;
4790 struct btrfs_extent_inline_ref *iref;
4793 path = btrfs_alloc_path();
4797 ret = lookup_extent_backref(trans, path, &iref, bytenr,
4798 root->fs_info->nodesize, parent,
4799 root->root_key.objectid, level, 0);
4800 btrfs_free_path(path);
4809 * helper to process tree block pointer.
4811 * when wc->stage == DROP_REFERENCE, this function checks
4812 * reference count of the block pointed to. if the block
4813 * is shared and we need update back refs for the subtree
4814 * rooted at the block, this function changes wc->stage to
4815 * UPDATE_BACKREF. if the block is shared and there is no
4816 * need to update back, this function drops the reference
4819 * NOTE: return value 1 means we should stop walking down.
4821 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
4822 struct btrfs_root *root,
4823 struct btrfs_path *path,
4824 struct walk_control *wc, int *lookup_info)
4826 struct btrfs_fs_info *fs_info = root->fs_info;
4830 struct btrfs_key key;
4831 struct btrfs_key first_key;
4832 struct btrfs_ref ref = { 0 };
4833 struct extent_buffer *next;
4834 int level = wc->level;
4837 bool need_account = false;
4839 generation = btrfs_node_ptr_generation(path->nodes[level],
4840 path->slots[level]);
4842 * if the lower level block was created before the snapshot
4843 * was created, we know there is no need to update back refs
4846 if (wc->stage == UPDATE_BACKREF &&
4847 generation <= root->root_key.offset) {
4852 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
4853 btrfs_node_key_to_cpu(path->nodes[level], &first_key,
4854 path->slots[level]);
4856 next = find_extent_buffer(fs_info, bytenr);
4858 next = btrfs_find_create_tree_block(fs_info, bytenr);
4860 return PTR_ERR(next);
4862 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
4866 btrfs_tree_lock(next);
4867 btrfs_set_lock_blocking_write(next);
4869 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
4870 &wc->refs[level - 1],
4871 &wc->flags[level - 1]);
4875 if (unlikely(wc->refs[level - 1] == 0)) {
4876 btrfs_err(fs_info, "Missing references.");
4882 if (wc->stage == DROP_REFERENCE) {
4883 if (wc->refs[level - 1] > 1) {
4884 need_account = true;
4886 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4889 if (!wc->update_ref ||
4890 generation <= root->root_key.offset)
4893 btrfs_node_key_to_cpu(path->nodes[level], &key,
4894 path->slots[level]);
4895 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
4899 wc->stage = UPDATE_BACKREF;
4900 wc->shared_level = level - 1;
4904 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4908 if (!btrfs_buffer_uptodate(next, generation, 0)) {
4909 btrfs_tree_unlock(next);
4910 free_extent_buffer(next);
4916 if (reada && level == 1)
4917 reada_walk_down(trans, root, wc, path);
4918 next = read_tree_block(fs_info, bytenr, generation, level - 1,
4921 return PTR_ERR(next);
4922 } else if (!extent_buffer_uptodate(next)) {
4923 free_extent_buffer(next);
4926 btrfs_tree_lock(next);
4927 btrfs_set_lock_blocking_write(next);
4931 ASSERT(level == btrfs_header_level(next));
4932 if (level != btrfs_header_level(next)) {
4933 btrfs_err(root->fs_info, "mismatched level");
4937 path->nodes[level] = next;
4938 path->slots[level] = 0;
4939 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
4945 wc->refs[level - 1] = 0;
4946 wc->flags[level - 1] = 0;
4947 if (wc->stage == DROP_REFERENCE) {
4948 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
4949 parent = path->nodes[level]->start;
4951 ASSERT(root->root_key.objectid ==
4952 btrfs_header_owner(path->nodes[level]));
4953 if (root->root_key.objectid !=
4954 btrfs_header_owner(path->nodes[level])) {
4955 btrfs_err(root->fs_info,
4956 "mismatched block owner");
4964 * If we had a drop_progress we need to verify the refs are set
4965 * as expected. If we find our ref then we know that from here
4966 * on out everything should be correct, and we can clear the
4969 if (wc->restarted) {
4970 ret = check_ref_exists(trans, root, bytenr, parent,
4981 * Reloc tree doesn't contribute to qgroup numbers, and we have
4982 * already accounted them at merge time (replace_path),
4983 * thus we could skip expensive subtree trace here.
4985 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
4987 ret = btrfs_qgroup_trace_subtree(trans, next,
4988 generation, level - 1);
4990 btrfs_err_rl(fs_info,
4991 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
4997 * We need to update the next key in our walk control so we can
4998 * update the drop_progress key accordingly. We don't care if
4999 * find_next_key doesn't find a key because that means we're at
5000 * the end and are going to clean up now.
5002 wc->drop_level = level;
5003 find_next_key(path, level, &wc->drop_progress);
5005 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
5006 fs_info->nodesize, parent);
5007 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid);
5008 ret = btrfs_free_extent(trans, &ref);
5017 btrfs_tree_unlock(next);
5018 free_extent_buffer(next);
5024 * helper to process tree block while walking up the tree.
5026 * when wc->stage == DROP_REFERENCE, this function drops
5027 * reference count on the block.
5029 * when wc->stage == UPDATE_BACKREF, this function changes
5030 * wc->stage back to DROP_REFERENCE if we changed wc->stage
5031 * to UPDATE_BACKREF previously while processing the block.
5033 * NOTE: return value 1 means we should stop walking up.
5035 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
5036 struct btrfs_root *root,
5037 struct btrfs_path *path,
5038 struct walk_control *wc)
5040 struct btrfs_fs_info *fs_info = root->fs_info;
5042 int level = wc->level;
5043 struct extent_buffer *eb = path->nodes[level];
5046 if (wc->stage == UPDATE_BACKREF) {
5047 BUG_ON(wc->shared_level < level);
5048 if (level < wc->shared_level)
5051 ret = find_next_key(path, level + 1, &wc->update_progress);
5055 wc->stage = DROP_REFERENCE;
5056 wc->shared_level = -1;
5057 path->slots[level] = 0;
5060 * check reference count again if the block isn't locked.
5061 * we should start walking down the tree again if reference
5064 if (!path->locks[level]) {
5066 btrfs_tree_lock(eb);
5067 btrfs_set_lock_blocking_write(eb);
5068 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5070 ret = btrfs_lookup_extent_info(trans, fs_info,
5071 eb->start, level, 1,
5075 btrfs_tree_unlock_rw(eb, path->locks[level]);
5076 path->locks[level] = 0;
5079 BUG_ON(wc->refs[level] == 0);
5080 if (wc->refs[level] == 1) {
5081 btrfs_tree_unlock_rw(eb, path->locks[level]);
5082 path->locks[level] = 0;
5088 /* wc->stage == DROP_REFERENCE */
5089 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5091 if (wc->refs[level] == 1) {
5093 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5094 ret = btrfs_dec_ref(trans, root, eb, 1);
5096 ret = btrfs_dec_ref(trans, root, eb, 0);
5097 BUG_ON(ret); /* -ENOMEM */
5098 if (is_fstree(root->root_key.objectid)) {
5099 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
5101 btrfs_err_rl(fs_info,
5102 "error %d accounting leaf items, quota is out of sync, rescan required",
5107 /* make block locked assertion in btrfs_clean_tree_block happy */
5108 if (!path->locks[level] &&
5109 btrfs_header_generation(eb) == trans->transid) {
5110 btrfs_tree_lock(eb);
5111 btrfs_set_lock_blocking_write(eb);
5112 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5114 btrfs_clean_tree_block(eb);
5117 if (eb == root->node) {
5118 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5120 else if (root->root_key.objectid != btrfs_header_owner(eb))
5121 goto owner_mismatch;
5123 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5124 parent = path->nodes[level + 1]->start;
5125 else if (root->root_key.objectid !=
5126 btrfs_header_owner(path->nodes[level + 1]))
5127 goto owner_mismatch;
5130 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
5132 wc->refs[level] = 0;
5133 wc->flags[level] = 0;
5137 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
5138 btrfs_header_owner(eb), root->root_key.objectid);
5142 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
5143 struct btrfs_root *root,
5144 struct btrfs_path *path,
5145 struct walk_control *wc)
5147 int level = wc->level;
5148 int lookup_info = 1;
5151 while (level >= 0) {
5152 ret = walk_down_proc(trans, root, path, wc, lookup_info);
5159 if (path->slots[level] >=
5160 btrfs_header_nritems(path->nodes[level]))
5163 ret = do_walk_down(trans, root, path, wc, &lookup_info);
5165 path->slots[level]++;
5174 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
5175 struct btrfs_root *root,
5176 struct btrfs_path *path,
5177 struct walk_control *wc, int max_level)
5179 int level = wc->level;
5182 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
5183 while (level < max_level && path->nodes[level]) {
5185 if (path->slots[level] + 1 <
5186 btrfs_header_nritems(path->nodes[level])) {
5187 path->slots[level]++;
5190 ret = walk_up_proc(trans, root, path, wc);
5196 if (path->locks[level]) {
5197 btrfs_tree_unlock_rw(path->nodes[level],
5198 path->locks[level]);
5199 path->locks[level] = 0;
5201 free_extent_buffer(path->nodes[level]);
5202 path->nodes[level] = NULL;
5210 * drop a subvolume tree.
5212 * this function traverses the tree freeing any blocks that only
5213 * referenced by the tree.
5215 * when a shared tree block is found. this function decreases its
5216 * reference count by one. if update_ref is true, this function
5217 * also make sure backrefs for the shared block and all lower level
5218 * blocks are properly updated.
5220 * If called with for_reloc == 0, may exit early with -EAGAIN
5222 int btrfs_drop_snapshot(struct btrfs_root *root,
5223 struct btrfs_block_rsv *block_rsv, int update_ref,
5226 struct btrfs_fs_info *fs_info = root->fs_info;
5227 struct btrfs_path *path;
5228 struct btrfs_trans_handle *trans;
5229 struct btrfs_root *tree_root = fs_info->tree_root;
5230 struct btrfs_root_item *root_item = &root->root_item;
5231 struct walk_control *wc;
5232 struct btrfs_key key;
5236 bool root_dropped = false;
5238 btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
5240 path = btrfs_alloc_path();
5246 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5248 btrfs_free_path(path);
5253 trans = btrfs_start_transaction(tree_root, 0);
5254 if (IS_ERR(trans)) {
5255 err = PTR_ERR(trans);
5259 err = btrfs_run_delayed_items(trans);
5264 trans->block_rsv = block_rsv;
5267 * This will help us catch people modifying the fs tree while we're
5268 * dropping it. It is unsafe to mess with the fs tree while it's being
5269 * dropped as we unlock the root node and parent nodes as we walk down
5270 * the tree, assuming nothing will change. If something does change
5271 * then we'll have stale information and drop references to blocks we've
5274 set_bit(BTRFS_ROOT_DELETING, &root->state);
5275 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
5276 level = btrfs_header_level(root->node);
5277 path->nodes[level] = btrfs_lock_root_node(root);
5278 btrfs_set_lock_blocking_write(path->nodes[level]);
5279 path->slots[level] = 0;
5280 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5281 memset(&wc->update_progress, 0,
5282 sizeof(wc->update_progress));
5284 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
5285 memcpy(&wc->update_progress, &key,
5286 sizeof(wc->update_progress));
5288 level = root_item->drop_level;
5290 path->lowest_level = level;
5291 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5292 path->lowest_level = 0;
5300 * unlock our path, this is safe because only this
5301 * function is allowed to delete this snapshot
5303 btrfs_unlock_up_safe(path, 0);
5305 level = btrfs_header_level(root->node);
5307 btrfs_tree_lock(path->nodes[level]);
5308 btrfs_set_lock_blocking_write(path->nodes[level]);
5309 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5311 ret = btrfs_lookup_extent_info(trans, fs_info,
5312 path->nodes[level]->start,
5313 level, 1, &wc->refs[level],
5319 BUG_ON(wc->refs[level] == 0);
5321 if (level == root_item->drop_level)
5324 btrfs_tree_unlock(path->nodes[level]);
5325 path->locks[level] = 0;
5326 WARN_ON(wc->refs[level] != 1);
5331 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
5333 wc->shared_level = -1;
5334 wc->stage = DROP_REFERENCE;
5335 wc->update_ref = update_ref;
5337 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5341 ret = walk_down_tree(trans, root, path, wc);
5347 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
5354 BUG_ON(wc->stage != DROP_REFERENCE);
5358 if (wc->stage == DROP_REFERENCE) {
5359 wc->drop_level = wc->level;
5360 btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
5362 path->slots[wc->drop_level]);
5364 btrfs_cpu_key_to_disk(&root_item->drop_progress,
5365 &wc->drop_progress);
5366 root_item->drop_level = wc->drop_level;
5368 BUG_ON(wc->level == 0);
5369 if (btrfs_should_end_transaction(trans) ||
5370 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
5371 ret = btrfs_update_root(trans, tree_root,
5375 btrfs_abort_transaction(trans, ret);
5380 btrfs_end_transaction_throttle(trans);
5381 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
5382 btrfs_debug(fs_info,
5383 "drop snapshot early exit");
5388 trans = btrfs_start_transaction(tree_root, 0);
5389 if (IS_ERR(trans)) {
5390 err = PTR_ERR(trans);
5394 trans->block_rsv = block_rsv;
5397 btrfs_release_path(path);
5401 ret = btrfs_del_root(trans, &root->root_key);
5403 btrfs_abort_transaction(trans, ret);
5408 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
5409 ret = btrfs_find_root(tree_root, &root->root_key, path,
5412 btrfs_abort_transaction(trans, ret);
5415 } else if (ret > 0) {
5416 /* if we fail to delete the orphan item this time
5417 * around, it'll get picked up the next time.
5419 * The most common failure here is just -ENOENT.
5421 btrfs_del_orphan_item(trans, tree_root,
5422 root->root_key.objectid);
5426 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
5427 btrfs_add_dropped_root(trans, root);
5429 free_extent_buffer(root->node);
5430 free_extent_buffer(root->commit_root);
5431 btrfs_put_root(root);
5433 root_dropped = true;
5435 btrfs_end_transaction_throttle(trans);
5438 btrfs_free_path(path);
5441 * So if we need to stop dropping the snapshot for whatever reason we
5442 * need to make sure to add it back to the dead root list so that we
5443 * keep trying to do the work later. This also cleans up roots if we
5444 * don't have it in the radix (like when we recover after a power fail
5445 * or unmount) so we don't leak memory.
5447 if (!for_reloc && !root_dropped)
5448 btrfs_add_dead_root(root);
5449 if (err && err != -EAGAIN)
5450 btrfs_handle_fs_error(fs_info, err, NULL);
5455 * drop subtree rooted at tree block 'node'.
5457 * NOTE: this function will unlock and release tree block 'node'
5458 * only used by relocation code
5460 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
5461 struct btrfs_root *root,
5462 struct extent_buffer *node,
5463 struct extent_buffer *parent)
5465 struct btrfs_fs_info *fs_info = root->fs_info;
5466 struct btrfs_path *path;
5467 struct walk_control *wc;
5473 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
5475 path = btrfs_alloc_path();
5479 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5481 btrfs_free_path(path);
5485 btrfs_assert_tree_locked(parent);
5486 parent_level = btrfs_header_level(parent);
5487 atomic_inc(&parent->refs);
5488 path->nodes[parent_level] = parent;
5489 path->slots[parent_level] = btrfs_header_nritems(parent);
5491 btrfs_assert_tree_locked(node);
5492 level = btrfs_header_level(node);
5493 path->nodes[level] = node;
5494 path->slots[level] = 0;
5495 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5497 wc->refs[parent_level] = 1;
5498 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5500 wc->shared_level = -1;
5501 wc->stage = DROP_REFERENCE;
5504 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5507 wret = walk_down_tree(trans, root, path, wc);
5513 wret = walk_up_tree(trans, root, path, wc, parent_level);
5521 btrfs_free_path(path);
5526 * helper to account the unused space of all the readonly block group in the
5527 * space_info. takes mirrors into account.
5529 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
5531 struct btrfs_block_group *block_group;
5535 /* It's df, we don't care if it's racy */
5536 if (list_empty(&sinfo->ro_bgs))
5539 spin_lock(&sinfo->lock);
5540 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
5541 spin_lock(&block_group->lock);
5543 if (!block_group->ro) {
5544 spin_unlock(&block_group->lock);
5548 factor = btrfs_bg_type_to_factor(block_group->flags);
5549 free_bytes += (block_group->length -
5550 block_group->used) * factor;
5552 spin_unlock(&block_group->lock);
5554 spin_unlock(&sinfo->lock);
5559 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
5562 return unpin_extent_range(fs_info, start, end, false);
5566 * It used to be that old block groups would be left around forever.
5567 * Iterating over them would be enough to trim unused space. Since we
5568 * now automatically remove them, we also need to iterate over unallocated
5571 * We don't want a transaction for this since the discard may take a
5572 * substantial amount of time. We don't require that a transaction be
5573 * running, but we do need to take a running transaction into account
5574 * to ensure that we're not discarding chunks that were released or
5575 * allocated in the current transaction.
5577 * Holding the chunks lock will prevent other threads from allocating
5578 * or releasing chunks, but it won't prevent a running transaction
5579 * from committing and releasing the memory that the pending chunks
5580 * list head uses. For that, we need to take a reference to the
5581 * transaction and hold the commit root sem. We only need to hold
5582 * it while performing the free space search since we have already
5583 * held back allocations.
5585 static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
5587 u64 start = SZ_1M, len = 0, end = 0;
5592 /* Discard not supported = nothing to do. */
5593 if (!blk_queue_discard(bdev_get_queue(device->bdev)))
5596 /* Not writable = nothing to do. */
5597 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
5600 /* No free space = nothing to do. */
5601 if (device->total_bytes <= device->bytes_used)
5607 struct btrfs_fs_info *fs_info = device->fs_info;
5610 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
5614 find_first_clear_extent_bit(&device->alloc_state, start,
5616 CHUNK_TRIMMED | CHUNK_ALLOCATED);
5618 /* Ensure we skip the reserved area in the first 1M */
5619 start = max_t(u64, start, SZ_1M);
5622 * If find_first_clear_extent_bit find a range that spans the
5623 * end of the device it will set end to -1, in this case it's up
5624 * to the caller to trim the value to the size of the device.
5626 end = min(end, device->total_bytes - 1);
5628 len = end - start + 1;
5630 /* We didn't find any extents */
5632 mutex_unlock(&fs_info->chunk_mutex);
5637 ret = btrfs_issue_discard(device->bdev, start, len,
5640 set_extent_bits(&device->alloc_state, start,
5643 mutex_unlock(&fs_info->chunk_mutex);
5651 if (fatal_signal_pending(current)) {
5663 * Trim the whole filesystem by:
5664 * 1) trimming the free space in each block group
5665 * 2) trimming the unallocated space on each device
5667 * This will also continue trimming even if a block group or device encounters
5668 * an error. The return value will be the last error, or 0 if nothing bad
5671 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
5673 struct btrfs_block_group *cache = NULL;
5674 struct btrfs_device *device;
5675 struct list_head *devices;
5677 u64 range_end = U64_MAX;
5688 * Check range overflow if range->len is set.
5689 * The default range->len is U64_MAX.
5691 if (range->len != U64_MAX &&
5692 check_add_overflow(range->start, range->len, &range_end))
5695 cache = btrfs_lookup_first_block_group(fs_info, range->start);
5696 for (; cache; cache = btrfs_next_block_group(cache)) {
5697 if (cache->start >= range_end) {
5698 btrfs_put_block_group(cache);
5702 start = max(range->start, cache->start);
5703 end = min(range_end, cache->start + cache->length);
5705 if (end - start >= range->minlen) {
5706 if (!btrfs_block_group_done(cache)) {
5707 ret = btrfs_cache_block_group(cache, 0);
5713 ret = btrfs_wait_block_group_cache_done(cache);
5720 ret = btrfs_trim_block_group(cache,
5726 trimmed += group_trimmed;
5737 "failed to trim %llu block group(s), last error %d",
5739 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5740 devices = &fs_info->fs_devices->devices;
5741 list_for_each_entry(device, devices, dev_list) {
5742 ret = btrfs_trim_free_extents(device, &group_trimmed);
5749 trimmed += group_trimmed;
5751 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5755 "failed to trim %llu device(s), last error %d",
5756 dev_failed, dev_ret);
5757 range->len = trimmed;