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