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