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