xref: /linux/fs/btrfs/extent-tree.c (revision 1b1937eb08f51319bf71575484cde2b8c517aedc)
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 			ret = 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 	ret = btrfs_record_squota_delta(trans->fs_info, delta);
3184 	if (unlikely(ret)) {
3185 		btrfs_abort_transaction(trans, ret);
3186 		return ret;
3187 	}
3188 
3189 	/* If remapped, FST has already been taken care of in remove_range_from_remap_tree(). */
3190 	if (!remapped) {
3191 		ret = btrfs_add_to_free_space_tree(trans, bytenr, num_bytes);
3192 		if (unlikely(ret)) {
3193 			btrfs_abort_transaction(trans, ret);
3194 			return ret;
3195 		}
3196 	}
3197 
3198 	ret = btrfs_update_block_group(trans, bytenr, num_bytes, false);
3199 	if (ret)
3200 		btrfs_abort_transaction(trans, ret);
3201 
3202 	return ret;
3203 }
3204 
3205 #define abort_and_dump(trans, path, fmt, args...)	\
3206 ({							\
3207 	btrfs_abort_transaction(trans, -EUCLEAN);	\
3208 	btrfs_print_leaf(path->nodes[0]);		\
3209 	btrfs_crit(trans->fs_info, fmt, ##args);	\
3210 })
3211 
3212 /*
3213  * Drop one or more refs of @node.
3214  *
3215  * 1. Locate the extent refs.
3216  *    It's either inline in EXTENT/METADATA_ITEM or in keyed SHARED_* item.
3217  *    Locate it, then reduce the refs number or remove the ref line completely.
3218  *
3219  * 2. Update the refs count in EXTENT/METADATA_ITEM
3220  *
3221  * Inline backref case:
3222  *
3223  * in extent tree we have:
3224  *
3225  * 	item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
3226  *		refs 2 gen 6 flags DATA
3227  *		extent data backref root FS_TREE objectid 258 offset 0 count 1
3228  *		extent data backref root FS_TREE objectid 257 offset 0 count 1
3229  *
3230  * This function gets called with:
3231  *
3232  *    node->bytenr = 13631488
3233  *    node->num_bytes = 1048576
3234  *    root_objectid = FS_TREE
3235  *    owner_objectid = 257
3236  *    owner_offset = 0
3237  *    refs_to_drop = 1
3238  *
3239  * Then we should get some like:
3240  *
3241  * 	item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
3242  *		refs 1 gen 6 flags DATA
3243  *		extent data backref root FS_TREE objectid 258 offset 0 count 1
3244  *
3245  * Keyed backref case:
3246  *
3247  * in extent tree we have:
3248  *
3249  *	item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
3250  *		refs 754 gen 6 flags DATA
3251  *	[...]
3252  *	item 2 key (13631488 EXTENT_DATA_REF <HASH>) itemoff 3915 itemsize 28
3253  *		extent data backref root FS_TREE objectid 866 offset 0 count 1
3254  *
3255  * This function get called with:
3256  *
3257  *    node->bytenr = 13631488
3258  *    node->num_bytes = 1048576
3259  *    root_objectid = FS_TREE
3260  *    owner_objectid = 866
3261  *    owner_offset = 0
3262  *    refs_to_drop = 1
3263  *
3264  * Then we should get some like:
3265  *
3266  *	item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
3267  *		refs 753 gen 6 flags DATA
3268  *
3269  * And that (13631488 EXTENT_DATA_REF <HASH>) gets removed.
3270  */
3271 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
3272 			       struct btrfs_delayed_ref_head *href,
3273 			       const struct btrfs_delayed_ref_node *node,
3274 			       struct btrfs_delayed_extent_op *extent_op)
3275 {
3276 	struct btrfs_fs_info *info = trans->fs_info;
3277 	struct btrfs_key key;
3278 	BTRFS_PATH_AUTO_FREE(path);
3279 	struct btrfs_root *extent_root;
3280 	struct extent_buffer *leaf;
3281 	struct btrfs_extent_item *ei;
3282 	struct btrfs_extent_inline_ref *iref;
3283 	int ret;
3284 	int is_data;
3285 	int extent_slot = 0;
3286 	bool found_extent = false;
3287 	int num_to_del = 1;
3288 	int refs_to_drop = node->ref_mod;
3289 	u32 item_size;
3290 	u64 refs;
3291 	u64 bytenr = node->bytenr;
3292 	u64 num_bytes = node->num_bytes;
3293 	u64 owner_objectid = btrfs_delayed_ref_owner(node);
3294 	u64 owner_offset = btrfs_delayed_ref_offset(node);
3295 	bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
3296 	u64 delayed_ref_root = href->owning_root;
3297 
3298 	extent_root = btrfs_extent_root(info, bytenr);
3299 	if (unlikely(!extent_root)) {
3300 		btrfs_err(info,
3301 			  "missing extent root for extent at bytenr %llu", bytenr);
3302 		return -EUCLEAN;
3303 	}
3304 
3305 	path = btrfs_alloc_path();
3306 	if (!path)
3307 		return -ENOMEM;
3308 
3309 	is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
3310 
3311 	if (unlikely(!is_data && refs_to_drop != 1)) {
3312 		btrfs_crit(info,
3313 "invalid refs_to_drop, dropping more than 1 refs for tree block %llu refs_to_drop %u",
3314 			   node->bytenr, refs_to_drop);
3315 		ret = -EINVAL;
3316 		btrfs_abort_transaction(trans, ret);
3317 		return ret;
3318 	}
3319 
3320 	if (is_data)
3321 		skinny_metadata = false;
3322 
3323 	ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
3324 				    node->parent, node->ref_root, owner_objectid,
3325 				    owner_offset);
3326 	if (ret == 0) {
3327 		/*
3328 		 * Either the inline backref or the SHARED_DATA_REF/
3329 		 * SHARED_BLOCK_REF is found
3330 		 *
3331 		 * Here is a quick path to locate EXTENT/METADATA_ITEM.
3332 		 * It's possible the EXTENT/METADATA_ITEM is near current slot.
3333 		 */
3334 		extent_slot = path->slots[0];
3335 		while (extent_slot >= 0) {
3336 			btrfs_item_key_to_cpu(path->nodes[0], &key,
3337 					      extent_slot);
3338 			if (key.objectid != bytenr)
3339 				break;
3340 			if (key.type == BTRFS_EXTENT_ITEM_KEY &&
3341 			    key.offset == num_bytes) {
3342 				found_extent = true;
3343 				break;
3344 			}
3345 			if (key.type == BTRFS_METADATA_ITEM_KEY &&
3346 			    key.offset == owner_objectid) {
3347 				found_extent = true;
3348 				break;
3349 			}
3350 
3351 			/* Quick path didn't find the EXTENT/METADATA_ITEM */
3352 			if (path->slots[0] - extent_slot > 5)
3353 				break;
3354 			extent_slot--;
3355 		}
3356 
3357 		if (!found_extent) {
3358 			if (unlikely(iref)) {
3359 				abort_and_dump(trans, path,
3360 "invalid iref slot %u, no EXTENT/METADATA_ITEM found but has inline extent ref",
3361 					   path->slots[0]);
3362 				return -EUCLEAN;
3363 			}
3364 			/* Must be SHARED_* item, remove the backref first */
3365 			ret = remove_extent_backref(trans, extent_root, path,
3366 						    NULL, refs_to_drop, is_data);
3367 			if (unlikely(ret)) {
3368 				btrfs_abort_transaction(trans, ret);
3369 				return ret;
3370 			}
3371 			btrfs_release_path(path);
3372 
3373 			/* Slow path to locate EXTENT/METADATA_ITEM */
3374 			key.objectid = bytenr;
3375 			key.type = BTRFS_EXTENT_ITEM_KEY;
3376 			key.offset = num_bytes;
3377 
3378 			if (!is_data && skinny_metadata) {
3379 				key.type = BTRFS_METADATA_ITEM_KEY;
3380 				key.offset = owner_objectid;
3381 			}
3382 
3383 			ret = btrfs_search_slot(trans, extent_root,
3384 						&key, path, -1, 1);
3385 			if (ret > 0 && skinny_metadata && path->slots[0]) {
3386 				/*
3387 				 * Couldn't find our skinny metadata item,
3388 				 * see if we have ye olde extent item.
3389 				 */
3390 				path->slots[0]--;
3391 				btrfs_item_key_to_cpu(path->nodes[0], &key,
3392 						      path->slots[0]);
3393 				if (key.objectid == bytenr &&
3394 				    key.type == BTRFS_EXTENT_ITEM_KEY &&
3395 				    key.offset == num_bytes)
3396 					ret = 0;
3397 			}
3398 
3399 			if (ret > 0 && skinny_metadata) {
3400 				skinny_metadata = false;
3401 				key.objectid = bytenr;
3402 				key.type = BTRFS_EXTENT_ITEM_KEY;
3403 				key.offset = num_bytes;
3404 				btrfs_release_path(path);
3405 				ret = btrfs_search_slot(trans, extent_root,
3406 							&key, path, -1, 1);
3407 			}
3408 
3409 			if (ret) {
3410 				if (ret > 0)
3411 					btrfs_print_leaf(path->nodes[0]);
3412 				btrfs_err(info,
3413 			"umm, got %d back from search, was looking for %llu, slot %d",
3414 					  ret, bytenr, path->slots[0]);
3415 			}
3416 			if (unlikely(ret < 0)) {
3417 				btrfs_abort_transaction(trans, ret);
3418 				return ret;
3419 			}
3420 			extent_slot = path->slots[0];
3421 		}
3422 	} else if (WARN_ON(ret == -ENOENT)) {
3423 		abort_and_dump(trans, path,
3424 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu slot %d",
3425 			       bytenr, node->parent, node->ref_root, owner_objectid,
3426 			       owner_offset, path->slots[0]);
3427 		return ret;
3428 	} else {
3429 		btrfs_abort_transaction(trans, ret);
3430 		return ret;
3431 	}
3432 
3433 	leaf = path->nodes[0];
3434 	item_size = btrfs_item_size(leaf, extent_slot);
3435 	if (unlikely(item_size < sizeof(*ei))) {
3436 		ret = -EUCLEAN;
3437 		btrfs_err(trans->fs_info,
3438 			  "unexpected extent item size, has %u expect >= %zu",
3439 			  item_size, sizeof(*ei));
3440 		btrfs_abort_transaction(trans, ret);
3441 		return ret;
3442 	}
3443 	ei = btrfs_item_ptr(leaf, extent_slot,
3444 			    struct btrfs_extent_item);
3445 	if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
3446 	    key.type == BTRFS_EXTENT_ITEM_KEY) {
3447 		struct btrfs_tree_block_info *bi;
3448 
3449 		if (unlikely(item_size < sizeof(*ei) + sizeof(*bi))) {
3450 			abort_and_dump(trans, path,
3451 "invalid extent item size for key (%llu, %u, %llu) slot %u owner %llu, has %u expect >= %zu",
3452 				       key.objectid, key.type, key.offset,
3453 				       path->slots[0], owner_objectid, item_size,
3454 				       sizeof(*ei) + sizeof(*bi));
3455 			return -EUCLEAN;
3456 		}
3457 		bi = (struct btrfs_tree_block_info *)(ei + 1);
3458 		WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
3459 	}
3460 
3461 	refs = btrfs_extent_refs(leaf, ei);
3462 	if (unlikely(refs < refs_to_drop)) {
3463 		abort_and_dump(trans, path,
3464 		"trying to drop %d refs but we only have %llu for bytenr %llu slot %u",
3465 			       refs_to_drop, refs, bytenr, path->slots[0]);
3466 		return -EUCLEAN;
3467 	}
3468 	refs -= refs_to_drop;
3469 
3470 	if (refs > 0) {
3471 		if (extent_op)
3472 			__run_delayed_extent_op(extent_op, leaf, ei);
3473 		/*
3474 		 * In the case of inline back ref, reference count will
3475 		 * be updated by remove_extent_backref
3476 		 */
3477 		if (iref) {
3478 			if (unlikely(!found_extent)) {
3479 				abort_and_dump(trans, path,
3480 "invalid iref, got inlined extent ref but no EXTENT/METADATA_ITEM found, slot %u",
3481 					       path->slots[0]);
3482 				return -EUCLEAN;
3483 			}
3484 		} else {
3485 			btrfs_set_extent_refs(leaf, ei, refs);
3486 		}
3487 		if (found_extent) {
3488 			ret = remove_extent_backref(trans, extent_root, path,
3489 						    iref, refs_to_drop, is_data);
3490 			if (unlikely(ret)) {
3491 				btrfs_abort_transaction(trans, ret);
3492 				return ret;
3493 			}
3494 		}
3495 	} else {
3496 		struct btrfs_squota_delta delta = {
3497 			.root = delayed_ref_root,
3498 			.num_bytes = num_bytes,
3499 			.is_data = is_data,
3500 			.is_inc = false,
3501 			.generation = btrfs_extent_generation(leaf, ei),
3502 		};
3503 
3504 		/* In this branch refs == 1 */
3505 		if (found_extent) {
3506 			if (unlikely(is_data && refs_to_drop !=
3507 				     extent_data_ref_count(path, iref))) {
3508 				abort_and_dump(trans, path,
3509 		"invalid refs_to_drop, current refs %u refs_to_drop %u slot %u",
3510 					       extent_data_ref_count(path, iref),
3511 					       refs_to_drop, path->slots[0]);
3512 				return -EUCLEAN;
3513 			}
3514 			if (iref) {
3515 				if (unlikely(path->slots[0] != extent_slot)) {
3516 					abort_and_dump(trans, path,
3517 "invalid iref, extent item key " BTRFS_KEY_FMT " slot %u doesn't have wanted iref",
3518 						       BTRFS_KEY_FMT_VALUE(&key),
3519 						       path->slots[0]);
3520 					return -EUCLEAN;
3521 				}
3522 			} else {
3523 				/*
3524 				 * No inline ref, we must be at SHARED_* item,
3525 				 * And it's single ref, it must be:
3526 				 * |	extent_slot	  ||extent_slot + 1|
3527 				 * [ EXTENT/METADATA_ITEM ][ SHARED_* ITEM ]
3528 				 */
3529 				if (unlikely(path->slots[0] != extent_slot + 1)) {
3530 					abort_and_dump(trans, path,
3531 	"invalid SHARED_* item slot %u, previous item is not EXTENT/METADATA_ITEM",
3532 						       path->slots[0]);
3533 					return -EUCLEAN;
3534 				}
3535 				path->slots[0] = extent_slot;
3536 				num_to_del = 2;
3537 			}
3538 		}
3539 		/*
3540 		 * We can't infer the data owner from the delayed ref, so we need
3541 		 * to try to get it from the owning ref item.
3542 		 *
3543 		 * If it is not present, then that extent was not written under
3544 		 * simple quotas mode, so we don't need to account for its deletion.
3545 		 */
3546 		if (is_data)
3547 			delta.root = btrfs_get_extent_owner_root(trans->fs_info,
3548 								 leaf, extent_slot);
3549 
3550 		ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
3551 				      num_to_del);
3552 		if (unlikely(ret)) {
3553 			btrfs_abort_transaction(trans, ret);
3554 			return ret;
3555 		}
3556 		btrfs_release_path(path);
3557 
3558 		ret = do_free_extent_accounting(trans, bytenr, &delta, path);
3559 	}
3560 	btrfs_release_path(path);
3561 
3562 	return ret;
3563 }
3564 
3565 /*
3566  * when we free an block, it is possible (and likely) that we free the last
3567  * delayed ref for that extent as well.  This searches the delayed ref tree for
3568  * a given extent, and if there are no other delayed refs to be processed, it
3569  * removes it from the tree.
3570  */
3571 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
3572 				      u64 bytenr)
3573 {
3574 	struct btrfs_fs_info *fs_info = trans->fs_info;
3575 	struct btrfs_delayed_ref_head *head;
3576 	struct btrfs_delayed_ref_root *delayed_refs;
3577 	int ret = 0;
3578 
3579 	delayed_refs = &trans->transaction->delayed_refs;
3580 	spin_lock(&delayed_refs->lock);
3581 	head = btrfs_find_delayed_ref_head(fs_info, delayed_refs, bytenr);
3582 	if (!head)
3583 		goto out_delayed_unlock;
3584 
3585 	spin_lock(&head->lock);
3586 	if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
3587 		goto out;
3588 
3589 	if (cleanup_extent_op(head) != NULL)
3590 		goto out;
3591 
3592 	/*
3593 	 * waiting for the lock here would deadlock.  If someone else has it
3594 	 * locked they are already in the process of dropping it anyway
3595 	 */
3596 	if (!mutex_trylock(&head->mutex))
3597 		goto out;
3598 
3599 	btrfs_delete_ref_head(fs_info, delayed_refs, head);
3600 	head->processing = false;
3601 
3602 	spin_unlock(&head->lock);
3603 	spin_unlock(&delayed_refs->lock);
3604 
3605 	BUG_ON(head->extent_op);
3606 	if (head->must_insert_reserved)
3607 		ret = 1;
3608 
3609 	btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
3610 	mutex_unlock(&head->mutex);
3611 	btrfs_put_delayed_ref_head(head);
3612 	return ret;
3613 out:
3614 	spin_unlock(&head->lock);
3615 
3616 out_delayed_unlock:
3617 	spin_unlock(&delayed_refs->lock);
3618 	return 0;
3619 }
3620 
3621 int btrfs_free_tree_block(struct btrfs_trans_handle *trans,
3622 			  u64 root_id,
3623 			  struct extent_buffer *buf,
3624 			  u64 parent, int last_ref)
3625 {
3626 	struct btrfs_fs_info *fs_info = trans->fs_info;
3627 	struct btrfs_block_group *bg;
3628 	int ret;
3629 
3630 	if (root_id != BTRFS_TREE_LOG_OBJECTID) {
3631 		struct btrfs_ref generic_ref = {
3632 			.action = BTRFS_DROP_DELAYED_REF,
3633 			.bytenr = buf->start,
3634 			.num_bytes = buf->len,
3635 			.parent = parent,
3636 			.owning_root = btrfs_header_owner(buf),
3637 			.ref_root = root_id,
3638 		};
3639 
3640 		/*
3641 		 * Assert that the extent buffer is not cleared due to
3642 		 * EXTENT_BUFFER_ZONED_ZEROOUT. Please refer
3643 		 * btrfs_clear_buffer_dirty() and btree_csum_one_bio() for
3644 		 * detail.
3645 		 */
3646 		ASSERT(btrfs_header_bytenr(buf) != 0);
3647 
3648 		btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf), 0, false);
3649 		btrfs_ref_tree_mod(fs_info, &generic_ref);
3650 		ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL);
3651 		if (ret < 0)
3652 			return ret;
3653 	}
3654 
3655 	if (!last_ref)
3656 		return 0;
3657 
3658 	if (btrfs_header_generation(buf) != trans->transid)
3659 		return 0;
3660 
3661 	if (root_id != BTRFS_TREE_LOG_OBJECTID) {
3662 		ret = check_ref_cleanup(trans, buf->start);
3663 		if (!ret)
3664 			return 0;
3665 	}
3666 
3667 	bg = btrfs_lookup_block_group(fs_info, buf->start);
3668 
3669 	if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
3670 		pin_down_extent(trans, bg, buf->start, buf->len, true);
3671 		btrfs_put_block_group(bg);
3672 		return 0;
3673 	}
3674 
3675 	/*
3676 	 * If there are tree mod log users we may have recorded mod log
3677 	 * operations for this node.  If we re-allocate this node we
3678 	 * could replay operations on this node that happened when it
3679 	 * existed in a completely different root.  For example if it
3680 	 * was part of root A, then was reallocated to root B, and we
3681 	 * are doing a btrfs_old_search_slot(root b), we could replay
3682 	 * operations that happened when the block was part of root A,
3683 	 * giving us an inconsistent view of the btree.
3684 	 *
3685 	 * We are safe from races here because at this point no other
3686 	 * node or root points to this extent buffer, so if after this
3687 	 * check a new tree mod log user joins we will not have an
3688 	 * existing log of operations on this node that we have to
3689 	 * contend with.
3690 	 */
3691 
3692 	if (test_bit(BTRFS_FS_TREE_MOD_LOG_USERS, &fs_info->flags)
3693 		     || btrfs_is_zoned(fs_info)) {
3694 		pin_down_extent(trans, bg, buf->start, buf->len, true);
3695 		btrfs_put_block_group(bg);
3696 		return 0;
3697 	}
3698 
3699 	WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
3700 
3701 	btrfs_add_free_space(bg, buf->start, buf->len);
3702 	btrfs_free_reserved_bytes(bg, buf->len, false);
3703 	btrfs_put_block_group(bg);
3704 	trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
3705 
3706 	return 0;
3707 }
3708 
3709 /* Can return -ENOMEM */
3710 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
3711 {
3712 	struct btrfs_fs_info *fs_info = trans->fs_info;
3713 	int ret;
3714 
3715 	if (btrfs_is_testing(fs_info))
3716 		return 0;
3717 
3718 	/*
3719 	 * tree log blocks never actually go into the extent allocation
3720 	 * tree, just update pinning info and exit early.
3721 	 */
3722 	if (ref->ref_root == BTRFS_TREE_LOG_OBJECTID) {
3723 		btrfs_pin_extent(trans, ref->bytenr, ref->num_bytes);
3724 		ret = 0;
3725 	} else if (ref->type == BTRFS_REF_METADATA) {
3726 		ret = btrfs_add_delayed_tree_ref(trans, ref, NULL);
3727 	} else {
3728 		ret = btrfs_add_delayed_data_ref(trans, ref, 0);
3729 	}
3730 
3731 	if (ref->ref_root != BTRFS_TREE_LOG_OBJECTID)
3732 		btrfs_ref_tree_mod(fs_info, ref);
3733 
3734 	return ret;
3735 }
3736 
3737 enum btrfs_loop_type {
3738 	/*
3739 	 * Start caching block groups but do not wait for progress or for them
3740 	 * to be done.
3741 	 */
3742 	LOOP_CACHING_NOWAIT,
3743 
3744 	/*
3745 	 * Wait for the block group free_space >= the space we're waiting for if
3746 	 * the block group isn't cached.
3747 	 */
3748 	LOOP_CACHING_WAIT,
3749 
3750 	/*
3751 	 * Allow allocations to happen from block groups that do not yet have a
3752 	 * size classification.
3753 	 */
3754 	LOOP_UNSET_SIZE_CLASS,
3755 
3756 	/*
3757 	 * Allocate a chunk and then retry the allocation.
3758 	 */
3759 	LOOP_ALLOC_CHUNK,
3760 
3761 	/*
3762 	 * Ignore the size class restrictions for this allocation.
3763 	 */
3764 	LOOP_WRONG_SIZE_CLASS,
3765 
3766 	/*
3767 	 * Ignore the empty size, only try to allocate the number of bytes
3768 	 * needed for this allocation.
3769 	 */
3770 	LOOP_NO_EMPTY_SIZE,
3771 };
3772 
3773 static inline void
3774 btrfs_lock_block_group(struct btrfs_block_group *cache, bool delalloc)
3775 {
3776 	if (delalloc)
3777 		down_read(&cache->data_rwsem);
3778 }
3779 
3780 static inline void btrfs_grab_block_group(struct btrfs_block_group *cache,
3781 					  bool delalloc)
3782 {
3783 	btrfs_get_block_group(cache);
3784 	if (delalloc)
3785 		down_read(&cache->data_rwsem);
3786 }
3787 
3788 static struct btrfs_block_group *btrfs_lock_cluster(
3789 		   struct btrfs_block_group *block_group,
3790 		   struct btrfs_free_cluster *cluster,
3791 		   bool delalloc)
3792 	__acquires(&cluster->refill_lock)
3793 {
3794 	struct btrfs_block_group *used_bg = NULL;
3795 
3796 	spin_lock(&cluster->refill_lock);
3797 	while (1) {
3798 		used_bg = cluster->block_group;
3799 		if (!used_bg)
3800 			return NULL;
3801 
3802 		if (used_bg == block_group)
3803 			return used_bg;
3804 
3805 		btrfs_get_block_group(used_bg);
3806 
3807 		if (!delalloc)
3808 			return used_bg;
3809 
3810 		if (down_read_trylock(&used_bg->data_rwsem))
3811 			return used_bg;
3812 
3813 		spin_unlock(&cluster->refill_lock);
3814 
3815 		/* We should only have one-level nested. */
3816 		down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
3817 
3818 		spin_lock(&cluster->refill_lock);
3819 		if (used_bg == cluster->block_group)
3820 			return used_bg;
3821 
3822 		up_read(&used_bg->data_rwsem);
3823 		btrfs_put_block_group(used_bg);
3824 	}
3825 }
3826 
3827 static inline void
3828 btrfs_release_block_group(struct btrfs_block_group *cache, bool delalloc)
3829 {
3830 	if (delalloc)
3831 		up_read(&cache->data_rwsem);
3832 	btrfs_put_block_group(cache);
3833 }
3834 
3835 static bool find_free_extent_check_size_class(const struct find_free_extent_ctl *ffe_ctl,
3836 					      const struct btrfs_block_group *bg)
3837 {
3838 	if (ffe_ctl->policy == BTRFS_EXTENT_ALLOC_ZONED)
3839 		return true;
3840 	if (!btrfs_block_group_should_use_size_class(bg))
3841 		return true;
3842 	if (ffe_ctl->loop >= LOOP_WRONG_SIZE_CLASS)
3843 		return true;
3844 	if (ffe_ctl->loop >= LOOP_UNSET_SIZE_CLASS &&
3845 	    bg->size_class == BTRFS_BG_SZ_NONE)
3846 		return true;
3847 	return ffe_ctl->size_class == bg->size_class;
3848 }
3849 
3850 /*
3851  * Helper function for find_free_extent().
3852  *
3853  * Return -ENOENT to inform caller that we need fallback to unclustered mode.
3854  * Return >0 to inform caller that we find nothing
3855  * Return 0 means we have found a location and set ffe_ctl->found_offset.
3856  */
3857 static int find_free_extent_clustered(struct btrfs_block_group *bg,
3858 				      struct find_free_extent_ctl *ffe_ctl,
3859 				      struct btrfs_block_group **cluster_bg_ret)
3860 {
3861 	struct btrfs_block_group *cluster_bg;
3862 	struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3863 	u64 aligned_cluster;
3864 	u64 offset;
3865 	int ret;
3866 
3867 	cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
3868 	if (!cluster_bg)
3869 		goto refill_cluster;
3870 	if (cluster_bg != bg && (cluster_bg->ro ||
3871 	    !block_group_bits(cluster_bg, ffe_ctl->flags) ||
3872 	    !find_free_extent_check_size_class(ffe_ctl, cluster_bg)))
3873 		goto release_cluster;
3874 
3875 	offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
3876 			ffe_ctl->num_bytes, cluster_bg->start,
3877 			&ffe_ctl->max_extent_size);
3878 	if (offset) {
3879 		/* We have a block, we're done */
3880 		spin_unlock(&last_ptr->refill_lock);
3881 		trace_btrfs_reserve_extent_cluster(cluster_bg, ffe_ctl);
3882 		*cluster_bg_ret = cluster_bg;
3883 		ffe_ctl->found_offset = offset;
3884 		return 0;
3885 	}
3886 	WARN_ON(last_ptr->block_group != cluster_bg);
3887 
3888 release_cluster:
3889 	/*
3890 	 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
3891 	 * lets just skip it and let the allocator find whatever block it can
3892 	 * find. If we reach this point, we will have tried the cluster
3893 	 * allocator plenty of times and not have found anything, so we are
3894 	 * likely way too fragmented for the clustering stuff to find anything.
3895 	 *
3896 	 * However, if the cluster is taken from the current block group,
3897 	 * release the cluster first, so that we stand a better chance of
3898 	 * succeeding in the unclustered allocation.
3899 	 */
3900 	if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
3901 		spin_unlock(&last_ptr->refill_lock);
3902 		btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3903 		return -ENOENT;
3904 	}
3905 
3906 	/* This cluster didn't work out, free it and start over */
3907 	btrfs_return_cluster_to_free_space(NULL, last_ptr);
3908 
3909 	if (cluster_bg != bg)
3910 		btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3911 
3912 refill_cluster:
3913 	if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
3914 		spin_unlock(&last_ptr->refill_lock);
3915 		return -ENOENT;
3916 	}
3917 
3918 	aligned_cluster = max_t(u64,
3919 			ffe_ctl->empty_cluster + ffe_ctl->empty_size,
3920 			bg->full_stripe_len);
3921 	ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
3922 			ffe_ctl->num_bytes, aligned_cluster);
3923 	if (ret == 0) {
3924 		/* Now pull our allocation out of this cluster */
3925 		offset = btrfs_alloc_from_cluster(bg, last_ptr,
3926 				ffe_ctl->num_bytes, ffe_ctl->search_start,
3927 				&ffe_ctl->max_extent_size);
3928 		if (offset) {
3929 			/* We found one, proceed */
3930 			spin_unlock(&last_ptr->refill_lock);
3931 			ffe_ctl->found_offset = offset;
3932 			trace_btrfs_reserve_extent_cluster(bg, ffe_ctl);
3933 			return 0;
3934 		}
3935 	}
3936 	/*
3937 	 * At this point we either didn't find a cluster or we weren't able to
3938 	 * allocate a block from our cluster.  Free the cluster we've been
3939 	 * trying to use, and go to the next block group.
3940 	 */
3941 	btrfs_return_cluster_to_free_space(NULL, last_ptr);
3942 	spin_unlock(&last_ptr->refill_lock);
3943 	return 1;
3944 }
3945 
3946 /*
3947  * Return >0 to inform caller that we find nothing
3948  * Return 0 when we found an free extent and set ffe_ctrl->found_offset
3949  */
3950 static int find_free_extent_unclustered(struct btrfs_block_group *bg,
3951 					struct find_free_extent_ctl *ffe_ctl)
3952 {
3953 	struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3954 	u64 offset;
3955 
3956 	/*
3957 	 * We are doing an unclustered allocation, set the fragmented flag so
3958 	 * we don't bother trying to setup a cluster again until we get more
3959 	 * space.
3960 	 */
3961 	if (unlikely(last_ptr)) {
3962 		spin_lock(&last_ptr->lock);
3963 		last_ptr->fragmented = 1;
3964 		spin_unlock(&last_ptr->lock);
3965 	}
3966 	if (ffe_ctl->cached) {
3967 		struct btrfs_free_space_ctl *free_space_ctl;
3968 
3969 		free_space_ctl = bg->free_space_ctl;
3970 		spin_lock(&free_space_ctl->tree_lock);
3971 		if (free_space_ctl->free_space <
3972 		    ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
3973 		    ffe_ctl->empty_size) {
3974 			ffe_ctl->total_free_space = max_t(u64,
3975 					ffe_ctl->total_free_space,
3976 					free_space_ctl->free_space);
3977 			spin_unlock(&free_space_ctl->tree_lock);
3978 			return 1;
3979 		}
3980 		spin_unlock(&free_space_ctl->tree_lock);
3981 	}
3982 
3983 	offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
3984 			ffe_ctl->num_bytes, ffe_ctl->empty_size,
3985 			&ffe_ctl->max_extent_size);
3986 	if (!offset)
3987 		return 1;
3988 	ffe_ctl->found_offset = offset;
3989 	return 0;
3990 }
3991 
3992 static int do_allocation_clustered(struct btrfs_block_group *block_group,
3993 				   struct find_free_extent_ctl *ffe_ctl,
3994 				   struct btrfs_block_group **bg_ret)
3995 {
3996 	int ret;
3997 
3998 	/* We want to try and use the cluster allocator, so lets look there */
3999 	if (ffe_ctl->last_ptr && ffe_ctl->use_cluster) {
4000 		ret = find_free_extent_clustered(block_group, ffe_ctl, bg_ret);
4001 		if (ret >= 0)
4002 			return ret;
4003 		/* ret == -ENOENT case falls through */
4004 	}
4005 
4006 	return find_free_extent_unclustered(block_group, ffe_ctl);
4007 }
4008 
4009 /*
4010  * Tree-log block group locking
4011  * ============================
4012  *
4013  * fs_info::treelog_bg_lock protects the fs_info::treelog_bg which
4014  * indicates the starting address of a block group, which is reserved only
4015  * for tree-log metadata.
4016  *
4017  * Lock nesting
4018  * ============
4019  *
4020  * block_group::lock
4021  *   fs_info::treelog_bg_lock
4022  */
4023 
4024 /*
4025  * Simple allocator for sequential-only block group. It only allows sequential
4026  * allocation. No need to play with trees. This function also reserves the
4027  * bytes as in btrfs_add_reserved_bytes.
4028  */
4029 static int do_allocation_zoned(struct btrfs_block_group *block_group,
4030 			       struct find_free_extent_ctl *ffe_ctl,
4031 			       struct btrfs_block_group **bg_ret)
4032 {
4033 	struct btrfs_fs_info *fs_info = block_group->fs_info;
4034 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
4035 	u64 start = block_group->start;
4036 	u64 num_bytes = ffe_ctl->num_bytes;
4037 	u64 avail;
4038 	u64 bytenr = block_group->start;
4039 	u64 log_bytenr;
4040 	u64 data_reloc_bytenr;
4041 	int ret = 0;
4042 	bool skip = false;
4043 
4044 	ASSERT(btrfs_is_zoned(block_group->fs_info));
4045 
4046 	/*
4047 	 * Do not allow non-tree-log blocks in the dedicated tree-log block
4048 	 * group, and vice versa.
4049 	 */
4050 	spin_lock(&fs_info->treelog_bg_lock);
4051 	log_bytenr = fs_info->treelog_bg;
4052 	if (log_bytenr && ((ffe_ctl->for_treelog && bytenr != log_bytenr) ||
4053 			   (!ffe_ctl->for_treelog && bytenr == log_bytenr)))
4054 		skip = true;
4055 	spin_unlock(&fs_info->treelog_bg_lock);
4056 	if (skip)
4057 		return 1;
4058 
4059 	/*
4060 	 * Do not allow non-relocation blocks in the dedicated relocation block
4061 	 * group, and vice versa.
4062 	 */
4063 	spin_lock(&fs_info->relocation_bg_lock);
4064 	data_reloc_bytenr = fs_info->data_reloc_bg;
4065 	if (data_reloc_bytenr &&
4066 	    ((ffe_ctl->for_data_reloc && bytenr != data_reloc_bytenr) ||
4067 	     (!ffe_ctl->for_data_reloc && bytenr == data_reloc_bytenr)))
4068 		skip = true;
4069 	spin_unlock(&fs_info->relocation_bg_lock);
4070 	if (skip)
4071 		return 1;
4072 
4073 	/* Check RO and no space case before trying to activate it */
4074 	spin_lock(&block_group->lock);
4075 	if (block_group->ro || btrfs_zoned_bg_is_full(block_group)) {
4076 		ret = 1;
4077 		/*
4078 		 * May need to clear fs_info->{treelog,data_reloc}_bg.
4079 		 * Return the error after taking the locks.
4080 		 */
4081 	}
4082 	spin_unlock(&block_group->lock);
4083 
4084 	/* Metadata block group is activated at write time. */
4085 	if (!ret && (block_group->flags & BTRFS_BLOCK_GROUP_DATA) &&
4086 	    !btrfs_zone_activate(block_group)) {
4087 		ret = 1;
4088 		/*
4089 		 * May need to clear fs_info->{treelog,data_reloc}_bg.
4090 		 * Return the error after taking the locks.
4091 		 */
4092 	}
4093 
4094 	spin_lock(&block_group->lock);
4095 	spin_lock(&fs_info->treelog_bg_lock);
4096 	spin_lock(&fs_info->relocation_bg_lock);
4097 
4098 	if (ret)
4099 		goto out;
4100 
4101 	ASSERT(!ffe_ctl->for_treelog ||
4102 	       block_group->start == fs_info->treelog_bg ||
4103 	       fs_info->treelog_bg == 0);
4104 	ASSERT(!ffe_ctl->for_data_reloc ||
4105 	       block_group->start == fs_info->data_reloc_bg ||
4106 	       fs_info->data_reloc_bg == 0);
4107 
4108 	if (block_group->ro ||
4109 	    (!ffe_ctl->for_data_reloc &&
4110 	     test_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags))) {
4111 		ret = 1;
4112 		goto out;
4113 	}
4114 
4115 	/*
4116 	 * Do not allow currently using block group to be tree-log dedicated
4117 	 * block group.
4118 	 */
4119 	if (ffe_ctl->for_treelog && !fs_info->treelog_bg &&
4120 	    (block_group->used || block_group->reserved)) {
4121 		ret = 1;
4122 		goto out;
4123 	}
4124 
4125 	/*
4126 	 * Do not allow currently used block group to be the data relocation
4127 	 * dedicated block group.
4128 	 */
4129 	if (ffe_ctl->for_data_reloc && !fs_info->data_reloc_bg &&
4130 	    (block_group->used || block_group->reserved)) {
4131 		ret = 1;
4132 		goto out;
4133 	}
4134 
4135 	WARN_ON_ONCE(block_group->alloc_offset > block_group->zone_capacity);
4136 	avail = block_group->zone_capacity - block_group->alloc_offset;
4137 	if (avail < num_bytes) {
4138 		if (ffe_ctl->max_extent_size < avail) {
4139 			/*
4140 			 * With sequential allocator, free space is always
4141 			 * contiguous
4142 			 */
4143 			ffe_ctl->max_extent_size = avail;
4144 			ffe_ctl->total_free_space = avail;
4145 		}
4146 		ret = 1;
4147 		goto out;
4148 	}
4149 
4150 	if (ffe_ctl->for_treelog && !fs_info->treelog_bg)
4151 		fs_info->treelog_bg = block_group->start;
4152 
4153 	if (ffe_ctl->for_data_reloc) {
4154 		if (!fs_info->data_reloc_bg)
4155 			fs_info->data_reloc_bg = block_group->start;
4156 		/*
4157 		 * Do not allow allocations from this block group, unless it is
4158 		 * for data relocation. Compared to increasing the ->ro, setting
4159 		 * the ->zoned_data_reloc_ongoing flag still allows nocow
4160 		 * writers to come in. See btrfs_inc_nocow_writers().
4161 		 *
4162 		 * We need to disable an allocation to avoid an allocation of
4163 		 * regular (non-relocation data) extent. With mix of relocation
4164 		 * extents and regular extents, we can dispatch WRITE commands
4165 		 * (for relocation extents) and ZONE APPEND commands (for
4166 		 * regular extents) at the same time to the same zone, which
4167 		 * easily break the write pointer.
4168 		 *
4169 		 * Also, this flag avoids this block group to be zone finished.
4170 		 */
4171 		set_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags);
4172 	}
4173 
4174 	ffe_ctl->found_offset = start + block_group->alloc_offset;
4175 	block_group->alloc_offset += num_bytes;
4176 	spin_lock(&ctl->tree_lock);
4177 	ctl->free_space -= num_bytes;
4178 	spin_unlock(&ctl->tree_lock);
4179 
4180 	/*
4181 	 * We do not check if found_offset is aligned to stripesize. The
4182 	 * address is anyway rewritten when using zone append writing.
4183 	 */
4184 
4185 	ffe_ctl->search_start = ffe_ctl->found_offset;
4186 
4187 out:
4188 	if (ret && ffe_ctl->for_treelog)
4189 		fs_info->treelog_bg = 0;
4190 	if (ret && ffe_ctl->for_data_reloc)
4191 		fs_info->data_reloc_bg = 0;
4192 	spin_unlock(&fs_info->relocation_bg_lock);
4193 	spin_unlock(&fs_info->treelog_bg_lock);
4194 	spin_unlock(&block_group->lock);
4195 	return ret;
4196 }
4197 
4198 static int do_allocation(struct btrfs_block_group *block_group,
4199 			 struct find_free_extent_ctl *ffe_ctl,
4200 			 struct btrfs_block_group **bg_ret)
4201 {
4202 	switch (ffe_ctl->policy) {
4203 	case BTRFS_EXTENT_ALLOC_CLUSTERED:
4204 		return do_allocation_clustered(block_group, ffe_ctl, bg_ret);
4205 	case BTRFS_EXTENT_ALLOC_ZONED:
4206 		return do_allocation_zoned(block_group, ffe_ctl, bg_ret);
4207 	default:
4208 		BUG();
4209 	}
4210 }
4211 
4212 static void release_block_group(struct btrfs_block_group *block_group,
4213 				struct find_free_extent_ctl *ffe_ctl,
4214 				bool delalloc)
4215 {
4216 	switch (ffe_ctl->policy) {
4217 	case BTRFS_EXTENT_ALLOC_CLUSTERED:
4218 		ffe_ctl->retry_uncached = false;
4219 		break;
4220 	case BTRFS_EXTENT_ALLOC_ZONED:
4221 		/* Nothing to do */
4222 		break;
4223 	default:
4224 		BUG();
4225 	}
4226 
4227 	BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
4228 	       ffe_ctl->index);
4229 	btrfs_release_block_group(block_group, delalloc);
4230 }
4231 
4232 static void found_extent_clustered(struct find_free_extent_ctl *ffe_ctl,
4233 				   struct btrfs_key *ins)
4234 {
4235 	struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
4236 
4237 	if (!ffe_ctl->use_cluster && last_ptr) {
4238 		spin_lock(&last_ptr->lock);
4239 		last_ptr->window_start = ins->objectid;
4240 		spin_unlock(&last_ptr->lock);
4241 	}
4242 }
4243 
4244 static void found_extent(struct find_free_extent_ctl *ffe_ctl,
4245 			 struct btrfs_key *ins)
4246 {
4247 	switch (ffe_ctl->policy) {
4248 	case BTRFS_EXTENT_ALLOC_CLUSTERED:
4249 		found_extent_clustered(ffe_ctl, ins);
4250 		break;
4251 	case BTRFS_EXTENT_ALLOC_ZONED:
4252 		/* Nothing to do */
4253 		break;
4254 	default:
4255 		BUG();
4256 	}
4257 }
4258 
4259 static int can_allocate_chunk_zoned(struct btrfs_fs_info *fs_info,
4260 				    struct find_free_extent_ctl *ffe_ctl)
4261 {
4262 	/* Block group's activeness is not a requirement for METADATA block groups. */
4263 	if (!(ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA))
4264 		return 0;
4265 
4266 	/* If we can activate new zone, just allocate a chunk and use it */
4267 	if (btrfs_can_activate_zone(fs_info->fs_devices, ffe_ctl->flags))
4268 		return 0;
4269 
4270 	/*
4271 	 * We already reached the max active zones. Try to finish one block
4272 	 * group to make a room for a new block group. This is only possible
4273 	 * for a data block group because btrfs_zone_finish() may need to wait
4274 	 * for a running transaction which can cause a deadlock for metadata
4275 	 * allocation.
4276 	 */
4277 	if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA) {
4278 		int ret = btrfs_zone_finish_one_bg(fs_info);
4279 
4280 		if (ret == 1)
4281 			return 0;
4282 		else if (ret < 0)
4283 			return ret;
4284 	}
4285 
4286 	/*
4287 	 * If we have enough free space left in an already active block group
4288 	 * and we can't activate any other zone now, do not allow allocating a
4289 	 * new chunk and let find_free_extent() retry with a smaller size.
4290 	 */
4291 	if (ffe_ctl->max_extent_size >= ffe_ctl->min_alloc_size)
4292 		return -ENOSPC;
4293 
4294 	/*
4295 	 * Even min_alloc_size is not left in any block groups. Since we cannot
4296 	 * activate a new block group, allocating it may not help. Let's tell a
4297 	 * caller to try again and hope it progress something by writing some
4298 	 * parts of the region. That is only possible for data block groups,
4299 	 * where a part of the region can be written.
4300 	 */
4301 	if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA)
4302 		return -EAGAIN;
4303 
4304 	/*
4305 	 * We cannot activate a new block group and no enough space left in any
4306 	 * block groups. So, allocating a new block group may not help. But,
4307 	 * there is nothing to do anyway, so let's go with it.
4308 	 */
4309 	return 0;
4310 }
4311 
4312 static int can_allocate_chunk(struct btrfs_fs_info *fs_info,
4313 			      struct find_free_extent_ctl *ffe_ctl)
4314 {
4315 	switch (ffe_ctl->policy) {
4316 	case BTRFS_EXTENT_ALLOC_CLUSTERED:
4317 		return 0;
4318 	case BTRFS_EXTENT_ALLOC_ZONED:
4319 		return can_allocate_chunk_zoned(fs_info, ffe_ctl);
4320 	default:
4321 		BUG();
4322 	}
4323 }
4324 
4325 /*
4326  * Return >0 means caller needs to re-search for free extent
4327  * Return 0 means we have the needed free extent.
4328  * Return <0 means we failed to locate any free extent.
4329  */
4330 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
4331 					struct btrfs_key *ins,
4332 					struct find_free_extent_ctl *ffe_ctl,
4333 					struct btrfs_space_info *space_info,
4334 					bool full_search)
4335 {
4336 	struct btrfs_root *root = fs_info->chunk_root;
4337 	int ret;
4338 
4339 	if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
4340 	    ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
4341 		ffe_ctl->orig_have_caching_bg = true;
4342 
4343 	if (ins->objectid) {
4344 		found_extent(ffe_ctl, ins);
4345 		return 0;
4346 	}
4347 
4348 	if (ffe_ctl->loop >= LOOP_CACHING_WAIT && ffe_ctl->have_caching_bg)
4349 		return 1;
4350 
4351 	ffe_ctl->index++;
4352 	if (ffe_ctl->index < BTRFS_NR_RAID_TYPES)
4353 		return 1;
4354 
4355 	/* See the comments for btrfs_loop_type for an explanation of the phases. */
4356 	if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE)
4357 		return -ENOSPC;
4358 
4359 	ffe_ctl->index = 0;
4360 	/*
4361 	 * We want to skip the LOOP_CACHING_WAIT step if we don't have any
4362 	 * uncached bgs and we've already done a full search through.
4363 	 */
4364 	if (ffe_ctl->loop == LOOP_CACHING_NOWAIT &&
4365 	    (!ffe_ctl->orig_have_caching_bg && full_search))
4366 		ffe_ctl->loop++;
4367 	ffe_ctl->loop++;
4368 
4369 	if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
4370 		struct btrfs_trans_handle *trans;
4371 		bool have_trans = false;
4372 
4373 		/* Check if allocation policy allows to create a new chunk. */
4374 		ret = can_allocate_chunk(fs_info, ffe_ctl);
4375 		if (ret)
4376 			return ret;
4377 
4378 		trans = current->journal_info;
4379 		if (trans)
4380 			have_trans = true;
4381 		else
4382 			trans = btrfs_join_transaction(root);
4383 
4384 		if (IS_ERR(trans))
4385 			return PTR_ERR(trans);
4386 
4387 		ret = btrfs_chunk_alloc(trans, space_info, ffe_ctl->flags,
4388 					CHUNK_ALLOC_FORCE_FOR_EXTENT);
4389 
4390 		/* Do not bail out on ENOSPC since we can do more. */
4391 		if (ret == -ENOSPC) {
4392 			ret = 0;
4393 			ffe_ctl->loop++;
4394 		} else if (ret < 0) {
4395 			btrfs_abort_transaction(trans, ret);
4396 		} else {
4397 			ret = 0;
4398 		}
4399 
4400 		if (!have_trans)
4401 			btrfs_end_transaction(trans);
4402 
4403 		if (ret)
4404 			return ret;
4405 	}
4406 
4407 	if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
4408 		if (ffe_ctl->policy != BTRFS_EXTENT_ALLOC_CLUSTERED)
4409 			return -ENOSPC;
4410 
4411 		/*
4412 		 * Don't loop again if we already have no empty_size and
4413 		 * no empty_cluster.
4414 		 */
4415 		if (ffe_ctl->empty_size == 0 && ffe_ctl->empty_cluster == 0)
4416 			return -ENOSPC;
4417 		ffe_ctl->empty_size = 0;
4418 		ffe_ctl->empty_cluster = 0;
4419 	}
4420 
4421 	return 1;
4422 }
4423 
4424 static int prepare_allocation_clustered(struct btrfs_fs_info *fs_info,
4425 					struct find_free_extent_ctl *ffe_ctl,
4426 					struct btrfs_space_info *space_info,
4427 					struct btrfs_key *ins)
4428 {
4429 	/*
4430 	 * If our free space is heavily fragmented we may not be able to make
4431 	 * big contiguous allocations, so instead of doing the expensive search
4432 	 * for free space, simply return ENOSPC with our max_extent_size so we
4433 	 * can go ahead and search for a more manageable chunk.
4434 	 *
4435 	 * If our max_extent_size is large enough for our allocation simply
4436 	 * disable clustering since we will likely not be able to find enough
4437 	 * space to create a cluster and induce latency trying.
4438 	 */
4439 	if (space_info->max_extent_size) {
4440 		spin_lock(&space_info->lock);
4441 		if (space_info->max_extent_size &&
4442 		    ffe_ctl->num_bytes > space_info->max_extent_size) {
4443 			ins->offset = space_info->max_extent_size;
4444 			spin_unlock(&space_info->lock);
4445 			return -ENOSPC;
4446 		} else if (space_info->max_extent_size) {
4447 			ffe_ctl->use_cluster = false;
4448 		}
4449 		spin_unlock(&space_info->lock);
4450 	}
4451 
4452 	ffe_ctl->last_ptr = fetch_cluster_info(fs_info, space_info,
4453 					       &ffe_ctl->empty_cluster);
4454 	if (ffe_ctl->last_ptr) {
4455 		struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
4456 
4457 		spin_lock(&last_ptr->lock);
4458 		if (last_ptr->block_group)
4459 			ffe_ctl->hint_byte = last_ptr->window_start;
4460 		if (last_ptr->fragmented) {
4461 			/*
4462 			 * We still set window_start so we can keep track of the
4463 			 * last place we found an allocation to try and save
4464 			 * some time.
4465 			 */
4466 			ffe_ctl->hint_byte = last_ptr->window_start;
4467 			ffe_ctl->use_cluster = false;
4468 		}
4469 		spin_unlock(&last_ptr->lock);
4470 	}
4471 
4472 	return 0;
4473 }
4474 
4475 static int prepare_allocation_zoned(struct btrfs_fs_info *fs_info,
4476 				    struct find_free_extent_ctl *ffe_ctl,
4477 				    struct btrfs_space_info *space_info)
4478 {
4479 	struct btrfs_block_group *block_group;
4480 
4481 	if (ffe_ctl->for_treelog) {
4482 		spin_lock(&fs_info->treelog_bg_lock);
4483 		if (fs_info->treelog_bg)
4484 			ffe_ctl->hint_byte = fs_info->treelog_bg;
4485 		spin_unlock(&fs_info->treelog_bg_lock);
4486 		return 0;
4487 	}
4488 
4489 	if (ffe_ctl->for_data_reloc) {
4490 		spin_lock(&fs_info->relocation_bg_lock);
4491 		if (fs_info->data_reloc_bg)
4492 			ffe_ctl->hint_byte = fs_info->data_reloc_bg;
4493 		spin_unlock(&fs_info->relocation_bg_lock);
4494 		return 0;
4495 	}
4496 
4497 	if (!(ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA))
4498 		return 0;
4499 
4500 	spin_lock(&fs_info->zone_active_bgs_lock);
4501 	list_for_each_entry(block_group, &fs_info->zone_active_bgs, active_bg_list) {
4502 		/*
4503 		 * No lock is OK here because avail is monotonically
4504 		 * decreasing, and this is just a hint.
4505 		 */
4506 		u64 avail = block_group->zone_capacity - block_group->alloc_offset;
4507 
4508 		if (block_group_bits(block_group, ffe_ctl->flags) &&
4509 		    block_group->space_info == space_info &&
4510 		    avail >= ffe_ctl->num_bytes) {
4511 			ffe_ctl->hint_byte = block_group->start;
4512 			break;
4513 		}
4514 	}
4515 	spin_unlock(&fs_info->zone_active_bgs_lock);
4516 
4517 	return 0;
4518 }
4519 
4520 static int prepare_allocation(struct btrfs_fs_info *fs_info,
4521 			      struct find_free_extent_ctl *ffe_ctl,
4522 			      struct btrfs_space_info *space_info,
4523 			      struct btrfs_key *ins)
4524 {
4525 	switch (ffe_ctl->policy) {
4526 	case BTRFS_EXTENT_ALLOC_CLUSTERED:
4527 		return prepare_allocation_clustered(fs_info, ffe_ctl,
4528 						    space_info, ins);
4529 	case BTRFS_EXTENT_ALLOC_ZONED:
4530 		return prepare_allocation_zoned(fs_info, ffe_ctl, space_info);
4531 	default:
4532 		BUG();
4533 	}
4534 }
4535 
4536 /*
4537  * walks the btree of allocated extents and find a hole of a given size.
4538  * The key ins is changed to record the hole:
4539  * ins->objectid == start position
4540  * ins->flags = BTRFS_EXTENT_ITEM_KEY
4541  * ins->offset == the size of the hole.
4542  * Any available blocks before search_start are skipped.
4543  *
4544  * If there is no suitable free space, we will record the max size of
4545  * the free space extent currently.
4546  *
4547  * The overall logic and call chain:
4548  *
4549  * find_free_extent()
4550  * |- Iterate through all block groups
4551  * |  |- Get a valid block group
4552  * |  |- Try to do clustered allocation in that block group
4553  * |  |- Try to do unclustered allocation in that block group
4554  * |  |- Check if the result is valid
4555  * |  |  |- If valid, then exit
4556  * |  |- Jump to next block group
4557  * |
4558  * |- Push harder to find free extents
4559  *    |- If not found, re-iterate all block groups
4560  */
4561 static noinline int find_free_extent(struct btrfs_root *root,
4562 				     struct btrfs_key *ins,
4563 				     struct find_free_extent_ctl *ffe_ctl)
4564 {
4565 	struct btrfs_fs_info *fs_info = root->fs_info;
4566 	int ret = 0;
4567 	int cache_block_group_error = 0;
4568 	struct btrfs_block_group *block_group = NULL;
4569 	struct btrfs_space_info *space_info;
4570 	bool full_search = false;
4571 
4572 	WARN_ON(ffe_ctl->num_bytes < fs_info->sectorsize);
4573 
4574 	ffe_ctl->search_start = 0;
4575 	/* For clustered allocation */
4576 	ffe_ctl->empty_cluster = 0;
4577 	ffe_ctl->last_ptr = NULL;
4578 	ffe_ctl->use_cluster = true;
4579 	ffe_ctl->have_caching_bg = false;
4580 	ffe_ctl->orig_have_caching_bg = false;
4581 	ffe_ctl->index = btrfs_bg_flags_to_raid_index(ffe_ctl->flags);
4582 	ffe_ctl->loop = 0;
4583 	ffe_ctl->retry_uncached = false;
4584 	ffe_ctl->cached = 0;
4585 	ffe_ctl->max_extent_size = 0;
4586 	ffe_ctl->total_free_space = 0;
4587 	ffe_ctl->found_offset = 0;
4588 	ffe_ctl->policy = BTRFS_EXTENT_ALLOC_CLUSTERED;
4589 	ffe_ctl->size_class = btrfs_calc_block_group_size_class(ffe_ctl->num_bytes);
4590 
4591 	if (btrfs_is_zoned(fs_info))
4592 		ffe_ctl->policy = BTRFS_EXTENT_ALLOC_ZONED;
4593 
4594 	ins->type = BTRFS_EXTENT_ITEM_KEY;
4595 	ins->objectid = 0;
4596 	ins->offset = 0;
4597 
4598 	trace_btrfs_find_free_extent(root, ffe_ctl);
4599 
4600 	space_info = btrfs_find_space_info(fs_info, ffe_ctl->flags);
4601 	if (btrfs_is_zoned(fs_info) && space_info) {
4602 		/* Use dedicated sub-space_info for dedicated block group users. */
4603 		if (ffe_ctl->for_data_reloc) {
4604 			space_info = space_info->sub_group[0];
4605 			ASSERT(space_info->subgroup_id == BTRFS_SUB_GROUP_DATA_RELOC,
4606 			       "space_info->subgroup_id=%d", space_info->subgroup_id);
4607 		} else if (ffe_ctl->for_treelog) {
4608 			space_info = space_info->sub_group[0];
4609 			ASSERT(space_info->subgroup_id == BTRFS_SUB_GROUP_TREELOG,
4610 			       "space_info->subgroup_id=%d", space_info->subgroup_id);
4611 		}
4612 	}
4613 	if (!space_info) {
4614 		btrfs_err(fs_info, "no space info for %llu, tree-log %d, relocation %d",
4615 			  ffe_ctl->flags, ffe_ctl->for_treelog, ffe_ctl->for_data_reloc);
4616 		return -ENOSPC;
4617 	}
4618 
4619 	ret = prepare_allocation(fs_info, ffe_ctl, space_info, ins);
4620 	if (ret < 0)
4621 		return ret;
4622 
4623 	ffe_ctl->search_start = max(ffe_ctl->search_start,
4624 				    first_logical_byte(fs_info));
4625 	ffe_ctl->search_start = max(ffe_ctl->search_start, ffe_ctl->hint_byte);
4626 	if (ffe_ctl->search_start == ffe_ctl->hint_byte) {
4627 		block_group = btrfs_lookup_block_group(fs_info,
4628 						       ffe_ctl->search_start);
4629 		/*
4630 		 * we don't want to use the block group if it doesn't match our
4631 		 * allocation bits, or if its not cached.
4632 		 *
4633 		 * However if we are re-searching with an ideal block group
4634 		 * picked out then we don't care that the block group is cached.
4635 		 */
4636 		if (block_group && block_group_bits(block_group, ffe_ctl->flags) &&
4637 		    block_group->space_info == space_info &&
4638 		    block_group->cached != BTRFS_CACHE_NO) {
4639 			down_read(&space_info->groups_sem);
4640 			if (list_empty(&block_group->list) ||
4641 			    block_group->ro ||
4642 			    (block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED)) {
4643 				/*
4644 				 * someone is removing this block group,
4645 				 * we can't jump into the have_block_group
4646 				 * target because our list pointers are not
4647 				 * valid
4648 				 */
4649 				btrfs_put_block_group(block_group);
4650 				up_read(&space_info->groups_sem);
4651 			} else {
4652 				ffe_ctl->index = btrfs_bg_flags_to_raid_index(
4653 							block_group->flags);
4654 				btrfs_lock_block_group(block_group,
4655 						       ffe_ctl->delalloc);
4656 				ffe_ctl->hinted = true;
4657 				goto have_block_group;
4658 			}
4659 		} else if (block_group) {
4660 			btrfs_put_block_group(block_group);
4661 		}
4662 	}
4663 search:
4664 	trace_btrfs_find_free_extent_search_loop(root, ffe_ctl);
4665 	ffe_ctl->have_caching_bg = false;
4666 	if (ffe_ctl->index == btrfs_bg_flags_to_raid_index(ffe_ctl->flags) ||
4667 	    ffe_ctl->index == 0)
4668 		full_search = true;
4669 	down_read(&space_info->groups_sem);
4670 	list_for_each_entry(block_group,
4671 			    &space_info->block_groups[ffe_ctl->index], list) {
4672 		struct btrfs_block_group *bg_ret;
4673 
4674 		ffe_ctl->hinted = false;
4675 		/* If the block group is read-only, we can skip it entirely. */
4676 		if (unlikely(block_group->ro ||
4677 			     (block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED))) {
4678 			if (ffe_ctl->for_treelog)
4679 				btrfs_clear_treelog_bg(block_group);
4680 			if (ffe_ctl->for_data_reloc)
4681 				btrfs_clear_data_reloc_bg(block_group);
4682 			continue;
4683 		}
4684 
4685 		btrfs_grab_block_group(block_group, ffe_ctl->delalloc);
4686 		ffe_ctl->search_start = block_group->start;
4687 
4688 		/*
4689 		 * this can happen if we end up cycling through all the
4690 		 * raid types, but we want to make sure we only allocate
4691 		 * for the proper type.
4692 		 */
4693 		if (!block_group_bits(block_group, ffe_ctl->flags)) {
4694 			u64 extra = BTRFS_BLOCK_GROUP_DUP |
4695 				BTRFS_BLOCK_GROUP_RAID1_MASK |
4696 				BTRFS_BLOCK_GROUP_RAID56_MASK |
4697 				BTRFS_BLOCK_GROUP_RAID10;
4698 
4699 			/*
4700 			 * if they asked for extra copies and this block group
4701 			 * doesn't provide them, bail.  This does allow us to
4702 			 * fill raid0 from raid1.
4703 			 */
4704 			if ((ffe_ctl->flags & extra) && !(block_group->flags & extra))
4705 				goto loop;
4706 
4707 			/*
4708 			 * This block group has different flags than we want.
4709 			 * It's possible that we have MIXED_GROUP flag but no
4710 			 * block group is mixed.  Just skip such block group.
4711 			 */
4712 			btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4713 			continue;
4714 		}
4715 
4716 have_block_group:
4717 		trace_btrfs_find_free_extent_have_block_group(root, ffe_ctl, block_group);
4718 		ffe_ctl->cached = btrfs_block_group_done(block_group);
4719 		if (unlikely(!ffe_ctl->cached)) {
4720 			ffe_ctl->have_caching_bg = true;
4721 			ret = btrfs_cache_block_group(block_group, false);
4722 
4723 			/*
4724 			 * If we get ENOMEM here or something else we want to
4725 			 * try other block groups, because it may not be fatal.
4726 			 * However if we can't find anything else we need to
4727 			 * save our return here so that we return the actual
4728 			 * error that caused problems, not ENOSPC.
4729 			 */
4730 			if (ret < 0) {
4731 				if (!cache_block_group_error)
4732 					cache_block_group_error = ret;
4733 				ret = 0;
4734 				goto loop;
4735 			}
4736 			ret = 0;
4737 		}
4738 
4739 		if (unlikely(block_group->cached == BTRFS_CACHE_ERROR)) {
4740 			if (!cache_block_group_error)
4741 				cache_block_group_error = -EIO;
4742 			goto loop;
4743 		}
4744 
4745 		if (!find_free_extent_check_size_class(ffe_ctl, block_group))
4746 			goto loop;
4747 
4748 		bg_ret = NULL;
4749 		ret = do_allocation(block_group, ffe_ctl, &bg_ret);
4750 		if (ret > 0)
4751 			goto loop;
4752 
4753 		if (bg_ret && bg_ret != block_group) {
4754 			btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4755 			block_group = bg_ret;
4756 		}
4757 
4758 		/* Checks */
4759 		ffe_ctl->search_start = round_up(ffe_ctl->found_offset,
4760 						 fs_info->stripesize);
4761 
4762 		/* move on to the next group */
4763 		if (ffe_ctl->search_start + ffe_ctl->num_bytes >
4764 		    btrfs_block_group_end(block_group)) {
4765 			btrfs_add_free_space_unused(block_group,
4766 					    ffe_ctl->found_offset,
4767 					    ffe_ctl->num_bytes);
4768 			goto loop;
4769 		}
4770 
4771 		if (ffe_ctl->found_offset < ffe_ctl->search_start)
4772 			btrfs_add_free_space_unused(block_group,
4773 					ffe_ctl->found_offset,
4774 					ffe_ctl->search_start - ffe_ctl->found_offset);
4775 
4776 		ret = btrfs_add_reserved_bytes(block_group, ffe_ctl->ram_bytes,
4777 					       ffe_ctl->num_bytes,
4778 					       ffe_ctl->delalloc,
4779 					       ffe_ctl->loop >= LOOP_WRONG_SIZE_CLASS);
4780 		if (ret == -EAGAIN) {
4781 			btrfs_add_free_space_unused(block_group,
4782 					ffe_ctl->found_offset,
4783 					ffe_ctl->num_bytes);
4784 			goto loop;
4785 		}
4786 		btrfs_inc_block_group_reservations(block_group);
4787 
4788 		/* we are all good, lets return */
4789 		ins->objectid = ffe_ctl->search_start;
4790 		ins->offset = ffe_ctl->num_bytes;
4791 
4792 		trace_btrfs_reserve_extent(block_group, ffe_ctl);
4793 		btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4794 		break;
4795 loop:
4796 		if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
4797 		    !ffe_ctl->retry_uncached) {
4798 			ffe_ctl->retry_uncached = true;
4799 			btrfs_wait_block_group_cache_progress(block_group,
4800 						ffe_ctl->num_bytes +
4801 						ffe_ctl->empty_cluster +
4802 						ffe_ctl->empty_size);
4803 			goto have_block_group;
4804 		}
4805 		release_block_group(block_group, ffe_ctl, ffe_ctl->delalloc);
4806 		cond_resched();
4807 	}
4808 	up_read(&space_info->groups_sem);
4809 
4810 	ret = find_free_extent_update_loop(fs_info, ins, ffe_ctl, space_info,
4811 					   full_search);
4812 	if (ret > 0)
4813 		goto search;
4814 
4815 	if (ret == -ENOSPC && !cache_block_group_error) {
4816 		/*
4817 		 * Use ffe_ctl->total_free_space as fallback if we can't find
4818 		 * any contiguous hole.
4819 		 */
4820 		if (!ffe_ctl->max_extent_size)
4821 			ffe_ctl->max_extent_size = ffe_ctl->total_free_space;
4822 		spin_lock(&space_info->lock);
4823 		space_info->max_extent_size = ffe_ctl->max_extent_size;
4824 		spin_unlock(&space_info->lock);
4825 		ins->offset = ffe_ctl->max_extent_size;
4826 	} else if (ret == -ENOSPC) {
4827 		ret = cache_block_group_error;
4828 	}
4829 	return ret;
4830 }
4831 
4832 /*
4833  * Entry point to the extent allocator. Tries to find a hole that is at least
4834  * as big as @num_bytes.
4835  *
4836  * @root           -	The root that will contain this extent
4837  *
4838  * @ram_bytes      -	The amount of space in ram that @num_bytes take. This
4839  *			is used for accounting purposes. This value differs
4840  *			from @num_bytes only in the case of compressed extents.
4841  *
4842  * @num_bytes      -	Number of bytes to allocate on-disk.
4843  *
4844  * @min_alloc_size -	Indicates the minimum amount of space that the
4845  *			allocator should try to satisfy. In some cases
4846  *			@num_bytes may be larger than what is required and if
4847  *			the filesystem is fragmented then allocation fails.
4848  *			However, the presence of @min_alloc_size gives a
4849  *			chance to try and satisfy the smaller allocation.
4850  *
4851  * @empty_size     -	A hint that you plan on doing more COW. This is the
4852  *			size in bytes the allocator should try to find free
4853  *			next to the block it returns.  This is just a hint and
4854  *			may be ignored by the allocator.
4855  *
4856  * @hint_byte      -	Hint to the allocator to start searching above the byte
4857  *			address passed. It might be ignored.
4858  *
4859  * @ins            -	This key is modified to record the found hole. It will
4860  *			have the following values:
4861  *			ins->objectid == start position
4862  *			ins->flags = BTRFS_EXTENT_ITEM_KEY
4863  *			ins->offset == the size of the hole.
4864  *
4865  * @is_data        -	Boolean flag indicating whether an extent is
4866  *			allocated for data (true) or metadata (false)
4867  *
4868  * @delalloc       -	Boolean flag indicating whether this allocation is for
4869  *			delalloc or not. If 'true' data_rwsem of block groups
4870  *			is going to be acquired.
4871  *
4872  *
4873  * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
4874  * case -ENOSPC is returned then @ins->offset will contain the size of the
4875  * largest available hole the allocator managed to find.
4876  */
4877 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
4878 			 u64 num_bytes, u64 min_alloc_size,
4879 			 u64 empty_size, u64 hint_byte,
4880 			 struct btrfs_key *ins, bool is_data, bool delalloc)
4881 {
4882 	struct btrfs_fs_info *fs_info = root->fs_info;
4883 	struct find_free_extent_ctl ffe_ctl = {};
4884 	bool final_tried = num_bytes == min_alloc_size;
4885 	u64 flags;
4886 	int ret;
4887 	bool for_treelog = (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID);
4888 	bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
4889 
4890 	flags = get_alloc_profile_by_root(root, is_data);
4891 again:
4892 	WARN_ON(num_bytes < fs_info->sectorsize);
4893 
4894 	ffe_ctl.ram_bytes = ram_bytes;
4895 	ffe_ctl.num_bytes = num_bytes;
4896 	ffe_ctl.min_alloc_size = min_alloc_size;
4897 	ffe_ctl.empty_size = empty_size;
4898 	ffe_ctl.flags = flags;
4899 	ffe_ctl.delalloc = delalloc;
4900 	ffe_ctl.hint_byte = hint_byte;
4901 	ffe_ctl.for_treelog = for_treelog;
4902 	ffe_ctl.for_data_reloc = for_data_reloc;
4903 
4904 	ret = find_free_extent(root, ins, &ffe_ctl);
4905 	if (!ret && !is_data) {
4906 		btrfs_dec_block_group_reservations(fs_info, ins->objectid);
4907 	} else if (ret == -ENOSPC) {
4908 		if (!final_tried && ins->offset) {
4909 			num_bytes = min(num_bytes >> 1, ins->offset);
4910 			num_bytes = round_down(num_bytes,
4911 					       fs_info->sectorsize);
4912 			num_bytes = max(num_bytes, min_alloc_size);
4913 			ram_bytes = num_bytes;
4914 			if (num_bytes == min_alloc_size)
4915 				final_tried = true;
4916 			goto again;
4917 		} else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4918 			struct btrfs_space_info *sinfo;
4919 
4920 			sinfo = btrfs_find_space_info(fs_info, flags);
4921 			btrfs_err(fs_info,
4922 	"allocation failed flags %llu, wanted %llu tree-log %d, relocation: %d",
4923 				  flags, num_bytes, for_treelog, for_data_reloc);
4924 			if (sinfo)
4925 				btrfs_dump_space_info(sinfo, num_bytes, 1);
4926 		}
4927 	}
4928 
4929 	return ret;
4930 }
4931 
4932 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len,
4933 			       bool is_delalloc)
4934 {
4935 	struct btrfs_block_group *cache;
4936 
4937 	cache = btrfs_lookup_block_group(fs_info, start);
4938 	if (!cache) {
4939 		btrfs_err(fs_info, "Unable to find block group for %llu",
4940 			  start);
4941 		return -ENOSPC;
4942 	}
4943 
4944 	btrfs_add_free_space(cache, start, len);
4945 	btrfs_free_reserved_bytes(cache, len, is_delalloc);
4946 	trace_btrfs_reserved_extent_free(fs_info, start, len);
4947 
4948 	btrfs_put_block_group(cache);
4949 	return 0;
4950 }
4951 
4952 int btrfs_pin_reserved_extent(struct btrfs_trans_handle *trans,
4953 			      const struct extent_buffer *eb)
4954 {
4955 	struct btrfs_block_group *cache;
4956 	int ret = 0;
4957 
4958 	cache = btrfs_lookup_block_group(trans->fs_info, eb->start);
4959 	if (!cache) {
4960 		btrfs_err(trans->fs_info, "unable to find block group for %llu",
4961 			  eb->start);
4962 		return -ENOSPC;
4963 	}
4964 
4965 	ret = pin_down_extent(trans, cache, eb->start, eb->len, true);
4966 	btrfs_put_block_group(cache);
4967 	return ret;
4968 }
4969 
4970 static int alloc_reserved_extent(struct btrfs_trans_handle *trans, u64 bytenr,
4971 				 u64 num_bytes)
4972 {
4973 	struct btrfs_fs_info *fs_info = trans->fs_info;
4974 	int ret;
4975 
4976 	ret = btrfs_remove_from_free_space_tree(trans, bytenr, num_bytes);
4977 	if (ret)
4978 		return ret;
4979 
4980 	ret = btrfs_update_block_group(trans, bytenr, num_bytes, true);
4981 	if (ret) {
4982 		ASSERT(!ret);
4983 		btrfs_err(fs_info, "update block group failed for %llu %llu",
4984 			  bytenr, num_bytes);
4985 		return ret;
4986 	}
4987 
4988 	trace_btrfs_reserved_extent_alloc(fs_info, bytenr, num_bytes);
4989 	return 0;
4990 }
4991 
4992 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4993 				      u64 parent, u64 root_objectid,
4994 				      u64 flags, u64 owner, u64 offset,
4995 				      struct btrfs_key *ins, int ref_mod, u64 oref_root)
4996 {
4997 	struct btrfs_fs_info *fs_info = trans->fs_info;
4998 	struct btrfs_root *extent_root;
4999 	int ret;
5000 	struct btrfs_extent_item *extent_item;
5001 	struct btrfs_extent_owner_ref *oref;
5002 	struct btrfs_extent_inline_ref *iref;
5003 	struct btrfs_path *path;
5004 	struct extent_buffer *leaf;
5005 	int type;
5006 	u32 size;
5007 	const bool simple_quota = (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE);
5008 
5009 	if (parent > 0)
5010 		type = BTRFS_SHARED_DATA_REF_KEY;
5011 	else
5012 		type = BTRFS_EXTENT_DATA_REF_KEY;
5013 
5014 	size = sizeof(*extent_item);
5015 	if (simple_quota)
5016 		size += btrfs_extent_inline_ref_size(BTRFS_EXTENT_OWNER_REF_KEY);
5017 	size += btrfs_extent_inline_ref_size(type);
5018 
5019 	extent_root = btrfs_extent_root(fs_info, ins->objectid);
5020 	if (unlikely(!extent_root)) {
5021 		btrfs_err(fs_info,
5022 			  "missing extent root for extent at bytenr %llu",
5023 			  ins->objectid);
5024 		return -EUCLEAN;
5025 	}
5026 
5027 	path = btrfs_alloc_path();
5028 	if (!path)
5029 		return -ENOMEM;
5030 
5031 	ret = btrfs_insert_empty_item(trans, extent_root, path, ins, size);
5032 	if (ret) {
5033 		btrfs_free_path(path);
5034 		return ret;
5035 	}
5036 
5037 	leaf = path->nodes[0];
5038 	extent_item = btrfs_item_ptr(leaf, path->slots[0],
5039 				     struct btrfs_extent_item);
5040 	btrfs_set_extent_refs(leaf, extent_item, ref_mod);
5041 	btrfs_set_extent_generation(leaf, extent_item, trans->transid);
5042 	btrfs_set_extent_flags(leaf, extent_item,
5043 			       flags | BTRFS_EXTENT_FLAG_DATA);
5044 
5045 	iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
5046 	if (simple_quota) {
5047 		btrfs_set_extent_inline_ref_type(leaf, iref, BTRFS_EXTENT_OWNER_REF_KEY);
5048 		oref = (struct btrfs_extent_owner_ref *)(&iref->offset);
5049 		btrfs_set_extent_owner_ref_root_id(leaf, oref, oref_root);
5050 		iref = (struct btrfs_extent_inline_ref *)(oref + 1);
5051 	}
5052 	btrfs_set_extent_inline_ref_type(leaf, iref, type);
5053 
5054 	if (parent > 0) {
5055 		struct btrfs_shared_data_ref *ref;
5056 		ref = (struct btrfs_shared_data_ref *)(iref + 1);
5057 		btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
5058 		btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
5059 	} else {
5060 		struct btrfs_extent_data_ref *ref;
5061 		ref = (struct btrfs_extent_data_ref *)(&iref->offset);
5062 		btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
5063 		btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
5064 		btrfs_set_extent_data_ref_offset(leaf, ref, offset);
5065 		btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
5066 	}
5067 
5068 	btrfs_free_path(path);
5069 
5070 	return alloc_reserved_extent(trans, ins->objectid, ins->offset);
5071 }
5072 
5073 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
5074 				     const struct btrfs_delayed_ref_node *node,
5075 				     struct btrfs_delayed_extent_op *extent_op)
5076 {
5077 	struct btrfs_fs_info *fs_info = trans->fs_info;
5078 	struct btrfs_root *extent_root;
5079 	int ret;
5080 	struct btrfs_extent_item *extent_item;
5081 	struct btrfs_key extent_key;
5082 	struct btrfs_tree_block_info *block_info;
5083 	struct btrfs_extent_inline_ref *iref;
5084 	struct btrfs_path *path;
5085 	struct extent_buffer *leaf;
5086 	u32 size = sizeof(*extent_item) + sizeof(*iref);
5087 	const u64 flags = (extent_op ? extent_op->flags_to_set : 0);
5088 	/* The owner of a tree block is the level. */
5089 	int level = btrfs_delayed_ref_owner(node);
5090 	bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
5091 
5092 	if (unlikely(node->ref_root == BTRFS_REMAP_TREE_OBJECTID))
5093 		goto skip;
5094 
5095 	extent_key.objectid = node->bytenr;
5096 	if (skinny_metadata) {
5097 		/* The owner of a tree block is the level. */
5098 		extent_key.offset = level;
5099 		extent_key.type = BTRFS_METADATA_ITEM_KEY;
5100 	} else {
5101 		extent_key.offset = node->num_bytes;
5102 		extent_key.type = BTRFS_EXTENT_ITEM_KEY;
5103 		size += sizeof(*block_info);
5104 	}
5105 
5106 	extent_root = btrfs_extent_root(fs_info, extent_key.objectid);
5107 	if (unlikely(!extent_root)) {
5108 		btrfs_err(fs_info,
5109 			  "missing extent root for extent at bytenr %llu",
5110 			  extent_key.objectid);
5111 		return -EUCLEAN;
5112 	}
5113 
5114 	path = btrfs_alloc_path();
5115 	if (!path)
5116 		return -ENOMEM;
5117 
5118 	ret = btrfs_insert_empty_item(trans, extent_root, path, &extent_key,
5119 				      size);
5120 	if (ret) {
5121 		btrfs_free_path(path);
5122 		return ret;
5123 	}
5124 
5125 	leaf = path->nodes[0];
5126 	extent_item = btrfs_item_ptr(leaf, path->slots[0],
5127 				     struct btrfs_extent_item);
5128 	btrfs_set_extent_refs(leaf, extent_item, 1);
5129 	btrfs_set_extent_generation(leaf, extent_item, trans->transid);
5130 	btrfs_set_extent_flags(leaf, extent_item,
5131 			       flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
5132 
5133 	if (skinny_metadata) {
5134 		iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
5135 	} else {
5136 		block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
5137 		btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
5138 		btrfs_set_tree_block_level(leaf, block_info, level);
5139 		iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
5140 	}
5141 
5142 	if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
5143 		btrfs_set_extent_inline_ref_type(leaf, iref,
5144 						 BTRFS_SHARED_BLOCK_REF_KEY);
5145 		btrfs_set_extent_inline_ref_offset(leaf, iref, node->parent);
5146 	} else {
5147 		btrfs_set_extent_inline_ref_type(leaf, iref,
5148 						 BTRFS_TREE_BLOCK_REF_KEY);
5149 		btrfs_set_extent_inline_ref_offset(leaf, iref, node->ref_root);
5150 	}
5151 
5152 	btrfs_free_path(path);
5153 
5154 skip:
5155 	return alloc_reserved_extent(trans, node->bytenr, fs_info->nodesize);
5156 }
5157 
5158 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
5159 				     struct btrfs_root *root, u64 owner,
5160 				     u64 offset, u64 ram_bytes,
5161 				     struct btrfs_key *ins)
5162 {
5163 	struct btrfs_ref generic_ref = {
5164 		.action = BTRFS_ADD_DELAYED_EXTENT,
5165 		.bytenr = ins->objectid,
5166 		.num_bytes = ins->offset,
5167 		.owning_root = btrfs_root_id(root),
5168 		.ref_root = btrfs_root_id(root),
5169 	};
5170 
5171 	ASSERT(generic_ref.ref_root != BTRFS_TREE_LOG_OBJECTID);
5172 
5173 	if (btrfs_is_data_reloc_root(root) && btrfs_is_fstree(root->relocation_src_root))
5174 		generic_ref.owning_root = root->relocation_src_root;
5175 
5176 	btrfs_init_data_ref(&generic_ref, owner, offset, 0, false);
5177 	btrfs_ref_tree_mod(root->fs_info, &generic_ref);
5178 
5179 	return btrfs_add_delayed_data_ref(trans, &generic_ref, ram_bytes);
5180 }
5181 
5182 /*
5183  * this is used by the tree logging recovery code.  It records that
5184  * an extent has been allocated and makes sure to clear the free
5185  * space cache bits as well
5186  */
5187 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
5188 				   u64 root_objectid, u64 owner, u64 offset,
5189 				   struct btrfs_key *ins)
5190 {
5191 	struct btrfs_fs_info *fs_info = trans->fs_info;
5192 	int ret;
5193 	struct btrfs_block_group *block_group;
5194 	struct btrfs_space_info *space_info;
5195 	const struct btrfs_squota_delta delta = {
5196 		.root = root_objectid,
5197 		.num_bytes = ins->offset,
5198 		.generation = trans->transid,
5199 		.is_data = true,
5200 		.is_inc = true,
5201 	};
5202 
5203 	/*
5204 	 * Mixed block groups will exclude before processing the log so we only
5205 	 * need to do the exclude dance if this fs isn't mixed.
5206 	 */
5207 	if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
5208 		ret = __exclude_logged_extent(fs_info, ins->objectid,
5209 					      ins->offset);
5210 		if (ret)
5211 			return ret;
5212 	}
5213 
5214 	block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
5215 	if (!block_group)
5216 		return -EINVAL;
5217 
5218 	space_info = block_group->space_info;
5219 	spin_lock(&space_info->lock);
5220 	spin_lock(&block_group->lock);
5221 	space_info->bytes_reserved += ins->offset;
5222 	block_group->reserved += ins->offset;
5223 	spin_unlock(&block_group->lock);
5224 	spin_unlock(&space_info->lock);
5225 
5226 	ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
5227 					 offset, ins, 1, root_objectid);
5228 	if (ret)
5229 		btrfs_pin_extent(trans, ins->objectid, ins->offset);
5230 	ret = btrfs_record_squota_delta(fs_info, &delta);
5231 	btrfs_put_block_group(block_group);
5232 	return ret;
5233 }
5234 
5235 #ifdef CONFIG_BTRFS_DEBUG
5236 /*
5237  * Extra safety check in case the extent tree is corrupted and extent allocator
5238  * chooses to use a tree block which is already used and locked.
5239  */
5240 static bool check_eb_lock_owner(const struct extent_buffer *eb)
5241 {
5242 	if (eb->lock_owner == current->pid) {
5243 		btrfs_err_rl(eb->fs_info,
5244 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
5245 			     eb->start, btrfs_header_owner(eb), current->pid);
5246 		return true;
5247 	}
5248 	return false;
5249 }
5250 #else
5251 static bool check_eb_lock_owner(struct extent_buffer *eb)
5252 {
5253 	return false;
5254 }
5255 #endif
5256 
5257 static struct extent_buffer *
5258 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
5259 		      u64 bytenr, int level, u64 owner,
5260 		      enum btrfs_lock_nesting nest)
5261 {
5262 	struct btrfs_fs_info *fs_info = root->fs_info;
5263 	struct extent_buffer *buf;
5264 	u64 lockdep_owner = owner;
5265 
5266 	buf = btrfs_find_create_tree_block(fs_info, bytenr, owner, level);
5267 	if (IS_ERR(buf))
5268 		return buf;
5269 
5270 	if (unlikely(check_eb_lock_owner(buf))) {
5271 		free_extent_buffer(buf);
5272 		return ERR_PTR(-EUCLEAN);
5273 	}
5274 
5275 	/*
5276 	 * The reloc trees are just snapshots, so we need them to appear to be
5277 	 * just like any other fs tree WRT lockdep.
5278 	 *
5279 	 * The exception however is in replace_path() in relocation, where we
5280 	 * hold the lock on the original fs root and then search for the reloc
5281 	 * root.  At that point we need to make sure any reloc root buffers are
5282 	 * set to the BTRFS_TREE_RELOC_OBJECTID lockdep class in order to make
5283 	 * lockdep happy.
5284 	 */
5285 	if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID &&
5286 	    !test_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &root->state))
5287 		lockdep_owner = BTRFS_FS_TREE_OBJECTID;
5288 
5289 	/* btrfs_clear_buffer_dirty() accesses generation field. */
5290 	btrfs_set_header_generation(buf, trans->transid);
5291 
5292 	/*
5293 	 * This needs to stay, because we could allocate a freed block from an
5294 	 * old tree into a new tree, so we need to make sure this new block is
5295 	 * set to the appropriate level and owner.
5296 	 */
5297 	btrfs_set_buffer_lockdep_class(lockdep_owner, buf, level);
5298 
5299 	btrfs_tree_lock_nested(buf, nest);
5300 	btrfs_clear_buffer_dirty(trans, buf);
5301 	clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
5302 	clear_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &buf->bflags);
5303 
5304 	set_extent_buffer_uptodate(buf);
5305 
5306 	memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
5307 	btrfs_set_header_level(buf, level);
5308 	btrfs_set_header_bytenr(buf, buf->start);
5309 	btrfs_set_header_generation(buf, trans->transid);
5310 	btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
5311 	btrfs_set_header_owner(buf, owner);
5312 	write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
5313 	write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
5314 	if (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID) {
5315 		buf->log_index = root->log_transid % 2;
5316 		/*
5317 		 * we allow two log transactions at a time, use different
5318 		 * EXTENT bit to differentiate dirty pages.
5319 		 */
5320 		if (buf->log_index == 0)
5321 			btrfs_set_extent_bit(&root->dirty_log_pages, buf->start,
5322 					     buf->start + buf->len - 1,
5323 					     EXTENT_DIRTY_LOG1, NULL);
5324 		else
5325 			btrfs_set_extent_bit(&root->dirty_log_pages, buf->start,
5326 					     buf->start + buf->len - 1,
5327 					     EXTENT_DIRTY_LOG2, NULL);
5328 	} else {
5329 		buf->log_index = -1;
5330 		btrfs_set_extent_bit(&trans->transaction->dirty_pages, buf->start,
5331 				     buf->start + buf->len - 1, EXTENT_DIRTY, NULL);
5332 	}
5333 	/* this returns a buffer locked for blocking */
5334 	return buf;
5335 }
5336 
5337 /*
5338  * finds a free extent and does all the dirty work required for allocation
5339  * returns the tree buffer or an ERR_PTR on error.
5340  */
5341 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
5342 					     struct btrfs_root *root,
5343 					     u64 parent, u64 root_objectid,
5344 					     const struct btrfs_disk_key *key,
5345 					     int level, u64 hint,
5346 					     u64 empty_size,
5347 					     u64 reloc_src_root,
5348 					     enum btrfs_lock_nesting nest)
5349 {
5350 	struct btrfs_fs_info *fs_info = root->fs_info;
5351 	struct btrfs_key ins;
5352 	struct btrfs_block_rsv *block_rsv;
5353 	struct extent_buffer *buf;
5354 	u64 flags = 0;
5355 	int ret;
5356 	u32 blocksize = fs_info->nodesize;
5357 	bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
5358 	u64 owning_root;
5359 
5360 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5361 	if (btrfs_is_testing(fs_info)) {
5362 		buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
5363 					    level, root_objectid, nest);
5364 		if (!IS_ERR(buf))
5365 			root->alloc_bytenr += blocksize;
5366 		return buf;
5367 	}
5368 #endif
5369 
5370 	block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
5371 	if (IS_ERR(block_rsv))
5372 		return ERR_CAST(block_rsv);
5373 
5374 	ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
5375 				   empty_size, hint, &ins, false, false);
5376 	if (ret)
5377 		goto out_unuse;
5378 
5379 	buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
5380 				    root_objectid, nest);
5381 	if (IS_ERR(buf)) {
5382 		ret = PTR_ERR(buf);
5383 		goto out_free_reserved;
5384 	}
5385 	owning_root = btrfs_header_owner(buf);
5386 
5387 	if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
5388 		if (parent == 0)
5389 			parent = ins.objectid;
5390 		flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5391 		owning_root = reloc_src_root;
5392 	} else
5393 		BUG_ON(parent > 0);
5394 
5395 	if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
5396 		struct btrfs_delayed_extent_op *extent_op;
5397 		struct btrfs_ref generic_ref = {
5398 			.action = BTRFS_ADD_DELAYED_EXTENT,
5399 			.bytenr = ins.objectid,
5400 			.num_bytes = ins.offset,
5401 			.parent = parent,
5402 			.owning_root = owning_root,
5403 			.ref_root = root_objectid,
5404 		};
5405 
5406 		if (!skinny_metadata || flags != 0) {
5407 			extent_op = btrfs_alloc_delayed_extent_op();
5408 			if (!extent_op) {
5409 				ret = -ENOMEM;
5410 				goto out_free_buf;
5411 			}
5412 			if (key)
5413 				memcpy(&extent_op->key, key, sizeof(extent_op->key));
5414 			else
5415 				memset(&extent_op->key, 0, sizeof(extent_op->key));
5416 			extent_op->flags_to_set = flags;
5417 			extent_op->update_key = (skinny_metadata ? false : true);
5418 			extent_op->update_flags = (flags != 0);
5419 		} else {
5420 			extent_op = NULL;
5421 		}
5422 
5423 		btrfs_init_tree_ref(&generic_ref, level, btrfs_root_id(root), false);
5424 		btrfs_ref_tree_mod(fs_info, &generic_ref);
5425 		ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, extent_op);
5426 		if (ret) {
5427 			btrfs_free_delayed_extent_op(extent_op);
5428 			goto out_free_buf;
5429 		}
5430 	}
5431 	return buf;
5432 
5433 out_free_buf:
5434 	btrfs_tree_unlock(buf);
5435 	free_extent_buffer(buf);
5436 out_free_reserved:
5437 	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, false);
5438 out_unuse:
5439 	btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
5440 	return ERR_PTR(ret);
5441 }
5442 
5443 struct walk_control {
5444 	u64 refs[BTRFS_MAX_LEVEL];
5445 	u64 flags[BTRFS_MAX_LEVEL];
5446 	struct btrfs_key update_progress;
5447 	struct btrfs_key drop_progress;
5448 	int drop_level;
5449 	int stage;
5450 	int level;
5451 	int shared_level;
5452 	int update_ref;
5453 	int keep_locks;
5454 	int reada_slot;
5455 	int reada_count;
5456 	int restarted;
5457 	/* Indicate that extent info needs to be looked up when walking the tree. */
5458 	int lookup_info;
5459 };
5460 
5461 /*
5462  * This is our normal stage.  We are traversing blocks the current snapshot owns
5463  * and we are dropping any of our references to any children we are able to, and
5464  * then freeing the block once we've processed all of the children.
5465  */
5466 #define DROP_REFERENCE	1
5467 
5468 /*
5469  * We enter this stage when we have to walk into a child block (meaning we can't
5470  * simply drop our reference to it from our current parent node) and there are
5471  * more than one reference on it.  If we are the owner of any of the children
5472  * blocks from the current parent node then we have to do the FULL_BACKREF dance
5473  * on them in order to drop our normal ref and add the shared ref.
5474  */
5475 #define UPDATE_BACKREF	2
5476 
5477 /*
5478  * Decide if we need to walk down into this node to adjust the references.
5479  *
5480  * @root:	the root we are currently deleting
5481  * @wc:		the walk control for this deletion
5482  * @eb:		the parent eb that we're currently visiting
5483  * @flags:	the flags for wc->level - 1
5484  * @slot:	the slot in the eb that we're currently checking
5485  *
5486  * This is meant to be called when we're evaluating if a node we point to at
5487  * wc->level should be read and walked into, or if we can simply delete our
5488  * reference to it.  We return true if we should walk into the node, false if we
5489  * can skip it.
5490  *
5491  * We have assertions in here to make sure this is called correctly.  We assume
5492  * that sanity checking on the blocks read to this point has been done, so any
5493  * corrupted file systems must have been caught before calling this function.
5494  */
5495 static bool visit_node_for_delete(struct btrfs_root *root, struct walk_control *wc,
5496 				  struct extent_buffer *eb, u64 flags, int slot)
5497 {
5498 	struct btrfs_key key;
5499 	u64 generation;
5500 	int level = wc->level;
5501 
5502 	ASSERT(level > 0);
5503 	ASSERT(wc->refs[level - 1] > 0);
5504 
5505 	/*
5506 	 * The update backref stage we only want to skip if we already have
5507 	 * FULL_BACKREF set, otherwise we need to read.
5508 	 */
5509 	if (wc->stage == UPDATE_BACKREF) {
5510 		if (level == 1 && flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5511 			return false;
5512 		return true;
5513 	}
5514 
5515 	/*
5516 	 * We're the last ref on this block, we must walk into it and process
5517 	 * any refs it's pointing at.
5518 	 */
5519 	if (wc->refs[level - 1] == 1)
5520 		return true;
5521 
5522 	/*
5523 	 * If we're already FULL_BACKREF then we know we can just drop our
5524 	 * current reference.
5525 	 */
5526 	if (level == 1 && flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5527 		return false;
5528 
5529 	/*
5530 	 * This block is older than our creation generation, we can drop our
5531 	 * reference to it.
5532 	 */
5533 	generation = btrfs_node_ptr_generation(eb, slot);
5534 	if (!wc->update_ref || generation <= btrfs_root_origin_generation(root))
5535 		return false;
5536 
5537 	/*
5538 	 * This block was processed from a previous snapshot deletion run, we
5539 	 * can skip it.
5540 	 */
5541 	btrfs_node_key_to_cpu(eb, &key, slot);
5542 	if (btrfs_comp_cpu_keys(&key, &wc->update_progress) < 0)
5543 		return false;
5544 
5545 	/* All other cases we need to wander into the node. */
5546 	return true;
5547 }
5548 
5549 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
5550 				     struct btrfs_root *root,
5551 				     struct walk_control *wc,
5552 				     struct btrfs_path *path)
5553 {
5554 	struct btrfs_fs_info *fs_info = root->fs_info;
5555 	u64 bytenr;
5556 	u64 generation;
5557 	u64 refs;
5558 	u64 flags;
5559 	u32 nritems;
5560 	struct extent_buffer *eb;
5561 	int ret;
5562 	int slot;
5563 	int nread = 0;
5564 
5565 	if (path->slots[wc->level] < wc->reada_slot) {
5566 		wc->reada_count = wc->reada_count * 2 / 3;
5567 		wc->reada_count = max(wc->reada_count, 2);
5568 	} else {
5569 		wc->reada_count = wc->reada_count * 3 / 2;
5570 		wc->reada_count = min_t(int, wc->reada_count,
5571 					BTRFS_NODEPTRS_PER_BLOCK(fs_info));
5572 	}
5573 
5574 	eb = path->nodes[wc->level];
5575 	nritems = btrfs_header_nritems(eb);
5576 
5577 	for (slot = path->slots[wc->level]; slot < nritems; slot++) {
5578 		if (nread >= wc->reada_count)
5579 			break;
5580 
5581 		cond_resched();
5582 		bytenr = btrfs_node_blockptr(eb, slot);
5583 		generation = btrfs_node_ptr_generation(eb, slot);
5584 
5585 		if (slot == path->slots[wc->level])
5586 			goto reada;
5587 
5588 		if (wc->stage == UPDATE_BACKREF &&
5589 		    generation <= btrfs_root_origin_generation(root))
5590 			continue;
5591 
5592 		/* We don't lock the tree block, it's OK to be racy here */
5593 		ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
5594 					       wc->level - 1, 1, &refs,
5595 					       &flags, NULL);
5596 		/* We don't care about errors in readahead. */
5597 		if (ret < 0)
5598 			continue;
5599 
5600 		/*
5601 		 * This could be racey, it's conceivable that we raced and end
5602 		 * up with a bogus refs count, if that's the case just skip, if
5603 		 * we are actually corrupt we will notice when we look up
5604 		 * everything again with our locks.
5605 		 */
5606 		if (refs == 0)
5607 			continue;
5608 
5609 		/* If we don't need to visit this node don't reada. */
5610 		if (!visit_node_for_delete(root, wc, eb, flags, slot))
5611 			continue;
5612 reada:
5613 		btrfs_readahead_node_child(eb, slot);
5614 		nread++;
5615 	}
5616 	wc->reada_slot = slot;
5617 }
5618 
5619 /*
5620  * helper to process tree block while walking down the tree.
5621  *
5622  * when wc->stage == UPDATE_BACKREF, this function updates
5623  * back refs for pointers in the block.
5624  *
5625  * NOTE: return value 1 means we should stop walking down.
5626  */
5627 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5628 				   struct btrfs_root *root,
5629 				   struct btrfs_path *path,
5630 				   struct walk_control *wc)
5631 {
5632 	struct btrfs_fs_info *fs_info = root->fs_info;
5633 	int level = wc->level;
5634 	struct extent_buffer *eb = path->nodes[level];
5635 	u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5636 	int ret;
5637 
5638 	if (wc->stage == UPDATE_BACKREF && btrfs_header_owner(eb) != btrfs_root_id(root))
5639 		return 1;
5640 
5641 	/*
5642 	 * when reference count of tree block is 1, it won't increase
5643 	 * again. once full backref flag is set, we never clear it.
5644 	 */
5645 	if (wc->lookup_info &&
5646 	    ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
5647 	     (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
5648 		ASSERT(path->locks[level]);
5649 		ret = btrfs_lookup_extent_info(trans, fs_info,
5650 					       eb->start, level, 1,
5651 					       &wc->refs[level],
5652 					       &wc->flags[level],
5653 					       NULL);
5654 		if (ret)
5655 			return ret;
5656 		if (unlikely(wc->refs[level] == 0)) {
5657 			btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0",
5658 				  eb->start);
5659 			return -EUCLEAN;
5660 		}
5661 	}
5662 
5663 	if (wc->stage == DROP_REFERENCE) {
5664 		if (wc->refs[level] > 1)
5665 			return 1;
5666 
5667 		if (path->locks[level] && !wc->keep_locks) {
5668 			btrfs_tree_unlock_rw(eb, path->locks[level]);
5669 			path->locks[level] = 0;
5670 		}
5671 		return 0;
5672 	}
5673 
5674 	/* wc->stage == UPDATE_BACKREF */
5675 	if (!(wc->flags[level] & flag)) {
5676 		ASSERT(path->locks[level]);
5677 		ret = btrfs_inc_ref(trans, root, eb, true);
5678 		if (unlikely(ret)) {
5679 			btrfs_abort_transaction(trans, ret);
5680 			return ret;
5681 		}
5682 		ret = btrfs_dec_ref(trans, root, eb, false);
5683 		if (unlikely(ret)) {
5684 			btrfs_abort_transaction(trans, ret);
5685 			return ret;
5686 		}
5687 		ret = btrfs_set_disk_extent_flags(trans, eb, flag);
5688 		if (unlikely(ret)) {
5689 			btrfs_abort_transaction(trans, ret);
5690 			return ret;
5691 		}
5692 		wc->flags[level] |= flag;
5693 	}
5694 
5695 	/*
5696 	 * the block is shared by multiple trees, so it's not good to
5697 	 * keep the tree lock
5698 	 */
5699 	if (path->locks[level] && level > 0) {
5700 		btrfs_tree_unlock_rw(eb, path->locks[level]);
5701 		path->locks[level] = 0;
5702 	}
5703 	return 0;
5704 }
5705 
5706 /*
5707  * This is used to verify a ref exists for this root to deal with a bug where we
5708  * would have a drop_progress key that hadn't been updated properly.
5709  */
5710 static int check_ref_exists(struct btrfs_trans_handle *trans,
5711 			    struct btrfs_root *root, u64 bytenr, u64 parent,
5712 			    int level)
5713 {
5714 	struct btrfs_delayed_ref_root *delayed_refs;
5715 	struct btrfs_delayed_ref_head *head;
5716 	BTRFS_PATH_AUTO_FREE(path);
5717 	struct btrfs_extent_inline_ref *iref;
5718 	int ret;
5719 	bool exists = false;
5720 
5721 	path = btrfs_alloc_path();
5722 	if (!path)
5723 		return -ENOMEM;
5724 again:
5725 	ret = lookup_extent_backref(trans, path, &iref, bytenr,
5726 				    root->fs_info->nodesize, parent,
5727 				    btrfs_root_id(root), level, 0);
5728 	if (ret != -ENOENT) {
5729 		/*
5730 		 * If we get 0 then we found our reference, return 1, else
5731 		 * return the error if it's not -ENOENT;
5732 		 */
5733 		return (ret < 0 ) ? ret : 1;
5734 	}
5735 
5736 	/*
5737 	 * We could have a delayed ref with this reference, so look it up while
5738 	 * we're holding the path open to make sure we don't race with the
5739 	 * delayed ref running.
5740 	 */
5741 	delayed_refs = &trans->transaction->delayed_refs;
5742 	spin_lock(&delayed_refs->lock);
5743 	head = btrfs_find_delayed_ref_head(root->fs_info, delayed_refs, bytenr);
5744 	if (!head)
5745 		goto out;
5746 	if (!mutex_trylock(&head->mutex)) {
5747 		/*
5748 		 * We're contended, means that the delayed ref is running, get a
5749 		 * reference and wait for the ref head to be complete and then
5750 		 * try again.
5751 		 */
5752 		refcount_inc(&head->refs);
5753 		spin_unlock(&delayed_refs->lock);
5754 
5755 		btrfs_release_path(path);
5756 
5757 		mutex_lock(&head->mutex);
5758 		mutex_unlock(&head->mutex);
5759 		btrfs_put_delayed_ref_head(head);
5760 		goto again;
5761 	}
5762 
5763 	exists = btrfs_find_delayed_tree_ref(head, btrfs_root_id(root), parent);
5764 	mutex_unlock(&head->mutex);
5765 out:
5766 	spin_unlock(&delayed_refs->lock);
5767 	return exists ? 1 : 0;
5768 }
5769 
5770 /*
5771  * We may not have an uptodate block, so if we are going to walk down into this
5772  * block we need to drop the lock, read it off of the disk, re-lock it and
5773  * return to continue dropping the snapshot.
5774  */
5775 static int check_next_block_uptodate(struct btrfs_trans_handle *trans,
5776 				     struct btrfs_root *root,
5777 				     struct btrfs_path *path,
5778 				     struct walk_control *wc,
5779 				     struct extent_buffer *next)
5780 {
5781 	struct btrfs_tree_parent_check check = { 0 };
5782 	u64 generation;
5783 	int level = wc->level;
5784 	int ret;
5785 
5786 	btrfs_assert_tree_write_locked(next);
5787 
5788 	generation = btrfs_node_ptr_generation(path->nodes[level], path->slots[level]);
5789 
5790 	check.level = level - 1;
5791 	check.transid = generation;
5792 	check.owner_root = btrfs_root_id(root);
5793 	check.has_first_key = true;
5794 	btrfs_node_key_to_cpu(path->nodes[level], &check.first_key, path->slots[level]);
5795 
5796 	ret = btrfs_buffer_uptodate(next, generation, &check);
5797 	if (ret > 0)
5798 		return 0;
5799 	btrfs_tree_unlock(next);
5800 	if (ret < 0) {
5801 		free_extent_buffer(next);
5802 		return ret;
5803 	}
5804 
5805 	if (level == 1)
5806 		reada_walk_down(trans, root, wc, path);
5807 	ret = btrfs_read_extent_buffer(next, &check);
5808 	if (ret) {
5809 		free_extent_buffer(next);
5810 		return ret;
5811 	}
5812 	btrfs_tree_lock(next);
5813 	wc->lookup_info = 1;
5814 	return 0;
5815 }
5816 
5817 /*
5818  * If we determine that we don't have to visit wc->level - 1 then we need to
5819  * determine if we can drop our reference.
5820  *
5821  * If we are UPDATE_BACKREF then we will not, we need to update our backrefs.
5822  *
5823  * If we are DROP_REFERENCE this will figure out if we need to drop our current
5824  * reference, skipping it if we dropped it from a previous uncompleted drop, or
5825  * dropping it if we still have a reference to it.
5826  */
5827 static int maybe_drop_reference(struct btrfs_trans_handle *trans, struct btrfs_root *root,
5828 				struct btrfs_path *path, struct walk_control *wc,
5829 				struct extent_buffer *next, u64 owner_root)
5830 {
5831 	struct btrfs_ref ref = {
5832 		.action = BTRFS_DROP_DELAYED_REF,
5833 		.bytenr = next->start,
5834 		.num_bytes = root->fs_info->nodesize,
5835 		.owning_root = owner_root,
5836 		.ref_root = btrfs_root_id(root),
5837 	};
5838 	int level = wc->level;
5839 	int ret;
5840 
5841 	/* We are UPDATE_BACKREF, we're not dropping anything. */
5842 	if (wc->stage == UPDATE_BACKREF)
5843 		return 0;
5844 
5845 	if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5846 		ref.parent = path->nodes[level]->start;
5847 	} else {
5848 		ASSERT(btrfs_root_id(root) == btrfs_header_owner(path->nodes[level]));
5849 		if (unlikely(btrfs_root_id(root) != btrfs_header_owner(path->nodes[level]))) {
5850 			btrfs_err(root->fs_info, "mismatched block owner");
5851 			return -EIO;
5852 		}
5853 	}
5854 
5855 	/*
5856 	 * If we had a drop_progress we need to verify the refs are set as
5857 	 * expected.  If we find our ref then we know that from here on out
5858 	 * everything should be correct, and we can clear the
5859 	 * ->restarted flag.
5860 	 */
5861 	if (wc->restarted) {
5862 		ret = check_ref_exists(trans, root, next->start, ref.parent,
5863 				       level - 1);
5864 		if (ret <= 0)
5865 			return ret;
5866 		ret = 0;
5867 		wc->restarted = 0;
5868 	}
5869 
5870 	/*
5871 	 * Reloc tree doesn't contribute to qgroup numbers, and we have already
5872 	 * accounted them at merge time (replace_path), thus we could skip
5873 	 * expensive subtree trace here.
5874 	 */
5875 	if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID &&
5876 	    wc->refs[level - 1] > 1) {
5877 		u64 generation = btrfs_node_ptr_generation(path->nodes[level],
5878 							   path->slots[level]);
5879 
5880 		ret = btrfs_qgroup_trace_subtree(trans, next, generation, level - 1);
5881 		if (ret) {
5882 			btrfs_err_rl(root->fs_info,
5883 "error %d accounting shared subtree, quota is out of sync, rescan required",
5884 				     ret);
5885 		}
5886 	}
5887 
5888 	/*
5889 	 * We need to update the next key in our walk control so we can update
5890 	 * the drop_progress key accordingly.  We don't care if find_next_key
5891 	 * doesn't find a key because that means we're at the end and are going
5892 	 * to clean up now.
5893 	 */
5894 	wc->drop_level = level;
5895 	find_next_key(path, level, &wc->drop_progress);
5896 
5897 	btrfs_init_tree_ref(&ref, level - 1, 0, false);
5898 	return btrfs_free_extent(trans, &ref);
5899 }
5900 
5901 /*
5902  * helper to process tree block pointer.
5903  *
5904  * when wc->stage == DROP_REFERENCE, this function checks
5905  * reference count of the block pointed to. if the block
5906  * is shared and we need update back refs for the subtree
5907  * rooted at the block, this function changes wc->stage to
5908  * UPDATE_BACKREF. if the block is shared and there is no
5909  * need to update back, this function drops the reference
5910  * to the block.
5911  *
5912  * NOTE: return value 1 means we should stop walking down.
5913  */
5914 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
5915 				 struct btrfs_root *root,
5916 				 struct btrfs_path *path,
5917 				 struct walk_control *wc)
5918 {
5919 	struct btrfs_fs_info *fs_info = root->fs_info;
5920 	u64 bytenr;
5921 	u64 generation;
5922 	u64 owner_root = 0;
5923 	struct extent_buffer *next;
5924 	int level = wc->level;
5925 	int ret = 0;
5926 
5927 	generation = btrfs_node_ptr_generation(path->nodes[level],
5928 					       path->slots[level]);
5929 	/*
5930 	 * if the lower level block was created before the snapshot
5931 	 * was created, we know there is no need to update back refs
5932 	 * for the subtree
5933 	 */
5934 	if (wc->stage == UPDATE_BACKREF &&
5935 	    generation <= btrfs_root_origin_generation(root)) {
5936 		wc->lookup_info = 1;
5937 		return 1;
5938 	}
5939 
5940 	bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
5941 
5942 	next = btrfs_find_create_tree_block(fs_info, bytenr, btrfs_root_id(root),
5943 					    level - 1);
5944 	if (IS_ERR(next))
5945 		return PTR_ERR(next);
5946 
5947 	btrfs_tree_lock(next);
5948 
5949 	ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
5950 				       &wc->refs[level - 1],
5951 				       &wc->flags[level - 1],
5952 				       &owner_root);
5953 	if (ret < 0)
5954 		goto out_unlock;
5955 
5956 	if (unlikely(wc->refs[level - 1] == 0)) {
5957 		btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0",
5958 			  bytenr);
5959 		ret = -EUCLEAN;
5960 		goto out_unlock;
5961 	}
5962 	wc->lookup_info = 0;
5963 
5964 	/* If we don't have to walk into this node skip it. */
5965 	if (!visit_node_for_delete(root, wc, path->nodes[level],
5966 				   wc->flags[level - 1], path->slots[level]))
5967 		goto skip;
5968 
5969 	/*
5970 	 * We have to walk down into this node, and if we're currently at the
5971 	 * DROP_REFERENCE stage and this block is shared then we need to switch
5972 	 * to the UPDATE_BACKREF stage in order to convert to FULL_BACKREF.
5973 	 */
5974 	if (wc->stage == DROP_REFERENCE && wc->refs[level - 1] > 1) {
5975 		wc->stage = UPDATE_BACKREF;
5976 		wc->shared_level = level - 1;
5977 	}
5978 
5979 	ret = check_next_block_uptodate(trans, root, path, wc, next);
5980 	if (ret)
5981 		return ret;
5982 
5983 	level--;
5984 	ASSERT(level == btrfs_header_level(next));
5985 	if (unlikely(level != btrfs_header_level(next))) {
5986 		btrfs_err(root->fs_info, "mismatched level");
5987 		ret = -EIO;
5988 		goto out_unlock;
5989 	}
5990 	path->nodes[level] = next;
5991 	path->slots[level] = 0;
5992 	path->locks[level] = BTRFS_WRITE_LOCK;
5993 	wc->level = level;
5994 	if (wc->level == 1)
5995 		wc->reada_slot = 0;
5996 	return 0;
5997 skip:
5998 	ret = maybe_drop_reference(trans, root, path, wc, next, owner_root);
5999 	if (ret)
6000 		goto out_unlock;
6001 	wc->refs[level - 1] = 0;
6002 	wc->flags[level - 1] = 0;
6003 	wc->lookup_info = 1;
6004 	ret = 1;
6005 
6006 out_unlock:
6007 	btrfs_tree_unlock(next);
6008 	free_extent_buffer(next);
6009 
6010 	return ret;
6011 }
6012 
6013 /*
6014  * helper to process tree block while walking up the tree.
6015  *
6016  * when wc->stage == DROP_REFERENCE, this function drops
6017  * reference count on the block.
6018  *
6019  * when wc->stage == UPDATE_BACKREF, this function changes
6020  * wc->stage back to DROP_REFERENCE if we changed wc->stage
6021  * to UPDATE_BACKREF previously while processing the block.
6022  *
6023  * NOTE: return value 1 means we should stop walking up.
6024  */
6025 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
6026 				 struct btrfs_root *root,
6027 				 struct btrfs_path *path,
6028 				 struct walk_control *wc)
6029 {
6030 	struct btrfs_fs_info *fs_info = root->fs_info;
6031 	int ret = 0;
6032 	int level = wc->level;
6033 	struct extent_buffer *eb = path->nodes[level];
6034 	u64 parent = 0;
6035 
6036 	if (wc->stage == UPDATE_BACKREF) {
6037 		ASSERT(wc->shared_level >= level);
6038 		if (level < wc->shared_level)
6039 			goto out;
6040 
6041 		ret = find_next_key(path, level + 1, &wc->update_progress);
6042 		if (ret > 0)
6043 			wc->update_ref = 0;
6044 
6045 		wc->stage = DROP_REFERENCE;
6046 		wc->shared_level = -1;
6047 		path->slots[level] = 0;
6048 
6049 		/*
6050 		 * check reference count again if the block isn't locked.
6051 		 * we should start walking down the tree again if reference
6052 		 * count is one.
6053 		 */
6054 		if (!path->locks[level]) {
6055 			ASSERT(level > 0);
6056 			btrfs_tree_lock(eb);
6057 			path->locks[level] = BTRFS_WRITE_LOCK;
6058 
6059 			ret = btrfs_lookup_extent_info(trans, fs_info,
6060 						       eb->start, level, 1,
6061 						       &wc->refs[level],
6062 						       &wc->flags[level],
6063 						       NULL);
6064 			if (ret < 0) {
6065 				btrfs_tree_unlock_rw(eb, path->locks[level]);
6066 				path->locks[level] = 0;
6067 				return ret;
6068 			}
6069 			if (unlikely(wc->refs[level] == 0)) {
6070 				btrfs_tree_unlock_rw(eb, path->locks[level]);
6071 				btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0",
6072 					  eb->start);
6073 				return -EUCLEAN;
6074 			}
6075 			if (wc->refs[level] == 1) {
6076 				btrfs_tree_unlock_rw(eb, path->locks[level]);
6077 				path->locks[level] = 0;
6078 				return 1;
6079 			}
6080 		}
6081 	}
6082 
6083 	/* wc->stage == DROP_REFERENCE */
6084 	ASSERT(path->locks[level] || wc->refs[level] == 1);
6085 
6086 	if (wc->refs[level] == 1) {
6087 		if (level == 0) {
6088 			const bool full_backref = (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF);
6089 
6090 			ret = btrfs_dec_ref(trans, root, eb, full_backref);
6091 			if (unlikely(ret)) {
6092 				btrfs_abort_transaction(trans, ret);
6093 				return ret;
6094 			}
6095 			if (btrfs_is_fstree(btrfs_root_id(root))) {
6096 				ret = btrfs_qgroup_trace_leaf_items(trans, eb);
6097 				if (ret) {
6098 					btrfs_err_rl(fs_info,
6099 	"error %d accounting leaf items, quota is out of sync, rescan required",
6100 					     ret);
6101 				}
6102 			}
6103 		}
6104 		/* Make block locked assertion in btrfs_clear_buffer_dirty happy. */
6105 		if (!path->locks[level]) {
6106 			btrfs_tree_lock(eb);
6107 			path->locks[level] = BTRFS_WRITE_LOCK;
6108 		}
6109 		btrfs_clear_buffer_dirty(trans, eb);
6110 	}
6111 
6112 	if (eb == root->node) {
6113 		if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6114 			parent = eb->start;
6115 		else if (unlikely(btrfs_root_id(root) != btrfs_header_owner(eb)))
6116 			goto owner_mismatch;
6117 	} else {
6118 		if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6119 			parent = path->nodes[level + 1]->start;
6120 		else if (unlikely(btrfs_root_id(root) !=
6121 				  btrfs_header_owner(path->nodes[level + 1])))
6122 			goto owner_mismatch;
6123 	}
6124 
6125 	ret = btrfs_free_tree_block(trans, btrfs_root_id(root), eb, parent,
6126 				    wc->refs[level] == 1);
6127 	if (ret < 0)
6128 		btrfs_abort_transaction(trans, ret);
6129 out:
6130 	wc->refs[level] = 0;
6131 	wc->flags[level] = 0;
6132 	return ret;
6133 
6134 owner_mismatch:
6135 	btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
6136 		     btrfs_header_owner(eb), btrfs_root_id(root));
6137 	return -EUCLEAN;
6138 }
6139 
6140 /*
6141  * walk_down_tree consists of two steps.
6142  *
6143  * walk_down_proc().  Look up the reference count and reference of our current
6144  * wc->level.  At this point path->nodes[wc->level] should be populated and
6145  * uptodate, and in most cases should already be locked.  If we are in
6146  * DROP_REFERENCE and our refcount is > 1 then we've entered a shared node and
6147  * we can walk back up the tree.  If we are UPDATE_BACKREF we have to set
6148  * FULL_BACKREF on this node if it's not already set, and then do the
6149  * FULL_BACKREF conversion dance, which is to drop the root reference and add
6150  * the shared reference to all of this nodes children.
6151  *
6152  * do_walk_down().  This is where we actually start iterating on the children of
6153  * our current path->nodes[wc->level].  For DROP_REFERENCE that means dropping
6154  * our reference to the children that return false from visit_node_for_delete(),
6155  * which has various conditions where we know we can just drop our reference
6156  * without visiting the node.  For UPDATE_BACKREF we will skip any children that
6157  * visit_node_for_delete() returns false for, only walking down when necessary.
6158  * The bulk of the work for UPDATE_BACKREF occurs in the walk_up_tree() part of
6159  * snapshot deletion.
6160  */
6161 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
6162 				   struct btrfs_root *root,
6163 				   struct btrfs_path *path,
6164 				   struct walk_control *wc)
6165 {
6166 	int level = wc->level;
6167 	int ret = 0;
6168 
6169 	wc->lookup_info = 1;
6170 	while (level >= 0) {
6171 		ret = walk_down_proc(trans, root, path, wc);
6172 		if (ret)
6173 			break;
6174 
6175 		if (level == 0)
6176 			break;
6177 
6178 		if (path->slots[level] >=
6179 		    btrfs_header_nritems(path->nodes[level]))
6180 			break;
6181 
6182 		ret = do_walk_down(trans, root, path, wc);
6183 		if (ret > 0) {
6184 			path->slots[level]++;
6185 			continue;
6186 		} else if (ret < 0)
6187 			break;
6188 		level = wc->level;
6189 	}
6190 	return (ret == 1) ? 0 : ret;
6191 }
6192 
6193 /*
6194  * walk_up_tree() is responsible for making sure we visit every slot on our
6195  * current node, and if we're at the end of that node then we call
6196  * walk_up_proc() on our current node which will do one of a few things based on
6197  * our stage.
6198  *
6199  * UPDATE_BACKREF.  If we wc->level is currently less than our wc->shared_level
6200  * then we need to walk back up the tree, and then going back down into the
6201  * other slots via walk_down_tree to update any other children from our original
6202  * wc->shared_level.  Once we're at or above our wc->shared_level we can switch
6203  * back to DROP_REFERENCE, lookup the current nodes refs and flags, and carry on.
6204  *
6205  * DROP_REFERENCE. If our refs == 1 then we're going to free this tree block.
6206  * If we're level 0 then we need to btrfs_dec_ref() on all of the data extents
6207  * in our current leaf.  After that we call btrfs_free_tree_block() on the
6208  * current node and walk up to the next node to walk down the next slot.
6209  */
6210 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
6211 				 struct btrfs_root *root,
6212 				 struct btrfs_path *path,
6213 				 struct walk_control *wc, int max_level)
6214 {
6215 	int level = wc->level;
6216 	int ret;
6217 
6218 	path->slots[level] = btrfs_header_nritems(path->nodes[level]);
6219 	while (level < max_level && path->nodes[level]) {
6220 		wc->level = level;
6221 		if (path->slots[level] + 1 <
6222 		    btrfs_header_nritems(path->nodes[level])) {
6223 			path->slots[level]++;
6224 			return 0;
6225 		} else {
6226 			ret = walk_up_proc(trans, root, path, wc);
6227 			if (ret > 0)
6228 				return 0;
6229 			if (ret < 0)
6230 				return ret;
6231 
6232 			if (path->locks[level]) {
6233 				btrfs_tree_unlock_rw(path->nodes[level],
6234 						     path->locks[level]);
6235 				path->locks[level] = 0;
6236 			}
6237 			free_extent_buffer(path->nodes[level]);
6238 			path->nodes[level] = NULL;
6239 			level++;
6240 		}
6241 	}
6242 	return 1;
6243 }
6244 
6245 /*
6246  * drop a subvolume tree.
6247  *
6248  * this function traverses the tree freeing any blocks that only
6249  * referenced by the tree.
6250  *
6251  * when a shared tree block is found. this function decreases its
6252  * reference count by one. if update_ref is true, this function
6253  * also make sure backrefs for the shared block and all lower level
6254  * blocks are properly updated.
6255  *
6256  * If called with for_reloc set, may exit early with -EAGAIN
6257  */
6258 int btrfs_drop_snapshot(struct btrfs_root *root, bool update_ref, bool for_reloc)
6259 {
6260 	const bool is_reloc_root = (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID);
6261 	struct btrfs_fs_info *fs_info = root->fs_info;
6262 	struct btrfs_path *path;
6263 	struct btrfs_trans_handle *trans;
6264 	struct btrfs_root *tree_root = fs_info->tree_root;
6265 	struct btrfs_root_item *root_item = &root->root_item;
6266 	struct walk_control AUTO_KFREE(wc);
6267 	struct btrfs_key key;
6268 	const u64 rootid = btrfs_root_id(root);
6269 	int ret = 0;
6270 	int level;
6271 	bool root_dropped = false;
6272 	bool unfinished_drop = false;
6273 
6274 	btrfs_debug(fs_info, "Drop subvolume %llu", btrfs_root_id(root));
6275 
6276 	path = btrfs_alloc_path();
6277 	if (!path) {
6278 		ret = -ENOMEM;
6279 		goto out;
6280 	}
6281 
6282 	wc = kzalloc(sizeof(*wc), GFP_NOFS);
6283 	if (!wc) {
6284 		ret = -ENOMEM;
6285 		goto out_free;
6286 	}
6287 
6288 	/*
6289 	 * Use join to avoid potential EINTR from transaction start. See
6290 	 * wait_reserve_ticket and the whole reservation callchain.
6291 	 */
6292 	if (for_reloc)
6293 		trans = btrfs_join_transaction(tree_root);
6294 	else
6295 		trans = btrfs_start_transaction(tree_root, 0);
6296 	if (IS_ERR(trans)) {
6297 		ret = PTR_ERR(trans);
6298 		goto out_free;
6299 	}
6300 
6301 	ret = btrfs_run_delayed_items(trans);
6302 	if (ret)
6303 		goto out_end_trans;
6304 
6305 	/*
6306 	 * This will help us catch people modifying the fs tree while we're
6307 	 * dropping it.  It is unsafe to mess with the fs tree while it's being
6308 	 * dropped as we unlock the root node and parent nodes as we walk down
6309 	 * the tree, assuming nothing will change.  If something does change
6310 	 * then we'll have stale information and drop references to blocks we've
6311 	 * already dropped.
6312 	 */
6313 	set_bit(BTRFS_ROOT_DELETING, &root->state);
6314 	unfinished_drop = test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state);
6315 
6316 	if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
6317 		level = btrfs_header_level(root->node);
6318 		path->nodes[level] = btrfs_lock_root_node(root);
6319 		path->slots[level] = 0;
6320 		path->locks[level] = BTRFS_WRITE_LOCK;
6321 		memset(&wc->update_progress, 0,
6322 		       sizeof(wc->update_progress));
6323 	} else {
6324 		btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
6325 		memcpy(&wc->update_progress, &key,
6326 		       sizeof(wc->update_progress));
6327 
6328 		level = btrfs_root_drop_level(root_item);
6329 		BUG_ON(level == 0);
6330 		path->lowest_level = level;
6331 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6332 		path->lowest_level = 0;
6333 		if (ret < 0)
6334 			goto out_end_trans;
6335 
6336 		WARN_ON(ret > 0);
6337 		ret = 0;
6338 
6339 		/*
6340 		 * unlock our path, this is safe because only this
6341 		 * function is allowed to delete this snapshot
6342 		 */
6343 		btrfs_unlock_up_safe(path, 0);
6344 
6345 		level = btrfs_header_level(root->node);
6346 		while (1) {
6347 			btrfs_tree_lock(path->nodes[level]);
6348 			path->locks[level] = BTRFS_WRITE_LOCK;
6349 
6350 			/*
6351 			 * btrfs_lookup_extent_info() returns 0 for success,
6352 			 * or < 0 for error.
6353 			 */
6354 			ret = btrfs_lookup_extent_info(trans, fs_info,
6355 						path->nodes[level]->start,
6356 						level, 1, &wc->refs[level],
6357 						&wc->flags[level], NULL);
6358 			if (ret < 0)
6359 				goto out_end_trans;
6360 
6361 			BUG_ON(wc->refs[level] == 0);
6362 
6363 			if (level == btrfs_root_drop_level(root_item))
6364 				break;
6365 
6366 			btrfs_tree_unlock(path->nodes[level]);
6367 			path->locks[level] = 0;
6368 			WARN_ON(wc->refs[level] != 1);
6369 			level--;
6370 		}
6371 	}
6372 
6373 	wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
6374 	wc->level = level;
6375 	wc->shared_level = -1;
6376 	wc->stage = DROP_REFERENCE;
6377 	wc->update_ref = update_ref;
6378 	wc->keep_locks = 0;
6379 	wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
6380 
6381 	while (1) {
6382 
6383 		ret = walk_down_tree(trans, root, path, wc);
6384 		if (unlikely(ret < 0)) {
6385 			btrfs_abort_transaction(trans, ret);
6386 			break;
6387 		}
6388 
6389 		ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
6390 		if (unlikely(ret < 0)) {
6391 			btrfs_abort_transaction(trans, ret);
6392 			break;
6393 		}
6394 
6395 		if (ret > 0) {
6396 			BUG_ON(wc->stage != DROP_REFERENCE);
6397 			ret = 0;
6398 			break;
6399 		}
6400 
6401 		if (wc->stage == DROP_REFERENCE) {
6402 			wc->drop_level = wc->level;
6403 			btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
6404 					      &wc->drop_progress,
6405 					      path->slots[wc->drop_level]);
6406 		}
6407 		btrfs_cpu_key_to_disk(&root_item->drop_progress,
6408 				      &wc->drop_progress);
6409 		btrfs_set_root_drop_level(root_item, wc->drop_level);
6410 
6411 		BUG_ON(wc->level == 0);
6412 		if (btrfs_should_end_transaction(trans) ||
6413 		    (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
6414 			ret = btrfs_update_root(trans, tree_root,
6415 						&root->root_key,
6416 						root_item);
6417 			if (unlikely(ret)) {
6418 				btrfs_abort_transaction(trans, ret);
6419 				goto out_end_trans;
6420 			}
6421 
6422 			if (!is_reloc_root)
6423 				btrfs_set_last_root_drop_gen(fs_info, trans->transid);
6424 
6425 			btrfs_end_transaction_throttle(trans);
6426 			if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
6427 				btrfs_debug(fs_info,
6428 					    "drop snapshot early exit");
6429 				ret = -EAGAIN;
6430 				goto out_free;
6431 			}
6432 
6433 		       /*
6434 			* Use join to avoid potential EINTR from transaction
6435 			* start. See wait_reserve_ticket and the whole
6436 			* reservation callchain.
6437 			*/
6438 			if (for_reloc)
6439 				trans = btrfs_join_transaction(tree_root);
6440 			else
6441 				trans = btrfs_start_transaction(tree_root, 0);
6442 			if (IS_ERR(trans)) {
6443 				ret = PTR_ERR(trans);
6444 				goto out_free;
6445 			}
6446 		}
6447 	}
6448 	btrfs_release_path(path);
6449 	if (ret)
6450 		goto out_end_trans;
6451 
6452 	ret = btrfs_del_root(trans, &root->root_key);
6453 	if (unlikely(ret)) {
6454 		btrfs_abort_transaction(trans, ret);
6455 		goto out_end_trans;
6456 	}
6457 
6458 	if (!is_reloc_root) {
6459 		ret = btrfs_find_root(tree_root, &root->root_key, path,
6460 				      NULL, NULL);
6461 		if (unlikely(ret < 0)) {
6462 			btrfs_abort_transaction(trans, ret);
6463 			goto out_end_trans;
6464 		} else if (ret > 0) {
6465 			ret = 0;
6466 			/*
6467 			 * If we fail to delete the orphan item this time
6468 			 * around, it'll get picked up the next time.
6469 			 *
6470 			 * The most common failure here is just -ENOENT.
6471 			 */
6472 			btrfs_del_orphan_item(trans, tree_root, btrfs_root_id(root));
6473 		}
6474 	}
6475 
6476 	/*
6477 	 * This subvolume is going to be completely dropped, and won't be
6478 	 * recorded as dirty roots, thus pertrans meta rsv will not be freed at
6479 	 * commit transaction time.  So free it here manually.
6480 	 */
6481 	btrfs_qgroup_convert_reserved_meta(root, INT_MAX);
6482 	btrfs_qgroup_free_meta_all_pertrans(root);
6483 
6484 	if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state))
6485 		btrfs_add_dropped_root(trans, root);
6486 	else
6487 		btrfs_put_root(root);
6488 	root_dropped = true;
6489 out_end_trans:
6490 	if (!is_reloc_root)
6491 		btrfs_set_last_root_drop_gen(fs_info, trans->transid);
6492 
6493 	btrfs_end_transaction_throttle(trans);
6494 out_free:
6495 	btrfs_free_path(path);
6496 out:
6497 	if (!ret && root_dropped) {
6498 		ret = btrfs_qgroup_cleanup_dropped_subvolume(fs_info, rootid);
6499 		if (ret < 0)
6500 			btrfs_warn_rl(fs_info,
6501 				      "failed to cleanup qgroup 0/%llu: %d",
6502 				      rootid, ret);
6503 		ret = 0;
6504 	}
6505 	/*
6506 	 * We were an unfinished drop root, check to see if there are any
6507 	 * pending, and if not clear and wake up any waiters.
6508 	 */
6509 	if (!ret && unfinished_drop)
6510 		btrfs_maybe_wake_unfinished_drop(fs_info);
6511 
6512 	/*
6513 	 * So if we need to stop dropping the snapshot for whatever reason we
6514 	 * need to make sure to add it back to the dead root list so that we
6515 	 * keep trying to do the work later.  This also cleans up roots if we
6516 	 * don't have it in the radix (like when we recover after a power fail
6517 	 * or unmount) so we don't leak memory.
6518 	 */
6519 	if (!for_reloc && !root_dropped)
6520 		btrfs_add_dead_root(root);
6521 	return ret;
6522 }
6523 
6524 /*
6525  * drop subtree rooted at tree block 'node'.
6526  *
6527  * NOTE: this function will unlock and release tree block 'node'
6528  * only used by relocation code
6529  */
6530 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
6531 			struct btrfs_root *root,
6532 			struct extent_buffer *node,
6533 			struct extent_buffer *parent)
6534 {
6535 	struct btrfs_fs_info *fs_info = root->fs_info;
6536 	BTRFS_PATH_AUTO_FREE(path);
6537 	struct walk_control AUTO_KFREE(wc);
6538 	int level;
6539 	int parent_level;
6540 	int ret = 0;
6541 
6542 	BUG_ON(btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID);
6543 
6544 	path = btrfs_alloc_path();
6545 	if (!path)
6546 		return -ENOMEM;
6547 
6548 	wc = kzalloc(sizeof(*wc), GFP_NOFS);
6549 	if (!wc)
6550 		return -ENOMEM;
6551 
6552 	btrfs_assert_tree_write_locked(parent);
6553 	parent_level = btrfs_header_level(parent);
6554 	refcount_inc(&parent->refs);
6555 	path->nodes[parent_level] = parent;
6556 	path->slots[parent_level] = btrfs_header_nritems(parent);
6557 
6558 	btrfs_assert_tree_write_locked(node);
6559 	level = btrfs_header_level(node);
6560 	path->nodes[level] = node;
6561 	path->slots[level] = 0;
6562 	path->locks[level] = BTRFS_WRITE_LOCK;
6563 
6564 	wc->refs[parent_level] = 1;
6565 	wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
6566 	wc->level = level;
6567 	wc->shared_level = -1;
6568 	wc->stage = DROP_REFERENCE;
6569 	wc->update_ref = 0;
6570 	wc->keep_locks = 1;
6571 	wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
6572 
6573 	while (1) {
6574 		ret = walk_down_tree(trans, root, path, wc);
6575 		if (ret < 0)
6576 			return ret;
6577 
6578 		ret = walk_up_tree(trans, root, path, wc, parent_level);
6579 		if (ret) {
6580 			if (ret < 0)
6581 				return ret;
6582 			break;
6583 		}
6584 	}
6585 
6586 	return 0;
6587 }
6588 
6589 /*
6590  * Unpin the extent range in an error context and don't add the space back.
6591  * Errors are not propagated further.
6592  */
6593 void btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info, u64 start, u64 end)
6594 {
6595 	unpin_extent_range(fs_info, start, end, false);
6596 }
6597 
6598 /*
6599  * It used to be that old block groups would be left around forever.
6600  * Iterating over them would be enough to trim unused space.  Since we
6601  * now automatically remove them, we also need to iterate over unallocated
6602  * space.
6603  *
6604  * We don't want a transaction for this since the discard may take a
6605  * substantial amount of time.  We don't require that a transaction be
6606  * running, but we do need to take a running transaction into account
6607  * to ensure that we're not discarding chunks that were released or
6608  * allocated in the current transaction.
6609  *
6610  * Holding the chunks lock will prevent other threads from allocating
6611  * or releasing chunks, but it won't prevent a running transaction
6612  * from committing and releasing the memory that the pending chunks
6613  * list head uses.  For that, we need to take a reference to the
6614  * transaction and hold the commit root sem.  We only need to hold
6615  * it while performing the free space search since we have already
6616  * held back allocations.
6617  */
6618 static int btrfs_trim_free_extents_throttle(struct btrfs_device *device,
6619 					    u64 *trimmed, u64 pos, u64 *ret_next_pos)
6620 {
6621 	int ret;
6622 	u64 start = pos;
6623 	u64 trim_len = 0;
6624 
6625 	*trimmed = 0;
6626 
6627 	/*
6628 	 * The caller only filters out MISSING devices, but a device that was
6629 	 * missing at mount and later rescanned has MISSING cleared while bdev
6630 	 * is still NULL and WRITEABLE is still unset. Skip those here.
6631 	 */
6632 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) || !device->bdev)
6633 		return 0;
6634 
6635 	/* Discard not supported = nothing to do. */
6636 	if (!bdev_max_discard_sectors(device->bdev))
6637 		return 0;
6638 
6639 	/* No free space = nothing to do. */
6640 	if (device->total_bytes <= device->bytes_used)
6641 		return 0;
6642 
6643 	ret = 0;
6644 
6645 	while (1) {
6646 		struct btrfs_fs_info *fs_info = device->fs_info;
6647 		u64 cur_start;
6648 		u64 end;
6649 		u64 len;
6650 		u64 bytes;
6651 
6652 		ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
6653 		if (ret)
6654 			break;
6655 
6656 		cur_start = start;
6657 		btrfs_find_first_clear_extent_bit(&device->alloc_state, start,
6658 						  &start, &end,
6659 						  CHUNK_TRIMMED | CHUNK_ALLOCATED);
6660 		start = max(start, cur_start);
6661 
6662 		/* Check if there are any CHUNK_* bits left */
6663 		if (unlikely(start > device->total_bytes)) {
6664 			DEBUG_WARN();
6665 			btrfs_warn(fs_info,
6666 "ignoring attempt to trim beyond device size: offset %llu length %llu device %s device size %llu",
6667 					  start, end - start + 1,
6668 					  btrfs_dev_name(device),
6669 					  device->total_bytes);
6670 			mutex_unlock(&fs_info->chunk_mutex);
6671 			ret = 0;
6672 			break;
6673 		}
6674 
6675 		/* Ensure we skip the reserved space on each device. */
6676 		start = max_t(u64, start, BTRFS_DEVICE_RANGE_RESERVED);
6677 
6678 		/*
6679 		 * If find_first_clear_extent_bit find a range that spans the
6680 		 * end of the device it will set end to -1, in this case it's up
6681 		 * to the caller to trim the value to the size of the device.
6682 		 */
6683 		end = min(end, device->total_bytes - 1);
6684 
6685 		len = end - start + 1;
6686 		len = min(len, BTRFS_MAX_TRIM_LENGTH);
6687 
6688 		/* We didn't find any extents */
6689 		if (!len) {
6690 			mutex_unlock(&fs_info->chunk_mutex);
6691 			ret = 0;
6692 			break;
6693 		}
6694 
6695 		ret = btrfs_issue_discard(device->bdev, start, len,
6696 					  &bytes);
6697 		if (!ret)
6698 			btrfs_set_extent_bit(&device->alloc_state, start,
6699 					     start + bytes - 1, CHUNK_TRIMMED, NULL);
6700 		mutex_unlock(&fs_info->chunk_mutex);
6701 
6702 		if (ret)
6703 			break;
6704 
6705 		start += len;
6706 		*trimmed += bytes;
6707 		trim_len += len;
6708 		if (trim_len >= BTRFS_MAX_TRIM_LENGTH) {
6709 			*ret_next_pos = start;
6710 			ret = -EAGAIN;
6711 			break;
6712 		}
6713 
6714 		if (btrfs_trim_interrupted()) {
6715 			ret = -ERESTARTSYS;
6716 			break;
6717 		}
6718 
6719 		cond_resched();
6720 	}
6721 
6722 	return ret;
6723 }
6724 
6725 static int btrfs_trim_free_extents(struct btrfs_fs_info *fs_info, u64 *trimmed,
6726 				   u64 *dev_failed, int *dev_ret)
6727 {
6728 	struct btrfs_device *dev;
6729 	struct btrfs_device *working_dev = NULL;
6730 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6731 	u8 uuid[BTRFS_UUID_SIZE];
6732 	u64 start = BTRFS_DEVICE_RANGE_RESERVED;
6733 
6734 	*trimmed = 0;
6735 	*dev_failed = 0;
6736 	*dev_ret = 0;
6737 
6738 	/* Find the device with the smallest UUID to start. */
6739 	mutex_lock(&fs_devices->device_list_mutex);
6740 	list_for_each_entry(dev, &fs_devices->devices, dev_list) {
6741 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
6742 			continue;
6743 		if (!working_dev ||
6744 		    memcmp(dev->uuid, working_dev->uuid, BTRFS_UUID_SIZE) < 0)
6745 			working_dev = dev;
6746 	}
6747 	if (working_dev)
6748 		memcpy(uuid, working_dev->uuid, BTRFS_UUID_SIZE);
6749 	mutex_unlock(&fs_devices->device_list_mutex);
6750 
6751 	if (!working_dev)
6752 		return 0;
6753 
6754 	while (1) {
6755 		u64 group_trimmed = 0;
6756 		u64 next_pos = 0;
6757 		int ret = 0;
6758 
6759 		mutex_lock(&fs_devices->device_list_mutex);
6760 
6761 		/* Find and trim the current device. */
6762 		list_for_each_entry(dev, &fs_devices->devices, dev_list) {
6763 			if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
6764 				continue;
6765 			if (dev == working_dev) {
6766 				ret = btrfs_trim_free_extents_throttle(working_dev,
6767 						&group_trimmed, start, &next_pos);
6768 				break;
6769 			}
6770 		}
6771 
6772 		/* Throttle: continue the same device from the new position. */
6773 		if (ret == -EAGAIN && next_pos > start) {
6774 			mutex_unlock(&fs_devices->device_list_mutex);
6775 			*trimmed += group_trimmed;
6776 			start = next_pos;
6777 			cond_resched();
6778 			continue;
6779 		}
6780 
6781 		/* User interrupted. */
6782 		if (ret == -ERESTARTSYS || ret == -EINTR) {
6783 			mutex_unlock(&fs_devices->device_list_mutex);
6784 			*trimmed += group_trimmed;
6785 			return ret;
6786 		}
6787 
6788 		/*
6789 		 * Device completed (ret == 0), failed, or EAGAIN with no progress.
6790 		 * Record error if any, then move to next device.
6791 		 */
6792 		if (ret == -EAGAIN) {
6793 			/* No progress - log and skip device. */
6794 			btrfs_warn(fs_info,
6795 				   "trim throttle: no progress, offset=%llu device %s, skipping",
6796 				   start, btrfs_dev_name(working_dev));
6797 			(*dev_failed)++;
6798 			if (!*dev_ret)
6799 				*dev_ret = ret;
6800 		} else if (ret) {
6801 			/* Device failed with error. */
6802 			(*dev_failed)++;
6803 			if (!*dev_ret)
6804 				*dev_ret = ret;
6805 		}
6806 
6807 		/*
6808 		 * Find next device: smallest UUID larger than current.
6809 		 * Devices added during trim with smaller UUID will be skipped.
6810 		 */
6811 		working_dev = NULL;
6812 		list_for_each_entry(dev, &fs_devices->devices, dev_list) {
6813 			if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
6814 				continue;
6815 			/* Must larger than current UUID. */
6816 			if (memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE) <= 0)
6817 				continue;
6818 			/* Find the smallest. */
6819 			if (!working_dev ||
6820 			    memcmp(dev->uuid, working_dev->uuid, BTRFS_UUID_SIZE) < 0)
6821 				working_dev = dev;
6822 		}
6823 		if (working_dev)
6824 			memcpy(uuid, working_dev->uuid, BTRFS_UUID_SIZE);
6825 
6826 		mutex_unlock(&fs_devices->device_list_mutex);
6827 
6828 		*trimmed += group_trimmed;
6829 		start = BTRFS_DEVICE_RANGE_RESERVED;
6830 
6831 		/* No more devices. */
6832 		if (!working_dev)
6833 			break;
6834 
6835 		cond_resched();
6836 	}
6837 
6838 	return 0;
6839 }
6840 
6841 /*
6842  * Trim the whole filesystem by:
6843  * 1) trimming the free space in each block group
6844  * 2) trimming the unallocated space on each device
6845  *
6846  * This will also continue trimming even if a block group or device encounters
6847  * an error.  The return value will be the first error, or 0 if nothing bad
6848  * happens.
6849  */
6850 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
6851 {
6852 	struct btrfs_block_group *cache = NULL;
6853 	u64 group_trimmed;
6854 	u64 range_end = U64_MAX;
6855 	u64 start;
6856 	u64 end;
6857 	u64 trimmed = 0;
6858 	u64 bg_failed = 0;
6859 	u64 dev_failed = 0;
6860 	int bg_ret = 0;
6861 	int dev_ret = 0;
6862 	int ret = 0;
6863 
6864 	if (range->start == U64_MAX)
6865 		return -EINVAL;
6866 
6867 	/*
6868 	 * Check range overflow if range->len is set.
6869 	 * The default range->len is U64_MAX.
6870 	 */
6871 	if (range->len != U64_MAX &&
6872 	    check_add_overflow(range->start, range->len, &range_end))
6873 		return -EINVAL;
6874 
6875 	cache = btrfs_lookup_first_block_group(fs_info, range->start);
6876 	for (; cache; cache = btrfs_next_block_group(cache)) {
6877 		if (cache->start >= range_end) {
6878 			btrfs_put_block_group(cache);
6879 			break;
6880 		}
6881 
6882 		start = max(range->start, cache->start);
6883 		end = min(range_end, btrfs_block_group_end(cache));
6884 
6885 		if (end - start >= range->minlen) {
6886 			if (!btrfs_block_group_done(cache)) {
6887 				ret = btrfs_cache_block_group(cache, true);
6888 				if (ret) {
6889 					bg_failed++;
6890 					if (!bg_ret)
6891 						bg_ret = ret;
6892 					continue;
6893 				}
6894 			}
6895 			ret = btrfs_trim_block_group(cache,
6896 						     &group_trimmed,
6897 						     start,
6898 						     end,
6899 						     range->minlen);
6900 
6901 			trimmed += group_trimmed;
6902 			if (ret == -ERESTARTSYS || ret == -EINTR) {
6903 				btrfs_put_block_group(cache);
6904 				break;
6905 			}
6906 			if (ret) {
6907 				bg_failed++;
6908 				if (!bg_ret)
6909 					bg_ret = ret;
6910 				continue;
6911 			}
6912 		}
6913 	}
6914 
6915 	if (bg_failed)
6916 		btrfs_warn(fs_info,
6917 			"failed to trim %llu block group(s), first error %d",
6918 			bg_failed, bg_ret);
6919 
6920 	if (ret == -ERESTARTSYS || ret == -EINTR)
6921 		return ret;
6922 
6923 	ret = btrfs_trim_free_extents(fs_info, &group_trimmed, &dev_failed, &dev_ret);
6924 	trimmed += group_trimmed;
6925 
6926 	if (dev_failed)
6927 		btrfs_warn(fs_info,
6928 			"failed to trim %llu device(s), first error %d",
6929 			dev_failed, dev_ret);
6930 	range->len = trimmed;
6931 	if (ret == -ERESTARTSYS || ret == -EINTR)
6932 		return ret;
6933 	if (bg_ret)
6934 		return bg_ret;
6935 	return dev_ret;
6936 }
6937