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