1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/sched/signal.h>
8 #include <linux/pagemap.h>
9 #include <linux/writeback.h>
10 #include <linux/blkdev.h>
11 #include <linux/sort.h>
12 #include <linux/rcupdate.h>
13 #include <linux/kthread.h>
14 #include <linux/slab.h>
15 #include <linux/ratelimit.h>
16 #include <linux/percpu_counter.h>
17 #include <linux/lockdep.h>
18 #include <linux/crc32c.h>
22 #include "print-tree.h"
26 #include "free-space-cache.h"
27 #include "free-space-tree.h"
30 #include "ref-verify.h"
31 #include "space-info.h"
32 #include "block-rsv.h"
33 #include "delalloc-space.h"
34 #include "block-group.h"
36 #include "rcu-string.h"
38 #include "dev-replace.h"
40 #undef SCRAMBLE_DELAYED_REFS
43 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
44 struct btrfs_delayed_ref_node *node, u64 parent,
45 u64 root_objectid, u64 owner_objectid,
46 u64 owner_offset, int refs_to_drop,
47 struct btrfs_delayed_extent_op *extra_op);
48 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
49 struct extent_buffer *leaf,
50 struct btrfs_extent_item *ei);
51 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
52 u64 parent, u64 root_objectid,
53 u64 flags, u64 owner, u64 offset,
54 struct btrfs_key *ins, int ref_mod);
55 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
56 struct btrfs_delayed_ref_node *node,
57 struct btrfs_delayed_extent_op *extent_op);
58 static int find_next_key(struct btrfs_path *path, int level,
59 struct btrfs_key *key);
61 static int block_group_bits(struct btrfs_block_group *cache, u64 bits)
63 return (cache->flags & bits) == bits;
66 int btrfs_add_excluded_extent(struct btrfs_fs_info *fs_info,
67 u64 start, u64 num_bytes)
69 u64 end = start + num_bytes - 1;
70 set_extent_bits(&fs_info->excluded_extents, start, end,
75 void btrfs_free_excluded_extents(struct btrfs_block_group *cache)
77 struct btrfs_fs_info *fs_info = cache->fs_info;
81 end = start + cache->length - 1;
83 clear_extent_bits(&fs_info->excluded_extents, start, end,
87 /* simple helper to search for an existing data extent at a given offset */
88 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
90 struct btrfs_root *root = btrfs_extent_root(fs_info, start);
93 struct btrfs_path *path;
95 path = btrfs_alloc_path();
101 key.type = BTRFS_EXTENT_ITEM_KEY;
102 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
103 btrfs_free_path(path);
108 * helper function to lookup reference count and flags of a tree block.
110 * the head node for delayed ref is used to store the sum of all the
111 * reference count modifications queued up in the rbtree. the head
112 * node may also store the extent flags to set. This way you can check
113 * to see what the reference count and extent flags would be if all of
114 * the delayed refs are not processed.
116 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
117 struct btrfs_fs_info *fs_info, u64 bytenr,
118 u64 offset, int metadata, u64 *refs, u64 *flags)
120 struct btrfs_root *extent_root;
121 struct btrfs_delayed_ref_head *head;
122 struct btrfs_delayed_ref_root *delayed_refs;
123 struct btrfs_path *path;
124 struct btrfs_extent_item *ei;
125 struct extent_buffer *leaf;
126 struct btrfs_key key;
133 * If we don't have skinny metadata, don't bother doing anything
136 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
137 offset = fs_info->nodesize;
141 path = btrfs_alloc_path();
146 path->skip_locking = 1;
147 path->search_commit_root = 1;
151 key.objectid = bytenr;
154 key.type = BTRFS_METADATA_ITEM_KEY;
156 key.type = BTRFS_EXTENT_ITEM_KEY;
158 extent_root = btrfs_extent_root(fs_info, bytenr);
159 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
163 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
164 if (path->slots[0]) {
166 btrfs_item_key_to_cpu(path->nodes[0], &key,
168 if (key.objectid == bytenr &&
169 key.type == BTRFS_EXTENT_ITEM_KEY &&
170 key.offset == fs_info->nodesize)
176 leaf = path->nodes[0];
177 item_size = btrfs_item_size(leaf, path->slots[0]);
178 if (item_size >= sizeof(*ei)) {
179 ei = btrfs_item_ptr(leaf, path->slots[0],
180 struct btrfs_extent_item);
181 num_refs = btrfs_extent_refs(leaf, ei);
182 extent_flags = btrfs_extent_flags(leaf, ei);
185 btrfs_print_v0_err(fs_info);
187 btrfs_abort_transaction(trans, ret);
189 btrfs_handle_fs_error(fs_info, ret, NULL);
194 BUG_ON(num_refs == 0);
204 delayed_refs = &trans->transaction->delayed_refs;
205 spin_lock(&delayed_refs->lock);
206 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
208 if (!mutex_trylock(&head->mutex)) {
209 refcount_inc(&head->refs);
210 spin_unlock(&delayed_refs->lock);
212 btrfs_release_path(path);
215 * Mutex was contended, block until it's released and try
218 mutex_lock(&head->mutex);
219 mutex_unlock(&head->mutex);
220 btrfs_put_delayed_ref_head(head);
223 spin_lock(&head->lock);
224 if (head->extent_op && head->extent_op->update_flags)
225 extent_flags |= head->extent_op->flags_to_set;
227 BUG_ON(num_refs == 0);
229 num_refs += head->ref_mod;
230 spin_unlock(&head->lock);
231 mutex_unlock(&head->mutex);
233 spin_unlock(&delayed_refs->lock);
235 WARN_ON(num_refs == 0);
239 *flags = extent_flags;
241 btrfs_free_path(path);
246 * Back reference rules. Back refs have three main goals:
248 * 1) differentiate between all holders of references to an extent so that
249 * when a reference is dropped we can make sure it was a valid reference
250 * before freeing the extent.
252 * 2) Provide enough information to quickly find the holders of an extent
253 * if we notice a given block is corrupted or bad.
255 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
256 * maintenance. This is actually the same as #2, but with a slightly
257 * different use case.
259 * There are two kinds of back refs. The implicit back refs is optimized
260 * for pointers in non-shared tree blocks. For a given pointer in a block,
261 * back refs of this kind provide information about the block's owner tree
262 * and the pointer's key. These information allow us to find the block by
263 * b-tree searching. The full back refs is for pointers in tree blocks not
264 * referenced by their owner trees. The location of tree block is recorded
265 * in the back refs. Actually the full back refs is generic, and can be
266 * used in all cases the implicit back refs is used. The major shortcoming
267 * of the full back refs is its overhead. Every time a tree block gets
268 * COWed, we have to update back refs entry for all pointers in it.
270 * For a newly allocated tree block, we use implicit back refs for
271 * pointers in it. This means most tree related operations only involve
272 * implicit back refs. For a tree block created in old transaction, the
273 * only way to drop a reference to it is COW it. So we can detect the
274 * event that tree block loses its owner tree's reference and do the
275 * back refs conversion.
277 * When a tree block is COWed through a tree, there are four cases:
279 * The reference count of the block is one and the tree is the block's
280 * owner tree. Nothing to do in this case.
282 * The reference count of the block is one and the tree is not the
283 * block's owner tree. In this case, full back refs is used for pointers
284 * in the block. Remove these full back refs, add implicit back refs for
285 * every pointers in the new block.
287 * The reference count of the block is greater than one and the tree is
288 * the block's owner tree. In this case, implicit back refs is used for
289 * pointers in the block. Add full back refs for every pointers in the
290 * block, increase lower level extents' reference counts. The original
291 * implicit back refs are entailed to the new block.
293 * The reference count of the block is greater than one and the tree is
294 * not the block's owner tree. Add implicit back refs for every pointer in
295 * the new block, increase lower level extents' reference count.
297 * Back Reference Key composing:
299 * The key objectid corresponds to the first byte in the extent,
300 * The key type is used to differentiate between types of back refs.
301 * There are different meanings of the key offset for different types
304 * File extents can be referenced by:
306 * - multiple snapshots, subvolumes, or different generations in one subvol
307 * - different files inside a single subvolume
308 * - different offsets inside a file (bookend extents in file.c)
310 * The extent ref structure for the implicit back refs has fields for:
312 * - Objectid of the subvolume root
313 * - objectid of the file holding the reference
314 * - original offset in the file
315 * - how many bookend extents
317 * The key offset for the implicit back refs is hash of the first
320 * The extent ref structure for the full back refs has field for:
322 * - number of pointers in the tree leaf
324 * The key offset for the implicit back refs is the first byte of
327 * When a file extent is allocated, The implicit back refs is used.
328 * the fields are filled in:
330 * (root_key.objectid, inode objectid, offset in file, 1)
332 * When a file extent is removed file truncation, we find the
333 * corresponding implicit back refs and check the following fields:
335 * (btrfs_header_owner(leaf), inode objectid, offset in file)
337 * Btree extents can be referenced by:
339 * - Different subvolumes
341 * Both the implicit back refs and the full back refs for tree blocks
342 * only consist of key. The key offset for the implicit back refs is
343 * objectid of block's owner tree. The key offset for the full back refs
344 * is the first byte of parent block.
346 * When implicit back refs is used, information about the lowest key and
347 * level of the tree block are required. These information are stored in
348 * tree block info structure.
352 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
353 * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
354 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
356 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
357 struct btrfs_extent_inline_ref *iref,
358 enum btrfs_inline_ref_type is_data)
360 int type = btrfs_extent_inline_ref_type(eb, iref);
361 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
363 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
364 type == BTRFS_SHARED_BLOCK_REF_KEY ||
365 type == BTRFS_SHARED_DATA_REF_KEY ||
366 type == BTRFS_EXTENT_DATA_REF_KEY) {
367 if (is_data == BTRFS_REF_TYPE_BLOCK) {
368 if (type == BTRFS_TREE_BLOCK_REF_KEY)
370 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
373 * Every shared one has parent tree block,
374 * which must be aligned to sector size.
377 IS_ALIGNED(offset, eb->fs_info->sectorsize))
380 } else if (is_data == BTRFS_REF_TYPE_DATA) {
381 if (type == BTRFS_EXTENT_DATA_REF_KEY)
383 if (type == BTRFS_SHARED_DATA_REF_KEY) {
386 * Every shared one has parent tree block,
387 * which must be aligned to sector size.
390 IS_ALIGNED(offset, eb->fs_info->sectorsize))
394 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
399 btrfs_print_leaf((struct extent_buffer *)eb);
400 btrfs_err(eb->fs_info,
401 "eb %llu iref 0x%lx invalid extent inline ref type %d",
402 eb->start, (unsigned long)iref, type);
405 return BTRFS_REF_TYPE_INVALID;
408 u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
410 u32 high_crc = ~(u32)0;
411 u32 low_crc = ~(u32)0;
414 lenum = cpu_to_le64(root_objectid);
415 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
416 lenum = cpu_to_le64(owner);
417 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
418 lenum = cpu_to_le64(offset);
419 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
421 return ((u64)high_crc << 31) ^ (u64)low_crc;
424 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
425 struct btrfs_extent_data_ref *ref)
427 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
428 btrfs_extent_data_ref_objectid(leaf, ref),
429 btrfs_extent_data_ref_offset(leaf, ref));
432 static int match_extent_data_ref(struct extent_buffer *leaf,
433 struct btrfs_extent_data_ref *ref,
434 u64 root_objectid, u64 owner, u64 offset)
436 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
437 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
438 btrfs_extent_data_ref_offset(leaf, ref) != offset)
443 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
444 struct btrfs_path *path,
445 u64 bytenr, u64 parent,
447 u64 owner, u64 offset)
449 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
450 struct btrfs_key key;
451 struct btrfs_extent_data_ref *ref;
452 struct extent_buffer *leaf;
458 key.objectid = bytenr;
460 key.type = BTRFS_SHARED_DATA_REF_KEY;
463 key.type = BTRFS_EXTENT_DATA_REF_KEY;
464 key.offset = hash_extent_data_ref(root_objectid,
469 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
481 leaf = path->nodes[0];
482 nritems = btrfs_header_nritems(leaf);
484 if (path->slots[0] >= nritems) {
485 ret = btrfs_next_leaf(root, path);
491 leaf = path->nodes[0];
492 nritems = btrfs_header_nritems(leaf);
496 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
497 if (key.objectid != bytenr ||
498 key.type != BTRFS_EXTENT_DATA_REF_KEY)
501 ref = btrfs_item_ptr(leaf, path->slots[0],
502 struct btrfs_extent_data_ref);
504 if (match_extent_data_ref(leaf, ref, root_objectid,
507 btrfs_release_path(path);
519 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
520 struct btrfs_path *path,
521 u64 bytenr, u64 parent,
522 u64 root_objectid, u64 owner,
523 u64 offset, int refs_to_add)
525 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
526 struct btrfs_key key;
527 struct extent_buffer *leaf;
532 key.objectid = bytenr;
534 key.type = BTRFS_SHARED_DATA_REF_KEY;
536 size = sizeof(struct btrfs_shared_data_ref);
538 key.type = BTRFS_EXTENT_DATA_REF_KEY;
539 key.offset = hash_extent_data_ref(root_objectid,
541 size = sizeof(struct btrfs_extent_data_ref);
544 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
545 if (ret && ret != -EEXIST)
548 leaf = path->nodes[0];
550 struct btrfs_shared_data_ref *ref;
551 ref = btrfs_item_ptr(leaf, path->slots[0],
552 struct btrfs_shared_data_ref);
554 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
556 num_refs = btrfs_shared_data_ref_count(leaf, ref);
557 num_refs += refs_to_add;
558 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
561 struct btrfs_extent_data_ref *ref;
562 while (ret == -EEXIST) {
563 ref = btrfs_item_ptr(leaf, path->slots[0],
564 struct btrfs_extent_data_ref);
565 if (match_extent_data_ref(leaf, ref, root_objectid,
568 btrfs_release_path(path);
570 ret = btrfs_insert_empty_item(trans, root, path, &key,
572 if (ret && ret != -EEXIST)
575 leaf = path->nodes[0];
577 ref = btrfs_item_ptr(leaf, path->slots[0],
578 struct btrfs_extent_data_ref);
580 btrfs_set_extent_data_ref_root(leaf, ref,
582 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
583 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
584 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
586 num_refs = btrfs_extent_data_ref_count(leaf, ref);
587 num_refs += refs_to_add;
588 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
591 btrfs_mark_buffer_dirty(leaf);
594 btrfs_release_path(path);
598 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
599 struct btrfs_root *root,
600 struct btrfs_path *path,
603 struct btrfs_key key;
604 struct btrfs_extent_data_ref *ref1 = NULL;
605 struct btrfs_shared_data_ref *ref2 = NULL;
606 struct extent_buffer *leaf;
610 leaf = path->nodes[0];
611 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
613 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
614 ref1 = btrfs_item_ptr(leaf, path->slots[0],
615 struct btrfs_extent_data_ref);
616 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
617 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
618 ref2 = btrfs_item_ptr(leaf, path->slots[0],
619 struct btrfs_shared_data_ref);
620 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
621 } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
622 btrfs_print_v0_err(trans->fs_info);
623 btrfs_abort_transaction(trans, -EINVAL);
629 BUG_ON(num_refs < refs_to_drop);
630 num_refs -= refs_to_drop;
633 ret = btrfs_del_item(trans, root, path);
635 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
636 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
637 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
638 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
639 btrfs_mark_buffer_dirty(leaf);
644 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
645 struct btrfs_extent_inline_ref *iref)
647 struct btrfs_key key;
648 struct extent_buffer *leaf;
649 struct btrfs_extent_data_ref *ref1;
650 struct btrfs_shared_data_ref *ref2;
654 leaf = path->nodes[0];
655 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
657 BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
660 * If type is invalid, we should have bailed out earlier than
663 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
664 ASSERT(type != BTRFS_REF_TYPE_INVALID);
665 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
666 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
667 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
669 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
670 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
672 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
673 ref1 = btrfs_item_ptr(leaf, path->slots[0],
674 struct btrfs_extent_data_ref);
675 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
676 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
677 ref2 = btrfs_item_ptr(leaf, path->slots[0],
678 struct btrfs_shared_data_ref);
679 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
686 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
687 struct btrfs_path *path,
688 u64 bytenr, u64 parent,
691 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
692 struct btrfs_key key;
695 key.objectid = bytenr;
697 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
700 key.type = BTRFS_TREE_BLOCK_REF_KEY;
701 key.offset = root_objectid;
704 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
710 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
711 struct btrfs_path *path,
712 u64 bytenr, u64 parent,
715 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
716 struct btrfs_key key;
719 key.objectid = bytenr;
721 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
724 key.type = BTRFS_TREE_BLOCK_REF_KEY;
725 key.offset = root_objectid;
728 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
729 btrfs_release_path(path);
733 static inline int extent_ref_type(u64 parent, u64 owner)
736 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
738 type = BTRFS_SHARED_BLOCK_REF_KEY;
740 type = BTRFS_TREE_BLOCK_REF_KEY;
743 type = BTRFS_SHARED_DATA_REF_KEY;
745 type = BTRFS_EXTENT_DATA_REF_KEY;
750 static int find_next_key(struct btrfs_path *path, int level,
751 struct btrfs_key *key)
754 for (; level < BTRFS_MAX_LEVEL; level++) {
755 if (!path->nodes[level])
757 if (path->slots[level] + 1 >=
758 btrfs_header_nritems(path->nodes[level]))
761 btrfs_item_key_to_cpu(path->nodes[level], key,
762 path->slots[level] + 1);
764 btrfs_node_key_to_cpu(path->nodes[level], key,
765 path->slots[level] + 1);
772 * look for inline back ref. if back ref is found, *ref_ret is set
773 * to the address of inline back ref, and 0 is returned.
775 * if back ref isn't found, *ref_ret is set to the address where it
776 * should be inserted, and -ENOENT is returned.
778 * if insert is true and there are too many inline back refs, the path
779 * points to the extent item, and -EAGAIN is returned.
781 * NOTE: inline back refs are ordered in the same way that back ref
782 * items in the tree are ordered.
784 static noinline_for_stack
785 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
786 struct btrfs_path *path,
787 struct btrfs_extent_inline_ref **ref_ret,
788 u64 bytenr, u64 num_bytes,
789 u64 parent, u64 root_objectid,
790 u64 owner, u64 offset, int insert)
792 struct btrfs_fs_info *fs_info = trans->fs_info;
793 struct btrfs_root *root = btrfs_extent_root(fs_info, bytenr);
794 struct btrfs_key key;
795 struct extent_buffer *leaf;
796 struct btrfs_extent_item *ei;
797 struct btrfs_extent_inline_ref *iref;
807 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
810 key.objectid = bytenr;
811 key.type = BTRFS_EXTENT_ITEM_KEY;
812 key.offset = num_bytes;
814 want = extent_ref_type(parent, owner);
816 extra_size = btrfs_extent_inline_ref_size(want);
817 path->search_for_extension = 1;
818 path->keep_locks = 1;
823 * Owner is our level, so we can just add one to get the level for the
824 * block we are interested in.
826 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
827 key.type = BTRFS_METADATA_ITEM_KEY;
832 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
839 * We may be a newly converted file system which still has the old fat
840 * extent entries for metadata, so try and see if we have one of those.
842 if (ret > 0 && skinny_metadata) {
843 skinny_metadata = false;
844 if (path->slots[0]) {
846 btrfs_item_key_to_cpu(path->nodes[0], &key,
848 if (key.objectid == bytenr &&
849 key.type == BTRFS_EXTENT_ITEM_KEY &&
850 key.offset == num_bytes)
854 key.objectid = bytenr;
855 key.type = BTRFS_EXTENT_ITEM_KEY;
856 key.offset = num_bytes;
857 btrfs_release_path(path);
862 if (ret && !insert) {
865 } else if (WARN_ON(ret)) {
870 leaf = path->nodes[0];
871 item_size = btrfs_item_size(leaf, path->slots[0]);
872 if (unlikely(item_size < sizeof(*ei))) {
874 btrfs_print_v0_err(fs_info);
875 btrfs_abort_transaction(trans, err);
879 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
880 flags = btrfs_extent_flags(leaf, ei);
882 ptr = (unsigned long)(ei + 1);
883 end = (unsigned long)ei + item_size;
885 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
886 ptr += sizeof(struct btrfs_tree_block_info);
890 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
891 needed = BTRFS_REF_TYPE_DATA;
893 needed = BTRFS_REF_TYPE_BLOCK;
900 btrfs_print_leaf(path->nodes[0]);
902 "overrun extent record at slot %d while looking for inline extent for root %llu owner %llu offset %llu parent %llu",
903 path->slots[0], root_objectid, owner, offset, parent);
907 iref = (struct btrfs_extent_inline_ref *)ptr;
908 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
909 if (type == BTRFS_REF_TYPE_INVALID) {
917 ptr += btrfs_extent_inline_ref_size(type);
921 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
922 struct btrfs_extent_data_ref *dref;
923 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
924 if (match_extent_data_ref(leaf, dref, root_objectid,
929 if (hash_extent_data_ref_item(leaf, dref) <
930 hash_extent_data_ref(root_objectid, owner, offset))
934 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
936 if (parent == ref_offset) {
940 if (ref_offset < parent)
943 if (root_objectid == ref_offset) {
947 if (ref_offset < root_objectid)
951 ptr += btrfs_extent_inline_ref_size(type);
953 if (err == -ENOENT && insert) {
954 if (item_size + extra_size >=
955 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
960 * To add new inline back ref, we have to make sure
961 * there is no corresponding back ref item.
962 * For simplicity, we just do not add new inline back
963 * ref if there is any kind of item for this block
965 if (find_next_key(path, 0, &key) == 0 &&
966 key.objectid == bytenr &&
967 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
972 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
975 path->keep_locks = 0;
976 path->search_for_extension = 0;
977 btrfs_unlock_up_safe(path, 1);
983 * helper to add new inline back ref
985 static noinline_for_stack
986 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
987 struct btrfs_path *path,
988 struct btrfs_extent_inline_ref *iref,
989 u64 parent, u64 root_objectid,
990 u64 owner, u64 offset, int refs_to_add,
991 struct btrfs_delayed_extent_op *extent_op)
993 struct extent_buffer *leaf;
994 struct btrfs_extent_item *ei;
997 unsigned long item_offset;
1002 leaf = path->nodes[0];
1003 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1004 item_offset = (unsigned long)iref - (unsigned long)ei;
1006 type = extent_ref_type(parent, owner);
1007 size = btrfs_extent_inline_ref_size(type);
1009 btrfs_extend_item(path, size);
1011 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1012 refs = btrfs_extent_refs(leaf, ei);
1013 refs += refs_to_add;
1014 btrfs_set_extent_refs(leaf, ei, refs);
1016 __run_delayed_extent_op(extent_op, leaf, ei);
1018 ptr = (unsigned long)ei + item_offset;
1019 end = (unsigned long)ei + btrfs_item_size(leaf, path->slots[0]);
1020 if (ptr < end - size)
1021 memmove_extent_buffer(leaf, ptr + size, ptr,
1024 iref = (struct btrfs_extent_inline_ref *)ptr;
1025 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1026 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1027 struct btrfs_extent_data_ref *dref;
1028 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1029 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1030 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1031 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1032 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1033 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1034 struct btrfs_shared_data_ref *sref;
1035 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1036 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1037 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1038 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1039 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1041 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1043 btrfs_mark_buffer_dirty(leaf);
1046 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1047 struct btrfs_path *path,
1048 struct btrfs_extent_inline_ref **ref_ret,
1049 u64 bytenr, u64 num_bytes, u64 parent,
1050 u64 root_objectid, u64 owner, u64 offset)
1054 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1055 num_bytes, parent, root_objectid,
1060 btrfs_release_path(path);
1063 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1064 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1067 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1068 root_objectid, owner, offset);
1074 * helper to update/remove inline back ref
1076 static noinline_for_stack
1077 void update_inline_extent_backref(struct btrfs_path *path,
1078 struct btrfs_extent_inline_ref *iref,
1080 struct btrfs_delayed_extent_op *extent_op)
1082 struct extent_buffer *leaf = path->nodes[0];
1083 struct btrfs_extent_item *ei;
1084 struct btrfs_extent_data_ref *dref = NULL;
1085 struct btrfs_shared_data_ref *sref = NULL;
1093 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1094 refs = btrfs_extent_refs(leaf, ei);
1095 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1096 refs += refs_to_mod;
1097 btrfs_set_extent_refs(leaf, ei, refs);
1099 __run_delayed_extent_op(extent_op, leaf, ei);
1102 * If type is invalid, we should have bailed out after
1103 * lookup_inline_extent_backref().
1105 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1106 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1108 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1109 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1110 refs = btrfs_extent_data_ref_count(leaf, dref);
1111 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1112 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1113 refs = btrfs_shared_data_ref_count(leaf, sref);
1116 BUG_ON(refs_to_mod != -1);
1119 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1120 refs += refs_to_mod;
1123 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1124 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1126 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1128 size = btrfs_extent_inline_ref_size(type);
1129 item_size = btrfs_item_size(leaf, path->slots[0]);
1130 ptr = (unsigned long)iref;
1131 end = (unsigned long)ei + item_size;
1132 if (ptr + size < end)
1133 memmove_extent_buffer(leaf, ptr, ptr + size,
1136 btrfs_truncate_item(path, item_size, 1);
1138 btrfs_mark_buffer_dirty(leaf);
1141 static noinline_for_stack
1142 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1143 struct btrfs_path *path,
1144 u64 bytenr, u64 num_bytes, u64 parent,
1145 u64 root_objectid, u64 owner,
1146 u64 offset, int refs_to_add,
1147 struct btrfs_delayed_extent_op *extent_op)
1149 struct btrfs_extent_inline_ref *iref;
1152 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1153 num_bytes, parent, root_objectid,
1157 * We're adding refs to a tree block we already own, this
1158 * should not happen at all.
1160 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1161 btrfs_crit(trans->fs_info,
1162 "adding refs to an existing tree ref, bytenr %llu num_bytes %llu root_objectid %llu",
1163 bytenr, num_bytes, root_objectid);
1164 if (IS_ENABLED(CONFIG_BTRFS_DEBUG)) {
1166 btrfs_crit(trans->fs_info,
1167 "path->slots[0]=%d path->nodes[0]:", path->slots[0]);
1168 btrfs_print_leaf(path->nodes[0]);
1172 update_inline_extent_backref(path, iref, refs_to_add, extent_op);
1173 } else if (ret == -ENOENT) {
1174 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1175 root_objectid, owner, offset,
1176 refs_to_add, extent_op);
1182 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1183 struct btrfs_root *root,
1184 struct btrfs_path *path,
1185 struct btrfs_extent_inline_ref *iref,
1186 int refs_to_drop, int is_data)
1190 BUG_ON(!is_data && refs_to_drop != 1);
1192 update_inline_extent_backref(path, iref, -refs_to_drop, NULL);
1194 ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
1196 ret = btrfs_del_item(trans, root, path);
1200 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1201 u64 *discarded_bytes)
1204 u64 bytes_left, end;
1205 u64 aligned_start = ALIGN(start, 1 << 9);
1207 if (WARN_ON(start != aligned_start)) {
1208 len -= aligned_start - start;
1209 len = round_down(len, 1 << 9);
1210 start = aligned_start;
1213 *discarded_bytes = 0;
1221 /* Skip any superblocks on this device. */
1222 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1223 u64 sb_start = btrfs_sb_offset(j);
1224 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1225 u64 size = sb_start - start;
1227 if (!in_range(sb_start, start, bytes_left) &&
1228 !in_range(sb_end, start, bytes_left) &&
1229 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1233 * Superblock spans beginning of range. Adjust start and
1236 if (sb_start <= start) {
1237 start += sb_end - start;
1242 bytes_left = end - start;
1247 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1250 *discarded_bytes += size;
1251 else if (ret != -EOPNOTSUPP)
1260 bytes_left = end - start;
1264 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1267 *discarded_bytes += bytes_left;
1272 static int do_discard_extent(struct btrfs_discard_stripe *stripe, u64 *bytes)
1274 struct btrfs_device *dev = stripe->dev;
1275 struct btrfs_fs_info *fs_info = dev->fs_info;
1276 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1277 u64 phys = stripe->physical;
1278 u64 len = stripe->length;
1282 /* Zone reset on a zoned filesystem */
1283 if (btrfs_can_zone_reset(dev, phys, len)) {
1286 ret = btrfs_reset_device_zone(dev, phys, len, &discarded);
1290 if (!btrfs_dev_replace_is_ongoing(dev_replace) ||
1291 dev != dev_replace->srcdev)
1294 src_disc = discarded;
1296 /* Send to replace target as well */
1297 ret = btrfs_reset_device_zone(dev_replace->tgtdev, phys, len,
1299 discarded += src_disc;
1300 } else if (bdev_max_discard_sectors(stripe->dev->bdev)) {
1301 ret = btrfs_issue_discard(dev->bdev, phys, len, &discarded);
1312 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1313 u64 num_bytes, u64 *actual_bytes)
1316 u64 discarded_bytes = 0;
1317 u64 end = bytenr + num_bytes;
1321 * Avoid races with device replace and make sure the devices in the
1322 * stripes don't go away while we are discarding.
1324 btrfs_bio_counter_inc_blocked(fs_info);
1326 struct btrfs_discard_stripe *stripes;
1327 unsigned int num_stripes;
1330 num_bytes = end - cur;
1331 stripes = btrfs_map_discard(fs_info, cur, &num_bytes, &num_stripes);
1332 if (IS_ERR(stripes)) {
1333 ret = PTR_ERR(stripes);
1334 if (ret == -EOPNOTSUPP)
1339 for (i = 0; i < num_stripes; i++) {
1340 struct btrfs_discard_stripe *stripe = stripes + i;
1343 if (!stripe->dev->bdev) {
1344 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1348 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
1349 &stripe->dev->dev_state))
1352 ret = do_discard_extent(stripe, &bytes);
1355 * Keep going if discard is not supported by the
1358 if (ret != -EOPNOTSUPP)
1362 discarded_bytes += bytes;
1370 btrfs_bio_counter_dec(fs_info);
1372 *actual_bytes = discarded_bytes;
1376 /* Can return -ENOMEM */
1377 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1378 struct btrfs_ref *generic_ref)
1380 struct btrfs_fs_info *fs_info = trans->fs_info;
1383 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
1384 generic_ref->action);
1385 BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
1386 generic_ref->tree_ref.owning_root == BTRFS_TREE_LOG_OBJECTID);
1388 if (generic_ref->type == BTRFS_REF_METADATA)
1389 ret = btrfs_add_delayed_tree_ref(trans, generic_ref, NULL);
1391 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0);
1393 btrfs_ref_tree_mod(fs_info, generic_ref);
1399 * __btrfs_inc_extent_ref - insert backreference for a given extent
1401 * The counterpart is in __btrfs_free_extent(), with examples and more details
1404 * @trans: Handle of transaction
1406 * @node: The delayed ref node used to get the bytenr/length for
1407 * extent whose references are incremented.
1409 * @parent: If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
1410 * BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
1411 * bytenr of the parent block. Since new extents are always
1412 * created with indirect references, this will only be the case
1413 * when relocating a shared extent. In that case, root_objectid
1414 * will be BTRFS_TREE_RELOC_OBJECTID. Otherwise, parent must
1417 * @root_objectid: The id of the root where this modification has originated,
1418 * this can be either one of the well-known metadata trees or
1419 * the subvolume id which references this extent.
1421 * @owner: For data extents it is the inode number of the owning file.
1422 * For metadata extents this parameter holds the level in the
1423 * tree of the extent.
1425 * @offset: For metadata extents the offset is ignored and is currently
1426 * always passed as 0. For data extents it is the fileoffset
1427 * this extent belongs to.
1429 * @refs_to_add Number of references to add
1431 * @extent_op Pointer to a structure, holding information necessary when
1432 * updating a tree block's flags
1435 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1436 struct btrfs_delayed_ref_node *node,
1437 u64 parent, u64 root_objectid,
1438 u64 owner, u64 offset, int refs_to_add,
1439 struct btrfs_delayed_extent_op *extent_op)
1441 struct btrfs_path *path;
1442 struct extent_buffer *leaf;
1443 struct btrfs_extent_item *item;
1444 struct btrfs_key key;
1445 u64 bytenr = node->bytenr;
1446 u64 num_bytes = node->num_bytes;
1450 path = btrfs_alloc_path();
1454 /* this will setup the path even if it fails to insert the back ref */
1455 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
1456 parent, root_objectid, owner,
1457 offset, refs_to_add, extent_op);
1458 if ((ret < 0 && ret != -EAGAIN) || !ret)
1462 * Ok we had -EAGAIN which means we didn't have space to insert and
1463 * inline extent ref, so just update the reference count and add a
1466 leaf = path->nodes[0];
1467 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1468 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1469 refs = btrfs_extent_refs(leaf, item);
1470 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1472 __run_delayed_extent_op(extent_op, leaf, item);
1474 btrfs_mark_buffer_dirty(leaf);
1475 btrfs_release_path(path);
1477 /* now insert the actual backref */
1478 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1479 BUG_ON(refs_to_add != 1);
1480 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1483 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1484 root_objectid, owner, offset,
1488 btrfs_abort_transaction(trans, ret);
1490 btrfs_free_path(path);
1494 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1495 struct btrfs_delayed_ref_node *node,
1496 struct btrfs_delayed_extent_op *extent_op,
1497 int insert_reserved)
1500 struct btrfs_delayed_data_ref *ref;
1501 struct btrfs_key ins;
1506 ins.objectid = node->bytenr;
1507 ins.offset = node->num_bytes;
1508 ins.type = BTRFS_EXTENT_ITEM_KEY;
1510 ref = btrfs_delayed_node_to_data_ref(node);
1511 trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
1513 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1514 parent = ref->parent;
1515 ref_root = ref->root;
1517 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1519 flags |= extent_op->flags_to_set;
1520 ret = alloc_reserved_file_extent(trans, parent, ref_root,
1521 flags, ref->objectid,
1524 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1525 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
1526 ref->objectid, ref->offset,
1527 node->ref_mod, extent_op);
1528 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1529 ret = __btrfs_free_extent(trans, node, parent,
1530 ref_root, ref->objectid,
1531 ref->offset, node->ref_mod,
1539 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1540 struct extent_buffer *leaf,
1541 struct btrfs_extent_item *ei)
1543 u64 flags = btrfs_extent_flags(leaf, ei);
1544 if (extent_op->update_flags) {
1545 flags |= extent_op->flags_to_set;
1546 btrfs_set_extent_flags(leaf, ei, flags);
1549 if (extent_op->update_key) {
1550 struct btrfs_tree_block_info *bi;
1551 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1552 bi = (struct btrfs_tree_block_info *)(ei + 1);
1553 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1557 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1558 struct btrfs_delayed_ref_head *head,
1559 struct btrfs_delayed_extent_op *extent_op)
1561 struct btrfs_fs_info *fs_info = trans->fs_info;
1562 struct btrfs_root *root;
1563 struct btrfs_key key;
1564 struct btrfs_path *path;
1565 struct btrfs_extent_item *ei;
1566 struct extent_buffer *leaf;
1572 if (TRANS_ABORTED(trans))
1575 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1578 path = btrfs_alloc_path();
1582 key.objectid = head->bytenr;
1585 key.type = BTRFS_METADATA_ITEM_KEY;
1586 key.offset = extent_op->level;
1588 key.type = BTRFS_EXTENT_ITEM_KEY;
1589 key.offset = head->num_bytes;
1592 root = btrfs_extent_root(fs_info, key.objectid);
1594 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1601 if (path->slots[0] > 0) {
1603 btrfs_item_key_to_cpu(path->nodes[0], &key,
1605 if (key.objectid == head->bytenr &&
1606 key.type == BTRFS_EXTENT_ITEM_KEY &&
1607 key.offset == head->num_bytes)
1611 btrfs_release_path(path);
1614 key.objectid = head->bytenr;
1615 key.offset = head->num_bytes;
1616 key.type = BTRFS_EXTENT_ITEM_KEY;
1625 leaf = path->nodes[0];
1626 item_size = btrfs_item_size(leaf, path->slots[0]);
1628 if (unlikely(item_size < sizeof(*ei))) {
1630 btrfs_print_v0_err(fs_info);
1631 btrfs_abort_transaction(trans, err);
1635 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1636 __run_delayed_extent_op(extent_op, leaf, ei);
1638 btrfs_mark_buffer_dirty(leaf);
1640 btrfs_free_path(path);
1644 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
1645 struct btrfs_delayed_ref_node *node,
1646 struct btrfs_delayed_extent_op *extent_op,
1647 int insert_reserved)
1650 struct btrfs_delayed_tree_ref *ref;
1654 ref = btrfs_delayed_node_to_tree_ref(node);
1655 trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
1657 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1658 parent = ref->parent;
1659 ref_root = ref->root;
1661 if (node->ref_mod != 1) {
1662 btrfs_err(trans->fs_info,
1663 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
1664 node->bytenr, node->ref_mod, node->action, ref_root,
1668 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1669 BUG_ON(!extent_op || !extent_op->update_flags);
1670 ret = alloc_reserved_tree_block(trans, node, extent_op);
1671 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1672 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
1673 ref->level, 0, 1, extent_op);
1674 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1675 ret = __btrfs_free_extent(trans, node, parent, ref_root,
1676 ref->level, 0, 1, extent_op);
1683 /* helper function to actually process a single delayed ref entry */
1684 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
1685 struct btrfs_delayed_ref_node *node,
1686 struct btrfs_delayed_extent_op *extent_op,
1687 int insert_reserved)
1691 if (TRANS_ABORTED(trans)) {
1692 if (insert_reserved)
1693 btrfs_pin_extent(trans, node->bytenr, node->num_bytes, 1);
1697 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
1698 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1699 ret = run_delayed_tree_ref(trans, node, extent_op,
1701 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
1702 node->type == BTRFS_SHARED_DATA_REF_KEY)
1703 ret = run_delayed_data_ref(trans, node, extent_op,
1707 if (ret && insert_reserved)
1708 btrfs_pin_extent(trans, node->bytenr, node->num_bytes, 1);
1712 static inline struct btrfs_delayed_ref_node *
1713 select_delayed_ref(struct btrfs_delayed_ref_head *head)
1715 struct btrfs_delayed_ref_node *ref;
1717 if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
1721 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
1722 * This is to prevent a ref count from going down to zero, which deletes
1723 * the extent item from the extent tree, when there still are references
1724 * to add, which would fail because they would not find the extent item.
1726 if (!list_empty(&head->ref_add_list))
1727 return list_first_entry(&head->ref_add_list,
1728 struct btrfs_delayed_ref_node, add_list);
1730 ref = rb_entry(rb_first_cached(&head->ref_tree),
1731 struct btrfs_delayed_ref_node, ref_node);
1732 ASSERT(list_empty(&ref->add_list));
1736 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
1737 struct btrfs_delayed_ref_head *head)
1739 spin_lock(&delayed_refs->lock);
1740 head->processing = 0;
1741 delayed_refs->num_heads_ready++;
1742 spin_unlock(&delayed_refs->lock);
1743 btrfs_delayed_ref_unlock(head);
1746 static struct btrfs_delayed_extent_op *cleanup_extent_op(
1747 struct btrfs_delayed_ref_head *head)
1749 struct btrfs_delayed_extent_op *extent_op = head->extent_op;
1754 if (head->must_insert_reserved) {
1755 head->extent_op = NULL;
1756 btrfs_free_delayed_extent_op(extent_op);
1762 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
1763 struct btrfs_delayed_ref_head *head)
1765 struct btrfs_delayed_extent_op *extent_op;
1768 extent_op = cleanup_extent_op(head);
1771 head->extent_op = NULL;
1772 spin_unlock(&head->lock);
1773 ret = run_delayed_extent_op(trans, head, extent_op);
1774 btrfs_free_delayed_extent_op(extent_op);
1775 return ret ? ret : 1;
1778 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
1779 struct btrfs_delayed_ref_root *delayed_refs,
1780 struct btrfs_delayed_ref_head *head)
1782 int nr_items = 1; /* Dropping this ref head update. */
1785 * We had csum deletions accounted for in our delayed refs rsv, we need
1786 * to drop the csum leaves for this update from our delayed_refs_rsv.
1788 if (head->total_ref_mod < 0 && head->is_data) {
1789 spin_lock(&delayed_refs->lock);
1790 delayed_refs->pending_csums -= head->num_bytes;
1791 spin_unlock(&delayed_refs->lock);
1792 nr_items += btrfs_csum_bytes_to_leaves(fs_info, head->num_bytes);
1795 btrfs_delayed_refs_rsv_release(fs_info, nr_items);
1798 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
1799 struct btrfs_delayed_ref_head *head)
1802 struct btrfs_fs_info *fs_info = trans->fs_info;
1803 struct btrfs_delayed_ref_root *delayed_refs;
1806 delayed_refs = &trans->transaction->delayed_refs;
1808 ret = run_and_cleanup_extent_op(trans, head);
1810 unselect_delayed_ref_head(delayed_refs, head);
1811 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
1818 * Need to drop our head ref lock and re-acquire the delayed ref lock
1819 * and then re-check to make sure nobody got added.
1821 spin_unlock(&head->lock);
1822 spin_lock(&delayed_refs->lock);
1823 spin_lock(&head->lock);
1824 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
1825 spin_unlock(&head->lock);
1826 spin_unlock(&delayed_refs->lock);
1829 btrfs_delete_ref_head(delayed_refs, head);
1830 spin_unlock(&head->lock);
1831 spin_unlock(&delayed_refs->lock);
1833 if (head->must_insert_reserved) {
1834 btrfs_pin_extent(trans, head->bytenr, head->num_bytes, 1);
1835 if (head->is_data) {
1836 struct btrfs_root *csum_root;
1838 csum_root = btrfs_csum_root(fs_info, head->bytenr);
1839 ret = btrfs_del_csums(trans, csum_root, head->bytenr,
1844 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
1846 trace_run_delayed_ref_head(fs_info, head, 0);
1847 btrfs_delayed_ref_unlock(head);
1848 btrfs_put_delayed_ref_head(head);
1852 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
1853 struct btrfs_trans_handle *trans)
1855 struct btrfs_delayed_ref_root *delayed_refs =
1856 &trans->transaction->delayed_refs;
1857 struct btrfs_delayed_ref_head *head = NULL;
1860 spin_lock(&delayed_refs->lock);
1861 head = btrfs_select_ref_head(delayed_refs);
1863 spin_unlock(&delayed_refs->lock);
1868 * Grab the lock that says we are going to process all the refs for
1871 ret = btrfs_delayed_ref_lock(delayed_refs, head);
1872 spin_unlock(&delayed_refs->lock);
1875 * We may have dropped the spin lock to get the head mutex lock, and
1876 * that might have given someone else time to free the head. If that's
1877 * true, it has been removed from our list and we can move on.
1880 head = ERR_PTR(-EAGAIN);
1885 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
1886 struct btrfs_delayed_ref_head *locked_ref,
1887 unsigned long *run_refs)
1889 struct btrfs_fs_info *fs_info = trans->fs_info;
1890 struct btrfs_delayed_ref_root *delayed_refs;
1891 struct btrfs_delayed_extent_op *extent_op;
1892 struct btrfs_delayed_ref_node *ref;
1893 int must_insert_reserved = 0;
1896 delayed_refs = &trans->transaction->delayed_refs;
1898 lockdep_assert_held(&locked_ref->mutex);
1899 lockdep_assert_held(&locked_ref->lock);
1901 while ((ref = select_delayed_ref(locked_ref))) {
1903 btrfs_check_delayed_seq(fs_info, ref->seq)) {
1904 spin_unlock(&locked_ref->lock);
1905 unselect_delayed_ref_head(delayed_refs, locked_ref);
1911 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
1912 RB_CLEAR_NODE(&ref->ref_node);
1913 if (!list_empty(&ref->add_list))
1914 list_del(&ref->add_list);
1916 * When we play the delayed ref, also correct the ref_mod on
1919 switch (ref->action) {
1920 case BTRFS_ADD_DELAYED_REF:
1921 case BTRFS_ADD_DELAYED_EXTENT:
1922 locked_ref->ref_mod -= ref->ref_mod;
1924 case BTRFS_DROP_DELAYED_REF:
1925 locked_ref->ref_mod += ref->ref_mod;
1930 atomic_dec(&delayed_refs->num_entries);
1933 * Record the must_insert_reserved flag before we drop the
1936 must_insert_reserved = locked_ref->must_insert_reserved;
1937 locked_ref->must_insert_reserved = 0;
1939 extent_op = locked_ref->extent_op;
1940 locked_ref->extent_op = NULL;
1941 spin_unlock(&locked_ref->lock);
1943 ret = run_one_delayed_ref(trans, ref, extent_op,
1944 must_insert_reserved);
1946 btrfs_free_delayed_extent_op(extent_op);
1948 unselect_delayed_ref_head(delayed_refs, locked_ref);
1949 btrfs_put_delayed_ref(ref);
1950 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
1955 btrfs_put_delayed_ref(ref);
1958 spin_lock(&locked_ref->lock);
1959 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
1966 * Returns 0 on success or if called with an already aborted transaction.
1967 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
1969 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
1972 struct btrfs_fs_info *fs_info = trans->fs_info;
1973 struct btrfs_delayed_ref_root *delayed_refs;
1974 struct btrfs_delayed_ref_head *locked_ref = NULL;
1975 ktime_t start = ktime_get();
1977 unsigned long count = 0;
1978 unsigned long actual_count = 0;
1980 delayed_refs = &trans->transaction->delayed_refs;
1983 locked_ref = btrfs_obtain_ref_head(trans);
1984 if (IS_ERR_OR_NULL(locked_ref)) {
1985 if (PTR_ERR(locked_ref) == -EAGAIN) {
1994 * We need to try and merge add/drops of the same ref since we
1995 * can run into issues with relocate dropping the implicit ref
1996 * and then it being added back again before the drop can
1997 * finish. If we merged anything we need to re-loop so we can
1999 * Or we can get node references of the same type that weren't
2000 * merged when created due to bumps in the tree mod seq, and
2001 * we need to merge them to prevent adding an inline extent
2002 * backref before dropping it (triggering a BUG_ON at
2003 * insert_inline_extent_backref()).
2005 spin_lock(&locked_ref->lock);
2006 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2008 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2010 if (ret < 0 && ret != -EAGAIN) {
2012 * Error, btrfs_run_delayed_refs_for_head already
2013 * unlocked everything so just bail out
2018 * Success, perform the usual cleanup of a processed
2021 ret = cleanup_ref_head(trans, locked_ref);
2023 /* We dropped our lock, we need to loop. */
2032 * Either success case or btrfs_run_delayed_refs_for_head
2033 * returned -EAGAIN, meaning we need to select another head
2038 } while ((nr != -1 && count < nr) || locked_ref);
2041 * We don't want to include ref heads since we can have empty ref heads
2042 * and those will drastically skew our runtime down since we just do
2043 * accounting, no actual extent tree updates.
2045 if (actual_count > 0) {
2046 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2050 * We weigh the current average higher than our current runtime
2051 * to avoid large swings in the average.
2053 spin_lock(&delayed_refs->lock);
2054 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2055 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2056 spin_unlock(&delayed_refs->lock);
2061 #ifdef SCRAMBLE_DELAYED_REFS
2063 * Normally delayed refs get processed in ascending bytenr order. This
2064 * correlates in most cases to the order added. To expose dependencies on this
2065 * order, we start to process the tree in the middle instead of the beginning
2067 static u64 find_middle(struct rb_root *root)
2069 struct rb_node *n = root->rb_node;
2070 struct btrfs_delayed_ref_node *entry;
2073 u64 first = 0, last = 0;
2077 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2078 first = entry->bytenr;
2082 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2083 last = entry->bytenr;
2088 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2089 WARN_ON(!entry->in_tree);
2091 middle = entry->bytenr;
2105 * this starts processing the delayed reference count updates and
2106 * extent insertions we have queued up so far. count can be
2107 * 0, which means to process everything in the tree at the start
2108 * of the run (but not newly added entries), or it can be some target
2109 * number you'd like to process.
2111 * Returns 0 on success or if called with an aborted transaction
2112 * Returns <0 on error and aborts the transaction
2114 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2115 unsigned long count)
2117 struct btrfs_fs_info *fs_info = trans->fs_info;
2118 struct rb_node *node;
2119 struct btrfs_delayed_ref_root *delayed_refs;
2120 struct btrfs_delayed_ref_head *head;
2122 int run_all = count == (unsigned long)-1;
2124 /* We'll clean this up in btrfs_cleanup_transaction */
2125 if (TRANS_ABORTED(trans))
2128 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2131 delayed_refs = &trans->transaction->delayed_refs;
2133 count = delayed_refs->num_heads_ready;
2136 #ifdef SCRAMBLE_DELAYED_REFS
2137 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2139 ret = __btrfs_run_delayed_refs(trans, count);
2141 btrfs_abort_transaction(trans, ret);
2146 btrfs_create_pending_block_groups(trans);
2148 spin_lock(&delayed_refs->lock);
2149 node = rb_first_cached(&delayed_refs->href_root);
2151 spin_unlock(&delayed_refs->lock);
2154 head = rb_entry(node, struct btrfs_delayed_ref_head,
2156 refcount_inc(&head->refs);
2157 spin_unlock(&delayed_refs->lock);
2159 /* Mutex was contended, block until it's released and retry. */
2160 mutex_lock(&head->mutex);
2161 mutex_unlock(&head->mutex);
2163 btrfs_put_delayed_ref_head(head);
2171 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2172 struct extent_buffer *eb, u64 flags,
2175 struct btrfs_delayed_extent_op *extent_op;
2178 extent_op = btrfs_alloc_delayed_extent_op();
2182 extent_op->flags_to_set = flags;
2183 extent_op->update_flags = true;
2184 extent_op->update_key = false;
2185 extent_op->level = level;
2187 ret = btrfs_add_delayed_extent_op(trans, eb->start, eb->len, extent_op);
2189 btrfs_free_delayed_extent_op(extent_op);
2193 static noinline int check_delayed_ref(struct btrfs_root *root,
2194 struct btrfs_path *path,
2195 u64 objectid, u64 offset, u64 bytenr)
2197 struct btrfs_delayed_ref_head *head;
2198 struct btrfs_delayed_ref_node *ref;
2199 struct btrfs_delayed_data_ref *data_ref;
2200 struct btrfs_delayed_ref_root *delayed_refs;
2201 struct btrfs_transaction *cur_trans;
2202 struct rb_node *node;
2205 spin_lock(&root->fs_info->trans_lock);
2206 cur_trans = root->fs_info->running_transaction;
2208 refcount_inc(&cur_trans->use_count);
2209 spin_unlock(&root->fs_info->trans_lock);
2213 delayed_refs = &cur_trans->delayed_refs;
2214 spin_lock(&delayed_refs->lock);
2215 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2217 spin_unlock(&delayed_refs->lock);
2218 btrfs_put_transaction(cur_trans);
2222 if (!mutex_trylock(&head->mutex)) {
2224 spin_unlock(&delayed_refs->lock);
2225 btrfs_put_transaction(cur_trans);
2229 refcount_inc(&head->refs);
2230 spin_unlock(&delayed_refs->lock);
2232 btrfs_release_path(path);
2235 * Mutex was contended, block until it's released and let
2238 mutex_lock(&head->mutex);
2239 mutex_unlock(&head->mutex);
2240 btrfs_put_delayed_ref_head(head);
2241 btrfs_put_transaction(cur_trans);
2244 spin_unlock(&delayed_refs->lock);
2246 spin_lock(&head->lock);
2248 * XXX: We should replace this with a proper search function in the
2251 for (node = rb_first_cached(&head->ref_tree); node;
2252 node = rb_next(node)) {
2253 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
2254 /* If it's a shared ref we know a cross reference exists */
2255 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2260 data_ref = btrfs_delayed_node_to_data_ref(ref);
2263 * If our ref doesn't match the one we're currently looking at
2264 * then we have a cross reference.
2266 if (data_ref->root != root->root_key.objectid ||
2267 data_ref->objectid != objectid ||
2268 data_ref->offset != offset) {
2273 spin_unlock(&head->lock);
2274 mutex_unlock(&head->mutex);
2275 btrfs_put_transaction(cur_trans);
2279 static noinline int check_committed_ref(struct btrfs_root *root,
2280 struct btrfs_path *path,
2281 u64 objectid, u64 offset, u64 bytenr,
2284 struct btrfs_fs_info *fs_info = root->fs_info;
2285 struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
2286 struct extent_buffer *leaf;
2287 struct btrfs_extent_data_ref *ref;
2288 struct btrfs_extent_inline_ref *iref;
2289 struct btrfs_extent_item *ei;
2290 struct btrfs_key key;
2295 key.objectid = bytenr;
2296 key.offset = (u64)-1;
2297 key.type = BTRFS_EXTENT_ITEM_KEY;
2299 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2302 BUG_ON(ret == 0); /* Corruption */
2305 if (path->slots[0] == 0)
2309 leaf = path->nodes[0];
2310 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2312 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2316 item_size = btrfs_item_size(leaf, path->slots[0]);
2317 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2319 /* If extent item has more than 1 inline ref then it's shared */
2320 if (item_size != sizeof(*ei) +
2321 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2325 * If extent created before last snapshot => it's shared unless the
2326 * snapshot has been deleted. Use the heuristic if strict is false.
2329 (btrfs_extent_generation(leaf, ei) <=
2330 btrfs_root_last_snapshot(&root->root_item)))
2333 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2335 /* If this extent has SHARED_DATA_REF then it's shared */
2336 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
2337 if (type != BTRFS_EXTENT_DATA_REF_KEY)
2340 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2341 if (btrfs_extent_refs(leaf, ei) !=
2342 btrfs_extent_data_ref_count(leaf, ref) ||
2343 btrfs_extent_data_ref_root(leaf, ref) !=
2344 root->root_key.objectid ||
2345 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2346 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2354 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
2355 u64 bytenr, bool strict, struct btrfs_path *path)
2360 ret = check_committed_ref(root, path, objectid,
2361 offset, bytenr, strict);
2362 if (ret && ret != -ENOENT)
2365 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
2366 } while (ret == -EAGAIN);
2369 btrfs_release_path(path);
2370 if (btrfs_is_data_reloc_root(root))
2375 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2376 struct btrfs_root *root,
2377 struct extent_buffer *buf,
2378 int full_backref, int inc)
2380 struct btrfs_fs_info *fs_info = root->fs_info;
2386 struct btrfs_key key;
2387 struct btrfs_file_extent_item *fi;
2388 struct btrfs_ref generic_ref = { 0 };
2389 bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
2395 if (btrfs_is_testing(fs_info))
2398 ref_root = btrfs_header_owner(buf);
2399 nritems = btrfs_header_nritems(buf);
2400 level = btrfs_header_level(buf);
2402 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state) && level == 0)
2406 parent = buf->start;
2410 action = BTRFS_ADD_DELAYED_REF;
2412 action = BTRFS_DROP_DELAYED_REF;
2414 for (i = 0; i < nritems; i++) {
2416 btrfs_item_key_to_cpu(buf, &key, i);
2417 if (key.type != BTRFS_EXTENT_DATA_KEY)
2419 fi = btrfs_item_ptr(buf, i,
2420 struct btrfs_file_extent_item);
2421 if (btrfs_file_extent_type(buf, fi) ==
2422 BTRFS_FILE_EXTENT_INLINE)
2424 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2428 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2429 key.offset -= btrfs_file_extent_offset(buf, fi);
2430 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2432 btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
2433 key.offset, root->root_key.objectid,
2436 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2438 ret = btrfs_free_extent(trans, &generic_ref);
2442 bytenr = btrfs_node_blockptr(buf, i);
2443 num_bytes = fs_info->nodesize;
2444 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2446 btrfs_init_tree_ref(&generic_ref, level - 1, ref_root,
2447 root->root_key.objectid, for_reloc);
2449 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2451 ret = btrfs_free_extent(trans, &generic_ref);
2461 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2462 struct extent_buffer *buf, int full_backref)
2464 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
2467 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2468 struct extent_buffer *buf, int full_backref)
2470 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2473 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
2475 struct btrfs_fs_info *fs_info = root->fs_info;
2480 flags = BTRFS_BLOCK_GROUP_DATA;
2481 else if (root == fs_info->chunk_root)
2482 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2484 flags = BTRFS_BLOCK_GROUP_METADATA;
2486 ret = btrfs_get_alloc_profile(fs_info, flags);
2490 static u64 first_logical_byte(struct btrfs_fs_info *fs_info)
2492 struct rb_node *leftmost;
2495 read_lock(&fs_info->block_group_cache_lock);
2496 /* Get the block group with the lowest logical start address. */
2497 leftmost = rb_first_cached(&fs_info->block_group_cache_tree);
2499 struct btrfs_block_group *bg;
2501 bg = rb_entry(leftmost, struct btrfs_block_group, cache_node);
2504 read_unlock(&fs_info->block_group_cache_lock);
2509 static int pin_down_extent(struct btrfs_trans_handle *trans,
2510 struct btrfs_block_group *cache,
2511 u64 bytenr, u64 num_bytes, int reserved)
2513 struct btrfs_fs_info *fs_info = cache->fs_info;
2515 spin_lock(&cache->space_info->lock);
2516 spin_lock(&cache->lock);
2517 cache->pinned += num_bytes;
2518 btrfs_space_info_update_bytes_pinned(fs_info, cache->space_info,
2521 cache->reserved -= num_bytes;
2522 cache->space_info->bytes_reserved -= num_bytes;
2524 spin_unlock(&cache->lock);
2525 spin_unlock(&cache->space_info->lock);
2527 set_extent_dirty(&trans->transaction->pinned_extents, bytenr,
2528 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
2532 int btrfs_pin_extent(struct btrfs_trans_handle *trans,
2533 u64 bytenr, u64 num_bytes, int reserved)
2535 struct btrfs_block_group *cache;
2537 cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
2538 BUG_ON(!cache); /* Logic error */
2540 pin_down_extent(trans, cache, bytenr, num_bytes, reserved);
2542 btrfs_put_block_group(cache);
2547 * this function must be called within transaction
2549 int btrfs_pin_extent_for_log_replay(struct btrfs_trans_handle *trans,
2550 u64 bytenr, u64 num_bytes)
2552 struct btrfs_block_group *cache;
2555 cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
2560 * Fully cache the free space first so that our pin removes the free space
2563 ret = btrfs_cache_block_group(cache, true);
2567 pin_down_extent(trans, cache, bytenr, num_bytes, 0);
2569 /* remove us from the free space cache (if we're there at all) */
2570 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
2572 btrfs_put_block_group(cache);
2576 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
2577 u64 start, u64 num_bytes)
2580 struct btrfs_block_group *block_group;
2582 block_group = btrfs_lookup_block_group(fs_info, start);
2586 ret = btrfs_cache_block_group(block_group, true);
2590 ret = btrfs_remove_free_space(block_group, start, num_bytes);
2592 btrfs_put_block_group(block_group);
2596 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
2598 struct btrfs_fs_info *fs_info = eb->fs_info;
2599 struct btrfs_file_extent_item *item;
2600 struct btrfs_key key;
2605 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
2608 for (i = 0; i < btrfs_header_nritems(eb); i++) {
2609 btrfs_item_key_to_cpu(eb, &key, i);
2610 if (key.type != BTRFS_EXTENT_DATA_KEY)
2612 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
2613 found_type = btrfs_file_extent_type(eb, item);
2614 if (found_type == BTRFS_FILE_EXTENT_INLINE)
2616 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
2618 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
2619 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
2620 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
2629 btrfs_inc_block_group_reservations(struct btrfs_block_group *bg)
2631 atomic_inc(&bg->reservations);
2635 * Returns the free cluster for the given space info and sets empty_cluster to
2636 * what it should be based on the mount options.
2638 static struct btrfs_free_cluster *
2639 fetch_cluster_info(struct btrfs_fs_info *fs_info,
2640 struct btrfs_space_info *space_info, u64 *empty_cluster)
2642 struct btrfs_free_cluster *ret = NULL;
2645 if (btrfs_mixed_space_info(space_info))
2648 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
2649 ret = &fs_info->meta_alloc_cluster;
2650 if (btrfs_test_opt(fs_info, SSD))
2651 *empty_cluster = SZ_2M;
2653 *empty_cluster = SZ_64K;
2654 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
2655 btrfs_test_opt(fs_info, SSD_SPREAD)) {
2656 *empty_cluster = SZ_2M;
2657 ret = &fs_info->data_alloc_cluster;
2663 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
2665 const bool return_free_space)
2667 struct btrfs_block_group *cache = NULL;
2668 struct btrfs_space_info *space_info;
2669 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2670 struct btrfs_free_cluster *cluster = NULL;
2672 u64 total_unpinned = 0;
2673 u64 empty_cluster = 0;
2676 while (start <= end) {
2679 start >= cache->start + cache->length) {
2681 btrfs_put_block_group(cache);
2683 cache = btrfs_lookup_block_group(fs_info, start);
2684 BUG_ON(!cache); /* Logic error */
2686 cluster = fetch_cluster_info(fs_info,
2689 empty_cluster <<= 1;
2692 len = cache->start + cache->length - start;
2693 len = min(len, end + 1 - start);
2695 if (return_free_space)
2696 btrfs_add_free_space(cache, start, len);
2699 total_unpinned += len;
2700 space_info = cache->space_info;
2703 * If this space cluster has been marked as fragmented and we've
2704 * unpinned enough in this block group to potentially allow a
2705 * cluster to be created inside of it go ahead and clear the
2708 if (cluster && cluster->fragmented &&
2709 total_unpinned > empty_cluster) {
2710 spin_lock(&cluster->lock);
2711 cluster->fragmented = 0;
2712 spin_unlock(&cluster->lock);
2715 spin_lock(&space_info->lock);
2716 spin_lock(&cache->lock);
2717 cache->pinned -= len;
2718 btrfs_space_info_update_bytes_pinned(fs_info, space_info, -len);
2719 space_info->max_extent_size = 0;
2721 space_info->bytes_readonly += len;
2723 } else if (btrfs_is_zoned(fs_info)) {
2724 /* Need reset before reusing in a zoned block group */
2725 space_info->bytes_zone_unusable += len;
2728 spin_unlock(&cache->lock);
2729 if (!readonly && return_free_space &&
2730 global_rsv->space_info == space_info) {
2731 spin_lock(&global_rsv->lock);
2732 if (!global_rsv->full) {
2733 u64 to_add = min(len, global_rsv->size -
2734 global_rsv->reserved);
2736 global_rsv->reserved += to_add;
2737 btrfs_space_info_update_bytes_may_use(fs_info,
2738 space_info, to_add);
2739 if (global_rsv->reserved >= global_rsv->size)
2740 global_rsv->full = 1;
2743 spin_unlock(&global_rsv->lock);
2745 /* Add to any tickets we may have */
2746 if (!readonly && return_free_space && len)
2747 btrfs_try_granting_tickets(fs_info, space_info);
2748 spin_unlock(&space_info->lock);
2752 btrfs_put_block_group(cache);
2756 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
2758 struct btrfs_fs_info *fs_info = trans->fs_info;
2759 struct btrfs_block_group *block_group, *tmp;
2760 struct list_head *deleted_bgs;
2761 struct extent_io_tree *unpin;
2766 unpin = &trans->transaction->pinned_extents;
2768 while (!TRANS_ABORTED(trans)) {
2769 struct extent_state *cached_state = NULL;
2771 mutex_lock(&fs_info->unused_bg_unpin_mutex);
2772 ret = find_first_extent_bit(unpin, 0, &start, &end,
2773 EXTENT_DIRTY, &cached_state);
2775 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2779 if (btrfs_test_opt(fs_info, DISCARD_SYNC))
2780 ret = btrfs_discard_extent(fs_info, start,
2781 end + 1 - start, NULL);
2783 clear_extent_dirty(unpin, start, end, &cached_state);
2784 unpin_extent_range(fs_info, start, end, true);
2785 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2786 free_extent_state(cached_state);
2790 if (btrfs_test_opt(fs_info, DISCARD_ASYNC)) {
2791 btrfs_discard_calc_delay(&fs_info->discard_ctl);
2792 btrfs_discard_schedule_work(&fs_info->discard_ctl, true);
2796 * Transaction is finished. We don't need the lock anymore. We
2797 * do need to clean up the block groups in case of a transaction
2800 deleted_bgs = &trans->transaction->deleted_bgs;
2801 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
2805 if (!TRANS_ABORTED(trans))
2806 ret = btrfs_discard_extent(fs_info,
2808 block_group->length,
2811 list_del_init(&block_group->bg_list);
2812 btrfs_unfreeze_block_group(block_group);
2813 btrfs_put_block_group(block_group);
2816 const char *errstr = btrfs_decode_error(ret);
2818 "discard failed while removing blockgroup: errno=%d %s",
2826 static int do_free_extent_accounting(struct btrfs_trans_handle *trans,
2827 u64 bytenr, u64 num_bytes, bool is_data)
2832 struct btrfs_root *csum_root;
2834 csum_root = btrfs_csum_root(trans->fs_info, bytenr);
2835 ret = btrfs_del_csums(trans, csum_root, bytenr, num_bytes);
2837 btrfs_abort_transaction(trans, ret);
2842 ret = add_to_free_space_tree(trans, bytenr, num_bytes);
2844 btrfs_abort_transaction(trans, ret);
2848 ret = btrfs_update_block_group(trans, bytenr, num_bytes, false);
2850 btrfs_abort_transaction(trans, ret);
2856 * Drop one or more refs of @node.
2858 * 1. Locate the extent refs.
2859 * It's either inline in EXTENT/METADATA_ITEM or in keyed SHARED_* item.
2860 * Locate it, then reduce the refs number or remove the ref line completely.
2862 * 2. Update the refs count in EXTENT/METADATA_ITEM
2864 * Inline backref case:
2866 * in extent tree we have:
2868 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
2869 * refs 2 gen 6 flags DATA
2870 * extent data backref root FS_TREE objectid 258 offset 0 count 1
2871 * extent data backref root FS_TREE objectid 257 offset 0 count 1
2873 * This function gets called with:
2875 * node->bytenr = 13631488
2876 * node->num_bytes = 1048576
2877 * root_objectid = FS_TREE
2878 * owner_objectid = 257
2882 * Then we should get some like:
2884 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
2885 * refs 1 gen 6 flags DATA
2886 * extent data backref root FS_TREE objectid 258 offset 0 count 1
2888 * Keyed backref case:
2890 * in extent tree we have:
2892 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
2893 * refs 754 gen 6 flags DATA
2895 * item 2 key (13631488 EXTENT_DATA_REF <HASH>) itemoff 3915 itemsize 28
2896 * extent data backref root FS_TREE objectid 866 offset 0 count 1
2898 * This function get called with:
2900 * node->bytenr = 13631488
2901 * node->num_bytes = 1048576
2902 * root_objectid = FS_TREE
2903 * owner_objectid = 866
2907 * Then we should get some like:
2909 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
2910 * refs 753 gen 6 flags DATA
2912 * And that (13631488 EXTENT_DATA_REF <HASH>) gets removed.
2914 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
2915 struct btrfs_delayed_ref_node *node, u64 parent,
2916 u64 root_objectid, u64 owner_objectid,
2917 u64 owner_offset, int refs_to_drop,
2918 struct btrfs_delayed_extent_op *extent_op)
2920 struct btrfs_fs_info *info = trans->fs_info;
2921 struct btrfs_key key;
2922 struct btrfs_path *path;
2923 struct btrfs_root *extent_root;
2924 struct extent_buffer *leaf;
2925 struct btrfs_extent_item *ei;
2926 struct btrfs_extent_inline_ref *iref;
2929 int extent_slot = 0;
2930 int found_extent = 0;
2934 u64 bytenr = node->bytenr;
2935 u64 num_bytes = node->num_bytes;
2936 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
2938 extent_root = btrfs_extent_root(info, bytenr);
2939 ASSERT(extent_root);
2941 path = btrfs_alloc_path();
2945 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
2947 if (!is_data && refs_to_drop != 1) {
2949 "invalid refs_to_drop, dropping more than 1 refs for tree block %llu refs_to_drop %u",
2950 node->bytenr, refs_to_drop);
2952 btrfs_abort_transaction(trans, ret);
2957 skinny_metadata = false;
2959 ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
2960 parent, root_objectid, owner_objectid,
2964 * Either the inline backref or the SHARED_DATA_REF/
2965 * SHARED_BLOCK_REF is found
2967 * Here is a quick path to locate EXTENT/METADATA_ITEM.
2968 * It's possible the EXTENT/METADATA_ITEM is near current slot.
2970 extent_slot = path->slots[0];
2971 while (extent_slot >= 0) {
2972 btrfs_item_key_to_cpu(path->nodes[0], &key,
2974 if (key.objectid != bytenr)
2976 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
2977 key.offset == num_bytes) {
2981 if (key.type == BTRFS_METADATA_ITEM_KEY &&
2982 key.offset == owner_objectid) {
2987 /* Quick path didn't find the EXTEMT/METADATA_ITEM */
2988 if (path->slots[0] - extent_slot > 5)
2993 if (!found_extent) {
2996 "invalid iref, no EXTENT/METADATA_ITEM found but has inline extent ref");
2997 btrfs_abort_transaction(trans, -EUCLEAN);
3000 /* Must be SHARED_* item, remove the backref first */
3001 ret = remove_extent_backref(trans, extent_root, path,
3002 NULL, refs_to_drop, is_data);
3004 btrfs_abort_transaction(trans, ret);
3007 btrfs_release_path(path);
3009 /* Slow path to locate EXTENT/METADATA_ITEM */
3010 key.objectid = bytenr;
3011 key.type = BTRFS_EXTENT_ITEM_KEY;
3012 key.offset = num_bytes;
3014 if (!is_data && skinny_metadata) {
3015 key.type = BTRFS_METADATA_ITEM_KEY;
3016 key.offset = owner_objectid;
3019 ret = btrfs_search_slot(trans, extent_root,
3021 if (ret > 0 && skinny_metadata && path->slots[0]) {
3023 * Couldn't find our skinny metadata item,
3024 * see if we have ye olde extent item.
3027 btrfs_item_key_to_cpu(path->nodes[0], &key,
3029 if (key.objectid == bytenr &&
3030 key.type == BTRFS_EXTENT_ITEM_KEY &&
3031 key.offset == num_bytes)
3035 if (ret > 0 && skinny_metadata) {
3036 skinny_metadata = false;
3037 key.objectid = bytenr;
3038 key.type = BTRFS_EXTENT_ITEM_KEY;
3039 key.offset = num_bytes;
3040 btrfs_release_path(path);
3041 ret = btrfs_search_slot(trans, extent_root,
3047 "umm, got %d back from search, was looking for %llu",
3050 btrfs_print_leaf(path->nodes[0]);
3053 btrfs_abort_transaction(trans, ret);
3056 extent_slot = path->slots[0];
3058 } else if (WARN_ON(ret == -ENOENT)) {
3059 btrfs_print_leaf(path->nodes[0]);
3061 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
3062 bytenr, parent, root_objectid, owner_objectid,
3064 btrfs_abort_transaction(trans, ret);
3067 btrfs_abort_transaction(trans, ret);
3071 leaf = path->nodes[0];
3072 item_size = btrfs_item_size(leaf, extent_slot);
3073 if (unlikely(item_size < sizeof(*ei))) {
3075 btrfs_print_v0_err(info);
3076 btrfs_abort_transaction(trans, ret);
3079 ei = btrfs_item_ptr(leaf, extent_slot,
3080 struct btrfs_extent_item);
3081 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
3082 key.type == BTRFS_EXTENT_ITEM_KEY) {
3083 struct btrfs_tree_block_info *bi;
3084 if (item_size < sizeof(*ei) + sizeof(*bi)) {
3086 "invalid extent item size for key (%llu, %u, %llu) owner %llu, has %u expect >= %zu",
3087 key.objectid, key.type, key.offset,
3088 owner_objectid, item_size,
3089 sizeof(*ei) + sizeof(*bi));
3090 btrfs_abort_transaction(trans, -EUCLEAN);
3093 bi = (struct btrfs_tree_block_info *)(ei + 1);
3094 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
3097 refs = btrfs_extent_refs(leaf, ei);
3098 if (refs < refs_to_drop) {
3100 "trying to drop %d refs but we only have %llu for bytenr %llu",
3101 refs_to_drop, refs, bytenr);
3102 btrfs_abort_transaction(trans, -EUCLEAN);
3105 refs -= refs_to_drop;
3109 __run_delayed_extent_op(extent_op, leaf, ei);
3111 * In the case of inline back ref, reference count will
3112 * be updated by remove_extent_backref
3115 if (!found_extent) {
3117 "invalid iref, got inlined extent ref but no EXTENT/METADATA_ITEM found");
3118 btrfs_abort_transaction(trans, -EUCLEAN);
3122 btrfs_set_extent_refs(leaf, ei, refs);
3123 btrfs_mark_buffer_dirty(leaf);
3126 ret = remove_extent_backref(trans, extent_root, path,
3127 iref, refs_to_drop, is_data);
3129 btrfs_abort_transaction(trans, ret);
3134 /* In this branch refs == 1 */
3136 if (is_data && refs_to_drop !=
3137 extent_data_ref_count(path, iref)) {
3139 "invalid refs_to_drop, current refs %u refs_to_drop %u",
3140 extent_data_ref_count(path, iref),
3142 btrfs_abort_transaction(trans, -EUCLEAN);
3146 if (path->slots[0] != extent_slot) {
3148 "invalid iref, extent item key (%llu %u %llu) doesn't have wanted iref",
3149 key.objectid, key.type,
3151 btrfs_abort_transaction(trans, -EUCLEAN);
3156 * No inline ref, we must be at SHARED_* item,
3157 * And it's single ref, it must be:
3158 * | extent_slot ||extent_slot + 1|
3159 * [ EXTENT/METADATA_ITEM ][ SHARED_* ITEM ]
3161 if (path->slots[0] != extent_slot + 1) {
3163 "invalid SHARED_* item, previous item is not EXTENT/METADATA_ITEM");
3164 btrfs_abort_transaction(trans, -EUCLEAN);
3167 path->slots[0] = extent_slot;
3172 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
3175 btrfs_abort_transaction(trans, ret);
3178 btrfs_release_path(path);
3180 ret = do_free_extent_accounting(trans, bytenr, num_bytes, is_data);
3182 btrfs_release_path(path);
3185 btrfs_free_path(path);
3189 * Leaf dump can take up a lot of log buffer, so we only do full leaf
3190 * dump for debug build.
3192 if (IS_ENABLED(CONFIG_BTRFS_DEBUG)) {
3193 btrfs_crit(info, "path->slots[0]=%d extent_slot=%d",
3194 path->slots[0], extent_slot);
3195 btrfs_print_leaf(path->nodes[0]);
3198 btrfs_free_path(path);
3203 * when we free an block, it is possible (and likely) that we free the last
3204 * delayed ref for that extent as well. This searches the delayed ref tree for
3205 * a given extent, and if there are no other delayed refs to be processed, it
3206 * removes it from the tree.
3208 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
3211 struct btrfs_delayed_ref_head *head;
3212 struct btrfs_delayed_ref_root *delayed_refs;
3215 delayed_refs = &trans->transaction->delayed_refs;
3216 spin_lock(&delayed_refs->lock);
3217 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
3219 goto out_delayed_unlock;
3221 spin_lock(&head->lock);
3222 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
3225 if (cleanup_extent_op(head) != NULL)
3229 * waiting for the lock here would deadlock. If someone else has it
3230 * locked they are already in the process of dropping it anyway
3232 if (!mutex_trylock(&head->mutex))
3235 btrfs_delete_ref_head(delayed_refs, head);
3236 head->processing = 0;
3238 spin_unlock(&head->lock);
3239 spin_unlock(&delayed_refs->lock);
3241 BUG_ON(head->extent_op);
3242 if (head->must_insert_reserved)
3245 btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
3246 mutex_unlock(&head->mutex);
3247 btrfs_put_delayed_ref_head(head);
3250 spin_unlock(&head->lock);
3253 spin_unlock(&delayed_refs->lock);
3257 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
3259 struct extent_buffer *buf,
3260 u64 parent, int last_ref)
3262 struct btrfs_fs_info *fs_info = trans->fs_info;
3263 struct btrfs_ref generic_ref = { 0 };
3266 btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
3267 buf->start, buf->len, parent);
3268 btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
3271 if (root_id != BTRFS_TREE_LOG_OBJECTID) {
3272 btrfs_ref_tree_mod(fs_info, &generic_ref);
3273 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL);
3274 BUG_ON(ret); /* -ENOMEM */
3277 if (last_ref && btrfs_header_generation(buf) == trans->transid) {
3278 struct btrfs_block_group *cache;
3279 bool must_pin = false;
3281 if (root_id != BTRFS_TREE_LOG_OBJECTID) {
3282 ret = check_ref_cleanup(trans, buf->start);
3284 btrfs_redirty_list_add(trans->transaction, buf);
3289 cache = btrfs_lookup_block_group(fs_info, buf->start);
3291 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
3292 pin_down_extent(trans, cache, buf->start, buf->len, 1);
3293 btrfs_put_block_group(cache);
3298 * If there are tree mod log users we may have recorded mod log
3299 * operations for this node. If we re-allocate this node we
3300 * could replay operations on this node that happened when it
3301 * existed in a completely different root. For example if it
3302 * was part of root A, then was reallocated to root B, and we
3303 * are doing a btrfs_old_search_slot(root b), we could replay
3304 * operations that happened when the block was part of root A,
3305 * giving us an inconsistent view of the btree.
3307 * We are safe from races here because at this point no other
3308 * node or root points to this extent buffer, so if after this
3309 * check a new tree mod log user joins we will not have an
3310 * existing log of operations on this node that we have to
3313 if (test_bit(BTRFS_FS_TREE_MOD_LOG_USERS, &fs_info->flags))
3316 if (must_pin || btrfs_is_zoned(fs_info)) {
3317 btrfs_redirty_list_add(trans->transaction, buf);
3318 pin_down_extent(trans, cache, buf->start, buf->len, 1);
3319 btrfs_put_block_group(cache);
3323 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
3325 btrfs_add_free_space(cache, buf->start, buf->len);
3326 btrfs_free_reserved_bytes(cache, buf->len, 0);
3327 btrfs_put_block_group(cache);
3328 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
3333 * Deleting the buffer, clear the corrupt flag since it doesn't
3336 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
3340 /* Can return -ENOMEM */
3341 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
3343 struct btrfs_fs_info *fs_info = trans->fs_info;
3346 if (btrfs_is_testing(fs_info))
3350 * tree log blocks never actually go into the extent allocation
3351 * tree, just update pinning info and exit early.
3353 if ((ref->type == BTRFS_REF_METADATA &&
3354 ref->tree_ref.owning_root == BTRFS_TREE_LOG_OBJECTID) ||
3355 (ref->type == BTRFS_REF_DATA &&
3356 ref->data_ref.owning_root == BTRFS_TREE_LOG_OBJECTID)) {
3357 /* unlocks the pinned mutex */
3358 btrfs_pin_extent(trans, ref->bytenr, ref->len, 1);
3360 } else if (ref->type == BTRFS_REF_METADATA) {
3361 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL);
3363 ret = btrfs_add_delayed_data_ref(trans, ref, 0);
3366 if (!((ref->type == BTRFS_REF_METADATA &&
3367 ref->tree_ref.owning_root == BTRFS_TREE_LOG_OBJECTID) ||
3368 (ref->type == BTRFS_REF_DATA &&
3369 ref->data_ref.owning_root == BTRFS_TREE_LOG_OBJECTID)))
3370 btrfs_ref_tree_mod(fs_info, ref);
3375 enum btrfs_loop_type {
3376 LOOP_CACHING_NOWAIT,
3383 btrfs_lock_block_group(struct btrfs_block_group *cache,
3387 down_read(&cache->data_rwsem);
3390 static inline void btrfs_grab_block_group(struct btrfs_block_group *cache,
3393 btrfs_get_block_group(cache);
3395 down_read(&cache->data_rwsem);
3398 static struct btrfs_block_group *btrfs_lock_cluster(
3399 struct btrfs_block_group *block_group,
3400 struct btrfs_free_cluster *cluster,
3402 __acquires(&cluster->refill_lock)
3404 struct btrfs_block_group *used_bg = NULL;
3406 spin_lock(&cluster->refill_lock);
3408 used_bg = cluster->block_group;
3412 if (used_bg == block_group)
3415 btrfs_get_block_group(used_bg);
3420 if (down_read_trylock(&used_bg->data_rwsem))
3423 spin_unlock(&cluster->refill_lock);
3425 /* We should only have one-level nested. */
3426 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
3428 spin_lock(&cluster->refill_lock);
3429 if (used_bg == cluster->block_group)
3432 up_read(&used_bg->data_rwsem);
3433 btrfs_put_block_group(used_bg);
3438 btrfs_release_block_group(struct btrfs_block_group *cache,
3442 up_read(&cache->data_rwsem);
3443 btrfs_put_block_group(cache);
3446 enum btrfs_extent_allocation_policy {
3447 BTRFS_EXTENT_ALLOC_CLUSTERED,
3448 BTRFS_EXTENT_ALLOC_ZONED,
3452 * Structure used internally for find_free_extent() function. Wraps needed
3455 struct find_free_extent_ctl {
3456 /* Basic allocation info */
3464 /* Where to start the search inside the bg */
3467 /* For clustered allocation */
3469 struct btrfs_free_cluster *last_ptr;
3472 bool have_caching_bg;
3473 bool orig_have_caching_bg;
3475 /* Allocation is called for tree-log */
3478 /* Allocation is called for data relocation */
3479 bool for_data_reloc;
3481 /* RAID index, converted from flags */
3485 * Current loop number, check find_free_extent_update_loop() for details
3490 * Whether we're refilling a cluster, if true we need to re-search
3491 * current block group but don't try to refill the cluster again.
3493 bool retry_clustered;
3496 * Whether we're updating free space cache, if true we need to re-search
3497 * current block group but don't try updating free space cache again.
3499 bool retry_unclustered;
3501 /* If current block group is cached */
3504 /* Max contiguous hole found */
3505 u64 max_extent_size;
3507 /* Total free space from free space cache, not always contiguous */
3508 u64 total_free_space;
3513 /* Hint where to start looking for an empty space */
3516 /* Allocation policy */
3517 enum btrfs_extent_allocation_policy policy;
3522 * Helper function for find_free_extent().
3524 * Return -ENOENT to inform caller that we need fallback to unclustered mode.
3525 * Return -EAGAIN to inform caller that we need to re-search this block group
3526 * Return >0 to inform caller that we find nothing
3527 * Return 0 means we have found a location and set ffe_ctl->found_offset.
3529 static int find_free_extent_clustered(struct btrfs_block_group *bg,
3530 struct find_free_extent_ctl *ffe_ctl,
3531 struct btrfs_block_group **cluster_bg_ret)
3533 struct btrfs_block_group *cluster_bg;
3534 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3535 u64 aligned_cluster;
3539 cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
3541 goto refill_cluster;
3542 if (cluster_bg != bg && (cluster_bg->ro ||
3543 !block_group_bits(cluster_bg, ffe_ctl->flags)))
3544 goto release_cluster;
3546 offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
3547 ffe_ctl->num_bytes, cluster_bg->start,
3548 &ffe_ctl->max_extent_size);
3550 /* We have a block, we're done */
3551 spin_unlock(&last_ptr->refill_lock);
3552 trace_btrfs_reserve_extent_cluster(cluster_bg,
3553 ffe_ctl->search_start, ffe_ctl->num_bytes);
3554 *cluster_bg_ret = cluster_bg;
3555 ffe_ctl->found_offset = offset;
3558 WARN_ON(last_ptr->block_group != cluster_bg);
3562 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
3563 * lets just skip it and let the allocator find whatever block it can
3564 * find. If we reach this point, we will have tried the cluster
3565 * allocator plenty of times and not have found anything, so we are
3566 * likely way too fragmented for the clustering stuff to find anything.
3568 * However, if the cluster is taken from the current block group,
3569 * release the cluster first, so that we stand a better chance of
3570 * succeeding in the unclustered allocation.
3572 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
3573 spin_unlock(&last_ptr->refill_lock);
3574 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3578 /* This cluster didn't work out, free it and start over */
3579 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3581 if (cluster_bg != bg)
3582 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3585 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
3586 spin_unlock(&last_ptr->refill_lock);
3590 aligned_cluster = max_t(u64,
3591 ffe_ctl->empty_cluster + ffe_ctl->empty_size,
3592 bg->full_stripe_len);
3593 ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
3594 ffe_ctl->num_bytes, aligned_cluster);
3596 /* Now pull our allocation out of this cluster */
3597 offset = btrfs_alloc_from_cluster(bg, last_ptr,
3598 ffe_ctl->num_bytes, ffe_ctl->search_start,
3599 &ffe_ctl->max_extent_size);
3601 /* We found one, proceed */
3602 spin_unlock(&last_ptr->refill_lock);
3603 trace_btrfs_reserve_extent_cluster(bg,
3604 ffe_ctl->search_start,
3605 ffe_ctl->num_bytes);
3606 ffe_ctl->found_offset = offset;
3609 } else if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
3610 !ffe_ctl->retry_clustered) {
3611 spin_unlock(&last_ptr->refill_lock);
3613 ffe_ctl->retry_clustered = true;
3614 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3615 ffe_ctl->empty_cluster + ffe_ctl->empty_size);
3619 * At this point we either didn't find a cluster or we weren't able to
3620 * allocate a block from our cluster. Free the cluster we've been
3621 * trying to use, and go to the next block group.
3623 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3624 spin_unlock(&last_ptr->refill_lock);
3629 * Return >0 to inform caller that we find nothing
3630 * Return 0 when we found an free extent and set ffe_ctrl->found_offset
3631 * Return -EAGAIN to inform caller that we need to re-search this block group
3633 static int find_free_extent_unclustered(struct btrfs_block_group *bg,
3634 struct find_free_extent_ctl *ffe_ctl)
3636 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3640 * We are doing an unclustered allocation, set the fragmented flag so
3641 * we don't bother trying to setup a cluster again until we get more
3644 if (unlikely(last_ptr)) {
3645 spin_lock(&last_ptr->lock);
3646 last_ptr->fragmented = 1;
3647 spin_unlock(&last_ptr->lock);
3649 if (ffe_ctl->cached) {
3650 struct btrfs_free_space_ctl *free_space_ctl;
3652 free_space_ctl = bg->free_space_ctl;
3653 spin_lock(&free_space_ctl->tree_lock);
3654 if (free_space_ctl->free_space <
3655 ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
3656 ffe_ctl->empty_size) {
3657 ffe_ctl->total_free_space = max_t(u64,
3658 ffe_ctl->total_free_space,
3659 free_space_ctl->free_space);
3660 spin_unlock(&free_space_ctl->tree_lock);
3663 spin_unlock(&free_space_ctl->tree_lock);
3666 offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
3667 ffe_ctl->num_bytes, ffe_ctl->empty_size,
3668 &ffe_ctl->max_extent_size);
3671 * If we didn't find a chunk, and we haven't failed on this block group
3672 * before, and this block group is in the middle of caching and we are
3673 * ok with waiting, then go ahead and wait for progress to be made, and
3674 * set @retry_unclustered to true.
3676 * If @retry_unclustered is true then we've already waited on this
3677 * block group once and should move on to the next block group.
3679 if (!offset && !ffe_ctl->retry_unclustered && !ffe_ctl->cached &&
3680 ffe_ctl->loop > LOOP_CACHING_NOWAIT) {
3681 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3682 ffe_ctl->empty_size);
3683 ffe_ctl->retry_unclustered = true;
3685 } else if (!offset) {
3688 ffe_ctl->found_offset = offset;
3692 static int do_allocation_clustered(struct btrfs_block_group *block_group,
3693 struct find_free_extent_ctl *ffe_ctl,
3694 struct btrfs_block_group **bg_ret)
3698 /* We want to try and use the cluster allocator, so lets look there */
3699 if (ffe_ctl->last_ptr && ffe_ctl->use_cluster) {
3700 ret = find_free_extent_clustered(block_group, ffe_ctl, bg_ret);
3701 if (ret >= 0 || ret == -EAGAIN)
3703 /* ret == -ENOENT case falls through */
3706 return find_free_extent_unclustered(block_group, ffe_ctl);
3710 * Tree-log block group locking
3711 * ============================
3713 * fs_info::treelog_bg_lock protects the fs_info::treelog_bg which
3714 * indicates the starting address of a block group, which is reserved only
3715 * for tree-log metadata.
3722 * fs_info::treelog_bg_lock
3726 * Simple allocator for sequential-only block group. It only allows sequential
3727 * allocation. No need to play with trees. This function also reserves the
3728 * bytes as in btrfs_add_reserved_bytes.
3730 static int do_allocation_zoned(struct btrfs_block_group *block_group,
3731 struct find_free_extent_ctl *ffe_ctl,
3732 struct btrfs_block_group **bg_ret)
3734 struct btrfs_fs_info *fs_info = block_group->fs_info;
3735 struct btrfs_space_info *space_info = block_group->space_info;
3736 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3737 u64 start = block_group->start;
3738 u64 num_bytes = ffe_ctl->num_bytes;
3740 u64 bytenr = block_group->start;
3742 u64 data_reloc_bytenr;
3746 ASSERT(btrfs_is_zoned(block_group->fs_info));
3749 * Do not allow non-tree-log blocks in the dedicated tree-log block
3750 * group, and vice versa.
3752 spin_lock(&fs_info->treelog_bg_lock);
3753 log_bytenr = fs_info->treelog_bg;
3754 if (log_bytenr && ((ffe_ctl->for_treelog && bytenr != log_bytenr) ||
3755 (!ffe_ctl->for_treelog && bytenr == log_bytenr)))
3757 spin_unlock(&fs_info->treelog_bg_lock);
3762 * Do not allow non-relocation blocks in the dedicated relocation block
3763 * group, and vice versa.
3765 spin_lock(&fs_info->relocation_bg_lock);
3766 data_reloc_bytenr = fs_info->data_reloc_bg;
3767 if (data_reloc_bytenr &&
3768 ((ffe_ctl->for_data_reloc && bytenr != data_reloc_bytenr) ||
3769 (!ffe_ctl->for_data_reloc && bytenr == data_reloc_bytenr)))
3771 spin_unlock(&fs_info->relocation_bg_lock);
3775 /* Check RO and no space case before trying to activate it */
3776 spin_lock(&block_group->lock);
3777 if (block_group->ro || btrfs_zoned_bg_is_full(block_group)) {
3780 * May need to clear fs_info->{treelog,data_reloc}_bg.
3781 * Return the error after taking the locks.
3784 spin_unlock(&block_group->lock);
3786 if (!ret && !btrfs_zone_activate(block_group)) {
3789 * May need to clear fs_info->{treelog,data_reloc}_bg.
3790 * Return the error after taking the locks.
3794 spin_lock(&space_info->lock);
3795 spin_lock(&block_group->lock);
3796 spin_lock(&fs_info->treelog_bg_lock);
3797 spin_lock(&fs_info->relocation_bg_lock);
3802 ASSERT(!ffe_ctl->for_treelog ||
3803 block_group->start == fs_info->treelog_bg ||
3804 fs_info->treelog_bg == 0);
3805 ASSERT(!ffe_ctl->for_data_reloc ||
3806 block_group->start == fs_info->data_reloc_bg ||
3807 fs_info->data_reloc_bg == 0);
3809 if (block_group->ro ||
3810 test_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags)) {
3816 * Do not allow currently using block group to be tree-log dedicated
3819 if (ffe_ctl->for_treelog && !fs_info->treelog_bg &&
3820 (block_group->used || block_group->reserved)) {
3826 * Do not allow currently used block group to be the data relocation
3827 * dedicated block group.
3829 if (ffe_ctl->for_data_reloc && !fs_info->data_reloc_bg &&
3830 (block_group->used || block_group->reserved)) {
3835 WARN_ON_ONCE(block_group->alloc_offset > block_group->zone_capacity);
3836 avail = block_group->zone_capacity - block_group->alloc_offset;
3837 if (avail < num_bytes) {
3838 if (ffe_ctl->max_extent_size < avail) {
3840 * With sequential allocator, free space is always
3843 ffe_ctl->max_extent_size = avail;
3844 ffe_ctl->total_free_space = avail;
3850 if (ffe_ctl->for_treelog && !fs_info->treelog_bg)
3851 fs_info->treelog_bg = block_group->start;
3853 if (ffe_ctl->for_data_reloc && !fs_info->data_reloc_bg)
3854 fs_info->data_reloc_bg = block_group->start;
3856 ffe_ctl->found_offset = start + block_group->alloc_offset;
3857 block_group->alloc_offset += num_bytes;
3858 spin_lock(&ctl->tree_lock);
3859 ctl->free_space -= num_bytes;
3860 spin_unlock(&ctl->tree_lock);
3863 * We do not check if found_offset is aligned to stripesize. The
3864 * address is anyway rewritten when using zone append writing.
3867 ffe_ctl->search_start = ffe_ctl->found_offset;
3870 if (ret && ffe_ctl->for_treelog)
3871 fs_info->treelog_bg = 0;
3872 if (ret && ffe_ctl->for_data_reloc &&
3873 fs_info->data_reloc_bg == block_group->start) {
3875 * Do not allow further allocations from this block group.
3876 * Compared to increasing the ->ro, setting the
3877 * ->zoned_data_reloc_ongoing flag still allows nocow
3878 * writers to come in. See btrfs_inc_nocow_writers().
3880 * We need to disable an allocation to avoid an allocation of
3881 * regular (non-relocation data) extent. With mix of relocation
3882 * extents and regular extents, we can dispatch WRITE commands
3883 * (for relocation extents) and ZONE APPEND commands (for
3884 * regular extents) at the same time to the same zone, which
3885 * easily break the write pointer.
3887 set_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags);
3888 fs_info->data_reloc_bg = 0;
3890 spin_unlock(&fs_info->relocation_bg_lock);
3891 spin_unlock(&fs_info->treelog_bg_lock);
3892 spin_unlock(&block_group->lock);
3893 spin_unlock(&space_info->lock);
3897 static int do_allocation(struct btrfs_block_group *block_group,
3898 struct find_free_extent_ctl *ffe_ctl,
3899 struct btrfs_block_group **bg_ret)
3901 switch (ffe_ctl->policy) {
3902 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3903 return do_allocation_clustered(block_group, ffe_ctl, bg_ret);
3904 case BTRFS_EXTENT_ALLOC_ZONED:
3905 return do_allocation_zoned(block_group, ffe_ctl, bg_ret);
3911 static void release_block_group(struct btrfs_block_group *block_group,
3912 struct find_free_extent_ctl *ffe_ctl,
3915 switch (ffe_ctl->policy) {
3916 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3917 ffe_ctl->retry_clustered = false;
3918 ffe_ctl->retry_unclustered = false;
3920 case BTRFS_EXTENT_ALLOC_ZONED:
3927 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
3929 btrfs_release_block_group(block_group, delalloc);
3932 static void found_extent_clustered(struct find_free_extent_ctl *ffe_ctl,
3933 struct btrfs_key *ins)
3935 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3937 if (!ffe_ctl->use_cluster && last_ptr) {
3938 spin_lock(&last_ptr->lock);
3939 last_ptr->window_start = ins->objectid;
3940 spin_unlock(&last_ptr->lock);
3944 static void found_extent(struct find_free_extent_ctl *ffe_ctl,
3945 struct btrfs_key *ins)
3947 switch (ffe_ctl->policy) {
3948 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3949 found_extent_clustered(ffe_ctl, ins);
3951 case BTRFS_EXTENT_ALLOC_ZONED:
3959 static int can_allocate_chunk_zoned(struct btrfs_fs_info *fs_info,
3960 struct find_free_extent_ctl *ffe_ctl)
3962 /* If we can activate new zone, just allocate a chunk and use it */
3963 if (btrfs_can_activate_zone(fs_info->fs_devices, ffe_ctl->flags))
3967 * We already reached the max active zones. Try to finish one block
3968 * group to make a room for a new block group. This is only possible
3969 * for a data block group because btrfs_zone_finish() may need to wait
3970 * for a running transaction which can cause a deadlock for metadata
3973 if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA) {
3974 int ret = btrfs_zone_finish_one_bg(fs_info);
3983 * If we have enough free space left in an already active block group
3984 * and we can't activate any other zone now, do not allow allocating a
3985 * new chunk and let find_free_extent() retry with a smaller size.
3987 if (ffe_ctl->max_extent_size >= ffe_ctl->min_alloc_size)
3991 * Even min_alloc_size is not left in any block groups. Since we cannot
3992 * activate a new block group, allocating it may not help. Let's tell a
3993 * caller to try again and hope it progress something by writing some
3994 * parts of the region. That is only possible for data block groups,
3995 * where a part of the region can be written.
3997 if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA)
4001 * We cannot activate a new block group and no enough space left in any
4002 * block groups. So, allocating a new block group may not help. But,
4003 * there is nothing to do anyway, so let's go with it.
4008 static int can_allocate_chunk(struct btrfs_fs_info *fs_info,
4009 struct find_free_extent_ctl *ffe_ctl)
4011 switch (ffe_ctl->policy) {
4012 case BTRFS_EXTENT_ALLOC_CLUSTERED:
4014 case BTRFS_EXTENT_ALLOC_ZONED:
4015 return can_allocate_chunk_zoned(fs_info, ffe_ctl);
4021 static int chunk_allocation_failed(struct find_free_extent_ctl *ffe_ctl)
4023 switch (ffe_ctl->policy) {
4024 case BTRFS_EXTENT_ALLOC_CLUSTERED:
4026 * If we can't allocate a new chunk we've already looped through
4027 * at least once, move on to the NO_EMPTY_SIZE case.
4029 ffe_ctl->loop = LOOP_NO_EMPTY_SIZE;
4031 case BTRFS_EXTENT_ALLOC_ZONED:
4040 * Return >0 means caller needs to re-search for free extent
4041 * Return 0 means we have the needed free extent.
4042 * Return <0 means we failed to locate any free extent.
4044 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
4045 struct btrfs_key *ins,
4046 struct find_free_extent_ctl *ffe_ctl,
4049 struct btrfs_root *root = fs_info->chunk_root;
4052 if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
4053 ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
4054 ffe_ctl->orig_have_caching_bg = true;
4056 if (ins->objectid) {
4057 found_extent(ffe_ctl, ins);
4061 if (ffe_ctl->loop >= LOOP_CACHING_WAIT && ffe_ctl->have_caching_bg)
4065 if (ffe_ctl->index < BTRFS_NR_RAID_TYPES)
4069 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
4070 * caching kthreads as we move along
4071 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
4072 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
4073 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
4076 if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
4078 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT) {
4080 * We want to skip the LOOP_CACHING_WAIT step if we
4081 * don't have any uncached bgs and we've already done a
4082 * full search through.
4084 if (ffe_ctl->orig_have_caching_bg || !full_search)
4085 ffe_ctl->loop = LOOP_CACHING_WAIT;
4087 ffe_ctl->loop = LOOP_ALLOC_CHUNK;
4092 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
4093 struct btrfs_trans_handle *trans;
4096 /*Check if allocation policy allows to create a new chunk */
4097 ret = can_allocate_chunk(fs_info, ffe_ctl);
4101 trans = current->journal_info;
4105 trans = btrfs_join_transaction(root);
4107 if (IS_ERR(trans)) {
4108 ret = PTR_ERR(trans);
4112 ret = btrfs_chunk_alloc(trans, ffe_ctl->flags,
4113 CHUNK_ALLOC_FORCE_FOR_EXTENT);
4115 /* Do not bail out on ENOSPC since we can do more. */
4117 ret = chunk_allocation_failed(ffe_ctl);
4119 btrfs_abort_transaction(trans, ret);
4123 btrfs_end_transaction(trans);
4128 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
4129 if (ffe_ctl->policy != BTRFS_EXTENT_ALLOC_CLUSTERED)
4133 * Don't loop again if we already have no empty_size and
4136 if (ffe_ctl->empty_size == 0 &&
4137 ffe_ctl->empty_cluster == 0)
4139 ffe_ctl->empty_size = 0;
4140 ffe_ctl->empty_cluster = 0;
4147 static int prepare_allocation_clustered(struct btrfs_fs_info *fs_info,
4148 struct find_free_extent_ctl *ffe_ctl,
4149 struct btrfs_space_info *space_info,
4150 struct btrfs_key *ins)
4153 * If our free space is heavily fragmented we may not be able to make
4154 * big contiguous allocations, so instead of doing the expensive search
4155 * for free space, simply return ENOSPC with our max_extent_size so we
4156 * can go ahead and search for a more manageable chunk.
4158 * If our max_extent_size is large enough for our allocation simply
4159 * disable clustering since we will likely not be able to find enough
4160 * space to create a cluster and induce latency trying.
4162 if (space_info->max_extent_size) {
4163 spin_lock(&space_info->lock);
4164 if (space_info->max_extent_size &&
4165 ffe_ctl->num_bytes > space_info->max_extent_size) {
4166 ins->offset = space_info->max_extent_size;
4167 spin_unlock(&space_info->lock);
4169 } else if (space_info->max_extent_size) {
4170 ffe_ctl->use_cluster = false;
4172 spin_unlock(&space_info->lock);
4175 ffe_ctl->last_ptr = fetch_cluster_info(fs_info, space_info,
4176 &ffe_ctl->empty_cluster);
4177 if (ffe_ctl->last_ptr) {
4178 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
4180 spin_lock(&last_ptr->lock);
4181 if (last_ptr->block_group)
4182 ffe_ctl->hint_byte = last_ptr->window_start;
4183 if (last_ptr->fragmented) {
4185 * We still set window_start so we can keep track of the
4186 * last place we found an allocation to try and save
4189 ffe_ctl->hint_byte = last_ptr->window_start;
4190 ffe_ctl->use_cluster = false;
4192 spin_unlock(&last_ptr->lock);
4198 static int prepare_allocation(struct btrfs_fs_info *fs_info,
4199 struct find_free_extent_ctl *ffe_ctl,
4200 struct btrfs_space_info *space_info,
4201 struct btrfs_key *ins)
4203 switch (ffe_ctl->policy) {
4204 case BTRFS_EXTENT_ALLOC_CLUSTERED:
4205 return prepare_allocation_clustered(fs_info, ffe_ctl,
4207 case BTRFS_EXTENT_ALLOC_ZONED:
4208 if (ffe_ctl->for_treelog) {
4209 spin_lock(&fs_info->treelog_bg_lock);
4210 if (fs_info->treelog_bg)
4211 ffe_ctl->hint_byte = fs_info->treelog_bg;
4212 spin_unlock(&fs_info->treelog_bg_lock);
4214 if (ffe_ctl->for_data_reloc) {
4215 spin_lock(&fs_info->relocation_bg_lock);
4216 if (fs_info->data_reloc_bg)
4217 ffe_ctl->hint_byte = fs_info->data_reloc_bg;
4218 spin_unlock(&fs_info->relocation_bg_lock);
4227 * walks the btree of allocated extents and find a hole of a given size.
4228 * The key ins is changed to record the hole:
4229 * ins->objectid == start position
4230 * ins->flags = BTRFS_EXTENT_ITEM_KEY
4231 * ins->offset == the size of the hole.
4232 * Any available blocks before search_start are skipped.
4234 * If there is no suitable free space, we will record the max size of
4235 * the free space extent currently.
4237 * The overall logic and call chain:
4239 * find_free_extent()
4240 * |- Iterate through all block groups
4241 * | |- Get a valid block group
4242 * | |- Try to do clustered allocation in that block group
4243 * | |- Try to do unclustered allocation in that block group
4244 * | |- Check if the result is valid
4245 * | | |- If valid, then exit
4246 * | |- Jump to next block group
4248 * |- Push harder to find free extents
4249 * |- If not found, re-iterate all block groups
4251 static noinline int find_free_extent(struct btrfs_root *root,
4252 struct btrfs_key *ins,
4253 struct find_free_extent_ctl *ffe_ctl)
4255 struct btrfs_fs_info *fs_info = root->fs_info;
4257 int cache_block_group_error = 0;
4258 struct btrfs_block_group *block_group = NULL;
4259 struct btrfs_space_info *space_info;
4260 bool full_search = false;
4262 WARN_ON(ffe_ctl->num_bytes < fs_info->sectorsize);
4264 ffe_ctl->search_start = 0;
4265 /* For clustered allocation */
4266 ffe_ctl->empty_cluster = 0;
4267 ffe_ctl->last_ptr = NULL;
4268 ffe_ctl->use_cluster = true;
4269 ffe_ctl->have_caching_bg = false;
4270 ffe_ctl->orig_have_caching_bg = false;
4271 ffe_ctl->index = btrfs_bg_flags_to_raid_index(ffe_ctl->flags);
4273 /* For clustered allocation */
4274 ffe_ctl->retry_clustered = false;
4275 ffe_ctl->retry_unclustered = false;
4276 ffe_ctl->cached = 0;
4277 ffe_ctl->max_extent_size = 0;
4278 ffe_ctl->total_free_space = 0;
4279 ffe_ctl->found_offset = 0;
4280 ffe_ctl->policy = BTRFS_EXTENT_ALLOC_CLUSTERED;
4282 if (btrfs_is_zoned(fs_info))
4283 ffe_ctl->policy = BTRFS_EXTENT_ALLOC_ZONED;
4285 ins->type = BTRFS_EXTENT_ITEM_KEY;
4289 trace_find_free_extent(root, ffe_ctl->num_bytes, ffe_ctl->empty_size,
4292 space_info = btrfs_find_space_info(fs_info, ffe_ctl->flags);
4294 btrfs_err(fs_info, "No space info for %llu", ffe_ctl->flags);
4298 ret = prepare_allocation(fs_info, ffe_ctl, space_info, ins);
4302 ffe_ctl->search_start = max(ffe_ctl->search_start,
4303 first_logical_byte(fs_info));
4304 ffe_ctl->search_start = max(ffe_ctl->search_start, ffe_ctl->hint_byte);
4305 if (ffe_ctl->search_start == ffe_ctl->hint_byte) {
4306 block_group = btrfs_lookup_block_group(fs_info,
4307 ffe_ctl->search_start);
4309 * we don't want to use the block group if it doesn't match our
4310 * allocation bits, or if its not cached.
4312 * However if we are re-searching with an ideal block group
4313 * picked out then we don't care that the block group is cached.
4315 if (block_group && block_group_bits(block_group, ffe_ctl->flags) &&
4316 block_group->cached != BTRFS_CACHE_NO) {
4317 down_read(&space_info->groups_sem);
4318 if (list_empty(&block_group->list) ||
4321 * someone is removing this block group,
4322 * we can't jump into the have_block_group
4323 * target because our list pointers are not
4326 btrfs_put_block_group(block_group);
4327 up_read(&space_info->groups_sem);
4329 ffe_ctl->index = btrfs_bg_flags_to_raid_index(
4330 block_group->flags);
4331 btrfs_lock_block_group(block_group,
4333 goto have_block_group;
4335 } else if (block_group) {
4336 btrfs_put_block_group(block_group);
4340 ffe_ctl->have_caching_bg = false;
4341 if (ffe_ctl->index == btrfs_bg_flags_to_raid_index(ffe_ctl->flags) ||
4342 ffe_ctl->index == 0)
4344 down_read(&space_info->groups_sem);
4345 list_for_each_entry(block_group,
4346 &space_info->block_groups[ffe_ctl->index], list) {
4347 struct btrfs_block_group *bg_ret;
4349 /* If the block group is read-only, we can skip it entirely. */
4350 if (unlikely(block_group->ro)) {
4351 if (ffe_ctl->for_treelog)
4352 btrfs_clear_treelog_bg(block_group);
4353 if (ffe_ctl->for_data_reloc)
4354 btrfs_clear_data_reloc_bg(block_group);
4358 btrfs_grab_block_group(block_group, ffe_ctl->delalloc);
4359 ffe_ctl->search_start = block_group->start;
4362 * this can happen if we end up cycling through all the
4363 * raid types, but we want to make sure we only allocate
4364 * for the proper type.
4366 if (!block_group_bits(block_group, ffe_ctl->flags)) {
4367 u64 extra = BTRFS_BLOCK_GROUP_DUP |
4368 BTRFS_BLOCK_GROUP_RAID1_MASK |
4369 BTRFS_BLOCK_GROUP_RAID56_MASK |
4370 BTRFS_BLOCK_GROUP_RAID10;
4373 * if they asked for extra copies and this block group
4374 * doesn't provide them, bail. This does allow us to
4375 * fill raid0 from raid1.
4377 if ((ffe_ctl->flags & extra) && !(block_group->flags & extra))
4381 * This block group has different flags than we want.
4382 * It's possible that we have MIXED_GROUP flag but no
4383 * block group is mixed. Just skip such block group.
4385 btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4390 ffe_ctl->cached = btrfs_block_group_done(block_group);
4391 if (unlikely(!ffe_ctl->cached)) {
4392 ffe_ctl->have_caching_bg = true;
4393 ret = btrfs_cache_block_group(block_group, false);
4396 * If we get ENOMEM here or something else we want to
4397 * try other block groups, because it may not be fatal.
4398 * However if we can't find anything else we need to
4399 * save our return here so that we return the actual
4400 * error that caused problems, not ENOSPC.
4403 if (!cache_block_group_error)
4404 cache_block_group_error = ret;
4411 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
4415 ret = do_allocation(block_group, ffe_ctl, &bg_ret);
4417 if (bg_ret && bg_ret != block_group) {
4418 btrfs_release_block_group(block_group,
4420 block_group = bg_ret;
4422 } else if (ret == -EAGAIN) {
4423 goto have_block_group;
4424 } else if (ret > 0) {
4429 ffe_ctl->search_start = round_up(ffe_ctl->found_offset,
4430 fs_info->stripesize);
4432 /* move on to the next group */
4433 if (ffe_ctl->search_start + ffe_ctl->num_bytes >
4434 block_group->start + block_group->length) {
4435 btrfs_add_free_space_unused(block_group,
4436 ffe_ctl->found_offset,
4437 ffe_ctl->num_bytes);
4441 if (ffe_ctl->found_offset < ffe_ctl->search_start)
4442 btrfs_add_free_space_unused(block_group,
4443 ffe_ctl->found_offset,
4444 ffe_ctl->search_start - ffe_ctl->found_offset);
4446 ret = btrfs_add_reserved_bytes(block_group, ffe_ctl->ram_bytes,
4449 if (ret == -EAGAIN) {
4450 btrfs_add_free_space_unused(block_group,
4451 ffe_ctl->found_offset,
4452 ffe_ctl->num_bytes);
4455 btrfs_inc_block_group_reservations(block_group);
4457 /* we are all good, lets return */
4458 ins->objectid = ffe_ctl->search_start;
4459 ins->offset = ffe_ctl->num_bytes;
4461 trace_btrfs_reserve_extent(block_group, ffe_ctl->search_start,
4462 ffe_ctl->num_bytes);
4463 btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4466 release_block_group(block_group, ffe_ctl, ffe_ctl->delalloc);
4469 up_read(&space_info->groups_sem);
4471 ret = find_free_extent_update_loop(fs_info, ins, ffe_ctl, full_search);
4475 if (ret == -ENOSPC && !cache_block_group_error) {
4477 * Use ffe_ctl->total_free_space as fallback if we can't find
4478 * any contiguous hole.
4480 if (!ffe_ctl->max_extent_size)
4481 ffe_ctl->max_extent_size = ffe_ctl->total_free_space;
4482 spin_lock(&space_info->lock);
4483 space_info->max_extent_size = ffe_ctl->max_extent_size;
4484 spin_unlock(&space_info->lock);
4485 ins->offset = ffe_ctl->max_extent_size;
4486 } else if (ret == -ENOSPC) {
4487 ret = cache_block_group_error;
4493 * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
4494 * hole that is at least as big as @num_bytes.
4496 * @root - The root that will contain this extent
4498 * @ram_bytes - The amount of space in ram that @num_bytes take. This
4499 * is used for accounting purposes. This value differs
4500 * from @num_bytes only in the case of compressed extents.
4502 * @num_bytes - Number of bytes to allocate on-disk.
4504 * @min_alloc_size - Indicates the minimum amount of space that the
4505 * allocator should try to satisfy. In some cases
4506 * @num_bytes may be larger than what is required and if
4507 * the filesystem is fragmented then allocation fails.
4508 * However, the presence of @min_alloc_size gives a
4509 * chance to try and satisfy the smaller allocation.
4511 * @empty_size - A hint that you plan on doing more COW. This is the
4512 * size in bytes the allocator should try to find free
4513 * next to the block it returns. This is just a hint and
4514 * may be ignored by the allocator.
4516 * @hint_byte - Hint to the allocator to start searching above the byte
4517 * address passed. It might be ignored.
4519 * @ins - This key is modified to record the found hole. It will
4520 * have the following values:
4521 * ins->objectid == start position
4522 * ins->flags = BTRFS_EXTENT_ITEM_KEY
4523 * ins->offset == the size of the hole.
4525 * @is_data - Boolean flag indicating whether an extent is
4526 * allocated for data (true) or metadata (false)
4528 * @delalloc - Boolean flag indicating whether this allocation is for
4529 * delalloc or not. If 'true' data_rwsem of block groups
4530 * is going to be acquired.
4533 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
4534 * case -ENOSPC is returned then @ins->offset will contain the size of the
4535 * largest available hole the allocator managed to find.
4537 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
4538 u64 num_bytes, u64 min_alloc_size,
4539 u64 empty_size, u64 hint_byte,
4540 struct btrfs_key *ins, int is_data, int delalloc)
4542 struct btrfs_fs_info *fs_info = root->fs_info;
4543 struct find_free_extent_ctl ffe_ctl = {};
4544 bool final_tried = num_bytes == min_alloc_size;
4547 bool for_treelog = (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
4548 bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
4550 flags = get_alloc_profile_by_root(root, is_data);
4552 WARN_ON(num_bytes < fs_info->sectorsize);
4554 ffe_ctl.ram_bytes = ram_bytes;
4555 ffe_ctl.num_bytes = num_bytes;
4556 ffe_ctl.min_alloc_size = min_alloc_size;
4557 ffe_ctl.empty_size = empty_size;
4558 ffe_ctl.flags = flags;
4559 ffe_ctl.delalloc = delalloc;
4560 ffe_ctl.hint_byte = hint_byte;
4561 ffe_ctl.for_treelog = for_treelog;
4562 ffe_ctl.for_data_reloc = for_data_reloc;
4564 ret = find_free_extent(root, ins, &ffe_ctl);
4565 if (!ret && !is_data) {
4566 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
4567 } else if (ret == -ENOSPC) {
4568 if (!final_tried && ins->offset) {
4569 num_bytes = min(num_bytes >> 1, ins->offset);
4570 num_bytes = round_down(num_bytes,
4571 fs_info->sectorsize);
4572 num_bytes = max(num_bytes, min_alloc_size);
4573 ram_bytes = num_bytes;
4574 if (num_bytes == min_alloc_size)
4577 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4578 struct btrfs_space_info *sinfo;
4580 sinfo = btrfs_find_space_info(fs_info, flags);
4582 "allocation failed flags %llu, wanted %llu tree-log %d, relocation: %d",
4583 flags, num_bytes, for_treelog, for_data_reloc);
4585 btrfs_dump_space_info(fs_info, sinfo,
4593 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
4594 u64 start, u64 len, int delalloc)
4596 struct btrfs_block_group *cache;
4598 cache = btrfs_lookup_block_group(fs_info, start);
4600 btrfs_err(fs_info, "Unable to find block group for %llu",
4605 btrfs_add_free_space(cache, start, len);
4606 btrfs_free_reserved_bytes(cache, len, delalloc);
4607 trace_btrfs_reserved_extent_free(fs_info, start, len);
4609 btrfs_put_block_group(cache);
4613 int btrfs_pin_reserved_extent(struct btrfs_trans_handle *trans, u64 start,
4616 struct btrfs_block_group *cache;
4619 cache = btrfs_lookup_block_group(trans->fs_info, start);
4621 btrfs_err(trans->fs_info, "unable to find block group for %llu",
4626 ret = pin_down_extent(trans, cache, start, len, 1);
4627 btrfs_put_block_group(cache);
4631 static int alloc_reserved_extent(struct btrfs_trans_handle *trans, u64 bytenr,
4634 struct btrfs_fs_info *fs_info = trans->fs_info;
4637 ret = remove_from_free_space_tree(trans, bytenr, num_bytes);
4641 ret = btrfs_update_block_group(trans, bytenr, num_bytes, true);
4644 btrfs_err(fs_info, "update block group failed for %llu %llu",
4649 trace_btrfs_reserved_extent_alloc(fs_info, bytenr, num_bytes);
4653 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4654 u64 parent, u64 root_objectid,
4655 u64 flags, u64 owner, u64 offset,
4656 struct btrfs_key *ins, int ref_mod)
4658 struct btrfs_fs_info *fs_info = trans->fs_info;
4659 struct btrfs_root *extent_root;
4661 struct btrfs_extent_item *extent_item;
4662 struct btrfs_extent_inline_ref *iref;
4663 struct btrfs_path *path;
4664 struct extent_buffer *leaf;
4669 type = BTRFS_SHARED_DATA_REF_KEY;
4671 type = BTRFS_EXTENT_DATA_REF_KEY;
4673 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
4675 path = btrfs_alloc_path();
4679 extent_root = btrfs_extent_root(fs_info, ins->objectid);
4680 ret = btrfs_insert_empty_item(trans, extent_root, path, ins, size);
4682 btrfs_free_path(path);
4686 leaf = path->nodes[0];
4687 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4688 struct btrfs_extent_item);
4689 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
4690 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4691 btrfs_set_extent_flags(leaf, extent_item,
4692 flags | BTRFS_EXTENT_FLAG_DATA);
4694 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4695 btrfs_set_extent_inline_ref_type(leaf, iref, type);
4697 struct btrfs_shared_data_ref *ref;
4698 ref = (struct btrfs_shared_data_ref *)(iref + 1);
4699 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
4700 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
4702 struct btrfs_extent_data_ref *ref;
4703 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
4704 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
4705 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
4706 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
4707 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
4710 btrfs_mark_buffer_dirty(path->nodes[0]);
4711 btrfs_free_path(path);
4713 return alloc_reserved_extent(trans, ins->objectid, ins->offset);
4716 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
4717 struct btrfs_delayed_ref_node *node,
4718 struct btrfs_delayed_extent_op *extent_op)
4720 struct btrfs_fs_info *fs_info = trans->fs_info;
4721 struct btrfs_root *extent_root;
4723 struct btrfs_extent_item *extent_item;
4724 struct btrfs_key extent_key;
4725 struct btrfs_tree_block_info *block_info;
4726 struct btrfs_extent_inline_ref *iref;
4727 struct btrfs_path *path;
4728 struct extent_buffer *leaf;
4729 struct btrfs_delayed_tree_ref *ref;
4730 u32 size = sizeof(*extent_item) + sizeof(*iref);
4731 u64 flags = extent_op->flags_to_set;
4732 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4734 ref = btrfs_delayed_node_to_tree_ref(node);
4736 extent_key.objectid = node->bytenr;
4737 if (skinny_metadata) {
4738 extent_key.offset = ref->level;
4739 extent_key.type = BTRFS_METADATA_ITEM_KEY;
4741 extent_key.offset = node->num_bytes;
4742 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
4743 size += sizeof(*block_info);
4746 path = btrfs_alloc_path();
4750 extent_root = btrfs_extent_root(fs_info, extent_key.objectid);
4751 ret = btrfs_insert_empty_item(trans, extent_root, path, &extent_key,
4754 btrfs_free_path(path);
4758 leaf = path->nodes[0];
4759 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4760 struct btrfs_extent_item);
4761 btrfs_set_extent_refs(leaf, extent_item, 1);
4762 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4763 btrfs_set_extent_flags(leaf, extent_item,
4764 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
4766 if (skinny_metadata) {
4767 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4769 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
4770 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
4771 btrfs_set_tree_block_level(leaf, block_info, ref->level);
4772 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
4775 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
4776 btrfs_set_extent_inline_ref_type(leaf, iref,
4777 BTRFS_SHARED_BLOCK_REF_KEY);
4778 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
4780 btrfs_set_extent_inline_ref_type(leaf, iref,
4781 BTRFS_TREE_BLOCK_REF_KEY);
4782 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
4785 btrfs_mark_buffer_dirty(leaf);
4786 btrfs_free_path(path);
4788 return alloc_reserved_extent(trans, node->bytenr, fs_info->nodesize);
4791 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4792 struct btrfs_root *root, u64 owner,
4793 u64 offset, u64 ram_bytes,
4794 struct btrfs_key *ins)
4796 struct btrfs_ref generic_ref = { 0 };
4798 BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
4800 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4801 ins->objectid, ins->offset, 0);
4802 btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner,
4804 btrfs_ref_tree_mod(root->fs_info, &generic_ref);
4806 return btrfs_add_delayed_data_ref(trans, &generic_ref, ram_bytes);
4810 * this is used by the tree logging recovery code. It records that
4811 * an extent has been allocated and makes sure to clear the free
4812 * space cache bits as well
4814 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
4815 u64 root_objectid, u64 owner, u64 offset,
4816 struct btrfs_key *ins)
4818 struct btrfs_fs_info *fs_info = trans->fs_info;
4820 struct btrfs_block_group *block_group;
4821 struct btrfs_space_info *space_info;
4824 * Mixed block groups will exclude before processing the log so we only
4825 * need to do the exclude dance if this fs isn't mixed.
4827 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
4828 ret = __exclude_logged_extent(fs_info, ins->objectid,
4834 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
4838 space_info = block_group->space_info;
4839 spin_lock(&space_info->lock);
4840 spin_lock(&block_group->lock);
4841 space_info->bytes_reserved += ins->offset;
4842 block_group->reserved += ins->offset;
4843 spin_unlock(&block_group->lock);
4844 spin_unlock(&space_info->lock);
4846 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
4849 btrfs_pin_extent(trans, ins->objectid, ins->offset, 1);
4850 btrfs_put_block_group(block_group);
4854 static struct extent_buffer *
4855 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4856 u64 bytenr, int level, u64 owner,
4857 enum btrfs_lock_nesting nest)
4859 struct btrfs_fs_info *fs_info = root->fs_info;
4860 struct extent_buffer *buf;
4861 u64 lockdep_owner = owner;
4863 buf = btrfs_find_create_tree_block(fs_info, bytenr, owner, level);
4868 * Extra safety check in case the extent tree is corrupted and extent
4869 * allocator chooses to use a tree block which is already used and
4872 if (buf->lock_owner == current->pid) {
4873 btrfs_err_rl(fs_info,
4874 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
4875 buf->start, btrfs_header_owner(buf), current->pid);
4876 free_extent_buffer(buf);
4877 return ERR_PTR(-EUCLEAN);
4881 * The reloc trees are just snapshots, so we need them to appear to be
4882 * just like any other fs tree WRT lockdep.
4884 * The exception however is in replace_path() in relocation, where we
4885 * hold the lock on the original fs root and then search for the reloc
4886 * root. At that point we need to make sure any reloc root buffers are
4887 * set to the BTRFS_TREE_RELOC_OBJECTID lockdep class in order to make
4890 if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID &&
4891 !test_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &root->state))
4892 lockdep_owner = BTRFS_FS_TREE_OBJECTID;
4894 /* btrfs_clean_tree_block() accesses generation field. */
4895 btrfs_set_header_generation(buf, trans->transid);
4898 * This needs to stay, because we could allocate a freed block from an
4899 * old tree into a new tree, so we need to make sure this new block is
4900 * set to the appropriate level and owner.
4902 btrfs_set_buffer_lockdep_class(lockdep_owner, buf, level);
4904 __btrfs_tree_lock(buf, nest);
4905 btrfs_clean_tree_block(buf);
4906 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
4907 clear_bit(EXTENT_BUFFER_NO_CHECK, &buf->bflags);
4909 set_extent_buffer_uptodate(buf);
4911 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
4912 btrfs_set_header_level(buf, level);
4913 btrfs_set_header_bytenr(buf, buf->start);
4914 btrfs_set_header_generation(buf, trans->transid);
4915 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
4916 btrfs_set_header_owner(buf, owner);
4917 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
4918 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
4919 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
4920 buf->log_index = root->log_transid % 2;
4922 * we allow two log transactions at a time, use different
4923 * EXTENT bit to differentiate dirty pages.
4925 if (buf->log_index == 0)
4926 set_extent_dirty(&root->dirty_log_pages, buf->start,
4927 buf->start + buf->len - 1, GFP_NOFS);
4929 set_extent_new(&root->dirty_log_pages, buf->start,
4930 buf->start + buf->len - 1);
4932 buf->log_index = -1;
4933 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
4934 buf->start + buf->len - 1, GFP_NOFS);
4936 /* this returns a buffer locked for blocking */
4941 * finds a free extent and does all the dirty work required for allocation
4942 * returns the tree buffer or an ERR_PTR on error.
4944 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
4945 struct btrfs_root *root,
4946 u64 parent, u64 root_objectid,
4947 const struct btrfs_disk_key *key,
4948 int level, u64 hint,
4950 enum btrfs_lock_nesting nest)
4952 struct btrfs_fs_info *fs_info = root->fs_info;
4953 struct btrfs_key ins;
4954 struct btrfs_block_rsv *block_rsv;
4955 struct extent_buffer *buf;
4956 struct btrfs_delayed_extent_op *extent_op;
4957 struct btrfs_ref generic_ref = { 0 };
4960 u32 blocksize = fs_info->nodesize;
4961 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4963 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4964 if (btrfs_is_testing(fs_info)) {
4965 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
4966 level, root_objectid, nest);
4968 root->alloc_bytenr += blocksize;
4973 block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
4974 if (IS_ERR(block_rsv))
4975 return ERR_CAST(block_rsv);
4977 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
4978 empty_size, hint, &ins, 0, 0);
4982 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
4983 root_objectid, nest);
4986 goto out_free_reserved;
4989 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
4991 parent = ins.objectid;
4992 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4996 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
4997 extent_op = btrfs_alloc_delayed_extent_op();
5003 memcpy(&extent_op->key, key, sizeof(extent_op->key));
5005 memset(&extent_op->key, 0, sizeof(extent_op->key));
5006 extent_op->flags_to_set = flags;
5007 extent_op->update_key = skinny_metadata ? false : true;
5008 extent_op->update_flags = true;
5009 extent_op->level = level;
5011 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
5012 ins.objectid, ins.offset, parent);
5013 btrfs_init_tree_ref(&generic_ref, level, root_objectid,
5014 root->root_key.objectid, false);
5015 btrfs_ref_tree_mod(fs_info, &generic_ref);
5016 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, extent_op);
5018 goto out_free_delayed;
5023 btrfs_free_delayed_extent_op(extent_op);
5025 btrfs_tree_unlock(buf);
5026 free_extent_buffer(buf);
5028 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
5030 btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
5031 return ERR_PTR(ret);
5034 struct walk_control {
5035 u64 refs[BTRFS_MAX_LEVEL];
5036 u64 flags[BTRFS_MAX_LEVEL];
5037 struct btrfs_key update_progress;
5038 struct btrfs_key drop_progress;
5050 #define DROP_REFERENCE 1
5051 #define UPDATE_BACKREF 2
5053 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
5054 struct btrfs_root *root,
5055 struct walk_control *wc,
5056 struct btrfs_path *path)
5058 struct btrfs_fs_info *fs_info = root->fs_info;
5064 struct btrfs_key key;
5065 struct extent_buffer *eb;
5070 if (path->slots[wc->level] < wc->reada_slot) {
5071 wc->reada_count = wc->reada_count * 2 / 3;
5072 wc->reada_count = max(wc->reada_count, 2);
5074 wc->reada_count = wc->reada_count * 3 / 2;
5075 wc->reada_count = min_t(int, wc->reada_count,
5076 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
5079 eb = path->nodes[wc->level];
5080 nritems = btrfs_header_nritems(eb);
5082 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
5083 if (nread >= wc->reada_count)
5087 bytenr = btrfs_node_blockptr(eb, slot);
5088 generation = btrfs_node_ptr_generation(eb, slot);
5090 if (slot == path->slots[wc->level])
5093 if (wc->stage == UPDATE_BACKREF &&
5094 generation <= root->root_key.offset)
5097 /* We don't lock the tree block, it's OK to be racy here */
5098 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
5099 wc->level - 1, 1, &refs,
5101 /* We don't care about errors in readahead. */
5106 if (wc->stage == DROP_REFERENCE) {
5110 if (wc->level == 1 &&
5111 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5113 if (!wc->update_ref ||
5114 generation <= root->root_key.offset)
5116 btrfs_node_key_to_cpu(eb, &key, slot);
5117 ret = btrfs_comp_cpu_keys(&key,
5118 &wc->update_progress);
5122 if (wc->level == 1 &&
5123 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5127 btrfs_readahead_node_child(eb, slot);
5130 wc->reada_slot = slot;
5134 * helper to process tree block while walking down the tree.
5136 * when wc->stage == UPDATE_BACKREF, this function updates
5137 * back refs for pointers in the block.
5139 * NOTE: return value 1 means we should stop walking down.
5141 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5142 struct btrfs_root *root,
5143 struct btrfs_path *path,
5144 struct walk_control *wc, int lookup_info)
5146 struct btrfs_fs_info *fs_info = root->fs_info;
5147 int level = wc->level;
5148 struct extent_buffer *eb = path->nodes[level];
5149 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5152 if (wc->stage == UPDATE_BACKREF &&
5153 btrfs_header_owner(eb) != root->root_key.objectid)
5157 * when reference count of tree block is 1, it won't increase
5158 * again. once full backref flag is set, we never clear it.
5161 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
5162 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
5163 BUG_ON(!path->locks[level]);
5164 ret = btrfs_lookup_extent_info(trans, fs_info,
5165 eb->start, level, 1,
5168 BUG_ON(ret == -ENOMEM);
5171 BUG_ON(wc->refs[level] == 0);
5174 if (wc->stage == DROP_REFERENCE) {
5175 if (wc->refs[level] > 1)
5178 if (path->locks[level] && !wc->keep_locks) {
5179 btrfs_tree_unlock_rw(eb, path->locks[level]);
5180 path->locks[level] = 0;
5185 /* wc->stage == UPDATE_BACKREF */
5186 if (!(wc->flags[level] & flag)) {
5187 BUG_ON(!path->locks[level]);
5188 ret = btrfs_inc_ref(trans, root, eb, 1);
5189 BUG_ON(ret); /* -ENOMEM */
5190 ret = btrfs_dec_ref(trans, root, eb, 0);
5191 BUG_ON(ret); /* -ENOMEM */
5192 ret = btrfs_set_disk_extent_flags(trans, eb, flag,
5193 btrfs_header_level(eb));
5194 BUG_ON(ret); /* -ENOMEM */
5195 wc->flags[level] |= flag;
5199 * the block is shared by multiple trees, so it's not good to
5200 * keep the tree lock
5202 if (path->locks[level] && level > 0) {
5203 btrfs_tree_unlock_rw(eb, path->locks[level]);
5204 path->locks[level] = 0;
5210 * This is used to verify a ref exists for this root to deal with a bug where we
5211 * would have a drop_progress key that hadn't been updated properly.
5213 static int check_ref_exists(struct btrfs_trans_handle *trans,
5214 struct btrfs_root *root, u64 bytenr, u64 parent,
5217 struct btrfs_path *path;
5218 struct btrfs_extent_inline_ref *iref;
5221 path = btrfs_alloc_path();
5225 ret = lookup_extent_backref(trans, path, &iref, bytenr,
5226 root->fs_info->nodesize, parent,
5227 root->root_key.objectid, level, 0);
5228 btrfs_free_path(path);
5237 * helper to process tree block pointer.
5239 * when wc->stage == DROP_REFERENCE, this function checks
5240 * reference count of the block pointed to. if the block
5241 * is shared and we need update back refs for the subtree
5242 * rooted at the block, this function changes wc->stage to
5243 * UPDATE_BACKREF. if the block is shared and there is no
5244 * need to update back, this function drops the reference
5247 * NOTE: return value 1 means we should stop walking down.
5249 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
5250 struct btrfs_root *root,
5251 struct btrfs_path *path,
5252 struct walk_control *wc, int *lookup_info)
5254 struct btrfs_fs_info *fs_info = root->fs_info;
5258 struct btrfs_key key;
5259 struct btrfs_key first_key;
5260 struct btrfs_ref ref = { 0 };
5261 struct extent_buffer *next;
5262 int level = wc->level;
5265 bool need_account = false;
5267 generation = btrfs_node_ptr_generation(path->nodes[level],
5268 path->slots[level]);
5270 * if the lower level block was created before the snapshot
5271 * was created, we know there is no need to update back refs
5274 if (wc->stage == UPDATE_BACKREF &&
5275 generation <= root->root_key.offset) {
5280 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
5281 btrfs_node_key_to_cpu(path->nodes[level], &first_key,
5282 path->slots[level]);
5284 next = find_extent_buffer(fs_info, bytenr);
5286 next = btrfs_find_create_tree_block(fs_info, bytenr,
5287 root->root_key.objectid, level - 1);
5289 return PTR_ERR(next);
5292 btrfs_tree_lock(next);
5294 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
5295 &wc->refs[level - 1],
5296 &wc->flags[level - 1]);
5300 if (unlikely(wc->refs[level - 1] == 0)) {
5301 btrfs_err(fs_info, "Missing references.");
5307 if (wc->stage == DROP_REFERENCE) {
5308 if (wc->refs[level - 1] > 1) {
5309 need_account = true;
5311 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5314 if (!wc->update_ref ||
5315 generation <= root->root_key.offset)
5318 btrfs_node_key_to_cpu(path->nodes[level], &key,
5319 path->slots[level]);
5320 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
5324 wc->stage = UPDATE_BACKREF;
5325 wc->shared_level = level - 1;
5329 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5333 if (!btrfs_buffer_uptodate(next, generation, 0)) {
5334 btrfs_tree_unlock(next);
5335 free_extent_buffer(next);
5341 if (reada && level == 1)
5342 reada_walk_down(trans, root, wc, path);
5343 next = read_tree_block(fs_info, bytenr, root->root_key.objectid,
5344 generation, level - 1, &first_key);
5346 return PTR_ERR(next);
5347 } else if (!extent_buffer_uptodate(next)) {
5348 free_extent_buffer(next);
5351 btrfs_tree_lock(next);
5355 ASSERT(level == btrfs_header_level(next));
5356 if (level != btrfs_header_level(next)) {
5357 btrfs_err(root->fs_info, "mismatched level");
5361 path->nodes[level] = next;
5362 path->slots[level] = 0;
5363 path->locks[level] = BTRFS_WRITE_LOCK;
5369 wc->refs[level - 1] = 0;
5370 wc->flags[level - 1] = 0;
5371 if (wc->stage == DROP_REFERENCE) {
5372 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5373 parent = path->nodes[level]->start;
5375 ASSERT(root->root_key.objectid ==
5376 btrfs_header_owner(path->nodes[level]));
5377 if (root->root_key.objectid !=
5378 btrfs_header_owner(path->nodes[level])) {
5379 btrfs_err(root->fs_info,
5380 "mismatched block owner");
5388 * If we had a drop_progress we need to verify the refs are set
5389 * as expected. If we find our ref then we know that from here
5390 * on out everything should be correct, and we can clear the
5393 if (wc->restarted) {
5394 ret = check_ref_exists(trans, root, bytenr, parent,
5405 * Reloc tree doesn't contribute to qgroup numbers, and we have
5406 * already accounted them at merge time (replace_path),
5407 * thus we could skip expensive subtree trace here.
5409 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
5411 ret = btrfs_qgroup_trace_subtree(trans, next,
5412 generation, level - 1);
5414 btrfs_err_rl(fs_info,
5415 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
5421 * We need to update the next key in our walk control so we can
5422 * update the drop_progress key accordingly. We don't care if
5423 * find_next_key doesn't find a key because that means we're at
5424 * the end and are going to clean up now.
5426 wc->drop_level = level;
5427 find_next_key(path, level, &wc->drop_progress);
5429 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
5430 fs_info->nodesize, parent);
5431 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid,
5433 ret = btrfs_free_extent(trans, &ref);
5442 btrfs_tree_unlock(next);
5443 free_extent_buffer(next);
5449 * helper to process tree block while walking up the tree.
5451 * when wc->stage == DROP_REFERENCE, this function drops
5452 * reference count on the block.
5454 * when wc->stage == UPDATE_BACKREF, this function changes
5455 * wc->stage back to DROP_REFERENCE if we changed wc->stage
5456 * to UPDATE_BACKREF previously while processing the block.
5458 * NOTE: return value 1 means we should stop walking up.
5460 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
5461 struct btrfs_root *root,
5462 struct btrfs_path *path,
5463 struct walk_control *wc)
5465 struct btrfs_fs_info *fs_info = root->fs_info;
5467 int level = wc->level;
5468 struct extent_buffer *eb = path->nodes[level];
5471 if (wc->stage == UPDATE_BACKREF) {
5472 BUG_ON(wc->shared_level < level);
5473 if (level < wc->shared_level)
5476 ret = find_next_key(path, level + 1, &wc->update_progress);
5480 wc->stage = DROP_REFERENCE;
5481 wc->shared_level = -1;
5482 path->slots[level] = 0;
5485 * check reference count again if the block isn't locked.
5486 * we should start walking down the tree again if reference
5489 if (!path->locks[level]) {
5491 btrfs_tree_lock(eb);
5492 path->locks[level] = BTRFS_WRITE_LOCK;
5494 ret = btrfs_lookup_extent_info(trans, fs_info,
5495 eb->start, level, 1,
5499 btrfs_tree_unlock_rw(eb, path->locks[level]);
5500 path->locks[level] = 0;
5503 BUG_ON(wc->refs[level] == 0);
5504 if (wc->refs[level] == 1) {
5505 btrfs_tree_unlock_rw(eb, path->locks[level]);
5506 path->locks[level] = 0;
5512 /* wc->stage == DROP_REFERENCE */
5513 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5515 if (wc->refs[level] == 1) {
5517 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5518 ret = btrfs_dec_ref(trans, root, eb, 1);
5520 ret = btrfs_dec_ref(trans, root, eb, 0);
5521 BUG_ON(ret); /* -ENOMEM */
5522 if (is_fstree(root->root_key.objectid)) {
5523 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
5525 btrfs_err_rl(fs_info,
5526 "error %d accounting leaf items, quota is out of sync, rescan required",
5531 /* make block locked assertion in btrfs_clean_tree_block happy */
5532 if (!path->locks[level] &&
5533 btrfs_header_generation(eb) == trans->transid) {
5534 btrfs_tree_lock(eb);
5535 path->locks[level] = BTRFS_WRITE_LOCK;
5537 btrfs_clean_tree_block(eb);
5540 if (eb == root->node) {
5541 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5543 else if (root->root_key.objectid != btrfs_header_owner(eb))
5544 goto owner_mismatch;
5546 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5547 parent = path->nodes[level + 1]->start;
5548 else if (root->root_key.objectid !=
5549 btrfs_header_owner(path->nodes[level + 1]))
5550 goto owner_mismatch;
5553 btrfs_free_tree_block(trans, btrfs_root_id(root), eb, parent,
5554 wc->refs[level] == 1);
5556 wc->refs[level] = 0;
5557 wc->flags[level] = 0;
5561 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
5562 btrfs_header_owner(eb), root->root_key.objectid);
5566 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
5567 struct btrfs_root *root,
5568 struct btrfs_path *path,
5569 struct walk_control *wc)
5571 int level = wc->level;
5572 int lookup_info = 1;
5575 while (level >= 0) {
5576 ret = walk_down_proc(trans, root, path, wc, lookup_info);
5583 if (path->slots[level] >=
5584 btrfs_header_nritems(path->nodes[level]))
5587 ret = do_walk_down(trans, root, path, wc, &lookup_info);
5589 path->slots[level]++;
5598 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
5599 struct btrfs_root *root,
5600 struct btrfs_path *path,
5601 struct walk_control *wc, int max_level)
5603 int level = wc->level;
5606 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
5607 while (level < max_level && path->nodes[level]) {
5609 if (path->slots[level] + 1 <
5610 btrfs_header_nritems(path->nodes[level])) {
5611 path->slots[level]++;
5614 ret = walk_up_proc(trans, root, path, wc);
5620 if (path->locks[level]) {
5621 btrfs_tree_unlock_rw(path->nodes[level],
5622 path->locks[level]);
5623 path->locks[level] = 0;
5625 free_extent_buffer(path->nodes[level]);
5626 path->nodes[level] = NULL;
5634 * drop a subvolume tree.
5636 * this function traverses the tree freeing any blocks that only
5637 * referenced by the tree.
5639 * when a shared tree block is found. this function decreases its
5640 * reference count by one. if update_ref is true, this function
5641 * also make sure backrefs for the shared block and all lower level
5642 * blocks are properly updated.
5644 * If called with for_reloc == 0, may exit early with -EAGAIN
5646 int btrfs_drop_snapshot(struct btrfs_root *root, int update_ref, int for_reloc)
5648 const bool is_reloc_root = (root->root_key.objectid ==
5649 BTRFS_TREE_RELOC_OBJECTID);
5650 struct btrfs_fs_info *fs_info = root->fs_info;
5651 struct btrfs_path *path;
5652 struct btrfs_trans_handle *trans;
5653 struct btrfs_root *tree_root = fs_info->tree_root;
5654 struct btrfs_root_item *root_item = &root->root_item;
5655 struct walk_control *wc;
5656 struct btrfs_key key;
5660 bool root_dropped = false;
5661 bool unfinished_drop = false;
5663 btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
5665 path = btrfs_alloc_path();
5671 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5673 btrfs_free_path(path);
5679 * Use join to avoid potential EINTR from transaction start. See
5680 * wait_reserve_ticket and the whole reservation callchain.
5683 trans = btrfs_join_transaction(tree_root);
5685 trans = btrfs_start_transaction(tree_root, 0);
5686 if (IS_ERR(trans)) {
5687 err = PTR_ERR(trans);
5691 err = btrfs_run_delayed_items(trans);
5696 * This will help us catch people modifying the fs tree while we're
5697 * dropping it. It is unsafe to mess with the fs tree while it's being
5698 * dropped as we unlock the root node and parent nodes as we walk down
5699 * the tree, assuming nothing will change. If something does change
5700 * then we'll have stale information and drop references to blocks we've
5703 set_bit(BTRFS_ROOT_DELETING, &root->state);
5704 unfinished_drop = test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state);
5706 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
5707 level = btrfs_header_level(root->node);
5708 path->nodes[level] = btrfs_lock_root_node(root);
5709 path->slots[level] = 0;
5710 path->locks[level] = BTRFS_WRITE_LOCK;
5711 memset(&wc->update_progress, 0,
5712 sizeof(wc->update_progress));
5714 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
5715 memcpy(&wc->update_progress, &key,
5716 sizeof(wc->update_progress));
5718 level = btrfs_root_drop_level(root_item);
5720 path->lowest_level = level;
5721 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5722 path->lowest_level = 0;
5730 * unlock our path, this is safe because only this
5731 * function is allowed to delete this snapshot
5733 btrfs_unlock_up_safe(path, 0);
5735 level = btrfs_header_level(root->node);
5737 btrfs_tree_lock(path->nodes[level]);
5738 path->locks[level] = BTRFS_WRITE_LOCK;
5740 ret = btrfs_lookup_extent_info(trans, fs_info,
5741 path->nodes[level]->start,
5742 level, 1, &wc->refs[level],
5748 BUG_ON(wc->refs[level] == 0);
5750 if (level == btrfs_root_drop_level(root_item))
5753 btrfs_tree_unlock(path->nodes[level]);
5754 path->locks[level] = 0;
5755 WARN_ON(wc->refs[level] != 1);
5760 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
5762 wc->shared_level = -1;
5763 wc->stage = DROP_REFERENCE;
5764 wc->update_ref = update_ref;
5766 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5770 ret = walk_down_tree(trans, root, path, wc);
5776 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
5783 BUG_ON(wc->stage != DROP_REFERENCE);
5787 if (wc->stage == DROP_REFERENCE) {
5788 wc->drop_level = wc->level;
5789 btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
5791 path->slots[wc->drop_level]);
5793 btrfs_cpu_key_to_disk(&root_item->drop_progress,
5794 &wc->drop_progress);
5795 btrfs_set_root_drop_level(root_item, wc->drop_level);
5797 BUG_ON(wc->level == 0);
5798 if (btrfs_should_end_transaction(trans) ||
5799 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
5800 ret = btrfs_update_root(trans, tree_root,
5804 btrfs_abort_transaction(trans, ret);
5810 btrfs_set_last_root_drop_gen(fs_info, trans->transid);
5812 btrfs_end_transaction_throttle(trans);
5813 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
5814 btrfs_debug(fs_info,
5815 "drop snapshot early exit");
5821 * Use join to avoid potential EINTR from transaction
5822 * start. See wait_reserve_ticket and the whole
5823 * reservation callchain.
5826 trans = btrfs_join_transaction(tree_root);
5828 trans = btrfs_start_transaction(tree_root, 0);
5829 if (IS_ERR(trans)) {
5830 err = PTR_ERR(trans);
5835 btrfs_release_path(path);
5839 ret = btrfs_del_root(trans, &root->root_key);
5841 btrfs_abort_transaction(trans, ret);
5846 if (!is_reloc_root) {
5847 ret = btrfs_find_root(tree_root, &root->root_key, path,
5850 btrfs_abort_transaction(trans, ret);
5853 } else if (ret > 0) {
5854 /* if we fail to delete the orphan item this time
5855 * around, it'll get picked up the next time.
5857 * The most common failure here is just -ENOENT.
5859 btrfs_del_orphan_item(trans, tree_root,
5860 root->root_key.objectid);
5865 * This subvolume is going to be completely dropped, and won't be
5866 * recorded as dirty roots, thus pertrans meta rsv will not be freed at
5867 * commit transaction time. So free it here manually.
5869 btrfs_qgroup_convert_reserved_meta(root, INT_MAX);
5870 btrfs_qgroup_free_meta_all_pertrans(root);
5872 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state))
5873 btrfs_add_dropped_root(trans, root);
5875 btrfs_put_root(root);
5876 root_dropped = true;
5879 btrfs_set_last_root_drop_gen(fs_info, trans->transid);
5881 btrfs_end_transaction_throttle(trans);
5884 btrfs_free_path(path);
5887 * We were an unfinished drop root, check to see if there are any
5888 * pending, and if not clear and wake up any waiters.
5890 if (!err && unfinished_drop)
5891 btrfs_maybe_wake_unfinished_drop(fs_info);
5894 * So if we need to stop dropping the snapshot for whatever reason we
5895 * need to make sure to add it back to the dead root list so that we
5896 * keep trying to do the work later. This also cleans up roots if we
5897 * don't have it in the radix (like when we recover after a power fail
5898 * or unmount) so we don't leak memory.
5900 if (!for_reloc && !root_dropped)
5901 btrfs_add_dead_root(root);
5906 * drop subtree rooted at tree block 'node'.
5908 * NOTE: this function will unlock and release tree block 'node'
5909 * only used by relocation code
5911 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
5912 struct btrfs_root *root,
5913 struct extent_buffer *node,
5914 struct extent_buffer *parent)
5916 struct btrfs_fs_info *fs_info = root->fs_info;
5917 struct btrfs_path *path;
5918 struct walk_control *wc;
5924 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
5926 path = btrfs_alloc_path();
5930 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5932 btrfs_free_path(path);
5936 btrfs_assert_tree_write_locked(parent);
5937 parent_level = btrfs_header_level(parent);
5938 atomic_inc(&parent->refs);
5939 path->nodes[parent_level] = parent;
5940 path->slots[parent_level] = btrfs_header_nritems(parent);
5942 btrfs_assert_tree_write_locked(node);
5943 level = btrfs_header_level(node);
5944 path->nodes[level] = node;
5945 path->slots[level] = 0;
5946 path->locks[level] = BTRFS_WRITE_LOCK;
5948 wc->refs[parent_level] = 1;
5949 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5951 wc->shared_level = -1;
5952 wc->stage = DROP_REFERENCE;
5955 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5958 wret = walk_down_tree(trans, root, path, wc);
5964 wret = walk_up_tree(trans, root, path, wc, parent_level);
5972 btrfs_free_path(path);
5977 * helper to account the unused space of all the readonly block group in the
5978 * space_info. takes mirrors into account.
5980 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
5982 struct btrfs_block_group *block_group;
5986 /* It's df, we don't care if it's racy */
5987 if (list_empty(&sinfo->ro_bgs))
5990 spin_lock(&sinfo->lock);
5991 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
5992 spin_lock(&block_group->lock);
5994 if (!block_group->ro) {
5995 spin_unlock(&block_group->lock);
5999 factor = btrfs_bg_type_to_factor(block_group->flags);
6000 free_bytes += (block_group->length -
6001 block_group->used) * factor;
6003 spin_unlock(&block_group->lock);
6005 spin_unlock(&sinfo->lock);
6010 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
6013 return unpin_extent_range(fs_info, start, end, false);
6017 * It used to be that old block groups would be left around forever.
6018 * Iterating over them would be enough to trim unused space. Since we
6019 * now automatically remove them, we also need to iterate over unallocated
6022 * We don't want a transaction for this since the discard may take a
6023 * substantial amount of time. We don't require that a transaction be
6024 * running, but we do need to take a running transaction into account
6025 * to ensure that we're not discarding chunks that were released or
6026 * allocated in the current transaction.
6028 * Holding the chunks lock will prevent other threads from allocating
6029 * or releasing chunks, but it won't prevent a running transaction
6030 * from committing and releasing the memory that the pending chunks
6031 * list head uses. For that, we need to take a reference to the
6032 * transaction and hold the commit root sem. We only need to hold
6033 * it while performing the free space search since we have already
6034 * held back allocations.
6036 static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
6038 u64 start = BTRFS_DEVICE_RANGE_RESERVED, len = 0, end = 0;
6043 /* Discard not supported = nothing to do. */
6044 if (!bdev_max_discard_sectors(device->bdev))
6047 /* Not writable = nothing to do. */
6048 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
6051 /* No free space = nothing to do. */
6052 if (device->total_bytes <= device->bytes_used)
6058 struct btrfs_fs_info *fs_info = device->fs_info;
6061 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
6065 find_first_clear_extent_bit(&device->alloc_state, start,
6067 CHUNK_TRIMMED | CHUNK_ALLOCATED);
6069 /* Check if there are any CHUNK_* bits left */
6070 if (start > device->total_bytes) {
6071 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
6072 btrfs_warn_in_rcu(fs_info,
6073 "ignoring attempt to trim beyond device size: offset %llu length %llu device %s device size %llu",
6074 start, end - start + 1,
6075 rcu_str_deref(device->name),
6076 device->total_bytes);
6077 mutex_unlock(&fs_info->chunk_mutex);
6082 /* Ensure we skip the reserved space on each device. */
6083 start = max_t(u64, start, BTRFS_DEVICE_RANGE_RESERVED);
6086 * If find_first_clear_extent_bit find a range that spans the
6087 * end of the device it will set end to -1, in this case it's up
6088 * to the caller to trim the value to the size of the device.
6090 end = min(end, device->total_bytes - 1);
6092 len = end - start + 1;
6094 /* We didn't find any extents */
6096 mutex_unlock(&fs_info->chunk_mutex);
6101 ret = btrfs_issue_discard(device->bdev, start, len,
6104 set_extent_bits(&device->alloc_state, start,
6107 mutex_unlock(&fs_info->chunk_mutex);
6115 if (fatal_signal_pending(current)) {
6127 * Trim the whole filesystem by:
6128 * 1) trimming the free space in each block group
6129 * 2) trimming the unallocated space on each device
6131 * This will also continue trimming even if a block group or device encounters
6132 * an error. The return value will be the last error, or 0 if nothing bad
6135 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
6137 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6138 struct btrfs_block_group *cache = NULL;
6139 struct btrfs_device *device;
6141 u64 range_end = U64_MAX;
6151 if (range->start == U64_MAX)
6155 * Check range overflow if range->len is set.
6156 * The default range->len is U64_MAX.
6158 if (range->len != U64_MAX &&
6159 check_add_overflow(range->start, range->len, &range_end))
6162 cache = btrfs_lookup_first_block_group(fs_info, range->start);
6163 for (; cache; cache = btrfs_next_block_group(cache)) {
6164 if (cache->start >= range_end) {
6165 btrfs_put_block_group(cache);
6169 start = max(range->start, cache->start);
6170 end = min(range_end, cache->start + cache->length);
6172 if (end - start >= range->minlen) {
6173 if (!btrfs_block_group_done(cache)) {
6174 ret = btrfs_cache_block_group(cache, true);
6181 ret = btrfs_trim_block_group(cache,
6187 trimmed += group_trimmed;
6198 "failed to trim %llu block group(s), last error %d",
6201 mutex_lock(&fs_devices->device_list_mutex);
6202 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6203 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
6206 ret = btrfs_trim_free_extents(device, &group_trimmed);
6213 trimmed += group_trimmed;
6215 mutex_unlock(&fs_devices->device_list_mutex);
6219 "failed to trim %llu device(s), last error %d",
6220 dev_failed, dev_ret);
6221 range->len = trimmed;