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