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