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