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