xref: /linux/fs/btrfs/extent-tree.c (revision c97b139c6ceeb69b264e0a87f2a47bab651a51a8)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5 
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>
19 #include "ctree.h"
20 #include "extent-tree.h"
21 #include "transaction.h"
22 #include "disk-io.h"
23 #include "print-tree.h"
24 #include "volumes.h"
25 #include "raid56.h"
26 #include "locking.h"
27 #include "free-space-cache.h"
28 #include "free-space-tree.h"
29 #include "qgroup.h"
30 #include "ref-verify.h"
31 #include "space-info.h"
32 #include "block-rsv.h"
33 #include "discard.h"
34 #include "zoned.h"
35 #include "dev-replace.h"
36 #include "fs.h"
37 #include "accessors.h"
38 #include "root-tree.h"
39 #include "file-item.h"
40 #include "orphan.h"
41 #include "tree-checker.h"
42 #include "raid-stripe-tree.h"
43 #include "delayed-inode.h"
44 #include "relocation.h"
45 
46 #undef SCRAMBLE_DELAYED_REFS
47 
48 
49 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
50 			       struct btrfs_delayed_ref_head *href,
51 			       const struct btrfs_delayed_ref_node *node,
52 			       struct btrfs_delayed_extent_op *extra_op);
53 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
54 				    struct extent_buffer *leaf,
55 				    struct btrfs_extent_item *ei);
56 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
57 				      u64 parent, u64 root_objectid,
58 				      u64 flags, u64 owner, u64 offset,
59 				      struct btrfs_key *ins, int ref_mod, u64 oref_root);
60 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
61 				     const struct btrfs_delayed_ref_node *node,
62 				     struct btrfs_delayed_extent_op *extent_op);
63 static int find_next_key(const struct btrfs_path *path, int level,
64 			 struct btrfs_key *key);
65 
66 static int block_group_bits(const struct btrfs_block_group *cache, u64 bits)
67 {
68 	return (cache->flags & bits) == bits;
69 }
70 
71 /* simple helper to search for an existing data extent at a given offset */
72 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
73 {
74 	struct btrfs_root *root = btrfs_extent_root(fs_info, start);
75 	struct btrfs_key key;
76 	BTRFS_PATH_AUTO_FREE(path);
77 
78 	if (unlikely(!root)) {
79 		btrfs_err(fs_info,
80 			  "missing extent root for extent at bytenr %llu", start);
81 		return -EUCLEAN;
82 	}
83 
84 	path = btrfs_alloc_path();
85 	if (!path)
86 		return -ENOMEM;
87 
88 	key.objectid = start;
89 	key.type = BTRFS_EXTENT_ITEM_KEY;
90 	key.offset = len;
91 	return btrfs_search_slot(NULL, root, &key, path, 0, 0);
92 }
93 
94 /*
95  * helper function to lookup reference count and flags of a tree block.
96  *
97  * the head node for delayed ref is used to store the sum of all the
98  * reference count modifications queued up in the rbtree. the head
99  * node may also store the extent flags to set. This way you can check
100  * to see what the reference count and extent flags would be if all of
101  * the delayed refs are not processed.
102  */
103 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
104 			     struct btrfs_fs_info *fs_info, u64 bytenr,
105 			     u64 offset, int metadata, u64 *refs, u64 *flags,
106 			     u64 *owning_root)
107 {
108 	struct btrfs_root *extent_root;
109 	struct btrfs_delayed_ref_head *head;
110 	struct btrfs_delayed_ref_root *delayed_refs;
111 	BTRFS_PATH_AUTO_FREE(path);
112 	struct btrfs_key key;
113 	u64 num_refs;
114 	u64 extent_flags;
115 	u64 owner = 0;
116 	int ret;
117 
118 	/*
119 	 * If we don't have skinny metadata, don't bother doing anything
120 	 * different
121 	 */
122 	if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
123 		offset = fs_info->nodesize;
124 		metadata = 0;
125 	}
126 
127 	path = btrfs_alloc_path();
128 	if (!path)
129 		return -ENOMEM;
130 
131 search_again:
132 	key.objectid = bytenr;
133 	if (metadata)
134 		key.type = BTRFS_METADATA_ITEM_KEY;
135 	else
136 		key.type = BTRFS_EXTENT_ITEM_KEY;
137 	key.offset = offset;
138 
139 	extent_root = btrfs_extent_root(fs_info, bytenr);
140 	if (unlikely(!extent_root)) {
141 		btrfs_err(fs_info,
142 			  "missing extent root for extent at bytenr %llu", bytenr);
143 		return -EUCLEAN;
144 	}
145 
146 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
147 	if (ret < 0)
148 		return ret;
149 
150 	if (ret > 0 && key.type == BTRFS_METADATA_ITEM_KEY) {
151 		if (path->slots[0]) {
152 			path->slots[0]--;
153 			btrfs_item_key_to_cpu(path->nodes[0], &key,
154 					      path->slots[0]);
155 			if (key.objectid == bytenr &&
156 			    key.type == BTRFS_EXTENT_ITEM_KEY &&
157 			    key.offset == fs_info->nodesize)
158 				ret = 0;
159 		}
160 	}
161 
162 	if (ret == 0) {
163 		struct extent_buffer *leaf = path->nodes[0];
164 		struct btrfs_extent_item *ei;
165 		const u32 item_size = btrfs_item_size(leaf, path->slots[0]);
166 
167 		if (unlikely(item_size < sizeof(*ei))) {
168 			ret = -EUCLEAN;
169 			btrfs_err(fs_info,
170 			"unexpected extent item size, has %u expect >= %zu",
171 				  item_size, sizeof(*ei));
172 			btrfs_abort_transaction(trans, ret);
173 			return ret;
174 		}
175 
176 		ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
177 		num_refs = btrfs_extent_refs(leaf, ei);
178 		if (unlikely(num_refs == 0)) {
179 			ret = -EUCLEAN;
180 			btrfs_err(fs_info,
181 		"unexpected zero reference count for extent item " BTRFS_KEY_FMT,
182 				  BTRFS_KEY_FMT_VALUE(&key));
183 			btrfs_abort_transaction(trans, ret);
184 			return ret;
185 		}
186 		extent_flags = btrfs_extent_flags(leaf, ei);
187 		owner = btrfs_get_extent_owner_root(fs_info, leaf, path->slots[0]);
188 	} else {
189 		num_refs = 0;
190 		extent_flags = 0;
191 		ret = 0;
192 	}
193 
194 	delayed_refs = &trans->transaction->delayed_refs;
195 	spin_lock(&delayed_refs->lock);
196 	head = btrfs_find_delayed_ref_head(fs_info, delayed_refs, bytenr);
197 	if (head) {
198 		if (!mutex_trylock(&head->mutex)) {
199 			refcount_inc(&head->refs);
200 			spin_unlock(&delayed_refs->lock);
201 
202 			btrfs_release_path(path);
203 
204 			/*
205 			 * Mutex was contended, block until it's released and try
206 			 * again
207 			 */
208 			mutex_lock(&head->mutex);
209 			mutex_unlock(&head->mutex);
210 			btrfs_put_delayed_ref_head(head);
211 			goto search_again;
212 		}
213 		spin_lock(&head->lock);
214 		if (head->extent_op && head->extent_op->update_flags)
215 			extent_flags |= head->extent_op->flags_to_set;
216 
217 		num_refs += head->ref_mod;
218 		spin_unlock(&head->lock);
219 		mutex_unlock(&head->mutex);
220 	}
221 	spin_unlock(&delayed_refs->lock);
222 
223 	WARN_ON(num_refs == 0);
224 	if (refs)
225 		*refs = num_refs;
226 	if (flags)
227 		*flags = extent_flags;
228 	if (owning_root)
229 		*owning_root = owner;
230 
231 	return ret;
232 }
233 
234 /*
235  * Back reference rules.  Back refs have three main goals:
236  *
237  * 1) differentiate between all holders of references to an extent so that
238  *    when a reference is dropped we can make sure it was a valid reference
239  *    before freeing the extent.
240  *
241  * 2) Provide enough information to quickly find the holders of an extent
242  *    if we notice a given block is corrupted or bad.
243  *
244  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
245  *    maintenance.  This is actually the same as #2, but with a slightly
246  *    different use case.
247  *
248  * There are two kinds of back refs. The implicit back refs is optimized
249  * for pointers in non-shared tree blocks. For a given pointer in a block,
250  * back refs of this kind provide information about the block's owner tree
251  * and the pointer's key. These information allow us to find the block by
252  * b-tree searching. The full back refs is for pointers in tree blocks not
253  * referenced by their owner trees. The location of tree block is recorded
254  * in the back refs. Actually the full back refs is generic, and can be
255  * used in all cases the implicit back refs is used. The major shortcoming
256  * of the full back refs is its overhead. Every time a tree block gets
257  * COWed, we have to update back refs entry for all pointers in it.
258  *
259  * For a newly allocated tree block, we use implicit back refs for
260  * pointers in it. This means most tree related operations only involve
261  * implicit back refs. For a tree block created in old transaction, the
262  * only way to drop a reference to it is COW it. So we can detect the
263  * event that tree block loses its owner tree's reference and do the
264  * back refs conversion.
265  *
266  * When a tree block is COWed through a tree, there are four cases:
267  *
268  * The reference count of the block is one and the tree is the block's
269  * owner tree. Nothing to do in this case.
270  *
271  * The reference count of the block is one and the tree is not the
272  * block's owner tree. In this case, full back refs is used for pointers
273  * in the block. Remove these full back refs, add implicit back refs for
274  * every pointers in the new block.
275  *
276  * The reference count of the block is greater than one and the tree is
277  * the block's owner tree. In this case, implicit back refs is used for
278  * pointers in the block. Add full back refs for every pointers in the
279  * block, increase lower level extents' reference counts. The original
280  * implicit back refs are entailed to the new block.
281  *
282  * The reference count of the block is greater than one and the tree is
283  * not the block's owner tree. Add implicit back refs for every pointer in
284  * the new block, increase lower level extents' reference count.
285  *
286  * Back Reference Key composing:
287  *
288  * The key objectid corresponds to the first byte in the extent,
289  * The key type is used to differentiate between types of back refs.
290  * There are different meanings of the key offset for different types
291  * of back refs.
292  *
293  * File extents can be referenced by:
294  *
295  * - multiple snapshots, subvolumes, or different generations in one subvol
296  * - different files inside a single subvolume
297  * - different offsets inside a file (bookend extents in file.c)
298  *
299  * The extent ref structure for the implicit back refs has fields for:
300  *
301  * - Objectid of the subvolume root
302  * - objectid of the file holding the reference
303  * - original offset in the file
304  * - how many bookend extents
305  *
306  * The key offset for the implicit back refs is hash of the first
307  * three fields.
308  *
309  * The extent ref structure for the full back refs has field for:
310  *
311  * - number of pointers in the tree leaf
312  *
313  * The key offset for the implicit back refs is the first byte of
314  * the tree leaf
315  *
316  * When a file extent is allocated, The implicit back refs is used.
317  * the fields are filled in:
318  *
319  *     (root_key.objectid, inode objectid, offset in file, 1)
320  *
321  * When a file extent is removed file truncation, we find the
322  * corresponding implicit back refs and check the following fields:
323  *
324  *     (btrfs_header_owner(leaf), inode objectid, offset in file)
325  *
326  * Btree extents can be referenced by:
327  *
328  * - Different subvolumes
329  *
330  * Both the implicit back refs and the full back refs for tree blocks
331  * only consist of key. The key offset for the implicit back refs is
332  * objectid of block's owner tree. The key offset for the full back refs
333  * is the first byte of parent block.
334  *
335  * When implicit back refs is used, information about the lowest key and
336  * level of the tree block are required. These information are stored in
337  * tree block info structure.
338  */
339 
340 /*
341  * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
342  * is_data == BTRFS_REF_TYPE_DATA, data type is required,
343  * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
344  */
345 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
346 				     const struct btrfs_extent_inline_ref *iref,
347 				     enum btrfs_inline_ref_type is_data)
348 {
349 	struct btrfs_fs_info *fs_info = eb->fs_info;
350 	int type = btrfs_extent_inline_ref_type(eb, iref);
351 	u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
352 
353 	if (type == BTRFS_EXTENT_OWNER_REF_KEY) {
354 		ASSERT(btrfs_fs_incompat(fs_info, SIMPLE_QUOTA));
355 		return type;
356 	}
357 
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)
364 				return type;
365 			if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
366 				ASSERT(fs_info);
367 				/*
368 				 * Every shared one has parent tree block,
369 				 * which must be aligned to sector size.
370 				 */
371 				if (offset && IS_ALIGNED(offset, fs_info->sectorsize))
372 					return type;
373 			}
374 		} else if (is_data == BTRFS_REF_TYPE_DATA) {
375 			if (type == BTRFS_EXTENT_DATA_REF_KEY)
376 				return type;
377 			if (type == BTRFS_SHARED_DATA_REF_KEY) {
378 				ASSERT(fs_info);
379 				/*
380 				 * Every shared one has parent tree block,
381 				 * which must be aligned to sector size.
382 				 */
383 				if (offset &&
384 				    IS_ALIGNED(offset, fs_info->sectorsize))
385 					return type;
386 			}
387 		} else {
388 			ASSERT(is_data == BTRFS_REF_TYPE_ANY, "is_data=%d", is_data);
389 			return type;
390 		}
391 	}
392 
393 	WARN_ON(1);
394 	btrfs_print_leaf(eb);
395 	btrfs_err(fs_info,
396 		  "eb %llu iref 0x%lx invalid extent inline ref type %d",
397 		  eb->start, (unsigned long)iref, type);
398 
399 	return BTRFS_REF_TYPE_INVALID;
400 }
401 
402 u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
403 {
404 	u32 high_crc = ~(u32)0;
405 	u32 low_crc = ~(u32)0;
406 	__le64 lenum;
407 
408 	lenum = cpu_to_le64(root_objectid);
409 	high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
410 	lenum = cpu_to_le64(owner);
411 	low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
412 	lenum = cpu_to_le64(offset);
413 	low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
414 
415 	return ((u64)high_crc << 31) ^ (u64)low_crc;
416 }
417 
418 static u64 hash_extent_data_ref_item(const struct extent_buffer *leaf,
419 				     const struct btrfs_extent_data_ref *ref)
420 {
421 	return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
422 				    btrfs_extent_data_ref_objectid(leaf, ref),
423 				    btrfs_extent_data_ref_offset(leaf, ref));
424 }
425 
426 static bool match_extent_data_ref(const struct extent_buffer *leaf,
427 				  const struct btrfs_extent_data_ref *ref,
428 				  u64 root_objectid, u64 owner, u64 offset)
429 {
430 	if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
431 	    btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
432 	    btrfs_extent_data_ref_offset(leaf, ref) != offset)
433 		return false;
434 	return true;
435 }
436 
437 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
438 					   struct btrfs_path *path,
439 					   u64 bytenr, u64 parent,
440 					   u64 root_objectid,
441 					   u64 owner, u64 offset)
442 {
443 	struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
444 	struct btrfs_key key;
445 	struct btrfs_extent_data_ref *ref;
446 	struct extent_buffer *leaf;
447 	u32 nritems;
448 	int recow;
449 	int ret;
450 
451 	if (unlikely(!root)) {
452 		btrfs_err(trans->fs_info,
453 			  "missing extent root for extent at bytenr %llu", bytenr);
454 		return -EUCLEAN;
455 	}
456 
457 	key.objectid = bytenr;
458 	if (parent) {
459 		key.type = BTRFS_SHARED_DATA_REF_KEY;
460 		key.offset = parent;
461 	} else {
462 		key.type = BTRFS_EXTENT_DATA_REF_KEY;
463 		key.offset = hash_extent_data_ref(root_objectid,
464 						  owner, offset);
465 	}
466 again:
467 	recow = 0;
468 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
469 	if (ret < 0)
470 		return ret;
471 
472 	if (parent) {
473 		if (ret)
474 			return -ENOENT;
475 		return 0;
476 	}
477 
478 	ret = -ENOENT;
479 	leaf = path->nodes[0];
480 	nritems = btrfs_header_nritems(leaf);
481 	while (1) {
482 		if (path->slots[0] >= nritems) {
483 			ret = btrfs_next_leaf(root, path);
484 			if (ret) {
485 				if (ret > 0)
486 					return -ENOENT;
487 				return ret;
488 			}
489 
490 			leaf = path->nodes[0];
491 			nritems = btrfs_header_nritems(leaf);
492 			recow = 1;
493 		}
494 
495 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
496 		if (key.objectid != bytenr ||
497 		    key.type != BTRFS_EXTENT_DATA_REF_KEY)
498 			return -ENOENT;
499 
500 		ref = btrfs_item_ptr(leaf, path->slots[0],
501 				     struct btrfs_extent_data_ref);
502 
503 		if (match_extent_data_ref(leaf, ref, root_objectid,
504 					  owner, offset)) {
505 			if (recow) {
506 				btrfs_release_path(path);
507 				goto again;
508 			}
509 			return 0;
510 		}
511 		path->slots[0]++;
512 	}
513 
514 	return ret;
515 }
516 
517 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
518 					   struct btrfs_path *path,
519 					   const struct btrfs_delayed_ref_node *node,
520 					   u64 bytenr)
521 {
522 	struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
523 	struct btrfs_key key;
524 	struct extent_buffer *leaf;
525 	u64 owner = btrfs_delayed_ref_owner(node);
526 	u64 offset = btrfs_delayed_ref_offset(node);
527 	u32 size;
528 	u32 num_refs;
529 	int ret;
530 
531 	if (unlikely(!root)) {
532 		btrfs_err(trans->fs_info,
533 			  "missing extent root for extent at bytenr %llu", bytenr);
534 		return -EUCLEAN;
535 	}
536 
537 	key.objectid = bytenr;
538 	if (node->parent) {
539 		key.type = BTRFS_SHARED_DATA_REF_KEY;
540 		key.offset = node->parent;
541 		size = sizeof(struct btrfs_shared_data_ref);
542 	} else {
543 		key.type = BTRFS_EXTENT_DATA_REF_KEY;
544 		key.offset = hash_extent_data_ref(node->ref_root, owner, offset);
545 		size = sizeof(struct btrfs_extent_data_ref);
546 	}
547 
548 	ret = btrfs_insert_empty_item(trans, root, path, &key, size);
549 	if (ret && ret != -EEXIST)
550 		goto fail;
551 
552 	leaf = path->nodes[0];
553 	if (node->parent) {
554 		struct btrfs_shared_data_ref *ref;
555 		ref = btrfs_item_ptr(leaf, path->slots[0],
556 				     struct btrfs_shared_data_ref);
557 		if (ret == 0) {
558 			btrfs_set_shared_data_ref_count(leaf, ref, node->ref_mod);
559 		} else {
560 			num_refs = btrfs_shared_data_ref_count(leaf, ref);
561 			num_refs += node->ref_mod;
562 			btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
563 		}
564 	} else {
565 		struct btrfs_extent_data_ref *ref;
566 		while (ret == -EEXIST) {
567 			ref = btrfs_item_ptr(leaf, path->slots[0],
568 					     struct btrfs_extent_data_ref);
569 			if (match_extent_data_ref(leaf, ref, node->ref_root,
570 						  owner, offset))
571 				break;
572 			btrfs_release_path(path);
573 			key.offset++;
574 			ret = btrfs_insert_empty_item(trans, root, path, &key,
575 						      size);
576 			if (ret && ret != -EEXIST)
577 				goto fail;
578 
579 			leaf = path->nodes[0];
580 		}
581 		ref = btrfs_item_ptr(leaf, path->slots[0],
582 				     struct btrfs_extent_data_ref);
583 		if (ret == 0) {
584 			btrfs_set_extent_data_ref_root(leaf, ref, node->ref_root);
585 			btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
586 			btrfs_set_extent_data_ref_offset(leaf, ref, offset);
587 			btrfs_set_extent_data_ref_count(leaf, ref, node->ref_mod);
588 		} else {
589 			num_refs = btrfs_extent_data_ref_count(leaf, ref);
590 			num_refs += node->ref_mod;
591 			btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
592 		}
593 	}
594 	ret = 0;
595 fail:
596 	btrfs_release_path(path);
597 	return ret;
598 }
599 
600 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
601 					   struct btrfs_root *root,
602 					   struct btrfs_path *path,
603 					   int refs_to_drop)
604 {
605 	struct btrfs_key key;
606 	struct btrfs_extent_data_ref *ref1 = NULL;
607 	struct btrfs_shared_data_ref *ref2 = NULL;
608 	struct extent_buffer *leaf;
609 	u32 num_refs = 0;
610 	int ret = 0;
611 
612 	leaf = path->nodes[0];
613 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
614 
615 	if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
616 		ref1 = btrfs_item_ptr(leaf, path->slots[0],
617 				      struct btrfs_extent_data_ref);
618 		num_refs = btrfs_extent_data_ref_count(leaf, ref1);
619 	} else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
620 		ref2 = btrfs_item_ptr(leaf, path->slots[0],
621 				      struct btrfs_shared_data_ref);
622 		num_refs = btrfs_shared_data_ref_count(leaf, ref2);
623 	} else {
624 		btrfs_err(trans->fs_info,
625 			  "unrecognized backref key " BTRFS_KEY_FMT,
626 			  BTRFS_KEY_FMT_VALUE(&key));
627 		btrfs_abort_transaction(trans, -EUCLEAN);
628 		return -EUCLEAN;
629 	}
630 
631 	BUG_ON(num_refs < refs_to_drop);
632 	num_refs -= refs_to_drop;
633 
634 	if (num_refs == 0) {
635 		ret = btrfs_del_item(trans, root, path);
636 	} else {
637 		if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
638 			btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
639 		else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
640 			btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
641 	}
642 	return ret;
643 }
644 
645 static noinline u32 extent_data_ref_count(const struct btrfs_path *path,
646 					  const struct btrfs_extent_inline_ref *iref)
647 {
648 	struct btrfs_key key;
649 	struct extent_buffer *leaf;
650 	const struct btrfs_extent_data_ref *ref1;
651 	const struct btrfs_shared_data_ref *ref2;
652 	u32 num_refs = 0;
653 	int type;
654 
655 	leaf = path->nodes[0];
656 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
657 
658 	if (iref) {
659 		/*
660 		 * If type is invalid, we should have bailed out earlier than
661 		 * this call.
662 		 */
663 		type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
664 		ASSERT(type != BTRFS_REF_TYPE_INVALID);
665 		if (type == BTRFS_EXTENT_DATA_REF_KEY) {
666 			ref1 = (const struct btrfs_extent_data_ref *)(&iref->offset);
667 			num_refs = btrfs_extent_data_ref_count(leaf, ref1);
668 		} else {
669 			ref2 = (const struct btrfs_shared_data_ref *)(iref + 1);
670 			num_refs = btrfs_shared_data_ref_count(leaf, ref2);
671 		}
672 	} else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
673 		ref1 = btrfs_item_ptr(leaf, path->slots[0],
674 				      struct btrfs_extent_data_ref);
675 		num_refs = btrfs_extent_data_ref_count(leaf, ref1);
676 	} else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
677 		ref2 = btrfs_item_ptr(leaf, path->slots[0],
678 				      struct btrfs_shared_data_ref);
679 		num_refs = btrfs_shared_data_ref_count(leaf, ref2);
680 	} else {
681 		WARN_ON(1);
682 	}
683 	return num_refs;
684 }
685 
686 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
687 					  struct btrfs_path *path,
688 					  u64 bytenr, u64 parent,
689 					  u64 root_objectid)
690 {
691 	struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
692 	struct btrfs_key key;
693 	int ret;
694 
695 	if (unlikely(!root)) {
696 		btrfs_err(trans->fs_info,
697 			  "missing extent root for extent at bytenr %llu", bytenr);
698 		return -EUCLEAN;
699 	}
700 
701 	key.objectid = bytenr;
702 	if (parent) {
703 		key.type = BTRFS_SHARED_BLOCK_REF_KEY;
704 		key.offset = parent;
705 	} else {
706 		key.type = BTRFS_TREE_BLOCK_REF_KEY;
707 		key.offset = root_objectid;
708 	}
709 
710 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
711 	if (ret > 0)
712 		ret = -ENOENT;
713 	return ret;
714 }
715 
716 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
717 					  struct btrfs_path *path,
718 					  const struct btrfs_delayed_ref_node *node,
719 					  u64 bytenr)
720 {
721 	struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
722 	struct btrfs_key key;
723 	int ret;
724 
725 	if (unlikely(!root)) {
726 		btrfs_err(trans->fs_info,
727 			  "missing extent root for extent at bytenr %llu", bytenr);
728 		return -EUCLEAN;
729 	}
730 
731 	key.objectid = bytenr;
732 	if (node->parent) {
733 		key.type = BTRFS_SHARED_BLOCK_REF_KEY;
734 		key.offset = node->parent;
735 	} else {
736 		key.type = BTRFS_TREE_BLOCK_REF_KEY;
737 		key.offset = node->ref_root;
738 	}
739 
740 	ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
741 	btrfs_release_path(path);
742 	return ret;
743 }
744 
745 static inline int extent_ref_type(u64 parent, u64 owner)
746 {
747 	int type;
748 	if (owner < BTRFS_FIRST_FREE_OBJECTID) {
749 		if (parent > 0)
750 			type = BTRFS_SHARED_BLOCK_REF_KEY;
751 		else
752 			type = BTRFS_TREE_BLOCK_REF_KEY;
753 	} else {
754 		if (parent > 0)
755 			type = BTRFS_SHARED_DATA_REF_KEY;
756 		else
757 			type = BTRFS_EXTENT_DATA_REF_KEY;
758 	}
759 	return type;
760 }
761 
762 static int find_next_key(const struct btrfs_path *path, int level,
763 			 struct btrfs_key *key)
764 
765 {
766 	for (; level < BTRFS_MAX_LEVEL; level++) {
767 		if (!path->nodes[level])
768 			break;
769 		if (path->slots[level] + 1 >=
770 		    btrfs_header_nritems(path->nodes[level]))
771 			continue;
772 		if (level == 0)
773 			btrfs_item_key_to_cpu(path->nodes[level], key,
774 					      path->slots[level] + 1);
775 		else
776 			btrfs_node_key_to_cpu(path->nodes[level], key,
777 					      path->slots[level] + 1);
778 		return 0;
779 	}
780 	return 1;
781 }
782 
783 /*
784  * look for inline back ref. if back ref is found, *ref_ret is set
785  * to the address of inline back ref, and 0 is returned.
786  *
787  * if back ref isn't found, *ref_ret is set to the address where it
788  * should be inserted, and -ENOENT is returned.
789  *
790  * if insert is true and there are too many inline back refs, the path
791  * points to the extent item, and -EAGAIN is returned.
792  *
793  * NOTE: inline back refs are ordered in the same way that back ref
794  *	 items in the tree are ordered.
795  */
796 static noinline_for_stack
797 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
798 				 struct btrfs_path *path,
799 				 struct btrfs_extent_inline_ref **ref_ret,
800 				 u64 bytenr, u64 num_bytes,
801 				 u64 parent, u64 root_objectid,
802 				 u64 owner, u64 offset, int insert)
803 {
804 	struct btrfs_fs_info *fs_info = trans->fs_info;
805 	struct btrfs_root *root = btrfs_extent_root(fs_info, bytenr);
806 	struct btrfs_key key;
807 	struct extent_buffer *leaf;
808 	struct btrfs_extent_item *ei;
809 	struct btrfs_extent_inline_ref *iref;
810 	u64 flags;
811 	u64 item_size;
812 	unsigned long ptr;
813 	unsigned long end;
814 	int extra_size;
815 	int type;
816 	int want;
817 	int ret;
818 	bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
819 	int needed;
820 
821 	if (unlikely(!root)) {
822 		btrfs_err(fs_info,
823 			  "missing extent root for extent at bytenr %llu", bytenr);
824 		return -EUCLEAN;
825 	}
826 
827 	key.objectid = bytenr;
828 	key.type = BTRFS_EXTENT_ITEM_KEY;
829 	key.offset = num_bytes;
830 
831 	want = extent_ref_type(parent, owner);
832 	if (insert) {
833 		extra_size = btrfs_extent_inline_ref_size(want);
834 		path->search_for_extension = true;
835 	} else
836 		extra_size = -1;
837 
838 	/*
839 	 * Owner is our level, so we can just add one to get the level for the
840 	 * block we are interested in.
841 	 */
842 	if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
843 		key.type = BTRFS_METADATA_ITEM_KEY;
844 		key.offset = owner;
845 	}
846 
847 again:
848 	ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
849 	if (ret < 0)
850 		goto out;
851 
852 	/*
853 	 * We may be a newly converted file system which still has the old fat
854 	 * extent entries for metadata, so try and see if we have one of those.
855 	 */
856 	if (ret > 0 && skinny_metadata) {
857 		skinny_metadata = false;
858 		if (path->slots[0]) {
859 			path->slots[0]--;
860 			btrfs_item_key_to_cpu(path->nodes[0], &key,
861 					      path->slots[0]);
862 			if (key.objectid == bytenr &&
863 			    key.type == BTRFS_EXTENT_ITEM_KEY &&
864 			    key.offset == num_bytes)
865 				ret = 0;
866 		}
867 		if (ret) {
868 			key.objectid = bytenr;
869 			key.type = BTRFS_EXTENT_ITEM_KEY;
870 			key.offset = num_bytes;
871 			btrfs_release_path(path);
872 			goto again;
873 		}
874 	}
875 
876 	if (ret && !insert) {
877 		ret = -ENOENT;
878 		goto out;
879 	} else if (WARN_ON(ret)) {
880 		btrfs_print_leaf(path->nodes[0]);
881 		btrfs_err(fs_info,
882 "extent item not found for insert, bytenr %llu num_bytes %llu parent %llu root_objectid %llu owner %llu offset %llu",
883 			  bytenr, num_bytes, parent, root_objectid, owner,
884 			  offset);
885 		ret = -EUCLEAN;
886 		goto out;
887 	}
888 
889 	leaf = path->nodes[0];
890 	item_size = btrfs_item_size(leaf, path->slots[0]);
891 	if (unlikely(item_size < sizeof(*ei))) {
892 		ret = -EUCLEAN;
893 		btrfs_err(fs_info,
894 			  "unexpected extent item size, has %llu expect >= %zu",
895 			  item_size, sizeof(*ei));
896 		btrfs_abort_transaction(trans, ret);
897 		goto out;
898 	}
899 
900 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
901 	flags = btrfs_extent_flags(leaf, ei);
902 
903 	ptr = (unsigned long)(ei + 1);
904 	end = (unsigned long)ei + item_size;
905 
906 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
907 		ptr += sizeof(struct btrfs_tree_block_info);
908 		BUG_ON(ptr > end);
909 	}
910 
911 	if (owner >= BTRFS_FIRST_FREE_OBJECTID)
912 		needed = BTRFS_REF_TYPE_DATA;
913 	else
914 		needed = BTRFS_REF_TYPE_BLOCK;
915 
916 	ret = -ENOENT;
917 	while (ptr < end) {
918 		iref = (struct btrfs_extent_inline_ref *)ptr;
919 		type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
920 		if (type == BTRFS_EXTENT_OWNER_REF_KEY) {
921 			ASSERT(btrfs_fs_incompat(fs_info, SIMPLE_QUOTA));
922 			ptr += btrfs_extent_inline_ref_size(type);
923 			continue;
924 		}
925 		if (unlikely(type == BTRFS_REF_TYPE_INVALID)) {
926 			ret = -EUCLEAN;
927 			goto out;
928 		}
929 
930 		if (want < type)
931 			break;
932 		if (want > type) {
933 			ptr += btrfs_extent_inline_ref_size(type);
934 			continue;
935 		}
936 
937 		if (type == BTRFS_EXTENT_DATA_REF_KEY) {
938 			struct btrfs_extent_data_ref *dref;
939 			dref = (struct btrfs_extent_data_ref *)(&iref->offset);
940 			if (match_extent_data_ref(leaf, dref, root_objectid,
941 						  owner, offset)) {
942 				ret = 0;
943 				break;
944 			}
945 			if (hash_extent_data_ref_item(leaf, dref) <
946 			    hash_extent_data_ref(root_objectid, owner, offset))
947 				break;
948 		} else {
949 			u64 ref_offset;
950 			ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
951 			if (parent > 0) {
952 				if (parent == ref_offset) {
953 					ret = 0;
954 					break;
955 				}
956 				if (ref_offset < parent)
957 					break;
958 			} else {
959 				if (root_objectid == ref_offset) {
960 					ret = 0;
961 					break;
962 				}
963 				if (ref_offset < root_objectid)
964 					break;
965 			}
966 		}
967 		ptr += btrfs_extent_inline_ref_size(type);
968 	}
969 
970 	if (unlikely(ptr > end)) {
971 		ret = -EUCLEAN;
972 		btrfs_print_leaf(path->nodes[0]);
973 		btrfs_crit(fs_info,
974 "overrun extent record at slot %d while looking for inline extent for root %llu owner %llu offset %llu parent %llu",
975 			   path->slots[0], root_objectid, owner, offset, parent);
976 		goto out;
977 	}
978 
979 	if (ret == -ENOENT && insert) {
980 		if (item_size + extra_size >=
981 		    BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
982 			ret = -EAGAIN;
983 			goto out;
984 		}
985 
986 		if (path->slots[0] + 1 < btrfs_header_nritems(path->nodes[0])) {
987 			struct btrfs_key tmp_key;
988 
989 			btrfs_item_key_to_cpu(path->nodes[0], &tmp_key, path->slots[0] + 1);
990 			if (tmp_key.objectid == bytenr &&
991 			    tmp_key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
992 				ret = -EAGAIN;
993 				goto out;
994 			}
995 			goto out_no_entry;
996 		}
997 
998 		if (!path->keep_locks) {
999 			btrfs_release_path(path);
1000 			path->keep_locks = true;
1001 			goto again;
1002 		}
1003 
1004 		/*
1005 		 * To add new inline back ref, we have to make sure
1006 		 * there is no corresponding back ref item.
1007 		 * For simplicity, we just do not add new inline back
1008 		 * ref if there is any kind of item for this block
1009 		 */
1010 		if (find_next_key(path, 0, &key) == 0 &&
1011 		    key.objectid == bytenr &&
1012 		    key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1013 			ret = -EAGAIN;
1014 			goto out;
1015 		}
1016 	}
1017 out_no_entry:
1018 	*ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1019 out:
1020 	if (path->keep_locks) {
1021 		path->keep_locks = false;
1022 		btrfs_unlock_up_safe(path, 1);
1023 	}
1024 	if (insert)
1025 		path->search_for_extension = false;
1026 	return ret;
1027 }
1028 
1029 /*
1030  * helper to add new inline back ref
1031  */
1032 static noinline_for_stack
1033 void setup_inline_extent_backref(struct btrfs_trans_handle *trans,
1034 				 struct btrfs_path *path,
1035 				 struct btrfs_extent_inline_ref *iref,
1036 				 u64 parent, u64 root_objectid,
1037 				 u64 owner, u64 offset, int refs_to_add,
1038 				 struct btrfs_delayed_extent_op *extent_op)
1039 {
1040 	struct extent_buffer *leaf;
1041 	struct btrfs_extent_item *ei;
1042 	unsigned long ptr;
1043 	unsigned long end;
1044 	unsigned long item_offset;
1045 	u64 refs;
1046 	int size;
1047 	int type;
1048 
1049 	leaf = path->nodes[0];
1050 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1051 	item_offset = (unsigned long)iref - (unsigned long)ei;
1052 
1053 	type = extent_ref_type(parent, owner);
1054 	size = btrfs_extent_inline_ref_size(type);
1055 
1056 	btrfs_extend_item(trans, path, size);
1057 
1058 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1059 	refs = btrfs_extent_refs(leaf, ei);
1060 	refs += refs_to_add;
1061 	btrfs_set_extent_refs(leaf, ei, refs);
1062 	if (extent_op)
1063 		__run_delayed_extent_op(extent_op, leaf, ei);
1064 
1065 	ptr = (unsigned long)ei + item_offset;
1066 	end = (unsigned long)ei + btrfs_item_size(leaf, path->slots[0]);
1067 	if (ptr < end - size)
1068 		memmove_extent_buffer(leaf, ptr + size, ptr,
1069 				      end - size - ptr);
1070 
1071 	iref = (struct btrfs_extent_inline_ref *)ptr;
1072 	btrfs_set_extent_inline_ref_type(leaf, iref, type);
1073 	if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1074 		struct btrfs_extent_data_ref *dref;
1075 		dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1076 		btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1077 		btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1078 		btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1079 		btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1080 	} else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1081 		struct btrfs_shared_data_ref *sref;
1082 		sref = (struct btrfs_shared_data_ref *)(iref + 1);
1083 		btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1084 		btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1085 	} else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1086 		btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1087 	} else {
1088 		btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1089 	}
1090 }
1091 
1092 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1093 				 struct btrfs_path *path,
1094 				 struct btrfs_extent_inline_ref **ref_ret,
1095 				 u64 bytenr, u64 num_bytes, u64 parent,
1096 				 u64 root_objectid, u64 owner, u64 offset)
1097 {
1098 	int ret;
1099 
1100 	ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1101 					   num_bytes, parent, root_objectid,
1102 					   owner, offset, 0);
1103 	if (ret != -ENOENT)
1104 		return ret;
1105 
1106 	btrfs_release_path(path);
1107 	*ref_ret = NULL;
1108 
1109 	if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1110 		ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1111 					    root_objectid);
1112 	} else {
1113 		ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1114 					     root_objectid, owner, offset);
1115 	}
1116 	return ret;
1117 }
1118 
1119 /*
1120  * helper to update/remove inline back ref
1121  */
1122 static noinline_for_stack int update_inline_extent_backref(
1123 				  struct btrfs_trans_handle *trans,
1124 				  struct btrfs_path *path,
1125 				  struct btrfs_extent_inline_ref *iref,
1126 				  int refs_to_mod,
1127 				  struct btrfs_delayed_extent_op *extent_op)
1128 {
1129 	struct extent_buffer *leaf = path->nodes[0];
1130 	struct btrfs_fs_info *fs_info = leaf->fs_info;
1131 	struct btrfs_extent_item *ei;
1132 	struct btrfs_extent_data_ref *dref = NULL;
1133 	struct btrfs_shared_data_ref *sref = NULL;
1134 	unsigned long ptr;
1135 	unsigned long end;
1136 	u32 item_size;
1137 	int size;
1138 	int type;
1139 	u64 refs;
1140 
1141 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1142 	refs = btrfs_extent_refs(leaf, ei);
1143 	if (unlikely(refs_to_mod < 0 && refs + refs_to_mod <= 0)) {
1144 		struct btrfs_key key;
1145 		u32 extent_size;
1146 
1147 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1148 		if (key.type == BTRFS_METADATA_ITEM_KEY)
1149 			extent_size = fs_info->nodesize;
1150 		else
1151 			extent_size = key.offset;
1152 		btrfs_print_leaf(leaf);
1153 		btrfs_err(fs_info,
1154 	"invalid refs_to_mod for extent %llu num_bytes %u, has %d expect >= -%llu",
1155 			  key.objectid, extent_size, refs_to_mod, refs);
1156 		return -EUCLEAN;
1157 	}
1158 	refs += refs_to_mod;
1159 	btrfs_set_extent_refs(leaf, ei, refs);
1160 	if (extent_op)
1161 		__run_delayed_extent_op(extent_op, leaf, ei);
1162 
1163 	type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1164 	/*
1165 	 * Function btrfs_get_extent_inline_ref_type() has already printed
1166 	 * error messages.
1167 	 */
1168 	if (unlikely(type == BTRFS_REF_TYPE_INVALID))
1169 		return -EUCLEAN;
1170 
1171 	if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1172 		dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1173 		refs = btrfs_extent_data_ref_count(leaf, dref);
1174 	} else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1175 		sref = (struct btrfs_shared_data_ref *)(iref + 1);
1176 		refs = btrfs_shared_data_ref_count(leaf, sref);
1177 	} else {
1178 		refs = 1;
1179 		/*
1180 		 * For tree blocks we can only drop one ref for it, and tree
1181 		 * blocks should not have refs > 1.
1182 		 *
1183 		 * Furthermore if we're inserting a new inline backref, we
1184 		 * won't reach this path either. That would be
1185 		 * setup_inline_extent_backref().
1186 		 */
1187 		if (unlikely(refs_to_mod != -1)) {
1188 			struct btrfs_key key;
1189 
1190 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1191 
1192 			btrfs_print_leaf(leaf);
1193 			btrfs_err(fs_info,
1194 			"invalid refs_to_mod for tree block %llu, has %d expect -1",
1195 				  key.objectid, refs_to_mod);
1196 			return -EUCLEAN;
1197 		}
1198 	}
1199 
1200 	if (unlikely(refs_to_mod < 0 && refs < -refs_to_mod)) {
1201 		struct btrfs_key key;
1202 		u32 extent_size;
1203 
1204 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1205 		if (key.type == BTRFS_METADATA_ITEM_KEY)
1206 			extent_size = fs_info->nodesize;
1207 		else
1208 			extent_size = key.offset;
1209 		btrfs_print_leaf(leaf);
1210 		btrfs_err(fs_info,
1211 "invalid refs_to_mod for backref entry, iref %lu extent %llu num_bytes %u, has %d expect >= -%llu",
1212 			  (unsigned long)iref, key.objectid, extent_size,
1213 			  refs_to_mod, refs);
1214 		return -EUCLEAN;
1215 	}
1216 	refs += refs_to_mod;
1217 
1218 	if (refs > 0) {
1219 		if (type == BTRFS_EXTENT_DATA_REF_KEY)
1220 			btrfs_set_extent_data_ref_count(leaf, dref, refs);
1221 		else
1222 			btrfs_set_shared_data_ref_count(leaf, sref, refs);
1223 	} else {
1224 		size =  btrfs_extent_inline_ref_size(type);
1225 		item_size = btrfs_item_size(leaf, path->slots[0]);
1226 		ptr = (unsigned long)iref;
1227 		end = (unsigned long)ei + item_size;
1228 		if (ptr + size < end)
1229 			memmove_extent_buffer(leaf, ptr, ptr + size,
1230 					      end - ptr - size);
1231 		item_size -= size;
1232 		btrfs_truncate_item(trans, path, item_size, 1);
1233 	}
1234 	return 0;
1235 }
1236 
1237 static noinline_for_stack
1238 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1239 				 struct btrfs_path *path,
1240 				 u64 bytenr, u64 num_bytes, u64 parent,
1241 				 u64 root_objectid, u64 owner,
1242 				 u64 offset, int refs_to_add,
1243 				 struct btrfs_delayed_extent_op *extent_op)
1244 {
1245 	struct btrfs_extent_inline_ref *iref;
1246 	int ret;
1247 
1248 	ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1249 					   num_bytes, parent, root_objectid,
1250 					   owner, offset, 1);
1251 	if (ret == 0) {
1252 		/*
1253 		 * We're adding refs to a tree block we already own, this
1254 		 * should not happen at all.
1255 		 */
1256 		if (unlikely(owner < BTRFS_FIRST_FREE_OBJECTID)) {
1257 			btrfs_print_leaf(path->nodes[0]);
1258 			btrfs_crit(trans->fs_info,
1259 "adding refs to an existing tree ref, bytenr %llu num_bytes %llu root_objectid %llu slot %u",
1260 				   bytenr, num_bytes, root_objectid, path->slots[0]);
1261 			return -EUCLEAN;
1262 		}
1263 		ret = update_inline_extent_backref(trans, path, iref,
1264 						   refs_to_add, extent_op);
1265 	} else if (ret == -ENOENT) {
1266 		setup_inline_extent_backref(trans, path, iref, parent,
1267 					    root_objectid, owner, offset,
1268 					    refs_to_add, extent_op);
1269 		ret = 0;
1270 	}
1271 	return ret;
1272 }
1273 
1274 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1275 				 struct btrfs_root *root,
1276 				 struct btrfs_path *path,
1277 				 struct btrfs_extent_inline_ref *iref,
1278 				 int refs_to_drop, int is_data)
1279 {
1280 	int ret = 0;
1281 
1282 	BUG_ON(!is_data && refs_to_drop != 1);
1283 	if (iref)
1284 		ret = update_inline_extent_backref(trans, path, iref,
1285 						   -refs_to_drop, NULL);
1286 	else if (is_data)
1287 		ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
1288 	else
1289 		ret = btrfs_del_item(trans, root, path);
1290 	return ret;
1291 }
1292 
1293 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1294 			       u64 *discarded_bytes)
1295 {
1296 	int j, ret = 0;
1297 	u64 bytes_left, end;
1298 	u64 aligned_start = ALIGN(start, SECTOR_SIZE);
1299 
1300 	/* Adjust the range to be aligned to 512B sectors if necessary. */
1301 	if (start != aligned_start) {
1302 		len -= aligned_start - start;
1303 		len = round_down(len, SECTOR_SIZE);
1304 		start = aligned_start;
1305 	}
1306 
1307 	*discarded_bytes = 0;
1308 
1309 	if (!len)
1310 		return 0;
1311 
1312 	end = start + len;
1313 	bytes_left = len;
1314 
1315 	/* Skip any superblocks on this device. */
1316 	for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1317 		u64 sb_start = btrfs_sb_offset(j);
1318 		u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1319 		u64 size = sb_start - start;
1320 
1321 		if (!in_range(sb_start, start, bytes_left) &&
1322 		    !in_range(sb_end, start, bytes_left) &&
1323 		    !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1324 			continue;
1325 
1326 		/*
1327 		 * Superblock spans beginning of range.  Adjust start and
1328 		 * try again.
1329 		 */
1330 		if (sb_start <= start) {
1331 			start += sb_end - start;
1332 			if (start > end) {
1333 				bytes_left = 0;
1334 				break;
1335 			}
1336 			bytes_left = end - start;
1337 			continue;
1338 		}
1339 
1340 		if (size) {
1341 			ret = blkdev_issue_discard(bdev, start >> SECTOR_SHIFT,
1342 						   size >> SECTOR_SHIFT,
1343 						   GFP_NOFS);
1344 			if (!ret)
1345 				*discarded_bytes += size;
1346 			else if (ret != -EOPNOTSUPP)
1347 				return ret;
1348 		}
1349 
1350 		start = sb_end;
1351 		if (start > end) {
1352 			bytes_left = 0;
1353 			break;
1354 		}
1355 		bytes_left = end - start;
1356 	}
1357 
1358 	while (bytes_left) {
1359 		u64 bytes_to_discard = min(BTRFS_MAX_DISCARD_CHUNK_SIZE, bytes_left);
1360 
1361 		ret = blkdev_issue_discard(bdev, start >> SECTOR_SHIFT,
1362 					   bytes_to_discard >> SECTOR_SHIFT,
1363 					   GFP_NOFS);
1364 
1365 		if (ret) {
1366 			if (ret != -EOPNOTSUPP)
1367 				break;
1368 			continue;
1369 		}
1370 
1371 		start += bytes_to_discard;
1372 		bytes_left -= bytes_to_discard;
1373 		*discarded_bytes += bytes_to_discard;
1374 
1375 		if (btrfs_trim_interrupted()) {
1376 			ret = -ERESTARTSYS;
1377 			break;
1378 		}
1379 	}
1380 
1381 	return ret;
1382 }
1383 
1384 static int do_discard_extent(struct btrfs_discard_stripe *stripe, u64 *bytes)
1385 {
1386 	struct btrfs_device *dev = stripe->dev;
1387 	struct btrfs_fs_info *fs_info = dev->fs_info;
1388 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1389 	u64 phys = stripe->physical;
1390 	u64 len = stripe->length;
1391 	u64 discarded = 0;
1392 	int ret = 0;
1393 
1394 	/* Zone reset on a zoned filesystem */
1395 	if (btrfs_can_zone_reset(dev, phys, len)) {
1396 		u64 src_disc;
1397 
1398 		ret = btrfs_reset_device_zone(dev, phys, len, &discarded);
1399 		if (ret)
1400 			goto out;
1401 
1402 		if (!btrfs_dev_replace_is_ongoing(dev_replace) ||
1403 		    dev != dev_replace->srcdev)
1404 			goto out;
1405 
1406 		src_disc = discarded;
1407 
1408 		/* Send to replace target as well */
1409 		ret = btrfs_reset_device_zone(dev_replace->tgtdev, phys, len,
1410 					      &discarded);
1411 		discarded += src_disc;
1412 	} else if (bdev_max_discard_sectors(stripe->dev->bdev)) {
1413 		ret = btrfs_issue_discard(dev->bdev, phys, len, &discarded);
1414 	} else {
1415 		ret = 0;
1416 		*bytes = 0;
1417 	}
1418 
1419 out:
1420 	*bytes = discarded;
1421 	return ret;
1422 }
1423 
1424 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1425 			 u64 num_bytes, u64 *actual_bytes, bool do_remap)
1426 {
1427 	int ret = 0;
1428 	u64 discarded_bytes = 0;
1429 	u64 end = bytenr + num_bytes;
1430 	u64 cur = bytenr;
1431 
1432 	/*
1433 	 * Avoid races with device replace and make sure the devices in the
1434 	 * stripes don't go away while we are discarding.
1435 	 */
1436 	btrfs_bio_counter_inc_blocked(fs_info);
1437 	while (cur < end) {
1438 		struct btrfs_discard_stripe *stripes;
1439 		unsigned int num_stripes;
1440 		int i;
1441 
1442 		num_bytes = end - cur;
1443 		stripes = btrfs_map_discard(fs_info, cur, &num_bytes, &num_stripes,
1444 					    do_remap);
1445 		if (IS_ERR(stripes)) {
1446 			ret = PTR_ERR(stripes);
1447 			if (ret == -EOPNOTSUPP)
1448 				ret = 0;
1449 			break;
1450 		}
1451 
1452 		for (i = 0; i < num_stripes; i++) {
1453 			struct btrfs_discard_stripe *stripe = stripes + i;
1454 			u64 bytes;
1455 
1456 			if (!stripe->dev->bdev) {
1457 				ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1458 				continue;
1459 			}
1460 
1461 			if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
1462 					&stripe->dev->dev_state))
1463 				continue;
1464 
1465 			ret = do_discard_extent(stripe, &bytes);
1466 			if (ret) {
1467 				/*
1468 				 * Keep going if discard is not supported by the
1469 				 * device.
1470 				 */
1471 				if (ret != -EOPNOTSUPP)
1472 					break;
1473 				ret = 0;
1474 			} else {
1475 				discarded_bytes += bytes;
1476 			}
1477 		}
1478 		kfree(stripes);
1479 		if (ret)
1480 			break;
1481 		cur += num_bytes;
1482 	}
1483 	btrfs_bio_counter_dec(fs_info);
1484 	if (actual_bytes)
1485 		*actual_bytes = discarded_bytes;
1486 	return ret;
1487 }
1488 
1489 /* Can return -ENOMEM */
1490 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1491 			 struct btrfs_ref *generic_ref)
1492 {
1493 	struct btrfs_fs_info *fs_info = trans->fs_info;
1494 	int ret;
1495 
1496 	ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
1497 	       generic_ref->action);
1498 	BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
1499 	       generic_ref->ref_root == BTRFS_TREE_LOG_OBJECTID);
1500 
1501 	if (generic_ref->type == BTRFS_REF_METADATA)
1502 		ret = btrfs_add_delayed_tree_ref(trans, generic_ref, NULL);
1503 	else
1504 		ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0);
1505 
1506 	btrfs_ref_tree_mod(fs_info, generic_ref);
1507 
1508 	return ret;
1509 }
1510 
1511 /*
1512  * Insert backreference for a given extent.
1513  *
1514  * The counterpart is in __btrfs_free_extent(), with examples and more details
1515  * how it works.
1516  *
1517  * @trans:	    Handle of transaction
1518  *
1519  * @node:	    The delayed ref node used to get the bytenr/length for
1520  *		    extent whose references are incremented.
1521  *
1522  * @extent_op       Pointer to a structure, holding information necessary when
1523  *                  updating a tree block's flags
1524  *
1525  */
1526 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1527 				  const struct btrfs_delayed_ref_node *node,
1528 				  struct btrfs_delayed_extent_op *extent_op)
1529 {
1530 	BTRFS_PATH_AUTO_FREE(path);
1531 	struct extent_buffer *leaf;
1532 	struct btrfs_extent_item *item;
1533 	struct btrfs_key key;
1534 	u64 bytenr = node->bytenr;
1535 	u64 num_bytes = node->num_bytes;
1536 	u64 owner = btrfs_delayed_ref_owner(node);
1537 	u64 offset = btrfs_delayed_ref_offset(node);
1538 	u64 refs;
1539 	int refs_to_add = node->ref_mod;
1540 	int ret;
1541 
1542 	path = btrfs_alloc_path();
1543 	if (!path)
1544 		return -ENOMEM;
1545 
1546 	/* this will setup the path even if it fails to insert the back ref */
1547 	ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
1548 					   node->parent, node->ref_root, owner,
1549 					   offset, refs_to_add, extent_op);
1550 	if ((ret < 0 && ret != -EAGAIN) || !ret)
1551 		return ret;
1552 
1553 	/*
1554 	 * Ok we had -EAGAIN which means we didn't have space to insert and
1555 	 * inline extent ref, so just update the reference count and add a
1556 	 * normal backref.
1557 	 */
1558 	leaf = path->nodes[0];
1559 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1560 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1561 	refs = btrfs_extent_refs(leaf, item);
1562 	btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1563 	if (extent_op)
1564 		__run_delayed_extent_op(extent_op, leaf, item);
1565 
1566 	btrfs_release_path(path);
1567 
1568 	/* now insert the actual backref */
1569 	if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1570 		ret = insert_tree_block_ref(trans, path, node, bytenr);
1571 		if (ret)
1572 			btrfs_abort_transaction(trans, ret);
1573 	} else {
1574 		ret = insert_extent_data_ref(trans, path, node, bytenr);
1575 		if (ret)
1576 			btrfs_abort_transaction(trans, ret);
1577 	}
1578 
1579 	return ret;
1580 }
1581 
1582 static void free_head_ref_squota_rsv(struct btrfs_fs_info *fs_info,
1583 				     const struct btrfs_delayed_ref_head *href)
1584 {
1585 	u64 root = href->owning_root;
1586 
1587 	/*
1588 	 * Don't check must_insert_reserved, as this is called from contexts
1589 	 * where it has already been unset.
1590 	 */
1591 	if (btrfs_qgroup_mode(fs_info) != BTRFS_QGROUP_MODE_SIMPLE ||
1592 	    !href->is_data || !btrfs_is_fstree(root))
1593 		return;
1594 
1595 	btrfs_qgroup_free_refroot(fs_info, root, href->reserved_bytes,
1596 				  BTRFS_QGROUP_RSV_DATA);
1597 }
1598 
1599 static int drop_remap_tree_ref(struct btrfs_trans_handle *trans,
1600 			       const struct btrfs_delayed_ref_node *node)
1601 {
1602 	u64 bytenr = node->bytenr;
1603 	u64 num_bytes = node->num_bytes;
1604 	int ret;
1605 
1606 	ret = btrfs_add_to_free_space_tree(trans, bytenr, num_bytes);
1607 	if (unlikely(ret)) {
1608 		btrfs_abort_transaction(trans, ret);
1609 		return ret;
1610 	}
1611 
1612 	ret = btrfs_update_block_group(trans, bytenr, num_bytes, false);
1613 	if (unlikely(ret)) {
1614 		btrfs_abort_transaction(trans, ret);
1615 		return ret;
1616 	}
1617 
1618 	return 0;
1619 }
1620 
1621 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1622 				struct btrfs_delayed_ref_head *href,
1623 				const struct btrfs_delayed_ref_node *node,
1624 				struct btrfs_delayed_extent_op *extent_op,
1625 				bool insert_reserved)
1626 {
1627 	int ret = 0;
1628 	u64 parent = 0;
1629 	u64 flags = 0;
1630 
1631 	trace_run_delayed_data_ref(trans->fs_info, node);
1632 
1633 	if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1634 		parent = node->parent;
1635 
1636 	if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1637 		struct btrfs_key key;
1638 		struct btrfs_squota_delta delta = {
1639 			.root = href->owning_root,
1640 			.num_bytes = node->num_bytes,
1641 			.is_data = true,
1642 			.is_inc	= true,
1643 			.generation = trans->transid,
1644 		};
1645 		u64 owner = btrfs_delayed_ref_owner(node);
1646 		u64 offset = btrfs_delayed_ref_offset(node);
1647 
1648 		if (extent_op)
1649 			flags |= extent_op->flags_to_set;
1650 
1651 		key.objectid = node->bytenr;
1652 		key.type = BTRFS_EXTENT_ITEM_KEY;
1653 		key.offset = node->num_bytes;
1654 
1655 		ret = alloc_reserved_file_extent(trans, parent, node->ref_root,
1656 						 flags, owner, offset, &key,
1657 						 node->ref_mod,
1658 						 href->owning_root);
1659 		free_head_ref_squota_rsv(trans->fs_info, href);
1660 		if (!ret)
1661 			btrfs_record_squota_delta(trans->fs_info, &delta);
1662 	} else if (node->action == BTRFS_ADD_DELAYED_REF) {
1663 		ret = __btrfs_inc_extent_ref(trans, node, extent_op);
1664 	} else if (node->action == BTRFS_DROP_DELAYED_REF) {
1665 		ret = __btrfs_free_extent(trans, href, node, extent_op);
1666 	} else {
1667 		BUG();
1668 	}
1669 	return ret;
1670 }
1671 
1672 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1673 				    struct extent_buffer *leaf,
1674 				    struct btrfs_extent_item *ei)
1675 {
1676 	u64 flags = btrfs_extent_flags(leaf, ei);
1677 	if (extent_op->update_flags) {
1678 		flags |= extent_op->flags_to_set;
1679 		btrfs_set_extent_flags(leaf, ei, flags);
1680 	}
1681 
1682 	if (extent_op->update_key) {
1683 		struct btrfs_tree_block_info *bi;
1684 		BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1685 		bi = (struct btrfs_tree_block_info *)(ei + 1);
1686 		btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1687 	}
1688 }
1689 
1690 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1691 				 const struct btrfs_delayed_ref_head *head,
1692 				 struct btrfs_delayed_extent_op *extent_op)
1693 {
1694 	struct btrfs_fs_info *fs_info = trans->fs_info;
1695 	struct btrfs_root *root;
1696 	struct btrfs_key key;
1697 	BTRFS_PATH_AUTO_FREE(path);
1698 	struct btrfs_extent_item *ei;
1699 	struct extent_buffer *leaf;
1700 	u32 item_size;
1701 	int ret;
1702 	bool metadata = true;
1703 
1704 	if (TRANS_ABORTED(trans))
1705 		return 0;
1706 
1707 	if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1708 		metadata = false;
1709 
1710 	path = btrfs_alloc_path();
1711 	if (!path)
1712 		return -ENOMEM;
1713 
1714 	key.objectid = head->bytenr;
1715 
1716 	if (metadata) {
1717 		key.type = BTRFS_METADATA_ITEM_KEY;
1718 		key.offset = head->level;
1719 	} else {
1720 		key.type = BTRFS_EXTENT_ITEM_KEY;
1721 		key.offset = head->num_bytes;
1722 	}
1723 
1724 	root = btrfs_extent_root(fs_info, key.objectid);
1725 	if (unlikely(!root)) {
1726 		btrfs_err(fs_info,
1727 			  "missing extent root for extent at bytenr %llu",
1728 			  key.objectid);
1729 		return -EUCLEAN;
1730 	}
1731 again:
1732 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1733 	if (ret < 0) {
1734 		return ret;
1735 	} else if (ret > 0) {
1736 		if (metadata) {
1737 			if (path->slots[0] > 0) {
1738 				path->slots[0]--;
1739 				btrfs_item_key_to_cpu(path->nodes[0], &key,
1740 						      path->slots[0]);
1741 				if (key.objectid == head->bytenr &&
1742 				    key.type == BTRFS_EXTENT_ITEM_KEY &&
1743 				    key.offset == head->num_bytes)
1744 					ret = 0;
1745 			}
1746 			if (ret > 0) {
1747 				btrfs_release_path(path);
1748 				metadata = false;
1749 
1750 				key.objectid = head->bytenr;
1751 				key.type = BTRFS_EXTENT_ITEM_KEY;
1752 				key.offset = head->num_bytes;
1753 				goto again;
1754 			}
1755 		} else {
1756 			ret = -EUCLEAN;
1757 			btrfs_err(fs_info,
1758 		  "missing extent item for extent %llu num_bytes %llu level %d",
1759 				  head->bytenr, head->num_bytes, head->level);
1760 			return ret;
1761 		}
1762 	}
1763 
1764 	leaf = path->nodes[0];
1765 	item_size = btrfs_item_size(leaf, path->slots[0]);
1766 
1767 	if (unlikely(item_size < sizeof(*ei))) {
1768 		ret = -EUCLEAN;
1769 		btrfs_err(fs_info,
1770 			  "unexpected extent item size, has %u expect >= %zu",
1771 			  item_size, sizeof(*ei));
1772 		btrfs_abort_transaction(trans, ret);
1773 		return ret;
1774 	}
1775 
1776 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1777 	__run_delayed_extent_op(extent_op, leaf, ei);
1778 
1779 	return ret;
1780 }
1781 
1782 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
1783 				struct btrfs_delayed_ref_head *href,
1784 				const struct btrfs_delayed_ref_node *node,
1785 				struct btrfs_delayed_extent_op *extent_op,
1786 				bool insert_reserved)
1787 {
1788 	int ret = 0;
1789 	struct btrfs_fs_info *fs_info = trans->fs_info;
1790 	u64 parent = 0;
1791 	u64 ref_root = 0;
1792 
1793 	trace_run_delayed_tree_ref(trans->fs_info, node);
1794 
1795 	if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1796 		parent = node->parent;
1797 	ref_root = node->ref_root;
1798 
1799 	if (unlikely(node->ref_mod != 1)) {
1800 		btrfs_err(trans->fs_info,
1801 	"btree block %llu has %d references rather than 1: action %d ref_root %llu parent %llu",
1802 			  node->bytenr, node->ref_mod, node->action, ref_root,
1803 			  parent);
1804 		return -EUCLEAN;
1805 	}
1806 	if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1807 		struct btrfs_squota_delta delta = {
1808 			.root = href->owning_root,
1809 			.num_bytes = fs_info->nodesize,
1810 			.is_data = false,
1811 			.is_inc = true,
1812 			.generation = trans->transid,
1813 		};
1814 
1815 		ret = alloc_reserved_tree_block(trans, node, extent_op);
1816 		if (!ret)
1817 			btrfs_record_squota_delta(fs_info, &delta);
1818 	} else if (node->action == BTRFS_ADD_DELAYED_REF) {
1819 		ret = __btrfs_inc_extent_ref(trans, node, extent_op);
1820 	} else if (node->action == BTRFS_DROP_DELAYED_REF) {
1821 		if (node->ref_root == BTRFS_REMAP_TREE_OBJECTID)
1822 			ret = drop_remap_tree_ref(trans, node);
1823 		else
1824 			ret = __btrfs_free_extent(trans, href, node, extent_op);
1825 	} else {
1826 		BUG();
1827 	}
1828 	return ret;
1829 }
1830 
1831 /* helper function to actually process a single delayed ref entry */
1832 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
1833 			       struct btrfs_delayed_ref_head *href,
1834 			       const struct btrfs_delayed_ref_node *node,
1835 			       struct btrfs_delayed_extent_op *extent_op,
1836 			       bool insert_reserved)
1837 {
1838 	struct btrfs_fs_info *fs_info = trans->fs_info;
1839 	int ret = 0;
1840 
1841 	if (TRANS_ABORTED(trans)) {
1842 		if (insert_reserved) {
1843 			btrfs_pin_extent(trans, node->bytenr, node->num_bytes);
1844 			free_head_ref_squota_rsv(fs_info, href);
1845 		}
1846 		return 0;
1847 	}
1848 
1849 	if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
1850 	    node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
1851 		ret = run_delayed_tree_ref(trans, href, node, extent_op,
1852 					   insert_reserved);
1853 	} else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
1854 		   node->type == BTRFS_SHARED_DATA_REF_KEY) {
1855 		ret = run_delayed_data_ref(trans, href, node, extent_op,
1856 					   insert_reserved);
1857 	} else if (unlikely(node->type != BTRFS_EXTENT_OWNER_REF_KEY)) {
1858 		ret = -EUCLEAN;
1859 		btrfs_err(fs_info, "unexpected delayed ref node type: %u", node->type);
1860 	}
1861 
1862 	if (unlikely(ret)) {
1863 		if (insert_reserved)
1864 			btrfs_pin_extent(trans, node->bytenr, node->num_bytes);
1865 		btrfs_err(fs_info,
1866 "failed to run delayed ref for logical %llu num_bytes %llu type %u action %u ref_mod %d: %d",
1867 			  node->bytenr, node->num_bytes, node->type,
1868 			  node->action, node->ref_mod, ret);
1869 	}
1870 
1871 	return ret;
1872 }
1873 
1874 static struct btrfs_delayed_extent_op *cleanup_extent_op(
1875 				struct btrfs_delayed_ref_head *head)
1876 {
1877 	struct btrfs_delayed_extent_op *extent_op = head->extent_op;
1878 
1879 	if (!extent_op)
1880 		return NULL;
1881 
1882 	if (head->must_insert_reserved) {
1883 		head->extent_op = NULL;
1884 		btrfs_free_delayed_extent_op(extent_op);
1885 		return NULL;
1886 	}
1887 	return extent_op;
1888 }
1889 
1890 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
1891 				     struct btrfs_delayed_ref_head *head)
1892 {
1893 	struct btrfs_delayed_extent_op *extent_op;
1894 	int ret;
1895 
1896 	extent_op = cleanup_extent_op(head);
1897 	if (!extent_op)
1898 		return 0;
1899 	head->extent_op = NULL;
1900 	spin_unlock(&head->lock);
1901 	ret = run_delayed_extent_op(trans, head, extent_op);
1902 	btrfs_free_delayed_extent_op(extent_op);
1903 	return ret ? ret : 1;
1904 }
1905 
1906 u64 btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
1907 				  struct btrfs_delayed_ref_root *delayed_refs,
1908 				  struct btrfs_delayed_ref_head *head)
1909 {
1910 	u64 ret = 0;
1911 
1912 	/*
1913 	 * We had csum deletions accounted for in our delayed refs rsv, we need
1914 	 * to drop the csum leaves for this update from our delayed_refs_rsv.
1915 	 */
1916 	if (head->total_ref_mod < 0 && head->is_data) {
1917 		int nr_csums;
1918 
1919 		spin_lock(&delayed_refs->lock);
1920 		delayed_refs->pending_csums -= head->num_bytes;
1921 		spin_unlock(&delayed_refs->lock);
1922 		nr_csums = btrfs_csum_bytes_to_leaves(fs_info, head->num_bytes);
1923 
1924 		btrfs_delayed_refs_rsv_release(fs_info, 0, nr_csums);
1925 
1926 		ret = btrfs_calc_delayed_ref_csum_bytes(fs_info, nr_csums);
1927 	}
1928 	/* must_insert_reserved can be set only if we didn't run the head ref. */
1929 	if (head->must_insert_reserved)
1930 		free_head_ref_squota_rsv(fs_info, head);
1931 
1932 	return ret;
1933 }
1934 
1935 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
1936 			    struct btrfs_delayed_ref_head *head,
1937 			    u64 *bytes_released)
1938 {
1939 
1940 	struct btrfs_fs_info *fs_info = trans->fs_info;
1941 	struct btrfs_delayed_ref_root *delayed_refs;
1942 	int ret;
1943 
1944 	delayed_refs = &trans->transaction->delayed_refs;
1945 
1946 	ret = run_and_cleanup_extent_op(trans, head);
1947 	if (ret < 0) {
1948 		btrfs_unselect_ref_head(delayed_refs, head);
1949 		btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
1950 		return ret;
1951 	} else if (ret) {
1952 		return ret;
1953 	}
1954 
1955 	/*
1956 	 * Need to drop our head ref lock and re-acquire the delayed ref lock
1957 	 * and then re-check to make sure nobody got added.
1958 	 */
1959 	spin_unlock(&head->lock);
1960 	spin_lock(&delayed_refs->lock);
1961 	spin_lock(&head->lock);
1962 	if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
1963 		spin_unlock(&head->lock);
1964 		spin_unlock(&delayed_refs->lock);
1965 		return 1;
1966 	}
1967 	btrfs_delete_ref_head(fs_info, delayed_refs, head);
1968 	spin_unlock(&head->lock);
1969 	spin_unlock(&delayed_refs->lock);
1970 
1971 	if (head->must_insert_reserved) {
1972 		btrfs_pin_extent(trans, head->bytenr, head->num_bytes);
1973 		if (head->is_data) {
1974 			struct btrfs_root *csum_root;
1975 
1976 			csum_root = btrfs_csum_root(fs_info, head->bytenr);
1977 			if (unlikely(!csum_root)) {
1978 				btrfs_err(fs_info,
1979 					  "missing csum root for extent at bytenr %llu",
1980 					  head->bytenr);
1981 				ret = -EUCLEAN;
1982 			} else {
1983 				ret = btrfs_del_csums(trans, csum_root, head->bytenr,
1984 						      head->num_bytes);
1985 			}
1986 		}
1987 	}
1988 
1989 	*bytes_released += btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
1990 
1991 	trace_run_delayed_ref_head(fs_info, head, 0);
1992 	btrfs_delayed_ref_unlock(head);
1993 	btrfs_put_delayed_ref_head(head);
1994 	return ret;
1995 }
1996 
1997 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
1998 					   struct btrfs_delayed_ref_head *locked_ref,
1999 					   u64 *bytes_released)
2000 {
2001 	struct btrfs_fs_info *fs_info = trans->fs_info;
2002 	struct btrfs_delayed_ref_root *delayed_refs;
2003 	struct btrfs_delayed_extent_op *extent_op;
2004 	struct btrfs_delayed_ref_node *ref;
2005 	bool must_insert_reserved;
2006 	int ret;
2007 
2008 	delayed_refs = &trans->transaction->delayed_refs;
2009 
2010 	lockdep_assert_held(&locked_ref->mutex);
2011 	lockdep_assert_held(&locked_ref->lock);
2012 
2013 	while ((ref = btrfs_select_delayed_ref(locked_ref))) {
2014 		if (ref->seq &&
2015 		    btrfs_check_delayed_seq(fs_info, ref->seq)) {
2016 			spin_unlock(&locked_ref->lock);
2017 			btrfs_unselect_ref_head(delayed_refs, locked_ref);
2018 			return -EAGAIN;
2019 		}
2020 
2021 		rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
2022 		RB_CLEAR_NODE(&ref->ref_node);
2023 		if (!list_empty(&ref->add_list))
2024 			list_del(&ref->add_list);
2025 		/*
2026 		 * When we play the delayed ref, also correct the ref_mod on
2027 		 * head
2028 		 */
2029 		switch (ref->action) {
2030 		case BTRFS_ADD_DELAYED_REF:
2031 		case BTRFS_ADD_DELAYED_EXTENT:
2032 			locked_ref->ref_mod -= ref->ref_mod;
2033 			break;
2034 		case BTRFS_DROP_DELAYED_REF:
2035 			locked_ref->ref_mod += ref->ref_mod;
2036 			break;
2037 		default:
2038 			WARN_ON(1);
2039 		}
2040 
2041 		/*
2042 		 * Record the must_insert_reserved flag before we drop the
2043 		 * spin lock.
2044 		 */
2045 		must_insert_reserved = locked_ref->must_insert_reserved;
2046 		/*
2047 		 * Unsetting this on the head ref relinquishes ownership of
2048 		 * the rsv_bytes, so it is critical that every possible code
2049 		 * path from here forward frees all reserves including qgroup
2050 		 * reserve.
2051 		 */
2052 		locked_ref->must_insert_reserved = false;
2053 
2054 		extent_op = locked_ref->extent_op;
2055 		locked_ref->extent_op = NULL;
2056 		spin_unlock(&locked_ref->lock);
2057 
2058 		ret = run_one_delayed_ref(trans, locked_ref, ref, extent_op,
2059 					  must_insert_reserved);
2060 		btrfs_delayed_refs_rsv_release(fs_info, 1, 0);
2061 		*bytes_released += btrfs_calc_delayed_ref_bytes(fs_info, 1);
2062 
2063 		btrfs_free_delayed_extent_op(extent_op);
2064 		if (ret) {
2065 			btrfs_unselect_ref_head(delayed_refs, locked_ref);
2066 			btrfs_put_delayed_ref(ref);
2067 			return ret;
2068 		}
2069 
2070 		btrfs_put_delayed_ref(ref);
2071 		cond_resched();
2072 
2073 		spin_lock(&locked_ref->lock);
2074 		btrfs_merge_delayed_refs(fs_info, delayed_refs, locked_ref);
2075 	}
2076 
2077 	return 0;
2078 }
2079 
2080 /*
2081  * Returns 0 on success or if called with an already aborted transaction.
2082  * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2083  */
2084 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2085 					     u64 min_bytes)
2086 {
2087 	struct btrfs_fs_info *fs_info = trans->fs_info;
2088 	struct btrfs_delayed_ref_root *delayed_refs;
2089 	struct btrfs_delayed_ref_head *locked_ref = NULL;
2090 	int ret;
2091 	unsigned long count = 0;
2092 	unsigned long max_count = 0;
2093 	u64 bytes_processed = 0;
2094 
2095 	delayed_refs = &trans->transaction->delayed_refs;
2096 	if (min_bytes == 0) {
2097 		/*
2098 		 * We may be subject to a harmless race if some task is
2099 		 * concurrently adding or removing a delayed ref, so silence
2100 		 * KCSAN and similar tools.
2101 		 */
2102 		max_count = data_race(delayed_refs->num_heads_ready);
2103 		min_bytes = U64_MAX;
2104 	}
2105 
2106 	do {
2107 		if (!locked_ref) {
2108 			locked_ref = btrfs_select_ref_head(fs_info, delayed_refs);
2109 			if (IS_ERR_OR_NULL(locked_ref)) {
2110 				if (PTR_ERR(locked_ref) == -EAGAIN) {
2111 					count++;
2112 					goto again;
2113 				} else {
2114 					break;
2115 				}
2116 			}
2117 			count++;
2118 		}
2119 		/*
2120 		 * We need to try and merge add/drops of the same ref since we
2121 		 * can run into issues with relocate dropping the implicit ref
2122 		 * and then it being added back again before the drop can
2123 		 * finish.  If we merged anything we need to re-loop so we can
2124 		 * get a good ref.
2125 		 * Or we can get node references of the same type that weren't
2126 		 * merged when created due to bumps in the tree mod seq, and
2127 		 * we need to merge them to prevent adding an inline extent
2128 		 * backref before dropping it (triggering a BUG_ON at
2129 		 * insert_inline_extent_backref()).
2130 		 */
2131 		spin_lock(&locked_ref->lock);
2132 		btrfs_merge_delayed_refs(fs_info, delayed_refs, locked_ref);
2133 
2134 		ret = btrfs_run_delayed_refs_for_head(trans, locked_ref, &bytes_processed);
2135 		if (ret < 0 && ret != -EAGAIN) {
2136 			/*
2137 			 * Error, btrfs_run_delayed_refs_for_head already
2138 			 * unlocked everything so just bail out
2139 			 */
2140 			return ret;
2141 		} else if (!ret) {
2142 			/*
2143 			 * Success, perform the usual cleanup of a processed
2144 			 * head
2145 			 */
2146 			ret = cleanup_ref_head(trans, locked_ref, &bytes_processed);
2147 			if (ret > 0 ) {
2148 				/* We dropped our lock, we need to loop. */
2149 				ret = 0;
2150 				continue;
2151 			} else if (ret) {
2152 				return ret;
2153 			}
2154 		}
2155 
2156 		/*
2157 		 * Either success case or btrfs_run_delayed_refs_for_head
2158 		 * returned -EAGAIN, meaning we need to select another head
2159 		 */
2160 again:
2161 		locked_ref = NULL;
2162 		cond_resched();
2163 	} while ((min_bytes != U64_MAX && bytes_processed < min_bytes) ||
2164 		 (max_count > 0 && count < max_count) ||
2165 		 locked_ref);
2166 
2167 	return 0;
2168 }
2169 
2170 #ifdef SCRAMBLE_DELAYED_REFS
2171 /*
2172  * Normally delayed refs get processed in ascending bytenr order. This
2173  * correlates in most cases to the order added. To expose dependencies on this
2174  * order, we start to process the tree in the middle instead of the beginning
2175  */
2176 static u64 find_middle(struct rb_root *root)
2177 {
2178 	struct rb_node *n = root->rb_node;
2179 	struct btrfs_delayed_ref_node *entry;
2180 	int alt = 1;
2181 	u64 middle;
2182 	u64 first = 0, last = 0;
2183 
2184 	n = rb_first(root);
2185 	if (n) {
2186 		entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2187 		first = entry->bytenr;
2188 	}
2189 	n = rb_last(root);
2190 	if (n) {
2191 		entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2192 		last = entry->bytenr;
2193 	}
2194 	n = root->rb_node;
2195 
2196 	while (n) {
2197 		entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2198 		WARN_ON(!entry->in_tree);
2199 
2200 		middle = entry->bytenr;
2201 
2202 		if (alt)
2203 			n = n->rb_left;
2204 		else
2205 			n = n->rb_right;
2206 
2207 		alt = 1 - alt;
2208 	}
2209 	return middle;
2210 }
2211 #endif
2212 
2213 /*
2214  * Start processing the delayed reference count updates and extent insertions
2215  * we have queued up so far.
2216  *
2217  * @trans:	Transaction handle.
2218  * @min_bytes:	How many bytes of delayed references to process. After this
2219  *		many bytes we stop processing delayed references if there are
2220  *		any more. If 0 it means to run all existing delayed references,
2221  *		but not new ones added after running all existing ones.
2222  *		Use (u64)-1 (U64_MAX) to run all existing delayed references
2223  *		plus any new ones that are added.
2224  *
2225  * Returns 0 on success or if called with an aborted transaction
2226  * Returns <0 on error and aborts the transaction
2227  */
2228 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans, u64 min_bytes)
2229 {
2230 	struct btrfs_fs_info *fs_info = trans->fs_info;
2231 	struct btrfs_delayed_ref_root *delayed_refs;
2232 	int ret;
2233 
2234 	/* We'll clean this up in btrfs_cleanup_transaction */
2235 	if (TRANS_ABORTED(trans))
2236 		return 0;
2237 
2238 	if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2239 		return 0;
2240 
2241 	delayed_refs = &trans->transaction->delayed_refs;
2242 again:
2243 #ifdef SCRAMBLE_DELAYED_REFS
2244 	delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2245 #endif
2246 	ret = __btrfs_run_delayed_refs(trans, min_bytes);
2247 	if (unlikely(ret < 0)) {
2248 		btrfs_abort_transaction(trans, ret);
2249 		return ret;
2250 	}
2251 
2252 	if (min_bytes == U64_MAX) {
2253 		btrfs_create_pending_block_groups(trans);
2254 
2255 		spin_lock(&delayed_refs->lock);
2256 		if (xa_empty(&delayed_refs->head_refs)) {
2257 			spin_unlock(&delayed_refs->lock);
2258 			return 0;
2259 		}
2260 		spin_unlock(&delayed_refs->lock);
2261 
2262 		cond_resched();
2263 		goto again;
2264 	}
2265 
2266 	return 0;
2267 }
2268 
2269 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2270 				struct extent_buffer *eb, u64 flags)
2271 {
2272 	struct btrfs_delayed_extent_op *extent_op;
2273 	int ret;
2274 
2275 	extent_op = btrfs_alloc_delayed_extent_op();
2276 	if (!extent_op)
2277 		return -ENOMEM;
2278 
2279 	extent_op->flags_to_set = flags;
2280 	extent_op->update_flags = true;
2281 	extent_op->update_key = false;
2282 
2283 	ret = btrfs_add_delayed_extent_op(trans, eb->start, eb->len,
2284 					  btrfs_header_level(eb), extent_op);
2285 	if (ret)
2286 		btrfs_free_delayed_extent_op(extent_op);
2287 	return ret;
2288 }
2289 
2290 static noinline int check_delayed_ref(struct btrfs_inode *inode,
2291 				      struct btrfs_path *path,
2292 				      u64 offset, u64 bytenr)
2293 {
2294 	struct btrfs_root *root = inode->root;
2295 	struct btrfs_delayed_ref_head *head;
2296 	struct btrfs_delayed_ref_node *ref;
2297 	struct btrfs_delayed_ref_root *delayed_refs;
2298 	struct btrfs_transaction *cur_trans;
2299 	struct rb_node *node;
2300 	int ret = 0;
2301 
2302 	spin_lock(&root->fs_info->trans_lock);
2303 	cur_trans = root->fs_info->running_transaction;
2304 	if (cur_trans)
2305 		refcount_inc(&cur_trans->use_count);
2306 	spin_unlock(&root->fs_info->trans_lock);
2307 	if (!cur_trans)
2308 		return 0;
2309 
2310 	delayed_refs = &cur_trans->delayed_refs;
2311 	spin_lock(&delayed_refs->lock);
2312 	head = btrfs_find_delayed_ref_head(root->fs_info, delayed_refs, bytenr);
2313 	if (!head) {
2314 		spin_unlock(&delayed_refs->lock);
2315 		btrfs_put_transaction(cur_trans);
2316 		return 0;
2317 	}
2318 
2319 	if (!mutex_trylock(&head->mutex)) {
2320 		if (path->nowait) {
2321 			spin_unlock(&delayed_refs->lock);
2322 			btrfs_put_transaction(cur_trans);
2323 			return -EAGAIN;
2324 		}
2325 
2326 		refcount_inc(&head->refs);
2327 		spin_unlock(&delayed_refs->lock);
2328 
2329 		btrfs_release_path(path);
2330 
2331 		/*
2332 		 * Mutex was contended, block until it's released and let
2333 		 * caller try again
2334 		 */
2335 		mutex_lock(&head->mutex);
2336 		mutex_unlock(&head->mutex);
2337 		btrfs_put_delayed_ref_head(head);
2338 		btrfs_put_transaction(cur_trans);
2339 		return -EAGAIN;
2340 	}
2341 	spin_unlock(&delayed_refs->lock);
2342 
2343 	spin_lock(&head->lock);
2344 	/*
2345 	 * XXX: We should replace this with a proper search function in the
2346 	 * future.
2347 	 */
2348 	for (node = rb_first_cached(&head->ref_tree); node;
2349 	     node = rb_next(node)) {
2350 		u64 ref_owner;
2351 		u64 ref_offset;
2352 
2353 		ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
2354 		/* If it's a shared ref we know a cross reference exists */
2355 		if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2356 			ret = 1;
2357 			break;
2358 		}
2359 
2360 		ref_owner = btrfs_delayed_ref_owner(ref);
2361 		ref_offset = btrfs_delayed_ref_offset(ref);
2362 
2363 		/*
2364 		 * If our ref doesn't match the one we're currently looking at
2365 		 * then we have a cross reference.
2366 		 */
2367 		if (ref->ref_root != btrfs_root_id(root) ||
2368 		    ref_owner != btrfs_ino(inode) || ref_offset != offset) {
2369 			ret = 1;
2370 			break;
2371 		}
2372 	}
2373 	spin_unlock(&head->lock);
2374 	mutex_unlock(&head->mutex);
2375 	btrfs_put_transaction(cur_trans);
2376 	return ret;
2377 }
2378 
2379 /*
2380  * Check if there are references for a data extent other than the one belonging
2381  * to the given inode and offset.
2382  *
2383  * @inode:     The only inode we expect to find associated with the data extent.
2384  * @path:      A path to use for searching the extent tree.
2385  * @offset:    The only offset we expect to find associated with the data extent.
2386  * @bytenr:    The logical address of the data extent.
2387  *
2388  * When the extent does not have any other references other than the one we
2389  * expect to find, we always return a value of 0 with the path having a locked
2390  * leaf that contains the extent's extent item - this is necessary to ensure
2391  * we don't race with a task running delayed references, and our caller must
2392  * have such a path when calling check_delayed_ref() - it must lock a delayed
2393  * ref head while holding the leaf locked. In case the extent item is not found
2394  * in the extent tree, we return -ENOENT with the path having the leaf (locked)
2395  * where the extent item should be, in order to prevent races with another task
2396  * running delayed references, so that we don't miss any reference when calling
2397  * check_delayed_ref().
2398  *
2399  * Note: this may return false positives, and this is because we want to be
2400  *       quick here as we're called in write paths (when flushing delalloc and
2401  *       in the direct IO write path). For example we can have an extent with
2402  *       a single reference but that reference is not inlined, or we may have
2403  *       many references in the extent tree but we also have delayed references
2404  *       that cancel all the reference except the one for our inode and offset,
2405  *       but it would be expensive to do such checks and complex due to all
2406  *       locking to avoid races between the checks and flushing delayed refs,
2407  *       plus non-inline references may be located on leaves other than the one
2408  *       that contains the extent item in the extent tree. The important thing
2409  *       here is to not return false negatives and that the false positives are
2410  *       not very common.
2411  *
2412  * Returns: 0 if there are no cross references and with the path having a locked
2413  *          leaf from the extent tree that contains the extent's extent item.
2414  *
2415  *          1 if there are cross references (false positives can happen).
2416  *
2417  *          < 0 in case of an error. In case of -ENOENT the leaf in the extent
2418  *          tree where the extent item should be located at is read locked and
2419  *          accessible in the given path.
2420  */
2421 static noinline int check_committed_ref(struct btrfs_inode *inode,
2422 					struct btrfs_path *path,
2423 					u64 offset, u64 bytenr)
2424 {
2425 	struct btrfs_root *root = inode->root;
2426 	struct btrfs_fs_info *fs_info = root->fs_info;
2427 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
2428 	struct extent_buffer *leaf;
2429 	struct btrfs_extent_data_ref *ref;
2430 	struct btrfs_extent_inline_ref *iref;
2431 	struct btrfs_extent_item *ei;
2432 	struct btrfs_key key;
2433 	u32 item_size;
2434 	u32 expected_size;
2435 	int type;
2436 	int ret;
2437 
2438 	if (unlikely(!extent_root)) {
2439 		btrfs_err(fs_info,
2440 			  "missing extent root for extent at bytenr %llu", bytenr);
2441 		return -EUCLEAN;
2442 	}
2443 
2444 	key.objectid = bytenr;
2445 	key.type = BTRFS_EXTENT_ITEM_KEY;
2446 	key.offset = (u64)-1;
2447 
2448 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2449 	if (ret < 0)
2450 		return ret;
2451 	if (unlikely(ret == 0)) {
2452 		/*
2453 		 * Key with offset -1 found, there would have to exist an extent
2454 		 * item with such offset, but this is out of the valid range.
2455 		 */
2456 		return -EUCLEAN;
2457 	}
2458 
2459 	if (path->slots[0] == 0)
2460 		return -ENOENT;
2461 
2462 	path->slots[0]--;
2463 	leaf = path->nodes[0];
2464 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2465 
2466 	if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2467 		return -ENOENT;
2468 
2469 	item_size = btrfs_item_size(leaf, path->slots[0]);
2470 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2471 	expected_size = sizeof(*ei) + btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY);
2472 
2473 	/* No inline refs; we need to bail before checking for owner ref. */
2474 	if (item_size == sizeof(*ei))
2475 		return 1;
2476 
2477 	/* Check for an owner ref; skip over it to the real inline refs. */
2478 	iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2479 	type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
2480 	if (btrfs_fs_incompat(fs_info, SIMPLE_QUOTA) && type == BTRFS_EXTENT_OWNER_REF_KEY) {
2481 		expected_size += btrfs_extent_inline_ref_size(BTRFS_EXTENT_OWNER_REF_KEY);
2482 		iref = (struct btrfs_extent_inline_ref *)(iref + 1);
2483 		type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
2484 	}
2485 
2486 	/* If extent item has more than 1 inline ref then it's shared */
2487 	if (item_size != expected_size)
2488 		return 1;
2489 
2490 	/* If this extent has SHARED_DATA_REF then it's shared */
2491 	if (type != BTRFS_EXTENT_DATA_REF_KEY)
2492 		return 1;
2493 
2494 	ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2495 	if (btrfs_extent_refs(leaf, ei) !=
2496 	    btrfs_extent_data_ref_count(leaf, ref) ||
2497 	    btrfs_extent_data_ref_root(leaf, ref) != btrfs_root_id(root) ||
2498 	    btrfs_extent_data_ref_objectid(leaf, ref) != btrfs_ino(inode) ||
2499 	    btrfs_extent_data_ref_offset(leaf, ref) != offset)
2500 		return 1;
2501 
2502 	return 0;
2503 }
2504 
2505 int btrfs_cross_ref_exist(struct btrfs_inode *inode, u64 offset,
2506 			  u64 bytenr, struct btrfs_path *path)
2507 {
2508 	int ret;
2509 
2510 	do {
2511 		ret = check_committed_ref(inode, path, offset, bytenr);
2512 		if (ret && ret != -ENOENT)
2513 			goto out;
2514 
2515 		/*
2516 		 * The path must have a locked leaf from the extent tree where
2517 		 * the extent item for our extent is located, in case it exists,
2518 		 * or where it should be located in case it doesn't exist yet
2519 		 * because it's new and its delayed ref was not yet flushed.
2520 		 * We need to lock the delayed ref head at check_delayed_ref(),
2521 		 * if one exists, while holding the leaf locked in order to not
2522 		 * race with delayed ref flushing, missing references and
2523 		 * incorrectly reporting that the extent is not shared.
2524 		 */
2525 		if (IS_ENABLED(CONFIG_BTRFS_ASSERT)) {
2526 			struct extent_buffer *leaf = path->nodes[0];
2527 
2528 			ASSERT(leaf != NULL);
2529 			btrfs_assert_tree_read_locked(leaf);
2530 
2531 			if (ret != -ENOENT) {
2532 				struct btrfs_key key;
2533 
2534 				btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2535 				ASSERT(key.objectid == bytenr,
2536 				       "key.objectid=%llu bytenr=%llu",
2537 				       key.objectid, bytenr);
2538 				ASSERT(key.type == BTRFS_EXTENT_ITEM_KEY, "key.type=%u",
2539 				       key.type);
2540 			}
2541 		}
2542 
2543 		ret = check_delayed_ref(inode, path, offset, bytenr);
2544 	} while (ret == -EAGAIN && !path->nowait);
2545 
2546 out:
2547 	btrfs_release_path(path);
2548 	if (btrfs_is_data_reloc_root(inode->root))
2549 		WARN_ON(ret > 0);
2550 	return ret;
2551 }
2552 
2553 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2554 			   struct btrfs_root *root,
2555 			   struct extent_buffer *buf,
2556 			   bool full_backref, bool inc)
2557 {
2558 	struct btrfs_fs_info *fs_info = root->fs_info;
2559 	u64 parent;
2560 	u64 ref_root;
2561 	u32 nritems;
2562 	struct btrfs_key key;
2563 	struct btrfs_file_extent_item *fi;
2564 	bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
2565 	int i;
2566 	int action;
2567 	int level;
2568 	int ret;
2569 
2570 	if (btrfs_is_testing(fs_info))
2571 		return 0;
2572 
2573 	ref_root = btrfs_header_owner(buf);
2574 	nritems = btrfs_header_nritems(buf);
2575 	level = btrfs_header_level(buf);
2576 
2577 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state) && level == 0)
2578 		return 0;
2579 
2580 	if (full_backref)
2581 		parent = buf->start;
2582 	else
2583 		parent = 0;
2584 	if (inc)
2585 		action = BTRFS_ADD_DELAYED_REF;
2586 	else
2587 		action = BTRFS_DROP_DELAYED_REF;
2588 
2589 	for (i = 0; i < nritems; i++) {
2590 		struct btrfs_ref ref = {
2591 			.action = action,
2592 			.parent = parent,
2593 			.ref_root = ref_root,
2594 		};
2595 
2596 		if (level == 0) {
2597 			btrfs_item_key_to_cpu(buf, &key, i);
2598 			if (key.type != BTRFS_EXTENT_DATA_KEY)
2599 				continue;
2600 			fi = btrfs_item_ptr(buf, i,
2601 					    struct btrfs_file_extent_item);
2602 			if (btrfs_file_extent_type(buf, fi) ==
2603 			    BTRFS_FILE_EXTENT_INLINE)
2604 				continue;
2605 			ref.bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2606 			if (ref.bytenr == 0)
2607 				continue;
2608 
2609 			ref.num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2610 			ref.owning_root = ref_root;
2611 
2612 			key.offset -= btrfs_file_extent_offset(buf, fi);
2613 			btrfs_init_data_ref(&ref, key.objectid, key.offset,
2614 					    btrfs_root_id(root), for_reloc);
2615 			if (inc)
2616 				ret = btrfs_inc_extent_ref(trans, &ref);
2617 			else
2618 				ret = btrfs_free_extent(trans, &ref);
2619 			if (ret)
2620 				return ret;
2621 		} else {
2622 			/* We don't know the owning_root, leave as 0. */
2623 			ref.bytenr = btrfs_node_blockptr(buf, i);
2624 			ref.num_bytes = fs_info->nodesize;
2625 
2626 			btrfs_init_tree_ref(&ref, level - 1,
2627 					    btrfs_root_id(root), for_reloc);
2628 			if (inc)
2629 				ret = btrfs_inc_extent_ref(trans, &ref);
2630 			else
2631 				ret = btrfs_free_extent(trans, &ref);
2632 			if (ret)
2633 				return ret;
2634 		}
2635 	}
2636 	return 0;
2637 }
2638 
2639 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2640 		  struct extent_buffer *buf, bool full_backref)
2641 {
2642 	return __btrfs_mod_ref(trans, root, buf, full_backref, true);
2643 }
2644 
2645 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2646 		  struct extent_buffer *buf, bool full_backref)
2647 {
2648 	return __btrfs_mod_ref(trans, root, buf, full_backref, false);
2649 }
2650 
2651 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
2652 {
2653 	struct btrfs_fs_info *fs_info = root->fs_info;
2654 	u64 flags;
2655 
2656 	if (data)
2657 		flags = BTRFS_BLOCK_GROUP_DATA;
2658 	else if (root == fs_info->chunk_root)
2659 		flags = BTRFS_BLOCK_GROUP_SYSTEM;
2660 	else if (root == fs_info->remap_root)
2661 		flags = BTRFS_BLOCK_GROUP_METADATA_REMAP;
2662 	else
2663 		flags = BTRFS_BLOCK_GROUP_METADATA;
2664 
2665 	return btrfs_get_alloc_profile(fs_info, flags);
2666 }
2667 
2668 static u64 first_logical_byte(struct btrfs_fs_info *fs_info)
2669 {
2670 	struct rb_node *leftmost;
2671 	u64 bytenr = 0;
2672 
2673 	read_lock(&fs_info->block_group_cache_lock);
2674 	/* Get the block group with the lowest logical start address. */
2675 	leftmost = rb_first_cached(&fs_info->block_group_cache_tree);
2676 	if (leftmost) {
2677 		struct btrfs_block_group *bg;
2678 
2679 		bg = rb_entry(leftmost, struct btrfs_block_group, cache_node);
2680 		bytenr = bg->start;
2681 	}
2682 	read_unlock(&fs_info->block_group_cache_lock);
2683 
2684 	return bytenr;
2685 }
2686 
2687 static int pin_down_extent(struct btrfs_trans_handle *trans,
2688 			   struct btrfs_block_group *bg,
2689 			   u64 bytenr, u64 num_bytes, bool reserved)
2690 {
2691 	struct btrfs_space_info *space_info = bg->space_info;
2692 	const u64 reserved_bytes = (reserved ? num_bytes : 0);
2693 
2694 	spin_lock(&space_info->lock);
2695 	spin_lock(&bg->lock);
2696 	bg->pinned += num_bytes;
2697 	bg->reserved -= reserved_bytes;
2698 	spin_unlock(&bg->lock);
2699 	space_info->bytes_reserved -= reserved_bytes;
2700 	btrfs_space_info_update_bytes_pinned(space_info, num_bytes);
2701 	spin_unlock(&space_info->lock);
2702 
2703 	btrfs_set_extent_bit(&trans->transaction->pinned_extents, bytenr,
2704 			     bytenr + num_bytes - 1, EXTENT_DIRTY, NULL);
2705 	return 0;
2706 }
2707 
2708 int btrfs_pin_extent(struct btrfs_trans_handle *trans, u64 bytenr, u64 num_bytes)
2709 {
2710 	struct btrfs_block_group *cache;
2711 
2712 	cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
2713 	BUG_ON(!cache); /* Logic error */
2714 
2715 	pin_down_extent(trans, cache, bytenr, num_bytes, true);
2716 
2717 	btrfs_put_block_group(cache);
2718 	return 0;
2719 }
2720 
2721 int btrfs_pin_extent_for_log_replay(struct btrfs_trans_handle *trans,
2722 				    const struct extent_buffer *eb)
2723 {
2724 	struct btrfs_block_group *cache;
2725 	int ret;
2726 
2727 	cache = btrfs_lookup_block_group(trans->fs_info, eb->start);
2728 	if (!cache)
2729 		return -EINVAL;
2730 
2731 	/*
2732 	 * Fully cache the free space first so that our pin removes the free space
2733 	 * from the cache.
2734 	 */
2735 	ret = btrfs_cache_block_group(cache, true);
2736 	if (ret)
2737 		goto out;
2738 
2739 	pin_down_extent(trans, cache, eb->start, eb->len, false);
2740 
2741 	/* remove us from the free space cache (if we're there at all) */
2742 	ret = btrfs_remove_free_space(cache, eb->start, eb->len);
2743 out:
2744 	btrfs_put_block_group(cache);
2745 	return ret;
2746 }
2747 
2748 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
2749 				   u64 start, u64 num_bytes)
2750 {
2751 	int ret;
2752 	struct btrfs_block_group *block_group;
2753 
2754 	block_group = btrfs_lookup_block_group(fs_info, start);
2755 	if (!block_group)
2756 		return -EINVAL;
2757 
2758 	ret = btrfs_cache_block_group(block_group, true);
2759 	if (ret)
2760 		goto out;
2761 
2762 	ret = btrfs_remove_free_space(block_group, start, num_bytes);
2763 out:
2764 	btrfs_put_block_group(block_group);
2765 	return ret;
2766 }
2767 
2768 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
2769 {
2770 	struct btrfs_fs_info *fs_info = eb->fs_info;
2771 	struct btrfs_file_extent_item *item;
2772 	struct btrfs_key key;
2773 	int found_type;
2774 	int i;
2775 	int ret = 0;
2776 
2777 	if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
2778 		return 0;
2779 
2780 	for (i = 0; i < btrfs_header_nritems(eb); i++) {
2781 		btrfs_item_key_to_cpu(eb, &key, i);
2782 		if (key.type != BTRFS_EXTENT_DATA_KEY)
2783 			continue;
2784 		item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
2785 		found_type = btrfs_file_extent_type(eb, item);
2786 		if (found_type == BTRFS_FILE_EXTENT_INLINE)
2787 			continue;
2788 		if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
2789 			continue;
2790 		key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
2791 		key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
2792 		ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
2793 		if (ret)
2794 			break;
2795 	}
2796 
2797 	return ret;
2798 }
2799 
2800 static void
2801 btrfs_inc_block_group_reservations(struct btrfs_block_group *bg)
2802 {
2803 	atomic_inc(&bg->reservations);
2804 }
2805 
2806 /*
2807  * Returns the free cluster for the given space info and sets empty_cluster to
2808  * what it should be based on the mount options.
2809  */
2810 static struct btrfs_free_cluster *
2811 fetch_cluster_info(struct btrfs_fs_info *fs_info,
2812 		   struct btrfs_space_info *space_info, u64 *empty_cluster)
2813 {
2814 	struct btrfs_free_cluster *ret = NULL;
2815 
2816 	*empty_cluster = 0;
2817 	if (btrfs_mixed_space_info(space_info))
2818 		return ret;
2819 
2820 	if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
2821 		ret = &fs_info->meta_alloc_cluster;
2822 		if (btrfs_test_opt(fs_info, SSD))
2823 			*empty_cluster = SZ_2M;
2824 		else
2825 			*empty_cluster = SZ_64K;
2826 	} else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
2827 		   btrfs_test_opt(fs_info, SSD_SPREAD)) {
2828 		*empty_cluster = SZ_2M;
2829 		ret = &fs_info->data_alloc_cluster;
2830 	}
2831 
2832 	return ret;
2833 }
2834 
2835 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
2836 			      u64 start, u64 end,
2837 			      const bool return_free_space)
2838 {
2839 	struct btrfs_block_group *cache = NULL;
2840 	struct btrfs_space_info *space_info;
2841 	struct btrfs_free_cluster *cluster = NULL;
2842 	u64 total_unpinned = 0;
2843 	u64 empty_cluster = 0;
2844 
2845 	while (start <= end) {
2846 		u64 len;
2847 		bool readonly;
2848 
2849 		if (!cache || start >= btrfs_block_group_end(cache)) {
2850 			if (cache)
2851 				btrfs_put_block_group(cache);
2852 			total_unpinned = 0;
2853 			cache = btrfs_lookup_block_group(fs_info, start);
2854 			if (unlikely(cache == NULL)) {
2855 				/* Logic error, something removed the block group. */
2856 				return -EUCLEAN;
2857 			}
2858 
2859 			cluster = fetch_cluster_info(fs_info,
2860 						     cache->space_info,
2861 						     &empty_cluster);
2862 			empty_cluster <<= 1;
2863 		}
2864 
2865 		len = btrfs_block_group_end(cache) - start;
2866 		len = min(len, end + 1 - start);
2867 
2868 		if (return_free_space)
2869 			btrfs_add_free_space(cache, start, len);
2870 
2871 		start += len;
2872 		total_unpinned += len;
2873 		space_info = cache->space_info;
2874 
2875 		/*
2876 		 * If this space cluster has been marked as fragmented and we've
2877 		 * unpinned enough in this block group to potentially allow a
2878 		 * cluster to be created inside of it go ahead and clear the
2879 		 * fragmented check.
2880 		 */
2881 		if (cluster && cluster->fragmented &&
2882 		    total_unpinned > empty_cluster) {
2883 			spin_lock(&cluster->lock);
2884 			cluster->fragmented = 0;
2885 			spin_unlock(&cluster->lock);
2886 		}
2887 
2888 		spin_lock(&space_info->lock);
2889 		spin_lock(&cache->lock);
2890 		readonly = cache->ro;
2891 		cache->pinned -= len;
2892 		spin_unlock(&cache->lock);
2893 
2894 		btrfs_space_info_update_bytes_pinned(space_info, -len);
2895 		space_info->max_extent_size = 0;
2896 
2897 		if (readonly) {
2898 			space_info->bytes_readonly += len;
2899 		} else if (btrfs_is_zoned(fs_info)) {
2900 			/* Need reset before reusing in a zoned block group */
2901 			btrfs_space_info_update_bytes_zone_unusable(space_info, len);
2902 		} else if (return_free_space) {
2903 			btrfs_return_free_space(space_info, len);
2904 		}
2905 		spin_unlock(&space_info->lock);
2906 	}
2907 
2908 	if (cache)
2909 		btrfs_put_block_group(cache);
2910 
2911 	return 0;
2912 }
2913 
2914 /*
2915  * Complete the remapping of a block group by removing its chunk stripes and
2916  * device extents, and adding it to the unused list if there's no longer any
2917  * extents nominally within it.
2918  */
2919 int btrfs_complete_bg_remapping(struct btrfs_block_group *bg)
2920 {
2921 	struct btrfs_fs_info *fs_info = bg->fs_info;
2922 	struct btrfs_chunk_map *map;
2923 	int ret;
2924 
2925 	map = btrfs_get_chunk_map(fs_info, bg->start, 1);
2926 	if (IS_ERR(map))
2927 		return PTR_ERR(map);
2928 
2929 	ret = btrfs_last_identity_remap_gone(map, bg);
2930 	if (ret) {
2931 		btrfs_free_chunk_map(map);
2932 		return ret;
2933 	}
2934 
2935 	/*
2936 	 * Set num_stripes to 0, so that btrfs_remove_dev_extents() won't run a
2937 	 * second time.
2938 	 */
2939 	map->num_stripes = 0;
2940 
2941 	btrfs_free_chunk_map(map);
2942 
2943 	if (bg->used == 0) {
2944 		spin_lock(&fs_info->unused_bgs_lock);
2945 		if (!list_empty(&bg->bg_list)) {
2946 			list_del_init(&bg->bg_list);
2947 			btrfs_put_block_group(bg);
2948 		}
2949 		spin_unlock(&fs_info->unused_bgs_lock);
2950 
2951 		btrfs_mark_bg_unused(bg);
2952 	}
2953 
2954 	return 0;
2955 }
2956 
2957 void btrfs_handle_fully_remapped_bgs(struct btrfs_fs_info *fs_info)
2958 {
2959 	struct btrfs_block_group *bg;
2960 	int ret;
2961 
2962 	spin_lock(&fs_info->unused_bgs_lock);
2963 	while (!list_empty(&fs_info->fully_remapped_bgs)) {
2964 		bg = list_first_entry(&fs_info->fully_remapped_bgs,
2965 				      struct btrfs_block_group, bg_list);
2966 		list_del_init(&bg->bg_list);
2967 		spin_unlock(&fs_info->unused_bgs_lock);
2968 
2969 		btrfs_discard_extent(fs_info, bg->start, bg->length, NULL, false);
2970 
2971 		ret = btrfs_complete_bg_remapping(bg);
2972 		if (ret) {
2973 			btrfs_put_block_group(bg);
2974 			return;
2975 		}
2976 
2977 		btrfs_put_block_group(bg);
2978 		spin_lock(&fs_info->unused_bgs_lock);
2979 	}
2980 	spin_unlock(&fs_info->unused_bgs_lock);
2981 }
2982 
2983 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
2984 {
2985 	struct btrfs_fs_info *fs_info = trans->fs_info;
2986 	struct btrfs_block_group *block_group, *tmp;
2987 	struct list_head *deleted_bgs;
2988 	struct extent_io_tree *unpin = &trans->transaction->pinned_extents;
2989 	struct extent_state *cached_state = NULL;
2990 	u64 start;
2991 	u64 end;
2992 	int unpin_error = 0;
2993 	int ret;
2994 
2995 	mutex_lock(&fs_info->unused_bg_unpin_mutex);
2996 	btrfs_find_first_extent_bit(unpin, 0, &start, &end, EXTENT_DIRTY, &cached_state);
2997 
2998 	while (!TRANS_ABORTED(trans) && cached_state) {
2999 		struct extent_state *next_state;
3000 
3001 		if (btrfs_test_opt(fs_info, DISCARD_SYNC)) {
3002 			ret = btrfs_discard_extent(fs_info, start,
3003 						   end + 1 - start, NULL, true);
3004 			if (ret) {
3005 				btrfs_warn(fs_info,
3006 				"discard failed for extent [%llu, %llu]: errno=%d %s",
3007 					   start, end, ret, btrfs_decode_error(ret));
3008 			}
3009 		}
3010 
3011 		next_state = btrfs_next_extent_state(unpin, cached_state);
3012 		btrfs_clear_extent_dirty(unpin, start, end, &cached_state);
3013 		ret = unpin_extent_range(fs_info, start, end, true);
3014 		/*
3015 		 * If we get an error unpinning an extent range, store the first
3016 		 * error to return later after trying to unpin all ranges and do
3017 		 * the sync discards. Our caller will abort the transaction
3018 		 * (which already wrote new superblocks) and on the next mount
3019 		 * the space will be available as it was pinned by in-memory
3020 		 * only structures in this phase.
3021 		 */
3022 		if (ret) {
3023 			btrfs_err_rl(fs_info,
3024 "failed to unpin extent range [%llu, %llu] when committing transaction %llu: %s (%d)",
3025 				     start, end, trans->transid,
3026 				     btrfs_decode_error(ret), ret);
3027 			if (!unpin_error)
3028 				unpin_error = ret;
3029 		}
3030 
3031 		btrfs_free_extent_state(cached_state);
3032 
3033 		if (need_resched()) {
3034 			btrfs_free_extent_state(next_state);
3035 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
3036 			cond_resched();
3037 			cached_state = NULL;
3038 			mutex_lock(&fs_info->unused_bg_unpin_mutex);
3039 			btrfs_find_first_extent_bit(unpin, 0, &start, &end,
3040 						    EXTENT_DIRTY, &cached_state);
3041 		} else {
3042 			cached_state = next_state;
3043 			if (cached_state) {
3044 				start = cached_state->start;
3045 				end = cached_state->end;
3046 			}
3047 		}
3048 	}
3049 	mutex_unlock(&fs_info->unused_bg_unpin_mutex);
3050 	btrfs_free_extent_state(cached_state);
3051 
3052 	if (btrfs_test_opt(fs_info, DISCARD_ASYNC)) {
3053 		btrfs_discard_calc_delay(&fs_info->discard_ctl);
3054 		btrfs_discard_schedule_work(&fs_info->discard_ctl, true);
3055 	}
3056 
3057 	/*
3058 	 * Transaction is finished.  We don't need the lock anymore.  We
3059 	 * do need to clean up the block groups in case of a transaction
3060 	 * abort.
3061 	 */
3062 	deleted_bgs = &trans->transaction->deleted_bgs;
3063 	list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
3064 		ret = -EROFS;
3065 		if (!TRANS_ABORTED(trans))
3066 			ret = btrfs_discard_extent(fs_info, block_group->start,
3067 						   block_group->length, NULL, true);
3068 
3069 		/*
3070 		 * Not strictly necessary to lock, as the block_group should be
3071 		 * read-only from btrfs_delete_unused_bgs().
3072 		 */
3073 		ASSERT(block_group->ro);
3074 		spin_lock(&fs_info->unused_bgs_lock);
3075 		list_del_init(&block_group->bg_list);
3076 		spin_unlock(&fs_info->unused_bgs_lock);
3077 
3078 		btrfs_unfreeze_block_group(block_group);
3079 		btrfs_put_block_group(block_group);
3080 
3081 		if (ret) {
3082 			const char *errstr = btrfs_decode_error(ret);
3083 			btrfs_warn(fs_info,
3084 			   "discard failed while removing blockgroup: errno=%d %s",
3085 				   ret, errstr);
3086 		}
3087 	}
3088 
3089 	return unpin_error;
3090 }
3091 
3092 /*
3093  * Parse an extent item's inline extents looking for a simple quotas owner ref.
3094  *
3095  * @fs_info:	the btrfs_fs_info for this mount
3096  * @leaf:	a leaf in the extent tree containing the extent item
3097  * @slot:	the slot in the leaf where the extent item is found
3098  *
3099  * Returns the objectid of the root that originally allocated the extent item
3100  * if the inline owner ref is expected and present, otherwise 0.
3101  *
3102  * If an extent item has an owner ref item, it will be the first inline ref
3103  * item. Therefore the logic is to check whether there are any inline ref
3104  * items, then check the type of the first one.
3105  */
3106 u64 btrfs_get_extent_owner_root(struct btrfs_fs_info *fs_info,
3107 				struct extent_buffer *leaf, int slot)
3108 {
3109 	struct btrfs_extent_item *ei;
3110 	struct btrfs_extent_inline_ref *iref;
3111 	struct btrfs_extent_owner_ref *oref;
3112 	unsigned long ptr;
3113 	unsigned long end;
3114 	int type;
3115 
3116 	if (!btrfs_fs_incompat(fs_info, SIMPLE_QUOTA))
3117 		return 0;
3118 
3119 	ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
3120 	ptr = (unsigned long)(ei + 1);
3121 	end = (unsigned long)ei + btrfs_item_size(leaf, slot);
3122 
3123 	/* No inline ref items of any kind, can't check type. */
3124 	if (ptr == end)
3125 		return 0;
3126 
3127 	iref = (struct btrfs_extent_inline_ref *)ptr;
3128 	type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
3129 
3130 	/* We found an owner ref, get the root out of it. */
3131 	if (type == BTRFS_EXTENT_OWNER_REF_KEY) {
3132 		oref = (struct btrfs_extent_owner_ref *)(&iref->offset);
3133 		return btrfs_extent_owner_ref_root_id(leaf, oref);
3134 	}
3135 
3136 	/* We have inline refs, but not an owner ref. */
3137 	return 0;
3138 }
3139 
3140 static int do_free_extent_accounting(struct btrfs_trans_handle *trans,
3141 				     u64 bytenr, struct btrfs_squota_delta *delta,
3142 				     struct btrfs_path *path)
3143 {
3144 	int ret;
3145 	bool remapped = false;
3146 	u64 num_bytes = delta->num_bytes;
3147 
3148 	/* Returns 1 on success and 0 on no-op. */
3149 	ret = btrfs_remove_extent_from_remap_tree(trans, path, bytenr, num_bytes);
3150 	if (unlikely(ret < 0)) {
3151 		btrfs_abort_transaction(trans, ret);
3152 		return ret;
3153 	} else if (ret == 1) {
3154 		remapped = true;
3155 	}
3156 
3157 	if (delta->is_data) {
3158 		struct btrfs_root *csum_root;
3159 
3160 		csum_root = btrfs_csum_root(trans->fs_info, bytenr);
3161 		if (unlikely(!csum_root)) {
3162 			ret = -EUCLEAN;
3163 			btrfs_abort_transaction(trans, ret);
3164 			btrfs_err(trans->fs_info,
3165 				  "missing csum root for extent at bytenr %llu",
3166 				  bytenr);
3167 			return ret;
3168 		}
3169 
3170 		ret = btrfs_del_csums(trans, csum_root, bytenr, num_bytes);
3171 		if (unlikely(ret)) {
3172 			btrfs_abort_transaction(trans, ret);
3173 			return ret;
3174 		}
3175 
3176 		ret = btrfs_delete_raid_extent(trans, bytenr, num_bytes);
3177 		if (unlikely(ret)) {
3178 			btrfs_abort_transaction(trans, ret);
3179 			return ret;
3180 		}
3181 	}
3182 
3183 	btrfs_record_squota_delta(trans->fs_info, delta);
3184 
3185 	/* If remapped, FST has already been taken care of in remove_range_from_remap_tree(). */
3186 	if (!remapped) {
3187 		ret = btrfs_add_to_free_space_tree(trans, bytenr, num_bytes);
3188 		if (unlikely(ret)) {
3189 			btrfs_abort_transaction(trans, ret);
3190 			return ret;
3191 		}
3192 	}
3193 
3194 	ret = btrfs_update_block_group(trans, bytenr, num_bytes, false);
3195 	if (ret)
3196 		btrfs_abort_transaction(trans, ret);
3197 
3198 	return ret;
3199 }
3200 
3201 #define abort_and_dump(trans, path, fmt, args...)	\
3202 ({							\
3203 	btrfs_abort_transaction(trans, -EUCLEAN);	\
3204 	btrfs_print_leaf(path->nodes[0]);		\
3205 	btrfs_crit(trans->fs_info, fmt, ##args);	\
3206 })
3207 
3208 /*
3209  * Drop one or more refs of @node.
3210  *
3211  * 1. Locate the extent refs.
3212  *    It's either inline in EXTENT/METADATA_ITEM or in keyed SHARED_* item.
3213  *    Locate it, then reduce the refs number or remove the ref line completely.
3214  *
3215  * 2. Update the refs count in EXTENT/METADATA_ITEM
3216  *
3217  * Inline backref case:
3218  *
3219  * in extent tree we have:
3220  *
3221  * 	item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
3222  *		refs 2 gen 6 flags DATA
3223  *		extent data backref root FS_TREE objectid 258 offset 0 count 1
3224  *		extent data backref root FS_TREE objectid 257 offset 0 count 1
3225  *
3226  * This function gets called with:
3227  *
3228  *    node->bytenr = 13631488
3229  *    node->num_bytes = 1048576
3230  *    root_objectid = FS_TREE
3231  *    owner_objectid = 257
3232  *    owner_offset = 0
3233  *    refs_to_drop = 1
3234  *
3235  * Then we should get some like:
3236  *
3237  * 	item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
3238  *		refs 1 gen 6 flags DATA
3239  *		extent data backref root FS_TREE objectid 258 offset 0 count 1
3240  *
3241  * Keyed backref case:
3242  *
3243  * in extent tree we have:
3244  *
3245  *	item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
3246  *		refs 754 gen 6 flags DATA
3247  *	[...]
3248  *	item 2 key (13631488 EXTENT_DATA_REF <HASH>) itemoff 3915 itemsize 28
3249  *		extent data backref root FS_TREE objectid 866 offset 0 count 1
3250  *
3251  * This function get called with:
3252  *
3253  *    node->bytenr = 13631488
3254  *    node->num_bytes = 1048576
3255  *    root_objectid = FS_TREE
3256  *    owner_objectid = 866
3257  *    owner_offset = 0
3258  *    refs_to_drop = 1
3259  *
3260  * Then we should get some like:
3261  *
3262  *	item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
3263  *		refs 753 gen 6 flags DATA
3264  *
3265  * And that (13631488 EXTENT_DATA_REF <HASH>) gets removed.
3266  */
3267 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
3268 			       struct btrfs_delayed_ref_head *href,
3269 			       const struct btrfs_delayed_ref_node *node,
3270 			       struct btrfs_delayed_extent_op *extent_op)
3271 {
3272 	struct btrfs_fs_info *info = trans->fs_info;
3273 	struct btrfs_key key;
3274 	BTRFS_PATH_AUTO_FREE(path);
3275 	struct btrfs_root *extent_root;
3276 	struct extent_buffer *leaf;
3277 	struct btrfs_extent_item *ei;
3278 	struct btrfs_extent_inline_ref *iref;
3279 	int ret;
3280 	int is_data;
3281 	int extent_slot = 0;
3282 	bool found_extent = false;
3283 	int num_to_del = 1;
3284 	int refs_to_drop = node->ref_mod;
3285 	u32 item_size;
3286 	u64 refs;
3287 	u64 bytenr = node->bytenr;
3288 	u64 num_bytes = node->num_bytes;
3289 	u64 owner_objectid = btrfs_delayed_ref_owner(node);
3290 	u64 owner_offset = btrfs_delayed_ref_offset(node);
3291 	bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
3292 	u64 delayed_ref_root = href->owning_root;
3293 
3294 	extent_root = btrfs_extent_root(info, bytenr);
3295 	if (unlikely(!extent_root)) {
3296 		btrfs_err(info,
3297 			  "missing extent root for extent at bytenr %llu", bytenr);
3298 		return -EUCLEAN;
3299 	}
3300 
3301 	path = btrfs_alloc_path();
3302 	if (!path)
3303 		return -ENOMEM;
3304 
3305 	is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
3306 
3307 	if (unlikely(!is_data && refs_to_drop != 1)) {
3308 		btrfs_crit(info,
3309 "invalid refs_to_drop, dropping more than 1 refs for tree block %llu refs_to_drop %u",
3310 			   node->bytenr, refs_to_drop);
3311 		ret = -EINVAL;
3312 		btrfs_abort_transaction(trans, ret);
3313 		return ret;
3314 	}
3315 
3316 	if (is_data)
3317 		skinny_metadata = false;
3318 
3319 	ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
3320 				    node->parent, node->ref_root, owner_objectid,
3321 				    owner_offset);
3322 	if (ret == 0) {
3323 		/*
3324 		 * Either the inline backref or the SHARED_DATA_REF/
3325 		 * SHARED_BLOCK_REF is found
3326 		 *
3327 		 * Here is a quick path to locate EXTENT/METADATA_ITEM.
3328 		 * It's possible the EXTENT/METADATA_ITEM is near current slot.
3329 		 */
3330 		extent_slot = path->slots[0];
3331 		while (extent_slot >= 0) {
3332 			btrfs_item_key_to_cpu(path->nodes[0], &key,
3333 					      extent_slot);
3334 			if (key.objectid != bytenr)
3335 				break;
3336 			if (key.type == BTRFS_EXTENT_ITEM_KEY &&
3337 			    key.offset == num_bytes) {
3338 				found_extent = true;
3339 				break;
3340 			}
3341 			if (key.type == BTRFS_METADATA_ITEM_KEY &&
3342 			    key.offset == owner_objectid) {
3343 				found_extent = true;
3344 				break;
3345 			}
3346 
3347 			/* Quick path didn't find the EXTENT/METADATA_ITEM */
3348 			if (path->slots[0] - extent_slot > 5)
3349 				break;
3350 			extent_slot--;
3351 		}
3352 
3353 		if (!found_extent) {
3354 			if (unlikely(iref)) {
3355 				abort_and_dump(trans, path,
3356 "invalid iref slot %u, no EXTENT/METADATA_ITEM found but has inline extent ref",
3357 					   path->slots[0]);
3358 				return -EUCLEAN;
3359 			}
3360 			/* Must be SHARED_* item, remove the backref first */
3361 			ret = remove_extent_backref(trans, extent_root, path,
3362 						    NULL, refs_to_drop, is_data);
3363 			if (unlikely(ret)) {
3364 				btrfs_abort_transaction(trans, ret);
3365 				return ret;
3366 			}
3367 			btrfs_release_path(path);
3368 
3369 			/* Slow path to locate EXTENT/METADATA_ITEM */
3370 			key.objectid = bytenr;
3371 			key.type = BTRFS_EXTENT_ITEM_KEY;
3372 			key.offset = num_bytes;
3373 
3374 			if (!is_data && skinny_metadata) {
3375 				key.type = BTRFS_METADATA_ITEM_KEY;
3376 				key.offset = owner_objectid;
3377 			}
3378 
3379 			ret = btrfs_search_slot(trans, extent_root,
3380 						&key, path, -1, 1);
3381 			if (ret > 0 && skinny_metadata && path->slots[0]) {
3382 				/*
3383 				 * Couldn't find our skinny metadata item,
3384 				 * see if we have ye olde extent item.
3385 				 */
3386 				path->slots[0]--;
3387 				btrfs_item_key_to_cpu(path->nodes[0], &key,
3388 						      path->slots[0]);
3389 				if (key.objectid == bytenr &&
3390 				    key.type == BTRFS_EXTENT_ITEM_KEY &&
3391 				    key.offset == num_bytes)
3392 					ret = 0;
3393 			}
3394 
3395 			if (ret > 0 && skinny_metadata) {
3396 				skinny_metadata = false;
3397 				key.objectid = bytenr;
3398 				key.type = BTRFS_EXTENT_ITEM_KEY;
3399 				key.offset = num_bytes;
3400 				btrfs_release_path(path);
3401 				ret = btrfs_search_slot(trans, extent_root,
3402 							&key, path, -1, 1);
3403 			}
3404 
3405 			if (ret) {
3406 				if (ret > 0)
3407 					btrfs_print_leaf(path->nodes[0]);
3408 				btrfs_err(info,
3409 			"umm, got %d back from search, was looking for %llu, slot %d",
3410 					  ret, bytenr, path->slots[0]);
3411 			}
3412 			if (unlikely(ret < 0)) {
3413 				btrfs_abort_transaction(trans, ret);
3414 				return ret;
3415 			}
3416 			extent_slot = path->slots[0];
3417 		}
3418 	} else if (WARN_ON(ret == -ENOENT)) {
3419 		abort_and_dump(trans, path,
3420 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu slot %d",
3421 			       bytenr, node->parent, node->ref_root, owner_objectid,
3422 			       owner_offset, path->slots[0]);
3423 		return ret;
3424 	} else {
3425 		btrfs_abort_transaction(trans, ret);
3426 		return ret;
3427 	}
3428 
3429 	leaf = path->nodes[0];
3430 	item_size = btrfs_item_size(leaf, extent_slot);
3431 	if (unlikely(item_size < sizeof(*ei))) {
3432 		ret = -EUCLEAN;
3433 		btrfs_err(trans->fs_info,
3434 			  "unexpected extent item size, has %u expect >= %zu",
3435 			  item_size, sizeof(*ei));
3436 		btrfs_abort_transaction(trans, ret);
3437 		return ret;
3438 	}
3439 	ei = btrfs_item_ptr(leaf, extent_slot,
3440 			    struct btrfs_extent_item);
3441 	if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
3442 	    key.type == BTRFS_EXTENT_ITEM_KEY) {
3443 		struct btrfs_tree_block_info *bi;
3444 
3445 		if (unlikely(item_size < sizeof(*ei) + sizeof(*bi))) {
3446 			abort_and_dump(trans, path,
3447 "invalid extent item size for key (%llu, %u, %llu) slot %u owner %llu, has %u expect >= %zu",
3448 				       key.objectid, key.type, key.offset,
3449 				       path->slots[0], owner_objectid, item_size,
3450 				       sizeof(*ei) + sizeof(*bi));
3451 			return -EUCLEAN;
3452 		}
3453 		bi = (struct btrfs_tree_block_info *)(ei + 1);
3454 		WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
3455 	}
3456 
3457 	refs = btrfs_extent_refs(leaf, ei);
3458 	if (unlikely(refs < refs_to_drop)) {
3459 		abort_and_dump(trans, path,
3460 		"trying to drop %d refs but we only have %llu for bytenr %llu slot %u",
3461 			       refs_to_drop, refs, bytenr, path->slots[0]);
3462 		return -EUCLEAN;
3463 	}
3464 	refs -= refs_to_drop;
3465 
3466 	if (refs > 0) {
3467 		if (extent_op)
3468 			__run_delayed_extent_op(extent_op, leaf, ei);
3469 		/*
3470 		 * In the case of inline back ref, reference count will
3471 		 * be updated by remove_extent_backref
3472 		 */
3473 		if (iref) {
3474 			if (unlikely(!found_extent)) {
3475 				abort_and_dump(trans, path,
3476 "invalid iref, got inlined extent ref but no EXTENT/METADATA_ITEM found, slot %u",
3477 					       path->slots[0]);
3478 				return -EUCLEAN;
3479 			}
3480 		} else {
3481 			btrfs_set_extent_refs(leaf, ei, refs);
3482 		}
3483 		if (found_extent) {
3484 			ret = remove_extent_backref(trans, extent_root, path,
3485 						    iref, refs_to_drop, is_data);
3486 			if (unlikely(ret)) {
3487 				btrfs_abort_transaction(trans, ret);
3488 				return ret;
3489 			}
3490 		}
3491 	} else {
3492 		struct btrfs_squota_delta delta = {
3493 			.root = delayed_ref_root,
3494 			.num_bytes = num_bytes,
3495 			.is_data = is_data,
3496 			.is_inc = false,
3497 			.generation = btrfs_extent_generation(leaf, ei),
3498 		};
3499 
3500 		/* In this branch refs == 1 */
3501 		if (found_extent) {
3502 			if (unlikely(is_data && refs_to_drop !=
3503 				     extent_data_ref_count(path, iref))) {
3504 				abort_and_dump(trans, path,
3505 		"invalid refs_to_drop, current refs %u refs_to_drop %u slot %u",
3506 					       extent_data_ref_count(path, iref),
3507 					       refs_to_drop, path->slots[0]);
3508 				return -EUCLEAN;
3509 			}
3510 			if (iref) {
3511 				if (unlikely(path->slots[0] != extent_slot)) {
3512 					abort_and_dump(trans, path,
3513 "invalid iref, extent item key " BTRFS_KEY_FMT " slot %u doesn't have wanted iref",
3514 						       BTRFS_KEY_FMT_VALUE(&key),
3515 						       path->slots[0]);
3516 					return -EUCLEAN;
3517 				}
3518 			} else {
3519 				/*
3520 				 * No inline ref, we must be at SHARED_* item,
3521 				 * And it's single ref, it must be:
3522 				 * |	extent_slot	  ||extent_slot + 1|
3523 				 * [ EXTENT/METADATA_ITEM ][ SHARED_* ITEM ]
3524 				 */
3525 				if (unlikely(path->slots[0] != extent_slot + 1)) {
3526 					abort_and_dump(trans, path,
3527 	"invalid SHARED_* item slot %u, previous item is not EXTENT/METADATA_ITEM",
3528 						       path->slots[0]);
3529 					return -EUCLEAN;
3530 				}
3531 				path->slots[0] = extent_slot;
3532 				num_to_del = 2;
3533 			}
3534 		}
3535 		/*
3536 		 * We can't infer the data owner from the delayed ref, so we need
3537 		 * to try to get it from the owning ref item.
3538 		 *
3539 		 * If it is not present, then that extent was not written under
3540 		 * simple quotas mode, so we don't need to account for its deletion.
3541 		 */
3542 		if (is_data)
3543 			delta.root = btrfs_get_extent_owner_root(trans->fs_info,
3544 								 leaf, extent_slot);
3545 
3546 		ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
3547 				      num_to_del);
3548 		if (unlikely(ret)) {
3549 			btrfs_abort_transaction(trans, ret);
3550 			return ret;
3551 		}
3552 		btrfs_release_path(path);
3553 
3554 		ret = do_free_extent_accounting(trans, bytenr, &delta, path);
3555 	}
3556 	btrfs_release_path(path);
3557 
3558 	return ret;
3559 }
3560 
3561 /*
3562  * when we free an block, it is possible (and likely) that we free the last
3563  * delayed ref for that extent as well.  This searches the delayed ref tree for
3564  * a given extent, and if there are no other delayed refs to be processed, it
3565  * removes it from the tree.
3566  */
3567 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
3568 				      u64 bytenr)
3569 {
3570 	struct btrfs_fs_info *fs_info = trans->fs_info;
3571 	struct btrfs_delayed_ref_head *head;
3572 	struct btrfs_delayed_ref_root *delayed_refs;
3573 	int ret = 0;
3574 
3575 	delayed_refs = &trans->transaction->delayed_refs;
3576 	spin_lock(&delayed_refs->lock);
3577 	head = btrfs_find_delayed_ref_head(fs_info, delayed_refs, bytenr);
3578 	if (!head)
3579 		goto out_delayed_unlock;
3580 
3581 	spin_lock(&head->lock);
3582 	if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
3583 		goto out;
3584 
3585 	if (cleanup_extent_op(head) != NULL)
3586 		goto out;
3587 
3588 	/*
3589 	 * waiting for the lock here would deadlock.  If someone else has it
3590 	 * locked they are already in the process of dropping it anyway
3591 	 */
3592 	if (!mutex_trylock(&head->mutex))
3593 		goto out;
3594 
3595 	btrfs_delete_ref_head(fs_info, delayed_refs, head);
3596 	head->processing = false;
3597 
3598 	spin_unlock(&head->lock);
3599 	spin_unlock(&delayed_refs->lock);
3600 
3601 	BUG_ON(head->extent_op);
3602 	if (head->must_insert_reserved)
3603 		ret = 1;
3604 
3605 	btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
3606 	mutex_unlock(&head->mutex);
3607 	btrfs_put_delayed_ref_head(head);
3608 	return ret;
3609 out:
3610 	spin_unlock(&head->lock);
3611 
3612 out_delayed_unlock:
3613 	spin_unlock(&delayed_refs->lock);
3614 	return 0;
3615 }
3616 
3617 int btrfs_free_tree_block(struct btrfs_trans_handle *trans,
3618 			  u64 root_id,
3619 			  struct extent_buffer *buf,
3620 			  u64 parent, int last_ref)
3621 {
3622 	struct btrfs_fs_info *fs_info = trans->fs_info;
3623 	struct btrfs_block_group *bg;
3624 	int ret;
3625 
3626 	if (root_id != BTRFS_TREE_LOG_OBJECTID) {
3627 		struct btrfs_ref generic_ref = {
3628 			.action = BTRFS_DROP_DELAYED_REF,
3629 			.bytenr = buf->start,
3630 			.num_bytes = buf->len,
3631 			.parent = parent,
3632 			.owning_root = btrfs_header_owner(buf),
3633 			.ref_root = root_id,
3634 		};
3635 
3636 		/*
3637 		 * Assert that the extent buffer is not cleared due to
3638 		 * EXTENT_BUFFER_ZONED_ZEROOUT. Please refer
3639 		 * btrfs_clear_buffer_dirty() and btree_csum_one_bio() for
3640 		 * detail.
3641 		 */
3642 		ASSERT(btrfs_header_bytenr(buf) != 0);
3643 
3644 		btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf), 0, false);
3645 		btrfs_ref_tree_mod(fs_info, &generic_ref);
3646 		ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL);
3647 		if (ret < 0)
3648 			return ret;
3649 	}
3650 
3651 	if (!last_ref)
3652 		return 0;
3653 
3654 	if (btrfs_header_generation(buf) != trans->transid)
3655 		return 0;
3656 
3657 	if (root_id != BTRFS_TREE_LOG_OBJECTID) {
3658 		ret = check_ref_cleanup(trans, buf->start);
3659 		if (!ret)
3660 			return 0;
3661 	}
3662 
3663 	bg = btrfs_lookup_block_group(fs_info, buf->start);
3664 
3665 	if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
3666 		pin_down_extent(trans, bg, buf->start, buf->len, true);
3667 		btrfs_put_block_group(bg);
3668 		return 0;
3669 	}
3670 
3671 	/*
3672 	 * If there are tree mod log users we may have recorded mod log
3673 	 * operations for this node.  If we re-allocate this node we
3674 	 * could replay operations on this node that happened when it
3675 	 * existed in a completely different root.  For example if it
3676 	 * was part of root A, then was reallocated to root B, and we
3677 	 * are doing a btrfs_old_search_slot(root b), we could replay
3678 	 * operations that happened when the block was part of root A,
3679 	 * giving us an inconsistent view of the btree.
3680 	 *
3681 	 * We are safe from races here because at this point no other
3682 	 * node or root points to this extent buffer, so if after this
3683 	 * check a new tree mod log user joins we will not have an
3684 	 * existing log of operations on this node that we have to
3685 	 * contend with.
3686 	 */
3687 
3688 	if (test_bit(BTRFS_FS_TREE_MOD_LOG_USERS, &fs_info->flags)
3689 		     || btrfs_is_zoned(fs_info)) {
3690 		pin_down_extent(trans, bg, buf->start, buf->len, true);
3691 		btrfs_put_block_group(bg);
3692 		return 0;
3693 	}
3694 
3695 	WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
3696 
3697 	btrfs_add_free_space(bg, buf->start, buf->len);
3698 	btrfs_free_reserved_bytes(bg, buf->len, false);
3699 	btrfs_put_block_group(bg);
3700 	trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
3701 
3702 	return 0;
3703 }
3704 
3705 /* Can return -ENOMEM */
3706 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
3707 {
3708 	struct btrfs_fs_info *fs_info = trans->fs_info;
3709 	int ret;
3710 
3711 	if (btrfs_is_testing(fs_info))
3712 		return 0;
3713 
3714 	/*
3715 	 * tree log blocks never actually go into the extent allocation
3716 	 * tree, just update pinning info and exit early.
3717 	 */
3718 	if (ref->ref_root == BTRFS_TREE_LOG_OBJECTID) {
3719 		btrfs_pin_extent(trans, ref->bytenr, ref->num_bytes);
3720 		ret = 0;
3721 	} else if (ref->type == BTRFS_REF_METADATA) {
3722 		ret = btrfs_add_delayed_tree_ref(trans, ref, NULL);
3723 	} else {
3724 		ret = btrfs_add_delayed_data_ref(trans, ref, 0);
3725 	}
3726 
3727 	if (ref->ref_root != BTRFS_TREE_LOG_OBJECTID)
3728 		btrfs_ref_tree_mod(fs_info, ref);
3729 
3730 	return ret;
3731 }
3732 
3733 enum btrfs_loop_type {
3734 	/*
3735 	 * Start caching block groups but do not wait for progress or for them
3736 	 * to be done.
3737 	 */
3738 	LOOP_CACHING_NOWAIT,
3739 
3740 	/*
3741 	 * Wait for the block group free_space >= the space we're waiting for if
3742 	 * the block group isn't cached.
3743 	 */
3744 	LOOP_CACHING_WAIT,
3745 
3746 	/*
3747 	 * Allow allocations to happen from block groups that do not yet have a
3748 	 * size classification.
3749 	 */
3750 	LOOP_UNSET_SIZE_CLASS,
3751 
3752 	/*
3753 	 * Allocate a chunk and then retry the allocation.
3754 	 */
3755 	LOOP_ALLOC_CHUNK,
3756 
3757 	/*
3758 	 * Ignore the size class restrictions for this allocation.
3759 	 */
3760 	LOOP_WRONG_SIZE_CLASS,
3761 
3762 	/*
3763 	 * Ignore the empty size, only try to allocate the number of bytes
3764 	 * needed for this allocation.
3765 	 */
3766 	LOOP_NO_EMPTY_SIZE,
3767 };
3768 
3769 static inline void
3770 btrfs_lock_block_group(struct btrfs_block_group *cache, bool delalloc)
3771 {
3772 	if (delalloc)
3773 		down_read(&cache->data_rwsem);
3774 }
3775 
3776 static inline void btrfs_grab_block_group(struct btrfs_block_group *cache,
3777 					  bool delalloc)
3778 {
3779 	btrfs_get_block_group(cache);
3780 	if (delalloc)
3781 		down_read(&cache->data_rwsem);
3782 }
3783 
3784 static struct btrfs_block_group *btrfs_lock_cluster(
3785 		   struct btrfs_block_group *block_group,
3786 		   struct btrfs_free_cluster *cluster,
3787 		   bool delalloc)
3788 	__acquires(&cluster->refill_lock)
3789 {
3790 	struct btrfs_block_group *used_bg = NULL;
3791 
3792 	spin_lock(&cluster->refill_lock);
3793 	while (1) {
3794 		used_bg = cluster->block_group;
3795 		if (!used_bg)
3796 			return NULL;
3797 
3798 		if (used_bg == block_group)
3799 			return used_bg;
3800 
3801 		btrfs_get_block_group(used_bg);
3802 
3803 		if (!delalloc)
3804 			return used_bg;
3805 
3806 		if (down_read_trylock(&used_bg->data_rwsem))
3807 			return used_bg;
3808 
3809 		spin_unlock(&cluster->refill_lock);
3810 
3811 		/* We should only have one-level nested. */
3812 		down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
3813 
3814 		spin_lock(&cluster->refill_lock);
3815 		if (used_bg == cluster->block_group)
3816 			return used_bg;
3817 
3818 		up_read(&used_bg->data_rwsem);
3819 		btrfs_put_block_group(used_bg);
3820 	}
3821 }
3822 
3823 static inline void
3824 btrfs_release_block_group(struct btrfs_block_group *cache, bool delalloc)
3825 {
3826 	if (delalloc)
3827 		up_read(&cache->data_rwsem);
3828 	btrfs_put_block_group(cache);
3829 }
3830 
3831 static bool find_free_extent_check_size_class(const struct find_free_extent_ctl *ffe_ctl,
3832 					      const struct btrfs_block_group *bg)
3833 {
3834 	if (ffe_ctl->policy == BTRFS_EXTENT_ALLOC_ZONED)
3835 		return true;
3836 	if (!btrfs_block_group_should_use_size_class(bg))
3837 		return true;
3838 	if (ffe_ctl->loop >= LOOP_WRONG_SIZE_CLASS)
3839 		return true;
3840 	if (ffe_ctl->loop >= LOOP_UNSET_SIZE_CLASS &&
3841 	    bg->size_class == BTRFS_BG_SZ_NONE)
3842 		return true;
3843 	return ffe_ctl->size_class == bg->size_class;
3844 }
3845 
3846 /*
3847  * Helper function for find_free_extent().
3848  *
3849  * Return -ENOENT to inform caller that we need fallback to unclustered mode.
3850  * Return >0 to inform caller that we find nothing
3851  * Return 0 means we have found a location and set ffe_ctl->found_offset.
3852  */
3853 static int find_free_extent_clustered(struct btrfs_block_group *bg,
3854 				      struct find_free_extent_ctl *ffe_ctl,
3855 				      struct btrfs_block_group **cluster_bg_ret)
3856 {
3857 	struct btrfs_block_group *cluster_bg;
3858 	struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3859 	u64 aligned_cluster;
3860 	u64 offset;
3861 	int ret;
3862 
3863 	cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
3864 	if (!cluster_bg)
3865 		goto refill_cluster;
3866 	if (cluster_bg != bg && (cluster_bg->ro ||
3867 	    !block_group_bits(cluster_bg, ffe_ctl->flags) ||
3868 	    !find_free_extent_check_size_class(ffe_ctl, cluster_bg)))
3869 		goto release_cluster;
3870 
3871 	offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
3872 			ffe_ctl->num_bytes, cluster_bg->start,
3873 			&ffe_ctl->max_extent_size);
3874 	if (offset) {
3875 		/* We have a block, we're done */
3876 		spin_unlock(&last_ptr->refill_lock);
3877 		trace_btrfs_reserve_extent_cluster(cluster_bg, ffe_ctl);
3878 		*cluster_bg_ret = cluster_bg;
3879 		ffe_ctl->found_offset = offset;
3880 		return 0;
3881 	}
3882 	WARN_ON(last_ptr->block_group != cluster_bg);
3883 
3884 release_cluster:
3885 	/*
3886 	 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
3887 	 * lets just skip it and let the allocator find whatever block it can
3888 	 * find. If we reach this point, we will have tried the cluster
3889 	 * allocator plenty of times and not have found anything, so we are
3890 	 * likely way too fragmented for the clustering stuff to find anything.
3891 	 *
3892 	 * However, if the cluster is taken from the current block group,
3893 	 * release the cluster first, so that we stand a better chance of
3894 	 * succeeding in the unclustered allocation.
3895 	 */
3896 	if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
3897 		spin_unlock(&last_ptr->refill_lock);
3898 		btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3899 		return -ENOENT;
3900 	}
3901 
3902 	/* This cluster didn't work out, free it and start over */
3903 	btrfs_return_cluster_to_free_space(NULL, last_ptr);
3904 
3905 	if (cluster_bg != bg)
3906 		btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3907 
3908 refill_cluster:
3909 	if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
3910 		spin_unlock(&last_ptr->refill_lock);
3911 		return -ENOENT;
3912 	}
3913 
3914 	aligned_cluster = max_t(u64,
3915 			ffe_ctl->empty_cluster + ffe_ctl->empty_size,
3916 			bg->full_stripe_len);
3917 	ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
3918 			ffe_ctl->num_bytes, aligned_cluster);
3919 	if (ret == 0) {
3920 		/* Now pull our allocation out of this cluster */
3921 		offset = btrfs_alloc_from_cluster(bg, last_ptr,
3922 				ffe_ctl->num_bytes, ffe_ctl->search_start,
3923 				&ffe_ctl->max_extent_size);
3924 		if (offset) {
3925 			/* We found one, proceed */
3926 			spin_unlock(&last_ptr->refill_lock);
3927 			ffe_ctl->found_offset = offset;
3928 			trace_btrfs_reserve_extent_cluster(bg, ffe_ctl);
3929 			return 0;
3930 		}
3931 	}
3932 	/*
3933 	 * At this point we either didn't find a cluster or we weren't able to
3934 	 * allocate a block from our cluster.  Free the cluster we've been
3935 	 * trying to use, and go to the next block group.
3936 	 */
3937 	btrfs_return_cluster_to_free_space(NULL, last_ptr);
3938 	spin_unlock(&last_ptr->refill_lock);
3939 	return 1;
3940 }
3941 
3942 /*
3943  * Return >0 to inform caller that we find nothing
3944  * Return 0 when we found an free extent and set ffe_ctrl->found_offset
3945  */
3946 static int find_free_extent_unclustered(struct btrfs_block_group *bg,
3947 					struct find_free_extent_ctl *ffe_ctl)
3948 {
3949 	struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3950 	u64 offset;
3951 
3952 	/*
3953 	 * We are doing an unclustered allocation, set the fragmented flag so
3954 	 * we don't bother trying to setup a cluster again until we get more
3955 	 * space.
3956 	 */
3957 	if (unlikely(last_ptr)) {
3958 		spin_lock(&last_ptr->lock);
3959 		last_ptr->fragmented = 1;
3960 		spin_unlock(&last_ptr->lock);
3961 	}
3962 	if (ffe_ctl->cached) {
3963 		struct btrfs_free_space_ctl *free_space_ctl;
3964 
3965 		free_space_ctl = bg->free_space_ctl;
3966 		spin_lock(&free_space_ctl->tree_lock);
3967 		if (free_space_ctl->free_space <
3968 		    ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
3969 		    ffe_ctl->empty_size) {
3970 			ffe_ctl->total_free_space = max_t(u64,
3971 					ffe_ctl->total_free_space,
3972 					free_space_ctl->free_space);
3973 			spin_unlock(&free_space_ctl->tree_lock);
3974 			return 1;
3975 		}
3976 		spin_unlock(&free_space_ctl->tree_lock);
3977 	}
3978 
3979 	offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
3980 			ffe_ctl->num_bytes, ffe_ctl->empty_size,
3981 			&ffe_ctl->max_extent_size);
3982 	if (!offset)
3983 		return 1;
3984 	ffe_ctl->found_offset = offset;
3985 	return 0;
3986 }
3987 
3988 static int do_allocation_clustered(struct btrfs_block_group *block_group,
3989 				   struct find_free_extent_ctl *ffe_ctl,
3990 				   struct btrfs_block_group **bg_ret)
3991 {
3992 	int ret;
3993 
3994 	/* We want to try and use the cluster allocator, so lets look there */
3995 	if (ffe_ctl->last_ptr && ffe_ctl->use_cluster) {
3996 		ret = find_free_extent_clustered(block_group, ffe_ctl, bg_ret);
3997 		if (ret >= 0)
3998 			return ret;
3999 		/* ret == -ENOENT case falls through */
4000 	}
4001 
4002 	return find_free_extent_unclustered(block_group, ffe_ctl);
4003 }
4004 
4005 /*
4006  * Tree-log block group locking
4007  * ============================
4008  *
4009  * fs_info::treelog_bg_lock protects the fs_info::treelog_bg which
4010  * indicates the starting address of a block group, which is reserved only
4011  * for tree-log metadata.
4012  *
4013  * Lock nesting
4014  * ============
4015  *
4016  * block_group::lock
4017  *   fs_info::treelog_bg_lock
4018  */
4019 
4020 /*
4021  * Simple allocator for sequential-only block group. It only allows sequential
4022  * allocation. No need to play with trees. This function also reserves the
4023  * bytes as in btrfs_add_reserved_bytes.
4024  */
4025 static int do_allocation_zoned(struct btrfs_block_group *block_group,
4026 			       struct find_free_extent_ctl *ffe_ctl,
4027 			       struct btrfs_block_group **bg_ret)
4028 {
4029 	struct btrfs_fs_info *fs_info = block_group->fs_info;
4030 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
4031 	u64 start = block_group->start;
4032 	u64 num_bytes = ffe_ctl->num_bytes;
4033 	u64 avail;
4034 	u64 bytenr = block_group->start;
4035 	u64 log_bytenr;
4036 	u64 data_reloc_bytenr;
4037 	int ret = 0;
4038 	bool skip = false;
4039 
4040 	ASSERT(btrfs_is_zoned(block_group->fs_info));
4041 
4042 	/*
4043 	 * Do not allow non-tree-log blocks in the dedicated tree-log block
4044 	 * group, and vice versa.
4045 	 */
4046 	spin_lock(&fs_info->treelog_bg_lock);
4047 	log_bytenr = fs_info->treelog_bg;
4048 	if (log_bytenr && ((ffe_ctl->for_treelog && bytenr != log_bytenr) ||
4049 			   (!ffe_ctl->for_treelog && bytenr == log_bytenr)))
4050 		skip = true;
4051 	spin_unlock(&fs_info->treelog_bg_lock);
4052 	if (skip)
4053 		return 1;
4054 
4055 	/*
4056 	 * Do not allow non-relocation blocks in the dedicated relocation block
4057 	 * group, and vice versa.
4058 	 */
4059 	spin_lock(&fs_info->relocation_bg_lock);
4060 	data_reloc_bytenr = fs_info->data_reloc_bg;
4061 	if (data_reloc_bytenr &&
4062 	    ((ffe_ctl->for_data_reloc && bytenr != data_reloc_bytenr) ||
4063 	     (!ffe_ctl->for_data_reloc && bytenr == data_reloc_bytenr)))
4064 		skip = true;
4065 	spin_unlock(&fs_info->relocation_bg_lock);
4066 	if (skip)
4067 		return 1;
4068 
4069 	/* Check RO and no space case before trying to activate it */
4070 	spin_lock(&block_group->lock);
4071 	if (block_group->ro || btrfs_zoned_bg_is_full(block_group)) {
4072 		ret = 1;
4073 		/*
4074 		 * May need to clear fs_info->{treelog,data_reloc}_bg.
4075 		 * Return the error after taking the locks.
4076 		 */
4077 	}
4078 	spin_unlock(&block_group->lock);
4079 
4080 	/* Metadata block group is activated at write time. */
4081 	if (!ret && (block_group->flags & BTRFS_BLOCK_GROUP_DATA) &&
4082 	    !btrfs_zone_activate(block_group)) {
4083 		ret = 1;
4084 		/*
4085 		 * May need to clear fs_info->{treelog,data_reloc}_bg.
4086 		 * Return the error after taking the locks.
4087 		 */
4088 	}
4089 
4090 	spin_lock(&block_group->lock);
4091 	spin_lock(&fs_info->treelog_bg_lock);
4092 	spin_lock(&fs_info->relocation_bg_lock);
4093 
4094 	if (ret)
4095 		goto out;
4096 
4097 	ASSERT(!ffe_ctl->for_treelog ||
4098 	       block_group->start == fs_info->treelog_bg ||
4099 	       fs_info->treelog_bg == 0);
4100 	ASSERT(!ffe_ctl->for_data_reloc ||
4101 	       block_group->start == fs_info->data_reloc_bg ||
4102 	       fs_info->data_reloc_bg == 0);
4103 
4104 	if (block_group->ro ||
4105 	    (!ffe_ctl->for_data_reloc &&
4106 	     test_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags))) {
4107 		ret = 1;
4108 		goto out;
4109 	}
4110 
4111 	/*
4112 	 * Do not allow currently using block group to be tree-log dedicated
4113 	 * block group.
4114 	 */
4115 	if (ffe_ctl->for_treelog && !fs_info->treelog_bg &&
4116 	    (block_group->used || block_group->reserved)) {
4117 		ret = 1;
4118 		goto out;
4119 	}
4120 
4121 	/*
4122 	 * Do not allow currently used block group to be the data relocation
4123 	 * dedicated block group.
4124 	 */
4125 	if (ffe_ctl->for_data_reloc && !fs_info->data_reloc_bg &&
4126 	    (block_group->used || block_group->reserved)) {
4127 		ret = 1;
4128 		goto out;
4129 	}
4130 
4131 	WARN_ON_ONCE(block_group->alloc_offset > block_group->zone_capacity);
4132 	avail = block_group->zone_capacity - block_group->alloc_offset;
4133 	if (avail < num_bytes) {
4134 		if (ffe_ctl->max_extent_size < avail) {
4135 			/*
4136 			 * With sequential allocator, free space is always
4137 			 * contiguous
4138 			 */
4139 			ffe_ctl->max_extent_size = avail;
4140 			ffe_ctl->total_free_space = avail;
4141 		}
4142 		ret = 1;
4143 		goto out;
4144 	}
4145 
4146 	if (ffe_ctl->for_treelog && !fs_info->treelog_bg)
4147 		fs_info->treelog_bg = block_group->start;
4148 
4149 	if (ffe_ctl->for_data_reloc) {
4150 		if (!fs_info->data_reloc_bg)
4151 			fs_info->data_reloc_bg = block_group->start;
4152 		/*
4153 		 * Do not allow allocations from this block group, unless it is
4154 		 * for data relocation. Compared to increasing the ->ro, setting
4155 		 * the ->zoned_data_reloc_ongoing flag still allows nocow
4156 		 * writers to come in. See btrfs_inc_nocow_writers().
4157 		 *
4158 		 * We need to disable an allocation to avoid an allocation of
4159 		 * regular (non-relocation data) extent. With mix of relocation
4160 		 * extents and regular extents, we can dispatch WRITE commands
4161 		 * (for relocation extents) and ZONE APPEND commands (for
4162 		 * regular extents) at the same time to the same zone, which
4163 		 * easily break the write pointer.
4164 		 *
4165 		 * Also, this flag avoids this block group to be zone finished.
4166 		 */
4167 		set_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags);
4168 	}
4169 
4170 	ffe_ctl->found_offset = start + block_group->alloc_offset;
4171 	block_group->alloc_offset += num_bytes;
4172 	spin_lock(&ctl->tree_lock);
4173 	ctl->free_space -= num_bytes;
4174 	spin_unlock(&ctl->tree_lock);
4175 
4176 	/*
4177 	 * We do not check if found_offset is aligned to stripesize. The
4178 	 * address is anyway rewritten when using zone append writing.
4179 	 */
4180 
4181 	ffe_ctl->search_start = ffe_ctl->found_offset;
4182 
4183 out:
4184 	if (ret && ffe_ctl->for_treelog)
4185 		fs_info->treelog_bg = 0;
4186 	if (ret && ffe_ctl->for_data_reloc)
4187 		fs_info->data_reloc_bg = 0;
4188 	spin_unlock(&fs_info->relocation_bg_lock);
4189 	spin_unlock(&fs_info->treelog_bg_lock);
4190 	spin_unlock(&block_group->lock);
4191 	return ret;
4192 }
4193 
4194 static int do_allocation(struct btrfs_block_group *block_group,
4195 			 struct find_free_extent_ctl *ffe_ctl,
4196 			 struct btrfs_block_group **bg_ret)
4197 {
4198 	switch (ffe_ctl->policy) {
4199 	case BTRFS_EXTENT_ALLOC_CLUSTERED:
4200 		return do_allocation_clustered(block_group, ffe_ctl, bg_ret);
4201 	case BTRFS_EXTENT_ALLOC_ZONED:
4202 		return do_allocation_zoned(block_group, ffe_ctl, bg_ret);
4203 	default:
4204 		BUG();
4205 	}
4206 }
4207 
4208 static void release_block_group(struct btrfs_block_group *block_group,
4209 				struct find_free_extent_ctl *ffe_ctl,
4210 				bool delalloc)
4211 {
4212 	switch (ffe_ctl->policy) {
4213 	case BTRFS_EXTENT_ALLOC_CLUSTERED:
4214 		ffe_ctl->retry_uncached = false;
4215 		break;
4216 	case BTRFS_EXTENT_ALLOC_ZONED:
4217 		/* Nothing to do */
4218 		break;
4219 	default:
4220 		BUG();
4221 	}
4222 
4223 	BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
4224 	       ffe_ctl->index);
4225 	btrfs_release_block_group(block_group, delalloc);
4226 }
4227 
4228 static void found_extent_clustered(struct find_free_extent_ctl *ffe_ctl,
4229 				   struct btrfs_key *ins)
4230 {
4231 	struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
4232 
4233 	if (!ffe_ctl->use_cluster && last_ptr) {
4234 		spin_lock(&last_ptr->lock);
4235 		last_ptr->window_start = ins->objectid;
4236 		spin_unlock(&last_ptr->lock);
4237 	}
4238 }
4239 
4240 static void found_extent(struct find_free_extent_ctl *ffe_ctl,
4241 			 struct btrfs_key *ins)
4242 {
4243 	switch (ffe_ctl->policy) {
4244 	case BTRFS_EXTENT_ALLOC_CLUSTERED:
4245 		found_extent_clustered(ffe_ctl, ins);
4246 		break;
4247 	case BTRFS_EXTENT_ALLOC_ZONED:
4248 		/* Nothing to do */
4249 		break;
4250 	default:
4251 		BUG();
4252 	}
4253 }
4254 
4255 static int can_allocate_chunk_zoned(struct btrfs_fs_info *fs_info,
4256 				    struct find_free_extent_ctl *ffe_ctl)
4257 {
4258 	/* Block group's activeness is not a requirement for METADATA block groups. */
4259 	if (!(ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA))
4260 		return 0;
4261 
4262 	/* If we can activate new zone, just allocate a chunk and use it */
4263 	if (btrfs_can_activate_zone(fs_info->fs_devices, ffe_ctl->flags))
4264 		return 0;
4265 
4266 	/*
4267 	 * We already reached the max active zones. Try to finish one block
4268 	 * group to make a room for a new block group. This is only possible
4269 	 * for a data block group because btrfs_zone_finish() may need to wait
4270 	 * for a running transaction which can cause a deadlock for metadata
4271 	 * allocation.
4272 	 */
4273 	if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA) {
4274 		int ret = btrfs_zone_finish_one_bg(fs_info);
4275 
4276 		if (ret == 1)
4277 			return 0;
4278 		else if (ret < 0)
4279 			return ret;
4280 	}
4281 
4282 	/*
4283 	 * If we have enough free space left in an already active block group
4284 	 * and we can't activate any other zone now, do not allow allocating a
4285 	 * new chunk and let find_free_extent() retry with a smaller size.
4286 	 */
4287 	if (ffe_ctl->max_extent_size >= ffe_ctl->min_alloc_size)
4288 		return -ENOSPC;
4289 
4290 	/*
4291 	 * Even min_alloc_size is not left in any block groups. Since we cannot
4292 	 * activate a new block group, allocating it may not help. Let's tell a
4293 	 * caller to try again and hope it progress something by writing some
4294 	 * parts of the region. That is only possible for data block groups,
4295 	 * where a part of the region can be written.
4296 	 */
4297 	if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA)
4298 		return -EAGAIN;
4299 
4300 	/*
4301 	 * We cannot activate a new block group and no enough space left in any
4302 	 * block groups. So, allocating a new block group may not help. But,
4303 	 * there is nothing to do anyway, so let's go with it.
4304 	 */
4305 	return 0;
4306 }
4307 
4308 static int can_allocate_chunk(struct btrfs_fs_info *fs_info,
4309 			      struct find_free_extent_ctl *ffe_ctl)
4310 {
4311 	switch (ffe_ctl->policy) {
4312 	case BTRFS_EXTENT_ALLOC_CLUSTERED:
4313 		return 0;
4314 	case BTRFS_EXTENT_ALLOC_ZONED:
4315 		return can_allocate_chunk_zoned(fs_info, ffe_ctl);
4316 	default:
4317 		BUG();
4318 	}
4319 }
4320 
4321 /*
4322  * Return >0 means caller needs to re-search for free extent
4323  * Return 0 means we have the needed free extent.
4324  * Return <0 means we failed to locate any free extent.
4325  */
4326 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
4327 					struct btrfs_key *ins,
4328 					struct find_free_extent_ctl *ffe_ctl,
4329 					struct btrfs_space_info *space_info,
4330 					bool full_search)
4331 {
4332 	struct btrfs_root *root = fs_info->chunk_root;
4333 	int ret;
4334 
4335 	if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
4336 	    ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
4337 		ffe_ctl->orig_have_caching_bg = true;
4338 
4339 	if (ins->objectid) {
4340 		found_extent(ffe_ctl, ins);
4341 		return 0;
4342 	}
4343 
4344 	if (ffe_ctl->loop >= LOOP_CACHING_WAIT && ffe_ctl->have_caching_bg)
4345 		return 1;
4346 
4347 	ffe_ctl->index++;
4348 	if (ffe_ctl->index < BTRFS_NR_RAID_TYPES)
4349 		return 1;
4350 
4351 	/* See the comments for btrfs_loop_type for an explanation of the phases. */
4352 	if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE)
4353 		return -ENOSPC;
4354 
4355 	ffe_ctl->index = 0;
4356 	/*
4357 	 * We want to skip the LOOP_CACHING_WAIT step if we don't have any
4358 	 * uncached bgs and we've already done a full search through.
4359 	 */
4360 	if (ffe_ctl->loop == LOOP_CACHING_NOWAIT &&
4361 	    (!ffe_ctl->orig_have_caching_bg && full_search))
4362 		ffe_ctl->loop++;
4363 	ffe_ctl->loop++;
4364 
4365 	if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
4366 		struct btrfs_trans_handle *trans;
4367 		bool have_trans = false;
4368 
4369 		/* Check if allocation policy allows to create a new chunk. */
4370 		ret = can_allocate_chunk(fs_info, ffe_ctl);
4371 		if (ret)
4372 			return ret;
4373 
4374 		trans = current->journal_info;
4375 		if (trans)
4376 			have_trans = true;
4377 		else
4378 			trans = btrfs_join_transaction(root);
4379 
4380 		if (IS_ERR(trans))
4381 			return PTR_ERR(trans);
4382 
4383 		ret = btrfs_chunk_alloc(trans, space_info, ffe_ctl->flags,
4384 					CHUNK_ALLOC_FORCE_FOR_EXTENT);
4385 
4386 		/* Do not bail out on ENOSPC since we can do more. */
4387 		if (ret == -ENOSPC) {
4388 			ret = 0;
4389 			ffe_ctl->loop++;
4390 		} else if (ret < 0) {
4391 			btrfs_abort_transaction(trans, ret);
4392 		} else {
4393 			ret = 0;
4394 		}
4395 
4396 		if (!have_trans)
4397 			btrfs_end_transaction(trans);
4398 
4399 		if (ret)
4400 			return ret;
4401 	}
4402 
4403 	if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
4404 		if (ffe_ctl->policy != BTRFS_EXTENT_ALLOC_CLUSTERED)
4405 			return -ENOSPC;
4406 
4407 		/*
4408 		 * Don't loop again if we already have no empty_size and
4409 		 * no empty_cluster.
4410 		 */
4411 		if (ffe_ctl->empty_size == 0 && ffe_ctl->empty_cluster == 0)
4412 			return -ENOSPC;
4413 		ffe_ctl->empty_size = 0;
4414 		ffe_ctl->empty_cluster = 0;
4415 	}
4416 
4417 	return 1;
4418 }
4419 
4420 static int prepare_allocation_clustered(struct btrfs_fs_info *fs_info,
4421 					struct find_free_extent_ctl *ffe_ctl,
4422 					struct btrfs_space_info *space_info,
4423 					struct btrfs_key *ins)
4424 {
4425 	/*
4426 	 * If our free space is heavily fragmented we may not be able to make
4427 	 * big contiguous allocations, so instead of doing the expensive search
4428 	 * for free space, simply return ENOSPC with our max_extent_size so we
4429 	 * can go ahead and search for a more manageable chunk.
4430 	 *
4431 	 * If our max_extent_size is large enough for our allocation simply
4432 	 * disable clustering since we will likely not be able to find enough
4433 	 * space to create a cluster and induce latency trying.
4434 	 */
4435 	if (space_info->max_extent_size) {
4436 		spin_lock(&space_info->lock);
4437 		if (space_info->max_extent_size &&
4438 		    ffe_ctl->num_bytes > space_info->max_extent_size) {
4439 			ins->offset = space_info->max_extent_size;
4440 			spin_unlock(&space_info->lock);
4441 			return -ENOSPC;
4442 		} else if (space_info->max_extent_size) {
4443 			ffe_ctl->use_cluster = false;
4444 		}
4445 		spin_unlock(&space_info->lock);
4446 	}
4447 
4448 	ffe_ctl->last_ptr = fetch_cluster_info(fs_info, space_info,
4449 					       &ffe_ctl->empty_cluster);
4450 	if (ffe_ctl->last_ptr) {
4451 		struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
4452 
4453 		spin_lock(&last_ptr->lock);
4454 		if (last_ptr->block_group)
4455 			ffe_ctl->hint_byte = last_ptr->window_start;
4456 		if (last_ptr->fragmented) {
4457 			/*
4458 			 * We still set window_start so we can keep track of the
4459 			 * last place we found an allocation to try and save
4460 			 * some time.
4461 			 */
4462 			ffe_ctl->hint_byte = last_ptr->window_start;
4463 			ffe_ctl->use_cluster = false;
4464 		}
4465 		spin_unlock(&last_ptr->lock);
4466 	}
4467 
4468 	return 0;
4469 }
4470 
4471 static int prepare_allocation_zoned(struct btrfs_fs_info *fs_info,
4472 				    struct find_free_extent_ctl *ffe_ctl,
4473 				    struct btrfs_space_info *space_info)
4474 {
4475 	struct btrfs_block_group *block_group;
4476 
4477 	if (ffe_ctl->for_treelog) {
4478 		spin_lock(&fs_info->treelog_bg_lock);
4479 		if (fs_info->treelog_bg)
4480 			ffe_ctl->hint_byte = fs_info->treelog_bg;
4481 		spin_unlock(&fs_info->treelog_bg_lock);
4482 		return 0;
4483 	}
4484 
4485 	if (ffe_ctl->for_data_reloc) {
4486 		spin_lock(&fs_info->relocation_bg_lock);
4487 		if (fs_info->data_reloc_bg)
4488 			ffe_ctl->hint_byte = fs_info->data_reloc_bg;
4489 		spin_unlock(&fs_info->relocation_bg_lock);
4490 		return 0;
4491 	}
4492 
4493 	if (!(ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA))
4494 		return 0;
4495 
4496 	spin_lock(&fs_info->zone_active_bgs_lock);
4497 	list_for_each_entry(block_group, &fs_info->zone_active_bgs, active_bg_list) {
4498 		/*
4499 		 * No lock is OK here because avail is monotonically
4500 		 * decreasing, and this is just a hint.
4501 		 */
4502 		u64 avail = block_group->zone_capacity - block_group->alloc_offset;
4503 
4504 		if (block_group_bits(block_group, ffe_ctl->flags) &&
4505 		    block_group->space_info == space_info &&
4506 		    avail >= ffe_ctl->num_bytes) {
4507 			ffe_ctl->hint_byte = block_group->start;
4508 			break;
4509 		}
4510 	}
4511 	spin_unlock(&fs_info->zone_active_bgs_lock);
4512 
4513 	return 0;
4514 }
4515 
4516 static int prepare_allocation(struct btrfs_fs_info *fs_info,
4517 			      struct find_free_extent_ctl *ffe_ctl,
4518 			      struct btrfs_space_info *space_info,
4519 			      struct btrfs_key *ins)
4520 {
4521 	switch (ffe_ctl->policy) {
4522 	case BTRFS_EXTENT_ALLOC_CLUSTERED:
4523 		return prepare_allocation_clustered(fs_info, ffe_ctl,
4524 						    space_info, ins);
4525 	case BTRFS_EXTENT_ALLOC_ZONED:
4526 		return prepare_allocation_zoned(fs_info, ffe_ctl, space_info);
4527 	default:
4528 		BUG();
4529 	}
4530 }
4531 
4532 /*
4533  * walks the btree of allocated extents and find a hole of a given size.
4534  * The key ins is changed to record the hole:
4535  * ins->objectid == start position
4536  * ins->flags = BTRFS_EXTENT_ITEM_KEY
4537  * ins->offset == the size of the hole.
4538  * Any available blocks before search_start are skipped.
4539  *
4540  * If there is no suitable free space, we will record the max size of
4541  * the free space extent currently.
4542  *
4543  * The overall logic and call chain:
4544  *
4545  * find_free_extent()
4546  * |- Iterate through all block groups
4547  * |  |- Get a valid block group
4548  * |  |- Try to do clustered allocation in that block group
4549  * |  |- Try to do unclustered allocation in that block group
4550  * |  |- Check if the result is valid
4551  * |  |  |- If valid, then exit
4552  * |  |- Jump to next block group
4553  * |
4554  * |- Push harder to find free extents
4555  *    |- If not found, re-iterate all block groups
4556  */
4557 static noinline int find_free_extent(struct btrfs_root *root,
4558 				     struct btrfs_key *ins,
4559 				     struct find_free_extent_ctl *ffe_ctl)
4560 {
4561 	struct btrfs_fs_info *fs_info = root->fs_info;
4562 	int ret = 0;
4563 	int cache_block_group_error = 0;
4564 	struct btrfs_block_group *block_group = NULL;
4565 	struct btrfs_space_info *space_info;
4566 	bool full_search = false;
4567 
4568 	WARN_ON(ffe_ctl->num_bytes < fs_info->sectorsize);
4569 
4570 	ffe_ctl->search_start = 0;
4571 	/* For clustered allocation */
4572 	ffe_ctl->empty_cluster = 0;
4573 	ffe_ctl->last_ptr = NULL;
4574 	ffe_ctl->use_cluster = true;
4575 	ffe_ctl->have_caching_bg = false;
4576 	ffe_ctl->orig_have_caching_bg = false;
4577 	ffe_ctl->index = btrfs_bg_flags_to_raid_index(ffe_ctl->flags);
4578 	ffe_ctl->loop = 0;
4579 	ffe_ctl->retry_uncached = false;
4580 	ffe_ctl->cached = 0;
4581 	ffe_ctl->max_extent_size = 0;
4582 	ffe_ctl->total_free_space = 0;
4583 	ffe_ctl->found_offset = 0;
4584 	ffe_ctl->policy = BTRFS_EXTENT_ALLOC_CLUSTERED;
4585 	ffe_ctl->size_class = btrfs_calc_block_group_size_class(ffe_ctl->num_bytes);
4586 
4587 	if (btrfs_is_zoned(fs_info))
4588 		ffe_ctl->policy = BTRFS_EXTENT_ALLOC_ZONED;
4589 
4590 	ins->type = BTRFS_EXTENT_ITEM_KEY;
4591 	ins->objectid = 0;
4592 	ins->offset = 0;
4593 
4594 	trace_btrfs_find_free_extent(root, ffe_ctl);
4595 
4596 	space_info = btrfs_find_space_info(fs_info, ffe_ctl->flags);
4597 	if (btrfs_is_zoned(fs_info) && space_info) {
4598 		/* Use dedicated sub-space_info for dedicated block group users. */
4599 		if (ffe_ctl->for_data_reloc) {
4600 			space_info = space_info->sub_group[0];
4601 			ASSERT(space_info->subgroup_id == BTRFS_SUB_GROUP_DATA_RELOC,
4602 			       "space_info->subgroup_id=%d", space_info->subgroup_id);
4603 		} else if (ffe_ctl->for_treelog) {
4604 			space_info = space_info->sub_group[0];
4605 			ASSERT(space_info->subgroup_id == BTRFS_SUB_GROUP_TREELOG,
4606 			       "space_info->subgroup_id=%d", space_info->subgroup_id);
4607 		}
4608 	}
4609 	if (!space_info) {
4610 		btrfs_err(fs_info, "no space info for %llu, tree-log %d, relocation %d",
4611 			  ffe_ctl->flags, ffe_ctl->for_treelog, ffe_ctl->for_data_reloc);
4612 		return -ENOSPC;
4613 	}
4614 
4615 	ret = prepare_allocation(fs_info, ffe_ctl, space_info, ins);
4616 	if (ret < 0)
4617 		return ret;
4618 
4619 	ffe_ctl->search_start = max(ffe_ctl->search_start,
4620 				    first_logical_byte(fs_info));
4621 	ffe_ctl->search_start = max(ffe_ctl->search_start, ffe_ctl->hint_byte);
4622 	if (ffe_ctl->search_start == ffe_ctl->hint_byte) {
4623 		block_group = btrfs_lookup_block_group(fs_info,
4624 						       ffe_ctl->search_start);
4625 		/*
4626 		 * we don't want to use the block group if it doesn't match our
4627 		 * allocation bits, or if its not cached.
4628 		 *
4629 		 * However if we are re-searching with an ideal block group
4630 		 * picked out then we don't care that the block group is cached.
4631 		 */
4632 		if (block_group && block_group_bits(block_group, ffe_ctl->flags) &&
4633 		    block_group->space_info == space_info &&
4634 		    block_group->cached != BTRFS_CACHE_NO) {
4635 			down_read(&space_info->groups_sem);
4636 			if (list_empty(&block_group->list) ||
4637 			    block_group->ro ||
4638 			    (block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED)) {
4639 				/*
4640 				 * someone is removing this block group,
4641 				 * we can't jump into the have_block_group
4642 				 * target because our list pointers are not
4643 				 * valid
4644 				 */
4645 				btrfs_put_block_group(block_group);
4646 				up_read(&space_info->groups_sem);
4647 			} else {
4648 				ffe_ctl->index = btrfs_bg_flags_to_raid_index(
4649 							block_group->flags);
4650 				btrfs_lock_block_group(block_group,
4651 						       ffe_ctl->delalloc);
4652 				ffe_ctl->hinted = true;
4653 				goto have_block_group;
4654 			}
4655 		} else if (block_group) {
4656 			btrfs_put_block_group(block_group);
4657 		}
4658 	}
4659 search:
4660 	trace_btrfs_find_free_extent_search_loop(root, ffe_ctl);
4661 	ffe_ctl->have_caching_bg = false;
4662 	if (ffe_ctl->index == btrfs_bg_flags_to_raid_index(ffe_ctl->flags) ||
4663 	    ffe_ctl->index == 0)
4664 		full_search = true;
4665 	down_read(&space_info->groups_sem);
4666 	list_for_each_entry(block_group,
4667 			    &space_info->block_groups[ffe_ctl->index], list) {
4668 		struct btrfs_block_group *bg_ret;
4669 
4670 		ffe_ctl->hinted = false;
4671 		/* If the block group is read-only, we can skip it entirely. */
4672 		if (unlikely(block_group->ro ||
4673 			     (block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED))) {
4674 			if (ffe_ctl->for_treelog)
4675 				btrfs_clear_treelog_bg(block_group);
4676 			if (ffe_ctl->for_data_reloc)
4677 				btrfs_clear_data_reloc_bg(block_group);
4678 			continue;
4679 		}
4680 
4681 		btrfs_grab_block_group(block_group, ffe_ctl->delalloc);
4682 		ffe_ctl->search_start = block_group->start;
4683 
4684 		/*
4685 		 * this can happen if we end up cycling through all the
4686 		 * raid types, but we want to make sure we only allocate
4687 		 * for the proper type.
4688 		 */
4689 		if (!block_group_bits(block_group, ffe_ctl->flags)) {
4690 			u64 extra = BTRFS_BLOCK_GROUP_DUP |
4691 				BTRFS_BLOCK_GROUP_RAID1_MASK |
4692 				BTRFS_BLOCK_GROUP_RAID56_MASK |
4693 				BTRFS_BLOCK_GROUP_RAID10;
4694 
4695 			/*
4696 			 * if they asked for extra copies and this block group
4697 			 * doesn't provide them, bail.  This does allow us to
4698 			 * fill raid0 from raid1.
4699 			 */
4700 			if ((ffe_ctl->flags & extra) && !(block_group->flags & extra))
4701 				goto loop;
4702 
4703 			/*
4704 			 * This block group has different flags than we want.
4705 			 * It's possible that we have MIXED_GROUP flag but no
4706 			 * block group is mixed.  Just skip such block group.
4707 			 */
4708 			btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4709 			continue;
4710 		}
4711 
4712 have_block_group:
4713 		trace_btrfs_find_free_extent_have_block_group(root, ffe_ctl, block_group);
4714 		ffe_ctl->cached = btrfs_block_group_done(block_group);
4715 		if (unlikely(!ffe_ctl->cached)) {
4716 			ffe_ctl->have_caching_bg = true;
4717 			ret = btrfs_cache_block_group(block_group, false);
4718 
4719 			/*
4720 			 * If we get ENOMEM here or something else we want to
4721 			 * try other block groups, because it may not be fatal.
4722 			 * However if we can't find anything else we need to
4723 			 * save our return here so that we return the actual
4724 			 * error that caused problems, not ENOSPC.
4725 			 */
4726 			if (ret < 0) {
4727 				if (!cache_block_group_error)
4728 					cache_block_group_error = ret;
4729 				ret = 0;
4730 				goto loop;
4731 			}
4732 			ret = 0;
4733 		}
4734 
4735 		if (unlikely(block_group->cached == BTRFS_CACHE_ERROR)) {
4736 			if (!cache_block_group_error)
4737 				cache_block_group_error = -EIO;
4738 			goto loop;
4739 		}
4740 
4741 		if (!find_free_extent_check_size_class(ffe_ctl, block_group))
4742 			goto loop;
4743 
4744 		bg_ret = NULL;
4745 		ret = do_allocation(block_group, ffe_ctl, &bg_ret);
4746 		if (ret > 0)
4747 			goto loop;
4748 
4749 		if (bg_ret && bg_ret != block_group) {
4750 			btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4751 			block_group = bg_ret;
4752 		}
4753 
4754 		/* Checks */
4755 		ffe_ctl->search_start = round_up(ffe_ctl->found_offset,
4756 						 fs_info->sectorsize);
4757 
4758 		/* move on to the next group */
4759 		if (ffe_ctl->search_start + ffe_ctl->num_bytes >
4760 		    btrfs_block_group_end(block_group)) {
4761 			btrfs_add_free_space_unused(block_group,
4762 					    ffe_ctl->found_offset,
4763 					    ffe_ctl->num_bytes);
4764 			goto loop;
4765 		}
4766 
4767 		if (ffe_ctl->found_offset < ffe_ctl->search_start)
4768 			btrfs_add_free_space_unused(block_group,
4769 					ffe_ctl->found_offset,
4770 					ffe_ctl->search_start - ffe_ctl->found_offset);
4771 
4772 		ret = btrfs_add_reserved_bytes(block_group, ffe_ctl->ram_bytes,
4773 					       ffe_ctl->num_bytes,
4774 					       ffe_ctl->delalloc,
4775 					       ffe_ctl->loop >= LOOP_WRONG_SIZE_CLASS);
4776 		if (ret == -EAGAIN) {
4777 			btrfs_add_free_space_unused(block_group,
4778 					ffe_ctl->found_offset,
4779 					ffe_ctl->num_bytes);
4780 			goto loop;
4781 		}
4782 		btrfs_inc_block_group_reservations(block_group);
4783 
4784 		/* we are all good, lets return */
4785 		ins->objectid = ffe_ctl->search_start;
4786 		ins->offset = ffe_ctl->num_bytes;
4787 
4788 		trace_btrfs_reserve_extent(block_group, ffe_ctl);
4789 		btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4790 		break;
4791 loop:
4792 		if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
4793 		    !ffe_ctl->retry_uncached) {
4794 			ffe_ctl->retry_uncached = true;
4795 			btrfs_wait_block_group_cache_progress(block_group,
4796 						ffe_ctl->num_bytes +
4797 						ffe_ctl->empty_cluster +
4798 						ffe_ctl->empty_size);
4799 			goto have_block_group;
4800 		}
4801 		release_block_group(block_group, ffe_ctl, ffe_ctl->delalloc);
4802 		cond_resched();
4803 	}
4804 	up_read(&space_info->groups_sem);
4805 
4806 	ret = find_free_extent_update_loop(fs_info, ins, ffe_ctl, space_info,
4807 					   full_search);
4808 	if (ret > 0)
4809 		goto search;
4810 
4811 	if (ret == -ENOSPC && !cache_block_group_error) {
4812 		/*
4813 		 * Use ffe_ctl->total_free_space as fallback if we can't find
4814 		 * any contiguous hole.
4815 		 */
4816 		if (!ffe_ctl->max_extent_size)
4817 			ffe_ctl->max_extent_size = ffe_ctl->total_free_space;
4818 		spin_lock(&space_info->lock);
4819 		space_info->max_extent_size = ffe_ctl->max_extent_size;
4820 		spin_unlock(&space_info->lock);
4821 		ins->offset = ffe_ctl->max_extent_size;
4822 	} else if (ret == -ENOSPC) {
4823 		ret = cache_block_group_error;
4824 	}
4825 	return ret;
4826 }
4827 
4828 /*
4829  * Entry point to the extent allocator. Tries to find a hole that is at least
4830  * as big as @num_bytes.
4831  *
4832  * @root           -	The root that will contain this extent
4833  *
4834  * @ram_bytes      -	The amount of space in ram that @num_bytes take. This
4835  *			is used for accounting purposes. This value differs
4836  *			from @num_bytes only in the case of compressed extents.
4837  *
4838  * @num_bytes      -	Number of bytes to allocate on-disk.
4839  *
4840  * @min_alloc_size -	Indicates the minimum amount of space that the
4841  *			allocator should try to satisfy. In some cases
4842  *			@num_bytes may be larger than what is required and if
4843  *			the filesystem is fragmented then allocation fails.
4844  *			However, the presence of @min_alloc_size gives a
4845  *			chance to try and satisfy the smaller allocation.
4846  *
4847  * @empty_size     -	A hint that you plan on doing more COW. This is the
4848  *			size in bytes the allocator should try to find free
4849  *			next to the block it returns.  This is just a hint and
4850  *			may be ignored by the allocator.
4851  *
4852  * @hint_byte      -	Hint to the allocator to start searching above the byte
4853  *			address passed. It might be ignored.
4854  *
4855  * @ins            -	This key is modified to record the found hole. It will
4856  *			have the following values:
4857  *			ins->objectid == start position
4858  *			ins->flags = BTRFS_EXTENT_ITEM_KEY
4859  *			ins->offset == the size of the hole.
4860  *
4861  * @is_data        -	Boolean flag indicating whether an extent is
4862  *			allocated for data (true) or metadata (false)
4863  *
4864  * @delalloc       -	Boolean flag indicating whether this allocation is for
4865  *			delalloc or not. If 'true' data_rwsem of block groups
4866  *			is going to be acquired.
4867  *
4868  *
4869  * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
4870  * case -ENOSPC is returned then @ins->offset will contain the size of the
4871  * largest available hole the allocator managed to find.
4872  */
4873 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
4874 			 u64 num_bytes, u64 min_alloc_size,
4875 			 u64 empty_size, u64 hint_byte,
4876 			 struct btrfs_key *ins, bool is_data, bool delalloc)
4877 {
4878 	struct btrfs_fs_info *fs_info = root->fs_info;
4879 	struct find_free_extent_ctl ffe_ctl = {};
4880 	bool final_tried = num_bytes == min_alloc_size;
4881 	u64 flags;
4882 	int ret;
4883 	bool for_treelog = (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID);
4884 	bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
4885 
4886 	flags = get_alloc_profile_by_root(root, is_data);
4887 again:
4888 	WARN_ON(num_bytes < fs_info->sectorsize);
4889 
4890 	ffe_ctl.ram_bytes = ram_bytes;
4891 	ffe_ctl.num_bytes = num_bytes;
4892 	ffe_ctl.min_alloc_size = min_alloc_size;
4893 	ffe_ctl.empty_size = empty_size;
4894 	ffe_ctl.flags = flags;
4895 	ffe_ctl.delalloc = delalloc;
4896 	ffe_ctl.hint_byte = hint_byte;
4897 	ffe_ctl.for_treelog = for_treelog;
4898 	ffe_ctl.for_data_reloc = for_data_reloc;
4899 
4900 	ret = find_free_extent(root, ins, &ffe_ctl);
4901 	if (!ret && !is_data) {
4902 		btrfs_dec_block_group_reservations(fs_info, ins->objectid);
4903 	} else if (ret == -ENOSPC) {
4904 		if (!final_tried && ins->offset) {
4905 			num_bytes = min(num_bytes >> 1, ins->offset);
4906 			num_bytes = round_down(num_bytes,
4907 					       fs_info->sectorsize);
4908 			num_bytes = max(num_bytes, min_alloc_size);
4909 			ram_bytes = num_bytes;
4910 			if (num_bytes == min_alloc_size)
4911 				final_tried = true;
4912 			goto again;
4913 		} else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4914 			struct btrfs_space_info *sinfo;
4915 
4916 			sinfo = btrfs_find_space_info(fs_info, flags);
4917 			btrfs_err(fs_info,
4918 	"allocation failed flags %llu, wanted %llu tree-log %d, relocation: %d",
4919 				  flags, num_bytes, for_treelog, for_data_reloc);
4920 			if (sinfo)
4921 				btrfs_dump_space_info(sinfo, num_bytes, 1);
4922 		}
4923 	}
4924 
4925 	return ret;
4926 }
4927 
4928 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len,
4929 			       bool is_delalloc)
4930 {
4931 	struct btrfs_block_group *cache;
4932 
4933 	cache = btrfs_lookup_block_group(fs_info, start);
4934 	if (!cache) {
4935 		btrfs_err(fs_info, "Unable to find block group for %llu",
4936 			  start);
4937 		return -ENOSPC;
4938 	}
4939 
4940 	btrfs_add_free_space(cache, start, len);
4941 	btrfs_free_reserved_bytes(cache, len, is_delalloc);
4942 	trace_btrfs_reserved_extent_free(fs_info, start, len);
4943 
4944 	btrfs_put_block_group(cache);
4945 	return 0;
4946 }
4947 
4948 int btrfs_pin_reserved_extent(struct btrfs_trans_handle *trans,
4949 			      const struct extent_buffer *eb)
4950 {
4951 	struct btrfs_block_group *cache;
4952 	int ret = 0;
4953 
4954 	cache = btrfs_lookup_block_group(trans->fs_info, eb->start);
4955 	if (!cache) {
4956 		btrfs_err(trans->fs_info, "unable to find block group for %llu",
4957 			  eb->start);
4958 		return -ENOSPC;
4959 	}
4960 
4961 	ret = pin_down_extent(trans, cache, eb->start, eb->len, true);
4962 	btrfs_put_block_group(cache);
4963 	return ret;
4964 }
4965 
4966 static int alloc_reserved_extent(struct btrfs_trans_handle *trans, u64 bytenr,
4967 				 u64 num_bytes)
4968 {
4969 	struct btrfs_fs_info *fs_info = trans->fs_info;
4970 	int ret;
4971 
4972 	ret = btrfs_remove_from_free_space_tree(trans, bytenr, num_bytes);
4973 	if (ret)
4974 		return ret;
4975 
4976 	ret = btrfs_update_block_group(trans, bytenr, num_bytes, true);
4977 	if (ret) {
4978 		ASSERT(!ret);
4979 		btrfs_err(fs_info, "update block group failed for %llu %llu",
4980 			  bytenr, num_bytes);
4981 		return ret;
4982 	}
4983 
4984 	trace_btrfs_reserved_extent_alloc(fs_info, bytenr, num_bytes);
4985 	return 0;
4986 }
4987 
4988 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4989 				      u64 parent, u64 root_objectid,
4990 				      u64 flags, u64 owner, u64 offset,
4991 				      struct btrfs_key *ins, int ref_mod, u64 oref_root)
4992 {
4993 	struct btrfs_fs_info *fs_info = trans->fs_info;
4994 	struct btrfs_root *extent_root;
4995 	int ret;
4996 	struct btrfs_extent_item *extent_item;
4997 	struct btrfs_extent_owner_ref *oref;
4998 	struct btrfs_extent_inline_ref *iref;
4999 	struct btrfs_path *path;
5000 	struct extent_buffer *leaf;
5001 	int type;
5002 	u32 size;
5003 	const bool simple_quota = (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE);
5004 
5005 	if (parent > 0)
5006 		type = BTRFS_SHARED_DATA_REF_KEY;
5007 	else
5008 		type = BTRFS_EXTENT_DATA_REF_KEY;
5009 
5010 	size = sizeof(*extent_item);
5011 	if (simple_quota)
5012 		size += btrfs_extent_inline_ref_size(BTRFS_EXTENT_OWNER_REF_KEY);
5013 	size += btrfs_extent_inline_ref_size(type);
5014 
5015 	extent_root = btrfs_extent_root(fs_info, ins->objectid);
5016 	if (unlikely(!extent_root)) {
5017 		btrfs_err(fs_info,
5018 			  "missing extent root for extent at bytenr %llu",
5019 			  ins->objectid);
5020 		return -EUCLEAN;
5021 	}
5022 
5023 	path = btrfs_alloc_path();
5024 	if (!path)
5025 		return -ENOMEM;
5026 
5027 	ret = btrfs_insert_empty_item(trans, extent_root, path, ins, size);
5028 	if (ret) {
5029 		btrfs_free_path(path);
5030 		return ret;
5031 	}
5032 
5033 	leaf = path->nodes[0];
5034 	extent_item = btrfs_item_ptr(leaf, path->slots[0],
5035 				     struct btrfs_extent_item);
5036 	btrfs_set_extent_refs(leaf, extent_item, ref_mod);
5037 	btrfs_set_extent_generation(leaf, extent_item, trans->transid);
5038 	btrfs_set_extent_flags(leaf, extent_item,
5039 			       flags | BTRFS_EXTENT_FLAG_DATA);
5040 
5041 	iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
5042 	if (simple_quota) {
5043 		btrfs_set_extent_inline_ref_type(leaf, iref, BTRFS_EXTENT_OWNER_REF_KEY);
5044 		oref = (struct btrfs_extent_owner_ref *)(&iref->offset);
5045 		btrfs_set_extent_owner_ref_root_id(leaf, oref, oref_root);
5046 		iref = (struct btrfs_extent_inline_ref *)(oref + 1);
5047 	}
5048 	btrfs_set_extent_inline_ref_type(leaf, iref, type);
5049 
5050 	if (parent > 0) {
5051 		struct btrfs_shared_data_ref *ref;
5052 		ref = (struct btrfs_shared_data_ref *)(iref + 1);
5053 		btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
5054 		btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
5055 	} else {
5056 		struct btrfs_extent_data_ref *ref;
5057 		ref = (struct btrfs_extent_data_ref *)(&iref->offset);
5058 		btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
5059 		btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
5060 		btrfs_set_extent_data_ref_offset(leaf, ref, offset);
5061 		btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
5062 	}
5063 
5064 	btrfs_free_path(path);
5065 
5066 	return alloc_reserved_extent(trans, ins->objectid, ins->offset);
5067 }
5068 
5069 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
5070 				     const struct btrfs_delayed_ref_node *node,
5071 				     struct btrfs_delayed_extent_op *extent_op)
5072 {
5073 	struct btrfs_fs_info *fs_info = trans->fs_info;
5074 	struct btrfs_root *extent_root;
5075 	int ret;
5076 	struct btrfs_extent_item *extent_item;
5077 	struct btrfs_key extent_key;
5078 	struct btrfs_tree_block_info *block_info;
5079 	struct btrfs_extent_inline_ref *iref;
5080 	struct btrfs_path *path;
5081 	struct extent_buffer *leaf;
5082 	u32 size = sizeof(*extent_item) + sizeof(*iref);
5083 	const u64 flags = (extent_op ? extent_op->flags_to_set : 0);
5084 	/* The owner of a tree block is the level. */
5085 	int level = btrfs_delayed_ref_owner(node);
5086 	bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
5087 
5088 	if (unlikely(node->ref_root == BTRFS_REMAP_TREE_OBJECTID))
5089 		goto skip;
5090 
5091 	extent_key.objectid = node->bytenr;
5092 	if (skinny_metadata) {
5093 		/* The owner of a tree block is the level. */
5094 		extent_key.offset = level;
5095 		extent_key.type = BTRFS_METADATA_ITEM_KEY;
5096 	} else {
5097 		extent_key.offset = node->num_bytes;
5098 		extent_key.type = BTRFS_EXTENT_ITEM_KEY;
5099 		size += sizeof(*block_info);
5100 	}
5101 
5102 	extent_root = btrfs_extent_root(fs_info, extent_key.objectid);
5103 	if (unlikely(!extent_root)) {
5104 		btrfs_err(fs_info,
5105 			  "missing extent root for extent at bytenr %llu",
5106 			  extent_key.objectid);
5107 		return -EUCLEAN;
5108 	}
5109 
5110 	path = btrfs_alloc_path();
5111 	if (!path)
5112 		return -ENOMEM;
5113 
5114 	ret = btrfs_insert_empty_item(trans, extent_root, path, &extent_key,
5115 				      size);
5116 	if (ret) {
5117 		btrfs_free_path(path);
5118 		return ret;
5119 	}
5120 
5121 	leaf = path->nodes[0];
5122 	extent_item = btrfs_item_ptr(leaf, path->slots[0],
5123 				     struct btrfs_extent_item);
5124 	btrfs_set_extent_refs(leaf, extent_item, 1);
5125 	btrfs_set_extent_generation(leaf, extent_item, trans->transid);
5126 	btrfs_set_extent_flags(leaf, extent_item,
5127 			       flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
5128 
5129 	if (skinny_metadata) {
5130 		iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
5131 	} else {
5132 		block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
5133 		btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
5134 		btrfs_set_tree_block_level(leaf, block_info, level);
5135 		iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
5136 	}
5137 
5138 	if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
5139 		btrfs_set_extent_inline_ref_type(leaf, iref,
5140 						 BTRFS_SHARED_BLOCK_REF_KEY);
5141 		btrfs_set_extent_inline_ref_offset(leaf, iref, node->parent);
5142 	} else {
5143 		btrfs_set_extent_inline_ref_type(leaf, iref,
5144 						 BTRFS_TREE_BLOCK_REF_KEY);
5145 		btrfs_set_extent_inline_ref_offset(leaf, iref, node->ref_root);
5146 	}
5147 
5148 	btrfs_free_path(path);
5149 
5150 skip:
5151 	return alloc_reserved_extent(trans, node->bytenr, fs_info->nodesize);
5152 }
5153 
5154 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
5155 				     struct btrfs_root *root, u64 owner,
5156 				     u64 offset, u64 ram_bytes,
5157 				     struct btrfs_key *ins)
5158 {
5159 	struct btrfs_ref generic_ref = {
5160 		.action = BTRFS_ADD_DELAYED_EXTENT,
5161 		.bytenr = ins->objectid,
5162 		.num_bytes = ins->offset,
5163 		.owning_root = btrfs_root_id(root),
5164 		.ref_root = btrfs_root_id(root),
5165 	};
5166 
5167 	ASSERT(generic_ref.ref_root != BTRFS_TREE_LOG_OBJECTID);
5168 
5169 	if (btrfs_is_data_reloc_root(root) && btrfs_is_fstree(root->relocation_src_root))
5170 		generic_ref.owning_root = root->relocation_src_root;
5171 
5172 	btrfs_init_data_ref(&generic_ref, owner, offset, 0, false);
5173 	btrfs_ref_tree_mod(root->fs_info, &generic_ref);
5174 
5175 	return btrfs_add_delayed_data_ref(trans, &generic_ref, ram_bytes);
5176 }
5177 
5178 /*
5179  * this is used by the tree logging recovery code.  It records that
5180  * an extent has been allocated and makes sure to clear the free
5181  * space cache bits as well
5182  */
5183 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
5184 				   u64 root_objectid, u64 owner, u64 offset,
5185 				   struct btrfs_key *ins)
5186 {
5187 	struct btrfs_fs_info *fs_info = trans->fs_info;
5188 	int ret;
5189 	struct btrfs_block_group *block_group;
5190 	struct btrfs_space_info *space_info;
5191 	const struct btrfs_squota_delta delta = {
5192 		.root = root_objectid,
5193 		.num_bytes = ins->offset,
5194 		.generation = trans->transid,
5195 		.is_data = true,
5196 		.is_inc = true,
5197 	};
5198 
5199 	/*
5200 	 * Mixed block groups will exclude before processing the log so we only
5201 	 * need to do the exclude dance if this fs isn't mixed.
5202 	 */
5203 	if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
5204 		ret = __exclude_logged_extent(fs_info, ins->objectid,
5205 					      ins->offset);
5206 		if (ret)
5207 			return ret;
5208 	}
5209 
5210 	block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
5211 	if (!block_group)
5212 		return -EINVAL;
5213 
5214 	space_info = block_group->space_info;
5215 	spin_lock(&space_info->lock);
5216 	spin_lock(&block_group->lock);
5217 	space_info->bytes_reserved += ins->offset;
5218 	block_group->reserved += ins->offset;
5219 	spin_unlock(&block_group->lock);
5220 	spin_unlock(&space_info->lock);
5221 
5222 	ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
5223 					 offset, ins, 1, root_objectid);
5224 	if (ret)
5225 		btrfs_pin_extent(trans, ins->objectid, ins->offset);
5226 	else
5227 		btrfs_record_squota_delta(fs_info, &delta);
5228 	btrfs_put_block_group(block_group);
5229 	return ret;
5230 }
5231 
5232 #ifdef CONFIG_BTRFS_DEBUG
5233 /*
5234  * Extra safety check in case the extent tree is corrupted and extent allocator
5235  * chooses to use a tree block which is already used and locked.
5236  */
5237 static bool check_eb_lock_owner(const struct extent_buffer *eb)
5238 {
5239 	if (eb->lock_owner == current->pid) {
5240 		btrfs_err_rl(eb->fs_info,
5241 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
5242 			     eb->start, btrfs_header_owner(eb), current->pid);
5243 		return true;
5244 	}
5245 	return false;
5246 }
5247 #else
5248 static bool check_eb_lock_owner(struct extent_buffer *eb)
5249 {
5250 	return false;
5251 }
5252 #endif
5253 
5254 static struct extent_buffer *
5255 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
5256 		      u64 bytenr, int level, u64 owner,
5257 		      enum btrfs_lock_nesting nest)
5258 {
5259 	struct btrfs_fs_info *fs_info = root->fs_info;
5260 	struct btrfs_eb_prealloc pa = { 0 };
5261 	struct extent_buffer *buf;
5262 	u64 lockdep_owner = owner;
5263 
5264 	buf = btrfs_find_create_tree_block(fs_info, &pa, bytenr, owner, level);
5265 	if (IS_ERR(buf))
5266 		return buf;
5267 
5268 	if (unlikely(check_eb_lock_owner(buf))) {
5269 		free_extent_buffer(buf);
5270 		return ERR_PTR(-EUCLEAN);
5271 	}
5272 
5273 	/*
5274 	 * The reloc trees are just snapshots, so we need them to appear to be
5275 	 * just like any other fs tree WRT lockdep.
5276 	 *
5277 	 * The exception however is in replace_path() in relocation, where we
5278 	 * hold the lock on the original fs root and then search for the reloc
5279 	 * root.  At that point we need to make sure any reloc root buffers are
5280 	 * set to the BTRFS_TREE_RELOC_OBJECTID lockdep class in order to make
5281 	 * lockdep happy.
5282 	 */
5283 	if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID &&
5284 	    !test_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &root->state))
5285 		lockdep_owner = BTRFS_FS_TREE_OBJECTID;
5286 
5287 	/* btrfs_clear_buffer_dirty() accesses generation field. */
5288 	btrfs_set_header_generation(buf, trans->transid);
5289 
5290 	/*
5291 	 * This needs to stay, because we could allocate a freed block from an
5292 	 * old tree into a new tree, so we need to make sure this new block is
5293 	 * set to the appropriate level and owner.
5294 	 */
5295 	btrfs_set_buffer_lockdep_class(lockdep_owner, buf, level);
5296 
5297 	btrfs_tree_lock_nested(buf, nest);
5298 	btrfs_clear_buffer_dirty(trans, buf);
5299 	clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
5300 	clear_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &buf->bflags);
5301 
5302 	set_extent_buffer_uptodate(buf);
5303 
5304 	memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
5305 	btrfs_set_header_level(buf, level);
5306 	btrfs_set_header_bytenr(buf, buf->start);
5307 	btrfs_set_header_generation(buf, trans->transid);
5308 	btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
5309 	btrfs_set_header_owner(buf, owner);
5310 	write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
5311 	write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
5312 	if (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID) {
5313 		buf->log_index = root->log_transid % 2;
5314 		/*
5315 		 * we allow two log transactions at a time, use different
5316 		 * EXTENT bit to differentiate dirty pages.
5317 		 */
5318 		if (buf->log_index == 0)
5319 			btrfs_set_extent_bit(&root->dirty_log_pages, buf->start,
5320 					     buf->start + buf->len - 1,
5321 					     EXTENT_DIRTY_LOG1, NULL);
5322 		else
5323 			btrfs_set_extent_bit(&root->dirty_log_pages, buf->start,
5324 					     buf->start + buf->len - 1,
5325 					     EXTENT_DIRTY_LOG2, NULL);
5326 	} else {
5327 		buf->log_index = -1;
5328 		btrfs_set_extent_bit(&trans->transaction->dirty_pages, buf->start,
5329 				     buf->start + buf->len - 1, EXTENT_DIRTY, NULL);
5330 	}
5331 	/* this returns a buffer locked for blocking */
5332 	return buf;
5333 }
5334 
5335 /*
5336  * finds a free extent and does all the dirty work required for allocation
5337  * returns the tree buffer or an ERR_PTR on error.
5338  */
5339 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
5340 					     struct btrfs_root *root,
5341 					     u64 parent, u64 root_objectid,
5342 					     const struct btrfs_disk_key *key,
5343 					     int level, u64 hint,
5344 					     u64 empty_size,
5345 					     u64 reloc_src_root,
5346 					     enum btrfs_lock_nesting nest)
5347 {
5348 	struct btrfs_fs_info *fs_info = root->fs_info;
5349 	struct btrfs_key ins;
5350 	struct btrfs_block_rsv *block_rsv;
5351 	struct extent_buffer *buf;
5352 	u64 flags = 0;
5353 	int ret;
5354 	u32 blocksize = fs_info->nodesize;
5355 	bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
5356 	u64 owning_root;
5357 
5358 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5359 	if (btrfs_is_testing(fs_info)) {
5360 		buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
5361 					    level, root_objectid, nest);
5362 		if (!IS_ERR(buf))
5363 			root->alloc_bytenr += blocksize;
5364 		return buf;
5365 	}
5366 #endif
5367 
5368 	block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
5369 	if (IS_ERR(block_rsv))
5370 		return ERR_CAST(block_rsv);
5371 
5372 	ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
5373 				   empty_size, hint, &ins, false, false);
5374 	if (ret)
5375 		goto out_unuse;
5376 
5377 	buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
5378 				    root_objectid, nest);
5379 	if (IS_ERR(buf)) {
5380 		ret = PTR_ERR(buf);
5381 		goto out_free_reserved;
5382 	}
5383 	owning_root = btrfs_header_owner(buf);
5384 
5385 	if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
5386 		if (parent == 0)
5387 			parent = ins.objectid;
5388 		flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5389 		owning_root = reloc_src_root;
5390 	} else
5391 		BUG_ON(parent > 0);
5392 
5393 	if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
5394 		struct btrfs_delayed_extent_op *extent_op;
5395 		struct btrfs_ref generic_ref = {
5396 			.action = BTRFS_ADD_DELAYED_EXTENT,
5397 			.bytenr = ins.objectid,
5398 			.num_bytes = ins.offset,
5399 			.parent = parent,
5400 			.owning_root = owning_root,
5401 			.ref_root = root_objectid,
5402 		};
5403 
5404 		if (!skinny_metadata || flags != 0) {
5405 			extent_op = btrfs_alloc_delayed_extent_op();
5406 			if (!extent_op) {
5407 				ret = -ENOMEM;
5408 				goto out_free_buf;
5409 			}
5410 			if (key)
5411 				memcpy(&extent_op->key, key, sizeof(extent_op->key));
5412 			else
5413 				memset(&extent_op->key, 0, sizeof(extent_op->key));
5414 			extent_op->flags_to_set = flags;
5415 			extent_op->update_key = (skinny_metadata ? false : true);
5416 			extent_op->update_flags = (flags != 0);
5417 		} else {
5418 			extent_op = NULL;
5419 		}
5420 
5421 		btrfs_init_tree_ref(&generic_ref, level, btrfs_root_id(root), false);
5422 		btrfs_ref_tree_mod(fs_info, &generic_ref);
5423 		ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, extent_op);
5424 		if (ret) {
5425 			btrfs_free_delayed_extent_op(extent_op);
5426 			goto out_free_buf;
5427 		}
5428 	}
5429 	return buf;
5430 
5431 out_free_buf:
5432 	btrfs_tree_unlock(buf);
5433 	free_extent_buffer(buf);
5434 out_free_reserved:
5435 	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, false);
5436 out_unuse:
5437 	btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
5438 	return ERR_PTR(ret);
5439 }
5440 
5441 struct walk_control {
5442 	u64 refs[BTRFS_MAX_LEVEL];
5443 	u64 flags[BTRFS_MAX_LEVEL];
5444 	struct btrfs_key update_progress;
5445 	struct btrfs_key drop_progress;
5446 	int drop_level;
5447 	int stage;
5448 	int level;
5449 	int shared_level;
5450 	int update_ref;
5451 	int keep_locks;
5452 	int reada_slot;
5453 	int reada_count;
5454 	int restarted;
5455 	/* Indicate that extent info needs to be looked up when walking the tree. */
5456 	int lookup_info;
5457 };
5458 
5459 /*
5460  * This is our normal stage.  We are traversing blocks the current snapshot owns
5461  * and we are dropping any of our references to any children we are able to, and
5462  * then freeing the block once we've processed all of the children.
5463  */
5464 #define DROP_REFERENCE	1
5465 
5466 /*
5467  * We enter this stage when we have to walk into a child block (meaning we can't
5468  * simply drop our reference to it from our current parent node) and there are
5469  * more than one reference on it.  If we are the owner of any of the children
5470  * blocks from the current parent node then we have to do the FULL_BACKREF dance
5471  * on them in order to drop our normal ref and add the shared ref.
5472  */
5473 #define UPDATE_BACKREF	2
5474 
5475 /*
5476  * Decide if we need to walk down into this node to adjust the references.
5477  *
5478  * @root:	the root we are currently deleting
5479  * @wc:		the walk control for this deletion
5480  * @eb:		the parent eb that we're currently visiting
5481  * @flags:	the flags for wc->level - 1
5482  * @slot:	the slot in the eb that we're currently checking
5483  *
5484  * This is meant to be called when we're evaluating if a node we point to at
5485  * wc->level should be read and walked into, or if we can simply delete our
5486  * reference to it.  We return true if we should walk into the node, false if we
5487  * can skip it.
5488  *
5489  * We have assertions in here to make sure this is called correctly.  We assume
5490  * that sanity checking on the blocks read to this point has been done, so any
5491  * corrupted file systems must have been caught before calling this function.
5492  */
5493 static bool visit_node_for_delete(struct btrfs_root *root, struct walk_control *wc,
5494 				  struct extent_buffer *eb, u64 flags, int slot)
5495 {
5496 	struct btrfs_key key;
5497 	u64 generation;
5498 	int level = wc->level;
5499 
5500 	ASSERT(level > 0);
5501 	ASSERT(wc->refs[level - 1] > 0);
5502 
5503 	/*
5504 	 * The update backref stage we only want to skip if we already have
5505 	 * FULL_BACKREF set, otherwise we need to read.
5506 	 */
5507 	if (wc->stage == UPDATE_BACKREF) {
5508 		if (level == 1 && flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5509 			return false;
5510 		return true;
5511 	}
5512 
5513 	/*
5514 	 * We're the last ref on this block, we must walk into it and process
5515 	 * any refs it's pointing at.
5516 	 */
5517 	if (wc->refs[level - 1] == 1)
5518 		return true;
5519 
5520 	/*
5521 	 * If we're already FULL_BACKREF then we know we can just drop our
5522 	 * current reference.
5523 	 */
5524 	if (level == 1 && flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5525 		return false;
5526 
5527 	/*
5528 	 * This block is older than our creation generation, we can drop our
5529 	 * reference to it.
5530 	 */
5531 	generation = btrfs_node_ptr_generation(eb, slot);
5532 	if (!wc->update_ref || generation <= btrfs_root_origin_generation(root))
5533 		return false;
5534 
5535 	/*
5536 	 * This block was processed from a previous snapshot deletion run, we
5537 	 * can skip it.
5538 	 */
5539 	btrfs_node_key_to_cpu(eb, &key, slot);
5540 	if (btrfs_comp_cpu_keys(&key, &wc->update_progress) < 0)
5541 		return false;
5542 
5543 	/* All other cases we need to wander into the node. */
5544 	return true;
5545 }
5546 
5547 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
5548 				     struct btrfs_root *root,
5549 				     struct walk_control *wc,
5550 				     struct btrfs_path *path)
5551 {
5552 	struct btrfs_fs_info *fs_info = root->fs_info;
5553 	u64 bytenr;
5554 	u64 generation;
5555 	u64 refs;
5556 	u64 flags;
5557 	u32 nritems;
5558 	struct extent_buffer *eb;
5559 	int ret;
5560 	int slot;
5561 	int nread = 0;
5562 
5563 	if (path->slots[wc->level] < wc->reada_slot) {
5564 		wc->reada_count = wc->reada_count * 2 / 3;
5565 		wc->reada_count = max(wc->reada_count, 2);
5566 	} else {
5567 		wc->reada_count = wc->reada_count * 3 / 2;
5568 		wc->reada_count = min_t(int, wc->reada_count,
5569 					BTRFS_NODEPTRS_PER_BLOCK(fs_info));
5570 	}
5571 
5572 	eb = path->nodes[wc->level];
5573 	nritems = btrfs_header_nritems(eb);
5574 
5575 	for (slot = path->slots[wc->level]; slot < nritems; slot++) {
5576 		if (nread >= wc->reada_count)
5577 			break;
5578 
5579 		cond_resched();
5580 		bytenr = btrfs_node_blockptr(eb, slot);
5581 		generation = btrfs_node_ptr_generation(eb, slot);
5582 
5583 		if (slot == path->slots[wc->level])
5584 			goto reada;
5585 
5586 		if (wc->stage == UPDATE_BACKREF &&
5587 		    generation <= btrfs_root_origin_generation(root))
5588 			continue;
5589 
5590 		/* We don't lock the tree block, it's OK to be racy here */
5591 		ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
5592 					       wc->level - 1, 1, &refs,
5593 					       &flags, NULL);
5594 		/* We don't care about errors in readahead. */
5595 		if (ret < 0)
5596 			continue;
5597 
5598 		/*
5599 		 * This could be racey, it's conceivable that we raced and end
5600 		 * up with a bogus refs count, if that's the case just skip, if
5601 		 * we are actually corrupt we will notice when we look up
5602 		 * everything again with our locks.
5603 		 */
5604 		if (refs == 0)
5605 			continue;
5606 
5607 		/* If we don't need to visit this node don't reada. */
5608 		if (!visit_node_for_delete(root, wc, eb, flags, slot))
5609 			continue;
5610 reada:
5611 		btrfs_readahead_node_child(eb, slot);
5612 		nread++;
5613 	}
5614 	wc->reada_slot = slot;
5615 }
5616 
5617 /*
5618  * helper to process tree block while walking down the tree.
5619  *
5620  * when wc->stage == UPDATE_BACKREF, this function updates
5621  * back refs for pointers in the block.
5622  *
5623  * NOTE: return value 1 means we should stop walking down.
5624  */
5625 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5626 				   struct btrfs_root *root,
5627 				   struct btrfs_path *path,
5628 				   struct walk_control *wc)
5629 {
5630 	struct btrfs_fs_info *fs_info = root->fs_info;
5631 	int level = wc->level;
5632 	struct extent_buffer *eb = path->nodes[level];
5633 	u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5634 	int ret;
5635 
5636 	if (wc->stage == UPDATE_BACKREF && btrfs_header_owner(eb) != btrfs_root_id(root))
5637 		return 1;
5638 
5639 	/*
5640 	 * when reference count of tree block is 1, it won't increase
5641 	 * again. once full backref flag is set, we never clear it.
5642 	 */
5643 	if (wc->lookup_info &&
5644 	    ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
5645 	     (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
5646 		ASSERT(path->locks[level]);
5647 		ret = btrfs_lookup_extent_info(trans, fs_info,
5648 					       eb->start, level, 1,
5649 					       &wc->refs[level],
5650 					       &wc->flags[level],
5651 					       NULL);
5652 		if (ret)
5653 			return ret;
5654 		if (unlikely(wc->refs[level] == 0)) {
5655 			btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0",
5656 				  eb->start);
5657 			return -EUCLEAN;
5658 		}
5659 	}
5660 
5661 	if (wc->stage == DROP_REFERENCE) {
5662 		if (wc->refs[level] > 1)
5663 			return 1;
5664 
5665 		if (path->locks[level] && !wc->keep_locks) {
5666 			btrfs_tree_unlock_rw(eb, path->locks[level]);
5667 			path->locks[level] = 0;
5668 		}
5669 		return 0;
5670 	}
5671 
5672 	/* wc->stage == UPDATE_BACKREF */
5673 	if (!(wc->flags[level] & flag)) {
5674 		ASSERT(path->locks[level]);
5675 		ret = btrfs_inc_ref(trans, root, eb, true);
5676 		if (unlikely(ret)) {
5677 			btrfs_abort_transaction(trans, ret);
5678 			return ret;
5679 		}
5680 		ret = btrfs_dec_ref(trans, root, eb, false);
5681 		if (unlikely(ret)) {
5682 			btrfs_abort_transaction(trans, ret);
5683 			return ret;
5684 		}
5685 		ret = btrfs_set_disk_extent_flags(trans, eb, flag);
5686 		if (unlikely(ret)) {
5687 			btrfs_abort_transaction(trans, ret);
5688 			return ret;
5689 		}
5690 		wc->flags[level] |= flag;
5691 	}
5692 
5693 	/*
5694 	 * the block is shared by multiple trees, so it's not good to
5695 	 * keep the tree lock
5696 	 */
5697 	if (path->locks[level] && level > 0) {
5698 		btrfs_tree_unlock_rw(eb, path->locks[level]);
5699 		path->locks[level] = 0;
5700 	}
5701 	return 0;
5702 }
5703 
5704 /*
5705  * This is used to verify a ref exists for this root to deal with a bug where we
5706  * would have a drop_progress key that hadn't been updated properly.
5707  */
5708 static int check_ref_exists(struct btrfs_trans_handle *trans,
5709 			    struct btrfs_root *root, u64 bytenr, u64 parent,
5710 			    int level)
5711 {
5712 	struct btrfs_delayed_ref_root *delayed_refs;
5713 	struct btrfs_delayed_ref_head *head;
5714 	BTRFS_PATH_AUTO_FREE(path);
5715 	struct btrfs_extent_inline_ref *iref;
5716 	int ret;
5717 	bool exists = false;
5718 
5719 	path = btrfs_alloc_path();
5720 	if (!path)
5721 		return -ENOMEM;
5722 again:
5723 	ret = lookup_extent_backref(trans, path, &iref, bytenr,
5724 				    root->fs_info->nodesize, parent,
5725 				    btrfs_root_id(root), level, 0);
5726 	if (ret != -ENOENT) {
5727 		/*
5728 		 * If we get 0 then we found our reference, return 1, else
5729 		 * return the error if it's not -ENOENT;
5730 		 */
5731 		return (ret < 0 ) ? ret : 1;
5732 	}
5733 
5734 	/*
5735 	 * We could have a delayed ref with this reference, so look it up while
5736 	 * we're holding the path open to make sure we don't race with the
5737 	 * delayed ref running.
5738 	 */
5739 	delayed_refs = &trans->transaction->delayed_refs;
5740 	spin_lock(&delayed_refs->lock);
5741 	head = btrfs_find_delayed_ref_head(root->fs_info, delayed_refs, bytenr);
5742 	if (!head)
5743 		goto out;
5744 	if (!mutex_trylock(&head->mutex)) {
5745 		/*
5746 		 * We're contended, means that the delayed ref is running, get a
5747 		 * reference and wait for the ref head to be complete and then
5748 		 * try again.
5749 		 */
5750 		refcount_inc(&head->refs);
5751 		spin_unlock(&delayed_refs->lock);
5752 
5753 		btrfs_release_path(path);
5754 
5755 		mutex_lock(&head->mutex);
5756 		mutex_unlock(&head->mutex);
5757 		btrfs_put_delayed_ref_head(head);
5758 		goto again;
5759 	}
5760 
5761 	exists = btrfs_find_delayed_tree_ref(head, btrfs_root_id(root), parent);
5762 	mutex_unlock(&head->mutex);
5763 out:
5764 	spin_unlock(&delayed_refs->lock);
5765 	return exists ? 1 : 0;
5766 }
5767 
5768 /*
5769  * We may not have an uptodate block, so if we are going to walk down into this
5770  * block we need to drop the lock, read it off of the disk, re-lock it and
5771  * return to continue dropping the snapshot.
5772  */
5773 static int check_next_block_uptodate(struct btrfs_trans_handle *trans,
5774 				     struct btrfs_root *root,
5775 				     struct btrfs_path *path,
5776 				     struct walk_control *wc,
5777 				     struct extent_buffer *next)
5778 {
5779 	struct btrfs_tree_parent_check check = { 0 };
5780 	u64 generation;
5781 	int level = wc->level;
5782 	int ret;
5783 
5784 	btrfs_assert_tree_write_locked(next);
5785 
5786 	generation = btrfs_node_ptr_generation(path->nodes[level], path->slots[level]);
5787 
5788 	check.level = level - 1;
5789 	check.transid = generation;
5790 	check.owner_root = btrfs_root_id(root);
5791 	check.has_first_key = true;
5792 	btrfs_node_key_to_cpu(path->nodes[level], &check.first_key, path->slots[level]);
5793 
5794 	ret = btrfs_buffer_uptodate(next, generation, &check);
5795 	if (ret > 0)
5796 		return 0;
5797 	btrfs_tree_unlock(next);
5798 	if (ret < 0) {
5799 		free_extent_buffer(next);
5800 		return ret;
5801 	}
5802 
5803 	if (level == 1)
5804 		reada_walk_down(trans, root, wc, path);
5805 	ret = btrfs_read_extent_buffer(next, &check);
5806 	if (ret) {
5807 		free_extent_buffer(next);
5808 		return ret;
5809 	}
5810 	btrfs_tree_lock(next);
5811 	wc->lookup_info = 1;
5812 	return 0;
5813 }
5814 
5815 /*
5816  * If we determine that we don't have to visit wc->level - 1 then we need to
5817  * determine if we can drop our reference.
5818  *
5819  * If we are UPDATE_BACKREF then we will not, we need to update our backrefs.
5820  *
5821  * If we are DROP_REFERENCE this will figure out if we need to drop our current
5822  * reference, skipping it if we dropped it from a previous uncompleted drop, or
5823  * dropping it if we still have a reference to it.
5824  */
5825 static int maybe_drop_reference(struct btrfs_trans_handle *trans, struct btrfs_root *root,
5826 				struct btrfs_path *path, struct walk_control *wc,
5827 				struct extent_buffer *next, u64 owner_root)
5828 {
5829 	struct btrfs_ref ref = {
5830 		.action = BTRFS_DROP_DELAYED_REF,
5831 		.bytenr = next->start,
5832 		.num_bytes = root->fs_info->nodesize,
5833 		.owning_root = owner_root,
5834 		.ref_root = btrfs_root_id(root),
5835 	};
5836 	int level = wc->level;
5837 	int ret;
5838 
5839 	/* We are UPDATE_BACKREF, we're not dropping anything. */
5840 	if (wc->stage == UPDATE_BACKREF)
5841 		return 0;
5842 
5843 	if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5844 		ref.parent = path->nodes[level]->start;
5845 	} else {
5846 		ASSERT(btrfs_root_id(root) == btrfs_header_owner(path->nodes[level]));
5847 		if (unlikely(btrfs_root_id(root) != btrfs_header_owner(path->nodes[level]))) {
5848 			btrfs_err(root->fs_info, "mismatched block owner");
5849 			return -EIO;
5850 		}
5851 	}
5852 
5853 	/*
5854 	 * If we had a drop_progress we need to verify the refs are set as
5855 	 * expected.  If we find our ref then we know that from here on out
5856 	 * everything should be correct, and we can clear the
5857 	 * ->restarted flag.
5858 	 */
5859 	if (wc->restarted) {
5860 		ret = check_ref_exists(trans, root, next->start, ref.parent,
5861 				       level - 1);
5862 		if (ret <= 0)
5863 			return ret;
5864 		ret = 0;
5865 		wc->restarted = 0;
5866 	}
5867 
5868 	/*
5869 	 * Reloc tree doesn't contribute to qgroup numbers, and we have already
5870 	 * accounted them at merge time (replace_path), thus we could skip
5871 	 * expensive subtree trace here.
5872 	 */
5873 	if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID &&
5874 	    wc->refs[level - 1] > 1) {
5875 		u64 generation = btrfs_node_ptr_generation(path->nodes[level],
5876 							   path->slots[level]);
5877 
5878 		ret = btrfs_qgroup_trace_subtree(trans, next, generation, level - 1);
5879 		if (ret) {
5880 			btrfs_err_rl(root->fs_info,
5881 "error %pe accounting shared subtree, quota is out of sync, rescan required",
5882 				     ERR_PTR(ret));
5883 		}
5884 	}
5885 
5886 	/*
5887 	 * We need to update the next key in our walk control so we can update
5888 	 * the drop_progress key accordingly.  We don't care if find_next_key
5889 	 * doesn't find a key because that means we're at the end and are going
5890 	 * to clean up now.
5891 	 */
5892 	wc->drop_level = level;
5893 	find_next_key(path, level, &wc->drop_progress);
5894 
5895 	btrfs_init_tree_ref(&ref, level - 1, 0, false);
5896 	return btrfs_free_extent(trans, &ref);
5897 }
5898 
5899 /*
5900  * helper to process tree block pointer.
5901  *
5902  * when wc->stage == DROP_REFERENCE, this function checks
5903  * reference count of the block pointed to. if the block
5904  * is shared and we need update back refs for the subtree
5905  * rooted at the block, this function changes wc->stage to
5906  * UPDATE_BACKREF. if the block is shared and there is no
5907  * need to update back, this function drops the reference
5908  * to the block.
5909  *
5910  * NOTE: return value 1 means we should stop walking down.
5911  */
5912 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
5913 				 struct btrfs_root *root,
5914 				 struct btrfs_path *path,
5915 				 struct walk_control *wc)
5916 {
5917 	struct btrfs_fs_info *fs_info = root->fs_info;
5918 	struct btrfs_eb_prealloc pa = { 0 };
5919 	u64 bytenr;
5920 	u64 generation;
5921 	u64 owner_root = 0;
5922 	struct extent_buffer *next;
5923 	int level = wc->level;
5924 	int ret = 0;
5925 
5926 	generation = btrfs_node_ptr_generation(path->nodes[level],
5927 					       path->slots[level]);
5928 	/*
5929 	 * if the lower level block was created before the snapshot
5930 	 * was created, we know there is no need to update back refs
5931 	 * for the subtree
5932 	 */
5933 	if (wc->stage == UPDATE_BACKREF &&
5934 	    generation <= btrfs_root_origin_generation(root)) {
5935 		wc->lookup_info = 1;
5936 		return 1;
5937 	}
5938 
5939 	bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
5940 
5941 	next = btrfs_find_create_tree_block(fs_info, &pa, bytenr, btrfs_root_id(root),
5942 					    level - 1);
5943 	if (IS_ERR(next))
5944 		return PTR_ERR(next);
5945 
5946 	btrfs_tree_lock(next);
5947 
5948 	ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
5949 				       &wc->refs[level - 1],
5950 				       &wc->flags[level - 1],
5951 				       &owner_root);
5952 	if (ret < 0)
5953 		goto out_unlock;
5954 
5955 	if (unlikely(wc->refs[level - 1] == 0)) {
5956 		btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0",
5957 			  bytenr);
5958 		ret = -EUCLEAN;
5959 		goto out_unlock;
5960 	}
5961 	wc->lookup_info = 0;
5962 
5963 	/* If we don't have to walk into this node skip it. */
5964 	if (!visit_node_for_delete(root, wc, path->nodes[level],
5965 				   wc->flags[level - 1], path->slots[level]))
5966 		goto skip;
5967 
5968 	/*
5969 	 * We have to walk down into this node, and if we're currently at the
5970 	 * DROP_REFERENCE stage and this block is shared then we need to switch
5971 	 * to the UPDATE_BACKREF stage in order to convert to FULL_BACKREF.
5972 	 */
5973 	if (wc->stage == DROP_REFERENCE && wc->refs[level - 1] > 1) {
5974 		wc->stage = UPDATE_BACKREF;
5975 		wc->shared_level = level - 1;
5976 	}
5977 
5978 	ret = check_next_block_uptodate(trans, root, path, wc, next);
5979 	if (ret)
5980 		return ret;
5981 
5982 	level--;
5983 	ASSERT(level == btrfs_header_level(next));
5984 	if (unlikely(level != btrfs_header_level(next))) {
5985 		btrfs_err(root->fs_info, "mismatched level");
5986 		ret = -EIO;
5987 		goto out_unlock;
5988 	}
5989 	path->nodes[level] = next;
5990 	path->slots[level] = 0;
5991 	path->locks[level] = BTRFS_WRITE_LOCK;
5992 	wc->level = level;
5993 	if (wc->level == 1)
5994 		wc->reada_slot = 0;
5995 	return 0;
5996 skip:
5997 	ret = maybe_drop_reference(trans, root, path, wc, next, owner_root);
5998 	if (ret)
5999 		goto out_unlock;
6000 	wc->refs[level - 1] = 0;
6001 	wc->flags[level - 1] = 0;
6002 	wc->lookup_info = 1;
6003 	ret = 1;
6004 
6005 out_unlock:
6006 	btrfs_tree_unlock(next);
6007 	free_extent_buffer(next);
6008 
6009 	return ret;
6010 }
6011 
6012 /*
6013  * helper to process tree block while walking up the tree.
6014  *
6015  * when wc->stage == DROP_REFERENCE, this function drops
6016  * reference count on the block.
6017  *
6018  * when wc->stage == UPDATE_BACKREF, this function changes
6019  * wc->stage back to DROP_REFERENCE if we changed wc->stage
6020  * to UPDATE_BACKREF previously while processing the block.
6021  *
6022  * NOTE: return value 1 means we should stop walking up.
6023  */
6024 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
6025 				 struct btrfs_root *root,
6026 				 struct btrfs_path *path,
6027 				 struct walk_control *wc)
6028 {
6029 	struct btrfs_fs_info *fs_info = root->fs_info;
6030 	int ret = 0;
6031 	int level = wc->level;
6032 	struct extent_buffer *eb = path->nodes[level];
6033 	u64 parent = 0;
6034 
6035 	if (wc->stage == UPDATE_BACKREF) {
6036 		ASSERT(wc->shared_level >= level);
6037 		if (level < wc->shared_level)
6038 			goto out;
6039 
6040 		ret = find_next_key(path, level + 1, &wc->update_progress);
6041 		if (ret > 0)
6042 			wc->update_ref = 0;
6043 
6044 		wc->stage = DROP_REFERENCE;
6045 		wc->shared_level = -1;
6046 		path->slots[level] = 0;
6047 
6048 		/*
6049 		 * check reference count again if the block isn't locked.
6050 		 * we should start walking down the tree again if reference
6051 		 * count is one.
6052 		 */
6053 		if (!path->locks[level]) {
6054 			ASSERT(level > 0);
6055 			btrfs_tree_lock(eb);
6056 			path->locks[level] = BTRFS_WRITE_LOCK;
6057 
6058 			ret = btrfs_lookup_extent_info(trans, fs_info,
6059 						       eb->start, level, 1,
6060 						       &wc->refs[level],
6061 						       &wc->flags[level],
6062 						       NULL);
6063 			if (ret < 0) {
6064 				btrfs_tree_unlock_rw(eb, path->locks[level]);
6065 				path->locks[level] = 0;
6066 				return ret;
6067 			}
6068 			if (unlikely(wc->refs[level] == 0)) {
6069 				btrfs_tree_unlock_rw(eb, path->locks[level]);
6070 				btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0",
6071 					  eb->start);
6072 				return -EUCLEAN;
6073 			}
6074 			if (wc->refs[level] == 1) {
6075 				btrfs_tree_unlock_rw(eb, path->locks[level]);
6076 				path->locks[level] = 0;
6077 				return 1;
6078 			}
6079 		}
6080 	}
6081 
6082 	/* wc->stage == DROP_REFERENCE */
6083 	ASSERT(path->locks[level] || wc->refs[level] == 1);
6084 
6085 	if (wc->refs[level] == 1) {
6086 		if (level == 0) {
6087 			const bool full_backref = (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF);
6088 
6089 			ret = btrfs_dec_ref(trans, root, eb, full_backref);
6090 			if (unlikely(ret)) {
6091 				btrfs_abort_transaction(trans, ret);
6092 				return ret;
6093 			}
6094 			if (btrfs_is_fstree(btrfs_root_id(root))) {
6095 				ret = btrfs_qgroup_trace_leaf_items(trans, eb);
6096 				if (ret) {
6097 					btrfs_err_rl(fs_info,
6098 	"error %pe accounting leaf items, quota is out of sync, rescan required",
6099 					     ERR_PTR(ret));
6100 				}
6101 			}
6102 		}
6103 		/* Make block locked assertion in btrfs_clear_buffer_dirty happy. */
6104 		if (!path->locks[level]) {
6105 			btrfs_tree_lock(eb);
6106 			path->locks[level] = BTRFS_WRITE_LOCK;
6107 		}
6108 		btrfs_clear_buffer_dirty(trans, eb);
6109 	}
6110 
6111 	if (eb == root->node) {
6112 		if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6113 			parent = eb->start;
6114 		else if (unlikely(btrfs_root_id(root) != btrfs_header_owner(eb)))
6115 			goto owner_mismatch;
6116 	} else {
6117 		if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6118 			parent = path->nodes[level + 1]->start;
6119 		else if (unlikely(btrfs_root_id(root) !=
6120 				  btrfs_header_owner(path->nodes[level + 1])))
6121 			goto owner_mismatch;
6122 	}
6123 
6124 	ret = btrfs_free_tree_block(trans, btrfs_root_id(root), eb, parent,
6125 				    wc->refs[level] == 1);
6126 	if (ret < 0)
6127 		btrfs_abort_transaction(trans, ret);
6128 out:
6129 	wc->refs[level] = 0;
6130 	wc->flags[level] = 0;
6131 	return ret;
6132 
6133 owner_mismatch:
6134 	btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
6135 		     btrfs_header_owner(eb), btrfs_root_id(root));
6136 	return -EUCLEAN;
6137 }
6138 
6139 /*
6140  * walk_down_tree consists of two steps.
6141  *
6142  * walk_down_proc().  Look up the reference count and reference of our current
6143  * wc->level.  At this point path->nodes[wc->level] should be populated and
6144  * uptodate, and in most cases should already be locked.  If we are in
6145  * DROP_REFERENCE and our refcount is > 1 then we've entered a shared node and
6146  * we can walk back up the tree.  If we are UPDATE_BACKREF we have to set
6147  * FULL_BACKREF on this node if it's not already set, and then do the
6148  * FULL_BACKREF conversion dance, which is to drop the root reference and add
6149  * the shared reference to all of this nodes children.
6150  *
6151  * do_walk_down().  This is where we actually start iterating on the children of
6152  * our current path->nodes[wc->level].  For DROP_REFERENCE that means dropping
6153  * our reference to the children that return false from visit_node_for_delete(),
6154  * which has various conditions where we know we can just drop our reference
6155  * without visiting the node.  For UPDATE_BACKREF we will skip any children that
6156  * visit_node_for_delete() returns false for, only walking down when necessary.
6157  * The bulk of the work for UPDATE_BACKREF occurs in the walk_up_tree() part of
6158  * snapshot deletion.
6159  */
6160 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
6161 				   struct btrfs_root *root,
6162 				   struct btrfs_path *path,
6163 				   struct walk_control *wc)
6164 {
6165 	int level = wc->level;
6166 	int ret = 0;
6167 
6168 	wc->lookup_info = 1;
6169 	while (level >= 0) {
6170 		ret = walk_down_proc(trans, root, path, wc);
6171 		if (ret)
6172 			break;
6173 
6174 		if (level == 0)
6175 			break;
6176 
6177 		if (path->slots[level] >=
6178 		    btrfs_header_nritems(path->nodes[level]))
6179 			break;
6180 
6181 		ret = do_walk_down(trans, root, path, wc);
6182 		if (ret > 0) {
6183 			path->slots[level]++;
6184 			continue;
6185 		} else if (ret < 0)
6186 			break;
6187 		level = wc->level;
6188 	}
6189 	return (ret == 1) ? 0 : ret;
6190 }
6191 
6192 /*
6193  * walk_up_tree() is responsible for making sure we visit every slot on our
6194  * current node, and if we're at the end of that node then we call
6195  * walk_up_proc() on our current node which will do one of a few things based on
6196  * our stage.
6197  *
6198  * UPDATE_BACKREF.  If we wc->level is currently less than our wc->shared_level
6199  * then we need to walk back up the tree, and then going back down into the
6200  * other slots via walk_down_tree to update any other children from our original
6201  * wc->shared_level.  Once we're at or above our wc->shared_level we can switch
6202  * back to DROP_REFERENCE, lookup the current nodes refs and flags, and carry on.
6203  *
6204  * DROP_REFERENCE. If our refs == 1 then we're going to free this tree block.
6205  * If we're level 0 then we need to btrfs_dec_ref() on all of the data extents
6206  * in our current leaf.  After that we call btrfs_free_tree_block() on the
6207  * current node and walk up to the next node to walk down the next slot.
6208  */
6209 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
6210 				 struct btrfs_root *root,
6211 				 struct btrfs_path *path,
6212 				 struct walk_control *wc, int max_level)
6213 {
6214 	int level = wc->level;
6215 	int ret;
6216 
6217 	path->slots[level] = btrfs_header_nritems(path->nodes[level]);
6218 	while (level < max_level && path->nodes[level]) {
6219 		wc->level = level;
6220 		if (path->slots[level] + 1 <
6221 		    btrfs_header_nritems(path->nodes[level])) {
6222 			path->slots[level]++;
6223 			return 0;
6224 		} else {
6225 			ret = walk_up_proc(trans, root, path, wc);
6226 			if (ret > 0)
6227 				return 0;
6228 			if (ret < 0)
6229 				return ret;
6230 
6231 			if (path->locks[level]) {
6232 				btrfs_tree_unlock_rw(path->nodes[level],
6233 						     path->locks[level]);
6234 				path->locks[level] = 0;
6235 			}
6236 			free_extent_buffer(path->nodes[level]);
6237 			path->nodes[level] = NULL;
6238 			level++;
6239 		}
6240 	}
6241 	return 1;
6242 }
6243 
6244 /*
6245  * drop a subvolume tree.
6246  *
6247  * this function traverses the tree freeing any blocks that only
6248  * referenced by the tree.
6249  *
6250  * when a shared tree block is found. this function decreases its
6251  * reference count by one. if update_ref is true, this function
6252  * also make sure backrefs for the shared block and all lower level
6253  * blocks are properly updated.
6254  *
6255  * If called with for_reloc set, may exit early with -EAGAIN
6256  */
6257 int btrfs_drop_snapshot(struct btrfs_root *root, bool update_ref, bool for_reloc)
6258 {
6259 	const bool is_reloc_root = (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID);
6260 	struct btrfs_fs_info *fs_info = root->fs_info;
6261 	struct btrfs_path *path;
6262 	struct btrfs_trans_handle *trans;
6263 	struct btrfs_root *tree_root = fs_info->tree_root;
6264 	struct btrfs_root_item *root_item = &root->root_item;
6265 	struct walk_control AUTO_KFREE(wc);
6266 	struct btrfs_key key;
6267 	const u64 rootid = btrfs_root_id(root);
6268 	int ret = 0;
6269 	int level;
6270 	bool root_dropped = false;
6271 	bool unfinished_drop = false;
6272 
6273 	btrfs_debug(fs_info, "Drop subvolume %llu", btrfs_root_id(root));
6274 
6275 	path = btrfs_alloc_path();
6276 	if (!path) {
6277 		ret = -ENOMEM;
6278 		goto out;
6279 	}
6280 
6281 	wc = kzalloc(sizeof(*wc), GFP_NOFS);
6282 	if (!wc) {
6283 		ret = -ENOMEM;
6284 		goto out_free;
6285 	}
6286 
6287 	/*
6288 	 * Use join to avoid potential EINTR from transaction start. See
6289 	 * wait_reserve_ticket and the whole reservation callchain.
6290 	 */
6291 	if (for_reloc)
6292 		trans = btrfs_join_transaction(tree_root);
6293 	else
6294 		trans = btrfs_start_transaction(tree_root, 0);
6295 	if (IS_ERR(trans)) {
6296 		ret = PTR_ERR(trans);
6297 		goto out_free;
6298 	}
6299 
6300 	ret = btrfs_run_delayed_items(trans);
6301 	if (ret)
6302 		goto out_end_trans;
6303 
6304 	/*
6305 	 * This will help us catch people modifying the fs tree while we're
6306 	 * dropping it.  It is unsafe to mess with the fs tree while it's being
6307 	 * dropped as we unlock the root node and parent nodes as we walk down
6308 	 * the tree, assuming nothing will change.  If something does change
6309 	 * then we'll have stale information and drop references to blocks we've
6310 	 * already dropped.
6311 	 */
6312 	set_bit(BTRFS_ROOT_DELETING, &root->state);
6313 	unfinished_drop = test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state);
6314 
6315 	/*
6316 	 * For subvolume dropping, check if the subvolume is large enough so
6317 	 * that we need to mark qgroup inconsistent to avoid long qgroup stall.
6318 	 *
6319 	 * Even for a subvolume without any snapshot, there can still be
6320 	 * a lot of qgroup records queued into one transaction.
6321 	 */
6322 	if (!for_reloc)
6323 		btrfs_qgroup_check_tree_drop(fs_info, rootid,
6324 					     btrfs_header_level(root->node));
6325 	if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
6326 		level = btrfs_header_level(root->node);
6327 		path->nodes[level] = btrfs_lock_root_node(root);
6328 		path->slots[level] = 0;
6329 		path->locks[level] = BTRFS_WRITE_LOCK;
6330 		memset(&wc->update_progress, 0,
6331 		       sizeof(wc->update_progress));
6332 	} else {
6333 		btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
6334 		memcpy(&wc->update_progress, &key,
6335 		       sizeof(wc->update_progress));
6336 
6337 		level = btrfs_root_drop_level(root_item);
6338 		BUG_ON(level == 0);
6339 		path->lowest_level = level;
6340 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6341 		path->lowest_level = 0;
6342 		if (ret < 0)
6343 			goto out_end_trans;
6344 
6345 		WARN_ON(ret > 0);
6346 		ret = 0;
6347 
6348 		/*
6349 		 * unlock our path, this is safe because only this
6350 		 * function is allowed to delete this snapshot
6351 		 */
6352 		btrfs_unlock_up_safe(path, 0);
6353 
6354 		level = btrfs_header_level(root->node);
6355 		while (1) {
6356 			btrfs_tree_lock(path->nodes[level]);
6357 			path->locks[level] = BTRFS_WRITE_LOCK;
6358 
6359 			/*
6360 			 * btrfs_lookup_extent_info() returns 0 for success,
6361 			 * or < 0 for error.
6362 			 */
6363 			ret = btrfs_lookup_extent_info(trans, fs_info,
6364 						path->nodes[level]->start,
6365 						level, 1, &wc->refs[level],
6366 						&wc->flags[level], NULL);
6367 			if (ret < 0)
6368 				goto out_end_trans;
6369 
6370 			BUG_ON(wc->refs[level] == 0);
6371 
6372 			if (level == btrfs_root_drop_level(root_item))
6373 				break;
6374 
6375 			btrfs_tree_unlock(path->nodes[level]);
6376 			path->locks[level] = 0;
6377 			WARN_ON(wc->refs[level] != 1);
6378 			level--;
6379 		}
6380 	}
6381 
6382 	wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
6383 	wc->level = level;
6384 	wc->shared_level = -1;
6385 	wc->stage = DROP_REFERENCE;
6386 	wc->update_ref = update_ref;
6387 	wc->keep_locks = 0;
6388 	wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
6389 
6390 	while (1) {
6391 
6392 		ret = walk_down_tree(trans, root, path, wc);
6393 		if (unlikely(ret < 0)) {
6394 			btrfs_abort_transaction(trans, ret);
6395 			break;
6396 		}
6397 
6398 		ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
6399 		if (unlikely(ret < 0)) {
6400 			btrfs_abort_transaction(trans, ret);
6401 			break;
6402 		}
6403 
6404 		if (ret > 0) {
6405 			BUG_ON(wc->stage != DROP_REFERENCE);
6406 			ret = 0;
6407 			break;
6408 		}
6409 
6410 		if (wc->stage == DROP_REFERENCE) {
6411 			wc->drop_level = wc->level;
6412 			btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
6413 					      &wc->drop_progress,
6414 					      path->slots[wc->drop_level]);
6415 		}
6416 		btrfs_cpu_key_to_disk(&root_item->drop_progress,
6417 				      &wc->drop_progress);
6418 		btrfs_set_root_drop_level(root_item, wc->drop_level);
6419 
6420 		BUG_ON(wc->level == 0);
6421 		if (btrfs_should_end_transaction(trans) ||
6422 		    (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
6423 			ret = btrfs_update_root(trans, tree_root,
6424 						&root->root_key,
6425 						root_item);
6426 			if (unlikely(ret)) {
6427 				btrfs_abort_transaction(trans, ret);
6428 				goto out_end_trans;
6429 			}
6430 
6431 			if (!is_reloc_root)
6432 				btrfs_set_last_root_drop_gen(fs_info, trans->transid);
6433 
6434 			btrfs_end_transaction_throttle(trans);
6435 			if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
6436 				btrfs_debug(fs_info,
6437 					    "drop snapshot early exit");
6438 				ret = -EAGAIN;
6439 				goto out_free;
6440 			}
6441 
6442 		       /*
6443 			* Use join to avoid potential EINTR from transaction
6444 			* start. See wait_reserve_ticket and the whole
6445 			* reservation callchain.
6446 			*/
6447 			if (for_reloc)
6448 				trans = btrfs_join_transaction(tree_root);
6449 			else
6450 				trans = btrfs_start_transaction(tree_root, 0);
6451 			if (IS_ERR(trans)) {
6452 				ret = PTR_ERR(trans);
6453 				goto out_free;
6454 			}
6455 		}
6456 	}
6457 	btrfs_release_path(path);
6458 	if (ret)
6459 		goto out_end_trans;
6460 
6461 	ret = btrfs_del_root(trans, &root->root_key);
6462 	if (unlikely(ret)) {
6463 		btrfs_abort_transaction(trans, ret);
6464 		goto out_end_trans;
6465 	}
6466 
6467 	if (!is_reloc_root) {
6468 		ret = btrfs_find_root(tree_root, &root->root_key, path,
6469 				      NULL, NULL);
6470 		if (unlikely(ret < 0)) {
6471 			btrfs_abort_transaction(trans, ret);
6472 			goto out_end_trans;
6473 		} else if (ret > 0) {
6474 			ret = 0;
6475 			/*
6476 			 * If we fail to delete the orphan item this time
6477 			 * around, it'll get picked up the next time.
6478 			 *
6479 			 * The most common failure here is just -ENOENT.
6480 			 */
6481 			btrfs_del_orphan_item(trans, tree_root, btrfs_root_id(root));
6482 		}
6483 	}
6484 
6485 	/*
6486 	 * This subvolume is going to be completely dropped, and won't be
6487 	 * recorded as dirty roots, thus pertrans meta rsv will not be freed at
6488 	 * commit transaction time.  So free it here manually.
6489 	 */
6490 	btrfs_qgroup_convert_reserved_meta(root, INT_MAX);
6491 	btrfs_qgroup_free_meta_all_pertrans(root);
6492 
6493 	if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state))
6494 		btrfs_add_dropped_root(trans, root);
6495 	else
6496 		btrfs_put_root(root);
6497 	root_dropped = true;
6498 out_end_trans:
6499 	if (!is_reloc_root)
6500 		btrfs_set_last_root_drop_gen(fs_info, trans->transid);
6501 
6502 	btrfs_end_transaction_throttle(trans);
6503 out_free:
6504 	btrfs_free_path(path);
6505 out:
6506 	if (!ret && root_dropped) {
6507 		ret = btrfs_qgroup_cleanup_dropped_subvolume(fs_info, rootid);
6508 		if (ret < 0)
6509 			btrfs_warn_rl(fs_info,
6510 				      "failed to cleanup qgroup 0/%llu: %pe",
6511 				      rootid, ERR_PTR(ret));
6512 		ret = 0;
6513 	}
6514 	/*
6515 	 * We were an unfinished drop root, check to see if there are any
6516 	 * pending, and if not clear and wake up any waiters.
6517 	 */
6518 	if (!ret && unfinished_drop)
6519 		btrfs_maybe_wake_unfinished_drop(fs_info);
6520 
6521 	/*
6522 	 * So if we need to stop dropping the snapshot for whatever reason we
6523 	 * need to make sure to add it back to the dead root list so that we
6524 	 * keep trying to do the work later.  This also cleans up roots if we
6525 	 * don't have it in the radix (like when we recover after a power fail
6526 	 * or unmount) so we don't leak memory.
6527 	 */
6528 	if (!for_reloc && !root_dropped)
6529 		btrfs_add_dead_root(root);
6530 	return ret;
6531 }
6532 
6533 /*
6534  * drop subtree rooted at tree block 'node'.
6535  *
6536  * NOTE: this function will unlock and release tree block 'node'
6537  * only used by relocation code
6538  */
6539 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
6540 			struct btrfs_root *root,
6541 			struct extent_buffer *node,
6542 			struct extent_buffer *parent)
6543 {
6544 	struct btrfs_fs_info *fs_info = root->fs_info;
6545 	BTRFS_PATH_AUTO_FREE(path);
6546 	struct walk_control AUTO_KFREE(wc);
6547 	int level;
6548 	int parent_level;
6549 	int ret = 0;
6550 
6551 	BUG_ON(btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID);
6552 
6553 	path = btrfs_alloc_path();
6554 	if (!path)
6555 		return -ENOMEM;
6556 
6557 	wc = kzalloc(sizeof(*wc), GFP_NOFS);
6558 	if (!wc)
6559 		return -ENOMEM;
6560 
6561 	btrfs_assert_tree_write_locked(parent);
6562 	parent_level = btrfs_header_level(parent);
6563 	refcount_inc(&parent->refs);
6564 	path->nodes[parent_level] = parent;
6565 	path->slots[parent_level] = btrfs_header_nritems(parent);
6566 
6567 	btrfs_assert_tree_write_locked(node);
6568 	level = btrfs_header_level(node);
6569 	path->nodes[level] = node;
6570 	path->slots[level] = 0;
6571 	path->locks[level] = BTRFS_WRITE_LOCK;
6572 
6573 	wc->refs[parent_level] = 1;
6574 	wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
6575 	wc->level = level;
6576 	wc->shared_level = -1;
6577 	wc->stage = DROP_REFERENCE;
6578 	wc->update_ref = 0;
6579 	wc->keep_locks = 1;
6580 	wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
6581 
6582 	while (1) {
6583 		ret = walk_down_tree(trans, root, path, wc);
6584 		if (ret < 0)
6585 			return ret;
6586 
6587 		ret = walk_up_tree(trans, root, path, wc, parent_level);
6588 		if (ret) {
6589 			if (ret < 0)
6590 				return ret;
6591 			break;
6592 		}
6593 	}
6594 
6595 	return 0;
6596 }
6597 
6598 /*
6599  * Unpin the extent range in an error context and don't add the space back.
6600  * Errors are not propagated further.
6601  */
6602 void btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info, u64 start, u64 end)
6603 {
6604 	unpin_extent_range(fs_info, start, end, false);
6605 }
6606 
6607 /*
6608  * It used to be that old block groups would be left around forever.
6609  * Iterating over them would be enough to trim unused space.  Since we
6610  * now automatically remove them, we also need to iterate over unallocated
6611  * space.
6612  *
6613  * We don't want a transaction for this since the discard may take a
6614  * substantial amount of time.  We don't require that a transaction be
6615  * running, but we do need to take a running transaction into account
6616  * to ensure that we're not discarding chunks that were released or
6617  * allocated in the current transaction.
6618  *
6619  * Holding the chunks lock will prevent other threads from allocating
6620  * or releasing chunks, but it won't prevent a running transaction
6621  * from committing and releasing the memory that the pending chunks
6622  * list head uses.  For that, we need to take a reference to the
6623  * transaction and hold the commit root sem.  We only need to hold
6624  * it while performing the free space search since we have already
6625  * held back allocations.
6626  */
6627 static int btrfs_trim_free_extents_throttle(struct btrfs_device *device,
6628 					    u64 *trimmed, u64 pos, u64 *ret_next_pos)
6629 {
6630 	int ret;
6631 	u64 start = pos;
6632 	u64 trim_len = 0;
6633 
6634 	*trimmed = 0;
6635 
6636 	/*
6637 	 * The caller only filters out MISSING devices, but a device that was
6638 	 * missing at mount and later rescanned has MISSING cleared while bdev
6639 	 * is still NULL and WRITEABLE is still unset. Skip those here.
6640 	 */
6641 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) || !device->bdev)
6642 		return 0;
6643 
6644 	/* Discard not supported = nothing to do. */
6645 	if (!bdev_max_discard_sectors(device->bdev))
6646 		return 0;
6647 
6648 	/* No free space = nothing to do. */
6649 	if (device->total_bytes <= device->bytes_used)
6650 		return 0;
6651 
6652 	ret = 0;
6653 
6654 	while (1) {
6655 		struct btrfs_fs_info *fs_info = device->fs_info;
6656 		u64 cur_start;
6657 		u64 end;
6658 		u64 len;
6659 		u64 bytes;
6660 
6661 		ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
6662 		if (ret)
6663 			break;
6664 
6665 		cur_start = start;
6666 		btrfs_find_first_clear_extent_bit(&device->alloc_state, start,
6667 						  &start, &end,
6668 						  CHUNK_TRIMMED | CHUNK_ALLOCATED);
6669 		start = max(start, cur_start);
6670 
6671 		/* Check if there are any CHUNK_* bits left */
6672 		if (unlikely(start > device->total_bytes)) {
6673 			DEBUG_WARN();
6674 			btrfs_warn(fs_info,
6675 "ignoring attempt to trim beyond device size: offset %llu length %llu device %s device size %llu",
6676 					  start, end - start + 1,
6677 					  btrfs_dev_name(device),
6678 					  device->total_bytes);
6679 			mutex_unlock(&fs_info->chunk_mutex);
6680 			ret = 0;
6681 			break;
6682 		}
6683 
6684 		/* Ensure we skip the reserved space on each device. */
6685 		start = max_t(u64, start, BTRFS_DEVICE_RANGE_RESERVED);
6686 
6687 		/*
6688 		 * If find_first_clear_extent_bit find a range that spans the
6689 		 * end of the device it will set end to -1, in this case it's up
6690 		 * to the caller to trim the value to the size of the device.
6691 		 */
6692 		end = min(end, device->total_bytes - 1);
6693 
6694 		len = end - start + 1;
6695 		len = min(len, BTRFS_MAX_TRIM_LENGTH);
6696 
6697 		/* We didn't find any extents */
6698 		if (!len) {
6699 			mutex_unlock(&fs_info->chunk_mutex);
6700 			ret = 0;
6701 			break;
6702 		}
6703 
6704 		ret = btrfs_issue_discard(device->bdev, start, len,
6705 					  &bytes);
6706 		if (!ret)
6707 			btrfs_set_extent_bit(&device->alloc_state, start,
6708 					     start + bytes - 1, CHUNK_TRIMMED, NULL);
6709 		mutex_unlock(&fs_info->chunk_mutex);
6710 
6711 		if (ret)
6712 			break;
6713 
6714 		start += len;
6715 		*trimmed += bytes;
6716 		trim_len += len;
6717 		if (trim_len >= BTRFS_MAX_TRIM_LENGTH) {
6718 			*ret_next_pos = start;
6719 			ret = -EAGAIN;
6720 			break;
6721 		}
6722 
6723 		if (btrfs_trim_interrupted()) {
6724 			ret = -ERESTARTSYS;
6725 			break;
6726 		}
6727 
6728 		cond_resched();
6729 	}
6730 
6731 	return ret;
6732 }
6733 
6734 static int btrfs_trim_free_extents(struct btrfs_fs_info *fs_info, u64 *trimmed,
6735 				   u64 *dev_failed, int *dev_ret)
6736 {
6737 	struct btrfs_device *dev;
6738 	struct btrfs_device *working_dev = NULL;
6739 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6740 	u8 uuid[BTRFS_UUID_SIZE];
6741 	u64 start = BTRFS_DEVICE_RANGE_RESERVED;
6742 
6743 	*trimmed = 0;
6744 	*dev_failed = 0;
6745 	*dev_ret = 0;
6746 
6747 	/* Find the device with the smallest UUID to start. */
6748 	mutex_lock(&fs_devices->device_list_mutex);
6749 	list_for_each_entry(dev, &fs_devices->devices, dev_list) {
6750 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
6751 			continue;
6752 		if (!working_dev ||
6753 		    memcmp(dev->uuid, working_dev->uuid, BTRFS_UUID_SIZE) < 0)
6754 			working_dev = dev;
6755 	}
6756 	if (working_dev)
6757 		memcpy(uuid, working_dev->uuid, BTRFS_UUID_SIZE);
6758 	mutex_unlock(&fs_devices->device_list_mutex);
6759 
6760 	if (!working_dev)
6761 		return 0;
6762 
6763 	while (1) {
6764 		u64 group_trimmed = 0;
6765 		u64 next_pos = 0;
6766 		int ret = 0;
6767 
6768 		mutex_lock(&fs_devices->device_list_mutex);
6769 
6770 		/* Find and trim the current device. */
6771 		list_for_each_entry(dev, &fs_devices->devices, dev_list) {
6772 			if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
6773 				continue;
6774 			if (dev == working_dev) {
6775 				ret = btrfs_trim_free_extents_throttle(working_dev,
6776 						&group_trimmed, start, &next_pos);
6777 				break;
6778 			}
6779 		}
6780 
6781 		/* Throttle: continue the same device from the new position. */
6782 		if (ret == -EAGAIN && next_pos > start) {
6783 			mutex_unlock(&fs_devices->device_list_mutex);
6784 			*trimmed += group_trimmed;
6785 			start = next_pos;
6786 			cond_resched();
6787 			continue;
6788 		}
6789 
6790 		/* User interrupted. */
6791 		if (ret == -ERESTARTSYS || ret == -EINTR) {
6792 			mutex_unlock(&fs_devices->device_list_mutex);
6793 			*trimmed += group_trimmed;
6794 			return ret;
6795 		}
6796 
6797 		/*
6798 		 * Device completed (ret == 0), failed, or EAGAIN with no progress.
6799 		 * Record error if any, then move to next device.
6800 		 */
6801 		if (ret == -EAGAIN) {
6802 			/* No progress - log and skip device. */
6803 			btrfs_warn(fs_info,
6804 				   "trim throttle: no progress, offset=%llu device %s, skipping",
6805 				   start, btrfs_dev_name(working_dev));
6806 			(*dev_failed)++;
6807 			if (!*dev_ret)
6808 				*dev_ret = ret;
6809 		} else if (ret) {
6810 			/* Device failed with error. */
6811 			(*dev_failed)++;
6812 			if (!*dev_ret)
6813 				*dev_ret = ret;
6814 		}
6815 
6816 		/*
6817 		 * Find next device: smallest UUID larger than current.
6818 		 * Devices added during trim with smaller UUID will be skipped.
6819 		 */
6820 		working_dev = NULL;
6821 		list_for_each_entry(dev, &fs_devices->devices, dev_list) {
6822 			if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
6823 				continue;
6824 			/* Must larger than current UUID. */
6825 			if (memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE) <= 0)
6826 				continue;
6827 			/* Find the smallest. */
6828 			if (!working_dev ||
6829 			    memcmp(dev->uuid, working_dev->uuid, BTRFS_UUID_SIZE) < 0)
6830 				working_dev = dev;
6831 		}
6832 		if (working_dev)
6833 			memcpy(uuid, working_dev->uuid, BTRFS_UUID_SIZE);
6834 
6835 		mutex_unlock(&fs_devices->device_list_mutex);
6836 
6837 		*trimmed += group_trimmed;
6838 		start = BTRFS_DEVICE_RANGE_RESERVED;
6839 
6840 		/* No more devices. */
6841 		if (!working_dev)
6842 			break;
6843 
6844 		cond_resched();
6845 	}
6846 
6847 	return 0;
6848 }
6849 
6850 /*
6851  * Trim the whole filesystem by:
6852  * 1) trimming the free space in each block group
6853  * 2) trimming the unallocated space on each device
6854  *
6855  * This will also continue trimming even if a block group or device encounters
6856  * an error.  The return value will be the first error, or 0 if nothing bad
6857  * happens.
6858  */
6859 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
6860 {
6861 	struct btrfs_block_group *cache = NULL;
6862 	u64 group_trimmed;
6863 	u64 range_end = U64_MAX;
6864 	u64 start;
6865 	u64 end;
6866 	u64 trimmed = 0;
6867 	u64 bg_failed = 0;
6868 	u64 dev_failed = 0;
6869 	int bg_ret = 0;
6870 	int dev_ret = 0;
6871 	int ret = 0;
6872 
6873 	if (range->start == U64_MAX)
6874 		return -EINVAL;
6875 
6876 	/*
6877 	 * Check range overflow if range->len is set.
6878 	 * The default range->len is U64_MAX.
6879 	 */
6880 	if (range->len != U64_MAX &&
6881 	    check_add_overflow(range->start, range->len, &range_end))
6882 		return -EINVAL;
6883 
6884 	cache = btrfs_lookup_first_block_group(fs_info, range->start);
6885 	for (; cache; cache = btrfs_next_block_group(cache)) {
6886 		if (cache->start >= range_end) {
6887 			btrfs_put_block_group(cache);
6888 			break;
6889 		}
6890 
6891 		start = max(range->start, cache->start);
6892 		end = min(range_end, btrfs_block_group_end(cache));
6893 
6894 		if (end - start >= range->minlen) {
6895 			if (!btrfs_block_group_done(cache)) {
6896 				ret = btrfs_cache_block_group(cache, true);
6897 				if (ret) {
6898 					bg_failed++;
6899 					if (!bg_ret)
6900 						bg_ret = ret;
6901 					continue;
6902 				}
6903 			}
6904 			ret = btrfs_trim_block_group(cache,
6905 						     &group_trimmed,
6906 						     start,
6907 						     end,
6908 						     range->minlen);
6909 
6910 			trimmed += group_trimmed;
6911 			if (ret == -ERESTARTSYS || ret == -EINTR) {
6912 				btrfs_put_block_group(cache);
6913 				break;
6914 			}
6915 			if (ret) {
6916 				bg_failed++;
6917 				if (!bg_ret)
6918 					bg_ret = ret;
6919 				continue;
6920 			}
6921 		}
6922 	}
6923 
6924 	if (bg_failed)
6925 		btrfs_warn(fs_info,
6926 			"failed to trim %llu block group(s), first error %pe",
6927 			bg_failed, ERR_PTR(bg_ret));
6928 
6929 	if (ret == -ERESTARTSYS || ret == -EINTR)
6930 		return ret;
6931 
6932 	ret = btrfs_trim_free_extents(fs_info, &group_trimmed, &dev_failed, &dev_ret);
6933 	trimmed += group_trimmed;
6934 
6935 	if (dev_failed)
6936 		btrfs_warn(fs_info,
6937 			"failed to trim %llu device(s), first error %pe",
6938 			dev_failed, ERR_PTR(dev_ret));
6939 	range->len = trimmed;
6940 	if (ret == -ERESTARTSYS || ret == -EINTR)
6941 		return ret;
6942 	if (bg_ret)
6943 		return bg_ret;
6944 	return dev_ret;
6945 }
6946