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