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