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