1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/sched/signal.h>
8 #include <linux/pagemap.h>
9 #include <linux/writeback.h>
10 #include <linux/blkdev.h>
11 #include <linux/sort.h>
12 #include <linux/rcupdate.h>
13 #include <linux/kthread.h>
14 #include <linux/slab.h>
15 #include <linux/ratelimit.h>
16 #include <linux/percpu_counter.h>
17 #include <linux/lockdep.h>
18 #include <linux/crc32c.h>
22 #include "print-tree.h"
26 #include "free-space-cache.h"
27 #include "free-space-tree.h"
30 #include "ref-verify.h"
31 #include "space-info.h"
32 #include "block-rsv.h"
33 #include "delalloc-space.h"
34 #include "block-group.h"
36 #undef SCRAMBLE_DELAYED_REFS
39 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
40 struct btrfs_delayed_ref_node *node, u64 parent,
41 u64 root_objectid, u64 owner_objectid,
42 u64 owner_offset, int refs_to_drop,
43 struct btrfs_delayed_extent_op *extra_op);
44 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
45 struct extent_buffer *leaf,
46 struct btrfs_extent_item *ei);
47 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
48 u64 parent, u64 root_objectid,
49 u64 flags, u64 owner, u64 offset,
50 struct btrfs_key *ins, int ref_mod);
51 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
52 struct btrfs_delayed_ref_node *node,
53 struct btrfs_delayed_extent_op *extent_op);
54 static int find_next_key(struct btrfs_path *path, int level,
55 struct btrfs_key *key);
57 static int block_group_bits(struct btrfs_block_group *cache, u64 bits)
59 return (cache->flags & bits) == bits;
62 int btrfs_add_excluded_extent(struct btrfs_fs_info *fs_info,
63 u64 start, u64 num_bytes)
65 u64 end = start + num_bytes - 1;
66 set_extent_bits(&fs_info->freed_extents[0],
67 start, end, EXTENT_UPTODATE);
68 set_extent_bits(&fs_info->freed_extents[1],
69 start, end, EXTENT_UPTODATE);
73 void btrfs_free_excluded_extents(struct btrfs_block_group *cache)
75 struct btrfs_fs_info *fs_info = cache->fs_info;
79 end = start + cache->length - 1;
81 clear_extent_bits(&fs_info->freed_extents[0],
82 start, end, EXTENT_UPTODATE);
83 clear_extent_bits(&fs_info->freed_extents[1],
84 start, end, EXTENT_UPTODATE);
87 static u64 generic_ref_to_space_flags(struct btrfs_ref *ref)
89 if (ref->type == BTRFS_REF_METADATA) {
90 if (ref->tree_ref.root == BTRFS_CHUNK_TREE_OBJECTID)
91 return BTRFS_BLOCK_GROUP_SYSTEM;
93 return BTRFS_BLOCK_GROUP_METADATA;
95 return BTRFS_BLOCK_GROUP_DATA;
98 static void add_pinned_bytes(struct btrfs_fs_info *fs_info,
99 struct btrfs_ref *ref)
101 struct btrfs_space_info *space_info;
102 u64 flags = generic_ref_to_space_flags(ref);
104 space_info = btrfs_find_space_info(fs_info, flags);
106 percpu_counter_add_batch(&space_info->total_bytes_pinned, ref->len,
107 BTRFS_TOTAL_BYTES_PINNED_BATCH);
110 static void sub_pinned_bytes(struct btrfs_fs_info *fs_info,
111 struct btrfs_ref *ref)
113 struct btrfs_space_info *space_info;
114 u64 flags = generic_ref_to_space_flags(ref);
116 space_info = btrfs_find_space_info(fs_info, flags);
118 percpu_counter_add_batch(&space_info->total_bytes_pinned, -ref->len,
119 BTRFS_TOTAL_BYTES_PINNED_BATCH);
122 /* simple helper to search for an existing data extent at a given offset */
123 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
126 struct btrfs_key key;
127 struct btrfs_path *path;
129 path = btrfs_alloc_path();
133 key.objectid = start;
135 key.type = BTRFS_EXTENT_ITEM_KEY;
136 ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
137 btrfs_free_path(path);
142 * helper function to lookup reference count and flags of a tree block.
144 * the head node for delayed ref is used to store the sum of all the
145 * reference count modifications queued up in the rbtree. the head
146 * node may also store the extent flags to set. This way you can check
147 * to see what the reference count and extent flags would be if all of
148 * the delayed refs are not processed.
150 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
151 struct btrfs_fs_info *fs_info, u64 bytenr,
152 u64 offset, int metadata, u64 *refs, u64 *flags)
154 struct btrfs_delayed_ref_head *head;
155 struct btrfs_delayed_ref_root *delayed_refs;
156 struct btrfs_path *path;
157 struct btrfs_extent_item *ei;
158 struct extent_buffer *leaf;
159 struct btrfs_key key;
166 * If we don't have skinny metadata, don't bother doing anything
169 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
170 offset = fs_info->nodesize;
174 path = btrfs_alloc_path();
179 path->skip_locking = 1;
180 path->search_commit_root = 1;
184 key.objectid = bytenr;
187 key.type = BTRFS_METADATA_ITEM_KEY;
189 key.type = BTRFS_EXTENT_ITEM_KEY;
191 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
195 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
196 if (path->slots[0]) {
198 btrfs_item_key_to_cpu(path->nodes[0], &key,
200 if (key.objectid == bytenr &&
201 key.type == BTRFS_EXTENT_ITEM_KEY &&
202 key.offset == fs_info->nodesize)
208 leaf = path->nodes[0];
209 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
210 if (item_size >= sizeof(*ei)) {
211 ei = btrfs_item_ptr(leaf, path->slots[0],
212 struct btrfs_extent_item);
213 num_refs = btrfs_extent_refs(leaf, ei);
214 extent_flags = btrfs_extent_flags(leaf, ei);
217 btrfs_print_v0_err(fs_info);
219 btrfs_abort_transaction(trans, ret);
221 btrfs_handle_fs_error(fs_info, ret, NULL);
226 BUG_ON(num_refs == 0);
236 delayed_refs = &trans->transaction->delayed_refs;
237 spin_lock(&delayed_refs->lock);
238 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
240 if (!mutex_trylock(&head->mutex)) {
241 refcount_inc(&head->refs);
242 spin_unlock(&delayed_refs->lock);
244 btrfs_release_path(path);
247 * Mutex was contended, block until it's released and try
250 mutex_lock(&head->mutex);
251 mutex_unlock(&head->mutex);
252 btrfs_put_delayed_ref_head(head);
255 spin_lock(&head->lock);
256 if (head->extent_op && head->extent_op->update_flags)
257 extent_flags |= head->extent_op->flags_to_set;
259 BUG_ON(num_refs == 0);
261 num_refs += head->ref_mod;
262 spin_unlock(&head->lock);
263 mutex_unlock(&head->mutex);
265 spin_unlock(&delayed_refs->lock);
267 WARN_ON(num_refs == 0);
271 *flags = extent_flags;
273 btrfs_free_path(path);
278 * Back reference rules. Back refs have three main goals:
280 * 1) differentiate between all holders of references to an extent so that
281 * when a reference is dropped we can make sure it was a valid reference
282 * before freeing the extent.
284 * 2) Provide enough information to quickly find the holders of an extent
285 * if we notice a given block is corrupted or bad.
287 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
288 * maintenance. This is actually the same as #2, but with a slightly
289 * different use case.
291 * There are two kinds of back refs. The implicit back refs is optimized
292 * for pointers in non-shared tree blocks. For a given pointer in a block,
293 * back refs of this kind provide information about the block's owner tree
294 * and the pointer's key. These information allow us to find the block by
295 * b-tree searching. The full back refs is for pointers in tree blocks not
296 * referenced by their owner trees. The location of tree block is recorded
297 * in the back refs. Actually the full back refs is generic, and can be
298 * used in all cases the implicit back refs is used. The major shortcoming
299 * of the full back refs is its overhead. Every time a tree block gets
300 * COWed, we have to update back refs entry for all pointers in it.
302 * For a newly allocated tree block, we use implicit back refs for
303 * pointers in it. This means most tree related operations only involve
304 * implicit back refs. For a tree block created in old transaction, the
305 * only way to drop a reference to it is COW it. So we can detect the
306 * event that tree block loses its owner tree's reference and do the
307 * back refs conversion.
309 * When a tree block is COWed through a tree, there are four cases:
311 * The reference count of the block is one and the tree is the block's
312 * owner tree. Nothing to do in this case.
314 * The reference count of the block is one and the tree is not the
315 * block's owner tree. In this case, full back refs is used for pointers
316 * in the block. Remove these full back refs, add implicit back refs for
317 * every pointers in the new block.
319 * The reference count of the block is greater than one and the tree is
320 * the block's owner tree. In this case, implicit back refs is used for
321 * pointers in the block. Add full back refs for every pointers in the
322 * block, increase lower level extents' reference counts. The original
323 * implicit back refs are entailed to the new block.
325 * The reference count of the block is greater than one and the tree is
326 * not the block's owner tree. Add implicit back refs for every pointer in
327 * the new block, increase lower level extents' reference count.
329 * Back Reference Key composing:
331 * The key objectid corresponds to the first byte in the extent,
332 * The key type is used to differentiate between types of back refs.
333 * There are different meanings of the key offset for different types
336 * File extents can be referenced by:
338 * - multiple snapshots, subvolumes, or different generations in one subvol
339 * - different files inside a single subvolume
340 * - different offsets inside a file (bookend extents in file.c)
342 * The extent ref structure for the implicit back refs has fields for:
344 * - Objectid of the subvolume root
345 * - objectid of the file holding the reference
346 * - original offset in the file
347 * - how many bookend extents
349 * The key offset for the implicit back refs is hash of the first
352 * The extent ref structure for the full back refs has field for:
354 * - number of pointers in the tree leaf
356 * The key offset for the implicit back refs is the first byte of
359 * When a file extent is allocated, The implicit back refs is used.
360 * the fields are filled in:
362 * (root_key.objectid, inode objectid, offset in file, 1)
364 * When a file extent is removed file truncation, we find the
365 * corresponding implicit back refs and check the following fields:
367 * (btrfs_header_owner(leaf), inode objectid, offset in file)
369 * Btree extents can be referenced by:
371 * - Different subvolumes
373 * Both the implicit back refs and the full back refs for tree blocks
374 * only consist of key. The key offset for the implicit back refs is
375 * objectid of block's owner tree. The key offset for the full back refs
376 * is the first byte of parent block.
378 * When implicit back refs is used, information about the lowest key and
379 * level of the tree block are required. These information are stored in
380 * tree block info structure.
384 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
385 * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
386 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
388 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
389 struct btrfs_extent_inline_ref *iref,
390 enum btrfs_inline_ref_type is_data)
392 int type = btrfs_extent_inline_ref_type(eb, iref);
393 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
395 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
396 type == BTRFS_SHARED_BLOCK_REF_KEY ||
397 type == BTRFS_SHARED_DATA_REF_KEY ||
398 type == BTRFS_EXTENT_DATA_REF_KEY) {
399 if (is_data == BTRFS_REF_TYPE_BLOCK) {
400 if (type == BTRFS_TREE_BLOCK_REF_KEY)
402 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
405 * Every shared one has parent tree
406 * block, which must be aligned to
410 IS_ALIGNED(offset, eb->fs_info->nodesize))
413 } else if (is_data == BTRFS_REF_TYPE_DATA) {
414 if (type == BTRFS_EXTENT_DATA_REF_KEY)
416 if (type == BTRFS_SHARED_DATA_REF_KEY) {
419 * Every shared one has parent tree
420 * block, which must be aligned to
424 IS_ALIGNED(offset, eb->fs_info->nodesize))
428 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
433 btrfs_print_leaf((struct extent_buffer *)eb);
434 btrfs_err(eb->fs_info, "eb %llu invalid extent inline ref type %d",
438 return BTRFS_REF_TYPE_INVALID;
441 u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
443 u32 high_crc = ~(u32)0;
444 u32 low_crc = ~(u32)0;
447 lenum = cpu_to_le64(root_objectid);
448 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
449 lenum = cpu_to_le64(owner);
450 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
451 lenum = cpu_to_le64(offset);
452 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
454 return ((u64)high_crc << 31) ^ (u64)low_crc;
457 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
458 struct btrfs_extent_data_ref *ref)
460 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
461 btrfs_extent_data_ref_objectid(leaf, ref),
462 btrfs_extent_data_ref_offset(leaf, ref));
465 static int match_extent_data_ref(struct extent_buffer *leaf,
466 struct btrfs_extent_data_ref *ref,
467 u64 root_objectid, u64 owner, u64 offset)
469 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
470 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
471 btrfs_extent_data_ref_offset(leaf, ref) != offset)
476 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
477 struct btrfs_path *path,
478 u64 bytenr, u64 parent,
480 u64 owner, u64 offset)
482 struct btrfs_root *root = trans->fs_info->extent_root;
483 struct btrfs_key key;
484 struct btrfs_extent_data_ref *ref;
485 struct extent_buffer *leaf;
491 key.objectid = bytenr;
493 key.type = BTRFS_SHARED_DATA_REF_KEY;
496 key.type = BTRFS_EXTENT_DATA_REF_KEY;
497 key.offset = hash_extent_data_ref(root_objectid,
502 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
514 leaf = path->nodes[0];
515 nritems = btrfs_header_nritems(leaf);
517 if (path->slots[0] >= nritems) {
518 ret = btrfs_next_leaf(root, path);
524 leaf = path->nodes[0];
525 nritems = btrfs_header_nritems(leaf);
529 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
530 if (key.objectid != bytenr ||
531 key.type != BTRFS_EXTENT_DATA_REF_KEY)
534 ref = btrfs_item_ptr(leaf, path->slots[0],
535 struct btrfs_extent_data_ref);
537 if (match_extent_data_ref(leaf, ref, root_objectid,
540 btrfs_release_path(path);
552 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
553 struct btrfs_path *path,
554 u64 bytenr, u64 parent,
555 u64 root_objectid, u64 owner,
556 u64 offset, int refs_to_add)
558 struct btrfs_root *root = trans->fs_info->extent_root;
559 struct btrfs_key key;
560 struct extent_buffer *leaf;
565 key.objectid = bytenr;
567 key.type = BTRFS_SHARED_DATA_REF_KEY;
569 size = sizeof(struct btrfs_shared_data_ref);
571 key.type = BTRFS_EXTENT_DATA_REF_KEY;
572 key.offset = hash_extent_data_ref(root_objectid,
574 size = sizeof(struct btrfs_extent_data_ref);
577 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
578 if (ret && ret != -EEXIST)
581 leaf = path->nodes[0];
583 struct btrfs_shared_data_ref *ref;
584 ref = btrfs_item_ptr(leaf, path->slots[0],
585 struct btrfs_shared_data_ref);
587 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
589 num_refs = btrfs_shared_data_ref_count(leaf, ref);
590 num_refs += refs_to_add;
591 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
594 struct btrfs_extent_data_ref *ref;
595 while (ret == -EEXIST) {
596 ref = btrfs_item_ptr(leaf, path->slots[0],
597 struct btrfs_extent_data_ref);
598 if (match_extent_data_ref(leaf, ref, root_objectid,
601 btrfs_release_path(path);
603 ret = btrfs_insert_empty_item(trans, root, path, &key,
605 if (ret && ret != -EEXIST)
608 leaf = path->nodes[0];
610 ref = btrfs_item_ptr(leaf, path->slots[0],
611 struct btrfs_extent_data_ref);
613 btrfs_set_extent_data_ref_root(leaf, ref,
615 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
616 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
617 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
619 num_refs = btrfs_extent_data_ref_count(leaf, ref);
620 num_refs += refs_to_add;
621 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
624 btrfs_mark_buffer_dirty(leaf);
627 btrfs_release_path(path);
631 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
632 struct btrfs_path *path,
633 int refs_to_drop, int *last_ref)
635 struct btrfs_key key;
636 struct btrfs_extent_data_ref *ref1 = NULL;
637 struct btrfs_shared_data_ref *ref2 = NULL;
638 struct extent_buffer *leaf;
642 leaf = path->nodes[0];
643 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
645 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
646 ref1 = btrfs_item_ptr(leaf, path->slots[0],
647 struct btrfs_extent_data_ref);
648 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
649 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
650 ref2 = btrfs_item_ptr(leaf, path->slots[0],
651 struct btrfs_shared_data_ref);
652 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
653 } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
654 btrfs_print_v0_err(trans->fs_info);
655 btrfs_abort_transaction(trans, -EINVAL);
661 BUG_ON(num_refs < refs_to_drop);
662 num_refs -= refs_to_drop;
665 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
668 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
669 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
670 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
671 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
672 btrfs_mark_buffer_dirty(leaf);
677 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
678 struct btrfs_extent_inline_ref *iref)
680 struct btrfs_key key;
681 struct extent_buffer *leaf;
682 struct btrfs_extent_data_ref *ref1;
683 struct btrfs_shared_data_ref *ref2;
687 leaf = path->nodes[0];
688 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
690 BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
693 * If type is invalid, we should have bailed out earlier than
696 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
697 ASSERT(type != BTRFS_REF_TYPE_INVALID);
698 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
699 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
700 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
702 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
703 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
705 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
706 ref1 = btrfs_item_ptr(leaf, path->slots[0],
707 struct btrfs_extent_data_ref);
708 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
709 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
710 ref2 = btrfs_item_ptr(leaf, path->slots[0],
711 struct btrfs_shared_data_ref);
712 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
719 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
720 struct btrfs_path *path,
721 u64 bytenr, u64 parent,
724 struct btrfs_root *root = trans->fs_info->extent_root;
725 struct btrfs_key key;
728 key.objectid = bytenr;
730 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
733 key.type = BTRFS_TREE_BLOCK_REF_KEY;
734 key.offset = root_objectid;
737 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
743 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
744 struct btrfs_path *path,
745 u64 bytenr, u64 parent,
748 struct btrfs_key key;
751 key.objectid = bytenr;
753 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
756 key.type = BTRFS_TREE_BLOCK_REF_KEY;
757 key.offset = root_objectid;
760 ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
762 btrfs_release_path(path);
766 static inline int extent_ref_type(u64 parent, u64 owner)
769 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
771 type = BTRFS_SHARED_BLOCK_REF_KEY;
773 type = BTRFS_TREE_BLOCK_REF_KEY;
776 type = BTRFS_SHARED_DATA_REF_KEY;
778 type = BTRFS_EXTENT_DATA_REF_KEY;
783 static int find_next_key(struct btrfs_path *path, int level,
784 struct btrfs_key *key)
787 for (; level < BTRFS_MAX_LEVEL; level++) {
788 if (!path->nodes[level])
790 if (path->slots[level] + 1 >=
791 btrfs_header_nritems(path->nodes[level]))
794 btrfs_item_key_to_cpu(path->nodes[level], key,
795 path->slots[level] + 1);
797 btrfs_node_key_to_cpu(path->nodes[level], key,
798 path->slots[level] + 1);
805 * look for inline back ref. if back ref is found, *ref_ret is set
806 * to the address of inline back ref, and 0 is returned.
808 * if back ref isn't found, *ref_ret is set to the address where it
809 * should be inserted, and -ENOENT is returned.
811 * if insert is true and there are too many inline back refs, the path
812 * points to the extent item, and -EAGAIN is returned.
814 * NOTE: inline back refs are ordered in the same way that back ref
815 * items in the tree are ordered.
817 static noinline_for_stack
818 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
819 struct btrfs_path *path,
820 struct btrfs_extent_inline_ref **ref_ret,
821 u64 bytenr, u64 num_bytes,
822 u64 parent, u64 root_objectid,
823 u64 owner, u64 offset, int insert)
825 struct btrfs_fs_info *fs_info = trans->fs_info;
826 struct btrfs_root *root = fs_info->extent_root;
827 struct btrfs_key key;
828 struct extent_buffer *leaf;
829 struct btrfs_extent_item *ei;
830 struct btrfs_extent_inline_ref *iref;
840 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
843 key.objectid = bytenr;
844 key.type = BTRFS_EXTENT_ITEM_KEY;
845 key.offset = num_bytes;
847 want = extent_ref_type(parent, owner);
849 extra_size = btrfs_extent_inline_ref_size(want);
850 path->keep_locks = 1;
855 * Owner is our level, so we can just add one to get the level for the
856 * block we are interested in.
858 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
859 key.type = BTRFS_METADATA_ITEM_KEY;
864 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
871 * We may be a newly converted file system which still has the old fat
872 * extent entries for metadata, so try and see if we have one of those.
874 if (ret > 0 && skinny_metadata) {
875 skinny_metadata = false;
876 if (path->slots[0]) {
878 btrfs_item_key_to_cpu(path->nodes[0], &key,
880 if (key.objectid == bytenr &&
881 key.type == BTRFS_EXTENT_ITEM_KEY &&
882 key.offset == num_bytes)
886 key.objectid = bytenr;
887 key.type = BTRFS_EXTENT_ITEM_KEY;
888 key.offset = num_bytes;
889 btrfs_release_path(path);
894 if (ret && !insert) {
897 } else if (WARN_ON(ret)) {
902 leaf = path->nodes[0];
903 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
904 if (unlikely(item_size < sizeof(*ei))) {
906 btrfs_print_v0_err(fs_info);
907 btrfs_abort_transaction(trans, err);
911 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
912 flags = btrfs_extent_flags(leaf, ei);
914 ptr = (unsigned long)(ei + 1);
915 end = (unsigned long)ei + item_size;
917 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
918 ptr += sizeof(struct btrfs_tree_block_info);
922 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
923 needed = BTRFS_REF_TYPE_DATA;
925 needed = BTRFS_REF_TYPE_BLOCK;
933 iref = (struct btrfs_extent_inline_ref *)ptr;
934 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
935 if (type == BTRFS_REF_TYPE_INVALID) {
943 ptr += btrfs_extent_inline_ref_size(type);
947 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
948 struct btrfs_extent_data_ref *dref;
949 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
950 if (match_extent_data_ref(leaf, dref, root_objectid,
955 if (hash_extent_data_ref_item(leaf, dref) <
956 hash_extent_data_ref(root_objectid, owner, offset))
960 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
962 if (parent == ref_offset) {
966 if (ref_offset < parent)
969 if (root_objectid == ref_offset) {
973 if (ref_offset < root_objectid)
977 ptr += btrfs_extent_inline_ref_size(type);
979 if (err == -ENOENT && insert) {
980 if (item_size + extra_size >=
981 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
986 * To add new inline back ref, we have to make sure
987 * there is no corresponding back ref item.
988 * For simplicity, we just do not add new inline back
989 * ref if there is any kind of item for this block
991 if (find_next_key(path, 0, &key) == 0 &&
992 key.objectid == bytenr &&
993 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
998 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1001 path->keep_locks = 0;
1002 btrfs_unlock_up_safe(path, 1);
1008 * helper to add new inline back ref
1010 static noinline_for_stack
1011 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1012 struct btrfs_path *path,
1013 struct btrfs_extent_inline_ref *iref,
1014 u64 parent, u64 root_objectid,
1015 u64 owner, u64 offset, int refs_to_add,
1016 struct btrfs_delayed_extent_op *extent_op)
1018 struct extent_buffer *leaf;
1019 struct btrfs_extent_item *ei;
1022 unsigned long item_offset;
1027 leaf = path->nodes[0];
1028 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1029 item_offset = (unsigned long)iref - (unsigned long)ei;
1031 type = extent_ref_type(parent, owner);
1032 size = btrfs_extent_inline_ref_size(type);
1034 btrfs_extend_item(path, size);
1036 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1037 refs = btrfs_extent_refs(leaf, ei);
1038 refs += refs_to_add;
1039 btrfs_set_extent_refs(leaf, ei, refs);
1041 __run_delayed_extent_op(extent_op, leaf, ei);
1043 ptr = (unsigned long)ei + item_offset;
1044 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1045 if (ptr < end - size)
1046 memmove_extent_buffer(leaf, ptr + size, ptr,
1049 iref = (struct btrfs_extent_inline_ref *)ptr;
1050 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1051 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1052 struct btrfs_extent_data_ref *dref;
1053 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1054 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1055 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1056 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1057 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1058 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1059 struct btrfs_shared_data_ref *sref;
1060 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1061 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1062 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1063 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1064 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1066 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1068 btrfs_mark_buffer_dirty(leaf);
1071 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1072 struct btrfs_path *path,
1073 struct btrfs_extent_inline_ref **ref_ret,
1074 u64 bytenr, u64 num_bytes, u64 parent,
1075 u64 root_objectid, u64 owner, u64 offset)
1079 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1080 num_bytes, parent, root_objectid,
1085 btrfs_release_path(path);
1088 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1089 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1092 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1093 root_objectid, owner, offset);
1099 * helper to update/remove inline back ref
1101 static noinline_for_stack
1102 void update_inline_extent_backref(struct btrfs_path *path,
1103 struct btrfs_extent_inline_ref *iref,
1105 struct btrfs_delayed_extent_op *extent_op,
1108 struct extent_buffer *leaf = path->nodes[0];
1109 struct btrfs_extent_item *ei;
1110 struct btrfs_extent_data_ref *dref = NULL;
1111 struct btrfs_shared_data_ref *sref = NULL;
1119 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1120 refs = btrfs_extent_refs(leaf, ei);
1121 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1122 refs += refs_to_mod;
1123 btrfs_set_extent_refs(leaf, ei, refs);
1125 __run_delayed_extent_op(extent_op, leaf, ei);
1128 * If type is invalid, we should have bailed out after
1129 * lookup_inline_extent_backref().
1131 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1132 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1134 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1135 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1136 refs = btrfs_extent_data_ref_count(leaf, dref);
1137 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1138 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1139 refs = btrfs_shared_data_ref_count(leaf, sref);
1142 BUG_ON(refs_to_mod != -1);
1145 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1146 refs += refs_to_mod;
1149 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1150 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1152 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1155 size = btrfs_extent_inline_ref_size(type);
1156 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1157 ptr = (unsigned long)iref;
1158 end = (unsigned long)ei + item_size;
1159 if (ptr + size < end)
1160 memmove_extent_buffer(leaf, ptr, ptr + size,
1163 btrfs_truncate_item(path, item_size, 1);
1165 btrfs_mark_buffer_dirty(leaf);
1168 static noinline_for_stack
1169 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1170 struct btrfs_path *path,
1171 u64 bytenr, u64 num_bytes, u64 parent,
1172 u64 root_objectid, u64 owner,
1173 u64 offset, int refs_to_add,
1174 struct btrfs_delayed_extent_op *extent_op)
1176 struct btrfs_extent_inline_ref *iref;
1179 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1180 num_bytes, parent, root_objectid,
1183 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1184 update_inline_extent_backref(path, iref, refs_to_add,
1186 } else if (ret == -ENOENT) {
1187 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1188 root_objectid, owner, offset,
1189 refs_to_add, extent_op);
1195 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1196 struct btrfs_path *path,
1197 u64 bytenr, u64 parent, u64 root_objectid,
1198 u64 owner, u64 offset, int refs_to_add)
1201 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1202 BUG_ON(refs_to_add != 1);
1203 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1206 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1207 root_objectid, owner, offset,
1213 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1214 struct btrfs_path *path,
1215 struct btrfs_extent_inline_ref *iref,
1216 int refs_to_drop, int is_data, int *last_ref)
1220 BUG_ON(!is_data && refs_to_drop != 1);
1222 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1224 } else if (is_data) {
1225 ret = remove_extent_data_ref(trans, path, refs_to_drop,
1229 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1234 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1235 u64 *discarded_bytes)
1238 u64 bytes_left, end;
1239 u64 aligned_start = ALIGN(start, 1 << 9);
1241 if (WARN_ON(start != aligned_start)) {
1242 len -= aligned_start - start;
1243 len = round_down(len, 1 << 9);
1244 start = aligned_start;
1247 *discarded_bytes = 0;
1255 /* Skip any superblocks on this device. */
1256 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1257 u64 sb_start = btrfs_sb_offset(j);
1258 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1259 u64 size = sb_start - start;
1261 if (!in_range(sb_start, start, bytes_left) &&
1262 !in_range(sb_end, start, bytes_left) &&
1263 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1267 * Superblock spans beginning of range. Adjust start and
1270 if (sb_start <= start) {
1271 start += sb_end - start;
1276 bytes_left = end - start;
1281 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1284 *discarded_bytes += size;
1285 else if (ret != -EOPNOTSUPP)
1294 bytes_left = end - start;
1298 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1301 *discarded_bytes += bytes_left;
1306 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1307 u64 num_bytes, u64 *actual_bytes)
1310 u64 discarded_bytes = 0;
1311 u64 end = bytenr + num_bytes;
1313 struct btrfs_bio *bbio = NULL;
1317 * Avoid races with device replace and make sure our bbio has devices
1318 * associated to its stripes that don't go away while we are discarding.
1320 btrfs_bio_counter_inc_blocked(fs_info);
1322 struct btrfs_bio_stripe *stripe;
1325 num_bytes = end - cur;
1326 /* Tell the block device(s) that the sectors can be discarded */
1327 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, cur,
1328 &num_bytes, &bbio, 0);
1330 * Error can be -ENOMEM, -ENOENT (no such chunk mapping) or
1331 * -EOPNOTSUPP. For any such error, @num_bytes is not updated,
1332 * thus we can't continue anyway.
1337 stripe = bbio->stripes;
1338 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
1340 struct request_queue *req_q;
1342 if (!stripe->dev->bdev) {
1343 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1346 req_q = bdev_get_queue(stripe->dev->bdev);
1347 if (!blk_queue_discard(req_q))
1350 ret = btrfs_issue_discard(stripe->dev->bdev,
1355 discarded_bytes += bytes;
1356 } else if (ret != -EOPNOTSUPP) {
1358 * Logic errors or -ENOMEM, or -EIO, but
1359 * unlikely to happen.
1361 * And since there are two loops, explicitly
1362 * go to out to avoid confusion.
1364 btrfs_put_bbio(bbio);
1369 * Just in case we get back EOPNOTSUPP for some reason,
1370 * just ignore the return value so we don't screw up
1371 * people calling discard_extent.
1375 btrfs_put_bbio(bbio);
1379 btrfs_bio_counter_dec(fs_info);
1382 *actual_bytes = discarded_bytes;
1385 if (ret == -EOPNOTSUPP)
1390 /* Can return -ENOMEM */
1391 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1392 struct btrfs_ref *generic_ref)
1394 struct btrfs_fs_info *fs_info = trans->fs_info;
1395 int old_ref_mod, new_ref_mod;
1398 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
1399 generic_ref->action);
1400 BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
1401 generic_ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID);
1403 if (generic_ref->type == BTRFS_REF_METADATA)
1404 ret = btrfs_add_delayed_tree_ref(trans, generic_ref,
1405 NULL, &old_ref_mod, &new_ref_mod);
1407 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0,
1408 &old_ref_mod, &new_ref_mod);
1410 btrfs_ref_tree_mod(fs_info, generic_ref);
1412 if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0)
1413 sub_pinned_bytes(fs_info, generic_ref);
1419 * __btrfs_inc_extent_ref - insert backreference for a given extent
1421 * @trans: Handle of transaction
1423 * @node: The delayed ref node used to get the bytenr/length for
1424 * extent whose references are incremented.
1426 * @parent: If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
1427 * BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
1428 * bytenr of the parent block. Since new extents are always
1429 * created with indirect references, this will only be the case
1430 * when relocating a shared extent. In that case, root_objectid
1431 * will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
1434 * @root_objectid: The id of the root where this modification has originated,
1435 * this can be either one of the well-known metadata trees or
1436 * the subvolume id which references this extent.
1438 * @owner: For data extents it is the inode number of the owning file.
1439 * For metadata extents this parameter holds the level in the
1440 * tree of the extent.
1442 * @offset: For metadata extents the offset is ignored and is currently
1443 * always passed as 0. For data extents it is the fileoffset
1444 * this extent belongs to.
1446 * @refs_to_add Number of references to add
1448 * @extent_op Pointer to a structure, holding information necessary when
1449 * updating a tree block's flags
1452 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1453 struct btrfs_delayed_ref_node *node,
1454 u64 parent, u64 root_objectid,
1455 u64 owner, u64 offset, int refs_to_add,
1456 struct btrfs_delayed_extent_op *extent_op)
1458 struct btrfs_path *path;
1459 struct extent_buffer *leaf;
1460 struct btrfs_extent_item *item;
1461 struct btrfs_key key;
1462 u64 bytenr = node->bytenr;
1463 u64 num_bytes = node->num_bytes;
1467 path = btrfs_alloc_path();
1471 path->reada = READA_FORWARD;
1472 path->leave_spinning = 1;
1473 /* this will setup the path even if it fails to insert the back ref */
1474 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
1475 parent, root_objectid, owner,
1476 offset, refs_to_add, extent_op);
1477 if ((ret < 0 && ret != -EAGAIN) || !ret)
1481 * Ok we had -EAGAIN which means we didn't have space to insert and
1482 * inline extent ref, so just update the reference count and add a
1485 leaf = path->nodes[0];
1486 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1487 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1488 refs = btrfs_extent_refs(leaf, item);
1489 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1491 __run_delayed_extent_op(extent_op, leaf, item);
1493 btrfs_mark_buffer_dirty(leaf);
1494 btrfs_release_path(path);
1496 path->reada = READA_FORWARD;
1497 path->leave_spinning = 1;
1498 /* now insert the actual backref */
1499 ret = insert_extent_backref(trans, path, bytenr, parent, root_objectid,
1500 owner, offset, refs_to_add);
1502 btrfs_abort_transaction(trans, ret);
1504 btrfs_free_path(path);
1508 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1509 struct btrfs_delayed_ref_node *node,
1510 struct btrfs_delayed_extent_op *extent_op,
1511 int insert_reserved)
1514 struct btrfs_delayed_data_ref *ref;
1515 struct btrfs_key ins;
1520 ins.objectid = node->bytenr;
1521 ins.offset = node->num_bytes;
1522 ins.type = BTRFS_EXTENT_ITEM_KEY;
1524 ref = btrfs_delayed_node_to_data_ref(node);
1525 trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
1527 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1528 parent = ref->parent;
1529 ref_root = ref->root;
1531 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1533 flags |= extent_op->flags_to_set;
1534 ret = alloc_reserved_file_extent(trans, parent, ref_root,
1535 flags, ref->objectid,
1538 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1539 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
1540 ref->objectid, ref->offset,
1541 node->ref_mod, extent_op);
1542 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1543 ret = __btrfs_free_extent(trans, node, parent,
1544 ref_root, ref->objectid,
1545 ref->offset, node->ref_mod,
1553 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1554 struct extent_buffer *leaf,
1555 struct btrfs_extent_item *ei)
1557 u64 flags = btrfs_extent_flags(leaf, ei);
1558 if (extent_op->update_flags) {
1559 flags |= extent_op->flags_to_set;
1560 btrfs_set_extent_flags(leaf, ei, flags);
1563 if (extent_op->update_key) {
1564 struct btrfs_tree_block_info *bi;
1565 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1566 bi = (struct btrfs_tree_block_info *)(ei + 1);
1567 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1571 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1572 struct btrfs_delayed_ref_head *head,
1573 struct btrfs_delayed_extent_op *extent_op)
1575 struct btrfs_fs_info *fs_info = trans->fs_info;
1576 struct btrfs_key key;
1577 struct btrfs_path *path;
1578 struct btrfs_extent_item *ei;
1579 struct extent_buffer *leaf;
1583 int metadata = !extent_op->is_data;
1588 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1591 path = btrfs_alloc_path();
1595 key.objectid = head->bytenr;
1598 key.type = BTRFS_METADATA_ITEM_KEY;
1599 key.offset = extent_op->level;
1601 key.type = BTRFS_EXTENT_ITEM_KEY;
1602 key.offset = head->num_bytes;
1606 path->reada = READA_FORWARD;
1607 path->leave_spinning = 1;
1608 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
1615 if (path->slots[0] > 0) {
1617 btrfs_item_key_to_cpu(path->nodes[0], &key,
1619 if (key.objectid == head->bytenr &&
1620 key.type == BTRFS_EXTENT_ITEM_KEY &&
1621 key.offset == head->num_bytes)
1625 btrfs_release_path(path);
1628 key.objectid = head->bytenr;
1629 key.offset = head->num_bytes;
1630 key.type = BTRFS_EXTENT_ITEM_KEY;
1639 leaf = path->nodes[0];
1640 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1642 if (unlikely(item_size < sizeof(*ei))) {
1644 btrfs_print_v0_err(fs_info);
1645 btrfs_abort_transaction(trans, err);
1649 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1650 __run_delayed_extent_op(extent_op, leaf, ei);
1652 btrfs_mark_buffer_dirty(leaf);
1654 btrfs_free_path(path);
1658 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
1659 struct btrfs_delayed_ref_node *node,
1660 struct btrfs_delayed_extent_op *extent_op,
1661 int insert_reserved)
1664 struct btrfs_delayed_tree_ref *ref;
1668 ref = btrfs_delayed_node_to_tree_ref(node);
1669 trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
1671 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1672 parent = ref->parent;
1673 ref_root = ref->root;
1675 if (node->ref_mod != 1) {
1676 btrfs_err(trans->fs_info,
1677 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
1678 node->bytenr, node->ref_mod, node->action, ref_root,
1682 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1683 BUG_ON(!extent_op || !extent_op->update_flags);
1684 ret = alloc_reserved_tree_block(trans, node, extent_op);
1685 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1686 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
1687 ref->level, 0, 1, extent_op);
1688 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1689 ret = __btrfs_free_extent(trans, node, parent, ref_root,
1690 ref->level, 0, 1, extent_op);
1697 /* helper function to actually process a single delayed ref entry */
1698 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
1699 struct btrfs_delayed_ref_node *node,
1700 struct btrfs_delayed_extent_op *extent_op,
1701 int insert_reserved)
1705 if (trans->aborted) {
1706 if (insert_reserved)
1707 btrfs_pin_extent(trans->fs_info, node->bytenr,
1708 node->num_bytes, 1);
1712 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
1713 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1714 ret = run_delayed_tree_ref(trans, node, extent_op,
1716 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
1717 node->type == BTRFS_SHARED_DATA_REF_KEY)
1718 ret = run_delayed_data_ref(trans, node, extent_op,
1722 if (ret && insert_reserved)
1723 btrfs_pin_extent(trans->fs_info, node->bytenr,
1724 node->num_bytes, 1);
1728 static inline struct btrfs_delayed_ref_node *
1729 select_delayed_ref(struct btrfs_delayed_ref_head *head)
1731 struct btrfs_delayed_ref_node *ref;
1733 if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
1737 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
1738 * This is to prevent a ref count from going down to zero, which deletes
1739 * the extent item from the extent tree, when there still are references
1740 * to add, which would fail because they would not find the extent item.
1742 if (!list_empty(&head->ref_add_list))
1743 return list_first_entry(&head->ref_add_list,
1744 struct btrfs_delayed_ref_node, add_list);
1746 ref = rb_entry(rb_first_cached(&head->ref_tree),
1747 struct btrfs_delayed_ref_node, ref_node);
1748 ASSERT(list_empty(&ref->add_list));
1752 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
1753 struct btrfs_delayed_ref_head *head)
1755 spin_lock(&delayed_refs->lock);
1756 head->processing = 0;
1757 delayed_refs->num_heads_ready++;
1758 spin_unlock(&delayed_refs->lock);
1759 btrfs_delayed_ref_unlock(head);
1762 static struct btrfs_delayed_extent_op *cleanup_extent_op(
1763 struct btrfs_delayed_ref_head *head)
1765 struct btrfs_delayed_extent_op *extent_op = head->extent_op;
1770 if (head->must_insert_reserved) {
1771 head->extent_op = NULL;
1772 btrfs_free_delayed_extent_op(extent_op);
1778 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
1779 struct btrfs_delayed_ref_head *head)
1781 struct btrfs_delayed_extent_op *extent_op;
1784 extent_op = cleanup_extent_op(head);
1787 head->extent_op = NULL;
1788 spin_unlock(&head->lock);
1789 ret = run_delayed_extent_op(trans, head, extent_op);
1790 btrfs_free_delayed_extent_op(extent_op);
1791 return ret ? ret : 1;
1794 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
1795 struct btrfs_delayed_ref_root *delayed_refs,
1796 struct btrfs_delayed_ref_head *head)
1798 int nr_items = 1; /* Dropping this ref head update. */
1800 if (head->total_ref_mod < 0) {
1801 struct btrfs_space_info *space_info;
1805 flags = BTRFS_BLOCK_GROUP_DATA;
1806 else if (head->is_system)
1807 flags = BTRFS_BLOCK_GROUP_SYSTEM;
1809 flags = BTRFS_BLOCK_GROUP_METADATA;
1810 space_info = btrfs_find_space_info(fs_info, flags);
1812 percpu_counter_add_batch(&space_info->total_bytes_pinned,
1814 BTRFS_TOTAL_BYTES_PINNED_BATCH);
1817 * We had csum deletions accounted for in our delayed refs rsv,
1818 * we need to drop the csum leaves for this update from our
1821 if (head->is_data) {
1822 spin_lock(&delayed_refs->lock);
1823 delayed_refs->pending_csums -= head->num_bytes;
1824 spin_unlock(&delayed_refs->lock);
1825 nr_items += btrfs_csum_bytes_to_leaves(fs_info,
1830 btrfs_delayed_refs_rsv_release(fs_info, nr_items);
1833 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
1834 struct btrfs_delayed_ref_head *head)
1837 struct btrfs_fs_info *fs_info = trans->fs_info;
1838 struct btrfs_delayed_ref_root *delayed_refs;
1841 delayed_refs = &trans->transaction->delayed_refs;
1843 ret = run_and_cleanup_extent_op(trans, head);
1845 unselect_delayed_ref_head(delayed_refs, head);
1846 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
1853 * Need to drop our head ref lock and re-acquire the delayed ref lock
1854 * and then re-check to make sure nobody got added.
1856 spin_unlock(&head->lock);
1857 spin_lock(&delayed_refs->lock);
1858 spin_lock(&head->lock);
1859 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
1860 spin_unlock(&head->lock);
1861 spin_unlock(&delayed_refs->lock);
1864 btrfs_delete_ref_head(delayed_refs, head);
1865 spin_unlock(&head->lock);
1866 spin_unlock(&delayed_refs->lock);
1868 if (head->must_insert_reserved) {
1869 btrfs_pin_extent(fs_info, head->bytenr,
1870 head->num_bytes, 1);
1871 if (head->is_data) {
1872 ret = btrfs_del_csums(trans, fs_info, head->bytenr,
1877 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
1879 trace_run_delayed_ref_head(fs_info, head, 0);
1880 btrfs_delayed_ref_unlock(head);
1881 btrfs_put_delayed_ref_head(head);
1885 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
1886 struct btrfs_trans_handle *trans)
1888 struct btrfs_delayed_ref_root *delayed_refs =
1889 &trans->transaction->delayed_refs;
1890 struct btrfs_delayed_ref_head *head = NULL;
1893 spin_lock(&delayed_refs->lock);
1894 head = btrfs_select_ref_head(delayed_refs);
1896 spin_unlock(&delayed_refs->lock);
1901 * Grab the lock that says we are going to process all the refs for
1904 ret = btrfs_delayed_ref_lock(delayed_refs, head);
1905 spin_unlock(&delayed_refs->lock);
1908 * We may have dropped the spin lock to get the head mutex lock, and
1909 * that might have given someone else time to free the head. If that's
1910 * true, it has been removed from our list and we can move on.
1913 head = ERR_PTR(-EAGAIN);
1918 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
1919 struct btrfs_delayed_ref_head *locked_ref,
1920 unsigned long *run_refs)
1922 struct btrfs_fs_info *fs_info = trans->fs_info;
1923 struct btrfs_delayed_ref_root *delayed_refs;
1924 struct btrfs_delayed_extent_op *extent_op;
1925 struct btrfs_delayed_ref_node *ref;
1926 int must_insert_reserved = 0;
1929 delayed_refs = &trans->transaction->delayed_refs;
1931 lockdep_assert_held(&locked_ref->mutex);
1932 lockdep_assert_held(&locked_ref->lock);
1934 while ((ref = select_delayed_ref(locked_ref))) {
1936 btrfs_check_delayed_seq(fs_info, ref->seq)) {
1937 spin_unlock(&locked_ref->lock);
1938 unselect_delayed_ref_head(delayed_refs, locked_ref);
1944 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
1945 RB_CLEAR_NODE(&ref->ref_node);
1946 if (!list_empty(&ref->add_list))
1947 list_del(&ref->add_list);
1949 * When we play the delayed ref, also correct the ref_mod on
1952 switch (ref->action) {
1953 case BTRFS_ADD_DELAYED_REF:
1954 case BTRFS_ADD_DELAYED_EXTENT:
1955 locked_ref->ref_mod -= ref->ref_mod;
1957 case BTRFS_DROP_DELAYED_REF:
1958 locked_ref->ref_mod += ref->ref_mod;
1963 atomic_dec(&delayed_refs->num_entries);
1966 * Record the must_insert_reserved flag before we drop the
1969 must_insert_reserved = locked_ref->must_insert_reserved;
1970 locked_ref->must_insert_reserved = 0;
1972 extent_op = locked_ref->extent_op;
1973 locked_ref->extent_op = NULL;
1974 spin_unlock(&locked_ref->lock);
1976 ret = run_one_delayed_ref(trans, ref, extent_op,
1977 must_insert_reserved);
1979 btrfs_free_delayed_extent_op(extent_op);
1981 unselect_delayed_ref_head(delayed_refs, locked_ref);
1982 btrfs_put_delayed_ref(ref);
1983 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
1988 btrfs_put_delayed_ref(ref);
1991 spin_lock(&locked_ref->lock);
1992 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
1999 * Returns 0 on success or if called with an already aborted transaction.
2000 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2002 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2005 struct btrfs_fs_info *fs_info = trans->fs_info;
2006 struct btrfs_delayed_ref_root *delayed_refs;
2007 struct btrfs_delayed_ref_head *locked_ref = NULL;
2008 ktime_t start = ktime_get();
2010 unsigned long count = 0;
2011 unsigned long actual_count = 0;
2013 delayed_refs = &trans->transaction->delayed_refs;
2016 locked_ref = btrfs_obtain_ref_head(trans);
2017 if (IS_ERR_OR_NULL(locked_ref)) {
2018 if (PTR_ERR(locked_ref) == -EAGAIN) {
2027 * We need to try and merge add/drops of the same ref since we
2028 * can run into issues with relocate dropping the implicit ref
2029 * and then it being added back again before the drop can
2030 * finish. If we merged anything we need to re-loop so we can
2032 * Or we can get node references of the same type that weren't
2033 * merged when created due to bumps in the tree mod seq, and
2034 * we need to merge them to prevent adding an inline extent
2035 * backref before dropping it (triggering a BUG_ON at
2036 * insert_inline_extent_backref()).
2038 spin_lock(&locked_ref->lock);
2039 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2041 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2043 if (ret < 0 && ret != -EAGAIN) {
2045 * Error, btrfs_run_delayed_refs_for_head already
2046 * unlocked everything so just bail out
2051 * Success, perform the usual cleanup of a processed
2054 ret = cleanup_ref_head(trans, locked_ref);
2056 /* We dropped our lock, we need to loop. */
2065 * Either success case or btrfs_run_delayed_refs_for_head
2066 * returned -EAGAIN, meaning we need to select another head
2071 } while ((nr != -1 && count < nr) || locked_ref);
2074 * We don't want to include ref heads since we can have empty ref heads
2075 * and those will drastically skew our runtime down since we just do
2076 * accounting, no actual extent tree updates.
2078 if (actual_count > 0) {
2079 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2083 * We weigh the current average higher than our current runtime
2084 * to avoid large swings in the average.
2086 spin_lock(&delayed_refs->lock);
2087 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2088 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2089 spin_unlock(&delayed_refs->lock);
2094 #ifdef SCRAMBLE_DELAYED_REFS
2096 * Normally delayed refs get processed in ascending bytenr order. This
2097 * correlates in most cases to the order added. To expose dependencies on this
2098 * order, we start to process the tree in the middle instead of the beginning
2100 static u64 find_middle(struct rb_root *root)
2102 struct rb_node *n = root->rb_node;
2103 struct btrfs_delayed_ref_node *entry;
2106 u64 first = 0, last = 0;
2110 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2111 first = entry->bytenr;
2115 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2116 last = entry->bytenr;
2121 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2122 WARN_ON(!entry->in_tree);
2124 middle = entry->bytenr;
2137 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2141 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2142 sizeof(struct btrfs_extent_inline_ref));
2143 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2144 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2147 * We don't ever fill up leaves all the way so multiply by 2 just to be
2148 * closer to what we're really going to want to use.
2150 return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2154 * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2155 * would require to store the csums for that many bytes.
2157 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2160 u64 num_csums_per_leaf;
2163 csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2164 num_csums_per_leaf = div64_u64(csum_size,
2165 (u64)btrfs_super_csum_size(fs_info->super_copy));
2166 num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2167 num_csums += num_csums_per_leaf - 1;
2168 num_csums = div64_u64(num_csums, num_csums_per_leaf);
2173 * this starts processing the delayed reference count updates and
2174 * extent insertions we have queued up so far. count can be
2175 * 0, which means to process everything in the tree at the start
2176 * of the run (but not newly added entries), or it can be some target
2177 * number you'd like to process.
2179 * Returns 0 on success or if called with an aborted transaction
2180 * Returns <0 on error and aborts the transaction
2182 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2183 unsigned long count)
2185 struct btrfs_fs_info *fs_info = trans->fs_info;
2186 struct rb_node *node;
2187 struct btrfs_delayed_ref_root *delayed_refs;
2188 struct btrfs_delayed_ref_head *head;
2190 int run_all = count == (unsigned long)-1;
2192 /* We'll clean this up in btrfs_cleanup_transaction */
2196 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2199 delayed_refs = &trans->transaction->delayed_refs;
2201 count = atomic_read(&delayed_refs->num_entries) * 2;
2204 #ifdef SCRAMBLE_DELAYED_REFS
2205 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2207 ret = __btrfs_run_delayed_refs(trans, count);
2209 btrfs_abort_transaction(trans, ret);
2214 btrfs_create_pending_block_groups(trans);
2216 spin_lock(&delayed_refs->lock);
2217 node = rb_first_cached(&delayed_refs->href_root);
2219 spin_unlock(&delayed_refs->lock);
2222 head = rb_entry(node, struct btrfs_delayed_ref_head,
2224 refcount_inc(&head->refs);
2225 spin_unlock(&delayed_refs->lock);
2227 /* Mutex was contended, block until it's released and retry. */
2228 mutex_lock(&head->mutex);
2229 mutex_unlock(&head->mutex);
2231 btrfs_put_delayed_ref_head(head);
2239 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2240 u64 bytenr, u64 num_bytes, u64 flags,
2241 int level, int is_data)
2243 struct btrfs_delayed_extent_op *extent_op;
2246 extent_op = btrfs_alloc_delayed_extent_op();
2250 extent_op->flags_to_set = flags;
2251 extent_op->update_flags = true;
2252 extent_op->update_key = false;
2253 extent_op->is_data = is_data ? true : false;
2254 extent_op->level = level;
2256 ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2258 btrfs_free_delayed_extent_op(extent_op);
2262 static noinline int check_delayed_ref(struct btrfs_root *root,
2263 struct btrfs_path *path,
2264 u64 objectid, u64 offset, u64 bytenr)
2266 struct btrfs_delayed_ref_head *head;
2267 struct btrfs_delayed_ref_node *ref;
2268 struct btrfs_delayed_data_ref *data_ref;
2269 struct btrfs_delayed_ref_root *delayed_refs;
2270 struct btrfs_transaction *cur_trans;
2271 struct rb_node *node;
2274 spin_lock(&root->fs_info->trans_lock);
2275 cur_trans = root->fs_info->running_transaction;
2277 refcount_inc(&cur_trans->use_count);
2278 spin_unlock(&root->fs_info->trans_lock);
2282 delayed_refs = &cur_trans->delayed_refs;
2283 spin_lock(&delayed_refs->lock);
2284 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2286 spin_unlock(&delayed_refs->lock);
2287 btrfs_put_transaction(cur_trans);
2291 if (!mutex_trylock(&head->mutex)) {
2292 refcount_inc(&head->refs);
2293 spin_unlock(&delayed_refs->lock);
2295 btrfs_release_path(path);
2298 * Mutex was contended, block until it's released and let
2301 mutex_lock(&head->mutex);
2302 mutex_unlock(&head->mutex);
2303 btrfs_put_delayed_ref_head(head);
2304 btrfs_put_transaction(cur_trans);
2307 spin_unlock(&delayed_refs->lock);
2309 spin_lock(&head->lock);
2311 * XXX: We should replace this with a proper search function in the
2314 for (node = rb_first_cached(&head->ref_tree); node;
2315 node = rb_next(node)) {
2316 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
2317 /* If it's a shared ref we know a cross reference exists */
2318 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2323 data_ref = btrfs_delayed_node_to_data_ref(ref);
2326 * If our ref doesn't match the one we're currently looking at
2327 * then we have a cross reference.
2329 if (data_ref->root != root->root_key.objectid ||
2330 data_ref->objectid != objectid ||
2331 data_ref->offset != offset) {
2336 spin_unlock(&head->lock);
2337 mutex_unlock(&head->mutex);
2338 btrfs_put_transaction(cur_trans);
2342 static noinline int check_committed_ref(struct btrfs_root *root,
2343 struct btrfs_path *path,
2344 u64 objectid, u64 offset, u64 bytenr)
2346 struct btrfs_fs_info *fs_info = root->fs_info;
2347 struct btrfs_root *extent_root = fs_info->extent_root;
2348 struct extent_buffer *leaf;
2349 struct btrfs_extent_data_ref *ref;
2350 struct btrfs_extent_inline_ref *iref;
2351 struct btrfs_extent_item *ei;
2352 struct btrfs_key key;
2357 key.objectid = bytenr;
2358 key.offset = (u64)-1;
2359 key.type = BTRFS_EXTENT_ITEM_KEY;
2361 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2364 BUG_ON(ret == 0); /* Corruption */
2367 if (path->slots[0] == 0)
2371 leaf = path->nodes[0];
2372 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2374 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2378 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2379 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2381 /* If extent item has more than 1 inline ref then it's shared */
2382 if (item_size != sizeof(*ei) +
2383 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2386 /* If extent created before last snapshot => it's definitely shared */
2387 if (btrfs_extent_generation(leaf, ei) <=
2388 btrfs_root_last_snapshot(&root->root_item))
2391 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2393 /* If this extent has SHARED_DATA_REF then it's shared */
2394 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
2395 if (type != BTRFS_EXTENT_DATA_REF_KEY)
2398 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2399 if (btrfs_extent_refs(leaf, ei) !=
2400 btrfs_extent_data_ref_count(leaf, ref) ||
2401 btrfs_extent_data_ref_root(leaf, ref) !=
2402 root->root_key.objectid ||
2403 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2404 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2412 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
2415 struct btrfs_path *path;
2418 path = btrfs_alloc_path();
2423 ret = check_committed_ref(root, path, objectid,
2425 if (ret && ret != -ENOENT)
2428 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
2429 } while (ret == -EAGAIN);
2432 btrfs_free_path(path);
2433 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2438 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2439 struct btrfs_root *root,
2440 struct extent_buffer *buf,
2441 int full_backref, int inc)
2443 struct btrfs_fs_info *fs_info = root->fs_info;
2449 struct btrfs_key key;
2450 struct btrfs_file_extent_item *fi;
2451 struct btrfs_ref generic_ref = { 0 };
2452 bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
2458 if (btrfs_is_testing(fs_info))
2461 ref_root = btrfs_header_owner(buf);
2462 nritems = btrfs_header_nritems(buf);
2463 level = btrfs_header_level(buf);
2465 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
2469 parent = buf->start;
2473 action = BTRFS_ADD_DELAYED_REF;
2475 action = BTRFS_DROP_DELAYED_REF;
2477 for (i = 0; i < nritems; i++) {
2479 btrfs_item_key_to_cpu(buf, &key, i);
2480 if (key.type != BTRFS_EXTENT_DATA_KEY)
2482 fi = btrfs_item_ptr(buf, i,
2483 struct btrfs_file_extent_item);
2484 if (btrfs_file_extent_type(buf, fi) ==
2485 BTRFS_FILE_EXTENT_INLINE)
2487 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2491 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2492 key.offset -= btrfs_file_extent_offset(buf, fi);
2493 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2495 generic_ref.real_root = root->root_key.objectid;
2496 btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
2498 generic_ref.skip_qgroup = for_reloc;
2500 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2502 ret = btrfs_free_extent(trans, &generic_ref);
2506 bytenr = btrfs_node_blockptr(buf, i);
2507 num_bytes = fs_info->nodesize;
2508 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2510 generic_ref.real_root = root->root_key.objectid;
2511 btrfs_init_tree_ref(&generic_ref, level - 1, ref_root);
2512 generic_ref.skip_qgroup = for_reloc;
2514 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2516 ret = btrfs_free_extent(trans, &generic_ref);
2526 int btrfs_inc_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, 1);
2532 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2533 struct extent_buffer *buf, int full_backref)
2535 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2538 int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
2540 struct btrfs_block_group *block_group;
2543 block_group = btrfs_lookup_block_group(fs_info, bytenr);
2544 if (!block_group || block_group->ro)
2547 btrfs_put_block_group(block_group);
2551 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
2553 struct btrfs_fs_info *fs_info = root->fs_info;
2558 flags = BTRFS_BLOCK_GROUP_DATA;
2559 else if (root == fs_info->chunk_root)
2560 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2562 flags = BTRFS_BLOCK_GROUP_METADATA;
2564 ret = btrfs_get_alloc_profile(fs_info, flags);
2568 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
2570 struct btrfs_block_group *cache;
2573 spin_lock(&fs_info->block_group_cache_lock);
2574 bytenr = fs_info->first_logical_byte;
2575 spin_unlock(&fs_info->block_group_cache_lock);
2577 if (bytenr < (u64)-1)
2580 cache = btrfs_lookup_first_block_group(fs_info, search_start);
2584 bytenr = cache->start;
2585 btrfs_put_block_group(cache);
2590 static int pin_down_extent(struct btrfs_block_group *cache,
2591 u64 bytenr, u64 num_bytes, int reserved)
2593 struct btrfs_fs_info *fs_info = cache->fs_info;
2595 spin_lock(&cache->space_info->lock);
2596 spin_lock(&cache->lock);
2597 cache->pinned += num_bytes;
2598 btrfs_space_info_update_bytes_pinned(fs_info, cache->space_info,
2601 cache->reserved -= num_bytes;
2602 cache->space_info->bytes_reserved -= num_bytes;
2604 spin_unlock(&cache->lock);
2605 spin_unlock(&cache->space_info->lock);
2607 percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
2608 num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
2609 set_extent_dirty(fs_info->pinned_extents, bytenr,
2610 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
2614 int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
2615 u64 bytenr, u64 num_bytes, int reserved)
2617 struct btrfs_block_group *cache;
2619 ASSERT(fs_info->running_transaction);
2621 cache = btrfs_lookup_block_group(fs_info, bytenr);
2622 BUG_ON(!cache); /* Logic error */
2624 pin_down_extent(cache, bytenr, num_bytes, reserved);
2626 btrfs_put_block_group(cache);
2631 * this function must be called within transaction
2633 int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
2634 u64 bytenr, u64 num_bytes)
2636 struct btrfs_block_group *cache;
2639 cache = btrfs_lookup_block_group(fs_info, bytenr);
2644 * pull in the free space cache (if any) so that our pin
2645 * removes the free space from the cache. We have load_only set
2646 * to one because the slow code to read in the free extents does check
2647 * the pinned extents.
2649 btrfs_cache_block_group(cache, 1);
2651 pin_down_extent(cache, bytenr, num_bytes, 0);
2653 /* remove us from the free space cache (if we're there at all) */
2654 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
2655 btrfs_put_block_group(cache);
2659 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
2660 u64 start, u64 num_bytes)
2663 struct btrfs_block_group *block_group;
2664 struct btrfs_caching_control *caching_ctl;
2666 block_group = btrfs_lookup_block_group(fs_info, start);
2670 btrfs_cache_block_group(block_group, 0);
2671 caching_ctl = btrfs_get_caching_control(block_group);
2675 BUG_ON(!btrfs_block_group_done(block_group));
2676 ret = btrfs_remove_free_space(block_group, start, num_bytes);
2678 mutex_lock(&caching_ctl->mutex);
2680 if (start >= caching_ctl->progress) {
2681 ret = btrfs_add_excluded_extent(fs_info, start,
2683 } else if (start + num_bytes <= caching_ctl->progress) {
2684 ret = btrfs_remove_free_space(block_group,
2687 num_bytes = caching_ctl->progress - start;
2688 ret = btrfs_remove_free_space(block_group,
2693 num_bytes = (start + num_bytes) -
2694 caching_ctl->progress;
2695 start = caching_ctl->progress;
2696 ret = btrfs_add_excluded_extent(fs_info, start,
2700 mutex_unlock(&caching_ctl->mutex);
2701 btrfs_put_caching_control(caching_ctl);
2703 btrfs_put_block_group(block_group);
2707 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
2709 struct btrfs_fs_info *fs_info = eb->fs_info;
2710 struct btrfs_file_extent_item *item;
2711 struct btrfs_key key;
2716 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
2719 for (i = 0; i < btrfs_header_nritems(eb); i++) {
2720 btrfs_item_key_to_cpu(eb, &key, i);
2721 if (key.type != BTRFS_EXTENT_DATA_KEY)
2723 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
2724 found_type = btrfs_file_extent_type(eb, item);
2725 if (found_type == BTRFS_FILE_EXTENT_INLINE)
2727 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
2729 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
2730 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
2731 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
2740 btrfs_inc_block_group_reservations(struct btrfs_block_group *bg)
2742 atomic_inc(&bg->reservations);
2745 void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
2747 struct btrfs_caching_control *next;
2748 struct btrfs_caching_control *caching_ctl;
2749 struct btrfs_block_group *cache;
2751 down_write(&fs_info->commit_root_sem);
2753 list_for_each_entry_safe(caching_ctl, next,
2754 &fs_info->caching_block_groups, list) {
2755 cache = caching_ctl->block_group;
2756 if (btrfs_block_group_done(cache)) {
2757 cache->last_byte_to_unpin = (u64)-1;
2758 list_del_init(&caching_ctl->list);
2759 btrfs_put_caching_control(caching_ctl);
2761 cache->last_byte_to_unpin = caching_ctl->progress;
2765 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
2766 fs_info->pinned_extents = &fs_info->freed_extents[1];
2768 fs_info->pinned_extents = &fs_info->freed_extents[0];
2770 up_write(&fs_info->commit_root_sem);
2772 btrfs_update_global_block_rsv(fs_info);
2776 * Returns the free cluster for the given space info and sets empty_cluster to
2777 * what it should be based on the mount options.
2779 static struct btrfs_free_cluster *
2780 fetch_cluster_info(struct btrfs_fs_info *fs_info,
2781 struct btrfs_space_info *space_info, u64 *empty_cluster)
2783 struct btrfs_free_cluster *ret = NULL;
2786 if (btrfs_mixed_space_info(space_info))
2789 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
2790 ret = &fs_info->meta_alloc_cluster;
2791 if (btrfs_test_opt(fs_info, SSD))
2792 *empty_cluster = SZ_2M;
2794 *empty_cluster = SZ_64K;
2795 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
2796 btrfs_test_opt(fs_info, SSD_SPREAD)) {
2797 *empty_cluster = SZ_2M;
2798 ret = &fs_info->data_alloc_cluster;
2804 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
2806 const bool return_free_space)
2808 struct btrfs_block_group *cache = NULL;
2809 struct btrfs_space_info *space_info;
2810 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2811 struct btrfs_free_cluster *cluster = NULL;
2813 u64 total_unpinned = 0;
2814 u64 empty_cluster = 0;
2817 while (start <= end) {
2820 start >= cache->start + cache->length) {
2822 btrfs_put_block_group(cache);
2824 cache = btrfs_lookup_block_group(fs_info, start);
2825 BUG_ON(!cache); /* Logic error */
2827 cluster = fetch_cluster_info(fs_info,
2830 empty_cluster <<= 1;
2833 len = cache->start + cache->length - start;
2834 len = min(len, end + 1 - start);
2836 if (start < cache->last_byte_to_unpin) {
2837 len = min(len, cache->last_byte_to_unpin - start);
2838 if (return_free_space)
2839 btrfs_add_free_space(cache, start, len);
2843 total_unpinned += len;
2844 space_info = cache->space_info;
2847 * If this space cluster has been marked as fragmented and we've
2848 * unpinned enough in this block group to potentially allow a
2849 * cluster to be created inside of it go ahead and clear the
2852 if (cluster && cluster->fragmented &&
2853 total_unpinned > empty_cluster) {
2854 spin_lock(&cluster->lock);
2855 cluster->fragmented = 0;
2856 spin_unlock(&cluster->lock);
2859 spin_lock(&space_info->lock);
2860 spin_lock(&cache->lock);
2861 cache->pinned -= len;
2862 btrfs_space_info_update_bytes_pinned(fs_info, space_info, -len);
2863 space_info->max_extent_size = 0;
2864 percpu_counter_add_batch(&space_info->total_bytes_pinned,
2865 -len, BTRFS_TOTAL_BYTES_PINNED_BATCH);
2867 space_info->bytes_readonly += len;
2870 spin_unlock(&cache->lock);
2871 if (!readonly && return_free_space &&
2872 global_rsv->space_info == space_info) {
2875 spin_lock(&global_rsv->lock);
2876 if (!global_rsv->full) {
2877 to_add = min(len, global_rsv->size -
2878 global_rsv->reserved);
2879 global_rsv->reserved += to_add;
2880 btrfs_space_info_update_bytes_may_use(fs_info,
2881 space_info, to_add);
2882 if (global_rsv->reserved >= global_rsv->size)
2883 global_rsv->full = 1;
2886 spin_unlock(&global_rsv->lock);
2887 /* Add to any tickets we may have */
2889 btrfs_try_granting_tickets(fs_info,
2892 spin_unlock(&space_info->lock);
2896 btrfs_put_block_group(cache);
2900 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
2902 struct btrfs_fs_info *fs_info = trans->fs_info;
2903 struct btrfs_block_group *block_group, *tmp;
2904 struct list_head *deleted_bgs;
2905 struct extent_io_tree *unpin;
2910 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
2911 unpin = &fs_info->freed_extents[1];
2913 unpin = &fs_info->freed_extents[0];
2915 while (!trans->aborted) {
2916 struct extent_state *cached_state = NULL;
2918 mutex_lock(&fs_info->unused_bg_unpin_mutex);
2919 ret = find_first_extent_bit(unpin, 0, &start, &end,
2920 EXTENT_DIRTY, &cached_state);
2922 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2926 if (btrfs_test_opt(fs_info, DISCARD))
2927 ret = btrfs_discard_extent(fs_info, start,
2928 end + 1 - start, NULL);
2930 clear_extent_dirty(unpin, start, end, &cached_state);
2931 unpin_extent_range(fs_info, start, end, true);
2932 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2933 free_extent_state(cached_state);
2938 * Transaction is finished. We don't need the lock anymore. We
2939 * do need to clean up the block groups in case of a transaction
2942 deleted_bgs = &trans->transaction->deleted_bgs;
2943 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
2947 if (!trans->aborted)
2948 ret = btrfs_discard_extent(fs_info,
2950 block_group->length,
2953 list_del_init(&block_group->bg_list);
2954 btrfs_put_block_group_trimming(block_group);
2955 btrfs_put_block_group(block_group);
2958 const char *errstr = btrfs_decode_error(ret);
2960 "discard failed while removing blockgroup: errno=%d %s",
2968 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
2969 struct btrfs_delayed_ref_node *node, u64 parent,
2970 u64 root_objectid, u64 owner_objectid,
2971 u64 owner_offset, int refs_to_drop,
2972 struct btrfs_delayed_extent_op *extent_op)
2974 struct btrfs_fs_info *info = trans->fs_info;
2975 struct btrfs_key key;
2976 struct btrfs_path *path;
2977 struct btrfs_root *extent_root = info->extent_root;
2978 struct extent_buffer *leaf;
2979 struct btrfs_extent_item *ei;
2980 struct btrfs_extent_inline_ref *iref;
2983 int extent_slot = 0;
2984 int found_extent = 0;
2988 u64 bytenr = node->bytenr;
2989 u64 num_bytes = node->num_bytes;
2991 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
2993 path = btrfs_alloc_path();
2997 path->reada = READA_FORWARD;
2998 path->leave_spinning = 1;
3000 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
3001 BUG_ON(!is_data && refs_to_drop != 1);
3004 skinny_metadata = false;
3006 ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
3007 parent, root_objectid, owner_objectid,
3010 extent_slot = path->slots[0];
3011 while (extent_slot >= 0) {
3012 btrfs_item_key_to_cpu(path->nodes[0], &key,
3014 if (key.objectid != bytenr)
3016 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
3017 key.offset == num_bytes) {
3021 if (key.type == BTRFS_METADATA_ITEM_KEY &&
3022 key.offset == owner_objectid) {
3026 if (path->slots[0] - extent_slot > 5)
3031 if (!found_extent) {
3033 ret = remove_extent_backref(trans, path, NULL,
3035 is_data, &last_ref);
3037 btrfs_abort_transaction(trans, ret);
3040 btrfs_release_path(path);
3041 path->leave_spinning = 1;
3043 key.objectid = bytenr;
3044 key.type = BTRFS_EXTENT_ITEM_KEY;
3045 key.offset = num_bytes;
3047 if (!is_data && skinny_metadata) {
3048 key.type = BTRFS_METADATA_ITEM_KEY;
3049 key.offset = owner_objectid;
3052 ret = btrfs_search_slot(trans, extent_root,
3054 if (ret > 0 && skinny_metadata && path->slots[0]) {
3056 * Couldn't find our skinny metadata item,
3057 * see if we have ye olde extent item.
3060 btrfs_item_key_to_cpu(path->nodes[0], &key,
3062 if (key.objectid == bytenr &&
3063 key.type == BTRFS_EXTENT_ITEM_KEY &&
3064 key.offset == num_bytes)
3068 if (ret > 0 && skinny_metadata) {
3069 skinny_metadata = false;
3070 key.objectid = bytenr;
3071 key.type = BTRFS_EXTENT_ITEM_KEY;
3072 key.offset = num_bytes;
3073 btrfs_release_path(path);
3074 ret = btrfs_search_slot(trans, extent_root,
3080 "umm, got %d back from search, was looking for %llu",
3083 btrfs_print_leaf(path->nodes[0]);
3086 btrfs_abort_transaction(trans, ret);
3089 extent_slot = path->slots[0];
3091 } else if (WARN_ON(ret == -ENOENT)) {
3092 btrfs_print_leaf(path->nodes[0]);
3094 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
3095 bytenr, parent, root_objectid, owner_objectid,
3097 btrfs_abort_transaction(trans, ret);
3100 btrfs_abort_transaction(trans, ret);
3104 leaf = path->nodes[0];
3105 item_size = btrfs_item_size_nr(leaf, extent_slot);
3106 if (unlikely(item_size < sizeof(*ei))) {
3108 btrfs_print_v0_err(info);
3109 btrfs_abort_transaction(trans, ret);
3112 ei = btrfs_item_ptr(leaf, extent_slot,
3113 struct btrfs_extent_item);
3114 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
3115 key.type == BTRFS_EXTENT_ITEM_KEY) {
3116 struct btrfs_tree_block_info *bi;
3117 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
3118 bi = (struct btrfs_tree_block_info *)(ei + 1);
3119 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
3122 refs = btrfs_extent_refs(leaf, ei);
3123 if (refs < refs_to_drop) {
3125 "trying to drop %d refs but we only have %Lu for bytenr %Lu",
3126 refs_to_drop, refs, bytenr);
3128 btrfs_abort_transaction(trans, ret);
3131 refs -= refs_to_drop;
3135 __run_delayed_extent_op(extent_op, leaf, ei);
3137 * In the case of inline back ref, reference count will
3138 * be updated by remove_extent_backref
3141 BUG_ON(!found_extent);
3143 btrfs_set_extent_refs(leaf, ei, refs);
3144 btrfs_mark_buffer_dirty(leaf);
3147 ret = remove_extent_backref(trans, path, iref,
3148 refs_to_drop, is_data,
3151 btrfs_abort_transaction(trans, ret);
3157 BUG_ON(is_data && refs_to_drop !=
3158 extent_data_ref_count(path, iref));
3160 BUG_ON(path->slots[0] != extent_slot);
3162 BUG_ON(path->slots[0] != extent_slot + 1);
3163 path->slots[0] = extent_slot;
3169 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
3172 btrfs_abort_transaction(trans, ret);
3175 btrfs_release_path(path);
3178 ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
3180 btrfs_abort_transaction(trans, ret);
3185 ret = add_to_free_space_tree(trans, bytenr, num_bytes);
3187 btrfs_abort_transaction(trans, ret);
3191 ret = btrfs_update_block_group(trans, bytenr, num_bytes, 0);
3193 btrfs_abort_transaction(trans, ret);
3197 btrfs_release_path(path);
3200 btrfs_free_path(path);
3205 * when we free an block, it is possible (and likely) that we free the last
3206 * delayed ref for that extent as well. This searches the delayed ref tree for
3207 * a given extent, and if there are no other delayed refs to be processed, it
3208 * removes it from the tree.
3210 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
3213 struct btrfs_delayed_ref_head *head;
3214 struct btrfs_delayed_ref_root *delayed_refs;
3217 delayed_refs = &trans->transaction->delayed_refs;
3218 spin_lock(&delayed_refs->lock);
3219 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
3221 goto out_delayed_unlock;
3223 spin_lock(&head->lock);
3224 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
3227 if (cleanup_extent_op(head) != NULL)
3231 * waiting for the lock here would deadlock. If someone else has it
3232 * locked they are already in the process of dropping it anyway
3234 if (!mutex_trylock(&head->mutex))
3237 btrfs_delete_ref_head(delayed_refs, head);
3238 head->processing = 0;
3240 spin_unlock(&head->lock);
3241 spin_unlock(&delayed_refs->lock);
3243 BUG_ON(head->extent_op);
3244 if (head->must_insert_reserved)
3247 btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
3248 mutex_unlock(&head->mutex);
3249 btrfs_put_delayed_ref_head(head);
3252 spin_unlock(&head->lock);
3255 spin_unlock(&delayed_refs->lock);
3259 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
3260 struct btrfs_root *root,
3261 struct extent_buffer *buf,
3262 u64 parent, int last_ref)
3264 struct btrfs_fs_info *fs_info = root->fs_info;
3265 struct btrfs_ref generic_ref = { 0 };
3269 btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
3270 buf->start, buf->len, parent);
3271 btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
3272 root->root_key.objectid);
3274 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
3275 int old_ref_mod, new_ref_mod;
3277 btrfs_ref_tree_mod(fs_info, &generic_ref);
3278 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL,
3279 &old_ref_mod, &new_ref_mod);
3280 BUG_ON(ret); /* -ENOMEM */
3281 pin = old_ref_mod >= 0 && new_ref_mod < 0;
3284 if (last_ref && btrfs_header_generation(buf) == trans->transid) {
3285 struct btrfs_block_group *cache;
3287 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
3288 ret = check_ref_cleanup(trans, buf->start);
3294 cache = btrfs_lookup_block_group(fs_info, buf->start);
3296 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
3297 pin_down_extent(cache, buf->start, buf->len, 1);
3298 btrfs_put_block_group(cache);
3302 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
3304 btrfs_add_free_space(cache, buf->start, buf->len);
3305 btrfs_free_reserved_bytes(cache, buf->len, 0);
3306 btrfs_put_block_group(cache);
3307 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
3311 add_pinned_bytes(fs_info, &generic_ref);
3315 * Deleting the buffer, clear the corrupt flag since it doesn't
3318 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
3322 /* Can return -ENOMEM */
3323 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
3325 struct btrfs_fs_info *fs_info = trans->fs_info;
3326 int old_ref_mod, new_ref_mod;
3329 if (btrfs_is_testing(fs_info))
3333 * tree log blocks never actually go into the extent allocation
3334 * tree, just update pinning info and exit early.
3336 if ((ref->type == BTRFS_REF_METADATA &&
3337 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
3338 (ref->type == BTRFS_REF_DATA &&
3339 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)) {
3340 /* unlocks the pinned mutex */
3341 btrfs_pin_extent(fs_info, ref->bytenr, ref->len, 1);
3342 old_ref_mod = new_ref_mod = 0;
3344 } else if (ref->type == BTRFS_REF_METADATA) {
3345 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL,
3346 &old_ref_mod, &new_ref_mod);
3348 ret = btrfs_add_delayed_data_ref(trans, ref, 0,
3349 &old_ref_mod, &new_ref_mod);
3352 if (!((ref->type == BTRFS_REF_METADATA &&
3353 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
3354 (ref->type == BTRFS_REF_DATA &&
3355 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)))
3356 btrfs_ref_tree_mod(fs_info, ref);
3358 if (ret == 0 && old_ref_mod >= 0 && new_ref_mod < 0)
3359 add_pinned_bytes(fs_info, ref);
3364 enum btrfs_loop_type {
3365 LOOP_CACHING_NOWAIT,
3372 btrfs_lock_block_group(struct btrfs_block_group *cache,
3376 down_read(&cache->data_rwsem);
3379 static inline void btrfs_grab_block_group(struct btrfs_block_group *cache,
3382 btrfs_get_block_group(cache);
3384 down_read(&cache->data_rwsem);
3387 static struct btrfs_block_group *btrfs_lock_cluster(
3388 struct btrfs_block_group *block_group,
3389 struct btrfs_free_cluster *cluster,
3392 struct btrfs_block_group *used_bg = NULL;
3394 spin_lock(&cluster->refill_lock);
3396 used_bg = cluster->block_group;
3400 if (used_bg == block_group)
3403 btrfs_get_block_group(used_bg);
3408 if (down_read_trylock(&used_bg->data_rwsem))
3411 spin_unlock(&cluster->refill_lock);
3413 /* We should only have one-level nested. */
3414 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
3416 spin_lock(&cluster->refill_lock);
3417 if (used_bg == cluster->block_group)
3420 up_read(&used_bg->data_rwsem);
3421 btrfs_put_block_group(used_bg);
3426 btrfs_release_block_group(struct btrfs_block_group *cache,
3430 up_read(&cache->data_rwsem);
3431 btrfs_put_block_group(cache);
3435 * Structure used internally for find_free_extent() function. Wraps needed
3438 struct find_free_extent_ctl {
3439 /* Basic allocation info */
3446 /* Where to start the search inside the bg */
3449 /* For clustered allocation */
3452 bool have_caching_bg;
3453 bool orig_have_caching_bg;
3455 /* RAID index, converted from flags */
3459 * Current loop number, check find_free_extent_update_loop() for details
3464 * Whether we're refilling a cluster, if true we need to re-search
3465 * current block group but don't try to refill the cluster again.
3467 bool retry_clustered;
3470 * Whether we're updating free space cache, if true we need to re-search
3471 * current block group but don't try updating free space cache again.
3473 bool retry_unclustered;
3475 /* If current block group is cached */
3478 /* Max contiguous hole found */
3479 u64 max_extent_size;
3481 /* Total free space from free space cache, not always contiguous */
3482 u64 total_free_space;
3490 * Helper function for find_free_extent().
3492 * Return -ENOENT to inform caller that we need fallback to unclustered mode.
3493 * Return -EAGAIN to inform caller that we need to re-search this block group
3494 * Return >0 to inform caller that we find nothing
3495 * Return 0 means we have found a location and set ffe_ctl->found_offset.
3497 static int find_free_extent_clustered(struct btrfs_block_group *bg,
3498 struct btrfs_free_cluster *last_ptr,
3499 struct find_free_extent_ctl *ffe_ctl,
3500 struct btrfs_block_group **cluster_bg_ret)
3502 struct btrfs_block_group *cluster_bg;
3503 u64 aligned_cluster;
3507 cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
3509 goto refill_cluster;
3510 if (cluster_bg != bg && (cluster_bg->ro ||
3511 !block_group_bits(cluster_bg, ffe_ctl->flags)))
3512 goto release_cluster;
3514 offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
3515 ffe_ctl->num_bytes, cluster_bg->start,
3516 &ffe_ctl->max_extent_size);
3518 /* We have a block, we're done */
3519 spin_unlock(&last_ptr->refill_lock);
3520 trace_btrfs_reserve_extent_cluster(cluster_bg,
3521 ffe_ctl->search_start, ffe_ctl->num_bytes);
3522 *cluster_bg_ret = cluster_bg;
3523 ffe_ctl->found_offset = offset;
3526 WARN_ON(last_ptr->block_group != cluster_bg);
3530 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
3531 * lets just skip it and let the allocator find whatever block it can
3532 * find. If we reach this point, we will have tried the cluster
3533 * allocator plenty of times and not have found anything, so we are
3534 * likely way too fragmented for the clustering stuff to find anything.
3536 * However, if the cluster is taken from the current block group,
3537 * release the cluster first, so that we stand a better chance of
3538 * succeeding in the unclustered allocation.
3540 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
3541 spin_unlock(&last_ptr->refill_lock);
3542 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3546 /* This cluster didn't work out, free it and start over */
3547 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3549 if (cluster_bg != bg)
3550 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3553 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
3554 spin_unlock(&last_ptr->refill_lock);
3558 aligned_cluster = max_t(u64,
3559 ffe_ctl->empty_cluster + ffe_ctl->empty_size,
3560 bg->full_stripe_len);
3561 ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
3562 ffe_ctl->num_bytes, aligned_cluster);
3564 /* Now pull our allocation out of this cluster */
3565 offset = btrfs_alloc_from_cluster(bg, last_ptr,
3566 ffe_ctl->num_bytes, ffe_ctl->search_start,
3567 &ffe_ctl->max_extent_size);
3569 /* We found one, proceed */
3570 spin_unlock(&last_ptr->refill_lock);
3571 trace_btrfs_reserve_extent_cluster(bg,
3572 ffe_ctl->search_start,
3573 ffe_ctl->num_bytes);
3574 ffe_ctl->found_offset = offset;
3577 } else if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
3578 !ffe_ctl->retry_clustered) {
3579 spin_unlock(&last_ptr->refill_lock);
3581 ffe_ctl->retry_clustered = true;
3582 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3583 ffe_ctl->empty_cluster + ffe_ctl->empty_size);
3587 * At this point we either didn't find a cluster or we weren't able to
3588 * allocate a block from our cluster. Free the cluster we've been
3589 * trying to use, and go to the next block group.
3591 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3592 spin_unlock(&last_ptr->refill_lock);
3597 * Return >0 to inform caller that we find nothing
3598 * Return 0 when we found an free extent and set ffe_ctrl->found_offset
3599 * Return -EAGAIN to inform caller that we need to re-search this block group
3601 static int find_free_extent_unclustered(struct btrfs_block_group *bg,
3602 struct btrfs_free_cluster *last_ptr,
3603 struct find_free_extent_ctl *ffe_ctl)
3608 * We are doing an unclustered allocation, set the fragmented flag so
3609 * we don't bother trying to setup a cluster again until we get more
3612 if (unlikely(last_ptr)) {
3613 spin_lock(&last_ptr->lock);
3614 last_ptr->fragmented = 1;
3615 spin_unlock(&last_ptr->lock);
3617 if (ffe_ctl->cached) {
3618 struct btrfs_free_space_ctl *free_space_ctl;
3620 free_space_ctl = bg->free_space_ctl;
3621 spin_lock(&free_space_ctl->tree_lock);
3622 if (free_space_ctl->free_space <
3623 ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
3624 ffe_ctl->empty_size) {
3625 ffe_ctl->total_free_space = max_t(u64,
3626 ffe_ctl->total_free_space,
3627 free_space_ctl->free_space);
3628 spin_unlock(&free_space_ctl->tree_lock);
3631 spin_unlock(&free_space_ctl->tree_lock);
3634 offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
3635 ffe_ctl->num_bytes, ffe_ctl->empty_size,
3636 &ffe_ctl->max_extent_size);
3639 * If we didn't find a chunk, and we haven't failed on this block group
3640 * before, and this block group is in the middle of caching and we are
3641 * ok with waiting, then go ahead and wait for progress to be made, and
3642 * set @retry_unclustered to true.
3644 * If @retry_unclustered is true then we've already waited on this
3645 * block group once and should move on to the next block group.
3647 if (!offset && !ffe_ctl->retry_unclustered && !ffe_ctl->cached &&
3648 ffe_ctl->loop > LOOP_CACHING_NOWAIT) {
3649 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3650 ffe_ctl->empty_size);
3651 ffe_ctl->retry_unclustered = true;
3653 } else if (!offset) {
3656 ffe_ctl->found_offset = offset;
3661 * Return >0 means caller needs to re-search for free extent
3662 * Return 0 means we have the needed free extent.
3663 * Return <0 means we failed to locate any free extent.
3665 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
3666 struct btrfs_free_cluster *last_ptr,
3667 struct btrfs_key *ins,
3668 struct find_free_extent_ctl *ffe_ctl,
3669 int full_search, bool use_cluster)
3671 struct btrfs_root *root = fs_info->extent_root;
3674 if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
3675 ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
3676 ffe_ctl->orig_have_caching_bg = true;
3678 if (!ins->objectid && ffe_ctl->loop >= LOOP_CACHING_WAIT &&
3679 ffe_ctl->have_caching_bg)
3682 if (!ins->objectid && ++(ffe_ctl->index) < BTRFS_NR_RAID_TYPES)
3685 if (ins->objectid) {
3686 if (!use_cluster && last_ptr) {
3687 spin_lock(&last_ptr->lock);
3688 last_ptr->window_start = ins->objectid;
3689 spin_unlock(&last_ptr->lock);
3695 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
3696 * caching kthreads as we move along
3697 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
3698 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
3699 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
3702 if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
3704 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT) {
3706 * We want to skip the LOOP_CACHING_WAIT step if we
3707 * don't have any uncached bgs and we've already done a
3708 * full search through.
3710 if (ffe_ctl->orig_have_caching_bg || !full_search)
3711 ffe_ctl->loop = LOOP_CACHING_WAIT;
3713 ffe_ctl->loop = LOOP_ALLOC_CHUNK;
3718 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
3719 struct btrfs_trans_handle *trans;
3722 trans = current->journal_info;
3726 trans = btrfs_join_transaction(root);
3728 if (IS_ERR(trans)) {
3729 ret = PTR_ERR(trans);
3733 ret = btrfs_chunk_alloc(trans, ffe_ctl->flags,
3737 * If we can't allocate a new chunk we've already looped
3738 * through at least once, move on to the NO_EMPTY_SIZE
3742 ffe_ctl->loop = LOOP_NO_EMPTY_SIZE;
3744 /* Do not bail out on ENOSPC since we can do more. */
3745 if (ret < 0 && ret != -ENOSPC)
3746 btrfs_abort_transaction(trans, ret);
3750 btrfs_end_transaction(trans);
3755 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
3757 * Don't loop again if we already have no empty_size and
3760 if (ffe_ctl->empty_size == 0 &&
3761 ffe_ctl->empty_cluster == 0)
3763 ffe_ctl->empty_size = 0;
3764 ffe_ctl->empty_cluster = 0;
3772 * walks the btree of allocated extents and find a hole of a given size.
3773 * The key ins is changed to record the hole:
3774 * ins->objectid == start position
3775 * ins->flags = BTRFS_EXTENT_ITEM_KEY
3776 * ins->offset == the size of the hole.
3777 * Any available blocks before search_start are skipped.
3779 * If there is no suitable free space, we will record the max size of
3780 * the free space extent currently.
3782 * The overall logic and call chain:
3784 * find_free_extent()
3785 * |- Iterate through all block groups
3786 * | |- Get a valid block group
3787 * | |- Try to do clustered allocation in that block group
3788 * | |- Try to do unclustered allocation in that block group
3789 * | |- Check if the result is valid
3790 * | | |- If valid, then exit
3791 * | |- Jump to next block group
3793 * |- Push harder to find free extents
3794 * |- If not found, re-iterate all block groups
3796 static noinline int find_free_extent(struct btrfs_fs_info *fs_info,
3797 u64 ram_bytes, u64 num_bytes, u64 empty_size,
3798 u64 hint_byte, struct btrfs_key *ins,
3799 u64 flags, int delalloc)
3802 struct btrfs_free_cluster *last_ptr = NULL;
3803 struct btrfs_block_group *block_group = NULL;
3804 struct find_free_extent_ctl ffe_ctl = {0};
3805 struct btrfs_space_info *space_info;
3806 bool use_cluster = true;
3807 bool full_search = false;
3809 WARN_ON(num_bytes < fs_info->sectorsize);
3811 ffe_ctl.ram_bytes = ram_bytes;
3812 ffe_ctl.num_bytes = num_bytes;
3813 ffe_ctl.empty_size = empty_size;
3814 ffe_ctl.flags = flags;
3815 ffe_ctl.search_start = 0;
3816 ffe_ctl.retry_clustered = false;
3817 ffe_ctl.retry_unclustered = false;
3818 ffe_ctl.delalloc = delalloc;
3819 ffe_ctl.index = btrfs_bg_flags_to_raid_index(flags);
3820 ffe_ctl.have_caching_bg = false;
3821 ffe_ctl.orig_have_caching_bg = false;
3822 ffe_ctl.found_offset = 0;
3824 ins->type = BTRFS_EXTENT_ITEM_KEY;
3828 trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
3830 space_info = btrfs_find_space_info(fs_info, flags);
3832 btrfs_err(fs_info, "No space info for %llu", flags);
3837 * If our free space is heavily fragmented we may not be able to make
3838 * big contiguous allocations, so instead of doing the expensive search
3839 * for free space, simply return ENOSPC with our max_extent_size so we
3840 * can go ahead and search for a more manageable chunk.
3842 * If our max_extent_size is large enough for our allocation simply
3843 * disable clustering since we will likely not be able to find enough
3844 * space to create a cluster and induce latency trying.
3846 if (unlikely(space_info->max_extent_size)) {
3847 spin_lock(&space_info->lock);
3848 if (space_info->max_extent_size &&
3849 num_bytes > space_info->max_extent_size) {
3850 ins->offset = space_info->max_extent_size;
3851 spin_unlock(&space_info->lock);
3853 } else if (space_info->max_extent_size) {
3854 use_cluster = false;
3856 spin_unlock(&space_info->lock);
3859 last_ptr = fetch_cluster_info(fs_info, space_info,
3860 &ffe_ctl.empty_cluster);
3862 spin_lock(&last_ptr->lock);
3863 if (last_ptr->block_group)
3864 hint_byte = last_ptr->window_start;
3865 if (last_ptr->fragmented) {
3867 * We still set window_start so we can keep track of the
3868 * last place we found an allocation to try and save
3871 hint_byte = last_ptr->window_start;
3872 use_cluster = false;
3874 spin_unlock(&last_ptr->lock);
3877 ffe_ctl.search_start = max(ffe_ctl.search_start,
3878 first_logical_byte(fs_info, 0));
3879 ffe_ctl.search_start = max(ffe_ctl.search_start, hint_byte);
3880 if (ffe_ctl.search_start == hint_byte) {
3881 block_group = btrfs_lookup_block_group(fs_info,
3882 ffe_ctl.search_start);
3884 * we don't want to use the block group if it doesn't match our
3885 * allocation bits, or if its not cached.
3887 * However if we are re-searching with an ideal block group
3888 * picked out then we don't care that the block group is cached.
3890 if (block_group && block_group_bits(block_group, flags) &&
3891 block_group->cached != BTRFS_CACHE_NO) {
3892 down_read(&space_info->groups_sem);
3893 if (list_empty(&block_group->list) ||
3896 * someone is removing this block group,
3897 * we can't jump into the have_block_group
3898 * target because our list pointers are not
3901 btrfs_put_block_group(block_group);
3902 up_read(&space_info->groups_sem);
3904 ffe_ctl.index = btrfs_bg_flags_to_raid_index(
3905 block_group->flags);
3906 btrfs_lock_block_group(block_group, delalloc);
3907 goto have_block_group;
3909 } else if (block_group) {
3910 btrfs_put_block_group(block_group);
3914 ffe_ctl.have_caching_bg = false;
3915 if (ffe_ctl.index == btrfs_bg_flags_to_raid_index(flags) ||
3918 down_read(&space_info->groups_sem);
3919 list_for_each_entry(block_group,
3920 &space_info->block_groups[ffe_ctl.index], list) {
3921 /* If the block group is read-only, we can skip it entirely. */
3922 if (unlikely(block_group->ro))
3925 btrfs_grab_block_group(block_group, delalloc);
3926 ffe_ctl.search_start = block_group->start;
3929 * this can happen if we end up cycling through all the
3930 * raid types, but we want to make sure we only allocate
3931 * for the proper type.
3933 if (!block_group_bits(block_group, flags)) {
3934 u64 extra = BTRFS_BLOCK_GROUP_DUP |
3935 BTRFS_BLOCK_GROUP_RAID1_MASK |
3936 BTRFS_BLOCK_GROUP_RAID56_MASK |
3937 BTRFS_BLOCK_GROUP_RAID10;
3940 * if they asked for extra copies and this block group
3941 * doesn't provide them, bail. This does allow us to
3942 * fill raid0 from raid1.
3944 if ((flags & extra) && !(block_group->flags & extra))
3948 * This block group has different flags than we want.
3949 * It's possible that we have MIXED_GROUP flag but no
3950 * block group is mixed. Just skip such block group.
3952 btrfs_release_block_group(block_group, delalloc);
3957 ffe_ctl.cached = btrfs_block_group_done(block_group);
3958 if (unlikely(!ffe_ctl.cached)) {
3959 ffe_ctl.have_caching_bg = true;
3960 ret = btrfs_cache_block_group(block_group, 0);
3965 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
3969 * Ok we want to try and use the cluster allocator, so
3972 if (last_ptr && use_cluster) {
3973 struct btrfs_block_group *cluster_bg = NULL;
3975 ret = find_free_extent_clustered(block_group, last_ptr,
3976 &ffe_ctl, &cluster_bg);
3979 if (cluster_bg && cluster_bg != block_group) {
3980 btrfs_release_block_group(block_group,
3982 block_group = cluster_bg;
3985 } else if (ret == -EAGAIN) {
3986 goto have_block_group;
3987 } else if (ret > 0) {
3990 /* ret == -ENOENT case falls through */
3993 ret = find_free_extent_unclustered(block_group, last_ptr,
3996 goto have_block_group;
3999 /* ret == 0 case falls through */
4001 ffe_ctl.search_start = round_up(ffe_ctl.found_offset,
4002 fs_info->stripesize);
4004 /* move on to the next group */
4005 if (ffe_ctl.search_start + num_bytes >
4006 block_group->start + block_group->length) {
4007 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
4012 if (ffe_ctl.found_offset < ffe_ctl.search_start)
4013 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
4014 ffe_ctl.search_start - ffe_ctl.found_offset);
4016 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
4017 num_bytes, delalloc);
4018 if (ret == -EAGAIN) {
4019 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
4023 btrfs_inc_block_group_reservations(block_group);
4025 /* we are all good, lets return */
4026 ins->objectid = ffe_ctl.search_start;
4027 ins->offset = num_bytes;
4029 trace_btrfs_reserve_extent(block_group, ffe_ctl.search_start,
4031 btrfs_release_block_group(block_group, delalloc);
4034 ffe_ctl.retry_clustered = false;
4035 ffe_ctl.retry_unclustered = false;
4036 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
4038 btrfs_release_block_group(block_group, delalloc);
4041 up_read(&space_info->groups_sem);
4043 ret = find_free_extent_update_loop(fs_info, last_ptr, ins, &ffe_ctl,
4044 full_search, use_cluster);
4048 if (ret == -ENOSPC) {
4050 * Use ffe_ctl->total_free_space as fallback if we can't find
4051 * any contiguous hole.
4053 if (!ffe_ctl.max_extent_size)
4054 ffe_ctl.max_extent_size = ffe_ctl.total_free_space;
4055 spin_lock(&space_info->lock);
4056 space_info->max_extent_size = ffe_ctl.max_extent_size;
4057 spin_unlock(&space_info->lock);
4058 ins->offset = ffe_ctl.max_extent_size;
4064 * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
4065 * hole that is at least as big as @num_bytes.
4067 * @root - The root that will contain this extent
4069 * @ram_bytes - The amount of space in ram that @num_bytes take. This
4070 * is used for accounting purposes. This value differs
4071 * from @num_bytes only in the case of compressed extents.
4073 * @num_bytes - Number of bytes to allocate on-disk.
4075 * @min_alloc_size - Indicates the minimum amount of space that the
4076 * allocator should try to satisfy. In some cases
4077 * @num_bytes may be larger than what is required and if
4078 * the filesystem is fragmented then allocation fails.
4079 * However, the presence of @min_alloc_size gives a
4080 * chance to try and satisfy the smaller allocation.
4082 * @empty_size - A hint that you plan on doing more COW. This is the
4083 * size in bytes the allocator should try to find free
4084 * next to the block it returns. This is just a hint and
4085 * may be ignored by the allocator.
4087 * @hint_byte - Hint to the allocator to start searching above the byte
4088 * address passed. It might be ignored.
4090 * @ins - This key is modified to record the found hole. It will
4091 * have the following values:
4092 * ins->objectid == start position
4093 * ins->flags = BTRFS_EXTENT_ITEM_KEY
4094 * ins->offset == the size of the hole.
4096 * @is_data - Boolean flag indicating whether an extent is
4097 * allocated for data (true) or metadata (false)
4099 * @delalloc - Boolean flag indicating whether this allocation is for
4100 * delalloc or not. If 'true' data_rwsem of block groups
4101 * is going to be acquired.
4104 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
4105 * case -ENOSPC is returned then @ins->offset will contain the size of the
4106 * largest available hole the allocator managed to find.
4108 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
4109 u64 num_bytes, u64 min_alloc_size,
4110 u64 empty_size, u64 hint_byte,
4111 struct btrfs_key *ins, int is_data, int delalloc)
4113 struct btrfs_fs_info *fs_info = root->fs_info;
4114 bool final_tried = num_bytes == min_alloc_size;
4118 flags = get_alloc_profile_by_root(root, is_data);
4120 WARN_ON(num_bytes < fs_info->sectorsize);
4121 ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
4122 hint_byte, ins, flags, delalloc);
4123 if (!ret && !is_data) {
4124 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
4125 } else if (ret == -ENOSPC) {
4126 if (!final_tried && ins->offset) {
4127 num_bytes = min(num_bytes >> 1, ins->offset);
4128 num_bytes = round_down(num_bytes,
4129 fs_info->sectorsize);
4130 num_bytes = max(num_bytes, min_alloc_size);
4131 ram_bytes = num_bytes;
4132 if (num_bytes == min_alloc_size)
4135 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4136 struct btrfs_space_info *sinfo;
4138 sinfo = btrfs_find_space_info(fs_info, flags);
4140 "allocation failed flags %llu, wanted %llu",
4143 btrfs_dump_space_info(fs_info, sinfo,
4151 static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
4153 int pin, int delalloc)
4155 struct btrfs_block_group *cache;
4158 cache = btrfs_lookup_block_group(fs_info, start);
4160 btrfs_err(fs_info, "Unable to find block group for %llu",
4166 pin_down_extent(cache, start, len, 1);
4168 if (btrfs_test_opt(fs_info, DISCARD))
4169 ret = btrfs_discard_extent(fs_info, start, len, NULL);
4170 btrfs_add_free_space(cache, start, len);
4171 btrfs_free_reserved_bytes(cache, len, delalloc);
4172 trace_btrfs_reserved_extent_free(fs_info, start, len);
4175 btrfs_put_block_group(cache);
4179 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
4180 u64 start, u64 len, int delalloc)
4182 return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
4185 int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
4188 return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
4191 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4192 u64 parent, u64 root_objectid,
4193 u64 flags, u64 owner, u64 offset,
4194 struct btrfs_key *ins, int ref_mod)
4196 struct btrfs_fs_info *fs_info = trans->fs_info;
4198 struct btrfs_extent_item *extent_item;
4199 struct btrfs_extent_inline_ref *iref;
4200 struct btrfs_path *path;
4201 struct extent_buffer *leaf;
4206 type = BTRFS_SHARED_DATA_REF_KEY;
4208 type = BTRFS_EXTENT_DATA_REF_KEY;
4210 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
4212 path = btrfs_alloc_path();
4216 path->leave_spinning = 1;
4217 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4220 btrfs_free_path(path);
4224 leaf = path->nodes[0];
4225 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4226 struct btrfs_extent_item);
4227 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
4228 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4229 btrfs_set_extent_flags(leaf, extent_item,
4230 flags | BTRFS_EXTENT_FLAG_DATA);
4232 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4233 btrfs_set_extent_inline_ref_type(leaf, iref, type);
4235 struct btrfs_shared_data_ref *ref;
4236 ref = (struct btrfs_shared_data_ref *)(iref + 1);
4237 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
4238 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
4240 struct btrfs_extent_data_ref *ref;
4241 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
4242 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
4243 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
4244 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
4245 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
4248 btrfs_mark_buffer_dirty(path->nodes[0]);
4249 btrfs_free_path(path);
4251 ret = remove_from_free_space_tree(trans, ins->objectid, ins->offset);
4255 ret = btrfs_update_block_group(trans, ins->objectid, ins->offset, 1);
4256 if (ret) { /* -ENOENT, logic error */
4257 btrfs_err(fs_info, "update block group failed for %llu %llu",
4258 ins->objectid, ins->offset);
4261 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
4265 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
4266 struct btrfs_delayed_ref_node *node,
4267 struct btrfs_delayed_extent_op *extent_op)
4269 struct btrfs_fs_info *fs_info = trans->fs_info;
4271 struct btrfs_extent_item *extent_item;
4272 struct btrfs_key extent_key;
4273 struct btrfs_tree_block_info *block_info;
4274 struct btrfs_extent_inline_ref *iref;
4275 struct btrfs_path *path;
4276 struct extent_buffer *leaf;
4277 struct btrfs_delayed_tree_ref *ref;
4278 u32 size = sizeof(*extent_item) + sizeof(*iref);
4280 u64 flags = extent_op->flags_to_set;
4281 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4283 ref = btrfs_delayed_node_to_tree_ref(node);
4285 extent_key.objectid = node->bytenr;
4286 if (skinny_metadata) {
4287 extent_key.offset = ref->level;
4288 extent_key.type = BTRFS_METADATA_ITEM_KEY;
4289 num_bytes = fs_info->nodesize;
4291 extent_key.offset = node->num_bytes;
4292 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
4293 size += sizeof(*block_info);
4294 num_bytes = node->num_bytes;
4297 path = btrfs_alloc_path();
4301 path->leave_spinning = 1;
4302 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4305 btrfs_free_path(path);
4309 leaf = path->nodes[0];
4310 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4311 struct btrfs_extent_item);
4312 btrfs_set_extent_refs(leaf, extent_item, 1);
4313 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4314 btrfs_set_extent_flags(leaf, extent_item,
4315 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
4317 if (skinny_metadata) {
4318 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4320 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
4321 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
4322 btrfs_set_tree_block_level(leaf, block_info, ref->level);
4323 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
4326 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
4327 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
4328 btrfs_set_extent_inline_ref_type(leaf, iref,
4329 BTRFS_SHARED_BLOCK_REF_KEY);
4330 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
4332 btrfs_set_extent_inline_ref_type(leaf, iref,
4333 BTRFS_TREE_BLOCK_REF_KEY);
4334 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
4337 btrfs_mark_buffer_dirty(leaf);
4338 btrfs_free_path(path);
4340 ret = remove_from_free_space_tree(trans, extent_key.objectid,
4345 ret = btrfs_update_block_group(trans, extent_key.objectid,
4346 fs_info->nodesize, 1);
4347 if (ret) { /* -ENOENT, logic error */
4348 btrfs_err(fs_info, "update block group failed for %llu %llu",
4349 extent_key.objectid, extent_key.offset);
4353 trace_btrfs_reserved_extent_alloc(fs_info, extent_key.objectid,
4358 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4359 struct btrfs_root *root, u64 owner,
4360 u64 offset, u64 ram_bytes,
4361 struct btrfs_key *ins)
4363 struct btrfs_ref generic_ref = { 0 };
4366 BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
4368 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4369 ins->objectid, ins->offset, 0);
4370 btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner, offset);
4371 btrfs_ref_tree_mod(root->fs_info, &generic_ref);
4372 ret = btrfs_add_delayed_data_ref(trans, &generic_ref,
4373 ram_bytes, NULL, NULL);
4378 * this is used by the tree logging recovery code. It records that
4379 * an extent has been allocated and makes sure to clear the free
4380 * space cache bits as well
4382 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
4383 u64 root_objectid, u64 owner, u64 offset,
4384 struct btrfs_key *ins)
4386 struct btrfs_fs_info *fs_info = trans->fs_info;
4388 struct btrfs_block_group *block_group;
4389 struct btrfs_space_info *space_info;
4392 * Mixed block groups will exclude before processing the log so we only
4393 * need to do the exclude dance if this fs isn't mixed.
4395 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
4396 ret = __exclude_logged_extent(fs_info, ins->objectid,
4402 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
4406 space_info = block_group->space_info;
4407 spin_lock(&space_info->lock);
4408 spin_lock(&block_group->lock);
4409 space_info->bytes_reserved += ins->offset;
4410 block_group->reserved += ins->offset;
4411 spin_unlock(&block_group->lock);
4412 spin_unlock(&space_info->lock);
4414 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
4416 btrfs_put_block_group(block_group);
4420 static struct extent_buffer *
4421 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4422 u64 bytenr, int level, u64 owner)
4424 struct btrfs_fs_info *fs_info = root->fs_info;
4425 struct extent_buffer *buf;
4427 buf = btrfs_find_create_tree_block(fs_info, bytenr);
4432 * Extra safety check in case the extent tree is corrupted and extent
4433 * allocator chooses to use a tree block which is already used and
4436 if (buf->lock_owner == current->pid) {
4437 btrfs_err_rl(fs_info,
4438 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
4439 buf->start, btrfs_header_owner(buf), current->pid);
4440 free_extent_buffer(buf);
4441 return ERR_PTR(-EUCLEAN);
4444 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
4445 btrfs_tree_lock(buf);
4446 btrfs_clean_tree_block(buf);
4447 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
4449 btrfs_set_lock_blocking_write(buf);
4450 set_extent_buffer_uptodate(buf);
4452 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
4453 btrfs_set_header_level(buf, level);
4454 btrfs_set_header_bytenr(buf, buf->start);
4455 btrfs_set_header_generation(buf, trans->transid);
4456 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
4457 btrfs_set_header_owner(buf, owner);
4458 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
4459 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
4460 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
4461 buf->log_index = root->log_transid % 2;
4463 * we allow two log transactions at a time, use different
4464 * EXTENT bit to differentiate dirty pages.
4466 if (buf->log_index == 0)
4467 set_extent_dirty(&root->dirty_log_pages, buf->start,
4468 buf->start + buf->len - 1, GFP_NOFS);
4470 set_extent_new(&root->dirty_log_pages, buf->start,
4471 buf->start + buf->len - 1);
4473 buf->log_index = -1;
4474 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
4475 buf->start + buf->len - 1, GFP_NOFS);
4477 trans->dirty = true;
4478 /* this returns a buffer locked for blocking */
4483 * finds a free extent and does all the dirty work required for allocation
4484 * returns the tree buffer or an ERR_PTR on error.
4486 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
4487 struct btrfs_root *root,
4488 u64 parent, u64 root_objectid,
4489 const struct btrfs_disk_key *key,
4490 int level, u64 hint,
4493 struct btrfs_fs_info *fs_info = root->fs_info;
4494 struct btrfs_key ins;
4495 struct btrfs_block_rsv *block_rsv;
4496 struct extent_buffer *buf;
4497 struct btrfs_delayed_extent_op *extent_op;
4498 struct btrfs_ref generic_ref = { 0 };
4501 u32 blocksize = fs_info->nodesize;
4502 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4504 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4505 if (btrfs_is_testing(fs_info)) {
4506 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
4507 level, root_objectid);
4509 root->alloc_bytenr += blocksize;
4514 block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
4515 if (IS_ERR(block_rsv))
4516 return ERR_CAST(block_rsv);
4518 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
4519 empty_size, hint, &ins, 0, 0);
4523 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
4527 goto out_free_reserved;
4530 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
4532 parent = ins.objectid;
4533 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4537 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
4538 extent_op = btrfs_alloc_delayed_extent_op();
4544 memcpy(&extent_op->key, key, sizeof(extent_op->key));
4546 memset(&extent_op->key, 0, sizeof(extent_op->key));
4547 extent_op->flags_to_set = flags;
4548 extent_op->update_key = skinny_metadata ? false : true;
4549 extent_op->update_flags = true;
4550 extent_op->is_data = false;
4551 extent_op->level = level;
4553 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4554 ins.objectid, ins.offset, parent);
4555 generic_ref.real_root = root->root_key.objectid;
4556 btrfs_init_tree_ref(&generic_ref, level, root_objectid);
4557 btrfs_ref_tree_mod(fs_info, &generic_ref);
4558 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref,
4559 extent_op, NULL, NULL);
4561 goto out_free_delayed;
4566 btrfs_free_delayed_extent_op(extent_op);
4568 free_extent_buffer(buf);
4570 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
4572 btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
4573 return ERR_PTR(ret);
4576 struct walk_control {
4577 u64 refs[BTRFS_MAX_LEVEL];
4578 u64 flags[BTRFS_MAX_LEVEL];
4579 struct btrfs_key update_progress;
4580 struct btrfs_key drop_progress;
4592 #define DROP_REFERENCE 1
4593 #define UPDATE_BACKREF 2
4595 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
4596 struct btrfs_root *root,
4597 struct walk_control *wc,
4598 struct btrfs_path *path)
4600 struct btrfs_fs_info *fs_info = root->fs_info;
4606 struct btrfs_key key;
4607 struct extent_buffer *eb;
4612 if (path->slots[wc->level] < wc->reada_slot) {
4613 wc->reada_count = wc->reada_count * 2 / 3;
4614 wc->reada_count = max(wc->reada_count, 2);
4616 wc->reada_count = wc->reada_count * 3 / 2;
4617 wc->reada_count = min_t(int, wc->reada_count,
4618 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
4621 eb = path->nodes[wc->level];
4622 nritems = btrfs_header_nritems(eb);
4624 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
4625 if (nread >= wc->reada_count)
4629 bytenr = btrfs_node_blockptr(eb, slot);
4630 generation = btrfs_node_ptr_generation(eb, slot);
4632 if (slot == path->slots[wc->level])
4635 if (wc->stage == UPDATE_BACKREF &&
4636 generation <= root->root_key.offset)
4639 /* We don't lock the tree block, it's OK to be racy here */
4640 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
4641 wc->level - 1, 1, &refs,
4643 /* We don't care about errors in readahead. */
4648 if (wc->stage == DROP_REFERENCE) {
4652 if (wc->level == 1 &&
4653 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4655 if (!wc->update_ref ||
4656 generation <= root->root_key.offset)
4658 btrfs_node_key_to_cpu(eb, &key, slot);
4659 ret = btrfs_comp_cpu_keys(&key,
4660 &wc->update_progress);
4664 if (wc->level == 1 &&
4665 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4669 readahead_tree_block(fs_info, bytenr);
4672 wc->reada_slot = slot;
4676 * helper to process tree block while walking down the tree.
4678 * when wc->stage == UPDATE_BACKREF, this function updates
4679 * back refs for pointers in the block.
4681 * NOTE: return value 1 means we should stop walking down.
4683 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
4684 struct btrfs_root *root,
4685 struct btrfs_path *path,
4686 struct walk_control *wc, int lookup_info)
4688 struct btrfs_fs_info *fs_info = root->fs_info;
4689 int level = wc->level;
4690 struct extent_buffer *eb = path->nodes[level];
4691 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
4694 if (wc->stage == UPDATE_BACKREF &&
4695 btrfs_header_owner(eb) != root->root_key.objectid)
4699 * when reference count of tree block is 1, it won't increase
4700 * again. once full backref flag is set, we never clear it.
4703 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
4704 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
4705 BUG_ON(!path->locks[level]);
4706 ret = btrfs_lookup_extent_info(trans, fs_info,
4707 eb->start, level, 1,
4710 BUG_ON(ret == -ENOMEM);
4713 BUG_ON(wc->refs[level] == 0);
4716 if (wc->stage == DROP_REFERENCE) {
4717 if (wc->refs[level] > 1)
4720 if (path->locks[level] && !wc->keep_locks) {
4721 btrfs_tree_unlock_rw(eb, path->locks[level]);
4722 path->locks[level] = 0;
4727 /* wc->stage == UPDATE_BACKREF */
4728 if (!(wc->flags[level] & flag)) {
4729 BUG_ON(!path->locks[level]);
4730 ret = btrfs_inc_ref(trans, root, eb, 1);
4731 BUG_ON(ret); /* -ENOMEM */
4732 ret = btrfs_dec_ref(trans, root, eb, 0);
4733 BUG_ON(ret); /* -ENOMEM */
4734 ret = btrfs_set_disk_extent_flags(trans, eb->start,
4736 btrfs_header_level(eb), 0);
4737 BUG_ON(ret); /* -ENOMEM */
4738 wc->flags[level] |= flag;
4742 * the block is shared by multiple trees, so it's not good to
4743 * keep the tree lock
4745 if (path->locks[level] && level > 0) {
4746 btrfs_tree_unlock_rw(eb, path->locks[level]);
4747 path->locks[level] = 0;
4753 * This is used to verify a ref exists for this root to deal with a bug where we
4754 * would have a drop_progress key that hadn't been updated properly.
4756 static int check_ref_exists(struct btrfs_trans_handle *trans,
4757 struct btrfs_root *root, u64 bytenr, u64 parent,
4760 struct btrfs_path *path;
4761 struct btrfs_extent_inline_ref *iref;
4764 path = btrfs_alloc_path();
4768 ret = lookup_extent_backref(trans, path, &iref, bytenr,
4769 root->fs_info->nodesize, parent,
4770 root->root_key.objectid, level, 0);
4771 btrfs_free_path(path);
4780 * helper to process tree block pointer.
4782 * when wc->stage == DROP_REFERENCE, this function checks
4783 * reference count of the block pointed to. if the block
4784 * is shared and we need update back refs for the subtree
4785 * rooted at the block, this function changes wc->stage to
4786 * UPDATE_BACKREF. if the block is shared and there is no
4787 * need to update back, this function drops the reference
4790 * NOTE: return value 1 means we should stop walking down.
4792 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
4793 struct btrfs_root *root,
4794 struct btrfs_path *path,
4795 struct walk_control *wc, int *lookup_info)
4797 struct btrfs_fs_info *fs_info = root->fs_info;
4801 struct btrfs_key key;
4802 struct btrfs_key first_key;
4803 struct btrfs_ref ref = { 0 };
4804 struct extent_buffer *next;
4805 int level = wc->level;
4808 bool need_account = false;
4810 generation = btrfs_node_ptr_generation(path->nodes[level],
4811 path->slots[level]);
4813 * if the lower level block was created before the snapshot
4814 * was created, we know there is no need to update back refs
4817 if (wc->stage == UPDATE_BACKREF &&
4818 generation <= root->root_key.offset) {
4823 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
4824 btrfs_node_key_to_cpu(path->nodes[level], &first_key,
4825 path->slots[level]);
4827 next = find_extent_buffer(fs_info, bytenr);
4829 next = btrfs_find_create_tree_block(fs_info, bytenr);
4831 return PTR_ERR(next);
4833 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
4837 btrfs_tree_lock(next);
4838 btrfs_set_lock_blocking_write(next);
4840 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
4841 &wc->refs[level - 1],
4842 &wc->flags[level - 1]);
4846 if (unlikely(wc->refs[level - 1] == 0)) {
4847 btrfs_err(fs_info, "Missing references.");
4853 if (wc->stage == DROP_REFERENCE) {
4854 if (wc->refs[level - 1] > 1) {
4855 need_account = true;
4857 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4860 if (!wc->update_ref ||
4861 generation <= root->root_key.offset)
4864 btrfs_node_key_to_cpu(path->nodes[level], &key,
4865 path->slots[level]);
4866 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
4870 wc->stage = UPDATE_BACKREF;
4871 wc->shared_level = level - 1;
4875 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4879 if (!btrfs_buffer_uptodate(next, generation, 0)) {
4880 btrfs_tree_unlock(next);
4881 free_extent_buffer(next);
4887 if (reada && level == 1)
4888 reada_walk_down(trans, root, wc, path);
4889 next = read_tree_block(fs_info, bytenr, generation, level - 1,
4892 return PTR_ERR(next);
4893 } else if (!extent_buffer_uptodate(next)) {
4894 free_extent_buffer(next);
4897 btrfs_tree_lock(next);
4898 btrfs_set_lock_blocking_write(next);
4902 ASSERT(level == btrfs_header_level(next));
4903 if (level != btrfs_header_level(next)) {
4904 btrfs_err(root->fs_info, "mismatched level");
4908 path->nodes[level] = next;
4909 path->slots[level] = 0;
4910 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
4916 wc->refs[level - 1] = 0;
4917 wc->flags[level - 1] = 0;
4918 if (wc->stage == DROP_REFERENCE) {
4919 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
4920 parent = path->nodes[level]->start;
4922 ASSERT(root->root_key.objectid ==
4923 btrfs_header_owner(path->nodes[level]));
4924 if (root->root_key.objectid !=
4925 btrfs_header_owner(path->nodes[level])) {
4926 btrfs_err(root->fs_info,
4927 "mismatched block owner");
4935 * If we had a drop_progress we need to verify the refs are set
4936 * as expected. If we find our ref then we know that from here
4937 * on out everything should be correct, and we can clear the
4940 if (wc->restarted) {
4941 ret = check_ref_exists(trans, root, bytenr, parent,
4952 * Reloc tree doesn't contribute to qgroup numbers, and we have
4953 * already accounted them at merge time (replace_path),
4954 * thus we could skip expensive subtree trace here.
4956 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
4958 ret = btrfs_qgroup_trace_subtree(trans, next,
4959 generation, level - 1);
4961 btrfs_err_rl(fs_info,
4962 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
4968 * We need to update the next key in our walk control so we can
4969 * update the drop_progress key accordingly. We don't care if
4970 * find_next_key doesn't find a key because that means we're at
4971 * the end and are going to clean up now.
4973 wc->drop_level = level;
4974 find_next_key(path, level, &wc->drop_progress);
4976 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
4977 fs_info->nodesize, parent);
4978 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid);
4979 ret = btrfs_free_extent(trans, &ref);
4988 btrfs_tree_unlock(next);
4989 free_extent_buffer(next);
4995 * helper to process tree block while walking up the tree.
4997 * when wc->stage == DROP_REFERENCE, this function drops
4998 * reference count on the block.
5000 * when wc->stage == UPDATE_BACKREF, this function changes
5001 * wc->stage back to DROP_REFERENCE if we changed wc->stage
5002 * to UPDATE_BACKREF previously while processing the block.
5004 * NOTE: return value 1 means we should stop walking up.
5006 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
5007 struct btrfs_root *root,
5008 struct btrfs_path *path,
5009 struct walk_control *wc)
5011 struct btrfs_fs_info *fs_info = root->fs_info;
5013 int level = wc->level;
5014 struct extent_buffer *eb = path->nodes[level];
5017 if (wc->stage == UPDATE_BACKREF) {
5018 BUG_ON(wc->shared_level < level);
5019 if (level < wc->shared_level)
5022 ret = find_next_key(path, level + 1, &wc->update_progress);
5026 wc->stage = DROP_REFERENCE;
5027 wc->shared_level = -1;
5028 path->slots[level] = 0;
5031 * check reference count again if the block isn't locked.
5032 * we should start walking down the tree again if reference
5035 if (!path->locks[level]) {
5037 btrfs_tree_lock(eb);
5038 btrfs_set_lock_blocking_write(eb);
5039 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5041 ret = btrfs_lookup_extent_info(trans, fs_info,
5042 eb->start, level, 1,
5046 btrfs_tree_unlock_rw(eb, path->locks[level]);
5047 path->locks[level] = 0;
5050 BUG_ON(wc->refs[level] == 0);
5051 if (wc->refs[level] == 1) {
5052 btrfs_tree_unlock_rw(eb, path->locks[level]);
5053 path->locks[level] = 0;
5059 /* wc->stage == DROP_REFERENCE */
5060 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5062 if (wc->refs[level] == 1) {
5064 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5065 ret = btrfs_dec_ref(trans, root, eb, 1);
5067 ret = btrfs_dec_ref(trans, root, eb, 0);
5068 BUG_ON(ret); /* -ENOMEM */
5069 if (is_fstree(root->root_key.objectid)) {
5070 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
5072 btrfs_err_rl(fs_info,
5073 "error %d accounting leaf items, quota is out of sync, rescan required",
5078 /* make block locked assertion in btrfs_clean_tree_block happy */
5079 if (!path->locks[level] &&
5080 btrfs_header_generation(eb) == trans->transid) {
5081 btrfs_tree_lock(eb);
5082 btrfs_set_lock_blocking_write(eb);
5083 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5085 btrfs_clean_tree_block(eb);
5088 if (eb == root->node) {
5089 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5091 else if (root->root_key.objectid != btrfs_header_owner(eb))
5092 goto owner_mismatch;
5094 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5095 parent = path->nodes[level + 1]->start;
5096 else if (root->root_key.objectid !=
5097 btrfs_header_owner(path->nodes[level + 1]))
5098 goto owner_mismatch;
5101 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
5103 wc->refs[level] = 0;
5104 wc->flags[level] = 0;
5108 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
5109 btrfs_header_owner(eb), root->root_key.objectid);
5113 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
5114 struct btrfs_root *root,
5115 struct btrfs_path *path,
5116 struct walk_control *wc)
5118 int level = wc->level;
5119 int lookup_info = 1;
5122 while (level >= 0) {
5123 ret = walk_down_proc(trans, root, path, wc, lookup_info);
5130 if (path->slots[level] >=
5131 btrfs_header_nritems(path->nodes[level]))
5134 ret = do_walk_down(trans, root, path, wc, &lookup_info);
5136 path->slots[level]++;
5145 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
5146 struct btrfs_root *root,
5147 struct btrfs_path *path,
5148 struct walk_control *wc, int max_level)
5150 int level = wc->level;
5153 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
5154 while (level < max_level && path->nodes[level]) {
5156 if (path->slots[level] + 1 <
5157 btrfs_header_nritems(path->nodes[level])) {
5158 path->slots[level]++;
5161 ret = walk_up_proc(trans, root, path, wc);
5167 if (path->locks[level]) {
5168 btrfs_tree_unlock_rw(path->nodes[level],
5169 path->locks[level]);
5170 path->locks[level] = 0;
5172 free_extent_buffer(path->nodes[level]);
5173 path->nodes[level] = NULL;
5181 * drop a subvolume tree.
5183 * this function traverses the tree freeing any blocks that only
5184 * referenced by the tree.
5186 * when a shared tree block is found. this function decreases its
5187 * reference count by one. if update_ref is true, this function
5188 * also make sure backrefs for the shared block and all lower level
5189 * blocks are properly updated.
5191 * If called with for_reloc == 0, may exit early with -EAGAIN
5193 int btrfs_drop_snapshot(struct btrfs_root *root,
5194 struct btrfs_block_rsv *block_rsv, int update_ref,
5197 struct btrfs_fs_info *fs_info = root->fs_info;
5198 struct btrfs_path *path;
5199 struct btrfs_trans_handle *trans;
5200 struct btrfs_root *tree_root = fs_info->tree_root;
5201 struct btrfs_root_item *root_item = &root->root_item;
5202 struct walk_control *wc;
5203 struct btrfs_key key;
5207 bool root_dropped = false;
5209 btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
5211 path = btrfs_alloc_path();
5217 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5219 btrfs_free_path(path);
5224 trans = btrfs_start_transaction(tree_root, 0);
5225 if (IS_ERR(trans)) {
5226 err = PTR_ERR(trans);
5230 err = btrfs_run_delayed_items(trans);
5235 trans->block_rsv = block_rsv;
5238 * This will help us catch people modifying the fs tree while we're
5239 * dropping it. It is unsafe to mess with the fs tree while it's being
5240 * dropped as we unlock the root node and parent nodes as we walk down
5241 * the tree, assuming nothing will change. If something does change
5242 * then we'll have stale information and drop references to blocks we've
5245 set_bit(BTRFS_ROOT_DELETING, &root->state);
5246 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
5247 level = btrfs_header_level(root->node);
5248 path->nodes[level] = btrfs_lock_root_node(root);
5249 btrfs_set_lock_blocking_write(path->nodes[level]);
5250 path->slots[level] = 0;
5251 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5252 memset(&wc->update_progress, 0,
5253 sizeof(wc->update_progress));
5255 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
5256 memcpy(&wc->update_progress, &key,
5257 sizeof(wc->update_progress));
5259 level = root_item->drop_level;
5261 path->lowest_level = level;
5262 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5263 path->lowest_level = 0;
5271 * unlock our path, this is safe because only this
5272 * function is allowed to delete this snapshot
5274 btrfs_unlock_up_safe(path, 0);
5276 level = btrfs_header_level(root->node);
5278 btrfs_tree_lock(path->nodes[level]);
5279 btrfs_set_lock_blocking_write(path->nodes[level]);
5280 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5282 ret = btrfs_lookup_extent_info(trans, fs_info,
5283 path->nodes[level]->start,
5284 level, 1, &wc->refs[level],
5290 BUG_ON(wc->refs[level] == 0);
5292 if (level == root_item->drop_level)
5295 btrfs_tree_unlock(path->nodes[level]);
5296 path->locks[level] = 0;
5297 WARN_ON(wc->refs[level] != 1);
5302 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
5304 wc->shared_level = -1;
5305 wc->stage = DROP_REFERENCE;
5306 wc->update_ref = update_ref;
5308 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5312 ret = walk_down_tree(trans, root, path, wc);
5318 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
5325 BUG_ON(wc->stage != DROP_REFERENCE);
5329 if (wc->stage == DROP_REFERENCE) {
5330 wc->drop_level = wc->level;
5331 btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
5333 path->slots[wc->drop_level]);
5335 btrfs_cpu_key_to_disk(&root_item->drop_progress,
5336 &wc->drop_progress);
5337 root_item->drop_level = wc->drop_level;
5339 BUG_ON(wc->level == 0);
5340 if (btrfs_should_end_transaction(trans) ||
5341 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
5342 ret = btrfs_update_root(trans, tree_root,
5346 btrfs_abort_transaction(trans, ret);
5351 btrfs_end_transaction_throttle(trans);
5352 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
5353 btrfs_debug(fs_info,
5354 "drop snapshot early exit");
5359 trans = btrfs_start_transaction(tree_root, 0);
5360 if (IS_ERR(trans)) {
5361 err = PTR_ERR(trans);
5365 trans->block_rsv = block_rsv;
5368 btrfs_release_path(path);
5372 ret = btrfs_del_root(trans, &root->root_key);
5374 btrfs_abort_transaction(trans, ret);
5379 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
5380 ret = btrfs_find_root(tree_root, &root->root_key, path,
5383 btrfs_abort_transaction(trans, ret);
5386 } else if (ret > 0) {
5387 /* if we fail to delete the orphan item this time
5388 * around, it'll get picked up the next time.
5390 * The most common failure here is just -ENOENT.
5392 btrfs_del_orphan_item(trans, tree_root,
5393 root->root_key.objectid);
5397 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
5398 btrfs_add_dropped_root(trans, root);
5400 free_extent_buffer(root->node);
5401 free_extent_buffer(root->commit_root);
5402 btrfs_put_fs_root(root);
5404 root_dropped = true;
5406 btrfs_end_transaction_throttle(trans);
5409 btrfs_free_path(path);
5412 * So if we need to stop dropping the snapshot for whatever reason we
5413 * need to make sure to add it back to the dead root list so that we
5414 * keep trying to do the work later. This also cleans up roots if we
5415 * don't have it in the radix (like when we recover after a power fail
5416 * or unmount) so we don't leak memory.
5418 if (!for_reloc && !root_dropped)
5419 btrfs_add_dead_root(root);
5420 if (err && err != -EAGAIN)
5421 btrfs_handle_fs_error(fs_info, err, NULL);
5426 * drop subtree rooted at tree block 'node'.
5428 * NOTE: this function will unlock and release tree block 'node'
5429 * only used by relocation code
5431 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
5432 struct btrfs_root *root,
5433 struct extent_buffer *node,
5434 struct extent_buffer *parent)
5436 struct btrfs_fs_info *fs_info = root->fs_info;
5437 struct btrfs_path *path;
5438 struct walk_control *wc;
5444 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
5446 path = btrfs_alloc_path();
5450 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5452 btrfs_free_path(path);
5456 btrfs_assert_tree_locked(parent);
5457 parent_level = btrfs_header_level(parent);
5458 atomic_inc(&parent->refs);
5459 path->nodes[parent_level] = parent;
5460 path->slots[parent_level] = btrfs_header_nritems(parent);
5462 btrfs_assert_tree_locked(node);
5463 level = btrfs_header_level(node);
5464 path->nodes[level] = node;
5465 path->slots[level] = 0;
5466 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5468 wc->refs[parent_level] = 1;
5469 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5471 wc->shared_level = -1;
5472 wc->stage = DROP_REFERENCE;
5475 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5478 wret = walk_down_tree(trans, root, path, wc);
5484 wret = walk_up_tree(trans, root, path, wc, parent_level);
5492 btrfs_free_path(path);
5497 * helper to account the unused space of all the readonly block group in the
5498 * space_info. takes mirrors into account.
5500 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
5502 struct btrfs_block_group *block_group;
5506 /* It's df, we don't care if it's racy */
5507 if (list_empty(&sinfo->ro_bgs))
5510 spin_lock(&sinfo->lock);
5511 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
5512 spin_lock(&block_group->lock);
5514 if (!block_group->ro) {
5515 spin_unlock(&block_group->lock);
5519 factor = btrfs_bg_type_to_factor(block_group->flags);
5520 free_bytes += (block_group->length -
5521 block_group->used) * factor;
5523 spin_unlock(&block_group->lock);
5525 spin_unlock(&sinfo->lock);
5530 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
5533 return unpin_extent_range(fs_info, start, end, false);
5537 * It used to be that old block groups would be left around forever.
5538 * Iterating over them would be enough to trim unused space. Since we
5539 * now automatically remove them, we also need to iterate over unallocated
5542 * We don't want a transaction for this since the discard may take a
5543 * substantial amount of time. We don't require that a transaction be
5544 * running, but we do need to take a running transaction into account
5545 * to ensure that we're not discarding chunks that were released or
5546 * allocated in the current transaction.
5548 * Holding the chunks lock will prevent other threads from allocating
5549 * or releasing chunks, but it won't prevent a running transaction
5550 * from committing and releasing the memory that the pending chunks
5551 * list head uses. For that, we need to take a reference to the
5552 * transaction and hold the commit root sem. We only need to hold
5553 * it while performing the free space search since we have already
5554 * held back allocations.
5556 static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
5558 u64 start = SZ_1M, len = 0, end = 0;
5563 /* Discard not supported = nothing to do. */
5564 if (!blk_queue_discard(bdev_get_queue(device->bdev)))
5567 /* Not writable = nothing to do. */
5568 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
5571 /* No free space = nothing to do. */
5572 if (device->total_bytes <= device->bytes_used)
5578 struct btrfs_fs_info *fs_info = device->fs_info;
5581 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
5585 find_first_clear_extent_bit(&device->alloc_state, start,
5587 CHUNK_TRIMMED | CHUNK_ALLOCATED);
5589 /* Ensure we skip the reserved area in the first 1M */
5590 start = max_t(u64, start, SZ_1M);
5593 * If find_first_clear_extent_bit find a range that spans the
5594 * end of the device it will set end to -1, in this case it's up
5595 * to the caller to trim the value to the size of the device.
5597 end = min(end, device->total_bytes - 1);
5599 len = end - start + 1;
5601 /* We didn't find any extents */
5603 mutex_unlock(&fs_info->chunk_mutex);
5608 ret = btrfs_issue_discard(device->bdev, start, len,
5611 set_extent_bits(&device->alloc_state, start,
5614 mutex_unlock(&fs_info->chunk_mutex);
5622 if (fatal_signal_pending(current)) {
5634 * Trim the whole filesystem by:
5635 * 1) trimming the free space in each block group
5636 * 2) trimming the unallocated space on each device
5638 * This will also continue trimming even if a block group or device encounters
5639 * an error. The return value will be the last error, or 0 if nothing bad
5642 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
5644 struct btrfs_block_group *cache = NULL;
5645 struct btrfs_device *device;
5646 struct list_head *devices;
5648 u64 range_end = U64_MAX;
5659 * Check range overflow if range->len is set.
5660 * The default range->len is U64_MAX.
5662 if (range->len != U64_MAX &&
5663 check_add_overflow(range->start, range->len, &range_end))
5666 cache = btrfs_lookup_first_block_group(fs_info, range->start);
5667 for (; cache; cache = btrfs_next_block_group(cache)) {
5668 if (cache->start >= range_end) {
5669 btrfs_put_block_group(cache);
5673 start = max(range->start, cache->start);
5674 end = min(range_end, cache->start + cache->length);
5676 if (end - start >= range->minlen) {
5677 if (!btrfs_block_group_done(cache)) {
5678 ret = btrfs_cache_block_group(cache, 0);
5684 ret = btrfs_wait_block_group_cache_done(cache);
5691 ret = btrfs_trim_block_group(cache,
5697 trimmed += group_trimmed;
5708 "failed to trim %llu block group(s), last error %d",
5710 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5711 devices = &fs_info->fs_devices->devices;
5712 list_for_each_entry(device, devices, dev_list) {
5713 ret = btrfs_trim_free_extents(device, &group_trimmed);
5720 trimmed += group_trimmed;
5722 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5726 "failed to trim %llu device(s), last error %d",
5727 dev_failed, dev_ret);
5728 range->len = trimmed;
5735 * btrfs_{start,end}_write_no_snapshotting() are similar to
5736 * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
5737 * data into the page cache through nocow before the subvolume is snapshoted,
5738 * but flush the data into disk after the snapshot creation, or to prevent
5739 * operations while snapshotting is ongoing and that cause the snapshot to be
5740 * inconsistent (writes followed by expanding truncates for example).
5742 void btrfs_end_write_no_snapshotting(struct btrfs_root *root)
5744 percpu_counter_dec(&root->subv_writers->counter);
5745 cond_wake_up(&root->subv_writers->wait);
5748 int btrfs_start_write_no_snapshotting(struct btrfs_root *root)
5750 if (atomic_read(&root->will_be_snapshotted))
5753 percpu_counter_inc(&root->subv_writers->counter);
5755 * Make sure counter is updated before we check for snapshot creation.
5758 if (atomic_read(&root->will_be_snapshotted)) {
5759 btrfs_end_write_no_snapshotting(root);
5765 void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
5770 ret = btrfs_start_write_no_snapshotting(root);
5773 wait_var_event(&root->will_be_snapshotted,
5774 !atomic_read(&root->will_be_snapshotted));