1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/sched/signal.h>
8 #include <linux/pagemap.h>
9 #include <linux/writeback.h>
10 #include <linux/blkdev.h>
11 #include <linux/sort.h>
12 #include <linux/rcupdate.h>
13 #include <linux/kthread.h>
14 #include <linux/slab.h>
15 #include <linux/ratelimit.h>
16 #include <linux/percpu_counter.h>
17 #include <linux/lockdep.h>
18 #include <linux/crc32c.h>
22 #include "print-tree.h"
26 #include "free-space-cache.h"
27 #include "free-space-tree.h"
30 #include "ref-verify.h"
31 #include "space-info.h"
32 #include "block-rsv.h"
33 #include "delalloc-space.h"
34 #include "block-group.h"
36 #include "rcu-string.h"
38 #undef SCRAMBLE_DELAYED_REFS
41 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
42 struct btrfs_delayed_ref_node *node, u64 parent,
43 u64 root_objectid, u64 owner_objectid,
44 u64 owner_offset, int refs_to_drop,
45 struct btrfs_delayed_extent_op *extra_op);
46 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
47 struct extent_buffer *leaf,
48 struct btrfs_extent_item *ei);
49 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
50 u64 parent, u64 root_objectid,
51 u64 flags, u64 owner, u64 offset,
52 struct btrfs_key *ins, int ref_mod);
53 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
54 struct btrfs_delayed_ref_node *node,
55 struct btrfs_delayed_extent_op *extent_op);
56 static int find_next_key(struct btrfs_path *path, int level,
57 struct btrfs_key *key);
59 static int block_group_bits(struct btrfs_block_group *cache, u64 bits)
61 return (cache->flags & bits) == bits;
64 int btrfs_add_excluded_extent(struct btrfs_fs_info *fs_info,
65 u64 start, u64 num_bytes)
67 u64 end = start + num_bytes - 1;
68 set_extent_bits(&fs_info->excluded_extents, start, end,
73 void btrfs_free_excluded_extents(struct btrfs_block_group *cache)
75 struct btrfs_fs_info *fs_info = cache->fs_info;
79 end = start + cache->length - 1;
81 clear_extent_bits(&fs_info->excluded_extents, start, end,
85 /* simple helper to search for an existing data extent at a given offset */
86 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
90 struct btrfs_path *path;
92 path = btrfs_alloc_path();
98 key.type = BTRFS_EXTENT_ITEM_KEY;
99 ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
100 btrfs_free_path(path);
105 * helper function to lookup reference count and flags of a tree block.
107 * the head node for delayed ref is used to store the sum of all the
108 * reference count modifications queued up in the rbtree. the head
109 * node may also store the extent flags to set. This way you can check
110 * to see what the reference count and extent flags would be if all of
111 * the delayed refs are not processed.
113 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
114 struct btrfs_fs_info *fs_info, u64 bytenr,
115 u64 offset, int metadata, u64 *refs, u64 *flags)
117 struct btrfs_delayed_ref_head *head;
118 struct btrfs_delayed_ref_root *delayed_refs;
119 struct btrfs_path *path;
120 struct btrfs_extent_item *ei;
121 struct extent_buffer *leaf;
122 struct btrfs_key key;
129 * If we don't have skinny metadata, don't bother doing anything
132 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
133 offset = fs_info->nodesize;
137 path = btrfs_alloc_path();
142 path->skip_locking = 1;
143 path->search_commit_root = 1;
147 key.objectid = bytenr;
150 key.type = BTRFS_METADATA_ITEM_KEY;
152 key.type = BTRFS_EXTENT_ITEM_KEY;
154 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
158 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
159 if (path->slots[0]) {
161 btrfs_item_key_to_cpu(path->nodes[0], &key,
163 if (key.objectid == bytenr &&
164 key.type == BTRFS_EXTENT_ITEM_KEY &&
165 key.offset == fs_info->nodesize)
171 leaf = path->nodes[0];
172 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
173 if (item_size >= sizeof(*ei)) {
174 ei = btrfs_item_ptr(leaf, path->slots[0],
175 struct btrfs_extent_item);
176 num_refs = btrfs_extent_refs(leaf, ei);
177 extent_flags = btrfs_extent_flags(leaf, ei);
180 btrfs_print_v0_err(fs_info);
182 btrfs_abort_transaction(trans, ret);
184 btrfs_handle_fs_error(fs_info, ret, NULL);
189 BUG_ON(num_refs == 0);
199 delayed_refs = &trans->transaction->delayed_refs;
200 spin_lock(&delayed_refs->lock);
201 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
203 if (!mutex_trylock(&head->mutex)) {
204 refcount_inc(&head->refs);
205 spin_unlock(&delayed_refs->lock);
207 btrfs_release_path(path);
210 * Mutex was contended, block until it's released and try
213 mutex_lock(&head->mutex);
214 mutex_unlock(&head->mutex);
215 btrfs_put_delayed_ref_head(head);
218 spin_lock(&head->lock);
219 if (head->extent_op && head->extent_op->update_flags)
220 extent_flags |= head->extent_op->flags_to_set;
222 BUG_ON(num_refs == 0);
224 num_refs += head->ref_mod;
225 spin_unlock(&head->lock);
226 mutex_unlock(&head->mutex);
228 spin_unlock(&delayed_refs->lock);
230 WARN_ON(num_refs == 0);
234 *flags = extent_flags;
236 btrfs_free_path(path);
241 * Back reference rules. Back refs have three main goals:
243 * 1) differentiate between all holders of references to an extent so that
244 * when a reference is dropped we can make sure it was a valid reference
245 * before freeing the extent.
247 * 2) Provide enough information to quickly find the holders of an extent
248 * if we notice a given block is corrupted or bad.
250 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
251 * maintenance. This is actually the same as #2, but with a slightly
252 * different use case.
254 * There are two kinds of back refs. The implicit back refs is optimized
255 * for pointers in non-shared tree blocks. For a given pointer in a block,
256 * back refs of this kind provide information about the block's owner tree
257 * and the pointer's key. These information allow us to find the block by
258 * b-tree searching. The full back refs is for pointers in tree blocks not
259 * referenced by their owner trees. The location of tree block is recorded
260 * in the back refs. Actually the full back refs is generic, and can be
261 * used in all cases the implicit back refs is used. The major shortcoming
262 * of the full back refs is its overhead. Every time a tree block gets
263 * COWed, we have to update back refs entry for all pointers in it.
265 * For a newly allocated tree block, we use implicit back refs for
266 * pointers in it. This means most tree related operations only involve
267 * implicit back refs. For a tree block created in old transaction, the
268 * only way to drop a reference to it is COW it. So we can detect the
269 * event that tree block loses its owner tree's reference and do the
270 * back refs conversion.
272 * When a tree block is COWed through a tree, there are four cases:
274 * The reference count of the block is one and the tree is the block's
275 * owner tree. Nothing to do in this case.
277 * The reference count of the block is one and the tree is not the
278 * block's owner tree. In this case, full back refs is used for pointers
279 * in the block. Remove these full back refs, add implicit back refs for
280 * every pointers in the new block.
282 * The reference count of the block is greater than one and the tree is
283 * the block's owner tree. In this case, implicit back refs is used for
284 * pointers in the block. Add full back refs for every pointers in the
285 * block, increase lower level extents' reference counts. The original
286 * implicit back refs are entailed to the new block.
288 * The reference count of the block is greater than one and the tree is
289 * not the block's owner tree. Add implicit back refs for every pointer in
290 * the new block, increase lower level extents' reference count.
292 * Back Reference Key composing:
294 * The key objectid corresponds to the first byte in the extent,
295 * The key type is used to differentiate between types of back refs.
296 * There are different meanings of the key offset for different types
299 * File extents can be referenced by:
301 * - multiple snapshots, subvolumes, or different generations in one subvol
302 * - different files inside a single subvolume
303 * - different offsets inside a file (bookend extents in file.c)
305 * The extent ref structure for the implicit back refs has fields for:
307 * - Objectid of the subvolume root
308 * - objectid of the file holding the reference
309 * - original offset in the file
310 * - how many bookend extents
312 * The key offset for the implicit back refs is hash of the first
315 * The extent ref structure for the full back refs has field for:
317 * - number of pointers in the tree leaf
319 * The key offset for the implicit back refs is the first byte of
322 * When a file extent is allocated, The implicit back refs is used.
323 * the fields are filled in:
325 * (root_key.objectid, inode objectid, offset in file, 1)
327 * When a file extent is removed file truncation, we find the
328 * corresponding implicit back refs and check the following fields:
330 * (btrfs_header_owner(leaf), inode objectid, offset in file)
332 * Btree extents can be referenced by:
334 * - Different subvolumes
336 * Both the implicit back refs and the full back refs for tree blocks
337 * only consist of key. The key offset for the implicit back refs is
338 * objectid of block's owner tree. The key offset for the full back refs
339 * is the first byte of parent block.
341 * When implicit back refs is used, information about the lowest key and
342 * level of the tree block are required. These information are stored in
343 * tree block info structure.
347 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
348 * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
349 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
351 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
352 struct btrfs_extent_inline_ref *iref,
353 enum btrfs_inline_ref_type is_data)
355 int type = btrfs_extent_inline_ref_type(eb, iref);
356 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
358 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
359 type == BTRFS_SHARED_BLOCK_REF_KEY ||
360 type == BTRFS_SHARED_DATA_REF_KEY ||
361 type == BTRFS_EXTENT_DATA_REF_KEY) {
362 if (is_data == BTRFS_REF_TYPE_BLOCK) {
363 if (type == BTRFS_TREE_BLOCK_REF_KEY)
365 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
368 * Every shared one has parent tree block,
369 * which must be aligned to sector size.
372 IS_ALIGNED(offset, eb->fs_info->sectorsize))
375 } else if (is_data == BTRFS_REF_TYPE_DATA) {
376 if (type == BTRFS_EXTENT_DATA_REF_KEY)
378 if (type == BTRFS_SHARED_DATA_REF_KEY) {
381 * Every shared one has parent tree block,
382 * which must be aligned to sector size.
385 IS_ALIGNED(offset, eb->fs_info->sectorsize))
389 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
394 btrfs_print_leaf((struct extent_buffer *)eb);
395 btrfs_err(eb->fs_info,
396 "eb %llu iref 0x%lx invalid extent inline ref type %d",
397 eb->start, (unsigned long)iref, type);
400 return BTRFS_REF_TYPE_INVALID;
403 u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
405 u32 high_crc = ~(u32)0;
406 u32 low_crc = ~(u32)0;
409 lenum = cpu_to_le64(root_objectid);
410 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
411 lenum = cpu_to_le64(owner);
412 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
413 lenum = cpu_to_le64(offset);
414 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
416 return ((u64)high_crc << 31) ^ (u64)low_crc;
419 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
420 struct btrfs_extent_data_ref *ref)
422 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
423 btrfs_extent_data_ref_objectid(leaf, ref),
424 btrfs_extent_data_ref_offset(leaf, ref));
427 static int match_extent_data_ref(struct extent_buffer *leaf,
428 struct btrfs_extent_data_ref *ref,
429 u64 root_objectid, u64 owner, u64 offset)
431 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
432 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
433 btrfs_extent_data_ref_offset(leaf, ref) != offset)
438 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
439 struct btrfs_path *path,
440 u64 bytenr, u64 parent,
442 u64 owner, u64 offset)
444 struct btrfs_root *root = trans->fs_info->extent_root;
445 struct btrfs_key key;
446 struct btrfs_extent_data_ref *ref;
447 struct extent_buffer *leaf;
453 key.objectid = bytenr;
455 key.type = BTRFS_SHARED_DATA_REF_KEY;
458 key.type = BTRFS_EXTENT_DATA_REF_KEY;
459 key.offset = hash_extent_data_ref(root_objectid,
464 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
476 leaf = path->nodes[0];
477 nritems = btrfs_header_nritems(leaf);
479 if (path->slots[0] >= nritems) {
480 ret = btrfs_next_leaf(root, path);
486 leaf = path->nodes[0];
487 nritems = btrfs_header_nritems(leaf);
491 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
492 if (key.objectid != bytenr ||
493 key.type != BTRFS_EXTENT_DATA_REF_KEY)
496 ref = btrfs_item_ptr(leaf, path->slots[0],
497 struct btrfs_extent_data_ref);
499 if (match_extent_data_ref(leaf, ref, root_objectid,
502 btrfs_release_path(path);
514 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
515 struct btrfs_path *path,
516 u64 bytenr, u64 parent,
517 u64 root_objectid, u64 owner,
518 u64 offset, int refs_to_add)
520 struct btrfs_root *root = trans->fs_info->extent_root;
521 struct btrfs_key key;
522 struct extent_buffer *leaf;
527 key.objectid = bytenr;
529 key.type = BTRFS_SHARED_DATA_REF_KEY;
531 size = sizeof(struct btrfs_shared_data_ref);
533 key.type = BTRFS_EXTENT_DATA_REF_KEY;
534 key.offset = hash_extent_data_ref(root_objectid,
536 size = sizeof(struct btrfs_extent_data_ref);
539 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
540 if (ret && ret != -EEXIST)
543 leaf = path->nodes[0];
545 struct btrfs_shared_data_ref *ref;
546 ref = btrfs_item_ptr(leaf, path->slots[0],
547 struct btrfs_shared_data_ref);
549 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
551 num_refs = btrfs_shared_data_ref_count(leaf, ref);
552 num_refs += refs_to_add;
553 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
556 struct btrfs_extent_data_ref *ref;
557 while (ret == -EEXIST) {
558 ref = btrfs_item_ptr(leaf, path->slots[0],
559 struct btrfs_extent_data_ref);
560 if (match_extent_data_ref(leaf, ref, root_objectid,
563 btrfs_release_path(path);
565 ret = btrfs_insert_empty_item(trans, root, path, &key,
567 if (ret && ret != -EEXIST)
570 leaf = path->nodes[0];
572 ref = btrfs_item_ptr(leaf, path->slots[0],
573 struct btrfs_extent_data_ref);
575 btrfs_set_extent_data_ref_root(leaf, ref,
577 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
578 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
579 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
581 num_refs = btrfs_extent_data_ref_count(leaf, ref);
582 num_refs += refs_to_add;
583 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
586 btrfs_mark_buffer_dirty(leaf);
589 btrfs_release_path(path);
593 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
594 struct btrfs_path *path,
595 int refs_to_drop, int *last_ref)
597 struct btrfs_key key;
598 struct btrfs_extent_data_ref *ref1 = NULL;
599 struct btrfs_shared_data_ref *ref2 = NULL;
600 struct extent_buffer *leaf;
604 leaf = path->nodes[0];
605 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
607 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
608 ref1 = btrfs_item_ptr(leaf, path->slots[0],
609 struct btrfs_extent_data_ref);
610 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
611 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
612 ref2 = btrfs_item_ptr(leaf, path->slots[0],
613 struct btrfs_shared_data_ref);
614 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
615 } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
616 btrfs_print_v0_err(trans->fs_info);
617 btrfs_abort_transaction(trans, -EINVAL);
623 BUG_ON(num_refs < refs_to_drop);
624 num_refs -= refs_to_drop;
627 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
630 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
631 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
632 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
633 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
634 btrfs_mark_buffer_dirty(leaf);
639 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
640 struct btrfs_extent_inline_ref *iref)
642 struct btrfs_key key;
643 struct extent_buffer *leaf;
644 struct btrfs_extent_data_ref *ref1;
645 struct btrfs_shared_data_ref *ref2;
649 leaf = path->nodes[0];
650 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
652 BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
655 * If type is invalid, we should have bailed out earlier than
658 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
659 ASSERT(type != BTRFS_REF_TYPE_INVALID);
660 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
661 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
662 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
664 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
665 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
667 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
668 ref1 = btrfs_item_ptr(leaf, path->slots[0],
669 struct btrfs_extent_data_ref);
670 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
671 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
672 ref2 = btrfs_item_ptr(leaf, path->slots[0],
673 struct btrfs_shared_data_ref);
674 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
681 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
682 struct btrfs_path *path,
683 u64 bytenr, u64 parent,
686 struct btrfs_root *root = trans->fs_info->extent_root;
687 struct btrfs_key key;
690 key.objectid = bytenr;
692 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
695 key.type = BTRFS_TREE_BLOCK_REF_KEY;
696 key.offset = root_objectid;
699 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
705 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
706 struct btrfs_path *path,
707 u64 bytenr, u64 parent,
710 struct btrfs_key key;
713 key.objectid = bytenr;
715 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
718 key.type = BTRFS_TREE_BLOCK_REF_KEY;
719 key.offset = root_objectid;
722 ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
724 btrfs_release_path(path);
728 static inline int extent_ref_type(u64 parent, u64 owner)
731 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
733 type = BTRFS_SHARED_BLOCK_REF_KEY;
735 type = BTRFS_TREE_BLOCK_REF_KEY;
738 type = BTRFS_SHARED_DATA_REF_KEY;
740 type = BTRFS_EXTENT_DATA_REF_KEY;
745 static int find_next_key(struct btrfs_path *path, int level,
746 struct btrfs_key *key)
749 for (; level < BTRFS_MAX_LEVEL; level++) {
750 if (!path->nodes[level])
752 if (path->slots[level] + 1 >=
753 btrfs_header_nritems(path->nodes[level]))
756 btrfs_item_key_to_cpu(path->nodes[level], key,
757 path->slots[level] + 1);
759 btrfs_node_key_to_cpu(path->nodes[level], key,
760 path->slots[level] + 1);
767 * look for inline back ref. if back ref is found, *ref_ret is set
768 * to the address of inline back ref, and 0 is returned.
770 * if back ref isn't found, *ref_ret is set to the address where it
771 * should be inserted, and -ENOENT is returned.
773 * if insert is true and there are too many inline back refs, the path
774 * points to the extent item, and -EAGAIN is returned.
776 * NOTE: inline back refs are ordered in the same way that back ref
777 * items in the tree are ordered.
779 static noinline_for_stack
780 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
781 struct btrfs_path *path,
782 struct btrfs_extent_inline_ref **ref_ret,
783 u64 bytenr, u64 num_bytes,
784 u64 parent, u64 root_objectid,
785 u64 owner, u64 offset, int insert)
787 struct btrfs_fs_info *fs_info = trans->fs_info;
788 struct btrfs_root *root = fs_info->extent_root;
789 struct btrfs_key key;
790 struct extent_buffer *leaf;
791 struct btrfs_extent_item *ei;
792 struct btrfs_extent_inline_ref *iref;
802 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
805 key.objectid = bytenr;
806 key.type = BTRFS_EXTENT_ITEM_KEY;
807 key.offset = num_bytes;
809 want = extent_ref_type(parent, owner);
811 extra_size = btrfs_extent_inline_ref_size(want);
812 path->search_for_extension = 1;
813 path->keep_locks = 1;
818 * Owner is our level, so we can just add one to get the level for the
819 * block we are interested in.
821 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
822 key.type = BTRFS_METADATA_ITEM_KEY;
827 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
834 * We may be a newly converted file system which still has the old fat
835 * extent entries for metadata, so try and see if we have one of those.
837 if (ret > 0 && skinny_metadata) {
838 skinny_metadata = false;
839 if (path->slots[0]) {
841 btrfs_item_key_to_cpu(path->nodes[0], &key,
843 if (key.objectid == bytenr &&
844 key.type == BTRFS_EXTENT_ITEM_KEY &&
845 key.offset == num_bytes)
849 key.objectid = bytenr;
850 key.type = BTRFS_EXTENT_ITEM_KEY;
851 key.offset = num_bytes;
852 btrfs_release_path(path);
857 if (ret && !insert) {
860 } else if (WARN_ON(ret)) {
865 leaf = path->nodes[0];
866 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
867 if (unlikely(item_size < sizeof(*ei))) {
869 btrfs_print_v0_err(fs_info);
870 btrfs_abort_transaction(trans, err);
874 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
875 flags = btrfs_extent_flags(leaf, ei);
877 ptr = (unsigned long)(ei + 1);
878 end = (unsigned long)ei + item_size;
880 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
881 ptr += sizeof(struct btrfs_tree_block_info);
885 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
886 needed = BTRFS_REF_TYPE_DATA;
888 needed = BTRFS_REF_TYPE_BLOCK;
896 iref = (struct btrfs_extent_inline_ref *)ptr;
897 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
898 if (type == BTRFS_REF_TYPE_INVALID) {
906 ptr += btrfs_extent_inline_ref_size(type);
910 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
911 struct btrfs_extent_data_ref *dref;
912 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
913 if (match_extent_data_ref(leaf, dref, root_objectid,
918 if (hash_extent_data_ref_item(leaf, dref) <
919 hash_extent_data_ref(root_objectid, owner, offset))
923 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
925 if (parent == ref_offset) {
929 if (ref_offset < parent)
932 if (root_objectid == ref_offset) {
936 if (ref_offset < root_objectid)
940 ptr += btrfs_extent_inline_ref_size(type);
942 if (err == -ENOENT && insert) {
943 if (item_size + extra_size >=
944 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
949 * To add new inline back ref, we have to make sure
950 * there is no corresponding back ref item.
951 * For simplicity, we just do not add new inline back
952 * ref if there is any kind of item for this block
954 if (find_next_key(path, 0, &key) == 0 &&
955 key.objectid == bytenr &&
956 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
961 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
964 path->keep_locks = 0;
965 path->search_for_extension = 0;
966 btrfs_unlock_up_safe(path, 1);
972 * helper to add new inline back ref
974 static noinline_for_stack
975 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
976 struct btrfs_path *path,
977 struct btrfs_extent_inline_ref *iref,
978 u64 parent, u64 root_objectid,
979 u64 owner, u64 offset, int refs_to_add,
980 struct btrfs_delayed_extent_op *extent_op)
982 struct extent_buffer *leaf;
983 struct btrfs_extent_item *ei;
986 unsigned long item_offset;
991 leaf = path->nodes[0];
992 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
993 item_offset = (unsigned long)iref - (unsigned long)ei;
995 type = extent_ref_type(parent, owner);
996 size = btrfs_extent_inline_ref_size(type);
998 btrfs_extend_item(path, size);
1000 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1001 refs = btrfs_extent_refs(leaf, ei);
1002 refs += refs_to_add;
1003 btrfs_set_extent_refs(leaf, ei, refs);
1005 __run_delayed_extent_op(extent_op, leaf, ei);
1007 ptr = (unsigned long)ei + item_offset;
1008 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1009 if (ptr < end - size)
1010 memmove_extent_buffer(leaf, ptr + size, ptr,
1013 iref = (struct btrfs_extent_inline_ref *)ptr;
1014 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1015 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1016 struct btrfs_extent_data_ref *dref;
1017 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1018 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1019 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1020 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1021 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1022 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1023 struct btrfs_shared_data_ref *sref;
1024 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1025 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1026 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1027 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1028 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1030 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1032 btrfs_mark_buffer_dirty(leaf);
1035 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1036 struct btrfs_path *path,
1037 struct btrfs_extent_inline_ref **ref_ret,
1038 u64 bytenr, u64 num_bytes, u64 parent,
1039 u64 root_objectid, u64 owner, u64 offset)
1043 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1044 num_bytes, parent, root_objectid,
1049 btrfs_release_path(path);
1052 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1053 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1056 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1057 root_objectid, owner, offset);
1063 * helper to update/remove inline back ref
1065 static noinline_for_stack
1066 void update_inline_extent_backref(struct btrfs_path *path,
1067 struct btrfs_extent_inline_ref *iref,
1069 struct btrfs_delayed_extent_op *extent_op,
1072 struct extent_buffer *leaf = path->nodes[0];
1073 struct btrfs_extent_item *ei;
1074 struct btrfs_extent_data_ref *dref = NULL;
1075 struct btrfs_shared_data_ref *sref = NULL;
1083 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1084 refs = btrfs_extent_refs(leaf, ei);
1085 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1086 refs += refs_to_mod;
1087 btrfs_set_extent_refs(leaf, ei, refs);
1089 __run_delayed_extent_op(extent_op, leaf, ei);
1092 * If type is invalid, we should have bailed out after
1093 * lookup_inline_extent_backref().
1095 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1096 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1098 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1099 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1100 refs = btrfs_extent_data_ref_count(leaf, dref);
1101 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1102 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1103 refs = btrfs_shared_data_ref_count(leaf, sref);
1106 BUG_ON(refs_to_mod != -1);
1109 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1110 refs += refs_to_mod;
1113 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1114 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1116 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1119 size = btrfs_extent_inline_ref_size(type);
1120 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1121 ptr = (unsigned long)iref;
1122 end = (unsigned long)ei + item_size;
1123 if (ptr + size < end)
1124 memmove_extent_buffer(leaf, ptr, ptr + size,
1127 btrfs_truncate_item(path, item_size, 1);
1129 btrfs_mark_buffer_dirty(leaf);
1132 static noinline_for_stack
1133 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1134 struct btrfs_path *path,
1135 u64 bytenr, u64 num_bytes, u64 parent,
1136 u64 root_objectid, u64 owner,
1137 u64 offset, int refs_to_add,
1138 struct btrfs_delayed_extent_op *extent_op)
1140 struct btrfs_extent_inline_ref *iref;
1143 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1144 num_bytes, parent, root_objectid,
1148 * We're adding refs to a tree block we already own, this
1149 * should not happen at all.
1151 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1152 btrfs_crit(trans->fs_info,
1153 "adding refs to an existing tree ref, bytenr %llu num_bytes %llu root_objectid %llu",
1154 bytenr, num_bytes, root_objectid);
1155 if (IS_ENABLED(CONFIG_BTRFS_DEBUG)) {
1157 btrfs_crit(trans->fs_info,
1158 "path->slots[0]=%d path->nodes[0]:", path->slots[0]);
1159 btrfs_print_leaf(path->nodes[0]);
1163 update_inline_extent_backref(path, iref, refs_to_add,
1165 } else if (ret == -ENOENT) {
1166 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1167 root_objectid, owner, offset,
1168 refs_to_add, extent_op);
1174 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1175 struct btrfs_path *path,
1176 struct btrfs_extent_inline_ref *iref,
1177 int refs_to_drop, int is_data, int *last_ref)
1181 BUG_ON(!is_data && refs_to_drop != 1);
1183 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1185 } else if (is_data) {
1186 ret = remove_extent_data_ref(trans, path, refs_to_drop,
1190 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1195 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1196 u64 *discarded_bytes)
1199 u64 bytes_left, end;
1200 u64 aligned_start = ALIGN(start, 1 << 9);
1202 if (WARN_ON(start != aligned_start)) {
1203 len -= aligned_start - start;
1204 len = round_down(len, 1 << 9);
1205 start = aligned_start;
1208 *discarded_bytes = 0;
1216 /* Skip any superblocks on this device. */
1217 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1218 u64 sb_start = btrfs_sb_offset(j);
1219 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1220 u64 size = sb_start - start;
1222 if (!in_range(sb_start, start, bytes_left) &&
1223 !in_range(sb_end, start, bytes_left) &&
1224 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1228 * Superblock spans beginning of range. Adjust start and
1231 if (sb_start <= start) {
1232 start += sb_end - start;
1237 bytes_left = end - start;
1242 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1245 *discarded_bytes += size;
1246 else if (ret != -EOPNOTSUPP)
1255 bytes_left = end - start;
1259 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1262 *discarded_bytes += bytes_left;
1267 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1268 u64 num_bytes, u64 *actual_bytes)
1271 u64 discarded_bytes = 0;
1272 u64 end = bytenr + num_bytes;
1274 struct btrfs_bio *bbio = NULL;
1278 * Avoid races with device replace and make sure our bbio has devices
1279 * associated to its stripes that don't go away while we are discarding.
1281 btrfs_bio_counter_inc_blocked(fs_info);
1283 struct btrfs_bio_stripe *stripe;
1286 num_bytes = end - cur;
1287 /* Tell the block device(s) that the sectors can be discarded */
1288 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, cur,
1289 &num_bytes, &bbio, 0);
1291 * Error can be -ENOMEM, -ENOENT (no such chunk mapping) or
1292 * -EOPNOTSUPP. For any such error, @num_bytes is not updated,
1293 * thus we can't continue anyway.
1298 stripe = bbio->stripes;
1299 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
1301 struct request_queue *req_q;
1303 if (!stripe->dev->bdev) {
1304 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1307 req_q = bdev_get_queue(stripe->dev->bdev);
1308 if (!blk_queue_discard(req_q))
1311 ret = btrfs_issue_discard(stripe->dev->bdev,
1316 discarded_bytes += bytes;
1317 } else if (ret != -EOPNOTSUPP) {
1319 * Logic errors or -ENOMEM, or -EIO, but
1320 * unlikely to happen.
1322 * And since there are two loops, explicitly
1323 * go to out to avoid confusion.
1325 btrfs_put_bbio(bbio);
1330 * Just in case we get back EOPNOTSUPP for some reason,
1331 * just ignore the return value so we don't screw up
1332 * people calling discard_extent.
1336 btrfs_put_bbio(bbio);
1340 btrfs_bio_counter_dec(fs_info);
1343 *actual_bytes = discarded_bytes;
1346 if (ret == -EOPNOTSUPP)
1351 /* Can return -ENOMEM */
1352 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1353 struct btrfs_ref *generic_ref)
1355 struct btrfs_fs_info *fs_info = trans->fs_info;
1358 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
1359 generic_ref->action);
1360 BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
1361 generic_ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID);
1363 if (generic_ref->type == BTRFS_REF_METADATA)
1364 ret = btrfs_add_delayed_tree_ref(trans, generic_ref, NULL);
1366 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0);
1368 btrfs_ref_tree_mod(fs_info, generic_ref);
1374 * __btrfs_inc_extent_ref - insert backreference for a given extent
1376 * The counterpart is in __btrfs_free_extent(), with examples and more details
1379 * @trans: Handle of transaction
1381 * @node: The delayed ref node used to get the bytenr/length for
1382 * extent whose references are incremented.
1384 * @parent: If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
1385 * BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
1386 * bytenr of the parent block. Since new extents are always
1387 * created with indirect references, this will only be the case
1388 * when relocating a shared extent. In that case, root_objectid
1389 * will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
1392 * @root_objectid: The id of the root where this modification has originated,
1393 * this can be either one of the well-known metadata trees or
1394 * the subvolume id which references this extent.
1396 * @owner: For data extents it is the inode number of the owning file.
1397 * For metadata extents this parameter holds the level in the
1398 * tree of the extent.
1400 * @offset: For metadata extents the offset is ignored and is currently
1401 * always passed as 0. For data extents it is the fileoffset
1402 * this extent belongs to.
1404 * @refs_to_add Number of references to add
1406 * @extent_op Pointer to a structure, holding information necessary when
1407 * updating a tree block's flags
1410 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1411 struct btrfs_delayed_ref_node *node,
1412 u64 parent, u64 root_objectid,
1413 u64 owner, u64 offset, int refs_to_add,
1414 struct btrfs_delayed_extent_op *extent_op)
1416 struct btrfs_path *path;
1417 struct extent_buffer *leaf;
1418 struct btrfs_extent_item *item;
1419 struct btrfs_key key;
1420 u64 bytenr = node->bytenr;
1421 u64 num_bytes = node->num_bytes;
1425 path = btrfs_alloc_path();
1429 /* this will setup the path even if it fails to insert the back ref */
1430 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
1431 parent, root_objectid, owner,
1432 offset, refs_to_add, extent_op);
1433 if ((ret < 0 && ret != -EAGAIN) || !ret)
1437 * Ok we had -EAGAIN which means we didn't have space to insert and
1438 * inline extent ref, so just update the reference count and add a
1441 leaf = path->nodes[0];
1442 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1443 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1444 refs = btrfs_extent_refs(leaf, item);
1445 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1447 __run_delayed_extent_op(extent_op, leaf, item);
1449 btrfs_mark_buffer_dirty(leaf);
1450 btrfs_release_path(path);
1452 /* now insert the actual backref */
1453 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1454 BUG_ON(refs_to_add != 1);
1455 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1458 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1459 root_objectid, owner, offset,
1463 btrfs_abort_transaction(trans, ret);
1465 btrfs_free_path(path);
1469 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1470 struct btrfs_delayed_ref_node *node,
1471 struct btrfs_delayed_extent_op *extent_op,
1472 int insert_reserved)
1475 struct btrfs_delayed_data_ref *ref;
1476 struct btrfs_key ins;
1481 ins.objectid = node->bytenr;
1482 ins.offset = node->num_bytes;
1483 ins.type = BTRFS_EXTENT_ITEM_KEY;
1485 ref = btrfs_delayed_node_to_data_ref(node);
1486 trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
1488 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1489 parent = ref->parent;
1490 ref_root = ref->root;
1492 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1494 flags |= extent_op->flags_to_set;
1495 ret = alloc_reserved_file_extent(trans, parent, ref_root,
1496 flags, ref->objectid,
1499 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1500 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
1501 ref->objectid, ref->offset,
1502 node->ref_mod, extent_op);
1503 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1504 ret = __btrfs_free_extent(trans, node, parent,
1505 ref_root, ref->objectid,
1506 ref->offset, node->ref_mod,
1514 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1515 struct extent_buffer *leaf,
1516 struct btrfs_extent_item *ei)
1518 u64 flags = btrfs_extent_flags(leaf, ei);
1519 if (extent_op->update_flags) {
1520 flags |= extent_op->flags_to_set;
1521 btrfs_set_extent_flags(leaf, ei, flags);
1524 if (extent_op->update_key) {
1525 struct btrfs_tree_block_info *bi;
1526 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1527 bi = (struct btrfs_tree_block_info *)(ei + 1);
1528 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1532 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1533 struct btrfs_delayed_ref_head *head,
1534 struct btrfs_delayed_extent_op *extent_op)
1536 struct btrfs_fs_info *fs_info = trans->fs_info;
1537 struct btrfs_key key;
1538 struct btrfs_path *path;
1539 struct btrfs_extent_item *ei;
1540 struct extent_buffer *leaf;
1544 int metadata = !extent_op->is_data;
1546 if (TRANS_ABORTED(trans))
1549 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1552 path = btrfs_alloc_path();
1556 key.objectid = head->bytenr;
1559 key.type = BTRFS_METADATA_ITEM_KEY;
1560 key.offset = extent_op->level;
1562 key.type = BTRFS_EXTENT_ITEM_KEY;
1563 key.offset = head->num_bytes;
1567 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
1574 if (path->slots[0] > 0) {
1576 btrfs_item_key_to_cpu(path->nodes[0], &key,
1578 if (key.objectid == head->bytenr &&
1579 key.type == BTRFS_EXTENT_ITEM_KEY &&
1580 key.offset == head->num_bytes)
1584 btrfs_release_path(path);
1587 key.objectid = head->bytenr;
1588 key.offset = head->num_bytes;
1589 key.type = BTRFS_EXTENT_ITEM_KEY;
1598 leaf = path->nodes[0];
1599 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1601 if (unlikely(item_size < sizeof(*ei))) {
1603 btrfs_print_v0_err(fs_info);
1604 btrfs_abort_transaction(trans, err);
1608 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1609 __run_delayed_extent_op(extent_op, leaf, ei);
1611 btrfs_mark_buffer_dirty(leaf);
1613 btrfs_free_path(path);
1617 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
1618 struct btrfs_delayed_ref_node *node,
1619 struct btrfs_delayed_extent_op *extent_op,
1620 int insert_reserved)
1623 struct btrfs_delayed_tree_ref *ref;
1627 ref = btrfs_delayed_node_to_tree_ref(node);
1628 trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
1630 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1631 parent = ref->parent;
1632 ref_root = ref->root;
1634 if (node->ref_mod != 1) {
1635 btrfs_err(trans->fs_info,
1636 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
1637 node->bytenr, node->ref_mod, node->action, ref_root,
1641 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1642 BUG_ON(!extent_op || !extent_op->update_flags);
1643 ret = alloc_reserved_tree_block(trans, node, extent_op);
1644 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1645 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
1646 ref->level, 0, 1, extent_op);
1647 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1648 ret = __btrfs_free_extent(trans, node, parent, ref_root,
1649 ref->level, 0, 1, extent_op);
1656 /* helper function to actually process a single delayed ref entry */
1657 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
1658 struct btrfs_delayed_ref_node *node,
1659 struct btrfs_delayed_extent_op *extent_op,
1660 int insert_reserved)
1664 if (TRANS_ABORTED(trans)) {
1665 if (insert_reserved)
1666 btrfs_pin_extent(trans, node->bytenr, node->num_bytes, 1);
1670 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
1671 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1672 ret = run_delayed_tree_ref(trans, node, extent_op,
1674 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
1675 node->type == BTRFS_SHARED_DATA_REF_KEY)
1676 ret = run_delayed_data_ref(trans, node, extent_op,
1680 if (ret && insert_reserved)
1681 btrfs_pin_extent(trans, node->bytenr, node->num_bytes, 1);
1685 static inline struct btrfs_delayed_ref_node *
1686 select_delayed_ref(struct btrfs_delayed_ref_head *head)
1688 struct btrfs_delayed_ref_node *ref;
1690 if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
1694 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
1695 * This is to prevent a ref count from going down to zero, which deletes
1696 * the extent item from the extent tree, when there still are references
1697 * to add, which would fail because they would not find the extent item.
1699 if (!list_empty(&head->ref_add_list))
1700 return list_first_entry(&head->ref_add_list,
1701 struct btrfs_delayed_ref_node, add_list);
1703 ref = rb_entry(rb_first_cached(&head->ref_tree),
1704 struct btrfs_delayed_ref_node, ref_node);
1705 ASSERT(list_empty(&ref->add_list));
1709 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
1710 struct btrfs_delayed_ref_head *head)
1712 spin_lock(&delayed_refs->lock);
1713 head->processing = 0;
1714 delayed_refs->num_heads_ready++;
1715 spin_unlock(&delayed_refs->lock);
1716 btrfs_delayed_ref_unlock(head);
1719 static struct btrfs_delayed_extent_op *cleanup_extent_op(
1720 struct btrfs_delayed_ref_head *head)
1722 struct btrfs_delayed_extent_op *extent_op = head->extent_op;
1727 if (head->must_insert_reserved) {
1728 head->extent_op = NULL;
1729 btrfs_free_delayed_extent_op(extent_op);
1735 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
1736 struct btrfs_delayed_ref_head *head)
1738 struct btrfs_delayed_extent_op *extent_op;
1741 extent_op = cleanup_extent_op(head);
1744 head->extent_op = NULL;
1745 spin_unlock(&head->lock);
1746 ret = run_delayed_extent_op(trans, head, extent_op);
1747 btrfs_free_delayed_extent_op(extent_op);
1748 return ret ? ret : 1;
1751 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
1752 struct btrfs_delayed_ref_root *delayed_refs,
1753 struct btrfs_delayed_ref_head *head)
1755 int nr_items = 1; /* Dropping this ref head update. */
1758 * We had csum deletions accounted for in our delayed refs rsv, we need
1759 * to drop the csum leaves for this update from our delayed_refs_rsv.
1761 if (head->total_ref_mod < 0 && head->is_data) {
1762 spin_lock(&delayed_refs->lock);
1763 delayed_refs->pending_csums -= head->num_bytes;
1764 spin_unlock(&delayed_refs->lock);
1765 nr_items += btrfs_csum_bytes_to_leaves(fs_info, head->num_bytes);
1769 * We were dropping refs, or had a new ref and dropped it, and thus must
1770 * adjust down our total_bytes_pinned, the space may or may not have
1771 * been pinned and so is accounted for properly in the pinned space by
1774 if (head->total_ref_mod < 0 ||
1775 (head->total_ref_mod == 0 && head->must_insert_reserved)) {
1776 u64 flags = btrfs_ref_head_to_space_flags(head);
1778 btrfs_mod_total_bytes_pinned(fs_info, flags, -head->num_bytes);
1781 btrfs_delayed_refs_rsv_release(fs_info, nr_items);
1784 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
1785 struct btrfs_delayed_ref_head *head)
1788 struct btrfs_fs_info *fs_info = trans->fs_info;
1789 struct btrfs_delayed_ref_root *delayed_refs;
1792 delayed_refs = &trans->transaction->delayed_refs;
1794 ret = run_and_cleanup_extent_op(trans, head);
1796 unselect_delayed_ref_head(delayed_refs, head);
1797 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
1804 * Need to drop our head ref lock and re-acquire the delayed ref lock
1805 * and then re-check to make sure nobody got added.
1807 spin_unlock(&head->lock);
1808 spin_lock(&delayed_refs->lock);
1809 spin_lock(&head->lock);
1810 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
1811 spin_unlock(&head->lock);
1812 spin_unlock(&delayed_refs->lock);
1815 btrfs_delete_ref_head(delayed_refs, head);
1816 spin_unlock(&head->lock);
1817 spin_unlock(&delayed_refs->lock);
1819 if (head->must_insert_reserved) {
1820 btrfs_pin_extent(trans, head->bytenr, head->num_bytes, 1);
1821 if (head->is_data) {
1822 ret = btrfs_del_csums(trans, fs_info->csum_root,
1823 head->bytenr, head->num_bytes);
1827 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
1829 trace_run_delayed_ref_head(fs_info, head, 0);
1830 btrfs_delayed_ref_unlock(head);
1831 btrfs_put_delayed_ref_head(head);
1835 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
1836 struct btrfs_trans_handle *trans)
1838 struct btrfs_delayed_ref_root *delayed_refs =
1839 &trans->transaction->delayed_refs;
1840 struct btrfs_delayed_ref_head *head = NULL;
1843 spin_lock(&delayed_refs->lock);
1844 head = btrfs_select_ref_head(delayed_refs);
1846 spin_unlock(&delayed_refs->lock);
1851 * Grab the lock that says we are going to process all the refs for
1854 ret = btrfs_delayed_ref_lock(delayed_refs, head);
1855 spin_unlock(&delayed_refs->lock);
1858 * We may have dropped the spin lock to get the head mutex lock, and
1859 * that might have given someone else time to free the head. If that's
1860 * true, it has been removed from our list and we can move on.
1863 head = ERR_PTR(-EAGAIN);
1868 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
1869 struct btrfs_delayed_ref_head *locked_ref,
1870 unsigned long *run_refs)
1872 struct btrfs_fs_info *fs_info = trans->fs_info;
1873 struct btrfs_delayed_ref_root *delayed_refs;
1874 struct btrfs_delayed_extent_op *extent_op;
1875 struct btrfs_delayed_ref_node *ref;
1876 int must_insert_reserved = 0;
1879 delayed_refs = &trans->transaction->delayed_refs;
1881 lockdep_assert_held(&locked_ref->mutex);
1882 lockdep_assert_held(&locked_ref->lock);
1884 while ((ref = select_delayed_ref(locked_ref))) {
1886 btrfs_check_delayed_seq(fs_info, ref->seq)) {
1887 spin_unlock(&locked_ref->lock);
1888 unselect_delayed_ref_head(delayed_refs, locked_ref);
1894 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
1895 RB_CLEAR_NODE(&ref->ref_node);
1896 if (!list_empty(&ref->add_list))
1897 list_del(&ref->add_list);
1899 * When we play the delayed ref, also correct the ref_mod on
1902 switch (ref->action) {
1903 case BTRFS_ADD_DELAYED_REF:
1904 case BTRFS_ADD_DELAYED_EXTENT:
1905 locked_ref->ref_mod -= ref->ref_mod;
1907 case BTRFS_DROP_DELAYED_REF:
1908 locked_ref->ref_mod += ref->ref_mod;
1913 atomic_dec(&delayed_refs->num_entries);
1916 * Record the must_insert_reserved flag before we drop the
1919 must_insert_reserved = locked_ref->must_insert_reserved;
1920 locked_ref->must_insert_reserved = 0;
1922 extent_op = locked_ref->extent_op;
1923 locked_ref->extent_op = NULL;
1924 spin_unlock(&locked_ref->lock);
1926 ret = run_one_delayed_ref(trans, ref, extent_op,
1927 must_insert_reserved);
1929 btrfs_free_delayed_extent_op(extent_op);
1931 unselect_delayed_ref_head(delayed_refs, locked_ref);
1932 btrfs_put_delayed_ref(ref);
1933 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
1938 btrfs_put_delayed_ref(ref);
1941 spin_lock(&locked_ref->lock);
1942 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
1949 * Returns 0 on success or if called with an already aborted transaction.
1950 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
1952 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
1955 struct btrfs_fs_info *fs_info = trans->fs_info;
1956 struct btrfs_delayed_ref_root *delayed_refs;
1957 struct btrfs_delayed_ref_head *locked_ref = NULL;
1958 ktime_t start = ktime_get();
1960 unsigned long count = 0;
1961 unsigned long actual_count = 0;
1963 delayed_refs = &trans->transaction->delayed_refs;
1966 locked_ref = btrfs_obtain_ref_head(trans);
1967 if (IS_ERR_OR_NULL(locked_ref)) {
1968 if (PTR_ERR(locked_ref) == -EAGAIN) {
1977 * We need to try and merge add/drops of the same ref since we
1978 * can run into issues with relocate dropping the implicit ref
1979 * and then it being added back again before the drop can
1980 * finish. If we merged anything we need to re-loop so we can
1982 * Or we can get node references of the same type that weren't
1983 * merged when created due to bumps in the tree mod seq, and
1984 * we need to merge them to prevent adding an inline extent
1985 * backref before dropping it (triggering a BUG_ON at
1986 * insert_inline_extent_backref()).
1988 spin_lock(&locked_ref->lock);
1989 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
1991 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
1993 if (ret < 0 && ret != -EAGAIN) {
1995 * Error, btrfs_run_delayed_refs_for_head already
1996 * unlocked everything so just bail out
2001 * Success, perform the usual cleanup of a processed
2004 ret = cleanup_ref_head(trans, locked_ref);
2006 /* We dropped our lock, we need to loop. */
2015 * Either success case or btrfs_run_delayed_refs_for_head
2016 * returned -EAGAIN, meaning we need to select another head
2021 } while ((nr != -1 && count < nr) || locked_ref);
2024 * We don't want to include ref heads since we can have empty ref heads
2025 * and those will drastically skew our runtime down since we just do
2026 * accounting, no actual extent tree updates.
2028 if (actual_count > 0) {
2029 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2033 * We weigh the current average higher than our current runtime
2034 * to avoid large swings in the average.
2036 spin_lock(&delayed_refs->lock);
2037 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2038 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2039 spin_unlock(&delayed_refs->lock);
2044 #ifdef SCRAMBLE_DELAYED_REFS
2046 * Normally delayed refs get processed in ascending bytenr order. This
2047 * correlates in most cases to the order added. To expose dependencies on this
2048 * order, we start to process the tree in the middle instead of the beginning
2050 static u64 find_middle(struct rb_root *root)
2052 struct rb_node *n = root->rb_node;
2053 struct btrfs_delayed_ref_node *entry;
2056 u64 first = 0, last = 0;
2060 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2061 first = entry->bytenr;
2065 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2066 last = entry->bytenr;
2071 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2072 WARN_ON(!entry->in_tree);
2074 middle = entry->bytenr;
2088 * this starts processing the delayed reference count updates and
2089 * extent insertions we have queued up so far. count can be
2090 * 0, which means to process everything in the tree at the start
2091 * of the run (but not newly added entries), or it can be some target
2092 * number you'd like to process.
2094 * Returns 0 on success or if called with an aborted transaction
2095 * Returns <0 on error and aborts the transaction
2097 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2098 unsigned long count)
2100 struct btrfs_fs_info *fs_info = trans->fs_info;
2101 struct rb_node *node;
2102 struct btrfs_delayed_ref_root *delayed_refs;
2103 struct btrfs_delayed_ref_head *head;
2105 int run_all = count == (unsigned long)-1;
2107 /* We'll clean this up in btrfs_cleanup_transaction */
2108 if (TRANS_ABORTED(trans))
2111 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2114 delayed_refs = &trans->transaction->delayed_refs;
2116 count = atomic_read(&delayed_refs->num_entries) * 2;
2119 #ifdef SCRAMBLE_DELAYED_REFS
2120 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2122 ret = __btrfs_run_delayed_refs(trans, count);
2124 btrfs_abort_transaction(trans, ret);
2129 btrfs_create_pending_block_groups(trans);
2131 spin_lock(&delayed_refs->lock);
2132 node = rb_first_cached(&delayed_refs->href_root);
2134 spin_unlock(&delayed_refs->lock);
2137 head = rb_entry(node, struct btrfs_delayed_ref_head,
2139 refcount_inc(&head->refs);
2140 spin_unlock(&delayed_refs->lock);
2142 /* Mutex was contended, block until it's released and retry. */
2143 mutex_lock(&head->mutex);
2144 mutex_unlock(&head->mutex);
2146 btrfs_put_delayed_ref_head(head);
2154 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2155 struct extent_buffer *eb, u64 flags,
2156 int level, int is_data)
2158 struct btrfs_delayed_extent_op *extent_op;
2161 extent_op = btrfs_alloc_delayed_extent_op();
2165 extent_op->flags_to_set = flags;
2166 extent_op->update_flags = true;
2167 extent_op->update_key = false;
2168 extent_op->is_data = is_data ? true : false;
2169 extent_op->level = level;
2171 ret = btrfs_add_delayed_extent_op(trans, eb->start, eb->len, extent_op);
2173 btrfs_free_delayed_extent_op(extent_op);
2177 static noinline int check_delayed_ref(struct btrfs_root *root,
2178 struct btrfs_path *path,
2179 u64 objectid, u64 offset, u64 bytenr)
2181 struct btrfs_delayed_ref_head *head;
2182 struct btrfs_delayed_ref_node *ref;
2183 struct btrfs_delayed_data_ref *data_ref;
2184 struct btrfs_delayed_ref_root *delayed_refs;
2185 struct btrfs_transaction *cur_trans;
2186 struct rb_node *node;
2189 spin_lock(&root->fs_info->trans_lock);
2190 cur_trans = root->fs_info->running_transaction;
2192 refcount_inc(&cur_trans->use_count);
2193 spin_unlock(&root->fs_info->trans_lock);
2197 delayed_refs = &cur_trans->delayed_refs;
2198 spin_lock(&delayed_refs->lock);
2199 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2201 spin_unlock(&delayed_refs->lock);
2202 btrfs_put_transaction(cur_trans);
2206 if (!mutex_trylock(&head->mutex)) {
2207 refcount_inc(&head->refs);
2208 spin_unlock(&delayed_refs->lock);
2210 btrfs_release_path(path);
2213 * Mutex was contended, block until it's released and let
2216 mutex_lock(&head->mutex);
2217 mutex_unlock(&head->mutex);
2218 btrfs_put_delayed_ref_head(head);
2219 btrfs_put_transaction(cur_trans);
2222 spin_unlock(&delayed_refs->lock);
2224 spin_lock(&head->lock);
2226 * XXX: We should replace this with a proper search function in the
2229 for (node = rb_first_cached(&head->ref_tree); node;
2230 node = rb_next(node)) {
2231 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
2232 /* If it's a shared ref we know a cross reference exists */
2233 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2238 data_ref = btrfs_delayed_node_to_data_ref(ref);
2241 * If our ref doesn't match the one we're currently looking at
2242 * then we have a cross reference.
2244 if (data_ref->root != root->root_key.objectid ||
2245 data_ref->objectid != objectid ||
2246 data_ref->offset != offset) {
2251 spin_unlock(&head->lock);
2252 mutex_unlock(&head->mutex);
2253 btrfs_put_transaction(cur_trans);
2257 static noinline int check_committed_ref(struct btrfs_root *root,
2258 struct btrfs_path *path,
2259 u64 objectid, u64 offset, u64 bytenr,
2262 struct btrfs_fs_info *fs_info = root->fs_info;
2263 struct btrfs_root *extent_root = fs_info->extent_root;
2264 struct extent_buffer *leaf;
2265 struct btrfs_extent_data_ref *ref;
2266 struct btrfs_extent_inline_ref *iref;
2267 struct btrfs_extent_item *ei;
2268 struct btrfs_key key;
2273 key.objectid = bytenr;
2274 key.offset = (u64)-1;
2275 key.type = BTRFS_EXTENT_ITEM_KEY;
2277 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2280 BUG_ON(ret == 0); /* Corruption */
2283 if (path->slots[0] == 0)
2287 leaf = path->nodes[0];
2288 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2290 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2294 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2295 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2297 /* If extent item has more than 1 inline ref then it's shared */
2298 if (item_size != sizeof(*ei) +
2299 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2303 * If extent created before last snapshot => it's shared unless the
2304 * snapshot has been deleted. Use the heuristic if strict is false.
2307 (btrfs_extent_generation(leaf, ei) <=
2308 btrfs_root_last_snapshot(&root->root_item)))
2311 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2313 /* If this extent has SHARED_DATA_REF then it's shared */
2314 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
2315 if (type != BTRFS_EXTENT_DATA_REF_KEY)
2318 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2319 if (btrfs_extent_refs(leaf, ei) !=
2320 btrfs_extent_data_ref_count(leaf, ref) ||
2321 btrfs_extent_data_ref_root(leaf, ref) !=
2322 root->root_key.objectid ||
2323 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2324 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2332 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
2333 u64 bytenr, bool strict)
2335 struct btrfs_path *path;
2338 path = btrfs_alloc_path();
2343 ret = check_committed_ref(root, path, objectid,
2344 offset, bytenr, strict);
2345 if (ret && ret != -ENOENT)
2348 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
2349 } while (ret == -EAGAIN);
2352 btrfs_free_path(path);
2353 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2358 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2359 struct btrfs_root *root,
2360 struct extent_buffer *buf,
2361 int full_backref, int inc)
2363 struct btrfs_fs_info *fs_info = root->fs_info;
2369 struct btrfs_key key;
2370 struct btrfs_file_extent_item *fi;
2371 struct btrfs_ref generic_ref = { 0 };
2372 bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
2378 if (btrfs_is_testing(fs_info))
2381 ref_root = btrfs_header_owner(buf);
2382 nritems = btrfs_header_nritems(buf);
2383 level = btrfs_header_level(buf);
2385 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state) && level == 0)
2389 parent = buf->start;
2393 action = BTRFS_ADD_DELAYED_REF;
2395 action = BTRFS_DROP_DELAYED_REF;
2397 for (i = 0; i < nritems; i++) {
2399 btrfs_item_key_to_cpu(buf, &key, i);
2400 if (key.type != BTRFS_EXTENT_DATA_KEY)
2402 fi = btrfs_item_ptr(buf, i,
2403 struct btrfs_file_extent_item);
2404 if (btrfs_file_extent_type(buf, fi) ==
2405 BTRFS_FILE_EXTENT_INLINE)
2407 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2411 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2412 key.offset -= btrfs_file_extent_offset(buf, fi);
2413 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2415 generic_ref.real_root = root->root_key.objectid;
2416 btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
2418 generic_ref.skip_qgroup = for_reloc;
2420 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2422 ret = btrfs_free_extent(trans, &generic_ref);
2426 bytenr = btrfs_node_blockptr(buf, i);
2427 num_bytes = fs_info->nodesize;
2428 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2430 generic_ref.real_root = root->root_key.objectid;
2431 btrfs_init_tree_ref(&generic_ref, level - 1, ref_root);
2432 generic_ref.skip_qgroup = for_reloc;
2434 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2436 ret = btrfs_free_extent(trans, &generic_ref);
2446 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2447 struct extent_buffer *buf, int full_backref)
2449 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
2452 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2453 struct extent_buffer *buf, int full_backref)
2455 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2458 int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
2460 struct btrfs_block_group *block_group;
2463 block_group = btrfs_lookup_block_group(fs_info, bytenr);
2464 if (!block_group || block_group->ro)
2467 btrfs_put_block_group(block_group);
2471 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
2473 struct btrfs_fs_info *fs_info = root->fs_info;
2478 flags = BTRFS_BLOCK_GROUP_DATA;
2479 else if (root == fs_info->chunk_root)
2480 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2482 flags = BTRFS_BLOCK_GROUP_METADATA;
2484 ret = btrfs_get_alloc_profile(fs_info, flags);
2488 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
2490 struct btrfs_block_group *cache;
2493 spin_lock(&fs_info->block_group_cache_lock);
2494 bytenr = fs_info->first_logical_byte;
2495 spin_unlock(&fs_info->block_group_cache_lock);
2497 if (bytenr < (u64)-1)
2500 cache = btrfs_lookup_first_block_group(fs_info, search_start);
2504 bytenr = cache->start;
2505 btrfs_put_block_group(cache);
2510 static int pin_down_extent(struct btrfs_trans_handle *trans,
2511 struct btrfs_block_group *cache,
2512 u64 bytenr, u64 num_bytes, int reserved)
2514 struct btrfs_fs_info *fs_info = cache->fs_info;
2516 spin_lock(&cache->space_info->lock);
2517 spin_lock(&cache->lock);
2518 cache->pinned += num_bytes;
2519 btrfs_space_info_update_bytes_pinned(fs_info, cache->space_info,
2522 cache->reserved -= num_bytes;
2523 cache->space_info->bytes_reserved -= num_bytes;
2525 spin_unlock(&cache->lock);
2526 spin_unlock(&cache->space_info->lock);
2528 __btrfs_mod_total_bytes_pinned(cache->space_info, num_bytes);
2529 set_extent_dirty(&trans->transaction->pinned_extents, bytenr,
2530 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
2534 int btrfs_pin_extent(struct btrfs_trans_handle *trans,
2535 u64 bytenr, u64 num_bytes, int reserved)
2537 struct btrfs_block_group *cache;
2539 cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
2540 BUG_ON(!cache); /* Logic error */
2542 pin_down_extent(trans, cache, bytenr, num_bytes, reserved);
2544 btrfs_put_block_group(cache);
2549 * this function must be called within transaction
2551 int btrfs_pin_extent_for_log_replay(struct btrfs_trans_handle *trans,
2552 u64 bytenr, u64 num_bytes)
2554 struct btrfs_block_group *cache;
2557 cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
2562 * pull in the free space cache (if any) so that our pin
2563 * removes the free space from the cache. We have load_only set
2564 * to one because the slow code to read in the free extents does check
2565 * the pinned extents.
2567 btrfs_cache_block_group(cache, 1);
2569 * Make sure we wait until the cache is completely built in case it is
2570 * missing or is invalid and therefore needs to be rebuilt.
2572 ret = btrfs_wait_block_group_cache_done(cache);
2576 pin_down_extent(trans, cache, bytenr, num_bytes, 0);
2578 /* remove us from the free space cache (if we're there at all) */
2579 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
2581 btrfs_put_block_group(cache);
2585 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
2586 u64 start, u64 num_bytes)
2589 struct btrfs_block_group *block_group;
2591 block_group = btrfs_lookup_block_group(fs_info, start);
2595 btrfs_cache_block_group(block_group, 1);
2597 * Make sure we wait until the cache is completely built in case it is
2598 * missing or is invalid and therefore needs to be rebuilt.
2600 ret = btrfs_wait_block_group_cache_done(block_group);
2604 ret = btrfs_remove_free_space(block_group, start, num_bytes);
2606 btrfs_put_block_group(block_group);
2610 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
2612 struct btrfs_fs_info *fs_info = eb->fs_info;
2613 struct btrfs_file_extent_item *item;
2614 struct btrfs_key key;
2619 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
2622 for (i = 0; i < btrfs_header_nritems(eb); i++) {
2623 btrfs_item_key_to_cpu(eb, &key, i);
2624 if (key.type != BTRFS_EXTENT_DATA_KEY)
2626 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
2627 found_type = btrfs_file_extent_type(eb, item);
2628 if (found_type == BTRFS_FILE_EXTENT_INLINE)
2630 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
2632 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
2633 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
2634 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
2643 btrfs_inc_block_group_reservations(struct btrfs_block_group *bg)
2645 atomic_inc(&bg->reservations);
2649 * Returns the free cluster for the given space info and sets empty_cluster to
2650 * what it should be based on the mount options.
2652 static struct btrfs_free_cluster *
2653 fetch_cluster_info(struct btrfs_fs_info *fs_info,
2654 struct btrfs_space_info *space_info, u64 *empty_cluster)
2656 struct btrfs_free_cluster *ret = NULL;
2659 if (btrfs_mixed_space_info(space_info))
2662 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
2663 ret = &fs_info->meta_alloc_cluster;
2664 if (btrfs_test_opt(fs_info, SSD))
2665 *empty_cluster = SZ_2M;
2667 *empty_cluster = SZ_64K;
2668 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
2669 btrfs_test_opt(fs_info, SSD_SPREAD)) {
2670 *empty_cluster = SZ_2M;
2671 ret = &fs_info->data_alloc_cluster;
2677 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
2679 const bool return_free_space)
2681 struct btrfs_block_group *cache = NULL;
2682 struct btrfs_space_info *space_info;
2683 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2684 struct btrfs_free_cluster *cluster = NULL;
2686 u64 total_unpinned = 0;
2687 u64 empty_cluster = 0;
2690 while (start <= end) {
2693 start >= cache->start + cache->length) {
2695 btrfs_put_block_group(cache);
2697 cache = btrfs_lookup_block_group(fs_info, start);
2698 BUG_ON(!cache); /* Logic error */
2700 cluster = fetch_cluster_info(fs_info,
2703 empty_cluster <<= 1;
2706 len = cache->start + cache->length - start;
2707 len = min(len, end + 1 - start);
2709 down_read(&fs_info->commit_root_sem);
2710 if (start < cache->last_byte_to_unpin && return_free_space) {
2711 u64 add_len = min(len, cache->last_byte_to_unpin - start);
2713 btrfs_add_free_space(cache, start, add_len);
2715 up_read(&fs_info->commit_root_sem);
2718 total_unpinned += len;
2719 space_info = cache->space_info;
2722 * If this space cluster has been marked as fragmented and we've
2723 * unpinned enough in this block group to potentially allow a
2724 * cluster to be created inside of it go ahead and clear the
2727 if (cluster && cluster->fragmented &&
2728 total_unpinned > empty_cluster) {
2729 spin_lock(&cluster->lock);
2730 cluster->fragmented = 0;
2731 spin_unlock(&cluster->lock);
2734 spin_lock(&space_info->lock);
2735 spin_lock(&cache->lock);
2736 cache->pinned -= len;
2737 btrfs_space_info_update_bytes_pinned(fs_info, space_info, -len);
2738 space_info->max_extent_size = 0;
2739 __btrfs_mod_total_bytes_pinned(space_info, -len);
2741 space_info->bytes_readonly += len;
2744 spin_unlock(&cache->lock);
2745 if (!readonly && return_free_space &&
2746 global_rsv->space_info == space_info) {
2749 spin_lock(&global_rsv->lock);
2750 if (!global_rsv->full) {
2751 to_add = min(len, global_rsv->size -
2752 global_rsv->reserved);
2753 global_rsv->reserved += to_add;
2754 btrfs_space_info_update_bytes_may_use(fs_info,
2755 space_info, to_add);
2756 if (global_rsv->reserved >= global_rsv->size)
2757 global_rsv->full = 1;
2760 spin_unlock(&global_rsv->lock);
2762 /* Add to any tickets we may have */
2763 if (!readonly && return_free_space && len)
2764 btrfs_try_granting_tickets(fs_info, space_info);
2765 spin_unlock(&space_info->lock);
2769 btrfs_put_block_group(cache);
2773 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
2775 struct btrfs_fs_info *fs_info = trans->fs_info;
2776 struct btrfs_block_group *block_group, *tmp;
2777 struct list_head *deleted_bgs;
2778 struct extent_io_tree *unpin;
2783 unpin = &trans->transaction->pinned_extents;
2785 while (!TRANS_ABORTED(trans)) {
2786 struct extent_state *cached_state = NULL;
2788 mutex_lock(&fs_info->unused_bg_unpin_mutex);
2789 ret = find_first_extent_bit(unpin, 0, &start, &end,
2790 EXTENT_DIRTY, &cached_state);
2792 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2796 if (btrfs_test_opt(fs_info, DISCARD_SYNC))
2797 ret = btrfs_discard_extent(fs_info, start,
2798 end + 1 - start, NULL);
2800 clear_extent_dirty(unpin, start, end, &cached_state);
2801 unpin_extent_range(fs_info, start, end, true);
2802 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2803 free_extent_state(cached_state);
2807 if (btrfs_test_opt(fs_info, DISCARD_ASYNC)) {
2808 btrfs_discard_calc_delay(&fs_info->discard_ctl);
2809 btrfs_discard_schedule_work(&fs_info->discard_ctl, true);
2813 * Transaction is finished. We don't need the lock anymore. We
2814 * do need to clean up the block groups in case of a transaction
2817 deleted_bgs = &trans->transaction->deleted_bgs;
2818 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
2822 if (!TRANS_ABORTED(trans))
2823 ret = btrfs_discard_extent(fs_info,
2825 block_group->length,
2828 list_del_init(&block_group->bg_list);
2829 btrfs_unfreeze_block_group(block_group);
2830 btrfs_put_block_group(block_group);
2833 const char *errstr = btrfs_decode_error(ret);
2835 "discard failed while removing blockgroup: errno=%d %s",
2844 * Drop one or more refs of @node.
2846 * 1. Locate the extent refs.
2847 * It's either inline in EXTENT/METADATA_ITEM or in keyed SHARED_* item.
2848 * Locate it, then reduce the refs number or remove the ref line completely.
2850 * 2. Update the refs count in EXTENT/METADATA_ITEM
2852 * Inline backref case:
2854 * in extent tree we have:
2856 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
2857 * refs 2 gen 6 flags DATA
2858 * extent data backref root FS_TREE objectid 258 offset 0 count 1
2859 * extent data backref root FS_TREE objectid 257 offset 0 count 1
2861 * This function gets called with:
2863 * node->bytenr = 13631488
2864 * node->num_bytes = 1048576
2865 * root_objectid = FS_TREE
2866 * owner_objectid = 257
2870 * Then we should get some like:
2872 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
2873 * refs 1 gen 6 flags DATA
2874 * extent data backref root FS_TREE objectid 258 offset 0 count 1
2876 * Keyed backref case:
2878 * in extent tree we have:
2880 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
2881 * refs 754 gen 6 flags DATA
2883 * item 2 key (13631488 EXTENT_DATA_REF <HASH>) itemoff 3915 itemsize 28
2884 * extent data backref root FS_TREE objectid 866 offset 0 count 1
2886 * This function get called with:
2888 * node->bytenr = 13631488
2889 * node->num_bytes = 1048576
2890 * root_objectid = FS_TREE
2891 * owner_objectid = 866
2895 * Then we should get some like:
2897 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
2898 * refs 753 gen 6 flags DATA
2900 * And that (13631488 EXTENT_DATA_REF <HASH>) gets removed.
2902 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
2903 struct btrfs_delayed_ref_node *node, u64 parent,
2904 u64 root_objectid, u64 owner_objectid,
2905 u64 owner_offset, int refs_to_drop,
2906 struct btrfs_delayed_extent_op *extent_op)
2908 struct btrfs_fs_info *info = trans->fs_info;
2909 struct btrfs_key key;
2910 struct btrfs_path *path;
2911 struct btrfs_root *extent_root = info->extent_root;
2912 struct extent_buffer *leaf;
2913 struct btrfs_extent_item *ei;
2914 struct btrfs_extent_inline_ref *iref;
2917 int extent_slot = 0;
2918 int found_extent = 0;
2922 u64 bytenr = node->bytenr;
2923 u64 num_bytes = node->num_bytes;
2925 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
2927 path = btrfs_alloc_path();
2931 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
2933 if (!is_data && refs_to_drop != 1) {
2935 "invalid refs_to_drop, dropping more than 1 refs for tree block %llu refs_to_drop %u",
2936 node->bytenr, refs_to_drop);
2938 btrfs_abort_transaction(trans, ret);
2943 skinny_metadata = false;
2945 ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
2946 parent, root_objectid, owner_objectid,
2950 * Either the inline backref or the SHARED_DATA_REF/
2951 * SHARED_BLOCK_REF is found
2953 * Here is a quick path to locate EXTENT/METADATA_ITEM.
2954 * It's possible the EXTENT/METADATA_ITEM is near current slot.
2956 extent_slot = path->slots[0];
2957 while (extent_slot >= 0) {
2958 btrfs_item_key_to_cpu(path->nodes[0], &key,
2960 if (key.objectid != bytenr)
2962 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
2963 key.offset == num_bytes) {
2967 if (key.type == BTRFS_METADATA_ITEM_KEY &&
2968 key.offset == owner_objectid) {
2973 /* Quick path didn't find the EXTEMT/METADATA_ITEM */
2974 if (path->slots[0] - extent_slot > 5)
2979 if (!found_extent) {
2982 "invalid iref, no EXTENT/METADATA_ITEM found but has inline extent ref");
2983 btrfs_abort_transaction(trans, -EUCLEAN);
2986 /* Must be SHARED_* item, remove the backref first */
2987 ret = remove_extent_backref(trans, path, NULL,
2989 is_data, &last_ref);
2991 btrfs_abort_transaction(trans, ret);
2994 btrfs_release_path(path);
2996 /* Slow path to locate EXTENT/METADATA_ITEM */
2997 key.objectid = bytenr;
2998 key.type = BTRFS_EXTENT_ITEM_KEY;
2999 key.offset = num_bytes;
3001 if (!is_data && skinny_metadata) {
3002 key.type = BTRFS_METADATA_ITEM_KEY;
3003 key.offset = owner_objectid;
3006 ret = btrfs_search_slot(trans, extent_root,
3008 if (ret > 0 && skinny_metadata && path->slots[0]) {
3010 * Couldn't find our skinny metadata item,
3011 * see if we have ye olde extent item.
3014 btrfs_item_key_to_cpu(path->nodes[0], &key,
3016 if (key.objectid == bytenr &&
3017 key.type == BTRFS_EXTENT_ITEM_KEY &&
3018 key.offset == num_bytes)
3022 if (ret > 0 && skinny_metadata) {
3023 skinny_metadata = false;
3024 key.objectid = bytenr;
3025 key.type = BTRFS_EXTENT_ITEM_KEY;
3026 key.offset = num_bytes;
3027 btrfs_release_path(path);
3028 ret = btrfs_search_slot(trans, extent_root,
3034 "umm, got %d back from search, was looking for %llu",
3037 btrfs_print_leaf(path->nodes[0]);
3040 btrfs_abort_transaction(trans, ret);
3043 extent_slot = path->slots[0];
3045 } else if (WARN_ON(ret == -ENOENT)) {
3046 btrfs_print_leaf(path->nodes[0]);
3048 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
3049 bytenr, parent, root_objectid, owner_objectid,
3051 btrfs_abort_transaction(trans, ret);
3054 btrfs_abort_transaction(trans, ret);
3058 leaf = path->nodes[0];
3059 item_size = btrfs_item_size_nr(leaf, extent_slot);
3060 if (unlikely(item_size < sizeof(*ei))) {
3062 btrfs_print_v0_err(info);
3063 btrfs_abort_transaction(trans, ret);
3066 ei = btrfs_item_ptr(leaf, extent_slot,
3067 struct btrfs_extent_item);
3068 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
3069 key.type == BTRFS_EXTENT_ITEM_KEY) {
3070 struct btrfs_tree_block_info *bi;
3071 if (item_size < sizeof(*ei) + sizeof(*bi)) {
3073 "invalid extent item size for key (%llu, %u, %llu) owner %llu, has %u expect >= %zu",
3074 key.objectid, key.type, key.offset,
3075 owner_objectid, item_size,
3076 sizeof(*ei) + sizeof(*bi));
3077 btrfs_abort_transaction(trans, -EUCLEAN);
3080 bi = (struct btrfs_tree_block_info *)(ei + 1);
3081 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
3084 refs = btrfs_extent_refs(leaf, ei);
3085 if (refs < refs_to_drop) {
3087 "trying to drop %d refs but we only have %llu for bytenr %llu",
3088 refs_to_drop, refs, bytenr);
3089 btrfs_abort_transaction(trans, -EUCLEAN);
3092 refs -= refs_to_drop;
3096 __run_delayed_extent_op(extent_op, leaf, ei);
3098 * In the case of inline back ref, reference count will
3099 * be updated by remove_extent_backref
3102 if (!found_extent) {
3104 "invalid iref, got inlined extent ref but no EXTENT/METADATA_ITEM found");
3105 btrfs_abort_transaction(trans, -EUCLEAN);
3109 btrfs_set_extent_refs(leaf, ei, refs);
3110 btrfs_mark_buffer_dirty(leaf);
3113 ret = remove_extent_backref(trans, path, iref,
3114 refs_to_drop, is_data,
3117 btrfs_abort_transaction(trans, ret);
3122 /* In this branch refs == 1 */
3124 if (is_data && refs_to_drop !=
3125 extent_data_ref_count(path, iref)) {
3127 "invalid refs_to_drop, current refs %u refs_to_drop %u",
3128 extent_data_ref_count(path, iref),
3130 btrfs_abort_transaction(trans, -EUCLEAN);
3134 if (path->slots[0] != extent_slot) {
3136 "invalid iref, extent item key (%llu %u %llu) doesn't have wanted iref",
3137 key.objectid, key.type,
3139 btrfs_abort_transaction(trans, -EUCLEAN);
3144 * No inline ref, we must be at SHARED_* item,
3145 * And it's single ref, it must be:
3146 * | extent_slot ||extent_slot + 1|
3147 * [ EXTENT/METADATA_ITEM ][ SHARED_* ITEM ]
3149 if (path->slots[0] != extent_slot + 1) {
3151 "invalid SHARED_* item, previous item is not EXTENT/METADATA_ITEM");
3152 btrfs_abort_transaction(trans, -EUCLEAN);
3155 path->slots[0] = extent_slot;
3161 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
3164 btrfs_abort_transaction(trans, ret);
3167 btrfs_release_path(path);
3170 ret = btrfs_del_csums(trans, info->csum_root, bytenr,
3173 btrfs_abort_transaction(trans, ret);
3178 ret = add_to_free_space_tree(trans, bytenr, num_bytes);
3180 btrfs_abort_transaction(trans, ret);
3184 ret = btrfs_update_block_group(trans, bytenr, num_bytes, 0);
3186 btrfs_abort_transaction(trans, ret);
3190 btrfs_release_path(path);
3193 btrfs_free_path(path);
3197 * Leaf dump can take up a lot of log buffer, so we only do full leaf
3198 * dump for debug build.
3200 if (IS_ENABLED(CONFIG_BTRFS_DEBUG)) {
3201 btrfs_crit(info, "path->slots[0]=%d extent_slot=%d",
3202 path->slots[0], extent_slot);
3203 btrfs_print_leaf(path->nodes[0]);
3206 btrfs_free_path(path);
3211 * when we free an block, it is possible (and likely) that we free the last
3212 * delayed ref for that extent as well. This searches the delayed ref tree for
3213 * a given extent, and if there are no other delayed refs to be processed, it
3214 * removes it from the tree.
3216 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
3219 struct btrfs_delayed_ref_head *head;
3220 struct btrfs_delayed_ref_root *delayed_refs;
3223 delayed_refs = &trans->transaction->delayed_refs;
3224 spin_lock(&delayed_refs->lock);
3225 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
3227 goto out_delayed_unlock;
3229 spin_lock(&head->lock);
3230 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
3233 if (cleanup_extent_op(head) != NULL)
3237 * waiting for the lock here would deadlock. If someone else has it
3238 * locked they are already in the process of dropping it anyway
3240 if (!mutex_trylock(&head->mutex))
3243 btrfs_delete_ref_head(delayed_refs, head);
3244 head->processing = 0;
3246 spin_unlock(&head->lock);
3247 spin_unlock(&delayed_refs->lock);
3249 BUG_ON(head->extent_op);
3250 if (head->must_insert_reserved)
3253 btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
3254 mutex_unlock(&head->mutex);
3255 btrfs_put_delayed_ref_head(head);
3258 spin_unlock(&head->lock);
3261 spin_unlock(&delayed_refs->lock);
3265 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
3266 struct btrfs_root *root,
3267 struct extent_buffer *buf,
3268 u64 parent, int last_ref)
3270 struct btrfs_fs_info *fs_info = root->fs_info;
3271 struct btrfs_ref generic_ref = { 0 };
3274 btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
3275 buf->start, buf->len, parent);
3276 btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
3277 root->root_key.objectid);
3279 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
3280 btrfs_ref_tree_mod(fs_info, &generic_ref);
3281 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL);
3282 BUG_ON(ret); /* -ENOMEM */
3285 if (last_ref && btrfs_header_generation(buf) == trans->transid) {
3286 struct btrfs_block_group *cache;
3288 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
3289 ret = check_ref_cleanup(trans, buf->start);
3294 cache = btrfs_lookup_block_group(fs_info, buf->start);
3296 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
3297 pin_down_extent(trans, cache, buf->start, buf->len, 1);
3298 btrfs_put_block_group(cache);
3302 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
3304 btrfs_add_free_space(cache, buf->start, buf->len);
3305 btrfs_free_reserved_bytes(cache, buf->len, 0);
3306 btrfs_put_block_group(cache);
3307 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
3312 * Deleting the buffer, clear the corrupt flag since it doesn't
3315 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
3319 /* Can return -ENOMEM */
3320 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
3322 struct btrfs_fs_info *fs_info = trans->fs_info;
3325 if (btrfs_is_testing(fs_info))
3329 * tree log blocks never actually go into the extent allocation
3330 * tree, just update pinning info and exit early.
3332 if ((ref->type == BTRFS_REF_METADATA &&
3333 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
3334 (ref->type == BTRFS_REF_DATA &&
3335 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)) {
3336 /* unlocks the pinned mutex */
3337 btrfs_pin_extent(trans, ref->bytenr, ref->len, 1);
3339 } else if (ref->type == BTRFS_REF_METADATA) {
3340 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL);
3342 ret = btrfs_add_delayed_data_ref(trans, ref, 0);
3345 if (!((ref->type == BTRFS_REF_METADATA &&
3346 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
3347 (ref->type == BTRFS_REF_DATA &&
3348 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)))
3349 btrfs_ref_tree_mod(fs_info, ref);
3354 enum btrfs_loop_type {
3355 LOOP_CACHING_NOWAIT,
3362 btrfs_lock_block_group(struct btrfs_block_group *cache,
3366 down_read(&cache->data_rwsem);
3369 static inline void btrfs_grab_block_group(struct btrfs_block_group *cache,
3372 btrfs_get_block_group(cache);
3374 down_read(&cache->data_rwsem);
3377 static struct btrfs_block_group *btrfs_lock_cluster(
3378 struct btrfs_block_group *block_group,
3379 struct btrfs_free_cluster *cluster,
3381 __acquires(&cluster->refill_lock)
3383 struct btrfs_block_group *used_bg = NULL;
3385 spin_lock(&cluster->refill_lock);
3387 used_bg = cluster->block_group;
3391 if (used_bg == block_group)
3394 btrfs_get_block_group(used_bg);
3399 if (down_read_trylock(&used_bg->data_rwsem))
3402 spin_unlock(&cluster->refill_lock);
3404 /* We should only have one-level nested. */
3405 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
3407 spin_lock(&cluster->refill_lock);
3408 if (used_bg == cluster->block_group)
3411 up_read(&used_bg->data_rwsem);
3412 btrfs_put_block_group(used_bg);
3417 btrfs_release_block_group(struct btrfs_block_group *cache,
3421 up_read(&cache->data_rwsem);
3422 btrfs_put_block_group(cache);
3425 enum btrfs_extent_allocation_policy {
3426 BTRFS_EXTENT_ALLOC_CLUSTERED,
3430 * Structure used internally for find_free_extent() function. Wraps needed
3433 struct find_free_extent_ctl {
3434 /* Basic allocation info */
3440 /* Where to start the search inside the bg */
3443 /* For clustered allocation */
3445 struct btrfs_free_cluster *last_ptr;
3448 bool have_caching_bg;
3449 bool orig_have_caching_bg;
3451 /* RAID index, converted from flags */
3455 * Current loop number, check find_free_extent_update_loop() for details
3460 * Whether we're refilling a cluster, if true we need to re-search
3461 * current block group but don't try to refill the cluster again.
3463 bool retry_clustered;
3466 * Whether we're updating free space cache, if true we need to re-search
3467 * current block group but don't try updating free space cache again.
3469 bool retry_unclustered;
3471 /* If current block group is cached */
3474 /* Max contiguous hole found */
3475 u64 max_extent_size;
3477 /* Total free space from free space cache, not always contiguous */
3478 u64 total_free_space;
3483 /* Hint where to start looking for an empty space */
3486 /* Allocation policy */
3487 enum btrfs_extent_allocation_policy policy;
3492 * Helper function for find_free_extent().
3494 * Return -ENOENT to inform caller that we need fallback to unclustered mode.
3495 * Return -EAGAIN to inform caller that we need to re-search this block group
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,
3523 ffe_ctl->search_start, ffe_ctl->num_bytes);
3524 *cluster_bg_ret = cluster_bg;
3525 ffe_ctl->found_offset = offset;
3528 WARN_ON(last_ptr->block_group != cluster_bg);
3532 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
3533 * lets just skip it and let the allocator find whatever block it can
3534 * find. If we reach this point, we will have tried the cluster
3535 * allocator plenty of times and not have found anything, so we are
3536 * likely way too fragmented for the clustering stuff to find anything.
3538 * However, if the cluster is taken from the current block group,
3539 * release the cluster first, so that we stand a better chance of
3540 * succeeding in the unclustered allocation.
3542 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
3543 spin_unlock(&last_ptr->refill_lock);
3544 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3548 /* This cluster didn't work out, free it and start over */
3549 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3551 if (cluster_bg != bg)
3552 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3555 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
3556 spin_unlock(&last_ptr->refill_lock);
3560 aligned_cluster = max_t(u64,
3561 ffe_ctl->empty_cluster + ffe_ctl->empty_size,
3562 bg->full_stripe_len);
3563 ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
3564 ffe_ctl->num_bytes, aligned_cluster);
3566 /* Now pull our allocation out of this cluster */
3567 offset = btrfs_alloc_from_cluster(bg, last_ptr,
3568 ffe_ctl->num_bytes, ffe_ctl->search_start,
3569 &ffe_ctl->max_extent_size);
3571 /* We found one, proceed */
3572 spin_unlock(&last_ptr->refill_lock);
3573 trace_btrfs_reserve_extent_cluster(bg,
3574 ffe_ctl->search_start,
3575 ffe_ctl->num_bytes);
3576 ffe_ctl->found_offset = offset;
3579 } else if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
3580 !ffe_ctl->retry_clustered) {
3581 spin_unlock(&last_ptr->refill_lock);
3583 ffe_ctl->retry_clustered = true;
3584 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3585 ffe_ctl->empty_cluster + ffe_ctl->empty_size);
3589 * At this point we either didn't find a cluster or we weren't able to
3590 * allocate a block from our cluster. Free the cluster we've been
3591 * trying to use, and go to the next block group.
3593 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3594 spin_unlock(&last_ptr->refill_lock);
3599 * Return >0 to inform caller that we find nothing
3600 * Return 0 when we found an free extent and set ffe_ctrl->found_offset
3601 * Return -EAGAIN to inform caller that we need to re-search this block group
3603 static int find_free_extent_unclustered(struct btrfs_block_group *bg,
3604 struct find_free_extent_ctl *ffe_ctl)
3606 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3610 * We are doing an unclustered allocation, set the fragmented flag so
3611 * we don't bother trying to setup a cluster again until we get more
3614 if (unlikely(last_ptr)) {
3615 spin_lock(&last_ptr->lock);
3616 last_ptr->fragmented = 1;
3617 spin_unlock(&last_ptr->lock);
3619 if (ffe_ctl->cached) {
3620 struct btrfs_free_space_ctl *free_space_ctl;
3622 free_space_ctl = bg->free_space_ctl;
3623 spin_lock(&free_space_ctl->tree_lock);
3624 if (free_space_ctl->free_space <
3625 ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
3626 ffe_ctl->empty_size) {
3627 ffe_ctl->total_free_space = max_t(u64,
3628 ffe_ctl->total_free_space,
3629 free_space_ctl->free_space);
3630 spin_unlock(&free_space_ctl->tree_lock);
3633 spin_unlock(&free_space_ctl->tree_lock);
3636 offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
3637 ffe_ctl->num_bytes, ffe_ctl->empty_size,
3638 &ffe_ctl->max_extent_size);
3641 * If we didn't find a chunk, and we haven't failed on this block group
3642 * before, and this block group is in the middle of caching and we are
3643 * ok with waiting, then go ahead and wait for progress to be made, and
3644 * set @retry_unclustered to true.
3646 * If @retry_unclustered is true then we've already waited on this
3647 * block group once and should move on to the next block group.
3649 if (!offset && !ffe_ctl->retry_unclustered && !ffe_ctl->cached &&
3650 ffe_ctl->loop > LOOP_CACHING_NOWAIT) {
3651 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3652 ffe_ctl->empty_size);
3653 ffe_ctl->retry_unclustered = true;
3655 } else if (!offset) {
3658 ffe_ctl->found_offset = offset;
3662 static int do_allocation_clustered(struct btrfs_block_group *block_group,
3663 struct find_free_extent_ctl *ffe_ctl,
3664 struct btrfs_block_group **bg_ret)
3668 /* We want to try and use the cluster allocator, so lets look there */
3669 if (ffe_ctl->last_ptr && ffe_ctl->use_cluster) {
3670 ret = find_free_extent_clustered(block_group, ffe_ctl, bg_ret);
3671 if (ret >= 0 || ret == -EAGAIN)
3673 /* ret == -ENOENT case falls through */
3676 return find_free_extent_unclustered(block_group, ffe_ctl);
3679 static int do_allocation(struct btrfs_block_group *block_group,
3680 struct find_free_extent_ctl *ffe_ctl,
3681 struct btrfs_block_group **bg_ret)
3683 switch (ffe_ctl->policy) {
3684 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3685 return do_allocation_clustered(block_group, ffe_ctl, bg_ret);
3691 static void release_block_group(struct btrfs_block_group *block_group,
3692 struct find_free_extent_ctl *ffe_ctl,
3695 switch (ffe_ctl->policy) {
3696 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3697 ffe_ctl->retry_clustered = false;
3698 ffe_ctl->retry_unclustered = false;
3704 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
3706 btrfs_release_block_group(block_group, delalloc);
3709 static void found_extent_clustered(struct find_free_extent_ctl *ffe_ctl,
3710 struct btrfs_key *ins)
3712 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3714 if (!ffe_ctl->use_cluster && last_ptr) {
3715 spin_lock(&last_ptr->lock);
3716 last_ptr->window_start = ins->objectid;
3717 spin_unlock(&last_ptr->lock);
3721 static void found_extent(struct find_free_extent_ctl *ffe_ctl,
3722 struct btrfs_key *ins)
3724 switch (ffe_ctl->policy) {
3725 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3726 found_extent_clustered(ffe_ctl, ins);
3733 static int chunk_allocation_failed(struct find_free_extent_ctl *ffe_ctl)
3735 switch (ffe_ctl->policy) {
3736 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3738 * If we can't allocate a new chunk we've already looped through
3739 * at least once, move on to the NO_EMPTY_SIZE case.
3741 ffe_ctl->loop = LOOP_NO_EMPTY_SIZE;
3749 * Return >0 means caller needs to re-search for free extent
3750 * Return 0 means we have the needed free extent.
3751 * Return <0 means we failed to locate any free extent.
3753 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
3754 struct btrfs_key *ins,
3755 struct find_free_extent_ctl *ffe_ctl,
3758 struct btrfs_root *root = fs_info->extent_root;
3761 if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
3762 ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
3763 ffe_ctl->orig_have_caching_bg = true;
3765 if (!ins->objectid && ffe_ctl->loop >= LOOP_CACHING_WAIT &&
3766 ffe_ctl->have_caching_bg)
3769 if (!ins->objectid && ++(ffe_ctl->index) < BTRFS_NR_RAID_TYPES)
3772 if (ins->objectid) {
3773 found_extent(ffe_ctl, ins);
3778 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
3779 * caching kthreads as we move along
3780 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
3781 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
3782 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
3785 if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
3787 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT) {
3789 * We want to skip the LOOP_CACHING_WAIT step if we
3790 * don't have any uncached bgs and we've already done a
3791 * full search through.
3793 if (ffe_ctl->orig_have_caching_bg || !full_search)
3794 ffe_ctl->loop = LOOP_CACHING_WAIT;
3796 ffe_ctl->loop = LOOP_ALLOC_CHUNK;
3801 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
3802 struct btrfs_trans_handle *trans;
3805 trans = current->journal_info;
3809 trans = btrfs_join_transaction(root);
3811 if (IS_ERR(trans)) {
3812 ret = PTR_ERR(trans);
3816 ret = btrfs_chunk_alloc(trans, ffe_ctl->flags,
3819 /* Do not bail out on ENOSPC since we can do more. */
3821 ret = chunk_allocation_failed(ffe_ctl);
3823 btrfs_abort_transaction(trans, ret);
3827 btrfs_end_transaction(trans);
3832 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
3833 if (ffe_ctl->policy != BTRFS_EXTENT_ALLOC_CLUSTERED)
3837 * Don't loop again if we already have no empty_size and
3840 if (ffe_ctl->empty_size == 0 &&
3841 ffe_ctl->empty_cluster == 0)
3843 ffe_ctl->empty_size = 0;
3844 ffe_ctl->empty_cluster = 0;
3851 static int prepare_allocation_clustered(struct btrfs_fs_info *fs_info,
3852 struct find_free_extent_ctl *ffe_ctl,
3853 struct btrfs_space_info *space_info,
3854 struct btrfs_key *ins)
3857 * If our free space is heavily fragmented we may not be able to make
3858 * big contiguous allocations, so instead of doing the expensive search
3859 * for free space, simply return ENOSPC with our max_extent_size so we
3860 * can go ahead and search for a more manageable chunk.
3862 * If our max_extent_size is large enough for our allocation simply
3863 * disable clustering since we will likely not be able to find enough
3864 * space to create a cluster and induce latency trying.
3866 if (space_info->max_extent_size) {
3867 spin_lock(&space_info->lock);
3868 if (space_info->max_extent_size &&
3869 ffe_ctl->num_bytes > space_info->max_extent_size) {
3870 ins->offset = space_info->max_extent_size;
3871 spin_unlock(&space_info->lock);
3873 } else if (space_info->max_extent_size) {
3874 ffe_ctl->use_cluster = false;
3876 spin_unlock(&space_info->lock);
3879 ffe_ctl->last_ptr = fetch_cluster_info(fs_info, space_info,
3880 &ffe_ctl->empty_cluster);
3881 if (ffe_ctl->last_ptr) {
3882 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3884 spin_lock(&last_ptr->lock);
3885 if (last_ptr->block_group)
3886 ffe_ctl->hint_byte = last_ptr->window_start;
3887 if (last_ptr->fragmented) {
3889 * We still set window_start so we can keep track of the
3890 * last place we found an allocation to try and save
3893 ffe_ctl->hint_byte = last_ptr->window_start;
3894 ffe_ctl->use_cluster = false;
3896 spin_unlock(&last_ptr->lock);
3902 static int prepare_allocation(struct btrfs_fs_info *fs_info,
3903 struct find_free_extent_ctl *ffe_ctl,
3904 struct btrfs_space_info *space_info,
3905 struct btrfs_key *ins)
3907 switch (ffe_ctl->policy) {
3908 case BTRFS_EXTENT_ALLOC_CLUSTERED:
3909 return prepare_allocation_clustered(fs_info, ffe_ctl,
3917 * walks the btree of allocated extents and find a hole of a given size.
3918 * The key ins is changed to record the hole:
3919 * ins->objectid == start position
3920 * ins->flags = BTRFS_EXTENT_ITEM_KEY
3921 * ins->offset == the size of the hole.
3922 * Any available blocks before search_start are skipped.
3924 * If there is no suitable free space, we will record the max size of
3925 * the free space extent currently.
3927 * The overall logic and call chain:
3929 * find_free_extent()
3930 * |- Iterate through all block groups
3931 * | |- Get a valid block group
3932 * | |- Try to do clustered allocation in that block group
3933 * | |- Try to do unclustered allocation in that block group
3934 * | |- Check if the result is valid
3935 * | | |- If valid, then exit
3936 * | |- Jump to next block group
3938 * |- Push harder to find free extents
3939 * |- If not found, re-iterate all block groups
3941 static noinline int find_free_extent(struct btrfs_root *root,
3942 u64 ram_bytes, u64 num_bytes, u64 empty_size,
3943 u64 hint_byte_orig, struct btrfs_key *ins,
3944 u64 flags, int delalloc)
3946 struct btrfs_fs_info *fs_info = root->fs_info;
3948 int cache_block_group_error = 0;
3949 struct btrfs_block_group *block_group = NULL;
3950 struct find_free_extent_ctl ffe_ctl = {0};
3951 struct btrfs_space_info *space_info;
3952 bool full_search = false;
3954 WARN_ON(num_bytes < fs_info->sectorsize);
3956 ffe_ctl.num_bytes = num_bytes;
3957 ffe_ctl.empty_size = empty_size;
3958 ffe_ctl.flags = flags;
3959 ffe_ctl.search_start = 0;
3960 ffe_ctl.delalloc = delalloc;
3961 ffe_ctl.index = btrfs_bg_flags_to_raid_index(flags);
3962 ffe_ctl.have_caching_bg = false;
3963 ffe_ctl.orig_have_caching_bg = false;
3964 ffe_ctl.found_offset = 0;
3965 ffe_ctl.hint_byte = hint_byte_orig;
3966 ffe_ctl.policy = BTRFS_EXTENT_ALLOC_CLUSTERED;
3968 /* For clustered allocation */
3969 ffe_ctl.retry_clustered = false;
3970 ffe_ctl.retry_unclustered = false;
3971 ffe_ctl.last_ptr = NULL;
3972 ffe_ctl.use_cluster = true;
3974 ins->type = BTRFS_EXTENT_ITEM_KEY;
3978 trace_find_free_extent(root, num_bytes, empty_size, flags);
3980 space_info = btrfs_find_space_info(fs_info, flags);
3982 btrfs_err(fs_info, "No space info for %llu", flags);
3986 ret = prepare_allocation(fs_info, &ffe_ctl, space_info, ins);
3990 ffe_ctl.search_start = max(ffe_ctl.search_start,
3991 first_logical_byte(fs_info, 0));
3992 ffe_ctl.search_start = max(ffe_ctl.search_start, ffe_ctl.hint_byte);
3993 if (ffe_ctl.search_start == ffe_ctl.hint_byte) {
3994 block_group = btrfs_lookup_block_group(fs_info,
3995 ffe_ctl.search_start);
3997 * we don't want to use the block group if it doesn't match our
3998 * allocation bits, or if its not cached.
4000 * However if we are re-searching with an ideal block group
4001 * picked out then we don't care that the block group is cached.
4003 if (block_group && block_group_bits(block_group, flags) &&
4004 block_group->cached != BTRFS_CACHE_NO) {
4005 down_read(&space_info->groups_sem);
4006 if (list_empty(&block_group->list) ||
4009 * someone is removing this block group,
4010 * we can't jump into the have_block_group
4011 * target because our list pointers are not
4014 btrfs_put_block_group(block_group);
4015 up_read(&space_info->groups_sem);
4017 ffe_ctl.index = btrfs_bg_flags_to_raid_index(
4018 block_group->flags);
4019 btrfs_lock_block_group(block_group, delalloc);
4020 goto have_block_group;
4022 } else if (block_group) {
4023 btrfs_put_block_group(block_group);
4027 ffe_ctl.have_caching_bg = false;
4028 if (ffe_ctl.index == btrfs_bg_flags_to_raid_index(flags) ||
4031 down_read(&space_info->groups_sem);
4032 list_for_each_entry(block_group,
4033 &space_info->block_groups[ffe_ctl.index], list) {
4034 struct btrfs_block_group *bg_ret;
4036 /* If the block group is read-only, we can skip it entirely. */
4037 if (unlikely(block_group->ro))
4040 btrfs_grab_block_group(block_group, delalloc);
4041 ffe_ctl.search_start = block_group->start;
4044 * this can happen if we end up cycling through all the
4045 * raid types, but we want to make sure we only allocate
4046 * for the proper type.
4048 if (!block_group_bits(block_group, flags)) {
4049 u64 extra = BTRFS_BLOCK_GROUP_DUP |
4050 BTRFS_BLOCK_GROUP_RAID1_MASK |
4051 BTRFS_BLOCK_GROUP_RAID56_MASK |
4052 BTRFS_BLOCK_GROUP_RAID10;
4055 * if they asked for extra copies and this block group
4056 * doesn't provide them, bail. This does allow us to
4057 * fill raid0 from raid1.
4059 if ((flags & extra) && !(block_group->flags & extra))
4063 * This block group has different flags than we want.
4064 * It's possible that we have MIXED_GROUP flag but no
4065 * block group is mixed. Just skip such block group.
4067 btrfs_release_block_group(block_group, delalloc);
4072 ffe_ctl.cached = btrfs_block_group_done(block_group);
4073 if (unlikely(!ffe_ctl.cached)) {
4074 ffe_ctl.have_caching_bg = true;
4075 ret = btrfs_cache_block_group(block_group, 0);
4078 * If we get ENOMEM here or something else we want to
4079 * try other block groups, because it may not be fatal.
4080 * However if we can't find anything else we need to
4081 * save our return here so that we return the actual
4082 * error that caused problems, not ENOSPC.
4085 if (!cache_block_group_error)
4086 cache_block_group_error = ret;
4093 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
4097 ret = do_allocation(block_group, &ffe_ctl, &bg_ret);
4099 if (bg_ret && bg_ret != block_group) {
4100 btrfs_release_block_group(block_group, delalloc);
4101 block_group = bg_ret;
4103 } else if (ret == -EAGAIN) {
4104 goto have_block_group;
4105 } else if (ret > 0) {
4110 ffe_ctl.search_start = round_up(ffe_ctl.found_offset,
4111 fs_info->stripesize);
4113 /* move on to the next group */
4114 if (ffe_ctl.search_start + num_bytes >
4115 block_group->start + block_group->length) {
4116 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
4121 if (ffe_ctl.found_offset < ffe_ctl.search_start)
4122 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
4123 ffe_ctl.search_start - ffe_ctl.found_offset);
4125 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
4126 num_bytes, delalloc);
4127 if (ret == -EAGAIN) {
4128 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
4132 btrfs_inc_block_group_reservations(block_group);
4134 /* we are all good, lets return */
4135 ins->objectid = ffe_ctl.search_start;
4136 ins->offset = num_bytes;
4138 trace_btrfs_reserve_extent(block_group, ffe_ctl.search_start,
4140 btrfs_release_block_group(block_group, delalloc);
4143 release_block_group(block_group, &ffe_ctl, delalloc);
4146 up_read(&space_info->groups_sem);
4148 ret = find_free_extent_update_loop(fs_info, ins, &ffe_ctl, full_search);
4152 if (ret == -ENOSPC && !cache_block_group_error) {
4154 * Use ffe_ctl->total_free_space as fallback if we can't find
4155 * any contiguous hole.
4157 if (!ffe_ctl.max_extent_size)
4158 ffe_ctl.max_extent_size = ffe_ctl.total_free_space;
4159 spin_lock(&space_info->lock);
4160 space_info->max_extent_size = ffe_ctl.max_extent_size;
4161 spin_unlock(&space_info->lock);
4162 ins->offset = ffe_ctl.max_extent_size;
4163 } else if (ret == -ENOSPC) {
4164 ret = cache_block_group_error;
4170 * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
4171 * hole that is at least as big as @num_bytes.
4173 * @root - The root that will contain this extent
4175 * @ram_bytes - The amount of space in ram that @num_bytes take. This
4176 * is used for accounting purposes. This value differs
4177 * from @num_bytes only in the case of compressed extents.
4179 * @num_bytes - Number of bytes to allocate on-disk.
4181 * @min_alloc_size - Indicates the minimum amount of space that the
4182 * allocator should try to satisfy. In some cases
4183 * @num_bytes may be larger than what is required and if
4184 * the filesystem is fragmented then allocation fails.
4185 * However, the presence of @min_alloc_size gives a
4186 * chance to try and satisfy the smaller allocation.
4188 * @empty_size - A hint that you plan on doing more COW. This is the
4189 * size in bytes the allocator should try to find free
4190 * next to the block it returns. This is just a hint and
4191 * may be ignored by the allocator.
4193 * @hint_byte - Hint to the allocator to start searching above the byte
4194 * address passed. It might be ignored.
4196 * @ins - This key is modified to record the found hole. It will
4197 * have the following values:
4198 * ins->objectid == start position
4199 * ins->flags = BTRFS_EXTENT_ITEM_KEY
4200 * ins->offset == the size of the hole.
4202 * @is_data - Boolean flag indicating whether an extent is
4203 * allocated for data (true) or metadata (false)
4205 * @delalloc - Boolean flag indicating whether this allocation is for
4206 * delalloc or not. If 'true' data_rwsem of block groups
4207 * is going to be acquired.
4210 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
4211 * case -ENOSPC is returned then @ins->offset will contain the size of the
4212 * largest available hole the allocator managed to find.
4214 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
4215 u64 num_bytes, u64 min_alloc_size,
4216 u64 empty_size, u64 hint_byte,
4217 struct btrfs_key *ins, int is_data, int delalloc)
4219 struct btrfs_fs_info *fs_info = root->fs_info;
4220 bool final_tried = num_bytes == min_alloc_size;
4224 flags = get_alloc_profile_by_root(root, is_data);
4226 WARN_ON(num_bytes < fs_info->sectorsize);
4227 ret = find_free_extent(root, ram_bytes, num_bytes, empty_size,
4228 hint_byte, ins, flags, delalloc);
4229 if (!ret && !is_data) {
4230 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
4231 } else if (ret == -ENOSPC) {
4232 if (!final_tried && ins->offset) {
4233 num_bytes = min(num_bytes >> 1, ins->offset);
4234 num_bytes = round_down(num_bytes,
4235 fs_info->sectorsize);
4236 num_bytes = max(num_bytes, min_alloc_size);
4237 ram_bytes = num_bytes;
4238 if (num_bytes == min_alloc_size)
4241 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4242 struct btrfs_space_info *sinfo;
4244 sinfo = btrfs_find_space_info(fs_info, flags);
4246 "allocation failed flags %llu, wanted %llu",
4249 btrfs_dump_space_info(fs_info, sinfo,
4257 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
4258 u64 start, u64 len, int delalloc)
4260 struct btrfs_block_group *cache;
4262 cache = btrfs_lookup_block_group(fs_info, start);
4264 btrfs_err(fs_info, "Unable to find block group for %llu",
4269 btrfs_add_free_space(cache, start, len);
4270 btrfs_free_reserved_bytes(cache, len, delalloc);
4271 trace_btrfs_reserved_extent_free(fs_info, start, len);
4273 btrfs_put_block_group(cache);
4277 int btrfs_pin_reserved_extent(struct btrfs_trans_handle *trans, u64 start,
4280 struct btrfs_block_group *cache;
4283 cache = btrfs_lookup_block_group(trans->fs_info, start);
4285 btrfs_err(trans->fs_info, "unable to find block group for %llu",
4290 ret = pin_down_extent(trans, cache, start, len, 1);
4291 btrfs_put_block_group(cache);
4295 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4296 u64 parent, u64 root_objectid,
4297 u64 flags, u64 owner, u64 offset,
4298 struct btrfs_key *ins, int ref_mod)
4300 struct btrfs_fs_info *fs_info = trans->fs_info;
4302 struct btrfs_extent_item *extent_item;
4303 struct btrfs_extent_inline_ref *iref;
4304 struct btrfs_path *path;
4305 struct extent_buffer *leaf;
4310 type = BTRFS_SHARED_DATA_REF_KEY;
4312 type = BTRFS_EXTENT_DATA_REF_KEY;
4314 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
4316 path = btrfs_alloc_path();
4320 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4323 btrfs_free_path(path);
4327 leaf = path->nodes[0];
4328 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4329 struct btrfs_extent_item);
4330 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
4331 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4332 btrfs_set_extent_flags(leaf, extent_item,
4333 flags | BTRFS_EXTENT_FLAG_DATA);
4335 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4336 btrfs_set_extent_inline_ref_type(leaf, iref, type);
4338 struct btrfs_shared_data_ref *ref;
4339 ref = (struct btrfs_shared_data_ref *)(iref + 1);
4340 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
4341 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
4343 struct btrfs_extent_data_ref *ref;
4344 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
4345 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
4346 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
4347 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
4348 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
4351 btrfs_mark_buffer_dirty(path->nodes[0]);
4352 btrfs_free_path(path);
4354 ret = remove_from_free_space_tree(trans, ins->objectid, ins->offset);
4358 ret = btrfs_update_block_group(trans, ins->objectid, ins->offset, 1);
4359 if (ret) { /* -ENOENT, logic error */
4360 btrfs_err(fs_info, "update block group failed for %llu %llu",
4361 ins->objectid, ins->offset);
4364 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
4368 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
4369 struct btrfs_delayed_ref_node *node,
4370 struct btrfs_delayed_extent_op *extent_op)
4372 struct btrfs_fs_info *fs_info = trans->fs_info;
4374 struct btrfs_extent_item *extent_item;
4375 struct btrfs_key extent_key;
4376 struct btrfs_tree_block_info *block_info;
4377 struct btrfs_extent_inline_ref *iref;
4378 struct btrfs_path *path;
4379 struct extent_buffer *leaf;
4380 struct btrfs_delayed_tree_ref *ref;
4381 u32 size = sizeof(*extent_item) + sizeof(*iref);
4383 u64 flags = extent_op->flags_to_set;
4384 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4386 ref = btrfs_delayed_node_to_tree_ref(node);
4388 extent_key.objectid = node->bytenr;
4389 if (skinny_metadata) {
4390 extent_key.offset = ref->level;
4391 extent_key.type = BTRFS_METADATA_ITEM_KEY;
4392 num_bytes = fs_info->nodesize;
4394 extent_key.offset = node->num_bytes;
4395 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
4396 size += sizeof(*block_info);
4397 num_bytes = node->num_bytes;
4400 path = btrfs_alloc_path();
4404 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4407 btrfs_free_path(path);
4411 leaf = path->nodes[0];
4412 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4413 struct btrfs_extent_item);
4414 btrfs_set_extent_refs(leaf, extent_item, 1);
4415 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4416 btrfs_set_extent_flags(leaf, extent_item,
4417 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
4419 if (skinny_metadata) {
4420 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4422 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
4423 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
4424 btrfs_set_tree_block_level(leaf, block_info, ref->level);
4425 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
4428 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
4429 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
4430 btrfs_set_extent_inline_ref_type(leaf, iref,
4431 BTRFS_SHARED_BLOCK_REF_KEY);
4432 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
4434 btrfs_set_extent_inline_ref_type(leaf, iref,
4435 BTRFS_TREE_BLOCK_REF_KEY);
4436 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
4439 btrfs_mark_buffer_dirty(leaf);
4440 btrfs_free_path(path);
4442 ret = remove_from_free_space_tree(trans, extent_key.objectid,
4447 ret = btrfs_update_block_group(trans, extent_key.objectid,
4448 fs_info->nodesize, 1);
4449 if (ret) { /* -ENOENT, logic error */
4450 btrfs_err(fs_info, "update block group failed for %llu %llu",
4451 extent_key.objectid, extent_key.offset);
4455 trace_btrfs_reserved_extent_alloc(fs_info, extent_key.objectid,
4460 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4461 struct btrfs_root *root, u64 owner,
4462 u64 offset, u64 ram_bytes,
4463 struct btrfs_key *ins)
4465 struct btrfs_ref generic_ref = { 0 };
4467 BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
4469 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4470 ins->objectid, ins->offset, 0);
4471 btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner, offset);
4472 btrfs_ref_tree_mod(root->fs_info, &generic_ref);
4474 return btrfs_add_delayed_data_ref(trans, &generic_ref, ram_bytes);
4478 * this is used by the tree logging recovery code. It records that
4479 * an extent has been allocated and makes sure to clear the free
4480 * space cache bits as well
4482 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
4483 u64 root_objectid, u64 owner, u64 offset,
4484 struct btrfs_key *ins)
4486 struct btrfs_fs_info *fs_info = trans->fs_info;
4488 struct btrfs_block_group *block_group;
4489 struct btrfs_space_info *space_info;
4492 * Mixed block groups will exclude before processing the log so we only
4493 * need to do the exclude dance if this fs isn't mixed.
4495 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
4496 ret = __exclude_logged_extent(fs_info, ins->objectid,
4502 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
4506 space_info = block_group->space_info;
4507 spin_lock(&space_info->lock);
4508 spin_lock(&block_group->lock);
4509 space_info->bytes_reserved += ins->offset;
4510 block_group->reserved += ins->offset;
4511 spin_unlock(&block_group->lock);
4512 spin_unlock(&space_info->lock);
4514 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
4517 btrfs_pin_extent(trans, ins->objectid, ins->offset, 1);
4518 btrfs_put_block_group(block_group);
4522 static struct extent_buffer *
4523 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4524 u64 bytenr, int level, u64 owner,
4525 enum btrfs_lock_nesting nest)
4527 struct btrfs_fs_info *fs_info = root->fs_info;
4528 struct extent_buffer *buf;
4530 buf = btrfs_find_create_tree_block(fs_info, bytenr, owner, level);
4535 * Extra safety check in case the extent tree is corrupted and extent
4536 * allocator chooses to use a tree block which is already used and
4539 if (buf->lock_owner == current->pid) {
4540 btrfs_err_rl(fs_info,
4541 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
4542 buf->start, btrfs_header_owner(buf), current->pid);
4543 free_extent_buffer(buf);
4544 return ERR_PTR(-EUCLEAN);
4548 * This needs to stay, because we could allocate a freed block from an
4549 * old tree into a new tree, so we need to make sure this new block is
4550 * set to the appropriate level and owner.
4552 btrfs_set_buffer_lockdep_class(owner, buf, level);
4553 __btrfs_tree_lock(buf, nest);
4554 btrfs_clean_tree_block(buf);
4555 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
4557 set_extent_buffer_uptodate(buf);
4559 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
4560 btrfs_set_header_level(buf, level);
4561 btrfs_set_header_bytenr(buf, buf->start);
4562 btrfs_set_header_generation(buf, trans->transid);
4563 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
4564 btrfs_set_header_owner(buf, owner);
4565 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
4566 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
4567 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
4568 buf->log_index = root->log_transid % 2;
4570 * we allow two log transactions at a time, use different
4571 * EXTENT bit to differentiate dirty pages.
4573 if (buf->log_index == 0)
4574 set_extent_dirty(&root->dirty_log_pages, buf->start,
4575 buf->start + buf->len - 1, GFP_NOFS);
4577 set_extent_new(&root->dirty_log_pages, buf->start,
4578 buf->start + buf->len - 1);
4580 buf->log_index = -1;
4581 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
4582 buf->start + buf->len - 1, GFP_NOFS);
4584 trans->dirty = true;
4585 /* this returns a buffer locked for blocking */
4590 * finds a free extent and does all the dirty work required for allocation
4591 * returns the tree buffer or an ERR_PTR on error.
4593 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
4594 struct btrfs_root *root,
4595 u64 parent, u64 root_objectid,
4596 const struct btrfs_disk_key *key,
4597 int level, u64 hint,
4599 enum btrfs_lock_nesting nest)
4601 struct btrfs_fs_info *fs_info = root->fs_info;
4602 struct btrfs_key ins;
4603 struct btrfs_block_rsv *block_rsv;
4604 struct extent_buffer *buf;
4605 struct btrfs_delayed_extent_op *extent_op;
4606 struct btrfs_ref generic_ref = { 0 };
4609 u32 blocksize = fs_info->nodesize;
4610 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4612 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4613 if (btrfs_is_testing(fs_info)) {
4614 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
4615 level, root_objectid, nest);
4617 root->alloc_bytenr += blocksize;
4622 block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
4623 if (IS_ERR(block_rsv))
4624 return ERR_CAST(block_rsv);
4626 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
4627 empty_size, hint, &ins, 0, 0);
4631 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
4632 root_objectid, nest);
4635 goto out_free_reserved;
4638 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
4640 parent = ins.objectid;
4641 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4645 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
4646 extent_op = btrfs_alloc_delayed_extent_op();
4652 memcpy(&extent_op->key, key, sizeof(extent_op->key));
4654 memset(&extent_op->key, 0, sizeof(extent_op->key));
4655 extent_op->flags_to_set = flags;
4656 extent_op->update_key = skinny_metadata ? false : true;
4657 extent_op->update_flags = true;
4658 extent_op->is_data = false;
4659 extent_op->level = level;
4661 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4662 ins.objectid, ins.offset, parent);
4663 generic_ref.real_root = root->root_key.objectid;
4664 btrfs_init_tree_ref(&generic_ref, level, root_objectid);
4665 btrfs_ref_tree_mod(fs_info, &generic_ref);
4666 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, extent_op);
4668 goto out_free_delayed;
4673 btrfs_free_delayed_extent_op(extent_op);
4675 free_extent_buffer(buf);
4677 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
4679 btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
4680 return ERR_PTR(ret);
4683 struct walk_control {
4684 u64 refs[BTRFS_MAX_LEVEL];
4685 u64 flags[BTRFS_MAX_LEVEL];
4686 struct btrfs_key update_progress;
4687 struct btrfs_key drop_progress;
4699 #define DROP_REFERENCE 1
4700 #define UPDATE_BACKREF 2
4702 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
4703 struct btrfs_root *root,
4704 struct walk_control *wc,
4705 struct btrfs_path *path)
4707 struct btrfs_fs_info *fs_info = root->fs_info;
4713 struct btrfs_key key;
4714 struct extent_buffer *eb;
4719 if (path->slots[wc->level] < wc->reada_slot) {
4720 wc->reada_count = wc->reada_count * 2 / 3;
4721 wc->reada_count = max(wc->reada_count, 2);
4723 wc->reada_count = wc->reada_count * 3 / 2;
4724 wc->reada_count = min_t(int, wc->reada_count,
4725 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
4728 eb = path->nodes[wc->level];
4729 nritems = btrfs_header_nritems(eb);
4731 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
4732 if (nread >= wc->reada_count)
4736 bytenr = btrfs_node_blockptr(eb, slot);
4737 generation = btrfs_node_ptr_generation(eb, slot);
4739 if (slot == path->slots[wc->level])
4742 if (wc->stage == UPDATE_BACKREF &&
4743 generation <= root->root_key.offset)
4746 /* We don't lock the tree block, it's OK to be racy here */
4747 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
4748 wc->level - 1, 1, &refs,
4750 /* We don't care about errors in readahead. */
4755 if (wc->stage == DROP_REFERENCE) {
4759 if (wc->level == 1 &&
4760 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4762 if (!wc->update_ref ||
4763 generation <= root->root_key.offset)
4765 btrfs_node_key_to_cpu(eb, &key, slot);
4766 ret = btrfs_comp_cpu_keys(&key,
4767 &wc->update_progress);
4771 if (wc->level == 1 &&
4772 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4776 btrfs_readahead_node_child(eb, slot);
4779 wc->reada_slot = slot;
4783 * helper to process tree block while walking down the tree.
4785 * when wc->stage == UPDATE_BACKREF, this function updates
4786 * back refs for pointers in the block.
4788 * NOTE: return value 1 means we should stop walking down.
4790 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
4791 struct btrfs_root *root,
4792 struct btrfs_path *path,
4793 struct walk_control *wc, int lookup_info)
4795 struct btrfs_fs_info *fs_info = root->fs_info;
4796 int level = wc->level;
4797 struct extent_buffer *eb = path->nodes[level];
4798 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
4801 if (wc->stage == UPDATE_BACKREF &&
4802 btrfs_header_owner(eb) != root->root_key.objectid)
4806 * when reference count of tree block is 1, it won't increase
4807 * again. once full backref flag is set, we never clear it.
4810 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
4811 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
4812 BUG_ON(!path->locks[level]);
4813 ret = btrfs_lookup_extent_info(trans, fs_info,
4814 eb->start, level, 1,
4817 BUG_ON(ret == -ENOMEM);
4820 BUG_ON(wc->refs[level] == 0);
4823 if (wc->stage == DROP_REFERENCE) {
4824 if (wc->refs[level] > 1)
4827 if (path->locks[level] && !wc->keep_locks) {
4828 btrfs_tree_unlock_rw(eb, path->locks[level]);
4829 path->locks[level] = 0;
4834 /* wc->stage == UPDATE_BACKREF */
4835 if (!(wc->flags[level] & flag)) {
4836 BUG_ON(!path->locks[level]);
4837 ret = btrfs_inc_ref(trans, root, eb, 1);
4838 BUG_ON(ret); /* -ENOMEM */
4839 ret = btrfs_dec_ref(trans, root, eb, 0);
4840 BUG_ON(ret); /* -ENOMEM */
4841 ret = btrfs_set_disk_extent_flags(trans, eb, flag,
4842 btrfs_header_level(eb), 0);
4843 BUG_ON(ret); /* -ENOMEM */
4844 wc->flags[level] |= flag;
4848 * the block is shared by multiple trees, so it's not good to
4849 * keep the tree lock
4851 if (path->locks[level] && level > 0) {
4852 btrfs_tree_unlock_rw(eb, path->locks[level]);
4853 path->locks[level] = 0;
4859 * This is used to verify a ref exists for this root to deal with a bug where we
4860 * would have a drop_progress key that hadn't been updated properly.
4862 static int check_ref_exists(struct btrfs_trans_handle *trans,
4863 struct btrfs_root *root, u64 bytenr, u64 parent,
4866 struct btrfs_path *path;
4867 struct btrfs_extent_inline_ref *iref;
4870 path = btrfs_alloc_path();
4874 ret = lookup_extent_backref(trans, path, &iref, bytenr,
4875 root->fs_info->nodesize, parent,
4876 root->root_key.objectid, level, 0);
4877 btrfs_free_path(path);
4886 * helper to process tree block pointer.
4888 * when wc->stage == DROP_REFERENCE, this function checks
4889 * reference count of the block pointed to. if the block
4890 * is shared and we need update back refs for the subtree
4891 * rooted at the block, this function changes wc->stage to
4892 * UPDATE_BACKREF. if the block is shared and there is no
4893 * need to update back, this function drops the reference
4896 * NOTE: return value 1 means we should stop walking down.
4898 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
4899 struct btrfs_root *root,
4900 struct btrfs_path *path,
4901 struct walk_control *wc, int *lookup_info)
4903 struct btrfs_fs_info *fs_info = root->fs_info;
4907 struct btrfs_key key;
4908 struct btrfs_key first_key;
4909 struct btrfs_ref ref = { 0 };
4910 struct extent_buffer *next;
4911 int level = wc->level;
4914 bool need_account = false;
4916 generation = btrfs_node_ptr_generation(path->nodes[level],
4917 path->slots[level]);
4919 * if the lower level block was created before the snapshot
4920 * was created, we know there is no need to update back refs
4923 if (wc->stage == UPDATE_BACKREF &&
4924 generation <= root->root_key.offset) {
4929 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
4930 btrfs_node_key_to_cpu(path->nodes[level], &first_key,
4931 path->slots[level]);
4933 next = find_extent_buffer(fs_info, bytenr);
4935 next = btrfs_find_create_tree_block(fs_info, bytenr,
4936 root->root_key.objectid, level - 1);
4938 return PTR_ERR(next);
4941 btrfs_tree_lock(next);
4943 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
4944 &wc->refs[level - 1],
4945 &wc->flags[level - 1]);
4949 if (unlikely(wc->refs[level - 1] == 0)) {
4950 btrfs_err(fs_info, "Missing references.");
4956 if (wc->stage == DROP_REFERENCE) {
4957 if (wc->refs[level - 1] > 1) {
4958 need_account = true;
4960 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4963 if (!wc->update_ref ||
4964 generation <= root->root_key.offset)
4967 btrfs_node_key_to_cpu(path->nodes[level], &key,
4968 path->slots[level]);
4969 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
4973 wc->stage = UPDATE_BACKREF;
4974 wc->shared_level = level - 1;
4978 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4982 if (!btrfs_buffer_uptodate(next, generation, 0)) {
4983 btrfs_tree_unlock(next);
4984 free_extent_buffer(next);
4990 if (reada && level == 1)
4991 reada_walk_down(trans, root, wc, path);
4992 next = read_tree_block(fs_info, bytenr, root->root_key.objectid,
4993 generation, level - 1, &first_key);
4995 return PTR_ERR(next);
4996 } else if (!extent_buffer_uptodate(next)) {
4997 free_extent_buffer(next);
5000 btrfs_tree_lock(next);
5004 ASSERT(level == btrfs_header_level(next));
5005 if (level != btrfs_header_level(next)) {
5006 btrfs_err(root->fs_info, "mismatched level");
5010 path->nodes[level] = next;
5011 path->slots[level] = 0;
5012 path->locks[level] = BTRFS_WRITE_LOCK;
5018 wc->refs[level - 1] = 0;
5019 wc->flags[level - 1] = 0;
5020 if (wc->stage == DROP_REFERENCE) {
5021 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5022 parent = path->nodes[level]->start;
5024 ASSERT(root->root_key.objectid ==
5025 btrfs_header_owner(path->nodes[level]));
5026 if (root->root_key.objectid !=
5027 btrfs_header_owner(path->nodes[level])) {
5028 btrfs_err(root->fs_info,
5029 "mismatched block owner");
5037 * If we had a drop_progress we need to verify the refs are set
5038 * as expected. If we find our ref then we know that from here
5039 * on out everything should be correct, and we can clear the
5042 if (wc->restarted) {
5043 ret = check_ref_exists(trans, root, bytenr, parent,
5054 * Reloc tree doesn't contribute to qgroup numbers, and we have
5055 * already accounted them at merge time (replace_path),
5056 * thus we could skip expensive subtree trace here.
5058 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
5060 ret = btrfs_qgroup_trace_subtree(trans, next,
5061 generation, level - 1);
5063 btrfs_err_rl(fs_info,
5064 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
5070 * We need to update the next key in our walk control so we can
5071 * update the drop_progress key accordingly. We don't care if
5072 * find_next_key doesn't find a key because that means we're at
5073 * the end and are going to clean up now.
5075 wc->drop_level = level;
5076 find_next_key(path, level, &wc->drop_progress);
5078 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
5079 fs_info->nodesize, parent);
5080 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid);
5081 ret = btrfs_free_extent(trans, &ref);
5090 btrfs_tree_unlock(next);
5091 free_extent_buffer(next);
5097 * helper to process tree block while walking up the tree.
5099 * when wc->stage == DROP_REFERENCE, this function drops
5100 * reference count on the block.
5102 * when wc->stage == UPDATE_BACKREF, this function changes
5103 * wc->stage back to DROP_REFERENCE if we changed wc->stage
5104 * to UPDATE_BACKREF previously while processing the block.
5106 * NOTE: return value 1 means we should stop walking up.
5108 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
5109 struct btrfs_root *root,
5110 struct btrfs_path *path,
5111 struct walk_control *wc)
5113 struct btrfs_fs_info *fs_info = root->fs_info;
5115 int level = wc->level;
5116 struct extent_buffer *eb = path->nodes[level];
5119 if (wc->stage == UPDATE_BACKREF) {
5120 BUG_ON(wc->shared_level < level);
5121 if (level < wc->shared_level)
5124 ret = find_next_key(path, level + 1, &wc->update_progress);
5128 wc->stage = DROP_REFERENCE;
5129 wc->shared_level = -1;
5130 path->slots[level] = 0;
5133 * check reference count again if the block isn't locked.
5134 * we should start walking down the tree again if reference
5137 if (!path->locks[level]) {
5139 btrfs_tree_lock(eb);
5140 path->locks[level] = BTRFS_WRITE_LOCK;
5142 ret = btrfs_lookup_extent_info(trans, fs_info,
5143 eb->start, level, 1,
5147 btrfs_tree_unlock_rw(eb, path->locks[level]);
5148 path->locks[level] = 0;
5151 BUG_ON(wc->refs[level] == 0);
5152 if (wc->refs[level] == 1) {
5153 btrfs_tree_unlock_rw(eb, path->locks[level]);
5154 path->locks[level] = 0;
5160 /* wc->stage == DROP_REFERENCE */
5161 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5163 if (wc->refs[level] == 1) {
5165 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5166 ret = btrfs_dec_ref(trans, root, eb, 1);
5168 ret = btrfs_dec_ref(trans, root, eb, 0);
5169 BUG_ON(ret); /* -ENOMEM */
5170 if (is_fstree(root->root_key.objectid)) {
5171 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
5173 btrfs_err_rl(fs_info,
5174 "error %d accounting leaf items, quota is out of sync, rescan required",
5179 /* make block locked assertion in btrfs_clean_tree_block happy */
5180 if (!path->locks[level] &&
5181 btrfs_header_generation(eb) == trans->transid) {
5182 btrfs_tree_lock(eb);
5183 path->locks[level] = BTRFS_WRITE_LOCK;
5185 btrfs_clean_tree_block(eb);
5188 if (eb == root->node) {
5189 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5191 else if (root->root_key.objectid != btrfs_header_owner(eb))
5192 goto owner_mismatch;
5194 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5195 parent = path->nodes[level + 1]->start;
5196 else if (root->root_key.objectid !=
5197 btrfs_header_owner(path->nodes[level + 1]))
5198 goto owner_mismatch;
5201 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
5203 wc->refs[level] = 0;
5204 wc->flags[level] = 0;
5208 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
5209 btrfs_header_owner(eb), root->root_key.objectid);
5213 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
5214 struct btrfs_root *root,
5215 struct btrfs_path *path,
5216 struct walk_control *wc)
5218 int level = wc->level;
5219 int lookup_info = 1;
5222 while (level >= 0) {
5223 ret = walk_down_proc(trans, root, path, wc, lookup_info);
5230 if (path->slots[level] >=
5231 btrfs_header_nritems(path->nodes[level]))
5234 ret = do_walk_down(trans, root, path, wc, &lookup_info);
5236 path->slots[level]++;
5245 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
5246 struct btrfs_root *root,
5247 struct btrfs_path *path,
5248 struct walk_control *wc, int max_level)
5250 int level = wc->level;
5253 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
5254 while (level < max_level && path->nodes[level]) {
5256 if (path->slots[level] + 1 <
5257 btrfs_header_nritems(path->nodes[level])) {
5258 path->slots[level]++;
5261 ret = walk_up_proc(trans, root, path, wc);
5267 if (path->locks[level]) {
5268 btrfs_tree_unlock_rw(path->nodes[level],
5269 path->locks[level]);
5270 path->locks[level] = 0;
5272 free_extent_buffer(path->nodes[level]);
5273 path->nodes[level] = NULL;
5281 * drop a subvolume tree.
5283 * this function traverses the tree freeing any blocks that only
5284 * referenced by the tree.
5286 * when a shared tree block is found. this function decreases its
5287 * reference count by one. if update_ref is true, this function
5288 * also make sure backrefs for the shared block and all lower level
5289 * blocks are properly updated.
5291 * If called with for_reloc == 0, may exit early with -EAGAIN
5293 int btrfs_drop_snapshot(struct btrfs_root *root, int update_ref, int for_reloc)
5295 struct btrfs_fs_info *fs_info = root->fs_info;
5296 struct btrfs_path *path;
5297 struct btrfs_trans_handle *trans;
5298 struct btrfs_root *tree_root = fs_info->tree_root;
5299 struct btrfs_root_item *root_item = &root->root_item;
5300 struct walk_control *wc;
5301 struct btrfs_key key;
5305 bool root_dropped = false;
5307 btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
5309 path = btrfs_alloc_path();
5315 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5317 btrfs_free_path(path);
5323 * Use join to avoid potential EINTR from transaction start. See
5324 * wait_reserve_ticket and the whole reservation callchain.
5327 trans = btrfs_join_transaction(tree_root);
5329 trans = btrfs_start_transaction(tree_root, 0);
5330 if (IS_ERR(trans)) {
5331 err = PTR_ERR(trans);
5335 err = btrfs_run_delayed_items(trans);
5340 * This will help us catch people modifying the fs tree while we're
5341 * dropping it. It is unsafe to mess with the fs tree while it's being
5342 * dropped as we unlock the root node and parent nodes as we walk down
5343 * the tree, assuming nothing will change. If something does change
5344 * then we'll have stale information and drop references to blocks we've
5347 set_bit(BTRFS_ROOT_DELETING, &root->state);
5348 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
5349 level = btrfs_header_level(root->node);
5350 path->nodes[level] = btrfs_lock_root_node(root);
5351 path->slots[level] = 0;
5352 path->locks[level] = BTRFS_WRITE_LOCK;
5353 memset(&wc->update_progress, 0,
5354 sizeof(wc->update_progress));
5356 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
5357 memcpy(&wc->update_progress, &key,
5358 sizeof(wc->update_progress));
5360 level = btrfs_root_drop_level(root_item);
5362 path->lowest_level = level;
5363 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5364 path->lowest_level = 0;
5372 * unlock our path, this is safe because only this
5373 * function is allowed to delete this snapshot
5375 btrfs_unlock_up_safe(path, 0);
5377 level = btrfs_header_level(root->node);
5379 btrfs_tree_lock(path->nodes[level]);
5380 path->locks[level] = BTRFS_WRITE_LOCK;
5382 ret = btrfs_lookup_extent_info(trans, fs_info,
5383 path->nodes[level]->start,
5384 level, 1, &wc->refs[level],
5390 BUG_ON(wc->refs[level] == 0);
5392 if (level == btrfs_root_drop_level(root_item))
5395 btrfs_tree_unlock(path->nodes[level]);
5396 path->locks[level] = 0;
5397 WARN_ON(wc->refs[level] != 1);
5402 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
5404 wc->shared_level = -1;
5405 wc->stage = DROP_REFERENCE;
5406 wc->update_ref = update_ref;
5408 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5412 ret = walk_down_tree(trans, root, path, wc);
5418 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
5425 BUG_ON(wc->stage != DROP_REFERENCE);
5429 if (wc->stage == DROP_REFERENCE) {
5430 wc->drop_level = wc->level;
5431 btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
5433 path->slots[wc->drop_level]);
5435 btrfs_cpu_key_to_disk(&root_item->drop_progress,
5436 &wc->drop_progress);
5437 btrfs_set_root_drop_level(root_item, wc->drop_level);
5439 BUG_ON(wc->level == 0);
5440 if (btrfs_should_end_transaction(trans) ||
5441 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
5442 ret = btrfs_update_root(trans, tree_root,
5446 btrfs_abort_transaction(trans, ret);
5451 btrfs_end_transaction_throttle(trans);
5452 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
5453 btrfs_debug(fs_info,
5454 "drop snapshot early exit");
5460 * Use join to avoid potential EINTR from transaction
5461 * start. See wait_reserve_ticket and the whole
5462 * reservation callchain.
5465 trans = btrfs_join_transaction(tree_root);
5467 trans = btrfs_start_transaction(tree_root, 0);
5468 if (IS_ERR(trans)) {
5469 err = PTR_ERR(trans);
5474 btrfs_release_path(path);
5478 ret = btrfs_del_root(trans, &root->root_key);
5480 btrfs_abort_transaction(trans, ret);
5485 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
5486 ret = btrfs_find_root(tree_root, &root->root_key, path,
5489 btrfs_abort_transaction(trans, ret);
5492 } else if (ret > 0) {
5493 /* if we fail to delete the orphan item this time
5494 * around, it'll get picked up the next time.
5496 * The most common failure here is just -ENOENT.
5498 btrfs_del_orphan_item(trans, tree_root,
5499 root->root_key.objectid);
5504 * This subvolume is going to be completely dropped, and won't be
5505 * recorded as dirty roots, thus pertrans meta rsv will not be freed at
5506 * commit transaction time. So free it here manually.
5508 btrfs_qgroup_convert_reserved_meta(root, INT_MAX);
5509 btrfs_qgroup_free_meta_all_pertrans(root);
5511 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state))
5512 btrfs_add_dropped_root(trans, root);
5514 btrfs_put_root(root);
5515 root_dropped = true;
5517 btrfs_end_transaction_throttle(trans);
5520 btrfs_free_path(path);
5523 * So if we need to stop dropping the snapshot for whatever reason we
5524 * need to make sure to add it back to the dead root list so that we
5525 * keep trying to do the work later. This also cleans up roots if we
5526 * don't have it in the radix (like when we recover after a power fail
5527 * or unmount) so we don't leak memory.
5529 if (!for_reloc && !root_dropped)
5530 btrfs_add_dead_root(root);
5535 * drop subtree rooted at tree block 'node'.
5537 * NOTE: this function will unlock and release tree block 'node'
5538 * only used by relocation code
5540 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
5541 struct btrfs_root *root,
5542 struct extent_buffer *node,
5543 struct extent_buffer *parent)
5545 struct btrfs_fs_info *fs_info = root->fs_info;
5546 struct btrfs_path *path;
5547 struct walk_control *wc;
5553 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
5555 path = btrfs_alloc_path();
5559 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5561 btrfs_free_path(path);
5565 btrfs_assert_tree_locked(parent);
5566 parent_level = btrfs_header_level(parent);
5567 atomic_inc(&parent->refs);
5568 path->nodes[parent_level] = parent;
5569 path->slots[parent_level] = btrfs_header_nritems(parent);
5571 btrfs_assert_tree_locked(node);
5572 level = btrfs_header_level(node);
5573 path->nodes[level] = node;
5574 path->slots[level] = 0;
5575 path->locks[level] = BTRFS_WRITE_LOCK;
5577 wc->refs[parent_level] = 1;
5578 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5580 wc->shared_level = -1;
5581 wc->stage = DROP_REFERENCE;
5584 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5587 wret = walk_down_tree(trans, root, path, wc);
5593 wret = walk_up_tree(trans, root, path, wc, parent_level);
5601 btrfs_free_path(path);
5606 * helper to account the unused space of all the readonly block group in the
5607 * space_info. takes mirrors into account.
5609 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
5611 struct btrfs_block_group *block_group;
5615 /* It's df, we don't care if it's racy */
5616 if (list_empty(&sinfo->ro_bgs))
5619 spin_lock(&sinfo->lock);
5620 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
5621 spin_lock(&block_group->lock);
5623 if (!block_group->ro) {
5624 spin_unlock(&block_group->lock);
5628 factor = btrfs_bg_type_to_factor(block_group->flags);
5629 free_bytes += (block_group->length -
5630 block_group->used) * factor;
5632 spin_unlock(&block_group->lock);
5634 spin_unlock(&sinfo->lock);
5639 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
5642 return unpin_extent_range(fs_info, start, end, false);
5646 * It used to be that old block groups would be left around forever.
5647 * Iterating over them would be enough to trim unused space. Since we
5648 * now automatically remove them, we also need to iterate over unallocated
5651 * We don't want a transaction for this since the discard may take a
5652 * substantial amount of time. We don't require that a transaction be
5653 * running, but we do need to take a running transaction into account
5654 * to ensure that we're not discarding chunks that were released or
5655 * allocated in the current transaction.
5657 * Holding the chunks lock will prevent other threads from allocating
5658 * or releasing chunks, but it won't prevent a running transaction
5659 * from committing and releasing the memory that the pending chunks
5660 * list head uses. For that, we need to take a reference to the
5661 * transaction and hold the commit root sem. We only need to hold
5662 * it while performing the free space search since we have already
5663 * held back allocations.
5665 static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
5667 u64 start = SZ_1M, len = 0, end = 0;
5672 /* Discard not supported = nothing to do. */
5673 if (!blk_queue_discard(bdev_get_queue(device->bdev)))
5676 /* Not writable = nothing to do. */
5677 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
5680 /* No free space = nothing to do. */
5681 if (device->total_bytes <= device->bytes_used)
5687 struct btrfs_fs_info *fs_info = device->fs_info;
5690 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
5694 find_first_clear_extent_bit(&device->alloc_state, start,
5696 CHUNK_TRIMMED | CHUNK_ALLOCATED);
5698 /* Check if there are any CHUNK_* bits left */
5699 if (start > device->total_bytes) {
5700 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
5701 btrfs_warn_in_rcu(fs_info,
5702 "ignoring attempt to trim beyond device size: offset %llu length %llu device %s device size %llu",
5703 start, end - start + 1,
5704 rcu_str_deref(device->name),
5705 device->total_bytes);
5706 mutex_unlock(&fs_info->chunk_mutex);
5711 /* Ensure we skip the reserved area in the first 1M */
5712 start = max_t(u64, start, SZ_1M);
5715 * If find_first_clear_extent_bit find a range that spans the
5716 * end of the device it will set end to -1, in this case it's up
5717 * to the caller to trim the value to the size of the device.
5719 end = min(end, device->total_bytes - 1);
5721 len = end - start + 1;
5723 /* We didn't find any extents */
5725 mutex_unlock(&fs_info->chunk_mutex);
5730 ret = btrfs_issue_discard(device->bdev, start, len,
5733 set_extent_bits(&device->alloc_state, start,
5736 mutex_unlock(&fs_info->chunk_mutex);
5744 if (fatal_signal_pending(current)) {
5756 * Trim the whole filesystem by:
5757 * 1) trimming the free space in each block group
5758 * 2) trimming the unallocated space on each device
5760 * This will also continue trimming even if a block group or device encounters
5761 * an error. The return value will be the last error, or 0 if nothing bad
5764 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
5766 struct btrfs_block_group *cache = NULL;
5767 struct btrfs_device *device;
5768 struct list_head *devices;
5770 u64 range_end = U64_MAX;
5781 * Check range overflow if range->len is set.
5782 * The default range->len is U64_MAX.
5784 if (range->len != U64_MAX &&
5785 check_add_overflow(range->start, range->len, &range_end))
5788 cache = btrfs_lookup_first_block_group(fs_info, range->start);
5789 for (; cache; cache = btrfs_next_block_group(cache)) {
5790 if (cache->start >= range_end) {
5791 btrfs_put_block_group(cache);
5795 start = max(range->start, cache->start);
5796 end = min(range_end, cache->start + cache->length);
5798 if (end - start >= range->minlen) {
5799 if (!btrfs_block_group_done(cache)) {
5800 ret = btrfs_cache_block_group(cache, 0);
5806 ret = btrfs_wait_block_group_cache_done(cache);
5813 ret = btrfs_trim_block_group(cache,
5819 trimmed += group_trimmed;
5830 "failed to trim %llu block group(s), last error %d",
5832 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5833 devices = &fs_info->fs_devices->devices;
5834 list_for_each_entry(device, devices, dev_list) {
5835 ret = btrfs_trim_free_extents(device, &group_trimmed);
5842 trimmed += group_trimmed;
5844 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5848 "failed to trim %llu device(s), last error %d",
5849 dev_failed, dev_ret);
5850 range->len = trimmed;