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