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>
20 #include "extent-tree.h"
23 #include "print-tree.h"
27 #include "free-space-cache.h"
28 #include "free-space-tree.h"
31 #include "ref-verify.h"
32 #include "space-info.h"
33 #include "block-rsv.h"
34 #include "delalloc-space.h"
36 #include "rcu-string.h"
38 #include "dev-replace.h"
40 #include "accessors.h"
41 #include "root-tree.h"
42 #include "file-item.h"
44 #include "tree-checker.h"
46 #undef SCRAMBLE_DELAYED_REFS
49 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
50 struct btrfs_delayed_ref_node *node, u64 parent,
51 u64 root_objectid, u64 owner_objectid,
53 struct btrfs_delayed_extent_op *extra_op);
54 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
55 struct extent_buffer *leaf,
56 struct btrfs_extent_item *ei);
57 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
58 u64 parent, u64 root_objectid,
59 u64 flags, u64 owner, u64 offset,
60 struct btrfs_key *ins, int ref_mod);
61 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
62 struct btrfs_delayed_ref_node *node,
63 struct btrfs_delayed_extent_op *extent_op);
64 static int find_next_key(struct btrfs_path *path, int level,
65 struct btrfs_key *key);
67 static int block_group_bits(struct btrfs_block_group *cache, u64 bits)
69 return (cache->flags & bits) == bits;
72 /* simple helper to search for an existing data extent at a given offset */
73 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
75 struct btrfs_root *root = btrfs_extent_root(fs_info, start);
78 struct btrfs_path *path;
80 path = btrfs_alloc_path();
86 key.type = BTRFS_EXTENT_ITEM_KEY;
87 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
88 btrfs_free_path(path);
93 * helper function to lookup reference count and flags of a tree block.
95 * the head node for delayed ref is used to store the sum of all the
96 * reference count modifications queued up in the rbtree. the head
97 * node may also store the extent flags to set. This way you can check
98 * to see what the reference count and extent flags would be if all of
99 * the delayed refs are not processed.
101 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
102 struct btrfs_fs_info *fs_info, u64 bytenr,
103 u64 offset, int metadata, u64 *refs, u64 *flags)
105 struct btrfs_root *extent_root;
106 struct btrfs_delayed_ref_head *head;
107 struct btrfs_delayed_ref_root *delayed_refs;
108 struct btrfs_path *path;
109 struct btrfs_extent_item *ei;
110 struct extent_buffer *leaf;
111 struct btrfs_key key;
118 * If we don't have skinny metadata, don't bother doing anything
121 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
122 offset = fs_info->nodesize;
126 path = btrfs_alloc_path();
131 path->skip_locking = 1;
132 path->search_commit_root = 1;
136 key.objectid = bytenr;
139 key.type = BTRFS_METADATA_ITEM_KEY;
141 key.type = BTRFS_EXTENT_ITEM_KEY;
143 extent_root = btrfs_extent_root(fs_info, bytenr);
144 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
148 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
149 if (path->slots[0]) {
151 btrfs_item_key_to_cpu(path->nodes[0], &key,
153 if (key.objectid == bytenr &&
154 key.type == BTRFS_EXTENT_ITEM_KEY &&
155 key.offset == fs_info->nodesize)
161 leaf = path->nodes[0];
162 item_size = btrfs_item_size(leaf, path->slots[0]);
163 if (item_size >= sizeof(*ei)) {
164 ei = btrfs_item_ptr(leaf, path->slots[0],
165 struct btrfs_extent_item);
166 num_refs = btrfs_extent_refs(leaf, ei);
167 extent_flags = btrfs_extent_flags(leaf, ei);
171 "unexpected extent item size, has %u expect >= %zu",
172 item_size, sizeof(*ei));
174 btrfs_abort_transaction(trans, ret);
176 btrfs_handle_fs_error(fs_info, ret, NULL);
181 BUG_ON(num_refs == 0);
191 delayed_refs = &trans->transaction->delayed_refs;
192 spin_lock(&delayed_refs->lock);
193 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
195 if (!mutex_trylock(&head->mutex)) {
196 refcount_inc(&head->refs);
197 spin_unlock(&delayed_refs->lock);
199 btrfs_release_path(path);
202 * Mutex was contended, block until it's released and try
205 mutex_lock(&head->mutex);
206 mutex_unlock(&head->mutex);
207 btrfs_put_delayed_ref_head(head);
210 spin_lock(&head->lock);
211 if (head->extent_op && head->extent_op->update_flags)
212 extent_flags |= head->extent_op->flags_to_set;
214 BUG_ON(num_refs == 0);
216 num_refs += head->ref_mod;
217 spin_unlock(&head->lock);
218 mutex_unlock(&head->mutex);
220 spin_unlock(&delayed_refs->lock);
222 WARN_ON(num_refs == 0);
226 *flags = extent_flags;
228 btrfs_free_path(path);
233 * Back reference rules. Back refs have three main goals:
235 * 1) differentiate between all holders of references to an extent so that
236 * when a reference is dropped we can make sure it was a valid reference
237 * before freeing the extent.
239 * 2) Provide enough information to quickly find the holders of an extent
240 * if we notice a given block is corrupted or bad.
242 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
243 * maintenance. This is actually the same as #2, but with a slightly
244 * different use case.
246 * There are two kinds of back refs. The implicit back refs is optimized
247 * for pointers in non-shared tree blocks. For a given pointer in a block,
248 * back refs of this kind provide information about the block's owner tree
249 * and the pointer's key. These information allow us to find the block by
250 * b-tree searching. The full back refs is for pointers in tree blocks not
251 * referenced by their owner trees. The location of tree block is recorded
252 * in the back refs. Actually the full back refs is generic, and can be
253 * used in all cases the implicit back refs is used. The major shortcoming
254 * of the full back refs is its overhead. Every time a tree block gets
255 * COWed, we have to update back refs entry for all pointers in it.
257 * For a newly allocated tree block, we use implicit back refs for
258 * pointers in it. This means most tree related operations only involve
259 * implicit back refs. For a tree block created in old transaction, the
260 * only way to drop a reference to it is COW it. So we can detect the
261 * event that tree block loses its owner tree's reference and do the
262 * back refs conversion.
264 * When a tree block is COWed through a tree, there are four cases:
266 * The reference count of the block is one and the tree is the block's
267 * owner tree. Nothing to do in this case.
269 * The reference count of the block is one and the tree is not the
270 * block's owner tree. In this case, full back refs is used for pointers
271 * in the block. Remove these full back refs, add implicit back refs for
272 * every pointers in the new block.
274 * The reference count of the block is greater than one and the tree is
275 * the block's owner tree. In this case, implicit back refs is used for
276 * pointers in the block. Add full back refs for every pointers in the
277 * block, increase lower level extents' reference counts. The original
278 * implicit back refs are entailed to the new block.
280 * The reference count of the block is greater than one and the tree is
281 * not the block's owner tree. Add implicit back refs for every pointer in
282 * the new block, increase lower level extents' reference count.
284 * Back Reference Key composing:
286 * The key objectid corresponds to the first byte in the extent,
287 * The key type is used to differentiate between types of back refs.
288 * There are different meanings of the key offset for different types
291 * File extents can be referenced by:
293 * - multiple snapshots, subvolumes, or different generations in one subvol
294 * - different files inside a single subvolume
295 * - different offsets inside a file (bookend extents in file.c)
297 * The extent ref structure for the implicit back refs has fields for:
299 * - Objectid of the subvolume root
300 * - objectid of the file holding the reference
301 * - original offset in the file
302 * - how many bookend extents
304 * The key offset for the implicit back refs is hash of the first
307 * The extent ref structure for the full back refs has field for:
309 * - number of pointers in the tree leaf
311 * The key offset for the implicit back refs is the first byte of
314 * When a file extent is allocated, The implicit back refs is used.
315 * the fields are filled in:
317 * (root_key.objectid, inode objectid, offset in file, 1)
319 * When a file extent is removed file truncation, we find the
320 * corresponding implicit back refs and check the following fields:
322 * (btrfs_header_owner(leaf), inode objectid, offset in file)
324 * Btree extents can be referenced by:
326 * - Different subvolumes
328 * Both the implicit back refs and the full back refs for tree blocks
329 * only consist of key. The key offset for the implicit back refs is
330 * objectid of block's owner tree. The key offset for the full back refs
331 * is the first byte of parent block.
333 * When implicit back refs is used, information about the lowest key and
334 * level of the tree block are required. These information are stored in
335 * tree block info structure.
339 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
340 * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
341 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
343 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
344 struct btrfs_extent_inline_ref *iref,
345 enum btrfs_inline_ref_type is_data)
347 int type = btrfs_extent_inline_ref_type(eb, iref);
348 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
350 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
351 type == BTRFS_SHARED_BLOCK_REF_KEY ||
352 type == BTRFS_SHARED_DATA_REF_KEY ||
353 type == BTRFS_EXTENT_DATA_REF_KEY) {
354 if (is_data == BTRFS_REF_TYPE_BLOCK) {
355 if (type == BTRFS_TREE_BLOCK_REF_KEY)
357 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
360 * Every shared one has parent tree block,
361 * which must be aligned to sector size.
364 IS_ALIGNED(offset, eb->fs_info->sectorsize))
367 } else if (is_data == BTRFS_REF_TYPE_DATA) {
368 if (type == BTRFS_EXTENT_DATA_REF_KEY)
370 if (type == BTRFS_SHARED_DATA_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))
381 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
387 btrfs_print_leaf(eb);
388 btrfs_err(eb->fs_info,
389 "eb %llu iref 0x%lx invalid extent inline ref type %d",
390 eb->start, (unsigned long)iref, type);
392 return BTRFS_REF_TYPE_INVALID;
395 u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
397 u32 high_crc = ~(u32)0;
398 u32 low_crc = ~(u32)0;
401 lenum = cpu_to_le64(root_objectid);
402 high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
403 lenum = cpu_to_le64(owner);
404 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
405 lenum = cpu_to_le64(offset);
406 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
408 return ((u64)high_crc << 31) ^ (u64)low_crc;
411 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
412 struct btrfs_extent_data_ref *ref)
414 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
415 btrfs_extent_data_ref_objectid(leaf, ref),
416 btrfs_extent_data_ref_offset(leaf, ref));
419 static int match_extent_data_ref(struct extent_buffer *leaf,
420 struct btrfs_extent_data_ref *ref,
421 u64 root_objectid, u64 owner, u64 offset)
423 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
424 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
425 btrfs_extent_data_ref_offset(leaf, ref) != offset)
430 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
431 struct btrfs_path *path,
432 u64 bytenr, u64 parent,
434 u64 owner, u64 offset)
436 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
437 struct btrfs_key key;
438 struct btrfs_extent_data_ref *ref;
439 struct extent_buffer *leaf;
445 key.objectid = bytenr;
447 key.type = BTRFS_SHARED_DATA_REF_KEY;
450 key.type = BTRFS_EXTENT_DATA_REF_KEY;
451 key.offset = hash_extent_data_ref(root_objectid,
456 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
468 leaf = path->nodes[0];
469 nritems = btrfs_header_nritems(leaf);
471 if (path->slots[0] >= nritems) {
472 ret = btrfs_next_leaf(root, path);
478 leaf = path->nodes[0];
479 nritems = btrfs_header_nritems(leaf);
483 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
484 if (key.objectid != bytenr ||
485 key.type != BTRFS_EXTENT_DATA_REF_KEY)
488 ref = btrfs_item_ptr(leaf, path->slots[0],
489 struct btrfs_extent_data_ref);
491 if (match_extent_data_ref(leaf, ref, root_objectid,
494 btrfs_release_path(path);
506 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
507 struct btrfs_path *path,
508 u64 bytenr, u64 parent,
509 u64 root_objectid, u64 owner,
510 u64 offset, int refs_to_add)
512 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
513 struct btrfs_key key;
514 struct extent_buffer *leaf;
519 key.objectid = bytenr;
521 key.type = BTRFS_SHARED_DATA_REF_KEY;
523 size = sizeof(struct btrfs_shared_data_ref);
525 key.type = BTRFS_EXTENT_DATA_REF_KEY;
526 key.offset = hash_extent_data_ref(root_objectid,
528 size = sizeof(struct btrfs_extent_data_ref);
531 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
532 if (ret && ret != -EEXIST)
535 leaf = path->nodes[0];
537 struct btrfs_shared_data_ref *ref;
538 ref = btrfs_item_ptr(leaf, path->slots[0],
539 struct btrfs_shared_data_ref);
541 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
543 num_refs = btrfs_shared_data_ref_count(leaf, ref);
544 num_refs += refs_to_add;
545 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
548 struct btrfs_extent_data_ref *ref;
549 while (ret == -EEXIST) {
550 ref = btrfs_item_ptr(leaf, path->slots[0],
551 struct btrfs_extent_data_ref);
552 if (match_extent_data_ref(leaf, ref, root_objectid,
555 btrfs_release_path(path);
557 ret = btrfs_insert_empty_item(trans, root, path, &key,
559 if (ret && ret != -EEXIST)
562 leaf = path->nodes[0];
564 ref = btrfs_item_ptr(leaf, path->slots[0],
565 struct btrfs_extent_data_ref);
567 btrfs_set_extent_data_ref_root(leaf, ref,
569 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
570 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
571 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
573 num_refs = btrfs_extent_data_ref_count(leaf, ref);
574 num_refs += refs_to_add;
575 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
578 btrfs_mark_buffer_dirty(trans, leaf);
581 btrfs_release_path(path);
585 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
586 struct btrfs_root *root,
587 struct btrfs_path *path,
590 struct btrfs_key key;
591 struct btrfs_extent_data_ref *ref1 = NULL;
592 struct btrfs_shared_data_ref *ref2 = NULL;
593 struct extent_buffer *leaf;
597 leaf = path->nodes[0];
598 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
600 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
601 ref1 = btrfs_item_ptr(leaf, path->slots[0],
602 struct btrfs_extent_data_ref);
603 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
604 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
605 ref2 = btrfs_item_ptr(leaf, path->slots[0],
606 struct btrfs_shared_data_ref);
607 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
609 btrfs_err(trans->fs_info,
610 "unrecognized backref key (%llu %u %llu)",
611 key.objectid, key.type, key.offset);
612 btrfs_abort_transaction(trans, -EUCLEAN);
616 BUG_ON(num_refs < refs_to_drop);
617 num_refs -= refs_to_drop;
620 ret = btrfs_del_item(trans, root, path);
622 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
623 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
624 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
625 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
626 btrfs_mark_buffer_dirty(trans, leaf);
631 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
632 struct btrfs_extent_inline_ref *iref)
634 struct btrfs_key key;
635 struct extent_buffer *leaf;
636 struct btrfs_extent_data_ref *ref1;
637 struct btrfs_shared_data_ref *ref2;
641 leaf = path->nodes[0];
642 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
646 * If type is invalid, we should have bailed out earlier than
649 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
650 ASSERT(type != BTRFS_REF_TYPE_INVALID);
651 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
652 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
653 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
655 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
656 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
658 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
659 ref1 = btrfs_item_ptr(leaf, path->slots[0],
660 struct btrfs_extent_data_ref);
661 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
662 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
663 ref2 = btrfs_item_ptr(leaf, path->slots[0],
664 struct btrfs_shared_data_ref);
665 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
672 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
673 struct btrfs_path *path,
674 u64 bytenr, u64 parent,
677 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
678 struct btrfs_key key;
681 key.objectid = bytenr;
683 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
686 key.type = BTRFS_TREE_BLOCK_REF_KEY;
687 key.offset = root_objectid;
690 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
696 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
697 struct btrfs_path *path,
698 u64 bytenr, u64 parent,
701 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
702 struct btrfs_key key;
705 key.objectid = bytenr;
707 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
710 key.type = BTRFS_TREE_BLOCK_REF_KEY;
711 key.offset = root_objectid;
714 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
715 btrfs_release_path(path);
719 static inline int extent_ref_type(u64 parent, u64 owner)
722 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
724 type = BTRFS_SHARED_BLOCK_REF_KEY;
726 type = BTRFS_TREE_BLOCK_REF_KEY;
729 type = BTRFS_SHARED_DATA_REF_KEY;
731 type = BTRFS_EXTENT_DATA_REF_KEY;
736 static int find_next_key(struct btrfs_path *path, int level,
737 struct btrfs_key *key)
740 for (; level < BTRFS_MAX_LEVEL; level++) {
741 if (!path->nodes[level])
743 if (path->slots[level] + 1 >=
744 btrfs_header_nritems(path->nodes[level]))
747 btrfs_item_key_to_cpu(path->nodes[level], key,
748 path->slots[level] + 1);
750 btrfs_node_key_to_cpu(path->nodes[level], key,
751 path->slots[level] + 1);
758 * look for inline back ref. if back ref is found, *ref_ret is set
759 * to the address of inline back ref, and 0 is returned.
761 * if back ref isn't found, *ref_ret is set to the address where it
762 * should be inserted, and -ENOENT is returned.
764 * if insert is true and there are too many inline back refs, the path
765 * points to the extent item, and -EAGAIN is returned.
767 * NOTE: inline back refs are ordered in the same way that back ref
768 * items in the tree are ordered.
770 static noinline_for_stack
771 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
772 struct btrfs_path *path,
773 struct btrfs_extent_inline_ref **ref_ret,
774 u64 bytenr, u64 num_bytes,
775 u64 parent, u64 root_objectid,
776 u64 owner, u64 offset, int insert)
778 struct btrfs_fs_info *fs_info = trans->fs_info;
779 struct btrfs_root *root = btrfs_extent_root(fs_info, bytenr);
780 struct btrfs_key key;
781 struct extent_buffer *leaf;
782 struct btrfs_extent_item *ei;
783 struct btrfs_extent_inline_ref *iref;
792 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
795 key.objectid = bytenr;
796 key.type = BTRFS_EXTENT_ITEM_KEY;
797 key.offset = num_bytes;
799 want = extent_ref_type(parent, owner);
801 extra_size = btrfs_extent_inline_ref_size(want);
802 path->search_for_extension = 1;
803 path->keep_locks = 1;
808 * Owner is our level, so we can just add one to get the level for the
809 * block we are interested in.
811 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
812 key.type = BTRFS_METADATA_ITEM_KEY;
817 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
822 * We may be a newly converted file system which still has the old fat
823 * extent entries for metadata, so try and see if we have one of those.
825 if (ret > 0 && skinny_metadata) {
826 skinny_metadata = false;
827 if (path->slots[0]) {
829 btrfs_item_key_to_cpu(path->nodes[0], &key,
831 if (key.objectid == bytenr &&
832 key.type == BTRFS_EXTENT_ITEM_KEY &&
833 key.offset == num_bytes)
837 key.objectid = bytenr;
838 key.type = BTRFS_EXTENT_ITEM_KEY;
839 key.offset = num_bytes;
840 btrfs_release_path(path);
845 if (ret && !insert) {
848 } else if (WARN_ON(ret)) {
849 btrfs_print_leaf(path->nodes[0]);
851 "extent item not found for insert, bytenr %llu num_bytes %llu parent %llu root_objectid %llu owner %llu offset %llu",
852 bytenr, num_bytes, parent, root_objectid, owner,
858 leaf = path->nodes[0];
859 item_size = btrfs_item_size(leaf, path->slots[0]);
860 if (unlikely(item_size < sizeof(*ei))) {
863 "unexpected extent item size, has %llu expect >= %zu",
864 item_size, sizeof(*ei));
865 btrfs_abort_transaction(trans, ret);
869 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
870 flags = btrfs_extent_flags(leaf, ei);
872 ptr = (unsigned long)(ei + 1);
873 end = (unsigned long)ei + item_size;
875 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
876 ptr += sizeof(struct btrfs_tree_block_info);
880 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
881 needed = BTRFS_REF_TYPE_DATA;
883 needed = BTRFS_REF_TYPE_BLOCK;
887 iref = (struct btrfs_extent_inline_ref *)ptr;
888 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
889 if (type == BTRFS_REF_TYPE_INVALID) {
897 ptr += btrfs_extent_inline_ref_size(type);
901 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
902 struct btrfs_extent_data_ref *dref;
903 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
904 if (match_extent_data_ref(leaf, dref, root_objectid,
909 if (hash_extent_data_ref_item(leaf, dref) <
910 hash_extent_data_ref(root_objectid, owner, offset))
914 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
916 if (parent == ref_offset) {
920 if (ref_offset < parent)
923 if (root_objectid == ref_offset) {
927 if (ref_offset < root_objectid)
931 ptr += btrfs_extent_inline_ref_size(type);
934 if (unlikely(ptr > end)) {
936 btrfs_print_leaf(path->nodes[0]);
938 "overrun extent record at slot %d while looking for inline extent for root %llu owner %llu offset %llu parent %llu",
939 path->slots[0], root_objectid, owner, offset, parent);
943 if (ret == -ENOENT && insert) {
944 if (item_size + extra_size >=
945 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
950 * To add new inline back ref, we have to make sure
951 * there is no corresponding back ref item.
952 * For simplicity, we just do not add new inline back
953 * ref if there is any kind of item for this block
955 if (find_next_key(path, 0, &key) == 0 &&
956 key.objectid == bytenr &&
957 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
962 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
965 path->keep_locks = 0;
966 path->search_for_extension = 0;
967 btrfs_unlock_up_safe(path, 1);
973 * helper to add new inline back ref
975 static noinline_for_stack
976 void setup_inline_extent_backref(struct btrfs_trans_handle *trans,
977 struct btrfs_path *path,
978 struct btrfs_extent_inline_ref *iref,
979 u64 parent, u64 root_objectid,
980 u64 owner, u64 offset, int refs_to_add,
981 struct btrfs_delayed_extent_op *extent_op)
983 struct extent_buffer *leaf;
984 struct btrfs_extent_item *ei;
987 unsigned long item_offset;
992 leaf = path->nodes[0];
993 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
994 item_offset = (unsigned long)iref - (unsigned long)ei;
996 type = extent_ref_type(parent, owner);
997 size = btrfs_extent_inline_ref_size(type);
999 btrfs_extend_item(trans, path, size);
1001 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1002 refs = btrfs_extent_refs(leaf, ei);
1003 refs += refs_to_add;
1004 btrfs_set_extent_refs(leaf, ei, refs);
1006 __run_delayed_extent_op(extent_op, leaf, ei);
1008 ptr = (unsigned long)ei + item_offset;
1009 end = (unsigned long)ei + btrfs_item_size(leaf, path->slots[0]);
1010 if (ptr < end - size)
1011 memmove_extent_buffer(leaf, ptr + size, ptr,
1014 iref = (struct btrfs_extent_inline_ref *)ptr;
1015 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1016 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1017 struct btrfs_extent_data_ref *dref;
1018 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1019 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1020 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1021 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1022 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1023 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1024 struct btrfs_shared_data_ref *sref;
1025 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1026 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1027 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1028 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1029 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1031 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1033 btrfs_mark_buffer_dirty(trans, leaf);
1036 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1037 struct btrfs_path *path,
1038 struct btrfs_extent_inline_ref **ref_ret,
1039 u64 bytenr, u64 num_bytes, u64 parent,
1040 u64 root_objectid, u64 owner, u64 offset)
1044 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1045 num_bytes, parent, root_objectid,
1050 btrfs_release_path(path);
1053 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1054 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1057 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1058 root_objectid, owner, offset);
1064 * helper to update/remove inline back ref
1066 static noinline_for_stack int update_inline_extent_backref(
1067 struct btrfs_trans_handle *trans,
1068 struct btrfs_path *path,
1069 struct btrfs_extent_inline_ref *iref,
1071 struct btrfs_delayed_extent_op *extent_op)
1073 struct extent_buffer *leaf = path->nodes[0];
1074 struct btrfs_fs_info *fs_info = leaf->fs_info;
1075 struct btrfs_extent_item *ei;
1076 struct btrfs_extent_data_ref *dref = NULL;
1077 struct btrfs_shared_data_ref *sref = NULL;
1085 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1086 refs = btrfs_extent_refs(leaf, ei);
1087 if (unlikely(refs_to_mod < 0 && refs + refs_to_mod <= 0)) {
1088 struct btrfs_key key;
1091 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1092 if (key.type == BTRFS_METADATA_ITEM_KEY)
1093 extent_size = fs_info->nodesize;
1095 extent_size = key.offset;
1096 btrfs_print_leaf(leaf);
1098 "invalid refs_to_mod for extent %llu num_bytes %u, has %d expect >= -%llu",
1099 key.objectid, extent_size, refs_to_mod, refs);
1102 refs += refs_to_mod;
1103 btrfs_set_extent_refs(leaf, ei, refs);
1105 __run_delayed_extent_op(extent_op, leaf, ei);
1107 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1109 * Function btrfs_get_extent_inline_ref_type() has already printed
1112 if (unlikely(type == BTRFS_REF_TYPE_INVALID))
1115 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1116 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1117 refs = btrfs_extent_data_ref_count(leaf, dref);
1118 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1119 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1120 refs = btrfs_shared_data_ref_count(leaf, sref);
1124 * For tree blocks we can only drop one ref for it, and tree
1125 * blocks should not have refs > 1.
1127 * Furthermore if we're inserting a new inline backref, we
1128 * won't reach this path either. That would be
1129 * setup_inline_extent_backref().
1131 if (unlikely(refs_to_mod != -1)) {
1132 struct btrfs_key key;
1134 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1136 btrfs_print_leaf(leaf);
1138 "invalid refs_to_mod for tree block %llu, has %d expect -1",
1139 key.objectid, refs_to_mod);
1144 if (unlikely(refs_to_mod < 0 && refs < -refs_to_mod)) {
1145 struct btrfs_key key;
1148 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1149 if (key.type == BTRFS_METADATA_ITEM_KEY)
1150 extent_size = fs_info->nodesize;
1152 extent_size = key.offset;
1153 btrfs_print_leaf(leaf);
1155 "invalid refs_to_mod for backref entry, iref %lu extent %llu num_bytes %u, has %d expect >= -%llu",
1156 (unsigned long)iref, key.objectid, extent_size,
1160 refs += refs_to_mod;
1163 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1164 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1166 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1168 size = btrfs_extent_inline_ref_size(type);
1169 item_size = btrfs_item_size(leaf, path->slots[0]);
1170 ptr = (unsigned long)iref;
1171 end = (unsigned long)ei + item_size;
1172 if (ptr + size < end)
1173 memmove_extent_buffer(leaf, ptr, ptr + size,
1176 btrfs_truncate_item(trans, path, item_size, 1);
1178 btrfs_mark_buffer_dirty(trans, leaf);
1182 static noinline_for_stack
1183 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1184 struct btrfs_path *path,
1185 u64 bytenr, u64 num_bytes, u64 parent,
1186 u64 root_objectid, u64 owner,
1187 u64 offset, int refs_to_add,
1188 struct btrfs_delayed_extent_op *extent_op)
1190 struct btrfs_extent_inline_ref *iref;
1193 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1194 num_bytes, parent, root_objectid,
1198 * We're adding refs to a tree block we already own, this
1199 * should not happen at all.
1201 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1202 btrfs_print_leaf(path->nodes[0]);
1203 btrfs_crit(trans->fs_info,
1204 "adding refs to an existing tree ref, bytenr %llu num_bytes %llu root_objectid %llu slot %u",
1205 bytenr, num_bytes, root_objectid, path->slots[0]);
1208 ret = update_inline_extent_backref(trans, path, iref,
1209 refs_to_add, extent_op);
1210 } else if (ret == -ENOENT) {
1211 setup_inline_extent_backref(trans, path, iref, parent,
1212 root_objectid, owner, offset,
1213 refs_to_add, extent_op);
1219 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1220 struct btrfs_root *root,
1221 struct btrfs_path *path,
1222 struct btrfs_extent_inline_ref *iref,
1223 int refs_to_drop, int is_data)
1227 BUG_ON(!is_data && refs_to_drop != 1);
1229 ret = update_inline_extent_backref(trans, path, iref,
1230 -refs_to_drop, NULL);
1232 ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
1234 ret = btrfs_del_item(trans, root, path);
1238 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1239 u64 *discarded_bytes)
1242 u64 bytes_left, end;
1243 u64 aligned_start = ALIGN(start, 1 << SECTOR_SHIFT);
1245 if (WARN_ON(start != aligned_start)) {
1246 len -= aligned_start - start;
1247 len = round_down(len, 1 << SECTOR_SHIFT);
1248 start = aligned_start;
1251 *discarded_bytes = 0;
1259 /* Skip any superblocks on this device. */
1260 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1261 u64 sb_start = btrfs_sb_offset(j);
1262 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1263 u64 size = sb_start - start;
1265 if (!in_range(sb_start, start, bytes_left) &&
1266 !in_range(sb_end, start, bytes_left) &&
1267 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1271 * Superblock spans beginning of range. Adjust start and
1274 if (sb_start <= start) {
1275 start += sb_end - start;
1280 bytes_left = end - start;
1285 ret = blkdev_issue_discard(bdev, start >> SECTOR_SHIFT,
1286 size >> SECTOR_SHIFT,
1289 *discarded_bytes += size;
1290 else if (ret != -EOPNOTSUPP)
1299 bytes_left = end - start;
1303 ret = blkdev_issue_discard(bdev, start >> SECTOR_SHIFT,
1304 bytes_left >> SECTOR_SHIFT,
1307 *discarded_bytes += bytes_left;
1312 static int do_discard_extent(struct btrfs_discard_stripe *stripe, u64 *bytes)
1314 struct btrfs_device *dev = stripe->dev;
1315 struct btrfs_fs_info *fs_info = dev->fs_info;
1316 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1317 u64 phys = stripe->physical;
1318 u64 len = stripe->length;
1322 /* Zone reset on a zoned filesystem */
1323 if (btrfs_can_zone_reset(dev, phys, len)) {
1326 ret = btrfs_reset_device_zone(dev, phys, len, &discarded);
1330 if (!btrfs_dev_replace_is_ongoing(dev_replace) ||
1331 dev != dev_replace->srcdev)
1334 src_disc = discarded;
1336 /* Send to replace target as well */
1337 ret = btrfs_reset_device_zone(dev_replace->tgtdev, phys, len,
1339 discarded += src_disc;
1340 } else if (bdev_max_discard_sectors(stripe->dev->bdev)) {
1341 ret = btrfs_issue_discard(dev->bdev, phys, len, &discarded);
1352 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1353 u64 num_bytes, u64 *actual_bytes)
1356 u64 discarded_bytes = 0;
1357 u64 end = bytenr + num_bytes;
1361 * Avoid races with device replace and make sure the devices in the
1362 * stripes don't go away while we are discarding.
1364 btrfs_bio_counter_inc_blocked(fs_info);
1366 struct btrfs_discard_stripe *stripes;
1367 unsigned int num_stripes;
1370 num_bytes = end - cur;
1371 stripes = btrfs_map_discard(fs_info, cur, &num_bytes, &num_stripes);
1372 if (IS_ERR(stripes)) {
1373 ret = PTR_ERR(stripes);
1374 if (ret == -EOPNOTSUPP)
1379 for (i = 0; i < num_stripes; i++) {
1380 struct btrfs_discard_stripe *stripe = stripes + i;
1383 if (!stripe->dev->bdev) {
1384 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1388 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
1389 &stripe->dev->dev_state))
1392 ret = do_discard_extent(stripe, &bytes);
1395 * Keep going if discard is not supported by the
1398 if (ret != -EOPNOTSUPP)
1402 discarded_bytes += bytes;
1410 btrfs_bio_counter_dec(fs_info);
1412 *actual_bytes = discarded_bytes;
1416 /* Can return -ENOMEM */
1417 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1418 struct btrfs_ref *generic_ref)
1420 struct btrfs_fs_info *fs_info = trans->fs_info;
1423 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
1424 generic_ref->action);
1425 BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
1426 generic_ref->tree_ref.owning_root == BTRFS_TREE_LOG_OBJECTID);
1428 if (generic_ref->type == BTRFS_REF_METADATA)
1429 ret = btrfs_add_delayed_tree_ref(trans, generic_ref, NULL);
1431 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0);
1433 btrfs_ref_tree_mod(fs_info, generic_ref);
1439 * Insert backreference for a given extent.
1441 * The counterpart is in __btrfs_free_extent(), with examples and more details
1444 * @trans: Handle of transaction
1446 * @node: The delayed ref node used to get the bytenr/length for
1447 * extent whose references are incremented.
1449 * @parent: If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
1450 * BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
1451 * bytenr of the parent block. Since new extents are always
1452 * created with indirect references, this will only be the case
1453 * when relocating a shared extent. In that case, root_objectid
1454 * will be BTRFS_TREE_RELOC_OBJECTID. Otherwise, parent must
1457 * @root_objectid: The id of the root where this modification has originated,
1458 * this can be either one of the well-known metadata trees or
1459 * the subvolume id which references this extent.
1461 * @owner: For data extents it is the inode number of the owning file.
1462 * For metadata extents this parameter holds the level in the
1463 * tree of the extent.
1465 * @offset: For metadata extents the offset is ignored and is currently
1466 * always passed as 0. For data extents it is the fileoffset
1467 * this extent belongs to.
1469 * @extent_op Pointer to a structure, holding information necessary when
1470 * updating a tree block's flags
1473 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1474 struct btrfs_delayed_ref_node *node,
1475 u64 parent, u64 root_objectid,
1476 u64 owner, u64 offset,
1477 struct btrfs_delayed_extent_op *extent_op)
1479 struct btrfs_path *path;
1480 struct extent_buffer *leaf;
1481 struct btrfs_extent_item *item;
1482 struct btrfs_key key;
1483 u64 bytenr = node->bytenr;
1484 u64 num_bytes = node->num_bytes;
1486 int refs_to_add = node->ref_mod;
1489 path = btrfs_alloc_path();
1493 /* this will setup the path even if it fails to insert the back ref */
1494 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
1495 parent, root_objectid, owner,
1496 offset, refs_to_add, extent_op);
1497 if ((ret < 0 && ret != -EAGAIN) || !ret)
1501 * Ok we had -EAGAIN which means we didn't have space to insert and
1502 * inline extent ref, so just update the reference count and add a
1505 leaf = path->nodes[0];
1506 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1507 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1508 refs = btrfs_extent_refs(leaf, item);
1509 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1511 __run_delayed_extent_op(extent_op, leaf, item);
1513 btrfs_mark_buffer_dirty(trans, leaf);
1514 btrfs_release_path(path);
1516 /* now insert the actual backref */
1517 if (owner < BTRFS_FIRST_FREE_OBJECTID)
1518 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1521 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1522 root_objectid, owner, offset,
1526 btrfs_abort_transaction(trans, ret);
1528 btrfs_free_path(path);
1532 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1533 struct btrfs_delayed_ref_node *node,
1534 struct btrfs_delayed_extent_op *extent_op,
1535 bool insert_reserved)
1538 struct btrfs_delayed_data_ref *ref;
1542 ref = btrfs_delayed_node_to_data_ref(node);
1543 trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
1545 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1546 parent = ref->parent;
1548 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1549 struct btrfs_key key;
1552 flags |= extent_op->flags_to_set;
1554 key.objectid = node->bytenr;
1555 key.type = BTRFS_EXTENT_ITEM_KEY;
1556 key.offset = node->num_bytes;
1558 ret = alloc_reserved_file_extent(trans, parent, ref->root,
1559 flags, ref->objectid,
1562 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1563 ret = __btrfs_inc_extent_ref(trans, node, parent, ref->root,
1564 ref->objectid, ref->offset,
1566 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1567 ret = __btrfs_free_extent(trans, node, parent,
1568 ref->root, ref->objectid,
1569 ref->offset, extent_op);
1576 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1577 struct extent_buffer *leaf,
1578 struct btrfs_extent_item *ei)
1580 u64 flags = btrfs_extent_flags(leaf, ei);
1581 if (extent_op->update_flags) {
1582 flags |= extent_op->flags_to_set;
1583 btrfs_set_extent_flags(leaf, ei, flags);
1586 if (extent_op->update_key) {
1587 struct btrfs_tree_block_info *bi;
1588 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1589 bi = (struct btrfs_tree_block_info *)(ei + 1);
1590 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1594 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1595 struct btrfs_delayed_ref_head *head,
1596 struct btrfs_delayed_extent_op *extent_op)
1598 struct btrfs_fs_info *fs_info = trans->fs_info;
1599 struct btrfs_root *root;
1600 struct btrfs_key key;
1601 struct btrfs_path *path;
1602 struct btrfs_extent_item *ei;
1603 struct extent_buffer *leaf;
1608 if (TRANS_ABORTED(trans))
1611 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1614 path = btrfs_alloc_path();
1618 key.objectid = head->bytenr;
1621 key.type = BTRFS_METADATA_ITEM_KEY;
1622 key.offset = extent_op->level;
1624 key.type = BTRFS_EXTENT_ITEM_KEY;
1625 key.offset = head->num_bytes;
1628 root = btrfs_extent_root(fs_info, key.objectid);
1630 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1633 } else if (ret > 0) {
1635 if (path->slots[0] > 0) {
1637 btrfs_item_key_to_cpu(path->nodes[0], &key,
1639 if (key.objectid == head->bytenr &&
1640 key.type == BTRFS_EXTENT_ITEM_KEY &&
1641 key.offset == head->num_bytes)
1645 btrfs_release_path(path);
1648 key.objectid = head->bytenr;
1649 key.offset = head->num_bytes;
1650 key.type = BTRFS_EXTENT_ITEM_KEY;
1656 "missing extent item for extent %llu num_bytes %llu level %d",
1657 head->bytenr, head->num_bytes, extent_op->level);
1662 leaf = path->nodes[0];
1663 item_size = btrfs_item_size(leaf, path->slots[0]);
1665 if (unlikely(item_size < sizeof(*ei))) {
1668 "unexpected extent item size, has %u expect >= %zu",
1669 item_size, sizeof(*ei));
1670 btrfs_abort_transaction(trans, ret);
1674 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1675 __run_delayed_extent_op(extent_op, leaf, ei);
1677 btrfs_mark_buffer_dirty(trans, leaf);
1679 btrfs_free_path(path);
1683 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
1684 struct btrfs_delayed_ref_node *node,
1685 struct btrfs_delayed_extent_op *extent_op,
1686 bool insert_reserved)
1689 struct btrfs_delayed_tree_ref *ref;
1693 ref = btrfs_delayed_node_to_tree_ref(node);
1694 trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
1696 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1697 parent = ref->parent;
1698 ref_root = ref->root;
1700 if (unlikely(node->ref_mod != 1)) {
1701 btrfs_err(trans->fs_info,
1702 "btree block %llu has %d references rather than 1: action %d ref_root %llu parent %llu",
1703 node->bytenr, node->ref_mod, node->action, ref_root,
1707 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1708 BUG_ON(!extent_op || !extent_op->update_flags);
1709 ret = alloc_reserved_tree_block(trans, node, extent_op);
1710 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1711 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
1712 ref->level, 0, extent_op);
1713 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1714 ret = __btrfs_free_extent(trans, node, parent, ref_root,
1715 ref->level, 0, extent_op);
1722 /* helper function to actually process a single delayed ref entry */
1723 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
1724 struct btrfs_delayed_ref_node *node,
1725 struct btrfs_delayed_extent_op *extent_op,
1726 bool insert_reserved)
1730 if (TRANS_ABORTED(trans)) {
1731 if (insert_reserved)
1732 btrfs_pin_extent(trans, node->bytenr, node->num_bytes, 1);
1736 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
1737 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1738 ret = run_delayed_tree_ref(trans, node, extent_op,
1740 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
1741 node->type == BTRFS_SHARED_DATA_REF_KEY)
1742 ret = run_delayed_data_ref(trans, node, extent_op,
1746 if (ret && insert_reserved)
1747 btrfs_pin_extent(trans, node->bytenr, node->num_bytes, 1);
1749 btrfs_err(trans->fs_info,
1750 "failed to run delayed ref for logical %llu num_bytes %llu type %u action %u ref_mod %d: %d",
1751 node->bytenr, node->num_bytes, node->type,
1752 node->action, node->ref_mod, ret);
1756 static inline struct btrfs_delayed_ref_node *
1757 select_delayed_ref(struct btrfs_delayed_ref_head *head)
1759 struct btrfs_delayed_ref_node *ref;
1761 if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
1765 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
1766 * This is to prevent a ref count from going down to zero, which deletes
1767 * the extent item from the extent tree, when there still are references
1768 * to add, which would fail because they would not find the extent item.
1770 if (!list_empty(&head->ref_add_list))
1771 return list_first_entry(&head->ref_add_list,
1772 struct btrfs_delayed_ref_node, add_list);
1774 ref = rb_entry(rb_first_cached(&head->ref_tree),
1775 struct btrfs_delayed_ref_node, ref_node);
1776 ASSERT(list_empty(&ref->add_list));
1780 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
1781 struct btrfs_delayed_ref_head *head)
1783 spin_lock(&delayed_refs->lock);
1784 head->processing = false;
1785 delayed_refs->num_heads_ready++;
1786 spin_unlock(&delayed_refs->lock);
1787 btrfs_delayed_ref_unlock(head);
1790 static struct btrfs_delayed_extent_op *cleanup_extent_op(
1791 struct btrfs_delayed_ref_head *head)
1793 struct btrfs_delayed_extent_op *extent_op = head->extent_op;
1798 if (head->must_insert_reserved) {
1799 head->extent_op = NULL;
1800 btrfs_free_delayed_extent_op(extent_op);
1806 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
1807 struct btrfs_delayed_ref_head *head)
1809 struct btrfs_delayed_extent_op *extent_op;
1812 extent_op = cleanup_extent_op(head);
1815 head->extent_op = NULL;
1816 spin_unlock(&head->lock);
1817 ret = run_delayed_extent_op(trans, head, extent_op);
1818 btrfs_free_delayed_extent_op(extent_op);
1819 return ret ? ret : 1;
1822 u64 btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
1823 struct btrfs_delayed_ref_root *delayed_refs,
1824 struct btrfs_delayed_ref_head *head)
1827 * We had csum deletions accounted for in our delayed refs rsv, we need
1828 * to drop the csum leaves for this update from our delayed_refs_rsv.
1830 if (head->total_ref_mod < 0 && head->is_data) {
1833 spin_lock(&delayed_refs->lock);
1834 delayed_refs->pending_csums -= head->num_bytes;
1835 spin_unlock(&delayed_refs->lock);
1836 nr_csums = btrfs_csum_bytes_to_leaves(fs_info, head->num_bytes);
1838 btrfs_delayed_refs_rsv_release(fs_info, 0, nr_csums);
1840 return btrfs_calc_delayed_ref_csum_bytes(fs_info, nr_csums);
1846 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
1847 struct btrfs_delayed_ref_head *head,
1848 u64 *bytes_released)
1851 struct btrfs_fs_info *fs_info = trans->fs_info;
1852 struct btrfs_delayed_ref_root *delayed_refs;
1855 delayed_refs = &trans->transaction->delayed_refs;
1857 ret = run_and_cleanup_extent_op(trans, head);
1859 unselect_delayed_ref_head(delayed_refs, head);
1860 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
1867 * Need to drop our head ref lock and re-acquire the delayed ref lock
1868 * and then re-check to make sure nobody got added.
1870 spin_unlock(&head->lock);
1871 spin_lock(&delayed_refs->lock);
1872 spin_lock(&head->lock);
1873 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
1874 spin_unlock(&head->lock);
1875 spin_unlock(&delayed_refs->lock);
1878 btrfs_delete_ref_head(delayed_refs, head);
1879 spin_unlock(&head->lock);
1880 spin_unlock(&delayed_refs->lock);
1882 if (head->must_insert_reserved) {
1883 btrfs_pin_extent(trans, head->bytenr, head->num_bytes, 1);
1884 if (head->is_data) {
1885 struct btrfs_root *csum_root;
1887 csum_root = btrfs_csum_root(fs_info, head->bytenr);
1888 ret = btrfs_del_csums(trans, csum_root, head->bytenr,
1893 *bytes_released += btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
1895 trace_run_delayed_ref_head(fs_info, head, 0);
1896 btrfs_delayed_ref_unlock(head);
1897 btrfs_put_delayed_ref_head(head);
1901 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
1902 struct btrfs_trans_handle *trans)
1904 struct btrfs_delayed_ref_root *delayed_refs =
1905 &trans->transaction->delayed_refs;
1906 struct btrfs_delayed_ref_head *head = NULL;
1909 spin_lock(&delayed_refs->lock);
1910 head = btrfs_select_ref_head(delayed_refs);
1912 spin_unlock(&delayed_refs->lock);
1917 * Grab the lock that says we are going to process all the refs for
1920 ret = btrfs_delayed_ref_lock(delayed_refs, head);
1921 spin_unlock(&delayed_refs->lock);
1924 * We may have dropped the spin lock to get the head mutex lock, and
1925 * that might have given someone else time to free the head. If that's
1926 * true, it has been removed from our list and we can move on.
1929 head = ERR_PTR(-EAGAIN);
1934 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
1935 struct btrfs_delayed_ref_head *locked_ref,
1936 u64 *bytes_released)
1938 struct btrfs_fs_info *fs_info = trans->fs_info;
1939 struct btrfs_delayed_ref_root *delayed_refs;
1940 struct btrfs_delayed_extent_op *extent_op;
1941 struct btrfs_delayed_ref_node *ref;
1942 bool must_insert_reserved;
1945 delayed_refs = &trans->transaction->delayed_refs;
1947 lockdep_assert_held(&locked_ref->mutex);
1948 lockdep_assert_held(&locked_ref->lock);
1950 while ((ref = select_delayed_ref(locked_ref))) {
1952 btrfs_check_delayed_seq(fs_info, ref->seq)) {
1953 spin_unlock(&locked_ref->lock);
1954 unselect_delayed_ref_head(delayed_refs, locked_ref);
1958 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
1959 RB_CLEAR_NODE(&ref->ref_node);
1960 if (!list_empty(&ref->add_list))
1961 list_del(&ref->add_list);
1963 * When we play the delayed ref, also correct the ref_mod on
1966 switch (ref->action) {
1967 case BTRFS_ADD_DELAYED_REF:
1968 case BTRFS_ADD_DELAYED_EXTENT:
1969 locked_ref->ref_mod -= ref->ref_mod;
1971 case BTRFS_DROP_DELAYED_REF:
1972 locked_ref->ref_mod += ref->ref_mod;
1977 atomic_dec(&delayed_refs->num_entries);
1980 * Record the must_insert_reserved flag before we drop the
1983 must_insert_reserved = locked_ref->must_insert_reserved;
1984 locked_ref->must_insert_reserved = false;
1986 extent_op = locked_ref->extent_op;
1987 locked_ref->extent_op = NULL;
1988 spin_unlock(&locked_ref->lock);
1990 ret = run_one_delayed_ref(trans, ref, extent_op,
1991 must_insert_reserved);
1992 btrfs_delayed_refs_rsv_release(fs_info, 1, 0);
1993 *bytes_released += btrfs_calc_delayed_ref_bytes(fs_info, 1);
1994 btrfs_free_delayed_extent_op(extent_op);
1996 unselect_delayed_ref_head(delayed_refs, locked_ref);
1997 btrfs_put_delayed_ref(ref);
2001 btrfs_put_delayed_ref(ref);
2004 spin_lock(&locked_ref->lock);
2005 btrfs_merge_delayed_refs(fs_info, delayed_refs, locked_ref);
2012 * Returns 0 on success or if called with an already aborted transaction.
2013 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2015 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2018 struct btrfs_fs_info *fs_info = trans->fs_info;
2019 struct btrfs_delayed_ref_root *delayed_refs;
2020 struct btrfs_delayed_ref_head *locked_ref = NULL;
2022 unsigned long count = 0;
2023 unsigned long max_count = 0;
2024 u64 bytes_processed = 0;
2026 delayed_refs = &trans->transaction->delayed_refs;
2027 if (min_bytes == 0) {
2028 max_count = delayed_refs->num_heads_ready;
2029 min_bytes = U64_MAX;
2034 locked_ref = btrfs_obtain_ref_head(trans);
2035 if (IS_ERR_OR_NULL(locked_ref)) {
2036 if (PTR_ERR(locked_ref) == -EAGAIN) {
2045 * We need to try and merge add/drops of the same ref since we
2046 * can run into issues with relocate dropping the implicit ref
2047 * and then it being added back again before the drop can
2048 * finish. If we merged anything we need to re-loop so we can
2050 * Or we can get node references of the same type that weren't
2051 * merged when created due to bumps in the tree mod seq, and
2052 * we need to merge them to prevent adding an inline extent
2053 * backref before dropping it (triggering a BUG_ON at
2054 * insert_inline_extent_backref()).
2056 spin_lock(&locked_ref->lock);
2057 btrfs_merge_delayed_refs(fs_info, delayed_refs, locked_ref);
2059 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref, &bytes_processed);
2060 if (ret < 0 && ret != -EAGAIN) {
2062 * Error, btrfs_run_delayed_refs_for_head already
2063 * unlocked everything so just bail out
2068 * Success, perform the usual cleanup of a processed
2071 ret = cleanup_ref_head(trans, locked_ref, &bytes_processed);
2073 /* We dropped our lock, we need to loop. */
2082 * Either success case or btrfs_run_delayed_refs_for_head
2083 * returned -EAGAIN, meaning we need to select another head
2088 } while ((min_bytes != U64_MAX && bytes_processed < min_bytes) ||
2089 (max_count > 0 && count < max_count) ||
2095 #ifdef SCRAMBLE_DELAYED_REFS
2097 * Normally delayed refs get processed in ascending bytenr order. This
2098 * correlates in most cases to the order added. To expose dependencies on this
2099 * order, we start to process the tree in the middle instead of the beginning
2101 static u64 find_middle(struct rb_root *root)
2103 struct rb_node *n = root->rb_node;
2104 struct btrfs_delayed_ref_node *entry;
2107 u64 first = 0, last = 0;
2111 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2112 first = entry->bytenr;
2116 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2117 last = entry->bytenr;
2122 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2123 WARN_ON(!entry->in_tree);
2125 middle = entry->bytenr;
2139 * Start processing the delayed reference count updates and extent insertions
2140 * we have queued up so far.
2142 * @trans: Transaction handle.
2143 * @min_bytes: How many bytes of delayed references to process. After this
2144 * many bytes we stop processing delayed references if there are
2145 * any more. If 0 it means to run all existing delayed references,
2146 * but not new ones added after running all existing ones.
2147 * Use (u64)-1 (U64_MAX) to run all existing delayed references
2148 * plus any new ones that are added.
2150 * Returns 0 on success or if called with an aborted transaction
2151 * Returns <0 on error and aborts the transaction
2153 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans, u64 min_bytes)
2155 struct btrfs_fs_info *fs_info = trans->fs_info;
2156 struct btrfs_delayed_ref_root *delayed_refs;
2159 /* We'll clean this up in btrfs_cleanup_transaction */
2160 if (TRANS_ABORTED(trans))
2163 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2166 delayed_refs = &trans->transaction->delayed_refs;
2168 #ifdef SCRAMBLE_DELAYED_REFS
2169 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2171 ret = __btrfs_run_delayed_refs(trans, min_bytes);
2173 btrfs_abort_transaction(trans, ret);
2177 if (min_bytes == U64_MAX) {
2178 btrfs_create_pending_block_groups(trans);
2180 spin_lock(&delayed_refs->lock);
2181 if (RB_EMPTY_ROOT(&delayed_refs->href_root.rb_root)) {
2182 spin_unlock(&delayed_refs->lock);
2185 spin_unlock(&delayed_refs->lock);
2194 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2195 struct extent_buffer *eb, u64 flags)
2197 struct btrfs_delayed_extent_op *extent_op;
2198 int level = btrfs_header_level(eb);
2201 extent_op = btrfs_alloc_delayed_extent_op();
2205 extent_op->flags_to_set = flags;
2206 extent_op->update_flags = true;
2207 extent_op->update_key = false;
2208 extent_op->level = level;
2210 ret = btrfs_add_delayed_extent_op(trans, eb->start, eb->len, extent_op);
2212 btrfs_free_delayed_extent_op(extent_op);
2216 static noinline int check_delayed_ref(struct btrfs_root *root,
2217 struct btrfs_path *path,
2218 u64 objectid, u64 offset, u64 bytenr)
2220 struct btrfs_delayed_ref_head *head;
2221 struct btrfs_delayed_ref_node *ref;
2222 struct btrfs_delayed_data_ref *data_ref;
2223 struct btrfs_delayed_ref_root *delayed_refs;
2224 struct btrfs_transaction *cur_trans;
2225 struct rb_node *node;
2228 spin_lock(&root->fs_info->trans_lock);
2229 cur_trans = root->fs_info->running_transaction;
2231 refcount_inc(&cur_trans->use_count);
2232 spin_unlock(&root->fs_info->trans_lock);
2236 delayed_refs = &cur_trans->delayed_refs;
2237 spin_lock(&delayed_refs->lock);
2238 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2240 spin_unlock(&delayed_refs->lock);
2241 btrfs_put_transaction(cur_trans);
2245 if (!mutex_trylock(&head->mutex)) {
2247 spin_unlock(&delayed_refs->lock);
2248 btrfs_put_transaction(cur_trans);
2252 refcount_inc(&head->refs);
2253 spin_unlock(&delayed_refs->lock);
2255 btrfs_release_path(path);
2258 * Mutex was contended, block until it's released and let
2261 mutex_lock(&head->mutex);
2262 mutex_unlock(&head->mutex);
2263 btrfs_put_delayed_ref_head(head);
2264 btrfs_put_transaction(cur_trans);
2267 spin_unlock(&delayed_refs->lock);
2269 spin_lock(&head->lock);
2271 * XXX: We should replace this with a proper search function in the
2274 for (node = rb_first_cached(&head->ref_tree); node;
2275 node = rb_next(node)) {
2276 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
2277 /* If it's a shared ref we know a cross reference exists */
2278 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2283 data_ref = btrfs_delayed_node_to_data_ref(ref);
2286 * If our ref doesn't match the one we're currently looking at
2287 * then we have a cross reference.
2289 if (data_ref->root != root->root_key.objectid ||
2290 data_ref->objectid != objectid ||
2291 data_ref->offset != offset) {
2296 spin_unlock(&head->lock);
2297 mutex_unlock(&head->mutex);
2298 btrfs_put_transaction(cur_trans);
2302 static noinline int check_committed_ref(struct btrfs_root *root,
2303 struct btrfs_path *path,
2304 u64 objectid, u64 offset, u64 bytenr,
2307 struct btrfs_fs_info *fs_info = root->fs_info;
2308 struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
2309 struct extent_buffer *leaf;
2310 struct btrfs_extent_data_ref *ref;
2311 struct btrfs_extent_inline_ref *iref;
2312 struct btrfs_extent_item *ei;
2313 struct btrfs_key key;
2318 key.objectid = bytenr;
2319 key.offset = (u64)-1;
2320 key.type = BTRFS_EXTENT_ITEM_KEY;
2322 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2325 BUG_ON(ret == 0); /* Corruption */
2328 if (path->slots[0] == 0)
2332 leaf = path->nodes[0];
2333 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2335 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2339 item_size = btrfs_item_size(leaf, path->slots[0]);
2340 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2342 /* If extent item has more than 1 inline ref then it's shared */
2343 if (item_size != sizeof(*ei) +
2344 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2348 * If extent created before last snapshot => it's shared unless the
2349 * snapshot has been deleted. Use the heuristic if strict is false.
2352 (btrfs_extent_generation(leaf, ei) <=
2353 btrfs_root_last_snapshot(&root->root_item)))
2356 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2358 /* If this extent has SHARED_DATA_REF then it's shared */
2359 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
2360 if (type != BTRFS_EXTENT_DATA_REF_KEY)
2363 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2364 if (btrfs_extent_refs(leaf, ei) !=
2365 btrfs_extent_data_ref_count(leaf, ref) ||
2366 btrfs_extent_data_ref_root(leaf, ref) !=
2367 root->root_key.objectid ||
2368 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2369 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2377 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
2378 u64 bytenr, bool strict, struct btrfs_path *path)
2383 ret = check_committed_ref(root, path, objectid,
2384 offset, bytenr, strict);
2385 if (ret && ret != -ENOENT)
2388 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
2389 } while (ret == -EAGAIN);
2392 btrfs_release_path(path);
2393 if (btrfs_is_data_reloc_root(root))
2398 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2399 struct btrfs_root *root,
2400 struct extent_buffer *buf,
2401 int full_backref, int inc)
2403 struct btrfs_fs_info *fs_info = root->fs_info;
2409 struct btrfs_key key;
2410 struct btrfs_file_extent_item *fi;
2411 struct btrfs_ref generic_ref = { 0 };
2412 bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
2418 if (btrfs_is_testing(fs_info))
2421 ref_root = btrfs_header_owner(buf);
2422 nritems = btrfs_header_nritems(buf);
2423 level = btrfs_header_level(buf);
2425 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state) && level == 0)
2429 parent = buf->start;
2433 action = BTRFS_ADD_DELAYED_REF;
2435 action = BTRFS_DROP_DELAYED_REF;
2437 for (i = 0; i < nritems; i++) {
2439 btrfs_item_key_to_cpu(buf, &key, i);
2440 if (key.type != BTRFS_EXTENT_DATA_KEY)
2442 fi = btrfs_item_ptr(buf, i,
2443 struct btrfs_file_extent_item);
2444 if (btrfs_file_extent_type(buf, fi) ==
2445 BTRFS_FILE_EXTENT_INLINE)
2447 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2451 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2452 key.offset -= btrfs_file_extent_offset(buf, fi);
2453 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2455 btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
2456 key.offset, root->root_key.objectid,
2459 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2461 ret = btrfs_free_extent(trans, &generic_ref);
2465 bytenr = btrfs_node_blockptr(buf, i);
2466 num_bytes = fs_info->nodesize;
2467 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2469 btrfs_init_tree_ref(&generic_ref, level - 1, ref_root,
2470 root->root_key.objectid, for_reloc);
2472 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2474 ret = btrfs_free_extent(trans, &generic_ref);
2484 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2485 struct extent_buffer *buf, int full_backref)
2487 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
2490 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2491 struct extent_buffer *buf, int full_backref)
2493 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2496 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
2498 struct btrfs_fs_info *fs_info = root->fs_info;
2503 flags = BTRFS_BLOCK_GROUP_DATA;
2504 else if (root == fs_info->chunk_root)
2505 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2507 flags = BTRFS_BLOCK_GROUP_METADATA;
2509 ret = btrfs_get_alloc_profile(fs_info, flags);
2513 static u64 first_logical_byte(struct btrfs_fs_info *fs_info)
2515 struct rb_node *leftmost;
2518 read_lock(&fs_info->block_group_cache_lock);
2519 /* Get the block group with the lowest logical start address. */
2520 leftmost = rb_first_cached(&fs_info->block_group_cache_tree);
2522 struct btrfs_block_group *bg;
2524 bg = rb_entry(leftmost, struct btrfs_block_group, cache_node);
2527 read_unlock(&fs_info->block_group_cache_lock);
2532 static int pin_down_extent(struct btrfs_trans_handle *trans,
2533 struct btrfs_block_group *cache,
2534 u64 bytenr, u64 num_bytes, int reserved)
2536 struct btrfs_fs_info *fs_info = cache->fs_info;
2538 spin_lock(&cache->space_info->lock);
2539 spin_lock(&cache->lock);
2540 cache->pinned += num_bytes;
2541 btrfs_space_info_update_bytes_pinned(fs_info, cache->space_info,
2544 cache->reserved -= num_bytes;
2545 cache->space_info->bytes_reserved -= num_bytes;
2547 spin_unlock(&cache->lock);
2548 spin_unlock(&cache->space_info->lock);
2550 set_extent_bit(&trans->transaction->pinned_extents, bytenr,
2551 bytenr + num_bytes - 1, EXTENT_DIRTY, NULL);
2555 int btrfs_pin_extent(struct btrfs_trans_handle *trans,
2556 u64 bytenr, u64 num_bytes, int reserved)
2558 struct btrfs_block_group *cache;
2560 cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
2561 BUG_ON(!cache); /* Logic error */
2563 pin_down_extent(trans, cache, bytenr, num_bytes, reserved);
2565 btrfs_put_block_group(cache);
2569 int btrfs_pin_extent_for_log_replay(struct btrfs_trans_handle *trans,
2570 const struct extent_buffer *eb)
2572 struct btrfs_block_group *cache;
2575 cache = btrfs_lookup_block_group(trans->fs_info, eb->start);
2580 * Fully cache the free space first so that our pin removes the free space
2583 ret = btrfs_cache_block_group(cache, true);
2587 pin_down_extent(trans, cache, eb->start, eb->len, 0);
2589 /* remove us from the free space cache (if we're there at all) */
2590 ret = btrfs_remove_free_space(cache, eb->start, eb->len);
2592 btrfs_put_block_group(cache);
2596 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
2597 u64 start, u64 num_bytes)
2600 struct btrfs_block_group *block_group;
2602 block_group = btrfs_lookup_block_group(fs_info, start);
2606 ret = btrfs_cache_block_group(block_group, true);
2610 ret = btrfs_remove_free_space(block_group, start, num_bytes);
2612 btrfs_put_block_group(block_group);
2616 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
2618 struct btrfs_fs_info *fs_info = eb->fs_info;
2619 struct btrfs_file_extent_item *item;
2620 struct btrfs_key key;
2625 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
2628 for (i = 0; i < btrfs_header_nritems(eb); i++) {
2629 btrfs_item_key_to_cpu(eb, &key, i);
2630 if (key.type != BTRFS_EXTENT_DATA_KEY)
2632 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
2633 found_type = btrfs_file_extent_type(eb, item);
2634 if (found_type == BTRFS_FILE_EXTENT_INLINE)
2636 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
2638 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
2639 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
2640 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
2649 btrfs_inc_block_group_reservations(struct btrfs_block_group *bg)
2651 atomic_inc(&bg->reservations);
2655 * Returns the free cluster for the given space info and sets empty_cluster to
2656 * what it should be based on the mount options.
2658 static struct btrfs_free_cluster *
2659 fetch_cluster_info(struct btrfs_fs_info *fs_info,
2660 struct btrfs_space_info *space_info, u64 *empty_cluster)
2662 struct btrfs_free_cluster *ret = NULL;
2665 if (btrfs_mixed_space_info(space_info))
2668 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
2669 ret = &fs_info->meta_alloc_cluster;
2670 if (btrfs_test_opt(fs_info, SSD))
2671 *empty_cluster = SZ_2M;
2673 *empty_cluster = SZ_64K;
2674 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
2675 btrfs_test_opt(fs_info, SSD_SPREAD)) {
2676 *empty_cluster = SZ_2M;
2677 ret = &fs_info->data_alloc_cluster;
2683 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
2685 const bool return_free_space)
2687 struct btrfs_block_group *cache = NULL;
2688 struct btrfs_space_info *space_info;
2689 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2690 struct btrfs_free_cluster *cluster = NULL;
2692 u64 total_unpinned = 0;
2693 u64 empty_cluster = 0;
2696 while (start <= end) {
2699 start >= cache->start + cache->length) {
2701 btrfs_put_block_group(cache);
2703 cache = btrfs_lookup_block_group(fs_info, start);
2704 BUG_ON(!cache); /* Logic error */
2706 cluster = fetch_cluster_info(fs_info,
2709 empty_cluster <<= 1;
2712 len = cache->start + cache->length - start;
2713 len = min(len, end + 1 - start);
2715 if (return_free_space)
2716 btrfs_add_free_space(cache, start, len);
2719 total_unpinned += len;
2720 space_info = cache->space_info;
2723 * If this space cluster has been marked as fragmented and we've
2724 * unpinned enough in this block group to potentially allow a
2725 * cluster to be created inside of it go ahead and clear the
2728 if (cluster && cluster->fragmented &&
2729 total_unpinned > empty_cluster) {
2730 spin_lock(&cluster->lock);
2731 cluster->fragmented = 0;
2732 spin_unlock(&cluster->lock);
2735 spin_lock(&space_info->lock);
2736 spin_lock(&cache->lock);
2737 cache->pinned -= len;
2738 btrfs_space_info_update_bytes_pinned(fs_info, space_info, -len);
2739 space_info->max_extent_size = 0;
2741 space_info->bytes_readonly += len;
2743 } else if (btrfs_is_zoned(fs_info)) {
2744 /* Need reset before reusing in a zoned block group */
2745 space_info->bytes_zone_unusable += len;
2748 spin_unlock(&cache->lock);
2749 if (!readonly && return_free_space &&
2750 global_rsv->space_info == space_info) {
2751 spin_lock(&global_rsv->lock);
2752 if (!global_rsv->full) {
2753 u64 to_add = min(len, global_rsv->size -
2754 global_rsv->reserved);
2756 global_rsv->reserved += to_add;
2757 btrfs_space_info_update_bytes_may_use(fs_info,
2758 space_info, to_add);
2759 if (global_rsv->reserved >= global_rsv->size)
2760 global_rsv->full = 1;
2763 spin_unlock(&global_rsv->lock);
2765 /* Add to any tickets we may have */
2766 if (!readonly && return_free_space && len)
2767 btrfs_try_granting_tickets(fs_info, space_info);
2768 spin_unlock(&space_info->lock);
2772 btrfs_put_block_group(cache);
2776 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
2778 struct btrfs_fs_info *fs_info = trans->fs_info;
2779 struct btrfs_block_group *block_group, *tmp;
2780 struct list_head *deleted_bgs;
2781 struct extent_io_tree *unpin;
2786 unpin = &trans->transaction->pinned_extents;
2788 while (!TRANS_ABORTED(trans)) {
2789 struct extent_state *cached_state = NULL;
2791 mutex_lock(&fs_info->unused_bg_unpin_mutex);
2792 if (!find_first_extent_bit(unpin, 0, &start, &end,
2793 EXTENT_DIRTY, &cached_state)) {
2794 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2798 if (btrfs_test_opt(fs_info, DISCARD_SYNC))
2799 ret = btrfs_discard_extent(fs_info, start,
2800 end + 1 - start, NULL);
2802 clear_extent_dirty(unpin, start, end, &cached_state);
2803 unpin_extent_range(fs_info, start, end, true);
2804 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2805 free_extent_state(cached_state);
2809 if (btrfs_test_opt(fs_info, DISCARD_ASYNC)) {
2810 btrfs_discard_calc_delay(&fs_info->discard_ctl);
2811 btrfs_discard_schedule_work(&fs_info->discard_ctl, true);
2815 * Transaction is finished. We don't need the lock anymore. We
2816 * do need to clean up the block groups in case of a transaction
2819 deleted_bgs = &trans->transaction->deleted_bgs;
2820 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
2824 if (!TRANS_ABORTED(trans))
2825 ret = btrfs_discard_extent(fs_info,
2827 block_group->length,
2830 list_del_init(&block_group->bg_list);
2831 btrfs_unfreeze_block_group(block_group);
2832 btrfs_put_block_group(block_group);
2835 const char *errstr = btrfs_decode_error(ret);
2837 "discard failed while removing blockgroup: errno=%d %s",
2845 static int do_free_extent_accounting(struct btrfs_trans_handle *trans,
2846 u64 bytenr, u64 num_bytes, bool is_data)
2851 struct btrfs_root *csum_root;
2853 csum_root = btrfs_csum_root(trans->fs_info, bytenr);
2854 ret = btrfs_del_csums(trans, csum_root, bytenr, num_bytes);
2856 btrfs_abort_transaction(trans, ret);
2861 ret = add_to_free_space_tree(trans, bytenr, num_bytes);
2863 btrfs_abort_transaction(trans, ret);
2867 ret = btrfs_update_block_group(trans, bytenr, num_bytes, false);
2869 btrfs_abort_transaction(trans, ret);
2874 #define abort_and_dump(trans, path, fmt, args...) \
2876 btrfs_abort_transaction(trans, -EUCLEAN); \
2877 btrfs_print_leaf(path->nodes[0]); \
2878 btrfs_crit(trans->fs_info, fmt, ##args); \
2882 * Drop one or more refs of @node.
2884 * 1. Locate the extent refs.
2885 * It's either inline in EXTENT/METADATA_ITEM or in keyed SHARED_* item.
2886 * Locate it, then reduce the refs number or remove the ref line completely.
2888 * 2. Update the refs count in EXTENT/METADATA_ITEM
2890 * Inline backref case:
2892 * in extent tree we have:
2894 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
2895 * refs 2 gen 6 flags DATA
2896 * extent data backref root FS_TREE objectid 258 offset 0 count 1
2897 * extent data backref root FS_TREE objectid 257 offset 0 count 1
2899 * This function gets called with:
2901 * node->bytenr = 13631488
2902 * node->num_bytes = 1048576
2903 * root_objectid = FS_TREE
2904 * owner_objectid = 257
2908 * Then we should get some like:
2910 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
2911 * refs 1 gen 6 flags DATA
2912 * extent data backref root FS_TREE objectid 258 offset 0 count 1
2914 * Keyed backref case:
2916 * in extent tree we have:
2918 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
2919 * refs 754 gen 6 flags DATA
2921 * item 2 key (13631488 EXTENT_DATA_REF <HASH>) itemoff 3915 itemsize 28
2922 * extent data backref root FS_TREE objectid 866 offset 0 count 1
2924 * This function get called with:
2926 * node->bytenr = 13631488
2927 * node->num_bytes = 1048576
2928 * root_objectid = FS_TREE
2929 * owner_objectid = 866
2933 * Then we should get some like:
2935 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
2936 * refs 753 gen 6 flags DATA
2938 * And that (13631488 EXTENT_DATA_REF <HASH>) gets removed.
2940 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
2941 struct btrfs_delayed_ref_node *node, u64 parent,
2942 u64 root_objectid, u64 owner_objectid,
2944 struct btrfs_delayed_extent_op *extent_op)
2946 struct btrfs_fs_info *info = trans->fs_info;
2947 struct btrfs_key key;
2948 struct btrfs_path *path;
2949 struct btrfs_root *extent_root;
2950 struct extent_buffer *leaf;
2951 struct btrfs_extent_item *ei;
2952 struct btrfs_extent_inline_ref *iref;
2955 int extent_slot = 0;
2956 int found_extent = 0;
2958 int refs_to_drop = node->ref_mod;
2961 u64 bytenr = node->bytenr;
2962 u64 num_bytes = node->num_bytes;
2963 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
2965 extent_root = btrfs_extent_root(info, bytenr);
2966 ASSERT(extent_root);
2968 path = btrfs_alloc_path();
2972 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
2974 if (!is_data && refs_to_drop != 1) {
2976 "invalid refs_to_drop, dropping more than 1 refs for tree block %llu refs_to_drop %u",
2977 node->bytenr, refs_to_drop);
2979 btrfs_abort_transaction(trans, ret);
2984 skinny_metadata = false;
2986 ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
2987 parent, root_objectid, owner_objectid,
2991 * Either the inline backref or the SHARED_DATA_REF/
2992 * SHARED_BLOCK_REF is found
2994 * Here is a quick path to locate EXTENT/METADATA_ITEM.
2995 * It's possible the EXTENT/METADATA_ITEM is near current slot.
2997 extent_slot = path->slots[0];
2998 while (extent_slot >= 0) {
2999 btrfs_item_key_to_cpu(path->nodes[0], &key,
3001 if (key.objectid != bytenr)
3003 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
3004 key.offset == num_bytes) {
3008 if (key.type == BTRFS_METADATA_ITEM_KEY &&
3009 key.offset == owner_objectid) {
3014 /* Quick path didn't find the EXTEMT/METADATA_ITEM */
3015 if (path->slots[0] - extent_slot > 5)
3020 if (!found_extent) {
3022 abort_and_dump(trans, path,
3023 "invalid iref slot %u, no EXTENT/METADATA_ITEM found but has inline extent ref",
3028 /* Must be SHARED_* item, remove the backref first */
3029 ret = remove_extent_backref(trans, extent_root, path,
3030 NULL, refs_to_drop, is_data);
3032 btrfs_abort_transaction(trans, ret);
3035 btrfs_release_path(path);
3037 /* Slow path to locate EXTENT/METADATA_ITEM */
3038 key.objectid = bytenr;
3039 key.type = BTRFS_EXTENT_ITEM_KEY;
3040 key.offset = num_bytes;
3042 if (!is_data && skinny_metadata) {
3043 key.type = BTRFS_METADATA_ITEM_KEY;
3044 key.offset = owner_objectid;
3047 ret = btrfs_search_slot(trans, extent_root,
3049 if (ret > 0 && skinny_metadata && path->slots[0]) {
3051 * Couldn't find our skinny metadata item,
3052 * see if we have ye olde extent item.
3055 btrfs_item_key_to_cpu(path->nodes[0], &key,
3057 if (key.objectid == bytenr &&
3058 key.type == BTRFS_EXTENT_ITEM_KEY &&
3059 key.offset == num_bytes)
3063 if (ret > 0 && skinny_metadata) {
3064 skinny_metadata = false;
3065 key.objectid = bytenr;
3066 key.type = BTRFS_EXTENT_ITEM_KEY;
3067 key.offset = num_bytes;
3068 btrfs_release_path(path);
3069 ret = btrfs_search_slot(trans, extent_root,
3075 btrfs_print_leaf(path->nodes[0]);
3077 "umm, got %d back from search, was looking for %llu, slot %d",
3078 ret, bytenr, path->slots[0]);
3081 btrfs_abort_transaction(trans, ret);
3084 extent_slot = path->slots[0];
3086 } else if (WARN_ON(ret == -ENOENT)) {
3087 abort_and_dump(trans, path,
3088 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu slot %d",
3089 bytenr, parent, root_objectid, owner_objectid,
3090 owner_offset, path->slots[0]);
3093 btrfs_abort_transaction(trans, ret);
3097 leaf = path->nodes[0];
3098 item_size = btrfs_item_size(leaf, extent_slot);
3099 if (unlikely(item_size < sizeof(*ei))) {
3101 btrfs_err(trans->fs_info,
3102 "unexpected extent item size, has %u expect >= %zu",
3103 item_size, sizeof(*ei));
3104 btrfs_abort_transaction(trans, ret);
3107 ei = btrfs_item_ptr(leaf, extent_slot,
3108 struct btrfs_extent_item);
3109 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
3110 key.type == BTRFS_EXTENT_ITEM_KEY) {
3111 struct btrfs_tree_block_info *bi;
3113 if (item_size < sizeof(*ei) + sizeof(*bi)) {
3114 abort_and_dump(trans, path,
3115 "invalid extent item size for key (%llu, %u, %llu) slot %u owner %llu, has %u expect >= %zu",
3116 key.objectid, key.type, key.offset,
3117 path->slots[0], owner_objectid, item_size,
3118 sizeof(*ei) + sizeof(*bi));
3122 bi = (struct btrfs_tree_block_info *)(ei + 1);
3123 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
3126 refs = btrfs_extent_refs(leaf, ei);
3127 if (refs < refs_to_drop) {
3128 abort_and_dump(trans, path,
3129 "trying to drop %d refs but we only have %llu for bytenr %llu slot %u",
3130 refs_to_drop, refs, bytenr, path->slots[0]);
3134 refs -= refs_to_drop;
3138 __run_delayed_extent_op(extent_op, leaf, ei);
3140 * In the case of inline back ref, reference count will
3141 * be updated by remove_extent_backref
3144 if (!found_extent) {
3145 abort_and_dump(trans, path,
3146 "invalid iref, got inlined extent ref but no EXTENT/METADATA_ITEM found, slot %u",
3152 btrfs_set_extent_refs(leaf, ei, refs);
3153 btrfs_mark_buffer_dirty(trans, leaf);
3156 ret = remove_extent_backref(trans, extent_root, path,
3157 iref, refs_to_drop, is_data);
3159 btrfs_abort_transaction(trans, ret);
3164 /* In this branch refs == 1 */
3166 if (is_data && refs_to_drop !=
3167 extent_data_ref_count(path, iref)) {
3168 abort_and_dump(trans, path,
3169 "invalid refs_to_drop, current refs %u refs_to_drop %u slot %u",
3170 extent_data_ref_count(path, iref),
3171 refs_to_drop, path->slots[0]);
3176 if (path->slots[0] != extent_slot) {
3177 abort_and_dump(trans, path,
3178 "invalid iref, extent item key (%llu %u %llu) slot %u doesn't have wanted iref",
3179 key.objectid, key.type,
3180 key.offset, path->slots[0]);
3186 * No inline ref, we must be at SHARED_* item,
3187 * And it's single ref, it must be:
3188 * | extent_slot ||extent_slot + 1|
3189 * [ EXTENT/METADATA_ITEM ][ SHARED_* ITEM ]
3191 if (path->slots[0] != extent_slot + 1) {
3192 abort_and_dump(trans, path,
3193 "invalid SHARED_* item slot %u, previous item is not EXTENT/METADATA_ITEM",
3198 path->slots[0] = extent_slot;
3203 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
3206 btrfs_abort_transaction(trans, ret);
3209 btrfs_release_path(path);
3211 ret = do_free_extent_accounting(trans, bytenr, num_bytes, is_data);
3213 btrfs_release_path(path);
3216 btrfs_free_path(path);
3221 * when we free an block, it is possible (and likely) that we free the last
3222 * delayed ref for that extent as well. This searches the delayed ref tree for
3223 * a given extent, and if there are no other delayed refs to be processed, it
3224 * removes it from the tree.
3226 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
3229 struct btrfs_delayed_ref_head *head;
3230 struct btrfs_delayed_ref_root *delayed_refs;
3233 delayed_refs = &trans->transaction->delayed_refs;
3234 spin_lock(&delayed_refs->lock);
3235 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
3237 goto out_delayed_unlock;
3239 spin_lock(&head->lock);
3240 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
3243 if (cleanup_extent_op(head) != NULL)
3247 * waiting for the lock here would deadlock. If someone else has it
3248 * locked they are already in the process of dropping it anyway
3250 if (!mutex_trylock(&head->mutex))
3253 btrfs_delete_ref_head(delayed_refs, head);
3254 head->processing = false;
3256 spin_unlock(&head->lock);
3257 spin_unlock(&delayed_refs->lock);
3259 BUG_ON(head->extent_op);
3260 if (head->must_insert_reserved)
3263 btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
3264 mutex_unlock(&head->mutex);
3265 btrfs_put_delayed_ref_head(head);
3268 spin_unlock(&head->lock);
3271 spin_unlock(&delayed_refs->lock);
3275 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
3277 struct extent_buffer *buf,
3278 u64 parent, int last_ref)
3280 struct btrfs_fs_info *fs_info = trans->fs_info;
3281 struct btrfs_ref generic_ref = { 0 };
3284 btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
3285 buf->start, buf->len, parent);
3286 btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
3289 if (root_id != BTRFS_TREE_LOG_OBJECTID) {
3290 btrfs_ref_tree_mod(fs_info, &generic_ref);
3291 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL);
3292 BUG_ON(ret); /* -ENOMEM */
3295 if (last_ref && btrfs_header_generation(buf) == trans->transid) {
3296 struct btrfs_block_group *cache;
3297 bool must_pin = false;
3299 if (root_id != BTRFS_TREE_LOG_OBJECTID) {
3300 ret = check_ref_cleanup(trans, buf->start);
3302 btrfs_redirty_list_add(trans->transaction, buf);
3307 cache = btrfs_lookup_block_group(fs_info, buf->start);
3309 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
3310 pin_down_extent(trans, cache, buf->start, buf->len, 1);
3311 btrfs_put_block_group(cache);
3316 * If there are tree mod log users we may have recorded mod log
3317 * operations for this node. If we re-allocate this node we
3318 * could replay operations on this node that happened when it
3319 * existed in a completely different root. For example if it
3320 * was part of root A, then was reallocated to root B, and we
3321 * are doing a btrfs_old_search_slot(root b), we could replay
3322 * operations that happened when the block was part of root A,
3323 * giving us an inconsistent view of the btree.
3325 * We are safe from races here because at this point no other
3326 * node or root points to this extent buffer, so if after this
3327 * check a new tree mod log user joins we will not have an
3328 * existing log of operations on this node that we have to
3331 if (test_bit(BTRFS_FS_TREE_MOD_LOG_USERS, &fs_info->flags))
3334 if (must_pin || btrfs_is_zoned(fs_info)) {
3335 btrfs_redirty_list_add(trans->transaction, buf);
3336 pin_down_extent(trans, cache, buf->start, buf->len, 1);
3337 btrfs_put_block_group(cache);
3341 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
3343 btrfs_add_free_space(cache, buf->start, buf->len);
3344 btrfs_free_reserved_bytes(cache, buf->len, 0);
3345 btrfs_put_block_group(cache);
3346 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
3351 * Deleting the buffer, clear the corrupt flag since it doesn't
3354 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
3358 /* Can return -ENOMEM */
3359 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
3361 struct btrfs_fs_info *fs_info = trans->fs_info;
3364 if (btrfs_is_testing(fs_info))
3368 * tree log blocks never actually go into the extent allocation
3369 * tree, just update pinning info and exit early.
3371 if ((ref->type == BTRFS_REF_METADATA &&
3372 ref->tree_ref.owning_root == BTRFS_TREE_LOG_OBJECTID) ||
3373 (ref->type == BTRFS_REF_DATA &&
3374 ref->data_ref.owning_root == BTRFS_TREE_LOG_OBJECTID)) {
3375 btrfs_pin_extent(trans, ref->bytenr, ref->len, 1);
3377 } else if (ref->type == BTRFS_REF_METADATA) {
3378 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL);
3380 ret = btrfs_add_delayed_data_ref(trans, ref, 0);
3383 if (!((ref->type == BTRFS_REF_METADATA &&
3384 ref->tree_ref.owning_root == BTRFS_TREE_LOG_OBJECTID) ||
3385 (ref->type == BTRFS_REF_DATA &&
3386 ref->data_ref.owning_root == BTRFS_TREE_LOG_OBJECTID)))
3387 btrfs_ref_tree_mod(fs_info, ref);
3392 enum btrfs_loop_type {
3394 * Start caching block groups but do not wait for progress or for them
3397 LOOP_CACHING_NOWAIT,
3400 * Wait for the block group free_space >= the space we're waiting for if
3401 * the block group isn't cached.
3406 * Allow allocations to happen from block groups that do not yet have a
3407 * size classification.
3409 LOOP_UNSET_SIZE_CLASS,
3412 * Allocate a chunk and then retry the allocation.
3417 * Ignore the size class restrictions for this allocation.
3419 LOOP_WRONG_SIZE_CLASS,
3422 * Ignore the empty size, only try to allocate the number of bytes
3423 * needed for this allocation.
3429 btrfs_lock_block_group(struct btrfs_block_group *cache,
3433 down_read(&cache->data_rwsem);
3436 static inline void btrfs_grab_block_group(struct btrfs_block_group *cache,
3439 btrfs_get_block_group(cache);
3441 down_read(&cache->data_rwsem);
3444 static struct btrfs_block_group *btrfs_lock_cluster(
3445 struct btrfs_block_group *block_group,
3446 struct btrfs_free_cluster *cluster,
3448 __acquires(&cluster->refill_lock)
3450 struct btrfs_block_group *used_bg = NULL;
3452 spin_lock(&cluster->refill_lock);
3454 used_bg = cluster->block_group;
3458 if (used_bg == block_group)
3461 btrfs_get_block_group(used_bg);
3466 if (down_read_trylock(&used_bg->data_rwsem))
3469 spin_unlock(&cluster->refill_lock);
3471 /* We should only have one-level nested. */
3472 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
3474 spin_lock(&cluster->refill_lock);
3475 if (used_bg == cluster->block_group)
3478 up_read(&used_bg->data_rwsem);
3479 btrfs_put_block_group(used_bg);
3484 btrfs_release_block_group(struct btrfs_block_group *cache,
3488 up_read(&cache->data_rwsem);
3489 btrfs_put_block_group(cache);
3493 * Helper function for find_free_extent().
3495 * Return -ENOENT to inform caller that we need fallback to unclustered mode.
3496 * Return >0 to inform caller that we find nothing
3497 * Return 0 means we have found a location and set ffe_ctl->found_offset.
3499 static int find_free_extent_clustered(struct btrfs_block_group *bg,
3500 struct find_free_extent_ctl *ffe_ctl,
3501 struct btrfs_block_group **cluster_bg_ret)
3503 struct btrfs_block_group *cluster_bg;
3504 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3505 u64 aligned_cluster;
3509 cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
3511 goto refill_cluster;
3512 if (cluster_bg != bg && (cluster_bg->ro ||
3513 !block_group_bits(cluster_bg, ffe_ctl->flags)))
3514 goto release_cluster;
3516 offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
3517 ffe_ctl->num_bytes, cluster_bg->start,
3518 &ffe_ctl->max_extent_size);
3520 /* We have a block, we're done */
3521 spin_unlock(&last_ptr->refill_lock);
3522 trace_btrfs_reserve_extent_cluster(cluster_bg, ffe_ctl);
3523 *cluster_bg_ret = cluster_bg;
3524 ffe_ctl->found_offset = offset;
3527 WARN_ON(last_ptr->block_group != cluster_bg);
3531 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
3532 * lets just skip it and let the allocator find whatever block it can
3533 * find. If we reach this point, we will have tried the cluster
3534 * allocator plenty of times and not have found anything, so we are
3535 * likely way too fragmented for the clustering stuff to find anything.
3537 * However, if the cluster is taken from the current block group,
3538 * release the cluster first, so that we stand a better chance of
3539 * succeeding in the unclustered allocation.
3541 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
3542 spin_unlock(&last_ptr->refill_lock);
3543 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3547 /* This cluster didn't work out, free it and start over */
3548 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3550 if (cluster_bg != bg)
3551 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3554 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
3555 spin_unlock(&last_ptr->refill_lock);
3559 aligned_cluster = max_t(u64,
3560 ffe_ctl->empty_cluster + ffe_ctl->empty_size,
3561 bg->full_stripe_len);
3562 ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
3563 ffe_ctl->num_bytes, aligned_cluster);
3565 /* Now pull our allocation out of this cluster */
3566 offset = btrfs_alloc_from_cluster(bg, last_ptr,
3567 ffe_ctl->num_bytes, ffe_ctl->search_start,
3568 &ffe_ctl->max_extent_size);
3570 /* We found one, proceed */
3571 spin_unlock(&last_ptr->refill_lock);
3572 ffe_ctl->found_offset = offset;
3573 trace_btrfs_reserve_extent_cluster(bg, ffe_ctl);
3578 * At this point we either didn't find a cluster or we weren't able to
3579 * allocate a block from our cluster. Free the cluster we've been
3580 * trying to use, and go to the next block group.
3582 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3583 spin_unlock(&last_ptr->refill_lock);
3588 * Return >0 to inform caller that we find nothing
3589 * Return 0 when we found an free extent and set ffe_ctrl->found_offset
3591 static int find_free_extent_unclustered(struct btrfs_block_group *bg,
3592 struct find_free_extent_ctl *ffe_ctl)
3594 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3598 * We are doing an unclustered allocation, set the fragmented flag so
3599 * we don't bother trying to setup a cluster again until we get more
3602 if (unlikely(last_ptr)) {
3603 spin_lock(&last_ptr->lock);
3604 last_ptr->fragmented = 1;
3605 spin_unlock(&last_ptr->lock);
3607 if (ffe_ctl->cached) {
3608 struct btrfs_free_space_ctl *free_space_ctl;
3610 free_space_ctl = bg->free_space_ctl;
3611 spin_lock(&free_space_ctl->tree_lock);
3612 if (free_space_ctl->free_space <
3613 ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
3614 ffe_ctl->empty_size) {
3615 ffe_ctl->total_free_space = max_t(u64,
3616 ffe_ctl->total_free_space,
3617 free_space_ctl->free_space);
3618 spin_unlock(&free_space_ctl->tree_lock);
3621 spin_unlock(&free_space_ctl->tree_lock);
3624 offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
3625 ffe_ctl->num_bytes, ffe_ctl->empty_size,
3626 &ffe_ctl->max_extent_size);
3629 ffe_ctl->found_offset = offset;
3633 static int do_allocation_clustered(struct btrfs_block_group *block_group,
3634 struct find_free_extent_ctl *ffe_ctl,
3635 struct btrfs_block_group **bg_ret)
3639 /* We want to try and use the cluster allocator, so lets look there */
3640 if (ffe_ctl->last_ptr && ffe_ctl->use_cluster) {
3641 ret = find_free_extent_clustered(block_group, ffe_ctl, bg_ret);
3644 /* ret == -ENOENT case falls through */
3647 return find_free_extent_unclustered(block_group, ffe_ctl);
3651 * Tree-log block group locking
3652 * ============================
3654 * fs_info::treelog_bg_lock protects the fs_info::treelog_bg which
3655 * indicates the starting address of a block group, which is reserved only
3656 * for tree-log metadata.
3663 * fs_info::treelog_bg_lock
3667 * Simple allocator for sequential-only block group. It only allows sequential
3668 * allocation. No need to play with trees. This function also reserves the
3669 * bytes as in btrfs_add_reserved_bytes.
3671 static int do_allocation_zoned(struct btrfs_block_group *block_group,
3672 struct find_free_extent_ctl *ffe_ctl,
3673 struct btrfs_block_group **bg_ret)
3675 struct btrfs_fs_info *fs_info = block_group->fs_info;
3676 struct btrfs_space_info *space_info = block_group->space_info;
3677 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3678 u64 start = block_group->start;
3679 u64 num_bytes = ffe_ctl->num_bytes;
3681 u64 bytenr = block_group->start;
3683 u64 data_reloc_bytenr;
3687 ASSERT(btrfs_is_zoned(block_group->fs_info));
3690 * Do not allow non-tree-log blocks in the dedicated tree-log block
3691 * group, and vice versa.
3693 spin_lock(&fs_info->treelog_bg_lock);
3694 log_bytenr = fs_info->treelog_bg;
3695 if (log_bytenr && ((ffe_ctl->for_treelog && bytenr != log_bytenr) ||
3696 (!ffe_ctl->for_treelog && bytenr == log_bytenr)))
3698 spin_unlock(&fs_info->treelog_bg_lock);
3703 * Do not allow non-relocation blocks in the dedicated relocation block
3704 * group, and vice versa.
3706 spin_lock(&fs_info->relocation_bg_lock);
3707 data_reloc_bytenr = fs_info->data_reloc_bg;
3708 if (data_reloc_bytenr &&
3709 ((ffe_ctl->for_data_reloc && bytenr != data_reloc_bytenr) ||
3710 (!ffe_ctl->for_data_reloc && bytenr == data_reloc_bytenr)))
3712 spin_unlock(&fs_info->relocation_bg_lock);
3716 /* Check RO and no space case before trying to activate it */
3717 spin_lock(&block_group->lock);
3718 if (block_group->ro || btrfs_zoned_bg_is_full(block_group)) {
3721 * May need to clear fs_info->{treelog,data_reloc}_bg.
3722 * Return the error after taking the locks.
3725 spin_unlock(&block_group->lock);
3727 /* Metadata block group is activated at write time. */
3728 if (!ret && (block_group->flags & BTRFS_BLOCK_GROUP_DATA) &&
3729 !btrfs_zone_activate(block_group)) {
3732 * May need to clear fs_info->{treelog,data_reloc}_bg.
3733 * Return the error after taking the locks.
3737 spin_lock(&space_info->lock);
3738 spin_lock(&block_group->lock);
3739 spin_lock(&fs_info->treelog_bg_lock);
3740 spin_lock(&fs_info->relocation_bg_lock);
3745 ASSERT(!ffe_ctl->for_treelog ||
3746 block_group->start == fs_info->treelog_bg ||
3747 fs_info->treelog_bg == 0);
3748 ASSERT(!ffe_ctl->for_data_reloc ||
3749 block_group->start == fs_info->data_reloc_bg ||
3750 fs_info->data_reloc_bg == 0);
3752 if (block_group->ro ||
3753 (!ffe_ctl->for_data_reloc &&
3754 test_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags))) {
3760 * Do not allow currently using block group to be tree-log dedicated
3763 if (ffe_ctl->for_treelog && !fs_info->treelog_bg &&
3764 (block_group->used || block_group->reserved)) {
3770 * Do not allow currently used block group to be the data relocation
3771 * dedicated block group.
3773 if (ffe_ctl->for_data_reloc && !fs_info->data_reloc_bg &&
3774 (block_group->used || block_group->reserved)) {
3779 WARN_ON_ONCE(block_group->alloc_offset > block_group->zone_capacity);
3780 avail = block_group->zone_capacity - block_group->alloc_offset;
3781 if (avail < num_bytes) {
3782 if (ffe_ctl->max_extent_size < avail) {
3784 * With sequential allocator, free space is always
3787 ffe_ctl->max_extent_size = avail;
3788 ffe_ctl->total_free_space = avail;
3794 if (ffe_ctl->for_treelog && !fs_info->treelog_bg)
3795 fs_info->treelog_bg = block_group->start;
3797 if (ffe_ctl->for_data_reloc) {
3798 if (!fs_info->data_reloc_bg)
3799 fs_info->data_reloc_bg = block_group->start;
3801 * Do not allow allocations from this block group, unless it is
3802 * for data relocation. Compared to increasing the ->ro, setting
3803 * the ->zoned_data_reloc_ongoing flag still allows nocow
3804 * writers to come in. See btrfs_inc_nocow_writers().
3806 * We need to disable an allocation to avoid an allocation of
3807 * regular (non-relocation data) extent. With mix of relocation
3808 * extents and regular extents, we can dispatch WRITE commands
3809 * (for relocation extents) and ZONE APPEND commands (for
3810 * regular extents) at the same time to the same zone, which
3811 * easily break the write pointer.
3813 * Also, this flag avoids this block group to be zone finished.
3815 set_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags);
3818 ffe_ctl->found_offset = start + block_group->alloc_offset;
3819 block_group->alloc_offset += num_bytes;
3820 spin_lock(&ctl->tree_lock);
3821 ctl->free_space -= num_bytes;
3822 spin_unlock(&ctl->tree_lock);
3825 * We do not check if found_offset is aligned to stripesize. The
3826 * address is anyway rewritten when using zone append writing.
3829 ffe_ctl->search_start = ffe_ctl->found_offset;
3832 if (ret && ffe_ctl->for_treelog)
3833 fs_info->treelog_bg = 0;
3834 if (ret && ffe_ctl->for_data_reloc)
3835 fs_info->data_reloc_bg = 0;
3836 spin_unlock(&fs_info->relocation_bg_lock);
3837 spin_unlock(&fs_info->treelog_bg_lock);
3838 spin_unlock(&block_group->lock);
3839 spin_unlock(&space_info->lock);
3843 static int do_allocation(struct btrfs_block_group *block_group,
3844 struct find_free_extent_ctl *ffe_ctl,
3845 struct btrfs_block_group **bg_ret)
3847 switch (ffe_ctl->policy) {
3848 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3849 return do_allocation_clustered(block_group, ffe_ctl, bg_ret);
3850 case BTRFS_EXTENT_ALLOC_ZONED:
3851 return do_allocation_zoned(block_group, ffe_ctl, bg_ret);
3857 static void release_block_group(struct btrfs_block_group *block_group,
3858 struct find_free_extent_ctl *ffe_ctl,
3861 switch (ffe_ctl->policy) {
3862 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3863 ffe_ctl->retry_uncached = false;
3865 case BTRFS_EXTENT_ALLOC_ZONED:
3872 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
3874 btrfs_release_block_group(block_group, delalloc);
3877 static void found_extent_clustered(struct find_free_extent_ctl *ffe_ctl,
3878 struct btrfs_key *ins)
3880 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3882 if (!ffe_ctl->use_cluster && last_ptr) {
3883 spin_lock(&last_ptr->lock);
3884 last_ptr->window_start = ins->objectid;
3885 spin_unlock(&last_ptr->lock);
3889 static void found_extent(struct find_free_extent_ctl *ffe_ctl,
3890 struct btrfs_key *ins)
3892 switch (ffe_ctl->policy) {
3893 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3894 found_extent_clustered(ffe_ctl, ins);
3896 case BTRFS_EXTENT_ALLOC_ZONED:
3904 static int can_allocate_chunk_zoned(struct btrfs_fs_info *fs_info,
3905 struct find_free_extent_ctl *ffe_ctl)
3907 /* Block group's activeness is not a requirement for METADATA block groups. */
3908 if (!(ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA))
3911 /* If we can activate new zone, just allocate a chunk and use it */
3912 if (btrfs_can_activate_zone(fs_info->fs_devices, ffe_ctl->flags))
3916 * We already reached the max active zones. Try to finish one block
3917 * group to make a room for a new block group. This is only possible
3918 * for a data block group because btrfs_zone_finish() may need to wait
3919 * for a running transaction which can cause a deadlock for metadata
3922 if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA) {
3923 int ret = btrfs_zone_finish_one_bg(fs_info);
3932 * If we have enough free space left in an already active block group
3933 * and we can't activate any other zone now, do not allow allocating a
3934 * new chunk and let find_free_extent() retry with a smaller size.
3936 if (ffe_ctl->max_extent_size >= ffe_ctl->min_alloc_size)
3940 * Even min_alloc_size is not left in any block groups. Since we cannot
3941 * activate a new block group, allocating it may not help. Let's tell a
3942 * caller to try again and hope it progress something by writing some
3943 * parts of the region. That is only possible for data block groups,
3944 * where a part of the region can be written.
3946 if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA)
3950 * We cannot activate a new block group and no enough space left in any
3951 * block groups. So, allocating a new block group may not help. But,
3952 * there is nothing to do anyway, so let's go with it.
3957 static int can_allocate_chunk(struct btrfs_fs_info *fs_info,
3958 struct find_free_extent_ctl *ffe_ctl)
3960 switch (ffe_ctl->policy) {
3961 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3963 case BTRFS_EXTENT_ALLOC_ZONED:
3964 return can_allocate_chunk_zoned(fs_info, ffe_ctl);
3971 * Return >0 means caller needs to re-search for free extent
3972 * Return 0 means we have the needed free extent.
3973 * Return <0 means we failed to locate any free extent.
3975 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
3976 struct btrfs_key *ins,
3977 struct find_free_extent_ctl *ffe_ctl,
3980 struct btrfs_root *root = fs_info->chunk_root;
3983 if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
3984 ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
3985 ffe_ctl->orig_have_caching_bg = true;
3987 if (ins->objectid) {
3988 found_extent(ffe_ctl, ins);
3992 if (ffe_ctl->loop >= LOOP_CACHING_WAIT && ffe_ctl->have_caching_bg)
3996 if (ffe_ctl->index < BTRFS_NR_RAID_TYPES)
3999 /* See the comments for btrfs_loop_type for an explanation of the phases. */
4000 if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
4003 * We want to skip the LOOP_CACHING_WAIT step if we don't have
4004 * any uncached bgs and we've already done a full search
4007 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT &&
4008 (!ffe_ctl->orig_have_caching_bg && full_search))
4012 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
4013 struct btrfs_trans_handle *trans;
4016 /* Check if allocation policy allows to create a new chunk */
4017 ret = can_allocate_chunk(fs_info, ffe_ctl);
4021 trans = current->journal_info;
4025 trans = btrfs_join_transaction(root);
4027 if (IS_ERR(trans)) {
4028 ret = PTR_ERR(trans);
4032 ret = btrfs_chunk_alloc(trans, ffe_ctl->flags,
4033 CHUNK_ALLOC_FORCE_FOR_EXTENT);
4035 /* Do not bail out on ENOSPC since we can do more. */
4036 if (ret == -ENOSPC) {
4041 btrfs_abort_transaction(trans, ret);
4045 btrfs_end_transaction(trans);
4050 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
4051 if (ffe_ctl->policy != BTRFS_EXTENT_ALLOC_CLUSTERED)
4055 * Don't loop again if we already have no empty_size and
4058 if (ffe_ctl->empty_size == 0 &&
4059 ffe_ctl->empty_cluster == 0)
4061 ffe_ctl->empty_size = 0;
4062 ffe_ctl->empty_cluster = 0;
4069 static bool find_free_extent_check_size_class(struct find_free_extent_ctl *ffe_ctl,
4070 struct btrfs_block_group *bg)
4072 if (ffe_ctl->policy == BTRFS_EXTENT_ALLOC_ZONED)
4074 if (!btrfs_block_group_should_use_size_class(bg))
4076 if (ffe_ctl->loop >= LOOP_WRONG_SIZE_CLASS)
4078 if (ffe_ctl->loop >= LOOP_UNSET_SIZE_CLASS &&
4079 bg->size_class == BTRFS_BG_SZ_NONE)
4081 return ffe_ctl->size_class == bg->size_class;
4084 static int prepare_allocation_clustered(struct btrfs_fs_info *fs_info,
4085 struct find_free_extent_ctl *ffe_ctl,
4086 struct btrfs_space_info *space_info,
4087 struct btrfs_key *ins)
4090 * If our free space is heavily fragmented we may not be able to make
4091 * big contiguous allocations, so instead of doing the expensive search
4092 * for free space, simply return ENOSPC with our max_extent_size so we
4093 * can go ahead and search for a more manageable chunk.
4095 * If our max_extent_size is large enough for our allocation simply
4096 * disable clustering since we will likely not be able to find enough
4097 * space to create a cluster and induce latency trying.
4099 if (space_info->max_extent_size) {
4100 spin_lock(&space_info->lock);
4101 if (space_info->max_extent_size &&
4102 ffe_ctl->num_bytes > space_info->max_extent_size) {
4103 ins->offset = space_info->max_extent_size;
4104 spin_unlock(&space_info->lock);
4106 } else if (space_info->max_extent_size) {
4107 ffe_ctl->use_cluster = false;
4109 spin_unlock(&space_info->lock);
4112 ffe_ctl->last_ptr = fetch_cluster_info(fs_info, space_info,
4113 &ffe_ctl->empty_cluster);
4114 if (ffe_ctl->last_ptr) {
4115 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
4117 spin_lock(&last_ptr->lock);
4118 if (last_ptr->block_group)
4119 ffe_ctl->hint_byte = last_ptr->window_start;
4120 if (last_ptr->fragmented) {
4122 * We still set window_start so we can keep track of the
4123 * last place we found an allocation to try and save
4126 ffe_ctl->hint_byte = last_ptr->window_start;
4127 ffe_ctl->use_cluster = false;
4129 spin_unlock(&last_ptr->lock);
4135 static int prepare_allocation(struct btrfs_fs_info *fs_info,
4136 struct find_free_extent_ctl *ffe_ctl,
4137 struct btrfs_space_info *space_info,
4138 struct btrfs_key *ins)
4140 switch (ffe_ctl->policy) {
4141 case BTRFS_EXTENT_ALLOC_CLUSTERED:
4142 return prepare_allocation_clustered(fs_info, ffe_ctl,
4144 case BTRFS_EXTENT_ALLOC_ZONED:
4145 if (ffe_ctl->for_treelog) {
4146 spin_lock(&fs_info->treelog_bg_lock);
4147 if (fs_info->treelog_bg)
4148 ffe_ctl->hint_byte = fs_info->treelog_bg;
4149 spin_unlock(&fs_info->treelog_bg_lock);
4151 if (ffe_ctl->for_data_reloc) {
4152 spin_lock(&fs_info->relocation_bg_lock);
4153 if (fs_info->data_reloc_bg)
4154 ffe_ctl->hint_byte = fs_info->data_reloc_bg;
4155 spin_unlock(&fs_info->relocation_bg_lock);
4164 * walks the btree of allocated extents and find a hole of a given size.
4165 * The key ins is changed to record the hole:
4166 * ins->objectid == start position
4167 * ins->flags = BTRFS_EXTENT_ITEM_KEY
4168 * ins->offset == the size of the hole.
4169 * Any available blocks before search_start are skipped.
4171 * If there is no suitable free space, we will record the max size of
4172 * the free space extent currently.
4174 * The overall logic and call chain:
4176 * find_free_extent()
4177 * |- Iterate through all block groups
4178 * | |- Get a valid block group
4179 * | |- Try to do clustered allocation in that block group
4180 * | |- Try to do unclustered allocation in that block group
4181 * | |- Check if the result is valid
4182 * | | |- If valid, then exit
4183 * | |- Jump to next block group
4185 * |- Push harder to find free extents
4186 * |- If not found, re-iterate all block groups
4188 static noinline int find_free_extent(struct btrfs_root *root,
4189 struct btrfs_key *ins,
4190 struct find_free_extent_ctl *ffe_ctl)
4192 struct btrfs_fs_info *fs_info = root->fs_info;
4194 int cache_block_group_error = 0;
4195 struct btrfs_block_group *block_group = NULL;
4196 struct btrfs_space_info *space_info;
4197 bool full_search = false;
4199 WARN_ON(ffe_ctl->num_bytes < fs_info->sectorsize);
4201 ffe_ctl->search_start = 0;
4202 /* For clustered allocation */
4203 ffe_ctl->empty_cluster = 0;
4204 ffe_ctl->last_ptr = NULL;
4205 ffe_ctl->use_cluster = true;
4206 ffe_ctl->have_caching_bg = false;
4207 ffe_ctl->orig_have_caching_bg = false;
4208 ffe_ctl->index = btrfs_bg_flags_to_raid_index(ffe_ctl->flags);
4210 ffe_ctl->retry_uncached = false;
4211 ffe_ctl->cached = 0;
4212 ffe_ctl->max_extent_size = 0;
4213 ffe_ctl->total_free_space = 0;
4214 ffe_ctl->found_offset = 0;
4215 ffe_ctl->policy = BTRFS_EXTENT_ALLOC_CLUSTERED;
4216 ffe_ctl->size_class = btrfs_calc_block_group_size_class(ffe_ctl->num_bytes);
4218 if (btrfs_is_zoned(fs_info))
4219 ffe_ctl->policy = BTRFS_EXTENT_ALLOC_ZONED;
4221 ins->type = BTRFS_EXTENT_ITEM_KEY;
4225 trace_find_free_extent(root, ffe_ctl);
4227 space_info = btrfs_find_space_info(fs_info, ffe_ctl->flags);
4229 btrfs_err(fs_info, "No space info for %llu", ffe_ctl->flags);
4233 ret = prepare_allocation(fs_info, ffe_ctl, space_info, ins);
4237 ffe_ctl->search_start = max(ffe_ctl->search_start,
4238 first_logical_byte(fs_info));
4239 ffe_ctl->search_start = max(ffe_ctl->search_start, ffe_ctl->hint_byte);
4240 if (ffe_ctl->search_start == ffe_ctl->hint_byte) {
4241 block_group = btrfs_lookup_block_group(fs_info,
4242 ffe_ctl->search_start);
4244 * we don't want to use the block group if it doesn't match our
4245 * allocation bits, or if its not cached.
4247 * However if we are re-searching with an ideal block group
4248 * picked out then we don't care that the block group is cached.
4250 if (block_group && block_group_bits(block_group, ffe_ctl->flags) &&
4251 block_group->cached != BTRFS_CACHE_NO) {
4252 down_read(&space_info->groups_sem);
4253 if (list_empty(&block_group->list) ||
4256 * someone is removing this block group,
4257 * we can't jump into the have_block_group
4258 * target because our list pointers are not
4261 btrfs_put_block_group(block_group);
4262 up_read(&space_info->groups_sem);
4264 ffe_ctl->index = btrfs_bg_flags_to_raid_index(
4265 block_group->flags);
4266 btrfs_lock_block_group(block_group,
4268 ffe_ctl->hinted = true;
4269 goto have_block_group;
4271 } else if (block_group) {
4272 btrfs_put_block_group(block_group);
4276 trace_find_free_extent_search_loop(root, ffe_ctl);
4277 ffe_ctl->have_caching_bg = false;
4278 if (ffe_ctl->index == btrfs_bg_flags_to_raid_index(ffe_ctl->flags) ||
4279 ffe_ctl->index == 0)
4281 down_read(&space_info->groups_sem);
4282 list_for_each_entry(block_group,
4283 &space_info->block_groups[ffe_ctl->index], list) {
4284 struct btrfs_block_group *bg_ret;
4286 ffe_ctl->hinted = false;
4287 /* If the block group is read-only, we can skip it entirely. */
4288 if (unlikely(block_group->ro)) {
4289 if (ffe_ctl->for_treelog)
4290 btrfs_clear_treelog_bg(block_group);
4291 if (ffe_ctl->for_data_reloc)
4292 btrfs_clear_data_reloc_bg(block_group);
4296 btrfs_grab_block_group(block_group, ffe_ctl->delalloc);
4297 ffe_ctl->search_start = block_group->start;
4300 * this can happen if we end up cycling through all the
4301 * raid types, but we want to make sure we only allocate
4302 * for the proper type.
4304 if (!block_group_bits(block_group, ffe_ctl->flags)) {
4305 u64 extra = BTRFS_BLOCK_GROUP_DUP |
4306 BTRFS_BLOCK_GROUP_RAID1_MASK |
4307 BTRFS_BLOCK_GROUP_RAID56_MASK |
4308 BTRFS_BLOCK_GROUP_RAID10;
4311 * if they asked for extra copies and this block group
4312 * doesn't provide them, bail. This does allow us to
4313 * fill raid0 from raid1.
4315 if ((ffe_ctl->flags & extra) && !(block_group->flags & extra))
4319 * This block group has different flags than we want.
4320 * It's possible that we have MIXED_GROUP flag but no
4321 * block group is mixed. Just skip such block group.
4323 btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4328 trace_find_free_extent_have_block_group(root, ffe_ctl, block_group);
4329 ffe_ctl->cached = btrfs_block_group_done(block_group);
4330 if (unlikely(!ffe_ctl->cached)) {
4331 ffe_ctl->have_caching_bg = true;
4332 ret = btrfs_cache_block_group(block_group, false);
4335 * If we get ENOMEM here or something else we want to
4336 * try other block groups, because it may not be fatal.
4337 * However if we can't find anything else we need to
4338 * save our return here so that we return the actual
4339 * error that caused problems, not ENOSPC.
4342 if (!cache_block_group_error)
4343 cache_block_group_error = ret;
4350 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR)) {
4351 if (!cache_block_group_error)
4352 cache_block_group_error = -EIO;
4356 if (!find_free_extent_check_size_class(ffe_ctl, block_group))
4360 ret = do_allocation(block_group, ffe_ctl, &bg_ret);
4364 if (bg_ret && bg_ret != block_group) {
4365 btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4366 block_group = bg_ret;
4370 ffe_ctl->search_start = round_up(ffe_ctl->found_offset,
4371 fs_info->stripesize);
4373 /* move on to the next group */
4374 if (ffe_ctl->search_start + ffe_ctl->num_bytes >
4375 block_group->start + block_group->length) {
4376 btrfs_add_free_space_unused(block_group,
4377 ffe_ctl->found_offset,
4378 ffe_ctl->num_bytes);
4382 if (ffe_ctl->found_offset < ffe_ctl->search_start)
4383 btrfs_add_free_space_unused(block_group,
4384 ffe_ctl->found_offset,
4385 ffe_ctl->search_start - ffe_ctl->found_offset);
4387 ret = btrfs_add_reserved_bytes(block_group, ffe_ctl->ram_bytes,
4390 ffe_ctl->loop >= LOOP_WRONG_SIZE_CLASS);
4391 if (ret == -EAGAIN) {
4392 btrfs_add_free_space_unused(block_group,
4393 ffe_ctl->found_offset,
4394 ffe_ctl->num_bytes);
4397 btrfs_inc_block_group_reservations(block_group);
4399 /* we are all good, lets return */
4400 ins->objectid = ffe_ctl->search_start;
4401 ins->offset = ffe_ctl->num_bytes;
4403 trace_btrfs_reserve_extent(block_group, ffe_ctl);
4404 btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4407 if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
4408 !ffe_ctl->retry_uncached) {
4409 ffe_ctl->retry_uncached = true;
4410 btrfs_wait_block_group_cache_progress(block_group,
4411 ffe_ctl->num_bytes +
4412 ffe_ctl->empty_cluster +
4413 ffe_ctl->empty_size);
4414 goto have_block_group;
4416 release_block_group(block_group, ffe_ctl, ffe_ctl->delalloc);
4419 up_read(&space_info->groups_sem);
4421 ret = find_free_extent_update_loop(fs_info, ins, ffe_ctl, full_search);
4425 if (ret == -ENOSPC && !cache_block_group_error) {
4427 * Use ffe_ctl->total_free_space as fallback if we can't find
4428 * any contiguous hole.
4430 if (!ffe_ctl->max_extent_size)
4431 ffe_ctl->max_extent_size = ffe_ctl->total_free_space;
4432 spin_lock(&space_info->lock);
4433 space_info->max_extent_size = ffe_ctl->max_extent_size;
4434 spin_unlock(&space_info->lock);
4435 ins->offset = ffe_ctl->max_extent_size;
4436 } else if (ret == -ENOSPC) {
4437 ret = cache_block_group_error;
4443 * Entry point to the extent allocator. Tries to find a hole that is at least
4444 * as big as @num_bytes.
4446 * @root - The root that will contain this extent
4448 * @ram_bytes - The amount of space in ram that @num_bytes take. This
4449 * is used for accounting purposes. This value differs
4450 * from @num_bytes only in the case of compressed extents.
4452 * @num_bytes - Number of bytes to allocate on-disk.
4454 * @min_alloc_size - Indicates the minimum amount of space that the
4455 * allocator should try to satisfy. In some cases
4456 * @num_bytes may be larger than what is required and if
4457 * the filesystem is fragmented then allocation fails.
4458 * However, the presence of @min_alloc_size gives a
4459 * chance to try and satisfy the smaller allocation.
4461 * @empty_size - A hint that you plan on doing more COW. This is the
4462 * size in bytes the allocator should try to find free
4463 * next to the block it returns. This is just a hint and
4464 * may be ignored by the allocator.
4466 * @hint_byte - Hint to the allocator to start searching above the byte
4467 * address passed. It might be ignored.
4469 * @ins - This key is modified to record the found hole. It will
4470 * have the following values:
4471 * ins->objectid == start position
4472 * ins->flags = BTRFS_EXTENT_ITEM_KEY
4473 * ins->offset == the size of the hole.
4475 * @is_data - Boolean flag indicating whether an extent is
4476 * allocated for data (true) or metadata (false)
4478 * @delalloc - Boolean flag indicating whether this allocation is for
4479 * delalloc or not. If 'true' data_rwsem of block groups
4480 * is going to be acquired.
4483 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
4484 * case -ENOSPC is returned then @ins->offset will contain the size of the
4485 * largest available hole the allocator managed to find.
4487 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
4488 u64 num_bytes, u64 min_alloc_size,
4489 u64 empty_size, u64 hint_byte,
4490 struct btrfs_key *ins, int is_data, int delalloc)
4492 struct btrfs_fs_info *fs_info = root->fs_info;
4493 struct find_free_extent_ctl ffe_ctl = {};
4494 bool final_tried = num_bytes == min_alloc_size;
4497 bool for_treelog = (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
4498 bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
4500 flags = get_alloc_profile_by_root(root, is_data);
4502 WARN_ON(num_bytes < fs_info->sectorsize);
4504 ffe_ctl.ram_bytes = ram_bytes;
4505 ffe_ctl.num_bytes = num_bytes;
4506 ffe_ctl.min_alloc_size = min_alloc_size;
4507 ffe_ctl.empty_size = empty_size;
4508 ffe_ctl.flags = flags;
4509 ffe_ctl.delalloc = delalloc;
4510 ffe_ctl.hint_byte = hint_byte;
4511 ffe_ctl.for_treelog = for_treelog;
4512 ffe_ctl.for_data_reloc = for_data_reloc;
4514 ret = find_free_extent(root, ins, &ffe_ctl);
4515 if (!ret && !is_data) {
4516 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
4517 } else if (ret == -ENOSPC) {
4518 if (!final_tried && ins->offset) {
4519 num_bytes = min(num_bytes >> 1, ins->offset);
4520 num_bytes = round_down(num_bytes,
4521 fs_info->sectorsize);
4522 num_bytes = max(num_bytes, min_alloc_size);
4523 ram_bytes = num_bytes;
4524 if (num_bytes == min_alloc_size)
4527 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4528 struct btrfs_space_info *sinfo;
4530 sinfo = btrfs_find_space_info(fs_info, flags);
4532 "allocation failed flags %llu, wanted %llu tree-log %d, relocation: %d",
4533 flags, num_bytes, for_treelog, for_data_reloc);
4535 btrfs_dump_space_info(fs_info, sinfo,
4543 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
4544 u64 start, u64 len, int delalloc)
4546 struct btrfs_block_group *cache;
4548 cache = btrfs_lookup_block_group(fs_info, start);
4550 btrfs_err(fs_info, "Unable to find block group for %llu",
4555 btrfs_add_free_space(cache, start, len);
4556 btrfs_free_reserved_bytes(cache, len, delalloc);
4557 trace_btrfs_reserved_extent_free(fs_info, start, len);
4559 btrfs_put_block_group(cache);
4563 int btrfs_pin_reserved_extent(struct btrfs_trans_handle *trans,
4564 const struct extent_buffer *eb)
4566 struct btrfs_block_group *cache;
4569 cache = btrfs_lookup_block_group(trans->fs_info, eb->start);
4571 btrfs_err(trans->fs_info, "unable to find block group for %llu",
4576 ret = pin_down_extent(trans, cache, eb->start, eb->len, 1);
4577 btrfs_put_block_group(cache);
4581 static int alloc_reserved_extent(struct btrfs_trans_handle *trans, u64 bytenr,
4584 struct btrfs_fs_info *fs_info = trans->fs_info;
4587 ret = remove_from_free_space_tree(trans, bytenr, num_bytes);
4591 ret = btrfs_update_block_group(trans, bytenr, num_bytes, true);
4594 btrfs_err(fs_info, "update block group failed for %llu %llu",
4599 trace_btrfs_reserved_extent_alloc(fs_info, bytenr, num_bytes);
4603 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4604 u64 parent, u64 root_objectid,
4605 u64 flags, u64 owner, u64 offset,
4606 struct btrfs_key *ins, int ref_mod)
4608 struct btrfs_fs_info *fs_info = trans->fs_info;
4609 struct btrfs_root *extent_root;
4611 struct btrfs_extent_item *extent_item;
4612 struct btrfs_extent_inline_ref *iref;
4613 struct btrfs_path *path;
4614 struct extent_buffer *leaf;
4619 type = BTRFS_SHARED_DATA_REF_KEY;
4621 type = BTRFS_EXTENT_DATA_REF_KEY;
4623 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
4625 path = btrfs_alloc_path();
4629 extent_root = btrfs_extent_root(fs_info, ins->objectid);
4630 ret = btrfs_insert_empty_item(trans, extent_root, path, ins, size);
4632 btrfs_free_path(path);
4636 leaf = path->nodes[0];
4637 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4638 struct btrfs_extent_item);
4639 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
4640 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4641 btrfs_set_extent_flags(leaf, extent_item,
4642 flags | BTRFS_EXTENT_FLAG_DATA);
4644 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4645 btrfs_set_extent_inline_ref_type(leaf, iref, type);
4647 struct btrfs_shared_data_ref *ref;
4648 ref = (struct btrfs_shared_data_ref *)(iref + 1);
4649 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
4650 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
4652 struct btrfs_extent_data_ref *ref;
4653 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
4654 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
4655 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
4656 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
4657 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
4660 btrfs_mark_buffer_dirty(trans, path->nodes[0]);
4661 btrfs_free_path(path);
4663 return alloc_reserved_extent(trans, ins->objectid, ins->offset);
4666 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
4667 struct btrfs_delayed_ref_node *node,
4668 struct btrfs_delayed_extent_op *extent_op)
4670 struct btrfs_fs_info *fs_info = trans->fs_info;
4671 struct btrfs_root *extent_root;
4673 struct btrfs_extent_item *extent_item;
4674 struct btrfs_key extent_key;
4675 struct btrfs_tree_block_info *block_info;
4676 struct btrfs_extent_inline_ref *iref;
4677 struct btrfs_path *path;
4678 struct extent_buffer *leaf;
4679 struct btrfs_delayed_tree_ref *ref;
4680 u32 size = sizeof(*extent_item) + sizeof(*iref);
4681 u64 flags = extent_op->flags_to_set;
4682 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4684 ref = btrfs_delayed_node_to_tree_ref(node);
4686 extent_key.objectid = node->bytenr;
4687 if (skinny_metadata) {
4688 extent_key.offset = ref->level;
4689 extent_key.type = BTRFS_METADATA_ITEM_KEY;
4691 extent_key.offset = node->num_bytes;
4692 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
4693 size += sizeof(*block_info);
4696 path = btrfs_alloc_path();
4700 extent_root = btrfs_extent_root(fs_info, extent_key.objectid);
4701 ret = btrfs_insert_empty_item(trans, extent_root, path, &extent_key,
4704 btrfs_free_path(path);
4708 leaf = path->nodes[0];
4709 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4710 struct btrfs_extent_item);
4711 btrfs_set_extent_refs(leaf, extent_item, 1);
4712 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4713 btrfs_set_extent_flags(leaf, extent_item,
4714 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
4716 if (skinny_metadata) {
4717 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4719 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
4720 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
4721 btrfs_set_tree_block_level(leaf, block_info, ref->level);
4722 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
4725 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
4726 btrfs_set_extent_inline_ref_type(leaf, iref,
4727 BTRFS_SHARED_BLOCK_REF_KEY);
4728 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
4730 btrfs_set_extent_inline_ref_type(leaf, iref,
4731 BTRFS_TREE_BLOCK_REF_KEY);
4732 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
4735 btrfs_mark_buffer_dirty(trans, leaf);
4736 btrfs_free_path(path);
4738 return alloc_reserved_extent(trans, node->bytenr, fs_info->nodesize);
4741 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4742 struct btrfs_root *root, u64 owner,
4743 u64 offset, u64 ram_bytes,
4744 struct btrfs_key *ins)
4746 struct btrfs_ref generic_ref = { 0 };
4748 BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
4750 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4751 ins->objectid, ins->offset, 0);
4752 btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner,
4754 btrfs_ref_tree_mod(root->fs_info, &generic_ref);
4756 return btrfs_add_delayed_data_ref(trans, &generic_ref, ram_bytes);
4760 * this is used by the tree logging recovery code. It records that
4761 * an extent has been allocated and makes sure to clear the free
4762 * space cache bits as well
4764 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
4765 u64 root_objectid, u64 owner, u64 offset,
4766 struct btrfs_key *ins)
4768 struct btrfs_fs_info *fs_info = trans->fs_info;
4770 struct btrfs_block_group *block_group;
4771 struct btrfs_space_info *space_info;
4774 * Mixed block groups will exclude before processing the log so we only
4775 * need to do the exclude dance if this fs isn't mixed.
4777 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
4778 ret = __exclude_logged_extent(fs_info, ins->objectid,
4784 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
4788 space_info = block_group->space_info;
4789 spin_lock(&space_info->lock);
4790 spin_lock(&block_group->lock);
4791 space_info->bytes_reserved += ins->offset;
4792 block_group->reserved += ins->offset;
4793 spin_unlock(&block_group->lock);
4794 spin_unlock(&space_info->lock);
4796 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
4799 btrfs_pin_extent(trans, ins->objectid, ins->offset, 1);
4800 btrfs_put_block_group(block_group);
4804 #ifdef CONFIG_BTRFS_DEBUG
4806 * Extra safety check in case the extent tree is corrupted and extent allocator
4807 * chooses to use a tree block which is already used and locked.
4809 static bool check_eb_lock_owner(const struct extent_buffer *eb)
4811 if (eb->lock_owner == current->pid) {
4812 btrfs_err_rl(eb->fs_info,
4813 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
4814 eb->start, btrfs_header_owner(eb), current->pid);
4820 static bool check_eb_lock_owner(struct extent_buffer *eb)
4826 static struct extent_buffer *
4827 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4828 u64 bytenr, int level, u64 owner,
4829 enum btrfs_lock_nesting nest)
4831 struct btrfs_fs_info *fs_info = root->fs_info;
4832 struct extent_buffer *buf;
4833 u64 lockdep_owner = owner;
4835 buf = btrfs_find_create_tree_block(fs_info, bytenr, owner, level);
4839 if (check_eb_lock_owner(buf)) {
4840 free_extent_buffer(buf);
4841 return ERR_PTR(-EUCLEAN);
4845 * The reloc trees are just snapshots, so we need them to appear to be
4846 * just like any other fs tree WRT lockdep.
4848 * The exception however is in replace_path() in relocation, where we
4849 * hold the lock on the original fs root and then search for the reloc
4850 * root. At that point we need to make sure any reloc root buffers are
4851 * set to the BTRFS_TREE_RELOC_OBJECTID lockdep class in order to make
4854 if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID &&
4855 !test_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &root->state))
4856 lockdep_owner = BTRFS_FS_TREE_OBJECTID;
4858 /* btrfs_clear_buffer_dirty() accesses generation field. */
4859 btrfs_set_header_generation(buf, trans->transid);
4862 * This needs to stay, because we could allocate a freed block from an
4863 * old tree into a new tree, so we need to make sure this new block is
4864 * set to the appropriate level and owner.
4866 btrfs_set_buffer_lockdep_class(lockdep_owner, buf, level);
4868 __btrfs_tree_lock(buf, nest);
4869 btrfs_clear_buffer_dirty(trans, buf);
4870 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
4871 clear_bit(EXTENT_BUFFER_NO_CHECK, &buf->bflags);
4873 set_extent_buffer_uptodate(buf);
4875 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
4876 btrfs_set_header_level(buf, level);
4877 btrfs_set_header_bytenr(buf, buf->start);
4878 btrfs_set_header_generation(buf, trans->transid);
4879 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
4880 btrfs_set_header_owner(buf, owner);
4881 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
4882 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
4883 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
4884 buf->log_index = root->log_transid % 2;
4886 * we allow two log transactions at a time, use different
4887 * EXTENT bit to differentiate dirty pages.
4889 if (buf->log_index == 0)
4890 set_extent_bit(&root->dirty_log_pages, buf->start,
4891 buf->start + buf->len - 1,
4892 EXTENT_DIRTY, NULL);
4894 set_extent_bit(&root->dirty_log_pages, buf->start,
4895 buf->start + buf->len - 1,
4898 buf->log_index = -1;
4899 set_extent_bit(&trans->transaction->dirty_pages, buf->start,
4900 buf->start + buf->len - 1, EXTENT_DIRTY, NULL);
4902 /* this returns a buffer locked for blocking */
4907 * finds a free extent and does all the dirty work required for allocation
4908 * returns the tree buffer or an ERR_PTR on error.
4910 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
4911 struct btrfs_root *root,
4912 u64 parent, u64 root_objectid,
4913 const struct btrfs_disk_key *key,
4914 int level, u64 hint,
4916 enum btrfs_lock_nesting nest)
4918 struct btrfs_fs_info *fs_info = root->fs_info;
4919 struct btrfs_key ins;
4920 struct btrfs_block_rsv *block_rsv;
4921 struct extent_buffer *buf;
4922 struct btrfs_delayed_extent_op *extent_op;
4923 struct btrfs_ref generic_ref = { 0 };
4926 u32 blocksize = fs_info->nodesize;
4927 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4929 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4930 if (btrfs_is_testing(fs_info)) {
4931 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
4932 level, root_objectid, nest);
4934 root->alloc_bytenr += blocksize;
4939 block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
4940 if (IS_ERR(block_rsv))
4941 return ERR_CAST(block_rsv);
4943 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
4944 empty_size, hint, &ins, 0, 0);
4948 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
4949 root_objectid, nest);
4952 goto out_free_reserved;
4955 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
4957 parent = ins.objectid;
4958 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4962 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
4963 extent_op = btrfs_alloc_delayed_extent_op();
4969 memcpy(&extent_op->key, key, sizeof(extent_op->key));
4971 memset(&extent_op->key, 0, sizeof(extent_op->key));
4972 extent_op->flags_to_set = flags;
4973 extent_op->update_key = skinny_metadata ? false : true;
4974 extent_op->update_flags = true;
4975 extent_op->level = level;
4977 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4978 ins.objectid, ins.offset, parent);
4979 btrfs_init_tree_ref(&generic_ref, level, root_objectid,
4980 root->root_key.objectid, false);
4981 btrfs_ref_tree_mod(fs_info, &generic_ref);
4982 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, extent_op);
4984 goto out_free_delayed;
4989 btrfs_free_delayed_extent_op(extent_op);
4991 btrfs_tree_unlock(buf);
4992 free_extent_buffer(buf);
4994 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
4996 btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
4997 return ERR_PTR(ret);
5000 struct walk_control {
5001 u64 refs[BTRFS_MAX_LEVEL];
5002 u64 flags[BTRFS_MAX_LEVEL];
5003 struct btrfs_key update_progress;
5004 struct btrfs_key drop_progress;
5016 #define DROP_REFERENCE 1
5017 #define UPDATE_BACKREF 2
5019 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
5020 struct btrfs_root *root,
5021 struct walk_control *wc,
5022 struct btrfs_path *path)
5024 struct btrfs_fs_info *fs_info = root->fs_info;
5030 struct btrfs_key key;
5031 struct extent_buffer *eb;
5036 if (path->slots[wc->level] < wc->reada_slot) {
5037 wc->reada_count = wc->reada_count * 2 / 3;
5038 wc->reada_count = max(wc->reada_count, 2);
5040 wc->reada_count = wc->reada_count * 3 / 2;
5041 wc->reada_count = min_t(int, wc->reada_count,
5042 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
5045 eb = path->nodes[wc->level];
5046 nritems = btrfs_header_nritems(eb);
5048 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
5049 if (nread >= wc->reada_count)
5053 bytenr = btrfs_node_blockptr(eb, slot);
5054 generation = btrfs_node_ptr_generation(eb, slot);
5056 if (slot == path->slots[wc->level])
5059 if (wc->stage == UPDATE_BACKREF &&
5060 generation <= root->root_key.offset)
5063 /* We don't lock the tree block, it's OK to be racy here */
5064 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
5065 wc->level - 1, 1, &refs,
5067 /* We don't care about errors in readahead. */
5072 if (wc->stage == DROP_REFERENCE) {
5076 if (wc->level == 1 &&
5077 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5079 if (!wc->update_ref ||
5080 generation <= root->root_key.offset)
5082 btrfs_node_key_to_cpu(eb, &key, slot);
5083 ret = btrfs_comp_cpu_keys(&key,
5084 &wc->update_progress);
5088 if (wc->level == 1 &&
5089 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5093 btrfs_readahead_node_child(eb, slot);
5096 wc->reada_slot = slot;
5100 * helper to process tree block while walking down the tree.
5102 * when wc->stage == UPDATE_BACKREF, this function updates
5103 * back refs for pointers in the block.
5105 * NOTE: return value 1 means we should stop walking down.
5107 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5108 struct btrfs_root *root,
5109 struct btrfs_path *path,
5110 struct walk_control *wc, int lookup_info)
5112 struct btrfs_fs_info *fs_info = root->fs_info;
5113 int level = wc->level;
5114 struct extent_buffer *eb = path->nodes[level];
5115 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5118 if (wc->stage == UPDATE_BACKREF &&
5119 btrfs_header_owner(eb) != root->root_key.objectid)
5123 * when reference count of tree block is 1, it won't increase
5124 * again. once full backref flag is set, we never clear it.
5127 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
5128 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
5129 BUG_ON(!path->locks[level]);
5130 ret = btrfs_lookup_extent_info(trans, fs_info,
5131 eb->start, level, 1,
5134 BUG_ON(ret == -ENOMEM);
5137 BUG_ON(wc->refs[level] == 0);
5140 if (wc->stage == DROP_REFERENCE) {
5141 if (wc->refs[level] > 1)
5144 if (path->locks[level] && !wc->keep_locks) {
5145 btrfs_tree_unlock_rw(eb, path->locks[level]);
5146 path->locks[level] = 0;
5151 /* wc->stage == UPDATE_BACKREF */
5152 if (!(wc->flags[level] & flag)) {
5153 BUG_ON(!path->locks[level]);
5154 ret = btrfs_inc_ref(trans, root, eb, 1);
5155 BUG_ON(ret); /* -ENOMEM */
5156 ret = btrfs_dec_ref(trans, root, eb, 0);
5157 BUG_ON(ret); /* -ENOMEM */
5158 ret = btrfs_set_disk_extent_flags(trans, eb, flag);
5159 BUG_ON(ret); /* -ENOMEM */
5160 wc->flags[level] |= flag;
5164 * the block is shared by multiple trees, so it's not good to
5165 * keep the tree lock
5167 if (path->locks[level] && level > 0) {
5168 btrfs_tree_unlock_rw(eb, path->locks[level]);
5169 path->locks[level] = 0;
5175 * This is used to verify a ref exists for this root to deal with a bug where we
5176 * would have a drop_progress key that hadn't been updated properly.
5178 static int check_ref_exists(struct btrfs_trans_handle *trans,
5179 struct btrfs_root *root, u64 bytenr, u64 parent,
5182 struct btrfs_path *path;
5183 struct btrfs_extent_inline_ref *iref;
5186 path = btrfs_alloc_path();
5190 ret = lookup_extent_backref(trans, path, &iref, bytenr,
5191 root->fs_info->nodesize, parent,
5192 root->root_key.objectid, level, 0);
5193 btrfs_free_path(path);
5202 * helper to process tree block pointer.
5204 * when wc->stage == DROP_REFERENCE, this function checks
5205 * reference count of the block pointed to. if the block
5206 * is shared and we need update back refs for the subtree
5207 * rooted at the block, this function changes wc->stage to
5208 * UPDATE_BACKREF. if the block is shared and there is no
5209 * need to update back, this function drops the reference
5212 * NOTE: return value 1 means we should stop walking down.
5214 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
5215 struct btrfs_root *root,
5216 struct btrfs_path *path,
5217 struct walk_control *wc, int *lookup_info)
5219 struct btrfs_fs_info *fs_info = root->fs_info;
5223 struct btrfs_tree_parent_check check = { 0 };
5224 struct btrfs_key key;
5225 struct btrfs_ref ref = { 0 };
5226 struct extent_buffer *next;
5227 int level = wc->level;
5230 bool need_account = false;
5232 generation = btrfs_node_ptr_generation(path->nodes[level],
5233 path->slots[level]);
5235 * if the lower level block was created before the snapshot
5236 * was created, we know there is no need to update back refs
5239 if (wc->stage == UPDATE_BACKREF &&
5240 generation <= root->root_key.offset) {
5245 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
5247 check.level = level - 1;
5248 check.transid = generation;
5249 check.owner_root = root->root_key.objectid;
5250 check.has_first_key = true;
5251 btrfs_node_key_to_cpu(path->nodes[level], &check.first_key,
5252 path->slots[level]);
5254 next = find_extent_buffer(fs_info, bytenr);
5256 next = btrfs_find_create_tree_block(fs_info, bytenr,
5257 root->root_key.objectid, level - 1);
5259 return PTR_ERR(next);
5262 btrfs_tree_lock(next);
5264 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
5265 &wc->refs[level - 1],
5266 &wc->flags[level - 1]);
5270 if (unlikely(wc->refs[level - 1] == 0)) {
5271 btrfs_err(fs_info, "Missing references.");
5277 if (wc->stage == DROP_REFERENCE) {
5278 if (wc->refs[level - 1] > 1) {
5279 need_account = true;
5281 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5284 if (!wc->update_ref ||
5285 generation <= root->root_key.offset)
5288 btrfs_node_key_to_cpu(path->nodes[level], &key,
5289 path->slots[level]);
5290 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
5294 wc->stage = UPDATE_BACKREF;
5295 wc->shared_level = level - 1;
5299 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5303 if (!btrfs_buffer_uptodate(next, generation, 0)) {
5304 btrfs_tree_unlock(next);
5305 free_extent_buffer(next);
5311 if (reada && level == 1)
5312 reada_walk_down(trans, root, wc, path);
5313 next = read_tree_block(fs_info, bytenr, &check);
5315 return PTR_ERR(next);
5316 } else if (!extent_buffer_uptodate(next)) {
5317 free_extent_buffer(next);
5320 btrfs_tree_lock(next);
5324 ASSERT(level == btrfs_header_level(next));
5325 if (level != btrfs_header_level(next)) {
5326 btrfs_err(root->fs_info, "mismatched level");
5330 path->nodes[level] = next;
5331 path->slots[level] = 0;
5332 path->locks[level] = BTRFS_WRITE_LOCK;
5338 wc->refs[level - 1] = 0;
5339 wc->flags[level - 1] = 0;
5340 if (wc->stage == DROP_REFERENCE) {
5341 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5342 parent = path->nodes[level]->start;
5344 ASSERT(root->root_key.objectid ==
5345 btrfs_header_owner(path->nodes[level]));
5346 if (root->root_key.objectid !=
5347 btrfs_header_owner(path->nodes[level])) {
5348 btrfs_err(root->fs_info,
5349 "mismatched block owner");
5357 * If we had a drop_progress we need to verify the refs are set
5358 * as expected. If we find our ref then we know that from here
5359 * on out everything should be correct, and we can clear the
5362 if (wc->restarted) {
5363 ret = check_ref_exists(trans, root, bytenr, parent,
5374 * Reloc tree doesn't contribute to qgroup numbers, and we have
5375 * already accounted them at merge time (replace_path),
5376 * thus we could skip expensive subtree trace here.
5378 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
5380 ret = btrfs_qgroup_trace_subtree(trans, next,
5381 generation, level - 1);
5383 btrfs_err_rl(fs_info,
5384 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
5390 * We need to update the next key in our walk control so we can
5391 * update the drop_progress key accordingly. We don't care if
5392 * find_next_key doesn't find a key because that means we're at
5393 * the end and are going to clean up now.
5395 wc->drop_level = level;
5396 find_next_key(path, level, &wc->drop_progress);
5398 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
5399 fs_info->nodesize, parent);
5400 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid,
5402 ret = btrfs_free_extent(trans, &ref);
5411 btrfs_tree_unlock(next);
5412 free_extent_buffer(next);
5418 * helper to process tree block while walking up the tree.
5420 * when wc->stage == DROP_REFERENCE, this function drops
5421 * reference count on the block.
5423 * when wc->stage == UPDATE_BACKREF, this function changes
5424 * wc->stage back to DROP_REFERENCE if we changed wc->stage
5425 * to UPDATE_BACKREF previously while processing the block.
5427 * NOTE: return value 1 means we should stop walking up.
5429 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
5430 struct btrfs_root *root,
5431 struct btrfs_path *path,
5432 struct walk_control *wc)
5434 struct btrfs_fs_info *fs_info = root->fs_info;
5436 int level = wc->level;
5437 struct extent_buffer *eb = path->nodes[level];
5440 if (wc->stage == UPDATE_BACKREF) {
5441 BUG_ON(wc->shared_level < level);
5442 if (level < wc->shared_level)
5445 ret = find_next_key(path, level + 1, &wc->update_progress);
5449 wc->stage = DROP_REFERENCE;
5450 wc->shared_level = -1;
5451 path->slots[level] = 0;
5454 * check reference count again if the block isn't locked.
5455 * we should start walking down the tree again if reference
5458 if (!path->locks[level]) {
5460 btrfs_tree_lock(eb);
5461 path->locks[level] = BTRFS_WRITE_LOCK;
5463 ret = btrfs_lookup_extent_info(trans, fs_info,
5464 eb->start, level, 1,
5468 btrfs_tree_unlock_rw(eb, path->locks[level]);
5469 path->locks[level] = 0;
5472 BUG_ON(wc->refs[level] == 0);
5473 if (wc->refs[level] == 1) {
5474 btrfs_tree_unlock_rw(eb, path->locks[level]);
5475 path->locks[level] = 0;
5481 /* wc->stage == DROP_REFERENCE */
5482 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5484 if (wc->refs[level] == 1) {
5486 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5487 ret = btrfs_dec_ref(trans, root, eb, 1);
5489 ret = btrfs_dec_ref(trans, root, eb, 0);
5490 BUG_ON(ret); /* -ENOMEM */
5491 if (is_fstree(root->root_key.objectid)) {
5492 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
5494 btrfs_err_rl(fs_info,
5495 "error %d accounting leaf items, quota is out of sync, rescan required",
5500 /* Make block locked assertion in btrfs_clear_buffer_dirty happy. */
5501 if (!path->locks[level]) {
5502 btrfs_tree_lock(eb);
5503 path->locks[level] = BTRFS_WRITE_LOCK;
5505 btrfs_clear_buffer_dirty(trans, eb);
5508 if (eb == root->node) {
5509 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5511 else if (root->root_key.objectid != btrfs_header_owner(eb))
5512 goto owner_mismatch;
5514 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5515 parent = path->nodes[level + 1]->start;
5516 else if (root->root_key.objectid !=
5517 btrfs_header_owner(path->nodes[level + 1]))
5518 goto owner_mismatch;
5521 btrfs_free_tree_block(trans, btrfs_root_id(root), eb, parent,
5522 wc->refs[level] == 1);
5524 wc->refs[level] = 0;
5525 wc->flags[level] = 0;
5529 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
5530 btrfs_header_owner(eb), root->root_key.objectid);
5534 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
5535 struct btrfs_root *root,
5536 struct btrfs_path *path,
5537 struct walk_control *wc)
5539 int level = wc->level;
5540 int lookup_info = 1;
5543 while (level >= 0) {
5544 ret = walk_down_proc(trans, root, path, wc, lookup_info);
5551 if (path->slots[level] >=
5552 btrfs_header_nritems(path->nodes[level]))
5555 ret = do_walk_down(trans, root, path, wc, &lookup_info);
5557 path->slots[level]++;
5563 return (ret == 1) ? 0 : ret;
5566 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
5567 struct btrfs_root *root,
5568 struct btrfs_path *path,
5569 struct walk_control *wc, int max_level)
5571 int level = wc->level;
5574 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
5575 while (level < max_level && path->nodes[level]) {
5577 if (path->slots[level] + 1 <
5578 btrfs_header_nritems(path->nodes[level])) {
5579 path->slots[level]++;
5582 ret = walk_up_proc(trans, root, path, wc);
5588 if (path->locks[level]) {
5589 btrfs_tree_unlock_rw(path->nodes[level],
5590 path->locks[level]);
5591 path->locks[level] = 0;
5593 free_extent_buffer(path->nodes[level]);
5594 path->nodes[level] = NULL;
5602 * drop a subvolume tree.
5604 * this function traverses the tree freeing any blocks that only
5605 * referenced by the tree.
5607 * when a shared tree block is found. this function decreases its
5608 * reference count by one. if update_ref is true, this function
5609 * also make sure backrefs for the shared block and all lower level
5610 * blocks are properly updated.
5612 * If called with for_reloc == 0, may exit early with -EAGAIN
5614 int btrfs_drop_snapshot(struct btrfs_root *root, int update_ref, int for_reloc)
5616 const bool is_reloc_root = (root->root_key.objectid ==
5617 BTRFS_TREE_RELOC_OBJECTID);
5618 struct btrfs_fs_info *fs_info = root->fs_info;
5619 struct btrfs_path *path;
5620 struct btrfs_trans_handle *trans;
5621 struct btrfs_root *tree_root = fs_info->tree_root;
5622 struct btrfs_root_item *root_item = &root->root_item;
5623 struct walk_control *wc;
5624 struct btrfs_key key;
5628 bool root_dropped = false;
5629 bool unfinished_drop = false;
5631 btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
5633 path = btrfs_alloc_path();
5639 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5641 btrfs_free_path(path);
5647 * Use join to avoid potential EINTR from transaction start. See
5648 * wait_reserve_ticket and the whole reservation callchain.
5651 trans = btrfs_join_transaction(tree_root);
5653 trans = btrfs_start_transaction(tree_root, 0);
5654 if (IS_ERR(trans)) {
5655 err = PTR_ERR(trans);
5659 err = btrfs_run_delayed_items(trans);
5664 * This will help us catch people modifying the fs tree while we're
5665 * dropping it. It is unsafe to mess with the fs tree while it's being
5666 * dropped as we unlock the root node and parent nodes as we walk down
5667 * the tree, assuming nothing will change. If something does change
5668 * then we'll have stale information and drop references to blocks we've
5671 set_bit(BTRFS_ROOT_DELETING, &root->state);
5672 unfinished_drop = test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state);
5674 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
5675 level = btrfs_header_level(root->node);
5676 path->nodes[level] = btrfs_lock_root_node(root);
5677 path->slots[level] = 0;
5678 path->locks[level] = BTRFS_WRITE_LOCK;
5679 memset(&wc->update_progress, 0,
5680 sizeof(wc->update_progress));
5682 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
5683 memcpy(&wc->update_progress, &key,
5684 sizeof(wc->update_progress));
5686 level = btrfs_root_drop_level(root_item);
5688 path->lowest_level = level;
5689 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5690 path->lowest_level = 0;
5698 * unlock our path, this is safe because only this
5699 * function is allowed to delete this snapshot
5701 btrfs_unlock_up_safe(path, 0);
5703 level = btrfs_header_level(root->node);
5705 btrfs_tree_lock(path->nodes[level]);
5706 path->locks[level] = BTRFS_WRITE_LOCK;
5708 ret = btrfs_lookup_extent_info(trans, fs_info,
5709 path->nodes[level]->start,
5710 level, 1, &wc->refs[level],
5716 BUG_ON(wc->refs[level] == 0);
5718 if (level == btrfs_root_drop_level(root_item))
5721 btrfs_tree_unlock(path->nodes[level]);
5722 path->locks[level] = 0;
5723 WARN_ON(wc->refs[level] != 1);
5728 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
5730 wc->shared_level = -1;
5731 wc->stage = DROP_REFERENCE;
5732 wc->update_ref = update_ref;
5734 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5738 ret = walk_down_tree(trans, root, path, wc);
5740 btrfs_abort_transaction(trans, ret);
5745 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
5747 btrfs_abort_transaction(trans, ret);
5753 BUG_ON(wc->stage != DROP_REFERENCE);
5757 if (wc->stage == DROP_REFERENCE) {
5758 wc->drop_level = wc->level;
5759 btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
5761 path->slots[wc->drop_level]);
5763 btrfs_cpu_key_to_disk(&root_item->drop_progress,
5764 &wc->drop_progress);
5765 btrfs_set_root_drop_level(root_item, wc->drop_level);
5767 BUG_ON(wc->level == 0);
5768 if (btrfs_should_end_transaction(trans) ||
5769 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
5770 ret = btrfs_update_root(trans, tree_root,
5774 btrfs_abort_transaction(trans, ret);
5780 btrfs_set_last_root_drop_gen(fs_info, trans->transid);
5782 btrfs_end_transaction_throttle(trans);
5783 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
5784 btrfs_debug(fs_info,
5785 "drop snapshot early exit");
5791 * Use join to avoid potential EINTR from transaction
5792 * start. See wait_reserve_ticket and the whole
5793 * reservation callchain.
5796 trans = btrfs_join_transaction(tree_root);
5798 trans = btrfs_start_transaction(tree_root, 0);
5799 if (IS_ERR(trans)) {
5800 err = PTR_ERR(trans);
5805 btrfs_release_path(path);
5809 ret = btrfs_del_root(trans, &root->root_key);
5811 btrfs_abort_transaction(trans, ret);
5816 if (!is_reloc_root) {
5817 ret = btrfs_find_root(tree_root, &root->root_key, path,
5820 btrfs_abort_transaction(trans, ret);
5823 } else if (ret > 0) {
5824 /* if we fail to delete the orphan item this time
5825 * around, it'll get picked up the next time.
5827 * The most common failure here is just -ENOENT.
5829 btrfs_del_orphan_item(trans, tree_root,
5830 root->root_key.objectid);
5835 * This subvolume is going to be completely dropped, and won't be
5836 * recorded as dirty roots, thus pertrans meta rsv will not be freed at
5837 * commit transaction time. So free it here manually.
5839 btrfs_qgroup_convert_reserved_meta(root, INT_MAX);
5840 btrfs_qgroup_free_meta_all_pertrans(root);
5842 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state))
5843 btrfs_add_dropped_root(trans, root);
5845 btrfs_put_root(root);
5846 root_dropped = true;
5849 btrfs_set_last_root_drop_gen(fs_info, trans->transid);
5851 btrfs_end_transaction_throttle(trans);
5854 btrfs_free_path(path);
5857 * We were an unfinished drop root, check to see if there are any
5858 * pending, and if not clear and wake up any waiters.
5860 if (!err && unfinished_drop)
5861 btrfs_maybe_wake_unfinished_drop(fs_info);
5864 * So if we need to stop dropping the snapshot for whatever reason we
5865 * need to make sure to add it back to the dead root list so that we
5866 * keep trying to do the work later. This also cleans up roots if we
5867 * don't have it in the radix (like when we recover after a power fail
5868 * or unmount) so we don't leak memory.
5870 if (!for_reloc && !root_dropped)
5871 btrfs_add_dead_root(root);
5876 * drop subtree rooted at tree block 'node'.
5878 * NOTE: this function will unlock and release tree block 'node'
5879 * only used by relocation code
5881 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
5882 struct btrfs_root *root,
5883 struct extent_buffer *node,
5884 struct extent_buffer *parent)
5886 struct btrfs_fs_info *fs_info = root->fs_info;
5887 struct btrfs_path *path;
5888 struct walk_control *wc;
5894 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
5896 path = btrfs_alloc_path();
5900 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5902 btrfs_free_path(path);
5906 btrfs_assert_tree_write_locked(parent);
5907 parent_level = btrfs_header_level(parent);
5908 atomic_inc(&parent->refs);
5909 path->nodes[parent_level] = parent;
5910 path->slots[parent_level] = btrfs_header_nritems(parent);
5912 btrfs_assert_tree_write_locked(node);
5913 level = btrfs_header_level(node);
5914 path->nodes[level] = node;
5915 path->slots[level] = 0;
5916 path->locks[level] = BTRFS_WRITE_LOCK;
5918 wc->refs[parent_level] = 1;
5919 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5921 wc->shared_level = -1;
5922 wc->stage = DROP_REFERENCE;
5925 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5928 wret = walk_down_tree(trans, root, path, wc);
5934 wret = walk_up_tree(trans, root, path, wc, parent_level);
5942 btrfs_free_path(path);
5946 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
5949 return unpin_extent_range(fs_info, start, end, false);
5953 * It used to be that old block groups would be left around forever.
5954 * Iterating over them would be enough to trim unused space. Since we
5955 * now automatically remove them, we also need to iterate over unallocated
5958 * We don't want a transaction for this since the discard may take a
5959 * substantial amount of time. We don't require that a transaction be
5960 * running, but we do need to take a running transaction into account
5961 * to ensure that we're not discarding chunks that were released or
5962 * allocated in the current transaction.
5964 * Holding the chunks lock will prevent other threads from allocating
5965 * or releasing chunks, but it won't prevent a running transaction
5966 * from committing and releasing the memory that the pending chunks
5967 * list head uses. For that, we need to take a reference to the
5968 * transaction and hold the commit root sem. We only need to hold
5969 * it while performing the free space search since we have already
5970 * held back allocations.
5972 static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
5974 u64 start = BTRFS_DEVICE_RANGE_RESERVED, len = 0, end = 0;
5979 /* Discard not supported = nothing to do. */
5980 if (!bdev_max_discard_sectors(device->bdev))
5983 /* Not writable = nothing to do. */
5984 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
5987 /* No free space = nothing to do. */
5988 if (device->total_bytes <= device->bytes_used)
5994 struct btrfs_fs_info *fs_info = device->fs_info;
5997 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
6001 find_first_clear_extent_bit(&device->alloc_state, start,
6003 CHUNK_TRIMMED | CHUNK_ALLOCATED);
6005 /* Check if there are any CHUNK_* bits left */
6006 if (start > device->total_bytes) {
6007 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
6008 btrfs_warn_in_rcu(fs_info,
6009 "ignoring attempt to trim beyond device size: offset %llu length %llu device %s device size %llu",
6010 start, end - start + 1,
6011 btrfs_dev_name(device),
6012 device->total_bytes);
6013 mutex_unlock(&fs_info->chunk_mutex);
6018 /* Ensure we skip the reserved space on each device. */
6019 start = max_t(u64, start, BTRFS_DEVICE_RANGE_RESERVED);
6022 * If find_first_clear_extent_bit find a range that spans the
6023 * end of the device it will set end to -1, in this case it's up
6024 * to the caller to trim the value to the size of the device.
6026 end = min(end, device->total_bytes - 1);
6028 len = end - start + 1;
6030 /* We didn't find any extents */
6032 mutex_unlock(&fs_info->chunk_mutex);
6037 ret = btrfs_issue_discard(device->bdev, start, len,
6040 set_extent_bit(&device->alloc_state, start,
6041 start + bytes - 1, CHUNK_TRIMMED, NULL);
6042 mutex_unlock(&fs_info->chunk_mutex);
6050 if (fatal_signal_pending(current)) {
6062 * Trim the whole filesystem by:
6063 * 1) trimming the free space in each block group
6064 * 2) trimming the unallocated space on each device
6066 * This will also continue trimming even if a block group or device encounters
6067 * an error. The return value will be the last error, or 0 if nothing bad
6070 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
6072 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6073 struct btrfs_block_group *cache = NULL;
6074 struct btrfs_device *device;
6076 u64 range_end = U64_MAX;
6086 if (range->start == U64_MAX)
6090 * Check range overflow if range->len is set.
6091 * The default range->len is U64_MAX.
6093 if (range->len != U64_MAX &&
6094 check_add_overflow(range->start, range->len, &range_end))
6097 cache = btrfs_lookup_first_block_group(fs_info, range->start);
6098 for (; cache; cache = btrfs_next_block_group(cache)) {
6099 if (cache->start >= range_end) {
6100 btrfs_put_block_group(cache);
6104 start = max(range->start, cache->start);
6105 end = min(range_end, cache->start + cache->length);
6107 if (end - start >= range->minlen) {
6108 if (!btrfs_block_group_done(cache)) {
6109 ret = btrfs_cache_block_group(cache, true);
6116 ret = btrfs_trim_block_group(cache,
6122 trimmed += group_trimmed;
6133 "failed to trim %llu block group(s), last error %d",
6136 mutex_lock(&fs_devices->device_list_mutex);
6137 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6138 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
6141 ret = btrfs_trim_free_extents(device, &group_trimmed);
6148 trimmed += group_trimmed;
6150 mutex_unlock(&fs_devices->device_list_mutex);
6154 "failed to trim %llu device(s), last error %d",
6155 dev_failed, dev_ret);
6156 range->len = trimmed;