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