1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include <linux/bitops.h>
4 #include <linux/slab.h>
5 #include <linux/bio.h>
6 #include <linux/mm.h>
7 #include <linux/pagemap.h>
8 #include <linux/page-flags.h>
9 #include <linux/sched/mm.h>
10 #include <linux/spinlock.h>
11 #include <linux/blkdev.h>
12 #include <linux/swap.h>
13 #include <linux/writeback.h>
14 #include <linux/pagevec.h>
15 #include <linux/prefetch.h>
16 #include <linux/fsverity.h>
17 #include "misc.h"
18 #include "extent_io.h"
19 #include "extent-io-tree.h"
20 #include "extent_map.h"
21 #include "ctree.h"
22 #include "btrfs_inode.h"
23 #include "volumes.h"
24 #include "check-integrity.h"
25 #include "locking.h"
26 #include "rcu-string.h"
27 #include "backref.h"
28 #include "disk-io.h"
29 #include "subpage.h"
30 #include "zoned.h"
31 #include "block-group.h"
32 #include "compression.h"
33 
34 static struct kmem_cache *extent_state_cache;
35 static struct kmem_cache *extent_buffer_cache;
36 static struct bio_set btrfs_bioset;
37 
extent_state_in_tree(const struct extent_state * state)38 static inline bool extent_state_in_tree(const struct extent_state *state)
39 {
40 	return !RB_EMPTY_NODE(&state->rb_node);
41 }
42 
43 #ifdef CONFIG_BTRFS_DEBUG
44 static LIST_HEAD(states);
45 static DEFINE_SPINLOCK(leak_lock);
46 
btrfs_leak_debug_add(spinlock_t * lock,struct list_head * new,struct list_head * head)47 static inline void btrfs_leak_debug_add(spinlock_t *lock,
48 					struct list_head *new,
49 					struct list_head *head)
50 {
51 	unsigned long flags;
52 
53 	spin_lock_irqsave(lock, flags);
54 	list_add(new, head);
55 	spin_unlock_irqrestore(lock, flags);
56 }
57 
btrfs_leak_debug_del(spinlock_t * lock,struct list_head * entry)58 static inline void btrfs_leak_debug_del(spinlock_t *lock,
59 					struct list_head *entry)
60 {
61 	unsigned long flags;
62 
63 	spin_lock_irqsave(lock, flags);
64 	list_del(entry);
65 	spin_unlock_irqrestore(lock, flags);
66 }
67 
btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info * fs_info)68 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
69 {
70 	struct extent_buffer *eb;
71 	unsigned long flags;
72 
73 	/*
74 	 * If we didn't get into open_ctree our allocated_ebs will not be
75 	 * initialized, so just skip this.
76 	 */
77 	if (!fs_info->allocated_ebs.next)
78 		return;
79 
80 	WARN_ON(!list_empty(&fs_info->allocated_ebs));
81 	spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
82 	while (!list_empty(&fs_info->allocated_ebs)) {
83 		eb = list_first_entry(&fs_info->allocated_ebs,
84 				      struct extent_buffer, leak_list);
85 		pr_err(
86 	"BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
87 		       eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
88 		       btrfs_header_owner(eb));
89 		list_del(&eb->leak_list);
90 		kmem_cache_free(extent_buffer_cache, eb);
91 	}
92 	spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
93 }
94 
btrfs_extent_state_leak_debug_check(void)95 static inline void btrfs_extent_state_leak_debug_check(void)
96 {
97 	struct extent_state *state;
98 
99 	while (!list_empty(&states)) {
100 		state = list_entry(states.next, struct extent_state, leak_list);
101 		pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
102 		       state->start, state->end, state->state,
103 		       extent_state_in_tree(state),
104 		       refcount_read(&state->refs));
105 		list_del(&state->leak_list);
106 		kmem_cache_free(extent_state_cache, state);
107 	}
108 }
109 
110 #define btrfs_debug_check_extent_io_range(tree, start, end)		\
111 	__btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
__btrfs_debug_check_extent_io_range(const char * caller,struct extent_io_tree * tree,u64 start,u64 end)112 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
113 		struct extent_io_tree *tree, u64 start, u64 end)
114 {
115 	struct inode *inode = tree->private_data;
116 	u64 isize;
117 
118 	if (!inode || !is_data_inode(inode))
119 		return;
120 
121 	isize = i_size_read(inode);
122 	if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
123 		btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
124 		    "%s: ino %llu isize %llu odd range [%llu,%llu]",
125 			caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
126 	}
127 }
128 #else
129 #define btrfs_leak_debug_add(lock, new, head)	do {} while (0)
130 #define btrfs_leak_debug_del(lock, entry)	do {} while (0)
131 #define btrfs_extent_state_leak_debug_check()	do {} while (0)
132 #define btrfs_debug_check_extent_io_range(c, s, e)	do {} while (0)
133 #endif
134 
135 struct tree_entry {
136 	u64 start;
137 	u64 end;
138 	struct rb_node rb_node;
139 };
140 
141 /*
142  * Structure to record info about the bio being assembled, and other info like
143  * how many bytes are there before stripe/ordered extent boundary.
144  */
145 struct btrfs_bio_ctrl {
146 	struct bio *bio;
147 	enum btrfs_compression_type compress_type;
148 	u32 len_to_stripe_boundary;
149 	u32 len_to_oe_boundary;
150 };
151 
152 struct extent_page_data {
153 	struct btrfs_bio_ctrl bio_ctrl;
154 	/* tells writepage not to lock the state bits for this range
155 	 * it still does the unlocking
156 	 */
157 	unsigned int extent_locked:1;
158 
159 	/* tells the submit_bio code to use REQ_SYNC */
160 	unsigned int sync_io:1;
161 };
162 
add_extent_changeset(struct extent_state * state,u32 bits,struct extent_changeset * changeset,int set)163 static int add_extent_changeset(struct extent_state *state, u32 bits,
164 				 struct extent_changeset *changeset,
165 				 int set)
166 {
167 	int ret;
168 
169 	if (!changeset)
170 		return 0;
171 	if (set && (state->state & bits) == bits)
172 		return 0;
173 	if (!set && (state->state & bits) == 0)
174 		return 0;
175 	changeset->bytes_changed += state->end - state->start + 1;
176 	ret = ulist_add(&changeset->range_changed, state->start, state->end,
177 			GFP_ATOMIC);
178 	return ret;
179 }
180 
submit_one_bio(struct bio * bio,int mirror_num,enum btrfs_compression_type compress_type)181 static void submit_one_bio(struct bio *bio, int mirror_num,
182 			   enum btrfs_compression_type compress_type)
183 {
184 	struct extent_io_tree *tree = bio->bi_private;
185 
186 	bio->bi_private = NULL;
187 
188 	/* Caller should ensure the bio has at least some range added */
189 	ASSERT(bio->bi_iter.bi_size);
190 
191 	if (is_data_inode(tree->private_data))
192 		btrfs_submit_data_bio(tree->private_data, bio, mirror_num,
193 					    compress_type);
194 	else
195 		btrfs_submit_metadata_bio(tree->private_data, bio, mirror_num);
196 	/*
197 	 * Above submission hooks will handle the error by ending the bio,
198 	 * which will do the cleanup properly.  So here we should not return
199 	 * any error, or the caller of submit_extent_page() will do cleanup
200 	 * again, causing problems.
201 	 */
202 }
203 
204 /* Cleanup unsubmitted bios */
end_write_bio(struct extent_page_data * epd,int ret)205 static void end_write_bio(struct extent_page_data *epd, int ret)
206 {
207 	struct bio *bio = epd->bio_ctrl.bio;
208 
209 	if (bio) {
210 		bio->bi_status = errno_to_blk_status(ret);
211 		bio_endio(bio);
212 		epd->bio_ctrl.bio = NULL;
213 	}
214 }
215 
216 /*
217  * Submit bio from extent page data via submit_one_bio
218  *
219  * Return 0 if everything is OK.
220  * Return <0 for error.
221  */
flush_write_bio(struct extent_page_data * epd)222 static void flush_write_bio(struct extent_page_data *epd)
223 {
224 	struct bio *bio = epd->bio_ctrl.bio;
225 
226 	if (bio) {
227 		submit_one_bio(bio, 0, 0);
228 		/*
229 		 * Clean up of epd->bio is handled by its endio function.
230 		 * And endio is either triggered by successful bio execution
231 		 * or the error handler of submit bio hook.
232 		 * So at this point, no matter what happened, we don't need
233 		 * to clean up epd->bio.
234 		 */
235 		epd->bio_ctrl.bio = NULL;
236 	}
237 }
238 
extent_state_cache_init(void)239 int __init extent_state_cache_init(void)
240 {
241 	extent_state_cache = kmem_cache_create("btrfs_extent_state",
242 			sizeof(struct extent_state), 0,
243 			SLAB_MEM_SPREAD, NULL);
244 	if (!extent_state_cache)
245 		return -ENOMEM;
246 	return 0;
247 }
248 
extent_io_init(void)249 int __init extent_io_init(void)
250 {
251 	extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
252 			sizeof(struct extent_buffer), 0,
253 			SLAB_MEM_SPREAD, NULL);
254 	if (!extent_buffer_cache)
255 		return -ENOMEM;
256 
257 	if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
258 			offsetof(struct btrfs_bio, bio),
259 			BIOSET_NEED_BVECS))
260 		goto free_buffer_cache;
261 
262 	if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
263 		goto free_bioset;
264 
265 	return 0;
266 
267 free_bioset:
268 	bioset_exit(&btrfs_bioset);
269 
270 free_buffer_cache:
271 	kmem_cache_destroy(extent_buffer_cache);
272 	extent_buffer_cache = NULL;
273 	return -ENOMEM;
274 }
275 
extent_state_cache_exit(void)276 void __cold extent_state_cache_exit(void)
277 {
278 	btrfs_extent_state_leak_debug_check();
279 	kmem_cache_destroy(extent_state_cache);
280 }
281 
extent_io_exit(void)282 void __cold extent_io_exit(void)
283 {
284 	/*
285 	 * Make sure all delayed rcu free are flushed before we
286 	 * destroy caches.
287 	 */
288 	rcu_barrier();
289 	kmem_cache_destroy(extent_buffer_cache);
290 	bioset_exit(&btrfs_bioset);
291 }
292 
293 /*
294  * For the file_extent_tree, we want to hold the inode lock when we lookup and
295  * update the disk_i_size, but lockdep will complain because our io_tree we hold
296  * the tree lock and get the inode lock when setting delalloc.  These two things
297  * are unrelated, so make a class for the file_extent_tree so we don't get the
298  * two locking patterns mixed up.
299  */
300 static struct lock_class_key file_extent_tree_class;
301 
extent_io_tree_init(struct btrfs_fs_info * fs_info,struct extent_io_tree * tree,unsigned int owner,void * private_data)302 void extent_io_tree_init(struct btrfs_fs_info *fs_info,
303 			 struct extent_io_tree *tree, unsigned int owner,
304 			 void *private_data)
305 {
306 	tree->fs_info = fs_info;
307 	tree->state = RB_ROOT;
308 	tree->dirty_bytes = 0;
309 	spin_lock_init(&tree->lock);
310 	tree->private_data = private_data;
311 	tree->owner = owner;
312 	if (owner == IO_TREE_INODE_FILE_EXTENT)
313 		lockdep_set_class(&tree->lock, &file_extent_tree_class);
314 }
315 
extent_io_tree_release(struct extent_io_tree * tree)316 void extent_io_tree_release(struct extent_io_tree *tree)
317 {
318 	spin_lock(&tree->lock);
319 	/*
320 	 * Do a single barrier for the waitqueue_active check here, the state
321 	 * of the waitqueue should not change once extent_io_tree_release is
322 	 * called.
323 	 */
324 	smp_mb();
325 	while (!RB_EMPTY_ROOT(&tree->state)) {
326 		struct rb_node *node;
327 		struct extent_state *state;
328 
329 		node = rb_first(&tree->state);
330 		state = rb_entry(node, struct extent_state, rb_node);
331 		rb_erase(&state->rb_node, &tree->state);
332 		RB_CLEAR_NODE(&state->rb_node);
333 		/*
334 		 * btree io trees aren't supposed to have tasks waiting for
335 		 * changes in the flags of extent states ever.
336 		 */
337 		ASSERT(!waitqueue_active(&state->wq));
338 		free_extent_state(state);
339 
340 		cond_resched_lock(&tree->lock);
341 	}
342 	spin_unlock(&tree->lock);
343 }
344 
alloc_extent_state(gfp_t mask)345 static struct extent_state *alloc_extent_state(gfp_t mask)
346 {
347 	struct extent_state *state;
348 
349 	/*
350 	 * The given mask might be not appropriate for the slab allocator,
351 	 * drop the unsupported bits
352 	 */
353 	mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
354 	state = kmem_cache_alloc(extent_state_cache, mask);
355 	if (!state)
356 		return state;
357 	state->state = 0;
358 	state->failrec = NULL;
359 	RB_CLEAR_NODE(&state->rb_node);
360 	btrfs_leak_debug_add(&leak_lock, &state->leak_list, &states);
361 	refcount_set(&state->refs, 1);
362 	init_waitqueue_head(&state->wq);
363 	trace_alloc_extent_state(state, mask, _RET_IP_);
364 	return state;
365 }
366 
free_extent_state(struct extent_state * state)367 void free_extent_state(struct extent_state *state)
368 {
369 	if (!state)
370 		return;
371 	if (refcount_dec_and_test(&state->refs)) {
372 		WARN_ON(extent_state_in_tree(state));
373 		btrfs_leak_debug_del(&leak_lock, &state->leak_list);
374 		trace_free_extent_state(state, _RET_IP_);
375 		kmem_cache_free(extent_state_cache, state);
376 	}
377 }
378 
tree_insert(struct rb_root * root,struct rb_node * search_start,u64 offset,struct rb_node * node,struct rb_node *** p_in,struct rb_node ** parent_in)379 static struct rb_node *tree_insert(struct rb_root *root,
380 				   struct rb_node *search_start,
381 				   u64 offset,
382 				   struct rb_node *node,
383 				   struct rb_node ***p_in,
384 				   struct rb_node **parent_in)
385 {
386 	struct rb_node **p;
387 	struct rb_node *parent = NULL;
388 	struct tree_entry *entry;
389 
390 	if (p_in && parent_in) {
391 		p = *p_in;
392 		parent = *parent_in;
393 		goto do_insert;
394 	}
395 
396 	p = search_start ? &search_start : &root->rb_node;
397 	while (*p) {
398 		parent = *p;
399 		entry = rb_entry(parent, struct tree_entry, rb_node);
400 
401 		if (offset < entry->start)
402 			p = &(*p)->rb_left;
403 		else if (offset > entry->end)
404 			p = &(*p)->rb_right;
405 		else
406 			return parent;
407 	}
408 
409 do_insert:
410 	rb_link_node(node, parent, p);
411 	rb_insert_color(node, root);
412 	return NULL;
413 }
414 
415 /**
416  * Search @tree for an entry that contains @offset. Such entry would have
417  * entry->start <= offset && entry->end >= offset.
418  *
419  * @tree:       the tree to search
420  * @offset:     offset that should fall within an entry in @tree
421  * @next_ret:   pointer to the first entry whose range ends after @offset
422  * @prev_ret:   pointer to the first entry whose range begins before @offset
423  * @p_ret:      pointer where new node should be anchored (used when inserting an
424  *	        entry in the tree)
425  * @parent_ret: points to entry which would have been the parent of the entry,
426  *               containing @offset
427  *
428  * This function returns a pointer to the entry that contains @offset byte
429  * address. If no such entry exists, then NULL is returned and the other
430  * pointer arguments to the function are filled, otherwise the found entry is
431  * returned and other pointers are left untouched.
432  */
__etree_search(struct extent_io_tree * tree,u64 offset,struct rb_node ** next_ret,struct rb_node ** prev_ret,struct rb_node *** p_ret,struct rb_node ** parent_ret)433 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
434 				      struct rb_node **next_ret,
435 				      struct rb_node **prev_ret,
436 				      struct rb_node ***p_ret,
437 				      struct rb_node **parent_ret)
438 {
439 	struct rb_root *root = &tree->state;
440 	struct rb_node **n = &root->rb_node;
441 	struct rb_node *prev = NULL;
442 	struct rb_node *orig_prev = NULL;
443 	struct tree_entry *entry;
444 	struct tree_entry *prev_entry = NULL;
445 
446 	while (*n) {
447 		prev = *n;
448 		entry = rb_entry(prev, struct tree_entry, rb_node);
449 		prev_entry = entry;
450 
451 		if (offset < entry->start)
452 			n = &(*n)->rb_left;
453 		else if (offset > entry->end)
454 			n = &(*n)->rb_right;
455 		else
456 			return *n;
457 	}
458 
459 	if (p_ret)
460 		*p_ret = n;
461 	if (parent_ret)
462 		*parent_ret = prev;
463 
464 	if (next_ret) {
465 		orig_prev = prev;
466 		while (prev && offset > prev_entry->end) {
467 			prev = rb_next(prev);
468 			prev_entry = rb_entry(prev, struct tree_entry, rb_node);
469 		}
470 		*next_ret = prev;
471 		prev = orig_prev;
472 	}
473 
474 	if (prev_ret) {
475 		prev_entry = rb_entry(prev, struct tree_entry, rb_node);
476 		while (prev && offset < prev_entry->start) {
477 			prev = rb_prev(prev);
478 			prev_entry = rb_entry(prev, struct tree_entry, rb_node);
479 		}
480 		*prev_ret = prev;
481 	}
482 	return NULL;
483 }
484 
485 static inline struct rb_node *
tree_search_for_insert(struct extent_io_tree * tree,u64 offset,struct rb_node *** p_ret,struct rb_node ** parent_ret)486 tree_search_for_insert(struct extent_io_tree *tree,
487 		       u64 offset,
488 		       struct rb_node ***p_ret,
489 		       struct rb_node **parent_ret)
490 {
491 	struct rb_node *next= NULL;
492 	struct rb_node *ret;
493 
494 	ret = __etree_search(tree, offset, &next, NULL, p_ret, parent_ret);
495 	if (!ret)
496 		return next;
497 	return ret;
498 }
499 
tree_search(struct extent_io_tree * tree,u64 offset)500 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
501 					  u64 offset)
502 {
503 	return tree_search_for_insert(tree, offset, NULL, NULL);
504 }
505 
506 /*
507  * utility function to look for merge candidates inside a given range.
508  * Any extents with matching state are merged together into a single
509  * extent in the tree.  Extents with EXTENT_IO in their state field
510  * are not merged because the end_io handlers need to be able to do
511  * operations on them without sleeping (or doing allocations/splits).
512  *
513  * This should be called with the tree lock held.
514  */
merge_state(struct extent_io_tree * tree,struct extent_state * state)515 static void merge_state(struct extent_io_tree *tree,
516 		        struct extent_state *state)
517 {
518 	struct extent_state *other;
519 	struct rb_node *other_node;
520 
521 	if (state->state & (EXTENT_LOCKED | EXTENT_BOUNDARY))
522 		return;
523 
524 	other_node = rb_prev(&state->rb_node);
525 	if (other_node) {
526 		other = rb_entry(other_node, struct extent_state, rb_node);
527 		if (other->end == state->start - 1 &&
528 		    other->state == state->state) {
529 			if (tree->private_data &&
530 			    is_data_inode(tree->private_data))
531 				btrfs_merge_delalloc_extent(tree->private_data,
532 							    state, other);
533 			state->start = other->start;
534 			rb_erase(&other->rb_node, &tree->state);
535 			RB_CLEAR_NODE(&other->rb_node);
536 			free_extent_state(other);
537 		}
538 	}
539 	other_node = rb_next(&state->rb_node);
540 	if (other_node) {
541 		other = rb_entry(other_node, struct extent_state, rb_node);
542 		if (other->start == state->end + 1 &&
543 		    other->state == state->state) {
544 			if (tree->private_data &&
545 			    is_data_inode(tree->private_data))
546 				btrfs_merge_delalloc_extent(tree->private_data,
547 							    state, other);
548 			state->end = other->end;
549 			rb_erase(&other->rb_node, &tree->state);
550 			RB_CLEAR_NODE(&other->rb_node);
551 			free_extent_state(other);
552 		}
553 	}
554 }
555 
556 static void set_state_bits(struct extent_io_tree *tree,
557 			   struct extent_state *state, u32 *bits,
558 			   struct extent_changeset *changeset);
559 
560 /*
561  * insert an extent_state struct into the tree.  'bits' are set on the
562  * struct before it is inserted.
563  *
564  * This may return -EEXIST if the extent is already there, in which case the
565  * state struct is freed.
566  *
567  * The tree lock is not taken internally.  This is a utility function and
568  * probably isn't what you want to call (see set/clear_extent_bit).
569  */
insert_state(struct extent_io_tree * tree,struct extent_state * state,u64 start,u64 end,struct rb_node *** p,struct rb_node ** parent,u32 * bits,struct extent_changeset * changeset)570 static int insert_state(struct extent_io_tree *tree,
571 			struct extent_state *state, u64 start, u64 end,
572 			struct rb_node ***p,
573 			struct rb_node **parent,
574 			u32 *bits, struct extent_changeset *changeset)
575 {
576 	struct rb_node *node;
577 
578 	if (end < start) {
579 		btrfs_err(tree->fs_info,
580 			"insert state: end < start %llu %llu", end, start);
581 		WARN_ON(1);
582 	}
583 	state->start = start;
584 	state->end = end;
585 
586 	set_state_bits(tree, state, bits, changeset);
587 
588 	node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
589 	if (node) {
590 		struct extent_state *found;
591 		found = rb_entry(node, struct extent_state, rb_node);
592 		btrfs_err(tree->fs_info,
593 		       "found node %llu %llu on insert of %llu %llu",
594 		       found->start, found->end, start, end);
595 		return -EEXIST;
596 	}
597 	merge_state(tree, state);
598 	return 0;
599 }
600 
601 /*
602  * split a given extent state struct in two, inserting the preallocated
603  * struct 'prealloc' as the newly created second half.  'split' indicates an
604  * offset inside 'orig' where it should be split.
605  *
606  * Before calling,
607  * the tree has 'orig' at [orig->start, orig->end].  After calling, there
608  * are two extent state structs in the tree:
609  * prealloc: [orig->start, split - 1]
610  * orig: [ split, orig->end ]
611  *
612  * The tree locks are not taken by this function. They need to be held
613  * by the caller.
614  */
split_state(struct extent_io_tree * tree,struct extent_state * orig,struct extent_state * prealloc,u64 split)615 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
616 		       struct extent_state *prealloc, u64 split)
617 {
618 	struct rb_node *node;
619 
620 	if (tree->private_data && is_data_inode(tree->private_data))
621 		btrfs_split_delalloc_extent(tree->private_data, orig, split);
622 
623 	prealloc->start = orig->start;
624 	prealloc->end = split - 1;
625 	prealloc->state = orig->state;
626 	orig->start = split;
627 
628 	node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
629 			   &prealloc->rb_node, NULL, NULL);
630 	if (node) {
631 		free_extent_state(prealloc);
632 		return -EEXIST;
633 	}
634 	return 0;
635 }
636 
next_state(struct extent_state * state)637 static struct extent_state *next_state(struct extent_state *state)
638 {
639 	struct rb_node *next = rb_next(&state->rb_node);
640 	if (next)
641 		return rb_entry(next, struct extent_state, rb_node);
642 	else
643 		return NULL;
644 }
645 
646 /*
647  * utility function to clear some bits in an extent state struct.
648  * it will optionally wake up anyone waiting on this state (wake == 1).
649  *
650  * If no bits are set on the state struct after clearing things, the
651  * struct is freed and removed from the tree
652  */
clear_state_bit(struct extent_io_tree * tree,struct extent_state * state,u32 * bits,int wake,struct extent_changeset * changeset)653 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
654 					    struct extent_state *state,
655 					    u32 *bits, int wake,
656 					    struct extent_changeset *changeset)
657 {
658 	struct extent_state *next;
659 	u32 bits_to_clear = *bits & ~EXTENT_CTLBITS;
660 	int ret;
661 
662 	if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
663 		u64 range = state->end - state->start + 1;
664 		WARN_ON(range > tree->dirty_bytes);
665 		tree->dirty_bytes -= range;
666 	}
667 
668 	if (tree->private_data && is_data_inode(tree->private_data))
669 		btrfs_clear_delalloc_extent(tree->private_data, state, bits);
670 
671 	ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
672 	BUG_ON(ret < 0);
673 	state->state &= ~bits_to_clear;
674 	if (wake)
675 		wake_up(&state->wq);
676 	if (state->state == 0) {
677 		next = next_state(state);
678 		if (extent_state_in_tree(state)) {
679 			rb_erase(&state->rb_node, &tree->state);
680 			RB_CLEAR_NODE(&state->rb_node);
681 			free_extent_state(state);
682 		} else {
683 			WARN_ON(1);
684 		}
685 	} else {
686 		merge_state(tree, state);
687 		next = next_state(state);
688 	}
689 	return next;
690 }
691 
692 static struct extent_state *
alloc_extent_state_atomic(struct extent_state * prealloc)693 alloc_extent_state_atomic(struct extent_state *prealloc)
694 {
695 	if (!prealloc)
696 		prealloc = alloc_extent_state(GFP_ATOMIC);
697 
698 	return prealloc;
699 }
700 
extent_io_tree_panic(struct extent_io_tree * tree,int err)701 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
702 {
703 	btrfs_panic(tree->fs_info, err,
704 	"locking error: extent tree was modified by another thread while locked");
705 }
706 
707 /*
708  * clear some bits on a range in the tree.  This may require splitting
709  * or inserting elements in the tree, so the gfp mask is used to
710  * indicate which allocations or sleeping are allowed.
711  *
712  * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
713  * the given range from the tree regardless of state (ie for truncate).
714  *
715  * the range [start, end] is inclusive.
716  *
717  * This takes the tree lock, and returns 0 on success and < 0 on error.
718  */
__clear_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,int wake,int delete,struct extent_state ** cached_state,gfp_t mask,struct extent_changeset * changeset)719 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
720 		       u32 bits, int wake, int delete,
721 		       struct extent_state **cached_state,
722 		       gfp_t mask, struct extent_changeset *changeset)
723 {
724 	struct extent_state *state;
725 	struct extent_state *cached;
726 	struct extent_state *prealloc = NULL;
727 	struct rb_node *node;
728 	u64 last_end;
729 	int err;
730 	int clear = 0;
731 
732 	btrfs_debug_check_extent_io_range(tree, start, end);
733 	trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
734 
735 	if (bits & EXTENT_DELALLOC)
736 		bits |= EXTENT_NORESERVE;
737 
738 	if (delete)
739 		bits |= ~EXTENT_CTLBITS;
740 
741 	if (bits & (EXTENT_LOCKED | EXTENT_BOUNDARY))
742 		clear = 1;
743 again:
744 	if (!prealloc && gfpflags_allow_blocking(mask)) {
745 		/*
746 		 * Don't care for allocation failure here because we might end
747 		 * up not needing the pre-allocated extent state at all, which
748 		 * is the case if we only have in the tree extent states that
749 		 * cover our input range and don't cover too any other range.
750 		 * If we end up needing a new extent state we allocate it later.
751 		 */
752 		prealloc = alloc_extent_state(mask);
753 	}
754 
755 	spin_lock(&tree->lock);
756 	if (cached_state) {
757 		cached = *cached_state;
758 
759 		if (clear) {
760 			*cached_state = NULL;
761 			cached_state = NULL;
762 		}
763 
764 		if (cached && extent_state_in_tree(cached) &&
765 		    cached->start <= start && cached->end > start) {
766 			if (clear)
767 				refcount_dec(&cached->refs);
768 			state = cached;
769 			goto hit_next;
770 		}
771 		if (clear)
772 			free_extent_state(cached);
773 	}
774 	/*
775 	 * this search will find the extents that end after
776 	 * our range starts
777 	 */
778 	node = tree_search(tree, start);
779 	if (!node)
780 		goto out;
781 	state = rb_entry(node, struct extent_state, rb_node);
782 hit_next:
783 	if (state->start > end)
784 		goto out;
785 	WARN_ON(state->end < start);
786 	last_end = state->end;
787 
788 	/* the state doesn't have the wanted bits, go ahead */
789 	if (!(state->state & bits)) {
790 		state = next_state(state);
791 		goto next;
792 	}
793 
794 	/*
795 	 *     | ---- desired range ---- |
796 	 *  | state | or
797 	 *  | ------------- state -------------- |
798 	 *
799 	 * We need to split the extent we found, and may flip
800 	 * bits on second half.
801 	 *
802 	 * If the extent we found extends past our range, we
803 	 * just split and search again.  It'll get split again
804 	 * the next time though.
805 	 *
806 	 * If the extent we found is inside our range, we clear
807 	 * the desired bit on it.
808 	 */
809 
810 	if (state->start < start) {
811 		prealloc = alloc_extent_state_atomic(prealloc);
812 		BUG_ON(!prealloc);
813 		err = split_state(tree, state, prealloc, start);
814 		if (err)
815 			extent_io_tree_panic(tree, err);
816 
817 		prealloc = NULL;
818 		if (err)
819 			goto out;
820 		if (state->end <= end) {
821 			state = clear_state_bit(tree, state, &bits, wake,
822 						changeset);
823 			goto next;
824 		}
825 		goto search_again;
826 	}
827 	/*
828 	 * | ---- desired range ---- |
829 	 *                        | state |
830 	 * We need to split the extent, and clear the bit
831 	 * on the first half
832 	 */
833 	if (state->start <= end && state->end > end) {
834 		prealloc = alloc_extent_state_atomic(prealloc);
835 		BUG_ON(!prealloc);
836 		err = split_state(tree, state, prealloc, end + 1);
837 		if (err)
838 			extent_io_tree_panic(tree, err);
839 
840 		if (wake)
841 			wake_up(&state->wq);
842 
843 		clear_state_bit(tree, prealloc, &bits, wake, changeset);
844 
845 		prealloc = NULL;
846 		goto out;
847 	}
848 
849 	state = clear_state_bit(tree, state, &bits, wake, changeset);
850 next:
851 	if (last_end == (u64)-1)
852 		goto out;
853 	start = last_end + 1;
854 	if (start <= end && state && !need_resched())
855 		goto hit_next;
856 
857 search_again:
858 	if (start > end)
859 		goto out;
860 	spin_unlock(&tree->lock);
861 	if (gfpflags_allow_blocking(mask))
862 		cond_resched();
863 	goto again;
864 
865 out:
866 	spin_unlock(&tree->lock);
867 	if (prealloc)
868 		free_extent_state(prealloc);
869 
870 	return 0;
871 
872 }
873 
wait_on_state(struct extent_io_tree * tree,struct extent_state * state)874 static void wait_on_state(struct extent_io_tree *tree,
875 			  struct extent_state *state)
876 		__releases(tree->lock)
877 		__acquires(tree->lock)
878 {
879 	DEFINE_WAIT(wait);
880 	prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
881 	spin_unlock(&tree->lock);
882 	schedule();
883 	spin_lock(&tree->lock);
884 	finish_wait(&state->wq, &wait);
885 }
886 
887 /*
888  * waits for one or more bits to clear on a range in the state tree.
889  * The range [start, end] is inclusive.
890  * The tree lock is taken by this function
891  */
wait_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,u32 bits)892 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
893 			    u32 bits)
894 {
895 	struct extent_state *state;
896 	struct rb_node *node;
897 
898 	btrfs_debug_check_extent_io_range(tree, start, end);
899 
900 	spin_lock(&tree->lock);
901 again:
902 	while (1) {
903 		/*
904 		 * this search will find all the extents that end after
905 		 * our range starts
906 		 */
907 		node = tree_search(tree, start);
908 process_node:
909 		if (!node)
910 			break;
911 
912 		state = rb_entry(node, struct extent_state, rb_node);
913 
914 		if (state->start > end)
915 			goto out;
916 
917 		if (state->state & bits) {
918 			start = state->start;
919 			refcount_inc(&state->refs);
920 			wait_on_state(tree, state);
921 			free_extent_state(state);
922 			goto again;
923 		}
924 		start = state->end + 1;
925 
926 		if (start > end)
927 			break;
928 
929 		if (!cond_resched_lock(&tree->lock)) {
930 			node = rb_next(node);
931 			goto process_node;
932 		}
933 	}
934 out:
935 	spin_unlock(&tree->lock);
936 }
937 
set_state_bits(struct extent_io_tree * tree,struct extent_state * state,u32 * bits,struct extent_changeset * changeset)938 static void set_state_bits(struct extent_io_tree *tree,
939 			   struct extent_state *state,
940 			   u32 *bits, struct extent_changeset *changeset)
941 {
942 	u32 bits_to_set = *bits & ~EXTENT_CTLBITS;
943 	int ret;
944 
945 	if (tree->private_data && is_data_inode(tree->private_data))
946 		btrfs_set_delalloc_extent(tree->private_data, state, bits);
947 
948 	if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
949 		u64 range = state->end - state->start + 1;
950 		tree->dirty_bytes += range;
951 	}
952 	ret = add_extent_changeset(state, bits_to_set, changeset, 1);
953 	BUG_ON(ret < 0);
954 	state->state |= bits_to_set;
955 }
956 
cache_state_if_flags(struct extent_state * state,struct extent_state ** cached_ptr,unsigned flags)957 static void cache_state_if_flags(struct extent_state *state,
958 				 struct extent_state **cached_ptr,
959 				 unsigned flags)
960 {
961 	if (cached_ptr && !(*cached_ptr)) {
962 		if (!flags || (state->state & flags)) {
963 			*cached_ptr = state;
964 			refcount_inc(&state->refs);
965 		}
966 	}
967 }
968 
cache_state(struct extent_state * state,struct extent_state ** cached_ptr)969 static void cache_state(struct extent_state *state,
970 			struct extent_state **cached_ptr)
971 {
972 	return cache_state_if_flags(state, cached_ptr,
973 				    EXTENT_LOCKED | EXTENT_BOUNDARY);
974 }
975 
976 /*
977  * set some bits on a range in the tree.  This may require allocations or
978  * sleeping, so the gfp mask is used to indicate what is allowed.
979  *
980  * If any of the exclusive bits are set, this will fail with -EEXIST if some
981  * part of the range already has the desired bits set.  The start of the
982  * existing range is returned in failed_start in this case.
983  *
984  * [start, end] is inclusive This takes the tree lock.
985  */
set_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,u32 exclusive_bits,u64 * failed_start,struct extent_state ** cached_state,gfp_t mask,struct extent_changeset * changeset)986 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, u32 bits,
987 		   u32 exclusive_bits, u64 *failed_start,
988 		   struct extent_state **cached_state, gfp_t mask,
989 		   struct extent_changeset *changeset)
990 {
991 	struct extent_state *state;
992 	struct extent_state *prealloc = NULL;
993 	struct rb_node *node;
994 	struct rb_node **p;
995 	struct rb_node *parent;
996 	int err = 0;
997 	u64 last_start;
998 	u64 last_end;
999 
1000 	btrfs_debug_check_extent_io_range(tree, start, end);
1001 	trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
1002 
1003 	if (exclusive_bits)
1004 		ASSERT(failed_start);
1005 	else
1006 		ASSERT(failed_start == NULL);
1007 again:
1008 	if (!prealloc && gfpflags_allow_blocking(mask)) {
1009 		/*
1010 		 * Don't care for allocation failure here because we might end
1011 		 * up not needing the pre-allocated extent state at all, which
1012 		 * is the case if we only have in the tree extent states that
1013 		 * cover our input range and don't cover too any other range.
1014 		 * If we end up needing a new extent state we allocate it later.
1015 		 */
1016 		prealloc = alloc_extent_state(mask);
1017 	}
1018 
1019 	spin_lock(&tree->lock);
1020 	if (cached_state && *cached_state) {
1021 		state = *cached_state;
1022 		if (state->start <= start && state->end > start &&
1023 		    extent_state_in_tree(state)) {
1024 			node = &state->rb_node;
1025 			goto hit_next;
1026 		}
1027 	}
1028 	/*
1029 	 * this search will find all the extents that end after
1030 	 * our range starts.
1031 	 */
1032 	node = tree_search_for_insert(tree, start, &p, &parent);
1033 	if (!node) {
1034 		prealloc = alloc_extent_state_atomic(prealloc);
1035 		BUG_ON(!prealloc);
1036 		err = insert_state(tree, prealloc, start, end,
1037 				   &p, &parent, &bits, changeset);
1038 		if (err)
1039 			extent_io_tree_panic(tree, err);
1040 
1041 		cache_state(prealloc, cached_state);
1042 		prealloc = NULL;
1043 		goto out;
1044 	}
1045 	state = rb_entry(node, struct extent_state, rb_node);
1046 hit_next:
1047 	last_start = state->start;
1048 	last_end = state->end;
1049 
1050 	/*
1051 	 * | ---- desired range ---- |
1052 	 * | state |
1053 	 *
1054 	 * Just lock what we found and keep going
1055 	 */
1056 	if (state->start == start && state->end <= end) {
1057 		if (state->state & exclusive_bits) {
1058 			*failed_start = state->start;
1059 			err = -EEXIST;
1060 			goto out;
1061 		}
1062 
1063 		set_state_bits(tree, state, &bits, changeset);
1064 		cache_state(state, cached_state);
1065 		merge_state(tree, state);
1066 		if (last_end == (u64)-1)
1067 			goto out;
1068 		start = last_end + 1;
1069 		state = next_state(state);
1070 		if (start < end && state && state->start == start &&
1071 		    !need_resched())
1072 			goto hit_next;
1073 		goto search_again;
1074 	}
1075 
1076 	/*
1077 	 *     | ---- desired range ---- |
1078 	 * | state |
1079 	 *   or
1080 	 * | ------------- state -------------- |
1081 	 *
1082 	 * We need to split the extent we found, and may flip bits on
1083 	 * second half.
1084 	 *
1085 	 * If the extent we found extends past our
1086 	 * range, we just split and search again.  It'll get split
1087 	 * again the next time though.
1088 	 *
1089 	 * If the extent we found is inside our range, we set the
1090 	 * desired bit on it.
1091 	 */
1092 	if (state->start < start) {
1093 		if (state->state & exclusive_bits) {
1094 			*failed_start = start;
1095 			err = -EEXIST;
1096 			goto out;
1097 		}
1098 
1099 		/*
1100 		 * If this extent already has all the bits we want set, then
1101 		 * skip it, not necessary to split it or do anything with it.
1102 		 */
1103 		if ((state->state & bits) == bits) {
1104 			start = state->end + 1;
1105 			cache_state(state, cached_state);
1106 			goto search_again;
1107 		}
1108 
1109 		prealloc = alloc_extent_state_atomic(prealloc);
1110 		BUG_ON(!prealloc);
1111 		err = split_state(tree, state, prealloc, start);
1112 		if (err)
1113 			extent_io_tree_panic(tree, err);
1114 
1115 		prealloc = NULL;
1116 		if (err)
1117 			goto out;
1118 		if (state->end <= end) {
1119 			set_state_bits(tree, state, &bits, changeset);
1120 			cache_state(state, cached_state);
1121 			merge_state(tree, state);
1122 			if (last_end == (u64)-1)
1123 				goto out;
1124 			start = last_end + 1;
1125 			state = next_state(state);
1126 			if (start < end && state && state->start == start &&
1127 			    !need_resched())
1128 				goto hit_next;
1129 		}
1130 		goto search_again;
1131 	}
1132 	/*
1133 	 * | ---- desired range ---- |
1134 	 *     | state | or               | state |
1135 	 *
1136 	 * There's a hole, we need to insert something in it and
1137 	 * ignore the extent we found.
1138 	 */
1139 	if (state->start > start) {
1140 		u64 this_end;
1141 		if (end < last_start)
1142 			this_end = end;
1143 		else
1144 			this_end = last_start - 1;
1145 
1146 		prealloc = alloc_extent_state_atomic(prealloc);
1147 		BUG_ON(!prealloc);
1148 
1149 		/*
1150 		 * Avoid to free 'prealloc' if it can be merged with
1151 		 * the later extent.
1152 		 */
1153 		err = insert_state(tree, prealloc, start, this_end,
1154 				   NULL, NULL, &bits, changeset);
1155 		if (err)
1156 			extent_io_tree_panic(tree, err);
1157 
1158 		cache_state(prealloc, cached_state);
1159 		prealloc = NULL;
1160 		start = this_end + 1;
1161 		goto search_again;
1162 	}
1163 	/*
1164 	 * | ---- desired range ---- |
1165 	 *                        | state |
1166 	 * We need to split the extent, and set the bit
1167 	 * on the first half
1168 	 */
1169 	if (state->start <= end && state->end > end) {
1170 		if (state->state & exclusive_bits) {
1171 			*failed_start = start;
1172 			err = -EEXIST;
1173 			goto out;
1174 		}
1175 
1176 		prealloc = alloc_extent_state_atomic(prealloc);
1177 		BUG_ON(!prealloc);
1178 		err = split_state(tree, state, prealloc, end + 1);
1179 		if (err)
1180 			extent_io_tree_panic(tree, err);
1181 
1182 		set_state_bits(tree, prealloc, &bits, changeset);
1183 		cache_state(prealloc, cached_state);
1184 		merge_state(tree, prealloc);
1185 		prealloc = NULL;
1186 		goto out;
1187 	}
1188 
1189 search_again:
1190 	if (start > end)
1191 		goto out;
1192 	spin_unlock(&tree->lock);
1193 	if (gfpflags_allow_blocking(mask))
1194 		cond_resched();
1195 	goto again;
1196 
1197 out:
1198 	spin_unlock(&tree->lock);
1199 	if (prealloc)
1200 		free_extent_state(prealloc);
1201 
1202 	return err;
1203 
1204 }
1205 
1206 /**
1207  * convert_extent_bit - convert all bits in a given range from one bit to
1208  * 			another
1209  * @tree:	the io tree to search
1210  * @start:	the start offset in bytes
1211  * @end:	the end offset in bytes (inclusive)
1212  * @bits:	the bits to set in this range
1213  * @clear_bits:	the bits to clear in this range
1214  * @cached_state:	state that we're going to cache
1215  *
1216  * This will go through and set bits for the given range.  If any states exist
1217  * already in this range they are set with the given bit and cleared of the
1218  * clear_bits.  This is only meant to be used by things that are mergeable, ie
1219  * converting from say DELALLOC to DIRTY.  This is not meant to be used with
1220  * boundary bits like LOCK.
1221  *
1222  * All allocations are done with GFP_NOFS.
1223  */
convert_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,u32 clear_bits,struct extent_state ** cached_state)1224 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1225 		       u32 bits, u32 clear_bits,
1226 		       struct extent_state **cached_state)
1227 {
1228 	struct extent_state *state;
1229 	struct extent_state *prealloc = NULL;
1230 	struct rb_node *node;
1231 	struct rb_node **p;
1232 	struct rb_node *parent;
1233 	int err = 0;
1234 	u64 last_start;
1235 	u64 last_end;
1236 	bool first_iteration = true;
1237 
1238 	btrfs_debug_check_extent_io_range(tree, start, end);
1239 	trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1240 				       clear_bits);
1241 
1242 again:
1243 	if (!prealloc) {
1244 		/*
1245 		 * Best effort, don't worry if extent state allocation fails
1246 		 * here for the first iteration. We might have a cached state
1247 		 * that matches exactly the target range, in which case no
1248 		 * extent state allocations are needed. We'll only know this
1249 		 * after locking the tree.
1250 		 */
1251 		prealloc = alloc_extent_state(GFP_NOFS);
1252 		if (!prealloc && !first_iteration)
1253 			return -ENOMEM;
1254 	}
1255 
1256 	spin_lock(&tree->lock);
1257 	if (cached_state && *cached_state) {
1258 		state = *cached_state;
1259 		if (state->start <= start && state->end > start &&
1260 		    extent_state_in_tree(state)) {
1261 			node = &state->rb_node;
1262 			goto hit_next;
1263 		}
1264 	}
1265 
1266 	/*
1267 	 * this search will find all the extents that end after
1268 	 * our range starts.
1269 	 */
1270 	node = tree_search_for_insert(tree, start, &p, &parent);
1271 	if (!node) {
1272 		prealloc = alloc_extent_state_atomic(prealloc);
1273 		if (!prealloc) {
1274 			err = -ENOMEM;
1275 			goto out;
1276 		}
1277 		err = insert_state(tree, prealloc, start, end,
1278 				   &p, &parent, &bits, NULL);
1279 		if (err)
1280 			extent_io_tree_panic(tree, err);
1281 		cache_state(prealloc, cached_state);
1282 		prealloc = NULL;
1283 		goto out;
1284 	}
1285 	state = rb_entry(node, struct extent_state, rb_node);
1286 hit_next:
1287 	last_start = state->start;
1288 	last_end = state->end;
1289 
1290 	/*
1291 	 * | ---- desired range ---- |
1292 	 * | state |
1293 	 *
1294 	 * Just lock what we found and keep going
1295 	 */
1296 	if (state->start == start && state->end <= end) {
1297 		set_state_bits(tree, state, &bits, NULL);
1298 		cache_state(state, cached_state);
1299 		state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1300 		if (last_end == (u64)-1)
1301 			goto out;
1302 		start = last_end + 1;
1303 		if (start < end && state && state->start == start &&
1304 		    !need_resched())
1305 			goto hit_next;
1306 		goto search_again;
1307 	}
1308 
1309 	/*
1310 	 *     | ---- desired range ---- |
1311 	 * | state |
1312 	 *   or
1313 	 * | ------------- state -------------- |
1314 	 *
1315 	 * We need to split the extent we found, and may flip bits on
1316 	 * second half.
1317 	 *
1318 	 * If the extent we found extends past our
1319 	 * range, we just split and search again.  It'll get split
1320 	 * again the next time though.
1321 	 *
1322 	 * If the extent we found is inside our range, we set the
1323 	 * desired bit on it.
1324 	 */
1325 	if (state->start < start) {
1326 		prealloc = alloc_extent_state_atomic(prealloc);
1327 		if (!prealloc) {
1328 			err = -ENOMEM;
1329 			goto out;
1330 		}
1331 		err = split_state(tree, state, prealloc, start);
1332 		if (err)
1333 			extent_io_tree_panic(tree, err);
1334 		prealloc = NULL;
1335 		if (err)
1336 			goto out;
1337 		if (state->end <= end) {
1338 			set_state_bits(tree, state, &bits, NULL);
1339 			cache_state(state, cached_state);
1340 			state = clear_state_bit(tree, state, &clear_bits, 0,
1341 						NULL);
1342 			if (last_end == (u64)-1)
1343 				goto out;
1344 			start = last_end + 1;
1345 			if (start < end && state && state->start == start &&
1346 			    !need_resched())
1347 				goto hit_next;
1348 		}
1349 		goto search_again;
1350 	}
1351 	/*
1352 	 * | ---- desired range ---- |
1353 	 *     | state | or               | state |
1354 	 *
1355 	 * There's a hole, we need to insert something in it and
1356 	 * ignore the extent we found.
1357 	 */
1358 	if (state->start > start) {
1359 		u64 this_end;
1360 		if (end < last_start)
1361 			this_end = end;
1362 		else
1363 			this_end = last_start - 1;
1364 
1365 		prealloc = alloc_extent_state_atomic(prealloc);
1366 		if (!prealloc) {
1367 			err = -ENOMEM;
1368 			goto out;
1369 		}
1370 
1371 		/*
1372 		 * Avoid to free 'prealloc' if it can be merged with
1373 		 * the later extent.
1374 		 */
1375 		err = insert_state(tree, prealloc, start, this_end,
1376 				   NULL, NULL, &bits, NULL);
1377 		if (err)
1378 			extent_io_tree_panic(tree, err);
1379 		cache_state(prealloc, cached_state);
1380 		prealloc = NULL;
1381 		start = this_end + 1;
1382 		goto search_again;
1383 	}
1384 	/*
1385 	 * | ---- desired range ---- |
1386 	 *                        | state |
1387 	 * We need to split the extent, and set the bit
1388 	 * on the first half
1389 	 */
1390 	if (state->start <= end && state->end > end) {
1391 		prealloc = alloc_extent_state_atomic(prealloc);
1392 		if (!prealloc) {
1393 			err = -ENOMEM;
1394 			goto out;
1395 		}
1396 
1397 		err = split_state(tree, state, prealloc, end + 1);
1398 		if (err)
1399 			extent_io_tree_panic(tree, err);
1400 
1401 		set_state_bits(tree, prealloc, &bits, NULL);
1402 		cache_state(prealloc, cached_state);
1403 		clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1404 		prealloc = NULL;
1405 		goto out;
1406 	}
1407 
1408 search_again:
1409 	if (start > end)
1410 		goto out;
1411 	spin_unlock(&tree->lock);
1412 	cond_resched();
1413 	first_iteration = false;
1414 	goto again;
1415 
1416 out:
1417 	spin_unlock(&tree->lock);
1418 	if (prealloc)
1419 		free_extent_state(prealloc);
1420 
1421 	return err;
1422 }
1423 
1424 /* wrappers around set/clear extent bit */
set_record_extent_bits(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,struct extent_changeset * changeset)1425 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1426 			   u32 bits, struct extent_changeset *changeset)
1427 {
1428 	/*
1429 	 * We don't support EXTENT_LOCKED yet, as current changeset will
1430 	 * record any bits changed, so for EXTENT_LOCKED case, it will
1431 	 * either fail with -EEXIST or changeset will record the whole
1432 	 * range.
1433 	 */
1434 	BUG_ON(bits & EXTENT_LOCKED);
1435 
1436 	return set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1437 			      changeset);
1438 }
1439 
set_extent_bits_nowait(struct extent_io_tree * tree,u64 start,u64 end,u32 bits)1440 int set_extent_bits_nowait(struct extent_io_tree *tree, u64 start, u64 end,
1441 			   u32 bits)
1442 {
1443 	return set_extent_bit(tree, start, end, bits, 0, NULL, NULL,
1444 			      GFP_NOWAIT, NULL);
1445 }
1446 
clear_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,int wake,int delete,struct extent_state ** cached)1447 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1448 		     u32 bits, int wake, int delete,
1449 		     struct extent_state **cached)
1450 {
1451 	return __clear_extent_bit(tree, start, end, bits, wake, delete,
1452 				  cached, GFP_NOFS, NULL);
1453 }
1454 
clear_record_extent_bits(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,struct extent_changeset * changeset)1455 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1456 		u32 bits, struct extent_changeset *changeset)
1457 {
1458 	/*
1459 	 * Don't support EXTENT_LOCKED case, same reason as
1460 	 * set_record_extent_bits().
1461 	 */
1462 	BUG_ON(bits & EXTENT_LOCKED);
1463 
1464 	return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1465 				  changeset);
1466 }
1467 
1468 /*
1469  * either insert or lock state struct between start and end use mask to tell
1470  * us if waiting is desired.
1471  */
lock_extent_bits(struct extent_io_tree * tree,u64 start,u64 end,struct extent_state ** cached_state)1472 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1473 		     struct extent_state **cached_state)
1474 {
1475 	int err;
1476 	u64 failed_start;
1477 
1478 	while (1) {
1479 		err = set_extent_bit(tree, start, end, EXTENT_LOCKED,
1480 				     EXTENT_LOCKED, &failed_start,
1481 				     cached_state, GFP_NOFS, NULL);
1482 		if (err == -EEXIST) {
1483 			wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1484 			start = failed_start;
1485 		} else
1486 			break;
1487 		WARN_ON(start > end);
1488 	}
1489 	return err;
1490 }
1491 
try_lock_extent(struct extent_io_tree * tree,u64 start,u64 end)1492 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1493 {
1494 	int err;
1495 	u64 failed_start;
1496 
1497 	err = set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1498 			     &failed_start, NULL, GFP_NOFS, NULL);
1499 	if (err == -EEXIST) {
1500 		if (failed_start > start)
1501 			clear_extent_bit(tree, start, failed_start - 1,
1502 					 EXTENT_LOCKED, 1, 0, NULL);
1503 		return 0;
1504 	}
1505 	return 1;
1506 }
1507 
extent_range_clear_dirty_for_io(struct inode * inode,u64 start,u64 end)1508 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1509 {
1510 	unsigned long index = start >> PAGE_SHIFT;
1511 	unsigned long end_index = end >> PAGE_SHIFT;
1512 	struct page *page;
1513 
1514 	while (index <= end_index) {
1515 		page = find_get_page(inode->i_mapping, index);
1516 		BUG_ON(!page); /* Pages should be in the extent_io_tree */
1517 		clear_page_dirty_for_io(page);
1518 		put_page(page);
1519 		index++;
1520 	}
1521 }
1522 
extent_range_redirty_for_io(struct inode * inode,u64 start,u64 end)1523 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1524 {
1525 	struct address_space *mapping = inode->i_mapping;
1526 	unsigned long index = start >> PAGE_SHIFT;
1527 	unsigned long end_index = end >> PAGE_SHIFT;
1528 	struct folio *folio;
1529 
1530 	while (index <= end_index) {
1531 		folio = filemap_get_folio(mapping, index);
1532 		filemap_dirty_folio(mapping, folio);
1533 		folio_account_redirty(folio);
1534 		index += folio_nr_pages(folio);
1535 		folio_put(folio);
1536 	}
1537 }
1538 
1539 /* find the first state struct with 'bits' set after 'start', and
1540  * return it.  tree->lock must be held.  NULL will returned if
1541  * nothing was found after 'start'
1542  */
1543 static struct extent_state *
find_first_extent_bit_state(struct extent_io_tree * tree,u64 start,u32 bits)1544 find_first_extent_bit_state(struct extent_io_tree *tree, u64 start, u32 bits)
1545 {
1546 	struct rb_node *node;
1547 	struct extent_state *state;
1548 
1549 	/*
1550 	 * this search will find all the extents that end after
1551 	 * our range starts.
1552 	 */
1553 	node = tree_search(tree, start);
1554 	if (!node)
1555 		goto out;
1556 
1557 	while (1) {
1558 		state = rb_entry(node, struct extent_state, rb_node);
1559 		if (state->end >= start && (state->state & bits))
1560 			return state;
1561 
1562 		node = rb_next(node);
1563 		if (!node)
1564 			break;
1565 	}
1566 out:
1567 	return NULL;
1568 }
1569 
1570 /*
1571  * Find the first offset in the io tree with one or more @bits set.
1572  *
1573  * Note: If there are multiple bits set in @bits, any of them will match.
1574  *
1575  * Return 0 if we find something, and update @start_ret and @end_ret.
1576  * Return 1 if we found nothing.
1577  */
find_first_extent_bit(struct extent_io_tree * tree,u64 start,u64 * start_ret,u64 * end_ret,u32 bits,struct extent_state ** cached_state)1578 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1579 			  u64 *start_ret, u64 *end_ret, u32 bits,
1580 			  struct extent_state **cached_state)
1581 {
1582 	struct extent_state *state;
1583 	int ret = 1;
1584 
1585 	spin_lock(&tree->lock);
1586 	if (cached_state && *cached_state) {
1587 		state = *cached_state;
1588 		if (state->end == start - 1 && extent_state_in_tree(state)) {
1589 			while ((state = next_state(state)) != NULL) {
1590 				if (state->state & bits)
1591 					goto got_it;
1592 			}
1593 			free_extent_state(*cached_state);
1594 			*cached_state = NULL;
1595 			goto out;
1596 		}
1597 		free_extent_state(*cached_state);
1598 		*cached_state = NULL;
1599 	}
1600 
1601 	state = find_first_extent_bit_state(tree, start, bits);
1602 got_it:
1603 	if (state) {
1604 		cache_state_if_flags(state, cached_state, 0);
1605 		*start_ret = state->start;
1606 		*end_ret = state->end;
1607 		ret = 0;
1608 	}
1609 out:
1610 	spin_unlock(&tree->lock);
1611 	return ret;
1612 }
1613 
1614 /**
1615  * Find a contiguous area of bits
1616  *
1617  * @tree:      io tree to check
1618  * @start:     offset to start the search from
1619  * @start_ret: the first offset we found with the bits set
1620  * @end_ret:   the final contiguous range of the bits that were set
1621  * @bits:      bits to look for
1622  *
1623  * set_extent_bit and clear_extent_bit can temporarily split contiguous ranges
1624  * to set bits appropriately, and then merge them again.  During this time it
1625  * will drop the tree->lock, so use this helper if you want to find the actual
1626  * contiguous area for given bits.  We will search to the first bit we find, and
1627  * then walk down the tree until we find a non-contiguous area.  The area
1628  * returned will be the full contiguous area with the bits set.
1629  */
find_contiguous_extent_bit(struct extent_io_tree * tree,u64 start,u64 * start_ret,u64 * end_ret,u32 bits)1630 int find_contiguous_extent_bit(struct extent_io_tree *tree, u64 start,
1631 			       u64 *start_ret, u64 *end_ret, u32 bits)
1632 {
1633 	struct extent_state *state;
1634 	int ret = 1;
1635 
1636 	spin_lock(&tree->lock);
1637 	state = find_first_extent_bit_state(tree, start, bits);
1638 	if (state) {
1639 		*start_ret = state->start;
1640 		*end_ret = state->end;
1641 		while ((state = next_state(state)) != NULL) {
1642 			if (state->start > (*end_ret + 1))
1643 				break;
1644 			*end_ret = state->end;
1645 		}
1646 		ret = 0;
1647 	}
1648 	spin_unlock(&tree->lock);
1649 	return ret;
1650 }
1651 
1652 /**
1653  * Find the first range that has @bits not set. This range could start before
1654  * @start.
1655  *
1656  * @tree:      the tree to search
1657  * @start:     offset at/after which the found extent should start
1658  * @start_ret: records the beginning of the range
1659  * @end_ret:   records the end of the range (inclusive)
1660  * @bits:      the set of bits which must be unset
1661  *
1662  * Since unallocated range is also considered one which doesn't have the bits
1663  * set it's possible that @end_ret contains -1, this happens in case the range
1664  * spans (last_range_end, end of device]. In this case it's up to the caller to
1665  * trim @end_ret to the appropriate size.
1666  */
find_first_clear_extent_bit(struct extent_io_tree * tree,u64 start,u64 * start_ret,u64 * end_ret,u32 bits)1667 void find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1668 				 u64 *start_ret, u64 *end_ret, u32 bits)
1669 {
1670 	struct extent_state *state;
1671 	struct rb_node *node, *prev = NULL, *next;
1672 
1673 	spin_lock(&tree->lock);
1674 
1675 	/* Find first extent with bits cleared */
1676 	while (1) {
1677 		node = __etree_search(tree, start, &next, &prev, NULL, NULL);
1678 		if (!node && !next && !prev) {
1679 			/*
1680 			 * Tree is completely empty, send full range and let
1681 			 * caller deal with it
1682 			 */
1683 			*start_ret = 0;
1684 			*end_ret = -1;
1685 			goto out;
1686 		} else if (!node && !next) {
1687 			/*
1688 			 * We are past the last allocated chunk, set start at
1689 			 * the end of the last extent.
1690 			 */
1691 			state = rb_entry(prev, struct extent_state, rb_node);
1692 			*start_ret = state->end + 1;
1693 			*end_ret = -1;
1694 			goto out;
1695 		} else if (!node) {
1696 			node = next;
1697 		}
1698 		/*
1699 		 * At this point 'node' either contains 'start' or start is
1700 		 * before 'node'
1701 		 */
1702 		state = rb_entry(node, struct extent_state, rb_node);
1703 
1704 		if (in_range(start, state->start, state->end - state->start + 1)) {
1705 			if (state->state & bits) {
1706 				/*
1707 				 * |--range with bits sets--|
1708 				 *    |
1709 				 *    start
1710 				 */
1711 				start = state->end + 1;
1712 			} else {
1713 				/*
1714 				 * 'start' falls within a range that doesn't
1715 				 * have the bits set, so take its start as
1716 				 * the beginning of the desired range
1717 				 *
1718 				 * |--range with bits cleared----|
1719 				 *      |
1720 				 *      start
1721 				 */
1722 				*start_ret = state->start;
1723 				break;
1724 			}
1725 		} else {
1726 			/*
1727 			 * |---prev range---|---hole/unset---|---node range---|
1728 			 *                          |
1729 			 *                        start
1730 			 *
1731 			 *                        or
1732 			 *
1733 			 * |---hole/unset--||--first node--|
1734 			 * 0   |
1735 			 *    start
1736 			 */
1737 			if (prev) {
1738 				state = rb_entry(prev, struct extent_state,
1739 						 rb_node);
1740 				*start_ret = state->end + 1;
1741 			} else {
1742 				*start_ret = 0;
1743 			}
1744 			break;
1745 		}
1746 	}
1747 
1748 	/*
1749 	 * Find the longest stretch from start until an entry which has the
1750 	 * bits set
1751 	 */
1752 	while (1) {
1753 		state = rb_entry(node, struct extent_state, rb_node);
1754 		if (state->end >= start && !(state->state & bits)) {
1755 			*end_ret = state->end;
1756 		} else {
1757 			*end_ret = state->start - 1;
1758 			break;
1759 		}
1760 
1761 		node = rb_next(node);
1762 		if (!node)
1763 			break;
1764 	}
1765 out:
1766 	spin_unlock(&tree->lock);
1767 }
1768 
1769 /*
1770  * find a contiguous range of bytes in the file marked as delalloc, not
1771  * more than 'max_bytes'.  start and end are used to return the range,
1772  *
1773  * true is returned if we find something, false if nothing was in the tree
1774  */
btrfs_find_delalloc_range(struct extent_io_tree * tree,u64 * start,u64 * end,u64 max_bytes,struct extent_state ** cached_state)1775 bool btrfs_find_delalloc_range(struct extent_io_tree *tree, u64 *start,
1776 			       u64 *end, u64 max_bytes,
1777 			       struct extent_state **cached_state)
1778 {
1779 	struct rb_node *node;
1780 	struct extent_state *state;
1781 	u64 cur_start = *start;
1782 	bool found = false;
1783 	u64 total_bytes = 0;
1784 
1785 	spin_lock(&tree->lock);
1786 
1787 	/*
1788 	 * this search will find all the extents that end after
1789 	 * our range starts.
1790 	 */
1791 	node = tree_search(tree, cur_start);
1792 	if (!node) {
1793 		*end = (u64)-1;
1794 		goto out;
1795 	}
1796 
1797 	while (1) {
1798 		state = rb_entry(node, struct extent_state, rb_node);
1799 		if (found && (state->start != cur_start ||
1800 			      (state->state & EXTENT_BOUNDARY))) {
1801 			goto out;
1802 		}
1803 		if (!(state->state & EXTENT_DELALLOC)) {
1804 			if (!found)
1805 				*end = state->end;
1806 			goto out;
1807 		}
1808 		if (!found) {
1809 			*start = state->start;
1810 			*cached_state = state;
1811 			refcount_inc(&state->refs);
1812 		}
1813 		found = true;
1814 		*end = state->end;
1815 		cur_start = state->end + 1;
1816 		node = rb_next(node);
1817 		total_bytes += state->end - state->start + 1;
1818 		if (total_bytes >= max_bytes)
1819 			break;
1820 		if (!node)
1821 			break;
1822 	}
1823 out:
1824 	spin_unlock(&tree->lock);
1825 	return found;
1826 }
1827 
1828 /*
1829  * Process one page for __process_pages_contig().
1830  *
1831  * Return >0 if we hit @page == @locked_page.
1832  * Return 0 if we updated the page status.
1833  * Return -EGAIN if the we need to try again.
1834  * (For PAGE_LOCK case but got dirty page or page not belong to mapping)
1835  */
process_one_page(struct btrfs_fs_info * fs_info,struct address_space * mapping,struct page * page,struct page * locked_page,unsigned long page_ops,u64 start,u64 end)1836 static int process_one_page(struct btrfs_fs_info *fs_info,
1837 			    struct address_space *mapping,
1838 			    struct page *page, struct page *locked_page,
1839 			    unsigned long page_ops, u64 start, u64 end)
1840 {
1841 	u32 len;
1842 
1843 	ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
1844 	len = end + 1 - start;
1845 
1846 	if (page_ops & PAGE_SET_ORDERED)
1847 		btrfs_page_clamp_set_ordered(fs_info, page, start, len);
1848 	if (page_ops & PAGE_SET_ERROR)
1849 		btrfs_page_clamp_set_error(fs_info, page, start, len);
1850 	if (page_ops & PAGE_START_WRITEBACK) {
1851 		btrfs_page_clamp_clear_dirty(fs_info, page, start, len);
1852 		btrfs_page_clamp_set_writeback(fs_info, page, start, len);
1853 	}
1854 	if (page_ops & PAGE_END_WRITEBACK)
1855 		btrfs_page_clamp_clear_writeback(fs_info, page, start, len);
1856 
1857 	if (page == locked_page)
1858 		return 1;
1859 
1860 	if (page_ops & PAGE_LOCK) {
1861 		int ret;
1862 
1863 		ret = btrfs_page_start_writer_lock(fs_info, page, start, len);
1864 		if (ret)
1865 			return ret;
1866 		if (!PageDirty(page) || page->mapping != mapping) {
1867 			btrfs_page_end_writer_lock(fs_info, page, start, len);
1868 			return -EAGAIN;
1869 		}
1870 	}
1871 	if (page_ops & PAGE_UNLOCK)
1872 		btrfs_page_end_writer_lock(fs_info, page, start, len);
1873 	return 0;
1874 }
1875 
__process_pages_contig(struct address_space * mapping,struct page * locked_page,u64 start,u64 end,unsigned long page_ops,u64 * processed_end)1876 static int __process_pages_contig(struct address_space *mapping,
1877 				  struct page *locked_page,
1878 				  u64 start, u64 end, unsigned long page_ops,
1879 				  u64 *processed_end)
1880 {
1881 	struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
1882 	pgoff_t start_index = start >> PAGE_SHIFT;
1883 	pgoff_t end_index = end >> PAGE_SHIFT;
1884 	pgoff_t index = start_index;
1885 	unsigned long nr_pages = end_index - start_index + 1;
1886 	unsigned long pages_processed = 0;
1887 	struct page *pages[16];
1888 	int err = 0;
1889 	int i;
1890 
1891 	if (page_ops & PAGE_LOCK) {
1892 		ASSERT(page_ops == PAGE_LOCK);
1893 		ASSERT(processed_end && *processed_end == start);
1894 	}
1895 
1896 	if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1897 		mapping_set_error(mapping, -EIO);
1898 
1899 	while (nr_pages > 0) {
1900 		int found_pages;
1901 
1902 		found_pages = find_get_pages_contig(mapping, index,
1903 				     min_t(unsigned long,
1904 				     nr_pages, ARRAY_SIZE(pages)), pages);
1905 		if (found_pages == 0) {
1906 			/*
1907 			 * Only if we're going to lock these pages, we can find
1908 			 * nothing at @index.
1909 			 */
1910 			ASSERT(page_ops & PAGE_LOCK);
1911 			err = -EAGAIN;
1912 			goto out;
1913 		}
1914 
1915 		for (i = 0; i < found_pages; i++) {
1916 			int process_ret;
1917 
1918 			process_ret = process_one_page(fs_info, mapping,
1919 					pages[i], locked_page, page_ops,
1920 					start, end);
1921 			if (process_ret < 0) {
1922 				for (; i < found_pages; i++)
1923 					put_page(pages[i]);
1924 				err = -EAGAIN;
1925 				goto out;
1926 			}
1927 			put_page(pages[i]);
1928 			pages_processed++;
1929 		}
1930 		nr_pages -= found_pages;
1931 		index += found_pages;
1932 		cond_resched();
1933 	}
1934 out:
1935 	if (err && processed_end) {
1936 		/*
1937 		 * Update @processed_end. I know this is awful since it has
1938 		 * two different return value patterns (inclusive vs exclusive).
1939 		 *
1940 		 * But the exclusive pattern is necessary if @start is 0, or we
1941 		 * underflow and check against processed_end won't work as
1942 		 * expected.
1943 		 */
1944 		if (pages_processed)
1945 			*processed_end = min(end,
1946 			((u64)(start_index + pages_processed) << PAGE_SHIFT) - 1);
1947 		else
1948 			*processed_end = start;
1949 	}
1950 	return err;
1951 }
1952 
__unlock_for_delalloc(struct inode * inode,struct page * locked_page,u64 start,u64 end)1953 static noinline void __unlock_for_delalloc(struct inode *inode,
1954 					   struct page *locked_page,
1955 					   u64 start, u64 end)
1956 {
1957 	unsigned long index = start >> PAGE_SHIFT;
1958 	unsigned long end_index = end >> PAGE_SHIFT;
1959 
1960 	ASSERT(locked_page);
1961 	if (index == locked_page->index && end_index == index)
1962 		return;
1963 
1964 	__process_pages_contig(inode->i_mapping, locked_page, start, end,
1965 			       PAGE_UNLOCK, NULL);
1966 }
1967 
lock_delalloc_pages(struct inode * inode,struct page * locked_page,u64 delalloc_start,u64 delalloc_end)1968 static noinline int lock_delalloc_pages(struct inode *inode,
1969 					struct page *locked_page,
1970 					u64 delalloc_start,
1971 					u64 delalloc_end)
1972 {
1973 	unsigned long index = delalloc_start >> PAGE_SHIFT;
1974 	unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1975 	u64 processed_end = delalloc_start;
1976 	int ret;
1977 
1978 	ASSERT(locked_page);
1979 	if (index == locked_page->index && index == end_index)
1980 		return 0;
1981 
1982 	ret = __process_pages_contig(inode->i_mapping, locked_page, delalloc_start,
1983 				     delalloc_end, PAGE_LOCK, &processed_end);
1984 	if (ret == -EAGAIN && processed_end > delalloc_start)
1985 		__unlock_for_delalloc(inode, locked_page, delalloc_start,
1986 				      processed_end);
1987 	return ret;
1988 }
1989 
1990 /*
1991  * Find and lock a contiguous range of bytes in the file marked as delalloc, no
1992  * more than @max_bytes.
1993  *
1994  * @start:	The original start bytenr to search.
1995  *		Will store the extent range start bytenr.
1996  * @end:	The original end bytenr of the search range
1997  *		Will store the extent range end bytenr.
1998  *
1999  * Return true if we find a delalloc range which starts inside the original
2000  * range, and @start/@end will store the delalloc range start/end.
2001  *
2002  * Return false if we can't find any delalloc range which starts inside the
2003  * original range, and @start/@end will be the non-delalloc range start/end.
2004  */
2005 EXPORT_FOR_TESTS
find_lock_delalloc_range(struct inode * inode,struct page * locked_page,u64 * start,u64 * end)2006 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
2007 				    struct page *locked_page, u64 *start,
2008 				    u64 *end)
2009 {
2010 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2011 	struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2012 	const u64 orig_start = *start;
2013 	const u64 orig_end = *end;
2014 	/* The sanity tests may not set a valid fs_info. */
2015 	u64 max_bytes = fs_info ? fs_info->max_extent_size : BTRFS_MAX_EXTENT_SIZE;
2016 	u64 delalloc_start;
2017 	u64 delalloc_end;
2018 	bool found;
2019 	struct extent_state *cached_state = NULL;
2020 	int ret;
2021 	int loops = 0;
2022 
2023 	/* Caller should pass a valid @end to indicate the search range end */
2024 	ASSERT(orig_end > orig_start);
2025 
2026 	/* The range should at least cover part of the page */
2027 	ASSERT(!(orig_start >= page_offset(locked_page) + PAGE_SIZE ||
2028 		 orig_end <= page_offset(locked_page)));
2029 again:
2030 	/* step one, find a bunch of delalloc bytes starting at start */
2031 	delalloc_start = *start;
2032 	delalloc_end = 0;
2033 	found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
2034 					  max_bytes, &cached_state);
2035 	if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
2036 		*start = delalloc_start;
2037 
2038 		/* @delalloc_end can be -1, never go beyond @orig_end */
2039 		*end = min(delalloc_end, orig_end);
2040 		free_extent_state(cached_state);
2041 		return false;
2042 	}
2043 
2044 	/*
2045 	 * start comes from the offset of locked_page.  We have to lock
2046 	 * pages in order, so we can't process delalloc bytes before
2047 	 * locked_page
2048 	 */
2049 	if (delalloc_start < *start)
2050 		delalloc_start = *start;
2051 
2052 	/*
2053 	 * make sure to limit the number of pages we try to lock down
2054 	 */
2055 	if (delalloc_end + 1 - delalloc_start > max_bytes)
2056 		delalloc_end = delalloc_start + max_bytes - 1;
2057 
2058 	/* step two, lock all the pages after the page that has start */
2059 	ret = lock_delalloc_pages(inode, locked_page,
2060 				  delalloc_start, delalloc_end);
2061 	ASSERT(!ret || ret == -EAGAIN);
2062 	if (ret == -EAGAIN) {
2063 		/* some of the pages are gone, lets avoid looping by
2064 		 * shortening the size of the delalloc range we're searching
2065 		 */
2066 		free_extent_state(cached_state);
2067 		cached_state = NULL;
2068 		if (!loops) {
2069 			max_bytes = PAGE_SIZE;
2070 			loops = 1;
2071 			goto again;
2072 		} else {
2073 			found = false;
2074 			goto out_failed;
2075 		}
2076 	}
2077 
2078 	/* step three, lock the state bits for the whole range */
2079 	lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
2080 
2081 	/* then test to make sure it is all still delalloc */
2082 	ret = test_range_bit(tree, delalloc_start, delalloc_end,
2083 			     EXTENT_DELALLOC, 1, cached_state);
2084 	if (!ret) {
2085 		unlock_extent_cached(tree, delalloc_start, delalloc_end,
2086 				     &cached_state);
2087 		__unlock_for_delalloc(inode, locked_page,
2088 			      delalloc_start, delalloc_end);
2089 		cond_resched();
2090 		goto again;
2091 	}
2092 	free_extent_state(cached_state);
2093 	*start = delalloc_start;
2094 	*end = delalloc_end;
2095 out_failed:
2096 	return found;
2097 }
2098 
extent_clear_unlock_delalloc(struct btrfs_inode * inode,u64 start,u64 end,struct page * locked_page,u32 clear_bits,unsigned long page_ops)2099 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2100 				  struct page *locked_page,
2101 				  u32 clear_bits, unsigned long page_ops)
2102 {
2103 	clear_extent_bit(&inode->io_tree, start, end, clear_bits, 1, 0, NULL);
2104 
2105 	__process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
2106 			       start, end, page_ops, NULL);
2107 }
2108 
2109 /*
2110  * count the number of bytes in the tree that have a given bit(s)
2111  * set.  This can be fairly slow, except for EXTENT_DIRTY which is
2112  * cached.  The total number found is returned.
2113  */
count_range_bits(struct extent_io_tree * tree,u64 * start,u64 search_end,u64 max_bytes,u32 bits,int contig)2114 u64 count_range_bits(struct extent_io_tree *tree,
2115 		     u64 *start, u64 search_end, u64 max_bytes,
2116 		     u32 bits, int contig)
2117 {
2118 	struct rb_node *node;
2119 	struct extent_state *state;
2120 	u64 cur_start = *start;
2121 	u64 total_bytes = 0;
2122 	u64 last = 0;
2123 	int found = 0;
2124 
2125 	if (WARN_ON(search_end <= cur_start))
2126 		return 0;
2127 
2128 	spin_lock(&tree->lock);
2129 	if (cur_start == 0 && bits == EXTENT_DIRTY) {
2130 		total_bytes = tree->dirty_bytes;
2131 		goto out;
2132 	}
2133 	/*
2134 	 * this search will find all the extents that end after
2135 	 * our range starts.
2136 	 */
2137 	node = tree_search(tree, cur_start);
2138 	if (!node)
2139 		goto out;
2140 
2141 	while (1) {
2142 		state = rb_entry(node, struct extent_state, rb_node);
2143 		if (state->start > search_end)
2144 			break;
2145 		if (contig && found && state->start > last + 1)
2146 			break;
2147 		if (state->end >= cur_start && (state->state & bits) == bits) {
2148 			total_bytes += min(search_end, state->end) + 1 -
2149 				       max(cur_start, state->start);
2150 			if (total_bytes >= max_bytes)
2151 				break;
2152 			if (!found) {
2153 				*start = max(cur_start, state->start);
2154 				found = 1;
2155 			}
2156 			last = state->end;
2157 		} else if (contig && found) {
2158 			break;
2159 		}
2160 		node = rb_next(node);
2161 		if (!node)
2162 			break;
2163 	}
2164 out:
2165 	spin_unlock(&tree->lock);
2166 	return total_bytes;
2167 }
2168 
2169 /*
2170  * set the private field for a given byte offset in the tree.  If there isn't
2171  * an extent_state there already, this does nothing.
2172  */
set_state_failrec(struct extent_io_tree * tree,u64 start,struct io_failure_record * failrec)2173 int set_state_failrec(struct extent_io_tree *tree, u64 start,
2174 		      struct io_failure_record *failrec)
2175 {
2176 	struct rb_node *node;
2177 	struct extent_state *state;
2178 	int ret = 0;
2179 
2180 	spin_lock(&tree->lock);
2181 	/*
2182 	 * this search will find all the extents that end after
2183 	 * our range starts.
2184 	 */
2185 	node = tree_search(tree, start);
2186 	if (!node) {
2187 		ret = -ENOENT;
2188 		goto out;
2189 	}
2190 	state = rb_entry(node, struct extent_state, rb_node);
2191 	if (state->start != start) {
2192 		ret = -ENOENT;
2193 		goto out;
2194 	}
2195 	state->failrec = failrec;
2196 out:
2197 	spin_unlock(&tree->lock);
2198 	return ret;
2199 }
2200 
get_state_failrec(struct extent_io_tree * tree,u64 start)2201 struct io_failure_record *get_state_failrec(struct extent_io_tree *tree, u64 start)
2202 {
2203 	struct rb_node *node;
2204 	struct extent_state *state;
2205 	struct io_failure_record *failrec;
2206 
2207 	spin_lock(&tree->lock);
2208 	/*
2209 	 * this search will find all the extents that end after
2210 	 * our range starts.
2211 	 */
2212 	node = tree_search(tree, start);
2213 	if (!node) {
2214 		failrec = ERR_PTR(-ENOENT);
2215 		goto out;
2216 	}
2217 	state = rb_entry(node, struct extent_state, rb_node);
2218 	if (state->start != start) {
2219 		failrec = ERR_PTR(-ENOENT);
2220 		goto out;
2221 	}
2222 
2223 	failrec = state->failrec;
2224 out:
2225 	spin_unlock(&tree->lock);
2226 	return failrec;
2227 }
2228 
2229 /*
2230  * searches a range in the state tree for a given mask.
2231  * If 'filled' == 1, this returns 1 only if every extent in the tree
2232  * has the bits set.  Otherwise, 1 is returned if any bit in the
2233  * range is found set.
2234  */
test_range_bit(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,int filled,struct extent_state * cached)2235 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
2236 		   u32 bits, int filled, struct extent_state *cached)
2237 {
2238 	struct extent_state *state = NULL;
2239 	struct rb_node *node;
2240 	int bitset = 0;
2241 
2242 	spin_lock(&tree->lock);
2243 	if (cached && extent_state_in_tree(cached) && cached->start <= start &&
2244 	    cached->end > start)
2245 		node = &cached->rb_node;
2246 	else
2247 		node = tree_search(tree, start);
2248 	while (node && start <= end) {
2249 		state = rb_entry(node, struct extent_state, rb_node);
2250 
2251 		if (filled && state->start > start) {
2252 			bitset = 0;
2253 			break;
2254 		}
2255 
2256 		if (state->start > end)
2257 			break;
2258 
2259 		if (state->state & bits) {
2260 			bitset = 1;
2261 			if (!filled)
2262 				break;
2263 		} else if (filled) {
2264 			bitset = 0;
2265 			break;
2266 		}
2267 
2268 		if (state->end == (u64)-1)
2269 			break;
2270 
2271 		start = state->end + 1;
2272 		if (start > end)
2273 			break;
2274 		node = rb_next(node);
2275 		if (!node) {
2276 			if (filled)
2277 				bitset = 0;
2278 			break;
2279 		}
2280 	}
2281 	spin_unlock(&tree->lock);
2282 	return bitset;
2283 }
2284 
free_io_failure(struct extent_io_tree * failure_tree,struct extent_io_tree * io_tree,struct io_failure_record * rec)2285 int free_io_failure(struct extent_io_tree *failure_tree,
2286 		    struct extent_io_tree *io_tree,
2287 		    struct io_failure_record *rec)
2288 {
2289 	int ret;
2290 	int err = 0;
2291 
2292 	set_state_failrec(failure_tree, rec->start, NULL);
2293 	ret = clear_extent_bits(failure_tree, rec->start,
2294 				rec->start + rec->len - 1,
2295 				EXTENT_LOCKED | EXTENT_DIRTY);
2296 	if (ret)
2297 		err = ret;
2298 
2299 	ret = clear_extent_bits(io_tree, rec->start,
2300 				rec->start + rec->len - 1,
2301 				EXTENT_DAMAGED);
2302 	if (ret && !err)
2303 		err = ret;
2304 
2305 	kfree(rec);
2306 	return err;
2307 }
2308 
2309 /*
2310  * this bypasses the standard btrfs submit functions deliberately, as
2311  * the standard behavior is to write all copies in a raid setup. here we only
2312  * want to write the one bad copy. so we do the mapping for ourselves and issue
2313  * submit_bio directly.
2314  * to avoid any synchronization issues, wait for the data after writing, which
2315  * actually prevents the read that triggered the error from finishing.
2316  * currently, there can be no more than two copies of every data bit. thus,
2317  * exactly one rewrite is required.
2318  */
repair_io_failure(struct btrfs_fs_info * fs_info,u64 ino,u64 start,u64 length,u64 logical,struct page * page,unsigned int pg_offset,int mirror_num)2319 static int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2320 			     u64 length, u64 logical, struct page *page,
2321 			     unsigned int pg_offset, int mirror_num)
2322 {
2323 	struct btrfs_device *dev;
2324 	struct bio_vec bvec;
2325 	struct bio bio;
2326 	u64 map_length = 0;
2327 	u64 sector;
2328 	struct btrfs_io_context *bioc = NULL;
2329 	int ret = 0;
2330 
2331 	ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2332 	BUG_ON(!mirror_num);
2333 
2334 	if (btrfs_repair_one_zone(fs_info, logical))
2335 		return 0;
2336 
2337 	map_length = length;
2338 
2339 	/*
2340 	 * Avoid races with device replace and make sure our bioc has devices
2341 	 * associated to its stripes that don't go away while we are doing the
2342 	 * read repair operation.
2343 	 */
2344 	btrfs_bio_counter_inc_blocked(fs_info);
2345 	if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2346 		/*
2347 		 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2348 		 * to update all raid stripes, but here we just want to correct
2349 		 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2350 		 * stripe's dev and sector.
2351 		 */
2352 		ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2353 				      &map_length, &bioc, 0);
2354 		if (ret)
2355 			goto out_counter_dec;
2356 		ASSERT(bioc->mirror_num == 1);
2357 	} else {
2358 		ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2359 				      &map_length, &bioc, mirror_num);
2360 		if (ret)
2361 			goto out_counter_dec;
2362 		BUG_ON(mirror_num != bioc->mirror_num);
2363 	}
2364 
2365 	sector = bioc->stripes[bioc->mirror_num - 1].physical >> 9;
2366 	dev = bioc->stripes[bioc->mirror_num - 1].dev;
2367 	btrfs_put_bioc(bioc);
2368 
2369 	if (!dev || !dev->bdev ||
2370 	    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2371 		ret = -EIO;
2372 		goto out_counter_dec;
2373 	}
2374 
2375 	bio_init(&bio, dev->bdev, &bvec, 1, REQ_OP_WRITE | REQ_SYNC);
2376 	bio.bi_iter.bi_sector = sector;
2377 	__bio_add_page(&bio, page, length, pg_offset);
2378 
2379 	btrfsic_check_bio(&bio);
2380 	ret = submit_bio_wait(&bio);
2381 	if (ret) {
2382 		/* try to remap that extent elsewhere? */
2383 		btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2384 		goto out_bio_uninit;
2385 	}
2386 
2387 	btrfs_info_rl_in_rcu(fs_info,
2388 		"read error corrected: ino %llu off %llu (dev %s sector %llu)",
2389 				  ino, start,
2390 				  rcu_str_deref(dev->name), sector);
2391 	ret = 0;
2392 
2393 out_bio_uninit:
2394 	bio_uninit(&bio);
2395 out_counter_dec:
2396 	btrfs_bio_counter_dec(fs_info);
2397 	return ret;
2398 }
2399 
btrfs_repair_eb_io_failure(const struct extent_buffer * eb,int mirror_num)2400 int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num)
2401 {
2402 	struct btrfs_fs_info *fs_info = eb->fs_info;
2403 	u64 start = eb->start;
2404 	int i, num_pages = num_extent_pages(eb);
2405 	int ret = 0;
2406 
2407 	if (sb_rdonly(fs_info->sb))
2408 		return -EROFS;
2409 
2410 	for (i = 0; i < num_pages; i++) {
2411 		struct page *p = eb->pages[i];
2412 
2413 		ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2414 					start - page_offset(p), mirror_num);
2415 		if (ret)
2416 			break;
2417 		start += PAGE_SIZE;
2418 	}
2419 
2420 	return ret;
2421 }
2422 
2423 /*
2424  * each time an IO finishes, we do a fast check in the IO failure tree
2425  * to see if we need to process or clean up an io_failure_record
2426  */
clean_io_failure(struct btrfs_fs_info * fs_info,struct extent_io_tree * failure_tree,struct extent_io_tree * io_tree,u64 start,struct page * page,u64 ino,unsigned int pg_offset)2427 int clean_io_failure(struct btrfs_fs_info *fs_info,
2428 		     struct extent_io_tree *failure_tree,
2429 		     struct extent_io_tree *io_tree, u64 start,
2430 		     struct page *page, u64 ino, unsigned int pg_offset)
2431 {
2432 	u64 private;
2433 	struct io_failure_record *failrec;
2434 	struct extent_state *state;
2435 	int num_copies;
2436 	int ret;
2437 
2438 	private = 0;
2439 	ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2440 			       EXTENT_DIRTY, 0);
2441 	if (!ret)
2442 		return 0;
2443 
2444 	failrec = get_state_failrec(failure_tree, start);
2445 	if (IS_ERR(failrec))
2446 		return 0;
2447 
2448 	BUG_ON(!failrec->this_mirror);
2449 
2450 	if (sb_rdonly(fs_info->sb))
2451 		goto out;
2452 
2453 	spin_lock(&io_tree->lock);
2454 	state = find_first_extent_bit_state(io_tree,
2455 					    failrec->start,
2456 					    EXTENT_LOCKED);
2457 	spin_unlock(&io_tree->lock);
2458 
2459 	if (state && state->start <= failrec->start &&
2460 	    state->end >= failrec->start + failrec->len - 1) {
2461 		num_copies = btrfs_num_copies(fs_info, failrec->logical,
2462 					      failrec->len);
2463 		if (num_copies > 1)  {
2464 			repair_io_failure(fs_info, ino, start, failrec->len,
2465 					  failrec->logical, page, pg_offset,
2466 					  failrec->failed_mirror);
2467 		}
2468 	}
2469 
2470 out:
2471 	free_io_failure(failure_tree, io_tree, failrec);
2472 
2473 	return 0;
2474 }
2475 
2476 /*
2477  * Can be called when
2478  * - hold extent lock
2479  * - under ordered extent
2480  * - the inode is freeing
2481  */
btrfs_free_io_failure_record(struct btrfs_inode * inode,u64 start,u64 end)2482 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2483 {
2484 	struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2485 	struct io_failure_record *failrec;
2486 	struct extent_state *state, *next;
2487 
2488 	if (RB_EMPTY_ROOT(&failure_tree->state))
2489 		return;
2490 
2491 	spin_lock(&failure_tree->lock);
2492 	state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2493 	while (state) {
2494 		if (state->start > end)
2495 			break;
2496 
2497 		ASSERT(state->end <= end);
2498 
2499 		next = next_state(state);
2500 
2501 		failrec = state->failrec;
2502 		free_extent_state(state);
2503 		kfree(failrec);
2504 
2505 		state = next;
2506 	}
2507 	spin_unlock(&failure_tree->lock);
2508 }
2509 
btrfs_get_io_failure_record(struct inode * inode,u64 start)2510 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
2511 							     u64 start)
2512 {
2513 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2514 	struct io_failure_record *failrec;
2515 	struct extent_map *em;
2516 	struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2517 	struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2518 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2519 	const u32 sectorsize = fs_info->sectorsize;
2520 	int ret;
2521 	u64 logical;
2522 
2523 	failrec = get_state_failrec(failure_tree, start);
2524 	if (!IS_ERR(failrec)) {
2525 		btrfs_debug(fs_info,
2526 	"Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu",
2527 			failrec->logical, failrec->start, failrec->len);
2528 		/*
2529 		 * when data can be on disk more than twice, add to failrec here
2530 		 * (e.g. with a list for failed_mirror) to make
2531 		 * clean_io_failure() clean all those errors at once.
2532 		 */
2533 
2534 		return failrec;
2535 	}
2536 
2537 	failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2538 	if (!failrec)
2539 		return ERR_PTR(-ENOMEM);
2540 
2541 	failrec->start = start;
2542 	failrec->len = sectorsize;
2543 	failrec->this_mirror = 0;
2544 	failrec->compress_type = BTRFS_COMPRESS_NONE;
2545 
2546 	read_lock(&em_tree->lock);
2547 	em = lookup_extent_mapping(em_tree, start, failrec->len);
2548 	if (!em) {
2549 		read_unlock(&em_tree->lock);
2550 		kfree(failrec);
2551 		return ERR_PTR(-EIO);
2552 	}
2553 
2554 	if (em->start > start || em->start + em->len <= start) {
2555 		free_extent_map(em);
2556 		em = NULL;
2557 	}
2558 	read_unlock(&em_tree->lock);
2559 	if (!em) {
2560 		kfree(failrec);
2561 		return ERR_PTR(-EIO);
2562 	}
2563 
2564 	logical = start - em->start;
2565 	logical = em->block_start + logical;
2566 	if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2567 		logical = em->block_start;
2568 		failrec->compress_type = em->compress_type;
2569 	}
2570 
2571 	btrfs_debug(fs_info,
2572 		    "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2573 		    logical, start, failrec->len);
2574 
2575 	failrec->logical = logical;
2576 	free_extent_map(em);
2577 
2578 	/* Set the bits in the private failure tree */
2579 	ret = set_extent_bits(failure_tree, start, start + sectorsize - 1,
2580 			      EXTENT_LOCKED | EXTENT_DIRTY);
2581 	if (ret >= 0) {
2582 		ret = set_state_failrec(failure_tree, start, failrec);
2583 		/* Set the bits in the inode's tree */
2584 		ret = set_extent_bits(tree, start, start + sectorsize - 1,
2585 				      EXTENT_DAMAGED);
2586 	} else if (ret < 0) {
2587 		kfree(failrec);
2588 		return ERR_PTR(ret);
2589 	}
2590 
2591 	return failrec;
2592 }
2593 
btrfs_check_repairable(struct inode * inode,struct io_failure_record * failrec,int failed_mirror)2594 static bool btrfs_check_repairable(struct inode *inode,
2595 				   struct io_failure_record *failrec,
2596 				   int failed_mirror)
2597 {
2598 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2599 	int num_copies;
2600 
2601 	num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2602 	if (num_copies == 1) {
2603 		/*
2604 		 * we only have a single copy of the data, so don't bother with
2605 		 * all the retry and error correction code that follows. no
2606 		 * matter what the error is, it is very likely to persist.
2607 		 */
2608 		btrfs_debug(fs_info,
2609 			"Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2610 			num_copies, failrec->this_mirror, failed_mirror);
2611 		return false;
2612 	}
2613 
2614 	/* The failure record should only contain one sector */
2615 	ASSERT(failrec->len == fs_info->sectorsize);
2616 
2617 	/*
2618 	 * There are two premises:
2619 	 * a) deliver good data to the caller
2620 	 * b) correct the bad sectors on disk
2621 	 *
2622 	 * Since we're only doing repair for one sector, we only need to get
2623 	 * a good copy of the failed sector and if we succeed, we have setup
2624 	 * everything for repair_io_failure to do the rest for us.
2625 	 */
2626 	ASSERT(failed_mirror);
2627 	failrec->failed_mirror = failed_mirror;
2628 	failrec->this_mirror++;
2629 	if (failrec->this_mirror == failed_mirror)
2630 		failrec->this_mirror++;
2631 
2632 	if (failrec->this_mirror > num_copies) {
2633 		btrfs_debug(fs_info,
2634 			"Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2635 			num_copies, failrec->this_mirror, failed_mirror);
2636 		return false;
2637 	}
2638 
2639 	return true;
2640 }
2641 
btrfs_repair_one_sector(struct inode * inode,struct bio * failed_bio,u32 bio_offset,struct page * page,unsigned int pgoff,u64 start,int failed_mirror,submit_bio_hook_t * submit_bio_hook)2642 int btrfs_repair_one_sector(struct inode *inode,
2643 			    struct bio *failed_bio, u32 bio_offset,
2644 			    struct page *page, unsigned int pgoff,
2645 			    u64 start, int failed_mirror,
2646 			    submit_bio_hook_t *submit_bio_hook)
2647 {
2648 	struct io_failure_record *failrec;
2649 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2650 	struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2651 	struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2652 	struct btrfs_bio *failed_bbio = btrfs_bio(failed_bio);
2653 	const int icsum = bio_offset >> fs_info->sectorsize_bits;
2654 	struct bio *repair_bio;
2655 	struct btrfs_bio *repair_bbio;
2656 
2657 	btrfs_debug(fs_info,
2658 		   "repair read error: read error at %llu", start);
2659 
2660 	BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2661 
2662 	failrec = btrfs_get_io_failure_record(inode, start);
2663 	if (IS_ERR(failrec))
2664 		return PTR_ERR(failrec);
2665 
2666 
2667 	if (!btrfs_check_repairable(inode, failrec, failed_mirror)) {
2668 		free_io_failure(failure_tree, tree, failrec);
2669 		return -EIO;
2670 	}
2671 
2672 	repair_bio = btrfs_bio_alloc(1);
2673 	repair_bbio = btrfs_bio(repair_bio);
2674 	repair_bbio->file_offset = start;
2675 	repair_bio->bi_opf = REQ_OP_READ;
2676 	repair_bio->bi_end_io = failed_bio->bi_end_io;
2677 	repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
2678 	repair_bio->bi_private = failed_bio->bi_private;
2679 
2680 	if (failed_bbio->csum) {
2681 		const u32 csum_size = fs_info->csum_size;
2682 
2683 		repair_bbio->csum = repair_bbio->csum_inline;
2684 		memcpy(repair_bbio->csum,
2685 		       failed_bbio->csum + csum_size * icsum, csum_size);
2686 	}
2687 
2688 	bio_add_page(repair_bio, page, failrec->len, pgoff);
2689 	repair_bbio->iter = repair_bio->bi_iter;
2690 
2691 	btrfs_debug(btrfs_sb(inode->i_sb),
2692 		    "repair read error: submitting new read to mirror %d",
2693 		    failrec->this_mirror);
2694 
2695 	/*
2696 	 * At this point we have a bio, so any errors from submit_bio_hook()
2697 	 * will be handled by the endio on the repair_bio, so we can't return an
2698 	 * error here.
2699 	 */
2700 	submit_bio_hook(inode, repair_bio, failrec->this_mirror, failrec->compress_type);
2701 	return BLK_STS_OK;
2702 }
2703 
end_page_read(struct page * page,bool uptodate,u64 start,u32 len)2704 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
2705 {
2706 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2707 
2708 	ASSERT(page_offset(page) <= start &&
2709 	       start + len <= page_offset(page) + PAGE_SIZE);
2710 
2711 	if (uptodate) {
2712 		if (fsverity_active(page->mapping->host) &&
2713 		    !PageError(page) &&
2714 		    !PageUptodate(page) &&
2715 		    start < i_size_read(page->mapping->host) &&
2716 		    !fsverity_verify_page(page)) {
2717 			btrfs_page_set_error(fs_info, page, start, len);
2718 		} else {
2719 			btrfs_page_set_uptodate(fs_info, page, start, len);
2720 		}
2721 	} else {
2722 		btrfs_page_clear_uptodate(fs_info, page, start, len);
2723 		btrfs_page_set_error(fs_info, page, start, len);
2724 	}
2725 
2726 	if (!btrfs_is_subpage(fs_info, page))
2727 		unlock_page(page);
2728 	else
2729 		btrfs_subpage_end_reader(fs_info, page, start, len);
2730 }
2731 
submit_data_read_repair(struct inode * inode,struct bio * failed_bio,u32 bio_offset,struct page * page,unsigned int pgoff,u64 start,u64 end,int failed_mirror,unsigned int error_bitmap)2732 static blk_status_t submit_data_read_repair(struct inode *inode,
2733 					    struct bio *failed_bio,
2734 					    u32 bio_offset, struct page *page,
2735 					    unsigned int pgoff,
2736 					    u64 start, u64 end,
2737 					    int failed_mirror,
2738 					    unsigned int error_bitmap)
2739 {
2740 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2741 	const u32 sectorsize = fs_info->sectorsize;
2742 	const int nr_bits = (end + 1 - start) >> fs_info->sectorsize_bits;
2743 	int error = 0;
2744 	int i;
2745 
2746 	BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2747 
2748 	/* This repair is only for data */
2749 	ASSERT(is_data_inode(inode));
2750 
2751 	/* We're here because we had some read errors or csum mismatch */
2752 	ASSERT(error_bitmap);
2753 
2754 	/*
2755 	 * We only get called on buffered IO, thus page must be mapped and bio
2756 	 * must not be cloned.
2757 	 */
2758 	ASSERT(page->mapping && !bio_flagged(failed_bio, BIO_CLONED));
2759 
2760 	/* Iterate through all the sectors in the range */
2761 	for (i = 0; i < nr_bits; i++) {
2762 		const unsigned int offset = i * sectorsize;
2763 		struct extent_state *cached = NULL;
2764 		bool uptodate = false;
2765 		int ret;
2766 
2767 		if (!(error_bitmap & (1U << i))) {
2768 			/*
2769 			 * This sector has no error, just end the page read
2770 			 * and unlock the range.
2771 			 */
2772 			uptodate = true;
2773 			goto next;
2774 		}
2775 
2776 		ret = btrfs_repair_one_sector(inode, failed_bio,
2777 				bio_offset + offset,
2778 				page, pgoff + offset, start + offset,
2779 				failed_mirror, btrfs_submit_data_bio);
2780 		if (!ret) {
2781 			/*
2782 			 * We have submitted the read repair, the page release
2783 			 * will be handled by the endio function of the
2784 			 * submitted repair bio.
2785 			 * Thus we don't need to do any thing here.
2786 			 */
2787 			continue;
2788 		}
2789 		/*
2790 		 * Repair failed, just record the error but still continue.
2791 		 * Or the remaining sectors will not be properly unlocked.
2792 		 */
2793 		if (!error)
2794 			error = ret;
2795 next:
2796 		end_page_read(page, uptodate, start + offset, sectorsize);
2797 		if (uptodate)
2798 			set_extent_uptodate(&BTRFS_I(inode)->io_tree,
2799 					start + offset,
2800 					start + offset + sectorsize - 1,
2801 					&cached, GFP_ATOMIC);
2802 		unlock_extent_cached_atomic(&BTRFS_I(inode)->io_tree,
2803 				start + offset,
2804 				start + offset + sectorsize - 1,
2805 				&cached);
2806 	}
2807 	return errno_to_blk_status(error);
2808 }
2809 
2810 /* lots and lots of room for performance fixes in the end_bio funcs */
2811 
end_extent_writepage(struct page * page,int err,u64 start,u64 end)2812 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2813 {
2814 	struct btrfs_inode *inode;
2815 	const bool uptodate = (err == 0);
2816 	int ret = 0;
2817 
2818 	ASSERT(page && page->mapping);
2819 	inode = BTRFS_I(page->mapping->host);
2820 	btrfs_writepage_endio_finish_ordered(inode, page, start, end, uptodate);
2821 
2822 	if (!uptodate) {
2823 		const struct btrfs_fs_info *fs_info = inode->root->fs_info;
2824 		u32 len;
2825 
2826 		ASSERT(end + 1 - start <= U32_MAX);
2827 		len = end + 1 - start;
2828 
2829 		btrfs_page_clear_uptodate(fs_info, page, start, len);
2830 		btrfs_page_set_error(fs_info, page, start, len);
2831 		ret = err < 0 ? err : -EIO;
2832 		mapping_set_error(page->mapping, ret);
2833 	}
2834 }
2835 
2836 /*
2837  * after a writepage IO is done, we need to:
2838  * clear the uptodate bits on error
2839  * clear the writeback bits in the extent tree for this IO
2840  * end_page_writeback if the page has no more pending IO
2841  *
2842  * Scheduling is not allowed, so the extent state tree is expected
2843  * to have one and only one object corresponding to this IO.
2844  */
end_bio_extent_writepage(struct bio * bio)2845 static void end_bio_extent_writepage(struct bio *bio)
2846 {
2847 	int error = blk_status_to_errno(bio->bi_status);
2848 	struct bio_vec *bvec;
2849 	u64 start;
2850 	u64 end;
2851 	struct bvec_iter_all iter_all;
2852 	bool first_bvec = true;
2853 
2854 	ASSERT(!bio_flagged(bio, BIO_CLONED));
2855 	bio_for_each_segment_all(bvec, bio, iter_all) {
2856 		struct page *page = bvec->bv_page;
2857 		struct inode *inode = page->mapping->host;
2858 		struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2859 		const u32 sectorsize = fs_info->sectorsize;
2860 
2861 		/* Our read/write should always be sector aligned. */
2862 		if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
2863 			btrfs_err(fs_info,
2864 		"partial page write in btrfs with offset %u and length %u",
2865 				  bvec->bv_offset, bvec->bv_len);
2866 		else if (!IS_ALIGNED(bvec->bv_len, sectorsize))
2867 			btrfs_info(fs_info,
2868 		"incomplete page write with offset %u and length %u",
2869 				   bvec->bv_offset, bvec->bv_len);
2870 
2871 		start = page_offset(page) + bvec->bv_offset;
2872 		end = start + bvec->bv_len - 1;
2873 
2874 		if (first_bvec) {
2875 			btrfs_record_physical_zoned(inode, start, bio);
2876 			first_bvec = false;
2877 		}
2878 
2879 		end_extent_writepage(page, error, start, end);
2880 
2881 		btrfs_page_clear_writeback(fs_info, page, start, bvec->bv_len);
2882 	}
2883 
2884 	bio_put(bio);
2885 }
2886 
2887 /*
2888  * Record previously processed extent range
2889  *
2890  * For endio_readpage_release_extent() to handle a full extent range, reducing
2891  * the extent io operations.
2892  */
2893 struct processed_extent {
2894 	struct btrfs_inode *inode;
2895 	/* Start of the range in @inode */
2896 	u64 start;
2897 	/* End of the range in @inode */
2898 	u64 end;
2899 	bool uptodate;
2900 };
2901 
2902 /*
2903  * Try to release processed extent range
2904  *
2905  * May not release the extent range right now if the current range is
2906  * contiguous to processed extent.
2907  *
2908  * Will release processed extent when any of @inode, @uptodate, the range is
2909  * no longer contiguous to the processed range.
2910  *
2911  * Passing @inode == NULL will force processed extent to be released.
2912  */
endio_readpage_release_extent(struct processed_extent * processed,struct btrfs_inode * inode,u64 start,u64 end,bool uptodate)2913 static void endio_readpage_release_extent(struct processed_extent *processed,
2914 			      struct btrfs_inode *inode, u64 start, u64 end,
2915 			      bool uptodate)
2916 {
2917 	struct extent_state *cached = NULL;
2918 	struct extent_io_tree *tree;
2919 
2920 	/* The first extent, initialize @processed */
2921 	if (!processed->inode)
2922 		goto update;
2923 
2924 	/*
2925 	 * Contiguous to processed extent, just uptodate the end.
2926 	 *
2927 	 * Several things to notice:
2928 	 *
2929 	 * - bio can be merged as long as on-disk bytenr is contiguous
2930 	 *   This means we can have page belonging to other inodes, thus need to
2931 	 *   check if the inode still matches.
2932 	 * - bvec can contain range beyond current page for multi-page bvec
2933 	 *   Thus we need to do processed->end + 1 >= start check
2934 	 */
2935 	if (processed->inode == inode && processed->uptodate == uptodate &&
2936 	    processed->end + 1 >= start && end >= processed->end) {
2937 		processed->end = end;
2938 		return;
2939 	}
2940 
2941 	tree = &processed->inode->io_tree;
2942 	/*
2943 	 * Now we don't have range contiguous to the processed range, release
2944 	 * the processed range now.
2945 	 */
2946 	if (processed->uptodate && tree->track_uptodate)
2947 		set_extent_uptodate(tree, processed->start, processed->end,
2948 				    &cached, GFP_ATOMIC);
2949 	unlock_extent_cached_atomic(tree, processed->start, processed->end,
2950 				    &cached);
2951 
2952 update:
2953 	/* Update processed to current range */
2954 	processed->inode = inode;
2955 	processed->start = start;
2956 	processed->end = end;
2957 	processed->uptodate = uptodate;
2958 }
2959 
begin_page_read(struct btrfs_fs_info * fs_info,struct page * page)2960 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
2961 {
2962 	ASSERT(PageLocked(page));
2963 	if (!btrfs_is_subpage(fs_info, page))
2964 		return;
2965 
2966 	ASSERT(PagePrivate(page));
2967 	btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
2968 }
2969 
2970 /*
2971  * Find extent buffer for a givne bytenr.
2972  *
2973  * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
2974  * in endio context.
2975  */
find_extent_buffer_readpage(struct btrfs_fs_info * fs_info,struct page * page,u64 bytenr)2976 static struct extent_buffer *find_extent_buffer_readpage(
2977 		struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
2978 {
2979 	struct extent_buffer *eb;
2980 
2981 	/*
2982 	 * For regular sectorsize, we can use page->private to grab extent
2983 	 * buffer
2984 	 */
2985 	if (fs_info->nodesize >= PAGE_SIZE) {
2986 		ASSERT(PagePrivate(page) && page->private);
2987 		return (struct extent_buffer *)page->private;
2988 	}
2989 
2990 	/* For subpage case, we need to lookup buffer radix tree */
2991 	rcu_read_lock();
2992 	eb = radix_tree_lookup(&fs_info->buffer_radix,
2993 			       bytenr >> fs_info->sectorsize_bits);
2994 	rcu_read_unlock();
2995 	ASSERT(eb);
2996 	return eb;
2997 }
2998 
2999 /*
3000  * after a readpage IO is done, we need to:
3001  * clear the uptodate bits on error
3002  * set the uptodate bits if things worked
3003  * set the page up to date if all extents in the tree are uptodate
3004  * clear the lock bit in the extent tree
3005  * unlock the page if there are no other extents locked for it
3006  *
3007  * Scheduling is not allowed, so the extent state tree is expected
3008  * to have one and only one object corresponding to this IO.
3009  */
end_bio_extent_readpage(struct bio * bio)3010 static void end_bio_extent_readpage(struct bio *bio)
3011 {
3012 	struct bio_vec *bvec;
3013 	struct btrfs_bio *bbio = btrfs_bio(bio);
3014 	struct extent_io_tree *tree, *failure_tree;
3015 	struct processed_extent processed = { 0 };
3016 	/*
3017 	 * The offset to the beginning of a bio, since one bio can never be
3018 	 * larger than UINT_MAX, u32 here is enough.
3019 	 */
3020 	u32 bio_offset = 0;
3021 	int mirror;
3022 	int ret;
3023 	struct bvec_iter_all iter_all;
3024 
3025 	ASSERT(!bio_flagged(bio, BIO_CLONED));
3026 	bio_for_each_segment_all(bvec, bio, iter_all) {
3027 		bool uptodate = !bio->bi_status;
3028 		struct page *page = bvec->bv_page;
3029 		struct inode *inode = page->mapping->host;
3030 		struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3031 		const u32 sectorsize = fs_info->sectorsize;
3032 		unsigned int error_bitmap = (unsigned int)-1;
3033 		u64 start;
3034 		u64 end;
3035 		u32 len;
3036 
3037 		btrfs_debug(fs_info,
3038 			"end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
3039 			bio->bi_iter.bi_sector, bio->bi_status,
3040 			bbio->mirror_num);
3041 		tree = &BTRFS_I(inode)->io_tree;
3042 		failure_tree = &BTRFS_I(inode)->io_failure_tree;
3043 
3044 		/*
3045 		 * We always issue full-sector reads, but if some block in a
3046 		 * page fails to read, blk_update_request() will advance
3047 		 * bv_offset and adjust bv_len to compensate.  Print a warning
3048 		 * for unaligned offsets, and an error if they don't add up to
3049 		 * a full sector.
3050 		 */
3051 		if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
3052 			btrfs_err(fs_info,
3053 		"partial page read in btrfs with offset %u and length %u",
3054 				  bvec->bv_offset, bvec->bv_len);
3055 		else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
3056 				     sectorsize))
3057 			btrfs_info(fs_info,
3058 		"incomplete page read with offset %u and length %u",
3059 				   bvec->bv_offset, bvec->bv_len);
3060 
3061 		start = page_offset(page) + bvec->bv_offset;
3062 		end = start + bvec->bv_len - 1;
3063 		len = bvec->bv_len;
3064 
3065 		mirror = bbio->mirror_num;
3066 		if (likely(uptodate)) {
3067 			if (is_data_inode(inode)) {
3068 				error_bitmap = btrfs_verify_data_csum(bbio,
3069 						bio_offset, page, start, end);
3070 				ret = error_bitmap;
3071 			} else {
3072 				ret = btrfs_validate_metadata_buffer(bbio,
3073 					page, start, end, mirror);
3074 			}
3075 			if (ret)
3076 				uptodate = false;
3077 			else
3078 				clean_io_failure(BTRFS_I(inode)->root->fs_info,
3079 						 failure_tree, tree, start,
3080 						 page,
3081 						 btrfs_ino(BTRFS_I(inode)), 0);
3082 		}
3083 
3084 		if (likely(uptodate))
3085 			goto readpage_ok;
3086 
3087 		if (is_data_inode(inode)) {
3088 			/*
3089 			 * If we failed to submit the IO at all we'll have a
3090 			 * mirror_num == 0, in which case we need to just mark
3091 			 * the page with an error and unlock it and carry on.
3092 			 */
3093 			if (mirror == 0)
3094 				goto readpage_ok;
3095 
3096 			/*
3097 			 * submit_data_read_repair() will handle all the good
3098 			 * and bad sectors, we just continue to the next bvec.
3099 			 */
3100 			submit_data_read_repair(inode, bio, bio_offset, page,
3101 						start - page_offset(page),
3102 						start, end, mirror,
3103 						error_bitmap);
3104 
3105 			ASSERT(bio_offset + len > bio_offset);
3106 			bio_offset += len;
3107 			continue;
3108 		} else {
3109 			struct extent_buffer *eb;
3110 
3111 			eb = find_extent_buffer_readpage(fs_info, page, start);
3112 			set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
3113 			eb->read_mirror = mirror;
3114 			atomic_dec(&eb->io_pages);
3115 		}
3116 readpage_ok:
3117 		if (likely(uptodate)) {
3118 			loff_t i_size = i_size_read(inode);
3119 			pgoff_t end_index = i_size >> PAGE_SHIFT;
3120 
3121 			/*
3122 			 * Zero out the remaining part if this range straddles
3123 			 * i_size.
3124 			 *
3125 			 * Here we should only zero the range inside the bvec,
3126 			 * not touch anything else.
3127 			 *
3128 			 * NOTE: i_size is exclusive while end is inclusive.
3129 			 */
3130 			if (page->index == end_index && i_size <= end) {
3131 				u32 zero_start = max(offset_in_page(i_size),
3132 						     offset_in_page(start));
3133 
3134 				zero_user_segment(page, zero_start,
3135 						  offset_in_page(end) + 1);
3136 			}
3137 		}
3138 		ASSERT(bio_offset + len > bio_offset);
3139 		bio_offset += len;
3140 
3141 		/* Update page status and unlock */
3142 		end_page_read(page, uptodate, start, len);
3143 		endio_readpage_release_extent(&processed, BTRFS_I(inode),
3144 					      start, end, PageUptodate(page));
3145 	}
3146 	/* Release the last extent */
3147 	endio_readpage_release_extent(&processed, NULL, 0, 0, false);
3148 	btrfs_bio_free_csum(bbio);
3149 	bio_put(bio);
3150 }
3151 
3152 /**
3153  * Populate every free slot in a provided array with pages.
3154  *
3155  * @nr_pages:   number of pages to allocate
3156  * @page_array: the array to fill with pages; any existing non-null entries in
3157  * 		the array will be skipped
3158  *
3159  * Return: 0        if all pages were able to be allocated;
3160  *         -ENOMEM  otherwise, and the caller is responsible for freeing all
3161  *                  non-null page pointers in the array.
3162  */
btrfs_alloc_page_array(unsigned int nr_pages,struct page ** page_array)3163 int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array)
3164 {
3165 	unsigned int allocated;
3166 
3167 	for (allocated = 0; allocated < nr_pages;) {
3168 		unsigned int last = allocated;
3169 
3170 		allocated = alloc_pages_bulk_array(GFP_NOFS, nr_pages, page_array);
3171 
3172 		if (allocated == nr_pages)
3173 			return 0;
3174 
3175 		/*
3176 		 * During this iteration, no page could be allocated, even
3177 		 * though alloc_pages_bulk_array() falls back to alloc_page()
3178 		 * if  it could not bulk-allocate. So we must be out of memory.
3179 		 */
3180 		if (allocated == last)
3181 			return -ENOMEM;
3182 
3183 		memalloc_retry_wait(GFP_NOFS);
3184 	}
3185 	return 0;
3186 }
3187 
3188 /*
3189  * Initialize the members up to but not including 'bio'. Use after allocating a
3190  * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
3191  * 'bio' because use of __GFP_ZERO is not supported.
3192  */
btrfs_bio_init(struct btrfs_bio * bbio)3193 static inline void btrfs_bio_init(struct btrfs_bio *bbio)
3194 {
3195 	memset(bbio, 0, offsetof(struct btrfs_bio, bio));
3196 }
3197 
3198 /*
3199  * Allocate a btrfs_io_bio, with @nr_iovecs as maximum number of iovecs.
3200  *
3201  * The bio allocation is backed by bioset and does not fail.
3202  */
btrfs_bio_alloc(unsigned int nr_iovecs)3203 struct bio *btrfs_bio_alloc(unsigned int nr_iovecs)
3204 {
3205 	struct bio *bio;
3206 
3207 	ASSERT(0 < nr_iovecs && nr_iovecs <= BIO_MAX_VECS);
3208 	bio = bio_alloc_bioset(NULL, nr_iovecs, 0, GFP_NOFS, &btrfs_bioset);
3209 	btrfs_bio_init(btrfs_bio(bio));
3210 	return bio;
3211 }
3212 
btrfs_bio_clone(struct block_device * bdev,struct bio * bio)3213 struct bio *btrfs_bio_clone(struct block_device *bdev, struct bio *bio)
3214 {
3215 	struct btrfs_bio *bbio;
3216 	struct bio *new;
3217 
3218 	/* Bio allocation backed by a bioset does not fail */
3219 	new = bio_alloc_clone(bdev, bio, GFP_NOFS, &btrfs_bioset);
3220 	bbio = btrfs_bio(new);
3221 	btrfs_bio_init(bbio);
3222 	bbio->iter = bio->bi_iter;
3223 	return new;
3224 }
3225 
btrfs_bio_clone_partial(struct bio * orig,u64 offset,u64 size)3226 struct bio *btrfs_bio_clone_partial(struct bio *orig, u64 offset, u64 size)
3227 {
3228 	struct bio *bio;
3229 	struct btrfs_bio *bbio;
3230 
3231 	ASSERT(offset <= UINT_MAX && size <= UINT_MAX);
3232 
3233 	/* this will never fail when it's backed by a bioset */
3234 	bio = bio_alloc_clone(orig->bi_bdev, orig, GFP_NOFS, &btrfs_bioset);
3235 	ASSERT(bio);
3236 
3237 	bbio = btrfs_bio(bio);
3238 	btrfs_bio_init(bbio);
3239 
3240 	bio_trim(bio, offset >> 9, size >> 9);
3241 	bbio->iter = bio->bi_iter;
3242 	return bio;
3243 }
3244 
3245 /**
3246  * Attempt to add a page to bio
3247  *
3248  * @bio_ctrl:	record both the bio, and its bio_flags
3249  * @page:	page to add to the bio
3250  * @disk_bytenr:  offset of the new bio or to check whether we are adding
3251  *                a contiguous page to the previous one
3252  * @size:	portion of page that we want to write
3253  * @pg_offset:	starting offset in the page
3254  * @compress_type:   compression type of the current bio to see if we can merge them
3255  *
3256  * Attempt to add a page to bio considering stripe alignment etc.
3257  *
3258  * Return >= 0 for the number of bytes added to the bio.
3259  * Can return 0 if the current bio is already at stripe/zone boundary.
3260  * Return <0 for error.
3261  */
btrfs_bio_add_page(struct btrfs_bio_ctrl * bio_ctrl,struct page * page,u64 disk_bytenr,unsigned int size,unsigned int pg_offset,enum btrfs_compression_type compress_type)3262 static int btrfs_bio_add_page(struct btrfs_bio_ctrl *bio_ctrl,
3263 			      struct page *page,
3264 			      u64 disk_bytenr, unsigned int size,
3265 			      unsigned int pg_offset,
3266 			      enum btrfs_compression_type compress_type)
3267 {
3268 	struct bio *bio = bio_ctrl->bio;
3269 	u32 bio_size = bio->bi_iter.bi_size;
3270 	u32 real_size;
3271 	const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
3272 	bool contig;
3273 	int ret;
3274 
3275 	ASSERT(bio);
3276 	/* The limit should be calculated when bio_ctrl->bio is allocated */
3277 	ASSERT(bio_ctrl->len_to_oe_boundary && bio_ctrl->len_to_stripe_boundary);
3278 	if (bio_ctrl->compress_type != compress_type)
3279 		return 0;
3280 
3281 	if (bio_ctrl->compress_type != BTRFS_COMPRESS_NONE)
3282 		contig = bio->bi_iter.bi_sector == sector;
3283 	else
3284 		contig = bio_end_sector(bio) == sector;
3285 	if (!contig)
3286 		return 0;
3287 
3288 	real_size = min(bio_ctrl->len_to_oe_boundary,
3289 			bio_ctrl->len_to_stripe_boundary) - bio_size;
3290 	real_size = min(real_size, size);
3291 
3292 	/*
3293 	 * If real_size is 0, never call bio_add_*_page(), as even size is 0,
3294 	 * bio will still execute its endio function on the page!
3295 	 */
3296 	if (real_size == 0)
3297 		return 0;
3298 
3299 	if (bio_op(bio) == REQ_OP_ZONE_APPEND)
3300 		ret = bio_add_zone_append_page(bio, page, real_size, pg_offset);
3301 	else
3302 		ret = bio_add_page(bio, page, real_size, pg_offset);
3303 
3304 	return ret;
3305 }
3306 
calc_bio_boundaries(struct btrfs_bio_ctrl * bio_ctrl,struct btrfs_inode * inode,u64 file_offset)3307 static int calc_bio_boundaries(struct btrfs_bio_ctrl *bio_ctrl,
3308 			       struct btrfs_inode *inode, u64 file_offset)
3309 {
3310 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
3311 	struct btrfs_io_geometry geom;
3312 	struct btrfs_ordered_extent *ordered;
3313 	struct extent_map *em;
3314 	u64 logical = (bio_ctrl->bio->bi_iter.bi_sector << SECTOR_SHIFT);
3315 	int ret;
3316 
3317 	/*
3318 	 * Pages for compressed extent are never submitted to disk directly,
3319 	 * thus it has no real boundary, just set them to U32_MAX.
3320 	 *
3321 	 * The split happens for real compressed bio, which happens in
3322 	 * btrfs_submit_compressed_read/write().
3323 	 */
3324 	if (bio_ctrl->compress_type != BTRFS_COMPRESS_NONE) {
3325 		bio_ctrl->len_to_oe_boundary = U32_MAX;
3326 		bio_ctrl->len_to_stripe_boundary = U32_MAX;
3327 		return 0;
3328 	}
3329 	em = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
3330 	if (IS_ERR(em))
3331 		return PTR_ERR(em);
3332 	ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio_ctrl->bio),
3333 				    logical, &geom);
3334 	free_extent_map(em);
3335 	if (ret < 0) {
3336 		return ret;
3337 	}
3338 	if (geom.len > U32_MAX)
3339 		bio_ctrl->len_to_stripe_boundary = U32_MAX;
3340 	else
3341 		bio_ctrl->len_to_stripe_boundary = (u32)geom.len;
3342 
3343 	if (bio_op(bio_ctrl->bio) != REQ_OP_ZONE_APPEND) {
3344 		bio_ctrl->len_to_oe_boundary = U32_MAX;
3345 		return 0;
3346 	}
3347 
3348 	/* Ordered extent not yet created, so we're good */
3349 	ordered = btrfs_lookup_ordered_extent(inode, file_offset);
3350 	if (!ordered) {
3351 		bio_ctrl->len_to_oe_boundary = U32_MAX;
3352 		return 0;
3353 	}
3354 
3355 	bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
3356 		ordered->disk_bytenr + ordered->disk_num_bytes - logical);
3357 	btrfs_put_ordered_extent(ordered);
3358 	return 0;
3359 }
3360 
alloc_new_bio(struct btrfs_inode * inode,struct btrfs_bio_ctrl * bio_ctrl,struct writeback_control * wbc,unsigned int opf,bio_end_io_t end_io_func,u64 disk_bytenr,u32 offset,u64 file_offset,enum btrfs_compression_type compress_type)3361 static int alloc_new_bio(struct btrfs_inode *inode,
3362 			 struct btrfs_bio_ctrl *bio_ctrl,
3363 			 struct writeback_control *wbc,
3364 			 unsigned int opf,
3365 			 bio_end_io_t end_io_func,
3366 			 u64 disk_bytenr, u32 offset, u64 file_offset,
3367 			 enum btrfs_compression_type compress_type)
3368 {
3369 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
3370 	struct bio *bio;
3371 	int ret;
3372 
3373 	bio = btrfs_bio_alloc(BIO_MAX_VECS);
3374 	/*
3375 	 * For compressed page range, its disk_bytenr is always @disk_bytenr
3376 	 * passed in, no matter if we have added any range into previous bio.
3377 	 */
3378 	if (compress_type != BTRFS_COMPRESS_NONE)
3379 		bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
3380 	else
3381 		bio->bi_iter.bi_sector = (disk_bytenr + offset) >> SECTOR_SHIFT;
3382 	bio_ctrl->bio = bio;
3383 	bio_ctrl->compress_type = compress_type;
3384 	bio->bi_end_io = end_io_func;
3385 	bio->bi_private = &inode->io_tree;
3386 	bio->bi_opf = opf;
3387 	ret = calc_bio_boundaries(bio_ctrl, inode, file_offset);
3388 	if (ret < 0)
3389 		goto error;
3390 
3391 	if (wbc) {
3392 		/*
3393 		 * For Zone append we need the correct block_device that we are
3394 		 * going to write to set in the bio to be able to respect the
3395 		 * hardware limitation.  Look it up here:
3396 		 */
3397 		if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
3398 			struct btrfs_device *dev;
3399 
3400 			dev = btrfs_zoned_get_device(fs_info, disk_bytenr,
3401 						     fs_info->sectorsize);
3402 			if (IS_ERR(dev)) {
3403 				ret = PTR_ERR(dev);
3404 				goto error;
3405 			}
3406 
3407 			bio_set_dev(bio, dev->bdev);
3408 		} else {
3409 			/*
3410 			 * Otherwise pick the last added device to support
3411 			 * cgroup writeback.  For multi-device file systems this
3412 			 * means blk-cgroup policies have to always be set on the
3413 			 * last added/replaced device.  This is a bit odd but has
3414 			 * been like that for a long time.
3415 			 */
3416 			bio_set_dev(bio, fs_info->fs_devices->latest_dev->bdev);
3417 		}
3418 		wbc_init_bio(wbc, bio);
3419 	} else {
3420 		ASSERT(bio_op(bio) != REQ_OP_ZONE_APPEND);
3421 	}
3422 	return 0;
3423 error:
3424 	bio_ctrl->bio = NULL;
3425 	bio->bi_status = errno_to_blk_status(ret);
3426 	bio_endio(bio);
3427 	return ret;
3428 }
3429 
3430 /*
3431  * @opf:	bio REQ_OP_* and REQ_* flags as one value
3432  * @wbc:	optional writeback control for io accounting
3433  * @page:	page to add to the bio
3434  * @disk_bytenr: logical bytenr where the write will be
3435  * @size:	portion of page that we want to write to
3436  * @pg_offset:	offset of the new bio or to check whether we are adding
3437  *              a contiguous page to the previous one
3438  * @bio_ret:	must be valid pointer, newly allocated bio will be stored there
3439  * @end_io_func:     end_io callback for new bio
3440  * @mirror_num:	     desired mirror to read/write
3441  * @prev_bio_flags:  flags of previous bio to see if we can merge the current one
3442  * @compress_type:   compress type for current bio
3443  */
submit_extent_page(unsigned int opf,struct writeback_control * wbc,struct btrfs_bio_ctrl * bio_ctrl,struct page * page,u64 disk_bytenr,size_t size,unsigned long pg_offset,bio_end_io_t end_io_func,int mirror_num,enum btrfs_compression_type compress_type,bool force_bio_submit)3444 static int submit_extent_page(unsigned int opf,
3445 			      struct writeback_control *wbc,
3446 			      struct btrfs_bio_ctrl *bio_ctrl,
3447 			      struct page *page, u64 disk_bytenr,
3448 			      size_t size, unsigned long pg_offset,
3449 			      bio_end_io_t end_io_func,
3450 			      int mirror_num,
3451 			      enum btrfs_compression_type compress_type,
3452 			      bool force_bio_submit)
3453 {
3454 	int ret = 0;
3455 	struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3456 	unsigned int cur = pg_offset;
3457 
3458 	ASSERT(bio_ctrl);
3459 
3460 	ASSERT(pg_offset < PAGE_SIZE && size <= PAGE_SIZE &&
3461 	       pg_offset + size <= PAGE_SIZE);
3462 	if (force_bio_submit && bio_ctrl->bio) {
3463 		submit_one_bio(bio_ctrl->bio, mirror_num, bio_ctrl->compress_type);
3464 		bio_ctrl->bio = NULL;
3465 	}
3466 
3467 	while (cur < pg_offset + size) {
3468 		u32 offset = cur - pg_offset;
3469 		int added;
3470 
3471 		/* Allocate new bio if needed */
3472 		if (!bio_ctrl->bio) {
3473 			ret = alloc_new_bio(inode, bio_ctrl, wbc, opf,
3474 					    end_io_func, disk_bytenr, offset,
3475 					    page_offset(page) + cur,
3476 					    compress_type);
3477 			if (ret < 0)
3478 				return ret;
3479 		}
3480 		/*
3481 		 * We must go through btrfs_bio_add_page() to ensure each
3482 		 * page range won't cross various boundaries.
3483 		 */
3484 		if (compress_type != BTRFS_COMPRESS_NONE)
3485 			added = btrfs_bio_add_page(bio_ctrl, page, disk_bytenr,
3486 					size - offset, pg_offset + offset,
3487 					compress_type);
3488 		else
3489 			added = btrfs_bio_add_page(bio_ctrl, page,
3490 					disk_bytenr + offset, size - offset,
3491 					pg_offset + offset, compress_type);
3492 
3493 		/* Metadata page range should never be split */
3494 		if (!is_data_inode(&inode->vfs_inode))
3495 			ASSERT(added == 0 || added == size - offset);
3496 
3497 		/* At least we added some page, update the account */
3498 		if (wbc && added)
3499 			wbc_account_cgroup_owner(wbc, page, added);
3500 
3501 		/* We have reached boundary, submit right now */
3502 		if (added < size - offset) {
3503 			/* The bio should contain some page(s) */
3504 			ASSERT(bio_ctrl->bio->bi_iter.bi_size);
3505 			submit_one_bio(bio_ctrl->bio, mirror_num, bio_ctrl->compress_type);
3506 			bio_ctrl->bio = NULL;
3507 		}
3508 		cur += added;
3509 	}
3510 	return 0;
3511 }
3512 
attach_extent_buffer_page(struct extent_buffer * eb,struct page * page,struct btrfs_subpage * prealloc)3513 static int attach_extent_buffer_page(struct extent_buffer *eb,
3514 				     struct page *page,
3515 				     struct btrfs_subpage *prealloc)
3516 {
3517 	struct btrfs_fs_info *fs_info = eb->fs_info;
3518 	int ret = 0;
3519 
3520 	/*
3521 	 * If the page is mapped to btree inode, we should hold the private
3522 	 * lock to prevent race.
3523 	 * For cloned or dummy extent buffers, their pages are not mapped and
3524 	 * will not race with any other ebs.
3525 	 */
3526 	if (page->mapping)
3527 		lockdep_assert_held(&page->mapping->private_lock);
3528 
3529 	if (fs_info->nodesize >= PAGE_SIZE) {
3530 		if (!PagePrivate(page))
3531 			attach_page_private(page, eb);
3532 		else
3533 			WARN_ON(page->private != (unsigned long)eb);
3534 		return 0;
3535 	}
3536 
3537 	/* Already mapped, just free prealloc */
3538 	if (PagePrivate(page)) {
3539 		btrfs_free_subpage(prealloc);
3540 		return 0;
3541 	}
3542 
3543 	if (prealloc)
3544 		/* Has preallocated memory for subpage */
3545 		attach_page_private(page, prealloc);
3546 	else
3547 		/* Do new allocation to attach subpage */
3548 		ret = btrfs_attach_subpage(fs_info, page,
3549 					   BTRFS_SUBPAGE_METADATA);
3550 	return ret;
3551 }
3552 
set_page_extent_mapped(struct page * page)3553 int set_page_extent_mapped(struct page *page)
3554 {
3555 	struct btrfs_fs_info *fs_info;
3556 
3557 	ASSERT(page->mapping);
3558 
3559 	if (PagePrivate(page))
3560 		return 0;
3561 
3562 	fs_info = btrfs_sb(page->mapping->host->i_sb);
3563 
3564 	if (btrfs_is_subpage(fs_info, page))
3565 		return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
3566 
3567 	attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
3568 	return 0;
3569 }
3570 
clear_page_extent_mapped(struct page * page)3571 void clear_page_extent_mapped(struct page *page)
3572 {
3573 	struct btrfs_fs_info *fs_info;
3574 
3575 	ASSERT(page->mapping);
3576 
3577 	if (!PagePrivate(page))
3578 		return;
3579 
3580 	fs_info = btrfs_sb(page->mapping->host->i_sb);
3581 	if (btrfs_is_subpage(fs_info, page))
3582 		return btrfs_detach_subpage(fs_info, page);
3583 
3584 	detach_page_private(page);
3585 }
3586 
3587 static struct extent_map *
__get_extent_map(struct inode * inode,struct page * page,size_t pg_offset,u64 start,u64 len,struct extent_map ** em_cached)3588 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
3589 		 u64 start, u64 len, struct extent_map **em_cached)
3590 {
3591 	struct extent_map *em;
3592 
3593 	if (em_cached && *em_cached) {
3594 		em = *em_cached;
3595 		if (extent_map_in_tree(em) && start >= em->start &&
3596 		    start < extent_map_end(em)) {
3597 			refcount_inc(&em->refs);
3598 			return em;
3599 		}
3600 
3601 		free_extent_map(em);
3602 		*em_cached = NULL;
3603 	}
3604 
3605 	em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
3606 	if (em_cached && !IS_ERR(em)) {
3607 		BUG_ON(*em_cached);
3608 		refcount_inc(&em->refs);
3609 		*em_cached = em;
3610 	}
3611 	return em;
3612 }
3613 /*
3614  * basic readpage implementation.  Locked extent state structs are inserted
3615  * into the tree that are removed when the IO is done (by the end_io
3616  * handlers)
3617  * XXX JDM: This needs looking at to ensure proper page locking
3618  * return 0 on success, otherwise return error
3619  */
btrfs_do_readpage(struct page * page,struct extent_map ** em_cached,struct btrfs_bio_ctrl * bio_ctrl,unsigned int read_flags,u64 * prev_em_start)3620 static int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
3621 		      struct btrfs_bio_ctrl *bio_ctrl,
3622 		      unsigned int read_flags, u64 *prev_em_start)
3623 {
3624 	struct inode *inode = page->mapping->host;
3625 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3626 	u64 start = page_offset(page);
3627 	const u64 end = start + PAGE_SIZE - 1;
3628 	u64 cur = start;
3629 	u64 extent_offset;
3630 	u64 last_byte = i_size_read(inode);
3631 	u64 block_start;
3632 	u64 cur_end;
3633 	struct extent_map *em;
3634 	int ret = 0;
3635 	size_t pg_offset = 0;
3636 	size_t iosize;
3637 	size_t blocksize = inode->i_sb->s_blocksize;
3638 	struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
3639 
3640 	ret = set_page_extent_mapped(page);
3641 	if (ret < 0) {
3642 		unlock_extent(tree, start, end);
3643 		btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
3644 		unlock_page(page);
3645 		goto out;
3646 	}
3647 
3648 	if (page->index == last_byte >> PAGE_SHIFT) {
3649 		size_t zero_offset = offset_in_page(last_byte);
3650 
3651 		if (zero_offset) {
3652 			iosize = PAGE_SIZE - zero_offset;
3653 			memzero_page(page, zero_offset, iosize);
3654 			flush_dcache_page(page);
3655 		}
3656 	}
3657 	begin_page_read(fs_info, page);
3658 	while (cur <= end) {
3659 		unsigned long this_bio_flag = 0;
3660 		bool force_bio_submit = false;
3661 		u64 disk_bytenr;
3662 
3663 		ASSERT(IS_ALIGNED(cur, fs_info->sectorsize));
3664 		if (cur >= last_byte) {
3665 			struct extent_state *cached = NULL;
3666 
3667 			iosize = PAGE_SIZE - pg_offset;
3668 			memzero_page(page, pg_offset, iosize);
3669 			flush_dcache_page(page);
3670 			set_extent_uptodate(tree, cur, cur + iosize - 1,
3671 					    &cached, GFP_NOFS);
3672 			unlock_extent_cached(tree, cur,
3673 					     cur + iosize - 1, &cached);
3674 			end_page_read(page, true, cur, iosize);
3675 			break;
3676 		}
3677 		em = __get_extent_map(inode, page, pg_offset, cur,
3678 				      end - cur + 1, em_cached);
3679 		if (IS_ERR(em)) {
3680 			unlock_extent(tree, cur, end);
3681 			end_page_read(page, false, cur, end + 1 - cur);
3682 			ret = PTR_ERR(em);
3683 			break;
3684 		}
3685 		extent_offset = cur - em->start;
3686 		BUG_ON(extent_map_end(em) <= cur);
3687 		BUG_ON(end < cur);
3688 
3689 		if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
3690 			this_bio_flag = em->compress_type;
3691 
3692 		iosize = min(extent_map_end(em) - cur, end - cur + 1);
3693 		cur_end = min(extent_map_end(em) - 1, end);
3694 		iosize = ALIGN(iosize, blocksize);
3695 		if (this_bio_flag != BTRFS_COMPRESS_NONE)
3696 			disk_bytenr = em->block_start;
3697 		else
3698 			disk_bytenr = em->block_start + extent_offset;
3699 		block_start = em->block_start;
3700 		if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3701 			block_start = EXTENT_MAP_HOLE;
3702 
3703 		/*
3704 		 * If we have a file range that points to a compressed extent
3705 		 * and it's followed by a consecutive file range that points
3706 		 * to the same compressed extent (possibly with a different
3707 		 * offset and/or length, so it either points to the whole extent
3708 		 * or only part of it), we must make sure we do not submit a
3709 		 * single bio to populate the pages for the 2 ranges because
3710 		 * this makes the compressed extent read zero out the pages
3711 		 * belonging to the 2nd range. Imagine the following scenario:
3712 		 *
3713 		 *  File layout
3714 		 *  [0 - 8K]                     [8K - 24K]
3715 		 *    |                               |
3716 		 *    |                               |
3717 		 * points to extent X,         points to extent X,
3718 		 * offset 4K, length of 8K     offset 0, length 16K
3719 		 *
3720 		 * [extent X, compressed length = 4K uncompressed length = 16K]
3721 		 *
3722 		 * If the bio to read the compressed extent covers both ranges,
3723 		 * it will decompress extent X into the pages belonging to the
3724 		 * first range and then it will stop, zeroing out the remaining
3725 		 * pages that belong to the other range that points to extent X.
3726 		 * So here we make sure we submit 2 bios, one for the first
3727 		 * range and another one for the third range. Both will target
3728 		 * the same physical extent from disk, but we can't currently
3729 		 * make the compressed bio endio callback populate the pages
3730 		 * for both ranges because each compressed bio is tightly
3731 		 * coupled with a single extent map, and each range can have
3732 		 * an extent map with a different offset value relative to the
3733 		 * uncompressed data of our extent and different lengths. This
3734 		 * is a corner case so we prioritize correctness over
3735 		 * non-optimal behavior (submitting 2 bios for the same extent).
3736 		 */
3737 		if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3738 		    prev_em_start && *prev_em_start != (u64)-1 &&
3739 		    *prev_em_start != em->start)
3740 			force_bio_submit = true;
3741 
3742 		if (prev_em_start)
3743 			*prev_em_start = em->start;
3744 
3745 		free_extent_map(em);
3746 		em = NULL;
3747 
3748 		/* we've found a hole, just zero and go on */
3749 		if (block_start == EXTENT_MAP_HOLE) {
3750 			struct extent_state *cached = NULL;
3751 
3752 			memzero_page(page, pg_offset, iosize);
3753 			flush_dcache_page(page);
3754 
3755 			set_extent_uptodate(tree, cur, cur + iosize - 1,
3756 					    &cached, GFP_NOFS);
3757 			unlock_extent_cached(tree, cur,
3758 					     cur + iosize - 1, &cached);
3759 			end_page_read(page, true, cur, iosize);
3760 			cur = cur + iosize;
3761 			pg_offset += iosize;
3762 			continue;
3763 		}
3764 		/* the get_extent function already copied into the page */
3765 		if (test_range_bit(tree, cur, cur_end,
3766 				   EXTENT_UPTODATE, 1, NULL)) {
3767 			unlock_extent(tree, cur, cur + iosize - 1);
3768 			end_page_read(page, true, cur, iosize);
3769 			cur = cur + iosize;
3770 			pg_offset += iosize;
3771 			continue;
3772 		}
3773 		/* we have an inline extent but it didn't get marked up
3774 		 * to date.  Error out
3775 		 */
3776 		if (block_start == EXTENT_MAP_INLINE) {
3777 			unlock_extent(tree, cur, cur + iosize - 1);
3778 			end_page_read(page, false, cur, iosize);
3779 			cur = cur + iosize;
3780 			pg_offset += iosize;
3781 			continue;
3782 		}
3783 
3784 		ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
3785 					 bio_ctrl, page, disk_bytenr, iosize,
3786 					 pg_offset,
3787 					 end_bio_extent_readpage, 0,
3788 					 this_bio_flag,
3789 					 force_bio_submit);
3790 		if (ret) {
3791 			/*
3792 			 * We have to unlock the remaining range, or the page
3793 			 * will never be unlocked.
3794 			 */
3795 			unlock_extent(tree, cur, end);
3796 			end_page_read(page, false, cur, end + 1 - cur);
3797 			goto out;
3798 		}
3799 		cur = cur + iosize;
3800 		pg_offset += iosize;
3801 	}
3802 out:
3803 	return ret;
3804 }
3805 
btrfs_read_folio(struct file * file,struct folio * folio)3806 int btrfs_read_folio(struct file *file, struct folio *folio)
3807 {
3808 	struct page *page = &folio->page;
3809 	struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3810 	u64 start = page_offset(page);
3811 	u64 end = start + PAGE_SIZE - 1;
3812 	struct btrfs_bio_ctrl bio_ctrl = { 0 };
3813 	int ret;
3814 
3815 	btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
3816 
3817 	ret = btrfs_do_readpage(page, NULL, &bio_ctrl, 0, NULL);
3818 	/*
3819 	 * If btrfs_do_readpage() failed we will want to submit the assembled
3820 	 * bio to do the cleanup.
3821 	 */
3822 	if (bio_ctrl.bio)
3823 		submit_one_bio(bio_ctrl.bio, 0, bio_ctrl.compress_type);
3824 	return ret;
3825 }
3826 
contiguous_readpages(struct page * pages[],int nr_pages,u64 start,u64 end,struct extent_map ** em_cached,struct btrfs_bio_ctrl * bio_ctrl,u64 * prev_em_start)3827 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
3828 					u64 start, u64 end,
3829 					struct extent_map **em_cached,
3830 					struct btrfs_bio_ctrl *bio_ctrl,
3831 					u64 *prev_em_start)
3832 {
3833 	struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
3834 	int index;
3835 
3836 	btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
3837 
3838 	for (index = 0; index < nr_pages; index++) {
3839 		btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
3840 				  REQ_RAHEAD, prev_em_start);
3841 		put_page(pages[index]);
3842 	}
3843 }
3844 
3845 /*
3846  * helper for __extent_writepage, doing all of the delayed allocation setup.
3847  *
3848  * This returns 1 if btrfs_run_delalloc_range function did all the work required
3849  * to write the page (copy into inline extent).  In this case the IO has
3850  * been started and the page is already unlocked.
3851  *
3852  * This returns 0 if all went well (page still locked)
3853  * This returns < 0 if there were errors (page still locked)
3854  */
writepage_delalloc(struct btrfs_inode * inode,struct page * page,struct writeback_control * wbc)3855 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
3856 		struct page *page, struct writeback_control *wbc)
3857 {
3858 	const u64 page_end = page_offset(page) + PAGE_SIZE - 1;
3859 	u64 delalloc_start = page_offset(page);
3860 	u64 delalloc_to_write = 0;
3861 	/* How many pages are started by btrfs_run_delalloc_range() */
3862 	unsigned long nr_written = 0;
3863 	int ret;
3864 	int page_started = 0;
3865 
3866 	while (delalloc_start < page_end) {
3867 		u64 delalloc_end = page_end;
3868 		bool found;
3869 
3870 		found = find_lock_delalloc_range(&inode->vfs_inode, page,
3871 					       &delalloc_start,
3872 					       &delalloc_end);
3873 		if (!found) {
3874 			delalloc_start = delalloc_end + 1;
3875 			continue;
3876 		}
3877 		ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3878 				delalloc_end, &page_started, &nr_written, wbc);
3879 		if (ret) {
3880 			btrfs_page_set_error(inode->root->fs_info, page,
3881 					     page_offset(page), PAGE_SIZE);
3882 			return ret;
3883 		}
3884 		/*
3885 		 * delalloc_end is already one less than the total length, so
3886 		 * we don't subtract one from PAGE_SIZE
3887 		 */
3888 		delalloc_to_write += (delalloc_end - delalloc_start +
3889 				      PAGE_SIZE) >> PAGE_SHIFT;
3890 		delalloc_start = delalloc_end + 1;
3891 	}
3892 	if (wbc->nr_to_write < delalloc_to_write) {
3893 		int thresh = 8192;
3894 
3895 		if (delalloc_to_write < thresh * 2)
3896 			thresh = delalloc_to_write;
3897 		wbc->nr_to_write = min_t(u64, delalloc_to_write,
3898 					 thresh);
3899 	}
3900 
3901 	/* Did btrfs_run_dealloc_range() already unlock and start the IO? */
3902 	if (page_started) {
3903 		/*
3904 		 * We've unlocked the page, so we can't update the mapping's
3905 		 * writeback index, just update nr_to_write.
3906 		 */
3907 		wbc->nr_to_write -= nr_written;
3908 		return 1;
3909 	}
3910 
3911 	return 0;
3912 }
3913 
3914 /*
3915  * Find the first byte we need to write.
3916  *
3917  * For subpage, one page can contain several sectors, and
3918  * __extent_writepage_io() will just grab all extent maps in the page
3919  * range and try to submit all non-inline/non-compressed extents.
3920  *
3921  * This is a big problem for subpage, we shouldn't re-submit already written
3922  * data at all.
3923  * This function will lookup subpage dirty bit to find which range we really
3924  * need to submit.
3925  *
3926  * Return the next dirty range in [@start, @end).
3927  * If no dirty range is found, @start will be page_offset(page) + PAGE_SIZE.
3928  */
find_next_dirty_byte(struct btrfs_fs_info * fs_info,struct page * page,u64 * start,u64 * end)3929 static void find_next_dirty_byte(struct btrfs_fs_info *fs_info,
3930 				 struct page *page, u64 *start, u64 *end)
3931 {
3932 	struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
3933 	struct btrfs_subpage_info *spi = fs_info->subpage_info;
3934 	u64 orig_start = *start;
3935 	/* Declare as unsigned long so we can use bitmap ops */
3936 	unsigned long flags;
3937 	int range_start_bit;
3938 	int range_end_bit;
3939 
3940 	/*
3941 	 * For regular sector size == page size case, since one page only
3942 	 * contains one sector, we return the page offset directly.
3943 	 */
3944 	if (!btrfs_is_subpage(fs_info, page)) {
3945 		*start = page_offset(page);
3946 		*end = page_offset(page) + PAGE_SIZE;
3947 		return;
3948 	}
3949 
3950 	range_start_bit = spi->dirty_offset +
3951 			  (offset_in_page(orig_start) >> fs_info->sectorsize_bits);
3952 
3953 	/* We should have the page locked, but just in case */
3954 	spin_lock_irqsave(&subpage->lock, flags);
3955 	bitmap_next_set_region(subpage->bitmaps, &range_start_bit, &range_end_bit,
3956 			       spi->dirty_offset + spi->bitmap_nr_bits);
3957 	spin_unlock_irqrestore(&subpage->lock, flags);
3958 
3959 	range_start_bit -= spi->dirty_offset;
3960 	range_end_bit -= spi->dirty_offset;
3961 
3962 	*start = page_offset(page) + range_start_bit * fs_info->sectorsize;
3963 	*end = page_offset(page) + range_end_bit * fs_info->sectorsize;
3964 }
3965 
3966 /*
3967  * helper for __extent_writepage.  This calls the writepage start hooks,
3968  * and does the loop to map the page into extents and bios.
3969  *
3970  * We return 1 if the IO is started and the page is unlocked,
3971  * 0 if all went well (page still locked)
3972  * < 0 if there were errors (page still locked)
3973  */
__extent_writepage_io(struct btrfs_inode * inode,struct page * page,struct writeback_control * wbc,struct extent_page_data * epd,loff_t i_size,int * nr_ret)3974 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
3975 				 struct page *page,
3976 				 struct writeback_control *wbc,
3977 				 struct extent_page_data *epd,
3978 				 loff_t i_size,
3979 				 int *nr_ret)
3980 {
3981 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
3982 	u64 cur = page_offset(page);
3983 	u64 end = cur + PAGE_SIZE - 1;
3984 	u64 extent_offset;
3985 	u64 block_start;
3986 	struct extent_map *em;
3987 	int saved_ret = 0;
3988 	int ret = 0;
3989 	int nr = 0;
3990 	u32 opf = REQ_OP_WRITE;
3991 	const unsigned int write_flags = wbc_to_write_flags(wbc);
3992 	bool has_error = false;
3993 	bool compressed;
3994 
3995 	ret = btrfs_writepage_cow_fixup(page);
3996 	if (ret) {
3997 		/* Fixup worker will requeue */
3998 		redirty_page_for_writepage(wbc, page);
3999 		unlock_page(page);
4000 		return 1;
4001 	}
4002 
4003 	/*
4004 	 * we don't want to touch the inode after unlocking the page,
4005 	 * so we update the mapping writeback index now
4006 	 */
4007 	wbc->nr_to_write--;
4008 
4009 	while (cur <= end) {
4010 		u64 disk_bytenr;
4011 		u64 em_end;
4012 		u64 dirty_range_start = cur;
4013 		u64 dirty_range_end;
4014 		u32 iosize;
4015 
4016 		if (cur >= i_size) {
4017 			btrfs_writepage_endio_finish_ordered(inode, page, cur,
4018 							     end, true);
4019 			/*
4020 			 * This range is beyond i_size, thus we don't need to
4021 			 * bother writing back.
4022 			 * But we still need to clear the dirty subpage bit, or
4023 			 * the next time the page gets dirtied, we will try to
4024 			 * writeback the sectors with subpage dirty bits,
4025 			 * causing writeback without ordered extent.
4026 			 */
4027 			btrfs_page_clear_dirty(fs_info, page, cur, end + 1 - cur);
4028 			break;
4029 		}
4030 
4031 		find_next_dirty_byte(fs_info, page, &dirty_range_start,
4032 				     &dirty_range_end);
4033 		if (cur < dirty_range_start) {
4034 			cur = dirty_range_start;
4035 			continue;
4036 		}
4037 
4038 		em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
4039 		if (IS_ERR(em)) {
4040 			btrfs_page_set_error(fs_info, page, cur, end - cur + 1);
4041 			ret = PTR_ERR_OR_ZERO(em);
4042 			has_error = true;
4043 			if (!saved_ret)
4044 				saved_ret = ret;
4045 			break;
4046 		}
4047 
4048 		extent_offset = cur - em->start;
4049 		em_end = extent_map_end(em);
4050 		ASSERT(cur <= em_end);
4051 		ASSERT(cur < end);
4052 		ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
4053 		ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
4054 		block_start = em->block_start;
4055 		compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
4056 		disk_bytenr = em->block_start + extent_offset;
4057 
4058 		/*
4059 		 * Note that em_end from extent_map_end() and dirty_range_end from
4060 		 * find_next_dirty_byte() are all exclusive
4061 		 */
4062 		iosize = min(min(em_end, end + 1), dirty_range_end) - cur;
4063 
4064 		if (btrfs_use_zone_append(inode, em->block_start))
4065 			opf = REQ_OP_ZONE_APPEND;
4066 
4067 		free_extent_map(em);
4068 		em = NULL;
4069 
4070 		/*
4071 		 * compressed and inline extents are written through other
4072 		 * paths in the FS
4073 		 */
4074 		if (compressed || block_start == EXTENT_MAP_HOLE ||
4075 		    block_start == EXTENT_MAP_INLINE) {
4076 			if (compressed)
4077 				nr++;
4078 			else
4079 				btrfs_writepage_endio_finish_ordered(inode,
4080 						page, cur, cur + iosize - 1, true);
4081 			btrfs_page_clear_dirty(fs_info, page, cur, iosize);
4082 			cur += iosize;
4083 			continue;
4084 		}
4085 
4086 		btrfs_set_range_writeback(inode, cur, cur + iosize - 1);
4087 		if (!PageWriteback(page)) {
4088 			btrfs_err(inode->root->fs_info,
4089 				   "page %lu not writeback, cur %llu end %llu",
4090 			       page->index, cur, end);
4091 		}
4092 
4093 		/*
4094 		 * Although the PageDirty bit is cleared before entering this
4095 		 * function, subpage dirty bit is not cleared.
4096 		 * So clear subpage dirty bit here so next time we won't submit
4097 		 * page for range already written to disk.
4098 		 */
4099 		btrfs_page_clear_dirty(fs_info, page, cur, iosize);
4100 
4101 		ret = submit_extent_page(opf | write_flags, wbc,
4102 					 &epd->bio_ctrl, page,
4103 					 disk_bytenr, iosize,
4104 					 cur - page_offset(page),
4105 					 end_bio_extent_writepage,
4106 					 0, 0, false);
4107 		if (ret) {
4108 			has_error = true;
4109 			if (!saved_ret)
4110 				saved_ret = ret;
4111 
4112 			btrfs_page_set_error(fs_info, page, cur, iosize);
4113 			if (PageWriteback(page))
4114 				btrfs_page_clear_writeback(fs_info, page, cur,
4115 							   iosize);
4116 		}
4117 
4118 		cur += iosize;
4119 		nr++;
4120 	}
4121 	/*
4122 	 * If we finish without problem, we should not only clear page dirty,
4123 	 * but also empty subpage dirty bits
4124 	 */
4125 	if (!has_error)
4126 		btrfs_page_assert_not_dirty(fs_info, page);
4127 	else
4128 		ret = saved_ret;
4129 	*nr_ret = nr;
4130 	return ret;
4131 }
4132 
4133 /*
4134  * the writepage semantics are similar to regular writepage.  extent
4135  * records are inserted to lock ranges in the tree, and as dirty areas
4136  * are found, they are marked writeback.  Then the lock bits are removed
4137  * and the end_io handler clears the writeback ranges
4138  *
4139  * Return 0 if everything goes well.
4140  * Return <0 for error.
4141  */
__extent_writepage(struct page * page,struct writeback_control * wbc,struct extent_page_data * epd)4142 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
4143 			      struct extent_page_data *epd)
4144 {
4145 	struct folio *folio = page_folio(page);
4146 	struct inode *inode = page->mapping->host;
4147 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4148 	const u64 page_start = page_offset(page);
4149 	const u64 page_end = page_start + PAGE_SIZE - 1;
4150 	int ret;
4151 	int nr = 0;
4152 	size_t pg_offset;
4153 	loff_t i_size = i_size_read(inode);
4154 	unsigned long end_index = i_size >> PAGE_SHIFT;
4155 
4156 	trace___extent_writepage(page, inode, wbc);
4157 
4158 	WARN_ON(!PageLocked(page));
4159 
4160 	btrfs_page_clear_error(btrfs_sb(inode->i_sb), page,
4161 			       page_offset(page), PAGE_SIZE);
4162 
4163 	pg_offset = offset_in_page(i_size);
4164 	if (page->index > end_index ||
4165 	   (page->index == end_index && !pg_offset)) {
4166 		folio_invalidate(folio, 0, folio_size(folio));
4167 		folio_unlock(folio);
4168 		return 0;
4169 	}
4170 
4171 	if (page->index == end_index) {
4172 		memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
4173 		flush_dcache_page(page);
4174 	}
4175 
4176 	ret = set_page_extent_mapped(page);
4177 	if (ret < 0) {
4178 		SetPageError(page);
4179 		goto done;
4180 	}
4181 
4182 	if (!epd->extent_locked) {
4183 		ret = writepage_delalloc(BTRFS_I(inode), page, wbc);
4184 		if (ret == 1)
4185 			return 0;
4186 		if (ret)
4187 			goto done;
4188 	}
4189 
4190 	ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
4191 				    &nr);
4192 	if (ret == 1)
4193 		return 0;
4194 
4195 done:
4196 	if (nr == 0) {
4197 		/* make sure the mapping tag for page dirty gets cleared */
4198 		set_page_writeback(page);
4199 		end_page_writeback(page);
4200 	}
4201 	/*
4202 	 * Here we used to have a check for PageError() and then set @ret and
4203 	 * call end_extent_writepage().
4204 	 *
4205 	 * But in fact setting @ret here will cause different error paths
4206 	 * between subpage and regular sectorsize.
4207 	 *
4208 	 * For regular page size, we never submit current page, but only add
4209 	 * current page to current bio.
4210 	 * The bio submission can only happen in next page.
4211 	 * Thus if we hit the PageError() branch, @ret is already set to
4212 	 * non-zero value and will not get updated for regular sectorsize.
4213 	 *
4214 	 * But for subpage case, it's possible we submit part of current page,
4215 	 * thus can get PageError() set by submitted bio of the same page,
4216 	 * while our @ret is still 0.
4217 	 *
4218 	 * So here we unify the behavior and don't set @ret.
4219 	 * Error can still be properly passed to higher layer as page will
4220 	 * be set error, here we just don't handle the IO failure.
4221 	 *
4222 	 * NOTE: This is just a hotfix for subpage.
4223 	 * The root fix will be properly ending ordered extent when we hit
4224 	 * an error during writeback.
4225 	 *
4226 	 * But that needs a bigger refactoring, as we not only need to grab the
4227 	 * submitted OE, but also need to know exactly at which bytenr we hit
4228 	 * the error.
4229 	 * Currently the full page based __extent_writepage_io() is not
4230 	 * capable of that.
4231 	 */
4232 	if (PageError(page))
4233 		end_extent_writepage(page, ret, page_start, page_end);
4234 	if (epd->extent_locked) {
4235 		/*
4236 		 * If epd->extent_locked, it's from extent_write_locked_range(),
4237 		 * the page can either be locked by lock_page() or
4238 		 * process_one_page().
4239 		 * Let btrfs_page_unlock_writer() handle both cases.
4240 		 */
4241 		ASSERT(wbc);
4242 		btrfs_page_unlock_writer(fs_info, page, wbc->range_start,
4243 					 wbc->range_end + 1 - wbc->range_start);
4244 	} else {
4245 		unlock_page(page);
4246 	}
4247 	ASSERT(ret <= 0);
4248 	return ret;
4249 }
4250 
wait_on_extent_buffer_writeback(struct extent_buffer * eb)4251 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
4252 {
4253 	wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
4254 		       TASK_UNINTERRUPTIBLE);
4255 }
4256 
end_extent_buffer_writeback(struct extent_buffer * eb)4257 static void end_extent_buffer_writeback(struct extent_buffer *eb)
4258 {
4259 	clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
4260 	smp_mb__after_atomic();
4261 	wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
4262 }
4263 
4264 /*
4265  * Lock extent buffer status and pages for writeback.
4266  *
4267  * May try to flush write bio if we can't get the lock.
4268  *
4269  * Return  0 if the extent buffer doesn't need to be submitted.
4270  *           (E.g. the extent buffer is not dirty)
4271  * Return >0 is the extent buffer is submitted to bio.
4272  * Return <0 if something went wrong, no page is locked.
4273  */
lock_extent_buffer_for_io(struct extent_buffer * eb,struct extent_page_data * epd)4274 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
4275 			  struct extent_page_data *epd)
4276 {
4277 	struct btrfs_fs_info *fs_info = eb->fs_info;
4278 	int i, num_pages;
4279 	int flush = 0;
4280 	int ret = 0;
4281 
4282 	if (!btrfs_try_tree_write_lock(eb)) {
4283 		flush_write_bio(epd);
4284 		flush = 1;
4285 		btrfs_tree_lock(eb);
4286 	}
4287 
4288 	if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
4289 		btrfs_tree_unlock(eb);
4290 		if (!epd->sync_io)
4291 			return 0;
4292 		if (!flush) {
4293 			flush_write_bio(epd);
4294 			flush = 1;
4295 		}
4296 		while (1) {
4297 			wait_on_extent_buffer_writeback(eb);
4298 			btrfs_tree_lock(eb);
4299 			if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
4300 				break;
4301 			btrfs_tree_unlock(eb);
4302 		}
4303 	}
4304 
4305 	/*
4306 	 * We need to do this to prevent races in people who check if the eb is
4307 	 * under IO since we can end up having no IO bits set for a short period
4308 	 * of time.
4309 	 */
4310 	spin_lock(&eb->refs_lock);
4311 	if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
4312 		set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
4313 		spin_unlock(&eb->refs_lock);
4314 		btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
4315 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4316 					 -eb->len,
4317 					 fs_info->dirty_metadata_batch);
4318 		ret = 1;
4319 	} else {
4320 		spin_unlock(&eb->refs_lock);
4321 	}
4322 
4323 	btrfs_tree_unlock(eb);
4324 
4325 	/*
4326 	 * Either we don't need to submit any tree block, or we're submitting
4327 	 * subpage eb.
4328 	 * Subpage metadata doesn't use page locking at all, so we can skip
4329 	 * the page locking.
4330 	 */
4331 	if (!ret || fs_info->nodesize < PAGE_SIZE)
4332 		return ret;
4333 
4334 	num_pages = num_extent_pages(eb);
4335 	for (i = 0; i < num_pages; i++) {
4336 		struct page *p = eb->pages[i];
4337 
4338 		if (!trylock_page(p)) {
4339 			if (!flush) {
4340 				flush_write_bio(epd);
4341 				flush = 1;
4342 			}
4343 			lock_page(p);
4344 		}
4345 	}
4346 
4347 	return ret;
4348 }
4349 
set_btree_ioerr(struct page * page,struct extent_buffer * eb)4350 static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
4351 {
4352 	struct btrfs_fs_info *fs_info = eb->fs_info;
4353 
4354 	btrfs_page_set_error(fs_info, page, eb->start, eb->len);
4355 	if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
4356 		return;
4357 
4358 	/*
4359 	 * A read may stumble upon this buffer later, make sure that it gets an
4360 	 * error and knows there was an error.
4361 	 */
4362 	clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4363 
4364 	/*
4365 	 * We need to set the mapping with the io error as well because a write
4366 	 * error will flip the file system readonly, and then syncfs() will
4367 	 * return a 0 because we are readonly if we don't modify the err seq for
4368 	 * the superblock.
4369 	 */
4370 	mapping_set_error(page->mapping, -EIO);
4371 
4372 	/*
4373 	 * If we error out, we should add back the dirty_metadata_bytes
4374 	 * to make it consistent.
4375 	 */
4376 	percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4377 				 eb->len, fs_info->dirty_metadata_batch);
4378 
4379 	/*
4380 	 * If writeback for a btree extent that doesn't belong to a log tree
4381 	 * failed, increment the counter transaction->eb_write_errors.
4382 	 * We do this because while the transaction is running and before it's
4383 	 * committing (when we call filemap_fdata[write|wait]_range against
4384 	 * the btree inode), we might have
4385 	 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
4386 	 * returns an error or an error happens during writeback, when we're
4387 	 * committing the transaction we wouldn't know about it, since the pages
4388 	 * can be no longer dirty nor marked anymore for writeback (if a
4389 	 * subsequent modification to the extent buffer didn't happen before the
4390 	 * transaction commit), which makes filemap_fdata[write|wait]_range not
4391 	 * able to find the pages tagged with SetPageError at transaction
4392 	 * commit time. So if this happens we must abort the transaction,
4393 	 * otherwise we commit a super block with btree roots that point to
4394 	 * btree nodes/leafs whose content on disk is invalid - either garbage
4395 	 * or the content of some node/leaf from a past generation that got
4396 	 * cowed or deleted and is no longer valid.
4397 	 *
4398 	 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
4399 	 * not be enough - we need to distinguish between log tree extents vs
4400 	 * non-log tree extents, and the next filemap_fdatawait_range() call
4401 	 * will catch and clear such errors in the mapping - and that call might
4402 	 * be from a log sync and not from a transaction commit. Also, checking
4403 	 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
4404 	 * not done and would not be reliable - the eb might have been released
4405 	 * from memory and reading it back again means that flag would not be
4406 	 * set (since it's a runtime flag, not persisted on disk).
4407 	 *
4408 	 * Using the flags below in the btree inode also makes us achieve the
4409 	 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
4410 	 * writeback for all dirty pages and before filemap_fdatawait_range()
4411 	 * is called, the writeback for all dirty pages had already finished
4412 	 * with errors - because we were not using AS_EIO/AS_ENOSPC,
4413 	 * filemap_fdatawait_range() would return success, as it could not know
4414 	 * that writeback errors happened (the pages were no longer tagged for
4415 	 * writeback).
4416 	 */
4417 	switch (eb->log_index) {
4418 	case -1:
4419 		set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
4420 		break;
4421 	case 0:
4422 		set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
4423 		break;
4424 	case 1:
4425 		set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
4426 		break;
4427 	default:
4428 		BUG(); /* unexpected, logic error */
4429 	}
4430 }
4431 
4432 /*
4433  * The endio specific version which won't touch any unsafe spinlock in endio
4434  * context.
4435  */
find_extent_buffer_nolock(struct btrfs_fs_info * fs_info,u64 start)4436 static struct extent_buffer *find_extent_buffer_nolock(
4437 		struct btrfs_fs_info *fs_info, u64 start)
4438 {
4439 	struct extent_buffer *eb;
4440 
4441 	rcu_read_lock();
4442 	eb = radix_tree_lookup(&fs_info->buffer_radix,
4443 			       start >> fs_info->sectorsize_bits);
4444 	if (eb && atomic_inc_not_zero(&eb->refs)) {
4445 		rcu_read_unlock();
4446 		return eb;
4447 	}
4448 	rcu_read_unlock();
4449 	return NULL;
4450 }
4451 
4452 /*
4453  * The endio function for subpage extent buffer write.
4454  *
4455  * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
4456  * after all extent buffers in the page has finished their writeback.
4457  */
end_bio_subpage_eb_writepage(struct bio * bio)4458 static void end_bio_subpage_eb_writepage(struct bio *bio)
4459 {
4460 	struct btrfs_fs_info *fs_info;
4461 	struct bio_vec *bvec;
4462 	struct bvec_iter_all iter_all;
4463 
4464 	fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
4465 	ASSERT(fs_info->nodesize < PAGE_SIZE);
4466 
4467 	ASSERT(!bio_flagged(bio, BIO_CLONED));
4468 	bio_for_each_segment_all(bvec, bio, iter_all) {
4469 		struct page *page = bvec->bv_page;
4470 		u64 bvec_start = page_offset(page) + bvec->bv_offset;
4471 		u64 bvec_end = bvec_start + bvec->bv_len - 1;
4472 		u64 cur_bytenr = bvec_start;
4473 
4474 		ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
4475 
4476 		/* Iterate through all extent buffers in the range */
4477 		while (cur_bytenr <= bvec_end) {
4478 			struct extent_buffer *eb;
4479 			int done;
4480 
4481 			/*
4482 			 * Here we can't use find_extent_buffer(), as it may
4483 			 * try to lock eb->refs_lock, which is not safe in endio
4484 			 * context.
4485 			 */
4486 			eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
4487 			ASSERT(eb);
4488 
4489 			cur_bytenr = eb->start + eb->len;
4490 
4491 			ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
4492 			done = atomic_dec_and_test(&eb->io_pages);
4493 			ASSERT(done);
4494 
4495 			if (bio->bi_status ||
4496 			    test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4497 				ClearPageUptodate(page);
4498 				set_btree_ioerr(page, eb);
4499 			}
4500 
4501 			btrfs_subpage_clear_writeback(fs_info, page, eb->start,
4502 						      eb->len);
4503 			end_extent_buffer_writeback(eb);
4504 			/*
4505 			 * free_extent_buffer() will grab spinlock which is not
4506 			 * safe in endio context. Thus here we manually dec
4507 			 * the ref.
4508 			 */
4509 			atomic_dec(&eb->refs);
4510 		}
4511 	}
4512 	bio_put(bio);
4513 }
4514 
end_bio_extent_buffer_writepage(struct bio * bio)4515 static void end_bio_extent_buffer_writepage(struct bio *bio)
4516 {
4517 	struct bio_vec *bvec;
4518 	struct extent_buffer *eb;
4519 	int done;
4520 	struct bvec_iter_all iter_all;
4521 
4522 	ASSERT(!bio_flagged(bio, BIO_CLONED));
4523 	bio_for_each_segment_all(bvec, bio, iter_all) {
4524 		struct page *page = bvec->bv_page;
4525 
4526 		eb = (struct extent_buffer *)page->private;
4527 		BUG_ON(!eb);
4528 		done = atomic_dec_and_test(&eb->io_pages);
4529 
4530 		if (bio->bi_status ||
4531 		    test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4532 			ClearPageUptodate(page);
4533 			set_btree_ioerr(page, eb);
4534 		}
4535 
4536 		end_page_writeback(page);
4537 
4538 		if (!done)
4539 			continue;
4540 
4541 		end_extent_buffer_writeback(eb);
4542 	}
4543 
4544 	bio_put(bio);
4545 }
4546 
prepare_eb_write(struct extent_buffer * eb)4547 static void prepare_eb_write(struct extent_buffer *eb)
4548 {
4549 	u32 nritems;
4550 	unsigned long start;
4551 	unsigned long end;
4552 
4553 	clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
4554 	atomic_set(&eb->io_pages, num_extent_pages(eb));
4555 
4556 	/* Set btree blocks beyond nritems with 0 to avoid stale content */
4557 	nritems = btrfs_header_nritems(eb);
4558 	if (btrfs_header_level(eb) > 0) {
4559 		end = btrfs_node_key_ptr_offset(nritems);
4560 		memzero_extent_buffer(eb, end, eb->len - end);
4561 	} else {
4562 		/*
4563 		 * Leaf:
4564 		 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
4565 		 */
4566 		start = btrfs_item_nr_offset(nritems);
4567 		end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
4568 		memzero_extent_buffer(eb, start, end - start);
4569 	}
4570 }
4571 
4572 /*
4573  * Unlike the work in write_one_eb(), we rely completely on extent locking.
4574  * Page locking is only utilized at minimum to keep the VMM code happy.
4575  */
write_one_subpage_eb(struct extent_buffer * eb,struct writeback_control * wbc,struct extent_page_data * epd)4576 static int write_one_subpage_eb(struct extent_buffer *eb,
4577 				struct writeback_control *wbc,
4578 				struct extent_page_data *epd)
4579 {
4580 	struct btrfs_fs_info *fs_info = eb->fs_info;
4581 	struct page *page = eb->pages[0];
4582 	unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4583 	bool no_dirty_ebs = false;
4584 	int ret;
4585 
4586 	prepare_eb_write(eb);
4587 
4588 	/* clear_page_dirty_for_io() in subpage helper needs page locked */
4589 	lock_page(page);
4590 	btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
4591 
4592 	/* Check if this is the last dirty bit to update nr_written */
4593 	no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
4594 							  eb->start, eb->len);
4595 	if (no_dirty_ebs)
4596 		clear_page_dirty_for_io(page);
4597 
4598 	ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4599 			&epd->bio_ctrl, page, eb->start, eb->len,
4600 			eb->start - page_offset(page),
4601 			end_bio_subpage_eb_writepage, 0, 0, false);
4602 	if (ret) {
4603 		btrfs_subpage_clear_writeback(fs_info, page, eb->start, eb->len);
4604 		set_btree_ioerr(page, eb);
4605 		unlock_page(page);
4606 
4607 		if (atomic_dec_and_test(&eb->io_pages))
4608 			end_extent_buffer_writeback(eb);
4609 		return -EIO;
4610 	}
4611 	unlock_page(page);
4612 	/*
4613 	 * Submission finished without problem, if no range of the page is
4614 	 * dirty anymore, we have submitted a page.  Update nr_written in wbc.
4615 	 */
4616 	if (no_dirty_ebs)
4617 		wbc->nr_to_write--;
4618 	return ret;
4619 }
4620 
write_one_eb(struct extent_buffer * eb,struct writeback_control * wbc,struct extent_page_data * epd)4621 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
4622 			struct writeback_control *wbc,
4623 			struct extent_page_data *epd)
4624 {
4625 	u64 disk_bytenr = eb->start;
4626 	int i, num_pages;
4627 	unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4628 	int ret = 0;
4629 
4630 	prepare_eb_write(eb);
4631 
4632 	num_pages = num_extent_pages(eb);
4633 	for (i = 0; i < num_pages; i++) {
4634 		struct page *p = eb->pages[i];
4635 
4636 		clear_page_dirty_for_io(p);
4637 		set_page_writeback(p);
4638 		ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
4639 					 &epd->bio_ctrl, p, disk_bytenr,
4640 					 PAGE_SIZE, 0,
4641 					 end_bio_extent_buffer_writepage,
4642 					 0, 0, false);
4643 		if (ret) {
4644 			set_btree_ioerr(p, eb);
4645 			if (PageWriteback(p))
4646 				end_page_writeback(p);
4647 			if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
4648 				end_extent_buffer_writeback(eb);
4649 			ret = -EIO;
4650 			break;
4651 		}
4652 		disk_bytenr += PAGE_SIZE;
4653 		wbc->nr_to_write--;
4654 		unlock_page(p);
4655 	}
4656 
4657 	if (unlikely(ret)) {
4658 		for (; i < num_pages; i++) {
4659 			struct page *p = eb->pages[i];
4660 			clear_page_dirty_for_io(p);
4661 			unlock_page(p);
4662 		}
4663 	}
4664 
4665 	return ret;
4666 }
4667 
4668 /*
4669  * Submit one subpage btree page.
4670  *
4671  * The main difference to submit_eb_page() is:
4672  * - Page locking
4673  *   For subpage, we don't rely on page locking at all.
4674  *
4675  * - Flush write bio
4676  *   We only flush bio if we may be unable to fit current extent buffers into
4677  *   current bio.
4678  *
4679  * Return >=0 for the number of submitted extent buffers.
4680  * Return <0 for fatal error.
4681  */
submit_eb_subpage(struct page * page,struct writeback_control * wbc,struct extent_page_data * epd)4682 static int submit_eb_subpage(struct page *page,
4683 			     struct writeback_control *wbc,
4684 			     struct extent_page_data *epd)
4685 {
4686 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
4687 	int submitted = 0;
4688 	u64 page_start = page_offset(page);
4689 	int bit_start = 0;
4690 	int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
4691 	int ret;
4692 
4693 	/* Lock and write each dirty extent buffers in the range */
4694 	while (bit_start < fs_info->subpage_info->bitmap_nr_bits) {
4695 		struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
4696 		struct extent_buffer *eb;
4697 		unsigned long flags;
4698 		u64 start;
4699 
4700 		/*
4701 		 * Take private lock to ensure the subpage won't be detached
4702 		 * in the meantime.
4703 		 */
4704 		spin_lock(&page->mapping->private_lock);
4705 		if (!PagePrivate(page)) {
4706 			spin_unlock(&page->mapping->private_lock);
4707 			break;
4708 		}
4709 		spin_lock_irqsave(&subpage->lock, flags);
4710 		if (!test_bit(bit_start + fs_info->subpage_info->dirty_offset,
4711 			      subpage->bitmaps)) {
4712 			spin_unlock_irqrestore(&subpage->lock, flags);
4713 			spin_unlock(&page->mapping->private_lock);
4714 			bit_start++;
4715 			continue;
4716 		}
4717 
4718 		start = page_start + bit_start * fs_info->sectorsize;
4719 		bit_start += sectors_per_node;
4720 
4721 		/*
4722 		 * Here we just want to grab the eb without touching extra
4723 		 * spin locks, so call find_extent_buffer_nolock().
4724 		 */
4725 		eb = find_extent_buffer_nolock(fs_info, start);
4726 		spin_unlock_irqrestore(&subpage->lock, flags);
4727 		spin_unlock(&page->mapping->private_lock);
4728 
4729 		/*
4730 		 * The eb has already reached 0 refs thus find_extent_buffer()
4731 		 * doesn't return it. We don't need to write back such eb
4732 		 * anyway.
4733 		 */
4734 		if (!eb)
4735 			continue;
4736 
4737 		ret = lock_extent_buffer_for_io(eb, epd);
4738 		if (ret == 0) {
4739 			free_extent_buffer(eb);
4740 			continue;
4741 		}
4742 		if (ret < 0) {
4743 			free_extent_buffer(eb);
4744 			goto cleanup;
4745 		}
4746 		ret = write_one_subpage_eb(eb, wbc, epd);
4747 		free_extent_buffer(eb);
4748 		if (ret < 0)
4749 			goto cleanup;
4750 		submitted++;
4751 	}
4752 	return submitted;
4753 
4754 cleanup:
4755 	/* We hit error, end bio for the submitted extent buffers */
4756 	end_write_bio(epd, ret);
4757 	return ret;
4758 }
4759 
4760 /*
4761  * Submit all page(s) of one extent buffer.
4762  *
4763  * @page:	the page of one extent buffer
4764  * @eb_context:	to determine if we need to submit this page, if current page
4765  *		belongs to this eb, we don't need to submit
4766  *
4767  * The caller should pass each page in their bytenr order, and here we use
4768  * @eb_context to determine if we have submitted pages of one extent buffer.
4769  *
4770  * If we have, we just skip until we hit a new page that doesn't belong to
4771  * current @eb_context.
4772  *
4773  * If not, we submit all the page(s) of the extent buffer.
4774  *
4775  * Return >0 if we have submitted the extent buffer successfully.
4776  * Return 0 if we don't need to submit the page, as it's already submitted by
4777  * previous call.
4778  * Return <0 for fatal error.
4779  */
submit_eb_page(struct page * page,struct writeback_control * wbc,struct extent_page_data * epd,struct extent_buffer ** eb_context)4780 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
4781 			  struct extent_page_data *epd,
4782 			  struct extent_buffer **eb_context)
4783 {
4784 	struct address_space *mapping = page->mapping;
4785 	struct btrfs_block_group *cache = NULL;
4786 	struct extent_buffer *eb;
4787 	int ret;
4788 
4789 	if (!PagePrivate(page))
4790 		return 0;
4791 
4792 	if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
4793 		return submit_eb_subpage(page, wbc, epd);
4794 
4795 	spin_lock(&mapping->private_lock);
4796 	if (!PagePrivate(page)) {
4797 		spin_unlock(&mapping->private_lock);
4798 		return 0;
4799 	}
4800 
4801 	eb = (struct extent_buffer *)page->private;
4802 
4803 	/*
4804 	 * Shouldn't happen and normally this would be a BUG_ON but no point
4805 	 * crashing the machine for something we can survive anyway.
4806 	 */
4807 	if (WARN_ON(!eb)) {
4808 		spin_unlock(&mapping->private_lock);
4809 		return 0;
4810 	}
4811 
4812 	if (eb == *eb_context) {
4813 		spin_unlock(&mapping->private_lock);
4814 		return 0;
4815 	}
4816 	ret = atomic_inc_not_zero(&eb->refs);
4817 	spin_unlock(&mapping->private_lock);
4818 	if (!ret)
4819 		return 0;
4820 
4821 	if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
4822 		/*
4823 		 * If for_sync, this hole will be filled with
4824 		 * trasnsaction commit.
4825 		 */
4826 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4827 			ret = -EAGAIN;
4828 		else
4829 			ret = 0;
4830 		free_extent_buffer(eb);
4831 		return ret;
4832 	}
4833 
4834 	*eb_context = eb;
4835 
4836 	ret = lock_extent_buffer_for_io(eb, epd);
4837 	if (ret <= 0) {
4838 		btrfs_revert_meta_write_pointer(cache, eb);
4839 		if (cache)
4840 			btrfs_put_block_group(cache);
4841 		free_extent_buffer(eb);
4842 		return ret;
4843 	}
4844 	if (cache) {
4845 		/*
4846 		 * Implies write in zoned mode. Mark the last eb in a block group.
4847 		 */
4848 		btrfs_schedule_zone_finish_bg(cache, eb);
4849 		btrfs_put_block_group(cache);
4850 	}
4851 	ret = write_one_eb(eb, wbc, epd);
4852 	free_extent_buffer(eb);
4853 	if (ret < 0)
4854 		return ret;
4855 	return 1;
4856 }
4857 
btree_write_cache_pages(struct address_space * mapping,struct writeback_control * wbc)4858 int btree_write_cache_pages(struct address_space *mapping,
4859 				   struct writeback_control *wbc)
4860 {
4861 	struct extent_buffer *eb_context = NULL;
4862 	struct extent_page_data epd = {
4863 		.bio_ctrl = { 0 },
4864 		.extent_locked = 0,
4865 		.sync_io = wbc->sync_mode == WB_SYNC_ALL,
4866 	};
4867 	struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
4868 	int ret = 0;
4869 	int done = 0;
4870 	int nr_to_write_done = 0;
4871 	struct pagevec pvec;
4872 	int nr_pages;
4873 	pgoff_t index;
4874 	pgoff_t end;		/* Inclusive */
4875 	int scanned = 0;
4876 	xa_mark_t tag;
4877 
4878 	pagevec_init(&pvec);
4879 	if (wbc->range_cyclic) {
4880 		index = mapping->writeback_index; /* Start from prev offset */
4881 		end = -1;
4882 		/*
4883 		 * Start from the beginning does not need to cycle over the
4884 		 * range, mark it as scanned.
4885 		 */
4886 		scanned = (index == 0);
4887 	} else {
4888 		index = wbc->range_start >> PAGE_SHIFT;
4889 		end = wbc->range_end >> PAGE_SHIFT;
4890 		scanned = 1;
4891 	}
4892 	if (wbc->sync_mode == WB_SYNC_ALL)
4893 		tag = PAGECACHE_TAG_TOWRITE;
4894 	else
4895 		tag = PAGECACHE_TAG_DIRTY;
4896 	btrfs_zoned_meta_io_lock(fs_info);
4897 retry:
4898 	if (wbc->sync_mode == WB_SYNC_ALL)
4899 		tag_pages_for_writeback(mapping, index, end);
4900 	while (!done && !nr_to_write_done && (index <= end) &&
4901 	       (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
4902 			tag))) {
4903 		unsigned i;
4904 
4905 		for (i = 0; i < nr_pages; i++) {
4906 			struct page *page = pvec.pages[i];
4907 
4908 			ret = submit_eb_page(page, wbc, &epd, &eb_context);
4909 			if (ret == 0)
4910 				continue;
4911 			if (ret < 0) {
4912 				done = 1;
4913 				break;
4914 			}
4915 
4916 			/*
4917 			 * the filesystem may choose to bump up nr_to_write.
4918 			 * We have to make sure to honor the new nr_to_write
4919 			 * at any time
4920 			 */
4921 			nr_to_write_done = wbc->nr_to_write <= 0;
4922 		}
4923 		pagevec_release(&pvec);
4924 		cond_resched();
4925 	}
4926 	if (!scanned && !done) {
4927 		/*
4928 		 * We hit the last page and there is more work to be done: wrap
4929 		 * back to the start of the file
4930 		 */
4931 		scanned = 1;
4932 		index = 0;
4933 		goto retry;
4934 	}
4935 	if (ret < 0) {
4936 		end_write_bio(&epd, ret);
4937 		goto out;
4938 	}
4939 	/*
4940 	 * If something went wrong, don't allow any metadata write bio to be
4941 	 * submitted.
4942 	 *
4943 	 * This would prevent use-after-free if we had dirty pages not
4944 	 * cleaned up, which can still happen by fuzzed images.
4945 	 *
4946 	 * - Bad extent tree
4947 	 *   Allowing existing tree block to be allocated for other trees.
4948 	 *
4949 	 * - Log tree operations
4950 	 *   Exiting tree blocks get allocated to log tree, bumps its
4951 	 *   generation, then get cleaned in tree re-balance.
4952 	 *   Such tree block will not be written back, since it's clean,
4953 	 *   thus no WRITTEN flag set.
4954 	 *   And after log writes back, this tree block is not traced by
4955 	 *   any dirty extent_io_tree.
4956 	 *
4957 	 * - Offending tree block gets re-dirtied from its original owner
4958 	 *   Since it has bumped generation, no WRITTEN flag, it can be
4959 	 *   reused without COWing. This tree block will not be traced
4960 	 *   by btrfs_transaction::dirty_pages.
4961 	 *
4962 	 *   Now such dirty tree block will not be cleaned by any dirty
4963 	 *   extent io tree. Thus we don't want to submit such wild eb
4964 	 *   if the fs already has error.
4965 	 */
4966 	if (!BTRFS_FS_ERROR(fs_info)) {
4967 		flush_write_bio(&epd);
4968 	} else {
4969 		ret = -EROFS;
4970 		end_write_bio(&epd, ret);
4971 	}
4972 out:
4973 	btrfs_zoned_meta_io_unlock(fs_info);
4974 	/*
4975 	 * We can get ret > 0 from submit_extent_page() indicating how many ebs
4976 	 * were submitted. Reset it to 0 to avoid false alerts for the caller.
4977 	 */
4978 	if (ret > 0)
4979 		ret = 0;
4980 	return ret;
4981 }
4982 
4983 /**
4984  * Walk the list of dirty pages of the given address space and write all of them.
4985  *
4986  * @mapping: address space structure to write
4987  * @wbc:     subtract the number of written pages from *@wbc->nr_to_write
4988  * @epd:     holds context for the write, namely the bio
4989  *
4990  * If a page is already under I/O, write_cache_pages() skips it, even
4991  * if it's dirty.  This is desirable behaviour for memory-cleaning writeback,
4992  * but it is INCORRECT for data-integrity system calls such as fsync().  fsync()
4993  * and msync() need to guarantee that all the data which was dirty at the time
4994  * the call was made get new I/O started against them.  If wbc->sync_mode is
4995  * WB_SYNC_ALL then we were called for data integrity and we must wait for
4996  * existing IO to complete.
4997  */
extent_write_cache_pages(struct address_space * mapping,struct writeback_control * wbc,struct extent_page_data * epd)4998 static int extent_write_cache_pages(struct address_space *mapping,
4999 			     struct writeback_control *wbc,
5000 			     struct extent_page_data *epd)
5001 {
5002 	struct inode *inode = mapping->host;
5003 	int ret = 0;
5004 	int done = 0;
5005 	int nr_to_write_done = 0;
5006 	struct pagevec pvec;
5007 	int nr_pages;
5008 	pgoff_t index;
5009 	pgoff_t end;		/* Inclusive */
5010 	pgoff_t done_index;
5011 	int range_whole = 0;
5012 	int scanned = 0;
5013 	xa_mark_t tag;
5014 
5015 	/*
5016 	 * We have to hold onto the inode so that ordered extents can do their
5017 	 * work when the IO finishes.  The alternative to this is failing to add
5018 	 * an ordered extent if the igrab() fails there and that is a huge pain
5019 	 * to deal with, so instead just hold onto the inode throughout the
5020 	 * writepages operation.  If it fails here we are freeing up the inode
5021 	 * anyway and we'd rather not waste our time writing out stuff that is
5022 	 * going to be truncated anyway.
5023 	 */
5024 	if (!igrab(inode))
5025 		return 0;
5026 
5027 	pagevec_init(&pvec);
5028 	if (wbc->range_cyclic) {
5029 		index = mapping->writeback_index; /* Start from prev offset */
5030 		end = -1;
5031 		/*
5032 		 * Start from the beginning does not need to cycle over the
5033 		 * range, mark it as scanned.
5034 		 */
5035 		scanned = (index == 0);
5036 	} else {
5037 		index = wbc->range_start >> PAGE_SHIFT;
5038 		end = wbc->range_end >> PAGE_SHIFT;
5039 		if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
5040 			range_whole = 1;
5041 		scanned = 1;
5042 	}
5043 
5044 	/*
5045 	 * We do the tagged writepage as long as the snapshot flush bit is set
5046 	 * and we are the first one who do the filemap_flush() on this inode.
5047 	 *
5048 	 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
5049 	 * not race in and drop the bit.
5050 	 */
5051 	if (range_whole && wbc->nr_to_write == LONG_MAX &&
5052 	    test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
5053 			       &BTRFS_I(inode)->runtime_flags))
5054 		wbc->tagged_writepages = 1;
5055 
5056 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
5057 		tag = PAGECACHE_TAG_TOWRITE;
5058 	else
5059 		tag = PAGECACHE_TAG_DIRTY;
5060 retry:
5061 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
5062 		tag_pages_for_writeback(mapping, index, end);
5063 	done_index = index;
5064 	while (!done && !nr_to_write_done && (index <= end) &&
5065 			(nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
5066 						&index, end, tag))) {
5067 		unsigned i;
5068 
5069 		for (i = 0; i < nr_pages; i++) {
5070 			struct page *page = pvec.pages[i];
5071 
5072 			done_index = page->index + 1;
5073 			/*
5074 			 * At this point we hold neither the i_pages lock nor
5075 			 * the page lock: the page may be truncated or
5076 			 * invalidated (changing page->mapping to NULL),
5077 			 * or even swizzled back from swapper_space to
5078 			 * tmpfs file mapping
5079 			 */
5080 			if (!trylock_page(page)) {
5081 				flush_write_bio(epd);
5082 				lock_page(page);
5083 			}
5084 
5085 			if (unlikely(page->mapping != mapping)) {
5086 				unlock_page(page);
5087 				continue;
5088 			}
5089 
5090 			if (wbc->sync_mode != WB_SYNC_NONE) {
5091 				if (PageWriteback(page))
5092 					flush_write_bio(epd);
5093 				wait_on_page_writeback(page);
5094 			}
5095 
5096 			if (PageWriteback(page) ||
5097 			    !clear_page_dirty_for_io(page)) {
5098 				unlock_page(page);
5099 				continue;
5100 			}
5101 
5102 			ret = __extent_writepage(page, wbc, epd);
5103 			if (ret < 0) {
5104 				done = 1;
5105 				break;
5106 			}
5107 
5108 			/*
5109 			 * the filesystem may choose to bump up nr_to_write.
5110 			 * We have to make sure to honor the new nr_to_write
5111 			 * at any time
5112 			 */
5113 			nr_to_write_done = wbc->nr_to_write <= 0;
5114 		}
5115 		pagevec_release(&pvec);
5116 		cond_resched();
5117 	}
5118 	if (!scanned && !done) {
5119 		/*
5120 		 * We hit the last page and there is more work to be done: wrap
5121 		 * back to the start of the file
5122 		 */
5123 		scanned = 1;
5124 		index = 0;
5125 
5126 		/*
5127 		 * If we're looping we could run into a page that is locked by a
5128 		 * writer and that writer could be waiting on writeback for a
5129 		 * page in our current bio, and thus deadlock, so flush the
5130 		 * write bio here.
5131 		 */
5132 		flush_write_bio(epd);
5133 		goto retry;
5134 	}
5135 
5136 	if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
5137 		mapping->writeback_index = done_index;
5138 
5139 	btrfs_add_delayed_iput(inode);
5140 	return ret;
5141 }
5142 
extent_write_full_page(struct page * page,struct writeback_control * wbc)5143 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
5144 {
5145 	int ret;
5146 	struct extent_page_data epd = {
5147 		.bio_ctrl = { 0 },
5148 		.extent_locked = 0,
5149 		.sync_io = wbc->sync_mode == WB_SYNC_ALL,
5150 	};
5151 
5152 	ret = __extent_writepage(page, wbc, &epd);
5153 	ASSERT(ret <= 0);
5154 	if (ret < 0) {
5155 		end_write_bio(&epd, ret);
5156 		return ret;
5157 	}
5158 
5159 	flush_write_bio(&epd);
5160 	return ret;
5161 }
5162 
5163 /*
5164  * Submit the pages in the range to bio for call sites which delalloc range has
5165  * already been ran (aka, ordered extent inserted) and all pages are still
5166  * locked.
5167  */
extent_write_locked_range(struct inode * inode,u64 start,u64 end)5168 int extent_write_locked_range(struct inode *inode, u64 start, u64 end)
5169 {
5170 	bool found_error = false;
5171 	int first_error = 0;
5172 	int ret = 0;
5173 	struct address_space *mapping = inode->i_mapping;
5174 	struct page *page;
5175 	u64 cur = start;
5176 	unsigned long nr_pages;
5177 	const u32 sectorsize = btrfs_sb(inode->i_sb)->sectorsize;
5178 	struct extent_page_data epd = {
5179 		.bio_ctrl = { 0 },
5180 		.extent_locked = 1,
5181 		.sync_io = 1,
5182 	};
5183 	struct writeback_control wbc_writepages = {
5184 		.sync_mode	= WB_SYNC_ALL,
5185 		.range_start	= start,
5186 		.range_end	= end + 1,
5187 		/* We're called from an async helper function */
5188 		.punt_to_cgroup	= 1,
5189 		.no_cgroup_owner = 1,
5190 	};
5191 
5192 	ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
5193 	nr_pages = (round_up(end, PAGE_SIZE) - round_down(start, PAGE_SIZE)) >>
5194 		   PAGE_SHIFT;
5195 	wbc_writepages.nr_to_write = nr_pages * 2;
5196 
5197 	wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
5198 	while (cur <= end) {
5199 		u64 cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
5200 
5201 		page = find_get_page(mapping, cur >> PAGE_SHIFT);
5202 		/*
5203 		 * All pages in the range are locked since
5204 		 * btrfs_run_delalloc_range(), thus there is no way to clear
5205 		 * the page dirty flag.
5206 		 */
5207 		ASSERT(PageLocked(page));
5208 		ASSERT(PageDirty(page));
5209 		clear_page_dirty_for_io(page);
5210 		ret = __extent_writepage(page, &wbc_writepages, &epd);
5211 		ASSERT(ret <= 0);
5212 		if (ret < 0) {
5213 			found_error = true;
5214 			first_error = ret;
5215 		}
5216 		put_page(page);
5217 		cur = cur_end + 1;
5218 	}
5219 
5220 	if (!found_error)
5221 		flush_write_bio(&epd);
5222 	else
5223 		end_write_bio(&epd, ret);
5224 
5225 	wbc_detach_inode(&wbc_writepages);
5226 	if (found_error)
5227 		return first_error;
5228 	return ret;
5229 }
5230 
extent_writepages(struct address_space * mapping,struct writeback_control * wbc)5231 int extent_writepages(struct address_space *mapping,
5232 		      struct writeback_control *wbc)
5233 {
5234 	struct inode *inode = mapping->host;
5235 	int ret = 0;
5236 	struct extent_page_data epd = {
5237 		.bio_ctrl = { 0 },
5238 		.extent_locked = 0,
5239 		.sync_io = wbc->sync_mode == WB_SYNC_ALL,
5240 	};
5241 
5242 	/*
5243 	 * Allow only a single thread to do the reloc work in zoned mode to
5244 	 * protect the write pointer updates.
5245 	 */
5246 	btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
5247 	ret = extent_write_cache_pages(mapping, wbc, &epd);
5248 	ASSERT(ret <= 0);
5249 	if (ret < 0) {
5250 		btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
5251 		end_write_bio(&epd, ret);
5252 		return ret;
5253 	}
5254 	flush_write_bio(&epd);
5255 	btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
5256 	return ret;
5257 }
5258 
extent_readahead(struct readahead_control * rac)5259 void extent_readahead(struct readahead_control *rac)
5260 {
5261 	struct btrfs_bio_ctrl bio_ctrl = { 0 };
5262 	struct page *pagepool[16];
5263 	struct extent_map *em_cached = NULL;
5264 	u64 prev_em_start = (u64)-1;
5265 	int nr;
5266 
5267 	while ((nr = readahead_page_batch(rac, pagepool))) {
5268 		u64 contig_start = readahead_pos(rac);
5269 		u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
5270 
5271 		contiguous_readpages(pagepool, nr, contig_start, contig_end,
5272 				&em_cached, &bio_ctrl, &prev_em_start);
5273 	}
5274 
5275 	if (em_cached)
5276 		free_extent_map(em_cached);
5277 
5278 	if (bio_ctrl.bio)
5279 		submit_one_bio(bio_ctrl.bio, 0, bio_ctrl.compress_type);
5280 }
5281 
5282 /*
5283  * basic invalidate_folio code, this waits on any locked or writeback
5284  * ranges corresponding to the folio, and then deletes any extent state
5285  * records from the tree
5286  */
extent_invalidate_folio(struct extent_io_tree * tree,struct folio * folio,size_t offset)5287 int extent_invalidate_folio(struct extent_io_tree *tree,
5288 			  struct folio *folio, size_t offset)
5289 {
5290 	struct extent_state *cached_state = NULL;
5291 	u64 start = folio_pos(folio);
5292 	u64 end = start + folio_size(folio) - 1;
5293 	size_t blocksize = folio->mapping->host->i_sb->s_blocksize;
5294 
5295 	/* This function is only called for the btree inode */
5296 	ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
5297 
5298 	start += ALIGN(offset, blocksize);
5299 	if (start > end)
5300 		return 0;
5301 
5302 	lock_extent_bits(tree, start, end, &cached_state);
5303 	folio_wait_writeback(folio);
5304 
5305 	/*
5306 	 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
5307 	 * so here we only need to unlock the extent range to free any
5308 	 * existing extent state.
5309 	 */
5310 	unlock_extent_cached(tree, start, end, &cached_state);
5311 	return 0;
5312 }
5313 
5314 /*
5315  * a helper for release_folio, this tests for areas of the page that
5316  * are locked or under IO and drops the related state bits if it is safe
5317  * to drop the page.
5318  */
try_release_extent_state(struct extent_io_tree * tree,struct page * page,gfp_t mask)5319 static int try_release_extent_state(struct extent_io_tree *tree,
5320 				    struct page *page, gfp_t mask)
5321 {
5322 	u64 start = page_offset(page);
5323 	u64 end = start + PAGE_SIZE - 1;
5324 	int ret = 1;
5325 
5326 	if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
5327 		ret = 0;
5328 	} else {
5329 		/*
5330 		 * At this point we can safely clear everything except the
5331 		 * locked bit, the nodatasum bit and the delalloc new bit.
5332 		 * The delalloc new bit will be cleared by ordered extent
5333 		 * completion.
5334 		 */
5335 		ret = __clear_extent_bit(tree, start, end,
5336 			 ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW),
5337 			 0, 0, NULL, mask, NULL);
5338 
5339 		/* if clear_extent_bit failed for enomem reasons,
5340 		 * we can't allow the release to continue.
5341 		 */
5342 		if (ret < 0)
5343 			ret = 0;
5344 		else
5345 			ret = 1;
5346 	}
5347 	return ret;
5348 }
5349 
5350 /*
5351  * a helper for release_folio.  As long as there are no locked extents
5352  * in the range corresponding to the page, both state records and extent
5353  * map records are removed
5354  */
try_release_extent_mapping(struct page * page,gfp_t mask)5355 int try_release_extent_mapping(struct page *page, gfp_t mask)
5356 {
5357 	struct extent_map *em;
5358 	u64 start = page_offset(page);
5359 	u64 end = start + PAGE_SIZE - 1;
5360 	struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
5361 	struct extent_io_tree *tree = &btrfs_inode->io_tree;
5362 	struct extent_map_tree *map = &btrfs_inode->extent_tree;
5363 
5364 	if (gfpflags_allow_blocking(mask) &&
5365 	    page->mapping->host->i_size > SZ_16M) {
5366 		u64 len;
5367 		while (start <= end) {
5368 			struct btrfs_fs_info *fs_info;
5369 			u64 cur_gen;
5370 
5371 			len = end - start + 1;
5372 			write_lock(&map->lock);
5373 			em = lookup_extent_mapping(map, start, len);
5374 			if (!em) {
5375 				write_unlock(&map->lock);
5376 				break;
5377 			}
5378 			if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
5379 			    em->start != start) {
5380 				write_unlock(&map->lock);
5381 				free_extent_map(em);
5382 				break;
5383 			}
5384 			if (test_range_bit(tree, em->start,
5385 					   extent_map_end(em) - 1,
5386 					   EXTENT_LOCKED, 0, NULL))
5387 				goto next;
5388 			/*
5389 			 * If it's not in the list of modified extents, used
5390 			 * by a fast fsync, we can remove it. If it's being
5391 			 * logged we can safely remove it since fsync took an
5392 			 * extra reference on the em.
5393 			 */
5394 			if (list_empty(&em->list) ||
5395 			    test_bit(EXTENT_FLAG_LOGGING, &em->flags))
5396 				goto remove_em;
5397 			/*
5398 			 * If it's in the list of modified extents, remove it
5399 			 * only if its generation is older then the current one,
5400 			 * in which case we don't need it for a fast fsync.
5401 			 * Otherwise don't remove it, we could be racing with an
5402 			 * ongoing fast fsync that could miss the new extent.
5403 			 */
5404 			fs_info = btrfs_inode->root->fs_info;
5405 			spin_lock(&fs_info->trans_lock);
5406 			cur_gen = fs_info->generation;
5407 			spin_unlock(&fs_info->trans_lock);
5408 			if (em->generation >= cur_gen)
5409 				goto next;
5410 remove_em:
5411 			/*
5412 			 * We only remove extent maps that are not in the list of
5413 			 * modified extents or that are in the list but with a
5414 			 * generation lower then the current generation, so there
5415 			 * is no need to set the full fsync flag on the inode (it
5416 			 * hurts the fsync performance for workloads with a data
5417 			 * size that exceeds or is close to the system's memory).
5418 			 */
5419 			remove_extent_mapping(map, em);
5420 			/* once for the rb tree */
5421 			free_extent_map(em);
5422 next:
5423 			start = extent_map_end(em);
5424 			write_unlock(&map->lock);
5425 
5426 			/* once for us */
5427 			free_extent_map(em);
5428 
5429 			cond_resched(); /* Allow large-extent preemption. */
5430 		}
5431 	}
5432 	return try_release_extent_state(tree, page, mask);
5433 }
5434 
5435 /*
5436  * helper function for fiemap, which doesn't want to see any holes.
5437  * This maps until we find something past 'last'
5438  */
get_extent_skip_holes(struct btrfs_inode * inode,u64 offset,u64 last)5439 static struct extent_map *get_extent_skip_holes(struct btrfs_inode *inode,
5440 						u64 offset, u64 last)
5441 {
5442 	u64 sectorsize = btrfs_inode_sectorsize(inode);
5443 	struct extent_map *em;
5444 	u64 len;
5445 
5446 	if (offset >= last)
5447 		return NULL;
5448 
5449 	while (1) {
5450 		len = last - offset;
5451 		if (len == 0)
5452 			break;
5453 		len = ALIGN(len, sectorsize);
5454 		em = btrfs_get_extent_fiemap(inode, offset, len);
5455 		if (IS_ERR(em))
5456 			return em;
5457 
5458 		/* if this isn't a hole return it */
5459 		if (em->block_start != EXTENT_MAP_HOLE)
5460 			return em;
5461 
5462 		/* this is a hole, advance to the next extent */
5463 		offset = extent_map_end(em);
5464 		free_extent_map(em);
5465 		if (offset >= last)
5466 			break;
5467 	}
5468 	return NULL;
5469 }
5470 
5471 /*
5472  * To cache previous fiemap extent
5473  *
5474  * Will be used for merging fiemap extent
5475  */
5476 struct fiemap_cache {
5477 	u64 offset;
5478 	u64 phys;
5479 	u64 len;
5480 	u32 flags;
5481 	bool cached;
5482 };
5483 
5484 /*
5485  * Helper to submit fiemap extent.
5486  *
5487  * Will try to merge current fiemap extent specified by @offset, @phys,
5488  * @len and @flags with cached one.
5489  * And only when we fails to merge, cached one will be submitted as
5490  * fiemap extent.
5491  *
5492  * Return value is the same as fiemap_fill_next_extent().
5493  */
emit_fiemap_extent(struct fiemap_extent_info * fieinfo,struct fiemap_cache * cache,u64 offset,u64 phys,u64 len,u32 flags)5494 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
5495 				struct fiemap_cache *cache,
5496 				u64 offset, u64 phys, u64 len, u32 flags)
5497 {
5498 	int ret = 0;
5499 
5500 	if (!cache->cached)
5501 		goto assign;
5502 
5503 	/*
5504 	 * Sanity check, extent_fiemap() should have ensured that new
5505 	 * fiemap extent won't overlap with cached one.
5506 	 * Not recoverable.
5507 	 *
5508 	 * NOTE: Physical address can overlap, due to compression
5509 	 */
5510 	if (cache->offset + cache->len > offset) {
5511 		WARN_ON(1);
5512 		return -EINVAL;
5513 	}
5514 
5515 	/*
5516 	 * Only merges fiemap extents if
5517 	 * 1) Their logical addresses are continuous
5518 	 *
5519 	 * 2) Their physical addresses are continuous
5520 	 *    So truly compressed (physical size smaller than logical size)
5521 	 *    extents won't get merged with each other
5522 	 *
5523 	 * 3) Share same flags except FIEMAP_EXTENT_LAST
5524 	 *    So regular extent won't get merged with prealloc extent
5525 	 */
5526 	if (cache->offset + cache->len  == offset &&
5527 	    cache->phys + cache->len == phys  &&
5528 	    (cache->flags & ~FIEMAP_EXTENT_LAST) ==
5529 			(flags & ~FIEMAP_EXTENT_LAST)) {
5530 		cache->len += len;
5531 		cache->flags |= flags;
5532 		goto try_submit_last;
5533 	}
5534 
5535 	/* Not mergeable, need to submit cached one */
5536 	ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5537 				      cache->len, cache->flags);
5538 	cache->cached = false;
5539 	if (ret)
5540 		return ret;
5541 assign:
5542 	cache->cached = true;
5543 	cache->offset = offset;
5544 	cache->phys = phys;
5545 	cache->len = len;
5546 	cache->flags = flags;
5547 try_submit_last:
5548 	if (cache->flags & FIEMAP_EXTENT_LAST) {
5549 		ret = fiemap_fill_next_extent(fieinfo, cache->offset,
5550 				cache->phys, cache->len, cache->flags);
5551 		cache->cached = false;
5552 	}
5553 	return ret;
5554 }
5555 
5556 /*
5557  * Emit last fiemap cache
5558  *
5559  * The last fiemap cache may still be cached in the following case:
5560  * 0		      4k		    8k
5561  * |<- Fiemap range ->|
5562  * |<------------  First extent ----------->|
5563  *
5564  * In this case, the first extent range will be cached but not emitted.
5565  * So we must emit it before ending extent_fiemap().
5566  */
emit_last_fiemap_cache(struct fiemap_extent_info * fieinfo,struct fiemap_cache * cache)5567 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
5568 				  struct fiemap_cache *cache)
5569 {
5570 	int ret;
5571 
5572 	if (!cache->cached)
5573 		return 0;
5574 
5575 	ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5576 				      cache->len, cache->flags);
5577 	cache->cached = false;
5578 	if (ret > 0)
5579 		ret = 0;
5580 	return ret;
5581 }
5582 
extent_fiemap(struct btrfs_inode * inode,struct fiemap_extent_info * fieinfo,u64 start,u64 len)5583 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
5584 		  u64 start, u64 len)
5585 {
5586 	int ret = 0;
5587 	u64 off;
5588 	u64 max = start + len;
5589 	u32 flags = 0;
5590 	u32 found_type;
5591 	u64 last;
5592 	u64 last_for_get_extent = 0;
5593 	u64 disko = 0;
5594 	u64 isize = i_size_read(&inode->vfs_inode);
5595 	struct btrfs_key found_key;
5596 	struct extent_map *em = NULL;
5597 	struct extent_state *cached_state = NULL;
5598 	struct btrfs_path *path;
5599 	struct btrfs_root *root = inode->root;
5600 	struct fiemap_cache cache = { 0 };
5601 	struct ulist *roots;
5602 	struct ulist *tmp_ulist;
5603 	int end = 0;
5604 	u64 em_start = 0;
5605 	u64 em_len = 0;
5606 	u64 em_end = 0;
5607 
5608 	if (len == 0)
5609 		return -EINVAL;
5610 
5611 	path = btrfs_alloc_path();
5612 	if (!path)
5613 		return -ENOMEM;
5614 
5615 	roots = ulist_alloc(GFP_KERNEL);
5616 	tmp_ulist = ulist_alloc(GFP_KERNEL);
5617 	if (!roots || !tmp_ulist) {
5618 		ret = -ENOMEM;
5619 		goto out_free_ulist;
5620 	}
5621 
5622 	/*
5623 	 * We can't initialize that to 'start' as this could miss extents due
5624 	 * to extent item merging
5625 	 */
5626 	off = 0;
5627 	start = round_down(start, btrfs_inode_sectorsize(inode));
5628 	len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
5629 
5630 	/*
5631 	 * lookup the last file extent.  We're not using i_size here
5632 	 * because there might be preallocation past i_size
5633 	 */
5634 	ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode), -1,
5635 				       0);
5636 	if (ret < 0) {
5637 		goto out_free_ulist;
5638 	} else {
5639 		WARN_ON(!ret);
5640 		if (ret == 1)
5641 			ret = 0;
5642 	}
5643 
5644 	path->slots[0]--;
5645 	btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
5646 	found_type = found_key.type;
5647 
5648 	/* No extents, but there might be delalloc bits */
5649 	if (found_key.objectid != btrfs_ino(inode) ||
5650 	    found_type != BTRFS_EXTENT_DATA_KEY) {
5651 		/* have to trust i_size as the end */
5652 		last = (u64)-1;
5653 		last_for_get_extent = isize;
5654 	} else {
5655 		/*
5656 		 * remember the start of the last extent.  There are a
5657 		 * bunch of different factors that go into the length of the
5658 		 * extent, so its much less complex to remember where it started
5659 		 */
5660 		last = found_key.offset;
5661 		last_for_get_extent = last + 1;
5662 	}
5663 	btrfs_release_path(path);
5664 
5665 	/*
5666 	 * we might have some extents allocated but more delalloc past those
5667 	 * extents.  so, we trust isize unless the start of the last extent is
5668 	 * beyond isize
5669 	 */
5670 	if (last < isize) {
5671 		last = (u64)-1;
5672 		last_for_get_extent = isize;
5673 	}
5674 
5675 	lock_extent_bits(&inode->io_tree, start, start + len - 1,
5676 			 &cached_state);
5677 
5678 	em = get_extent_skip_holes(inode, start, last_for_get_extent);
5679 	if (!em)
5680 		goto out;
5681 	if (IS_ERR(em)) {
5682 		ret = PTR_ERR(em);
5683 		goto out;
5684 	}
5685 
5686 	while (!end) {
5687 		u64 offset_in_extent = 0;
5688 
5689 		/* break if the extent we found is outside the range */
5690 		if (em->start >= max || extent_map_end(em) < off)
5691 			break;
5692 
5693 		/*
5694 		 * get_extent may return an extent that starts before our
5695 		 * requested range.  We have to make sure the ranges
5696 		 * we return to fiemap always move forward and don't
5697 		 * overlap, so adjust the offsets here
5698 		 */
5699 		em_start = max(em->start, off);
5700 
5701 		/*
5702 		 * record the offset from the start of the extent
5703 		 * for adjusting the disk offset below.  Only do this if the
5704 		 * extent isn't compressed since our in ram offset may be past
5705 		 * what we have actually allocated on disk.
5706 		 */
5707 		if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5708 			offset_in_extent = em_start - em->start;
5709 		em_end = extent_map_end(em);
5710 		em_len = em_end - em_start;
5711 		flags = 0;
5712 		if (em->block_start < EXTENT_MAP_LAST_BYTE)
5713 			disko = em->block_start + offset_in_extent;
5714 		else
5715 			disko = 0;
5716 
5717 		/*
5718 		 * bump off for our next call to get_extent
5719 		 */
5720 		off = extent_map_end(em);
5721 		if (off >= max)
5722 			end = 1;
5723 
5724 		if (em->block_start == EXTENT_MAP_LAST_BYTE) {
5725 			end = 1;
5726 			flags |= FIEMAP_EXTENT_LAST;
5727 		} else if (em->block_start == EXTENT_MAP_INLINE) {
5728 			flags |= (FIEMAP_EXTENT_DATA_INLINE |
5729 				  FIEMAP_EXTENT_NOT_ALIGNED);
5730 		} else if (em->block_start == EXTENT_MAP_DELALLOC) {
5731 			flags |= (FIEMAP_EXTENT_DELALLOC |
5732 				  FIEMAP_EXTENT_UNKNOWN);
5733 		} else if (fieinfo->fi_extents_max) {
5734 			u64 bytenr = em->block_start -
5735 				(em->start - em->orig_start);
5736 
5737 			/*
5738 			 * As btrfs supports shared space, this information
5739 			 * can be exported to userspace tools via
5740 			 * flag FIEMAP_EXTENT_SHARED.  If fi_extents_max == 0
5741 			 * then we're just getting a count and we can skip the
5742 			 * lookup stuff.
5743 			 */
5744 			ret = btrfs_check_shared(root, btrfs_ino(inode),
5745 						 bytenr, roots, tmp_ulist);
5746 			if (ret < 0)
5747 				goto out_free;
5748 			if (ret)
5749 				flags |= FIEMAP_EXTENT_SHARED;
5750 			ret = 0;
5751 		}
5752 		if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5753 			flags |= FIEMAP_EXTENT_ENCODED;
5754 		if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5755 			flags |= FIEMAP_EXTENT_UNWRITTEN;
5756 
5757 		free_extent_map(em);
5758 		em = NULL;
5759 		if ((em_start >= last) || em_len == (u64)-1 ||
5760 		   (last == (u64)-1 && isize <= em_end)) {
5761 			flags |= FIEMAP_EXTENT_LAST;
5762 			end = 1;
5763 		}
5764 
5765 		/* now scan forward to see if this is really the last extent. */
5766 		em = get_extent_skip_holes(inode, off, last_for_get_extent);
5767 		if (IS_ERR(em)) {
5768 			ret = PTR_ERR(em);
5769 			goto out;
5770 		}
5771 		if (!em) {
5772 			flags |= FIEMAP_EXTENT_LAST;
5773 			end = 1;
5774 		}
5775 		ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
5776 					   em_len, flags);
5777 		if (ret) {
5778 			if (ret == 1)
5779 				ret = 0;
5780 			goto out_free;
5781 		}
5782 	}
5783 out_free:
5784 	if (!ret)
5785 		ret = emit_last_fiemap_cache(fieinfo, &cache);
5786 	free_extent_map(em);
5787 out:
5788 	unlock_extent_cached(&inode->io_tree, start, start + len - 1,
5789 			     &cached_state);
5790 
5791 out_free_ulist:
5792 	btrfs_free_path(path);
5793 	ulist_free(roots);
5794 	ulist_free(tmp_ulist);
5795 	return ret;
5796 }
5797 
__free_extent_buffer(struct extent_buffer * eb)5798 static void __free_extent_buffer(struct extent_buffer *eb)
5799 {
5800 	kmem_cache_free(extent_buffer_cache, eb);
5801 }
5802 
extent_buffer_under_io(const struct extent_buffer * eb)5803 int extent_buffer_under_io(const struct extent_buffer *eb)
5804 {
5805 	return (atomic_read(&eb->io_pages) ||
5806 		test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
5807 		test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5808 }
5809 
page_range_has_eb(struct btrfs_fs_info * fs_info,struct page * page)5810 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
5811 {
5812 	struct btrfs_subpage *subpage;
5813 
5814 	lockdep_assert_held(&page->mapping->private_lock);
5815 
5816 	if (PagePrivate(page)) {
5817 		subpage = (struct btrfs_subpage *)page->private;
5818 		if (atomic_read(&subpage->eb_refs))
5819 			return true;
5820 		/*
5821 		 * Even there is no eb refs here, we may still have
5822 		 * end_page_read() call relying on page::private.
5823 		 */
5824 		if (atomic_read(&subpage->readers))
5825 			return true;
5826 	}
5827 	return false;
5828 }
5829 
detach_extent_buffer_page(struct extent_buffer * eb,struct page * page)5830 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
5831 {
5832 	struct btrfs_fs_info *fs_info = eb->fs_info;
5833 	const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5834 
5835 	/*
5836 	 * For mapped eb, we're going to change the page private, which should
5837 	 * be done under the private_lock.
5838 	 */
5839 	if (mapped)
5840 		spin_lock(&page->mapping->private_lock);
5841 
5842 	if (!PagePrivate(page)) {
5843 		if (mapped)
5844 			spin_unlock(&page->mapping->private_lock);
5845 		return;
5846 	}
5847 
5848 	if (fs_info->nodesize >= PAGE_SIZE) {
5849 		/*
5850 		 * We do this since we'll remove the pages after we've
5851 		 * removed the eb from the radix tree, so we could race
5852 		 * and have this page now attached to the new eb.  So
5853 		 * only clear page_private if it's still connected to
5854 		 * this eb.
5855 		 */
5856 		if (PagePrivate(page) &&
5857 		    page->private == (unsigned long)eb) {
5858 			BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5859 			BUG_ON(PageDirty(page));
5860 			BUG_ON(PageWriteback(page));
5861 			/*
5862 			 * We need to make sure we haven't be attached
5863 			 * to a new eb.
5864 			 */
5865 			detach_page_private(page);
5866 		}
5867 		if (mapped)
5868 			spin_unlock(&page->mapping->private_lock);
5869 		return;
5870 	}
5871 
5872 	/*
5873 	 * For subpage, we can have dummy eb with page private.  In this case,
5874 	 * we can directly detach the private as such page is only attached to
5875 	 * one dummy eb, no sharing.
5876 	 */
5877 	if (!mapped) {
5878 		btrfs_detach_subpage(fs_info, page);
5879 		return;
5880 	}
5881 
5882 	btrfs_page_dec_eb_refs(fs_info, page);
5883 
5884 	/*
5885 	 * We can only detach the page private if there are no other ebs in the
5886 	 * page range and no unfinished IO.
5887 	 */
5888 	if (!page_range_has_eb(fs_info, page))
5889 		btrfs_detach_subpage(fs_info, page);
5890 
5891 	spin_unlock(&page->mapping->private_lock);
5892 }
5893 
5894 /* Release all pages attached to the extent buffer */
btrfs_release_extent_buffer_pages(struct extent_buffer * eb)5895 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
5896 {
5897 	int i;
5898 	int num_pages;
5899 
5900 	ASSERT(!extent_buffer_under_io(eb));
5901 
5902 	num_pages = num_extent_pages(eb);
5903 	for (i = 0; i < num_pages; i++) {
5904 		struct page *page = eb->pages[i];
5905 
5906 		if (!page)
5907 			continue;
5908 
5909 		detach_extent_buffer_page(eb, page);
5910 
5911 		/* One for when we allocated the page */
5912 		put_page(page);
5913 	}
5914 }
5915 
5916 /*
5917  * Helper for releasing the extent buffer.
5918  */
btrfs_release_extent_buffer(struct extent_buffer * eb)5919 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
5920 {
5921 	btrfs_release_extent_buffer_pages(eb);
5922 	btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
5923 	__free_extent_buffer(eb);
5924 }
5925 
5926 static struct extent_buffer *
__alloc_extent_buffer(struct btrfs_fs_info * fs_info,u64 start,unsigned long len)5927 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
5928 		      unsigned long len)
5929 {
5930 	struct extent_buffer *eb = NULL;
5931 
5932 	eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
5933 	eb->start = start;
5934 	eb->len = len;
5935 	eb->fs_info = fs_info;
5936 	eb->bflags = 0;
5937 	init_rwsem(&eb->lock);
5938 
5939 	btrfs_leak_debug_add(&fs_info->eb_leak_lock, &eb->leak_list,
5940 			     &fs_info->allocated_ebs);
5941 	INIT_LIST_HEAD(&eb->release_list);
5942 
5943 	spin_lock_init(&eb->refs_lock);
5944 	atomic_set(&eb->refs, 1);
5945 	atomic_set(&eb->io_pages, 0);
5946 
5947 	ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
5948 
5949 	return eb;
5950 }
5951 
btrfs_clone_extent_buffer(const struct extent_buffer * src)5952 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
5953 {
5954 	int i;
5955 	struct extent_buffer *new;
5956 	int num_pages = num_extent_pages(src);
5957 	int ret;
5958 
5959 	new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
5960 	if (new == NULL)
5961 		return NULL;
5962 
5963 	/*
5964 	 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
5965 	 * btrfs_release_extent_buffer() have different behavior for
5966 	 * UNMAPPED subpage extent buffer.
5967 	 */
5968 	set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
5969 
5970 	memset(new->pages, 0, sizeof(*new->pages) * num_pages);
5971 	ret = btrfs_alloc_page_array(num_pages, new->pages);
5972 	if (ret) {
5973 		btrfs_release_extent_buffer(new);
5974 		return NULL;
5975 	}
5976 
5977 	for (i = 0; i < num_pages; i++) {
5978 		int ret;
5979 		struct page *p = new->pages[i];
5980 
5981 		ret = attach_extent_buffer_page(new, p, NULL);
5982 		if (ret < 0) {
5983 			btrfs_release_extent_buffer(new);
5984 			return NULL;
5985 		}
5986 		WARN_ON(PageDirty(p));
5987 		copy_page(page_address(p), page_address(src->pages[i]));
5988 	}
5989 	set_extent_buffer_uptodate(new);
5990 
5991 	return new;
5992 }
5993 
__alloc_dummy_extent_buffer(struct btrfs_fs_info * fs_info,u64 start,unsigned long len)5994 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5995 						  u64 start, unsigned long len)
5996 {
5997 	struct extent_buffer *eb;
5998 	int num_pages;
5999 	int i;
6000 	int ret;
6001 
6002 	eb = __alloc_extent_buffer(fs_info, start, len);
6003 	if (!eb)
6004 		return NULL;
6005 
6006 	num_pages = num_extent_pages(eb);
6007 	ret = btrfs_alloc_page_array(num_pages, eb->pages);
6008 	if (ret)
6009 		goto err;
6010 
6011 	for (i = 0; i < num_pages; i++) {
6012 		struct page *p = eb->pages[i];
6013 
6014 		ret = attach_extent_buffer_page(eb, p, NULL);
6015 		if (ret < 0)
6016 			goto err;
6017 	}
6018 
6019 	set_extent_buffer_uptodate(eb);
6020 	btrfs_set_header_nritems(eb, 0);
6021 	set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
6022 
6023 	return eb;
6024 err:
6025 	for (i = 0; i < num_pages; i++) {
6026 		if (eb->pages[i]) {
6027 			detach_extent_buffer_page(eb, eb->pages[i]);
6028 			__free_page(eb->pages[i]);
6029 		}
6030 	}
6031 	__free_extent_buffer(eb);
6032 	return NULL;
6033 }
6034 
alloc_dummy_extent_buffer(struct btrfs_fs_info * fs_info,u64 start)6035 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
6036 						u64 start)
6037 {
6038 	return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
6039 }
6040 
check_buffer_tree_ref(struct extent_buffer * eb)6041 static void check_buffer_tree_ref(struct extent_buffer *eb)
6042 {
6043 	int refs;
6044 	/*
6045 	 * The TREE_REF bit is first set when the extent_buffer is added
6046 	 * to the radix tree. It is also reset, if unset, when a new reference
6047 	 * is created by find_extent_buffer.
6048 	 *
6049 	 * It is only cleared in two cases: freeing the last non-tree
6050 	 * reference to the extent_buffer when its STALE bit is set or
6051 	 * calling release_folio when the tree reference is the only reference.
6052 	 *
6053 	 * In both cases, care is taken to ensure that the extent_buffer's
6054 	 * pages are not under io. However, release_folio can be concurrently
6055 	 * called with creating new references, which is prone to race
6056 	 * conditions between the calls to check_buffer_tree_ref in those
6057 	 * codepaths and clearing TREE_REF in try_release_extent_buffer.
6058 	 *
6059 	 * The actual lifetime of the extent_buffer in the radix tree is
6060 	 * adequately protected by the refcount, but the TREE_REF bit and
6061 	 * its corresponding reference are not. To protect against this
6062 	 * class of races, we call check_buffer_tree_ref from the codepaths
6063 	 * which trigger io after they set eb->io_pages. Note that once io is
6064 	 * initiated, TREE_REF can no longer be cleared, so that is the
6065 	 * moment at which any such race is best fixed.
6066 	 */
6067 	refs = atomic_read(&eb->refs);
6068 	if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6069 		return;
6070 
6071 	spin_lock(&eb->refs_lock);
6072 	if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6073 		atomic_inc(&eb->refs);
6074 	spin_unlock(&eb->refs_lock);
6075 }
6076 
mark_extent_buffer_accessed(struct extent_buffer * eb,struct page * accessed)6077 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
6078 		struct page *accessed)
6079 {
6080 	int num_pages, i;
6081 
6082 	check_buffer_tree_ref(eb);
6083 
6084 	num_pages = num_extent_pages(eb);
6085 	for (i = 0; i < num_pages; i++) {
6086 		struct page *p = eb->pages[i];
6087 
6088 		if (p != accessed)
6089 			mark_page_accessed(p);
6090 	}
6091 }
6092 
find_extent_buffer(struct btrfs_fs_info * fs_info,u64 start)6093 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
6094 					 u64 start)
6095 {
6096 	struct extent_buffer *eb;
6097 
6098 	eb = find_extent_buffer_nolock(fs_info, start);
6099 	if (!eb)
6100 		return NULL;
6101 	/*
6102 	 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
6103 	 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
6104 	 * another task running free_extent_buffer() might have seen that flag
6105 	 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
6106 	 * writeback flags not set) and it's still in the tree (flag
6107 	 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
6108 	 * decrementing the extent buffer's reference count twice.  So here we
6109 	 * could race and increment the eb's reference count, clear its stale
6110 	 * flag, mark it as dirty and drop our reference before the other task
6111 	 * finishes executing free_extent_buffer, which would later result in
6112 	 * an attempt to free an extent buffer that is dirty.
6113 	 */
6114 	if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
6115 		spin_lock(&eb->refs_lock);
6116 		spin_unlock(&eb->refs_lock);
6117 	}
6118 	mark_extent_buffer_accessed(eb, NULL);
6119 	return eb;
6120 }
6121 
6122 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
alloc_test_extent_buffer(struct btrfs_fs_info * fs_info,u64 start)6123 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
6124 					u64 start)
6125 {
6126 	struct extent_buffer *eb, *exists = NULL;
6127 	int ret;
6128 
6129 	eb = find_extent_buffer(fs_info, start);
6130 	if (eb)
6131 		return eb;
6132 	eb = alloc_dummy_extent_buffer(fs_info, start);
6133 	if (!eb)
6134 		return ERR_PTR(-ENOMEM);
6135 	eb->fs_info = fs_info;
6136 again:
6137 	ret = radix_tree_preload(GFP_NOFS);
6138 	if (ret) {
6139 		exists = ERR_PTR(ret);
6140 		goto free_eb;
6141 	}
6142 	spin_lock(&fs_info->buffer_lock);
6143 	ret = radix_tree_insert(&fs_info->buffer_radix,
6144 				start >> fs_info->sectorsize_bits, eb);
6145 	spin_unlock(&fs_info->buffer_lock);
6146 	radix_tree_preload_end();
6147 	if (ret == -EEXIST) {
6148 		exists = find_extent_buffer(fs_info, start);
6149 		if (exists)
6150 			goto free_eb;
6151 		else
6152 			goto again;
6153 	}
6154 	check_buffer_tree_ref(eb);
6155 	set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
6156 
6157 	return eb;
6158 free_eb:
6159 	btrfs_release_extent_buffer(eb);
6160 	return exists;
6161 }
6162 #endif
6163 
grab_extent_buffer(struct btrfs_fs_info * fs_info,struct page * page)6164 static struct extent_buffer *grab_extent_buffer(
6165 		struct btrfs_fs_info *fs_info, struct page *page)
6166 {
6167 	struct extent_buffer *exists;
6168 
6169 	/*
6170 	 * For subpage case, we completely rely on radix tree to ensure we
6171 	 * don't try to insert two ebs for the same bytenr.  So here we always
6172 	 * return NULL and just continue.
6173 	 */
6174 	if (fs_info->nodesize < PAGE_SIZE)
6175 		return NULL;
6176 
6177 	/* Page not yet attached to an extent buffer */
6178 	if (!PagePrivate(page))
6179 		return NULL;
6180 
6181 	/*
6182 	 * We could have already allocated an eb for this page and attached one
6183 	 * so lets see if we can get a ref on the existing eb, and if we can we
6184 	 * know it's good and we can just return that one, else we know we can
6185 	 * just overwrite page->private.
6186 	 */
6187 	exists = (struct extent_buffer *)page->private;
6188 	if (atomic_inc_not_zero(&exists->refs))
6189 		return exists;
6190 
6191 	WARN_ON(PageDirty(page));
6192 	detach_page_private(page);
6193 	return NULL;
6194 }
6195 
check_eb_alignment(struct btrfs_fs_info * fs_info,u64 start)6196 static int check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
6197 {
6198 	if (!IS_ALIGNED(start, fs_info->sectorsize)) {
6199 		btrfs_err(fs_info, "bad tree block start %llu", start);
6200 		return -EINVAL;
6201 	}
6202 
6203 	if (fs_info->nodesize < PAGE_SIZE &&
6204 	    offset_in_page(start) + fs_info->nodesize > PAGE_SIZE) {
6205 		btrfs_err(fs_info,
6206 		"tree block crosses page boundary, start %llu nodesize %u",
6207 			  start, fs_info->nodesize);
6208 		return -EINVAL;
6209 	}
6210 	if (fs_info->nodesize >= PAGE_SIZE &&
6211 	    !IS_ALIGNED(start, PAGE_SIZE)) {
6212 		btrfs_err(fs_info,
6213 		"tree block is not page aligned, start %llu nodesize %u",
6214 			  start, fs_info->nodesize);
6215 		return -EINVAL;
6216 	}
6217 	return 0;
6218 }
6219 
alloc_extent_buffer(struct btrfs_fs_info * fs_info,u64 start,u64 owner_root,int level)6220 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
6221 					  u64 start, u64 owner_root, int level)
6222 {
6223 	unsigned long len = fs_info->nodesize;
6224 	int num_pages;
6225 	int i;
6226 	unsigned long index = start >> PAGE_SHIFT;
6227 	struct extent_buffer *eb;
6228 	struct extent_buffer *exists = NULL;
6229 	struct page *p;
6230 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
6231 	u64 lockdep_owner = owner_root;
6232 	int uptodate = 1;
6233 	int ret;
6234 
6235 	if (check_eb_alignment(fs_info, start))
6236 		return ERR_PTR(-EINVAL);
6237 
6238 #if BITS_PER_LONG == 32
6239 	if (start >= MAX_LFS_FILESIZE) {
6240 		btrfs_err_rl(fs_info,
6241 		"extent buffer %llu is beyond 32bit page cache limit", start);
6242 		btrfs_err_32bit_limit(fs_info);
6243 		return ERR_PTR(-EOVERFLOW);
6244 	}
6245 	if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
6246 		btrfs_warn_32bit_limit(fs_info);
6247 #endif
6248 
6249 	eb = find_extent_buffer(fs_info, start);
6250 	if (eb)
6251 		return eb;
6252 
6253 	eb = __alloc_extent_buffer(fs_info, start, len);
6254 	if (!eb)
6255 		return ERR_PTR(-ENOMEM);
6256 
6257 	/*
6258 	 * The reloc trees are just snapshots, so we need them to appear to be
6259 	 * just like any other fs tree WRT lockdep.
6260 	 */
6261 	if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID)
6262 		lockdep_owner = BTRFS_FS_TREE_OBJECTID;
6263 
6264 	btrfs_set_buffer_lockdep_class(lockdep_owner, eb, level);
6265 
6266 	num_pages = num_extent_pages(eb);
6267 	for (i = 0; i < num_pages; i++, index++) {
6268 		struct btrfs_subpage *prealloc = NULL;
6269 
6270 		p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
6271 		if (!p) {
6272 			exists = ERR_PTR(-ENOMEM);
6273 			goto free_eb;
6274 		}
6275 
6276 		/*
6277 		 * Preallocate page->private for subpage case, so that we won't
6278 		 * allocate memory with private_lock hold.  The memory will be
6279 		 * freed by attach_extent_buffer_page() or freed manually if
6280 		 * we exit earlier.
6281 		 *
6282 		 * Although we have ensured one subpage eb can only have one
6283 		 * page, but it may change in the future for 16K page size
6284 		 * support, so we still preallocate the memory in the loop.
6285 		 */
6286 		if (fs_info->nodesize < PAGE_SIZE) {
6287 			prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
6288 			if (IS_ERR(prealloc)) {
6289 				ret = PTR_ERR(prealloc);
6290 				unlock_page(p);
6291 				put_page(p);
6292 				exists = ERR_PTR(ret);
6293 				goto free_eb;
6294 			}
6295 		}
6296 
6297 		spin_lock(&mapping->private_lock);
6298 		exists = grab_extent_buffer(fs_info, p);
6299 		if (exists) {
6300 			spin_unlock(&mapping->private_lock);
6301 			unlock_page(p);
6302 			put_page(p);
6303 			mark_extent_buffer_accessed(exists, p);
6304 			btrfs_free_subpage(prealloc);
6305 			goto free_eb;
6306 		}
6307 		/* Should not fail, as we have preallocated the memory */
6308 		ret = attach_extent_buffer_page(eb, p, prealloc);
6309 		ASSERT(!ret);
6310 		/*
6311 		 * To inform we have extra eb under allocation, so that
6312 		 * detach_extent_buffer_page() won't release the page private
6313 		 * when the eb hasn't yet been inserted into radix tree.
6314 		 *
6315 		 * The ref will be decreased when the eb released the page, in
6316 		 * detach_extent_buffer_page().
6317 		 * Thus needs no special handling in error path.
6318 		 */
6319 		btrfs_page_inc_eb_refs(fs_info, p);
6320 		spin_unlock(&mapping->private_lock);
6321 
6322 		WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
6323 		eb->pages[i] = p;
6324 		if (!PageUptodate(p))
6325 			uptodate = 0;
6326 
6327 		/*
6328 		 * We can't unlock the pages just yet since the extent buffer
6329 		 * hasn't been properly inserted in the radix tree, this
6330 		 * opens a race with btree_release_folio which can free a page
6331 		 * while we are still filling in all pages for the buffer and
6332 		 * we could crash.
6333 		 */
6334 	}
6335 	if (uptodate)
6336 		set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6337 again:
6338 	ret = radix_tree_preload(GFP_NOFS);
6339 	if (ret) {
6340 		exists = ERR_PTR(ret);
6341 		goto free_eb;
6342 	}
6343 
6344 	spin_lock(&fs_info->buffer_lock);
6345 	ret = radix_tree_insert(&fs_info->buffer_radix,
6346 				start >> fs_info->sectorsize_bits, eb);
6347 	spin_unlock(&fs_info->buffer_lock);
6348 	radix_tree_preload_end();
6349 	if (ret == -EEXIST) {
6350 		exists = find_extent_buffer(fs_info, start);
6351 		if (exists)
6352 			goto free_eb;
6353 		else
6354 			goto again;
6355 	}
6356 	/* add one reference for the tree */
6357 	check_buffer_tree_ref(eb);
6358 	set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
6359 
6360 	/*
6361 	 * Now it's safe to unlock the pages because any calls to
6362 	 * btree_release_folio will correctly detect that a page belongs to a
6363 	 * live buffer and won't free them prematurely.
6364 	 */
6365 	for (i = 0; i < num_pages; i++)
6366 		unlock_page(eb->pages[i]);
6367 	return eb;
6368 
6369 free_eb:
6370 	WARN_ON(!atomic_dec_and_test(&eb->refs));
6371 	for (i = 0; i < num_pages; i++) {
6372 		if (eb->pages[i])
6373 			unlock_page(eb->pages[i]);
6374 	}
6375 
6376 	btrfs_release_extent_buffer(eb);
6377 	return exists;
6378 }
6379 
btrfs_release_extent_buffer_rcu(struct rcu_head * head)6380 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
6381 {
6382 	struct extent_buffer *eb =
6383 			container_of(head, struct extent_buffer, rcu_head);
6384 
6385 	__free_extent_buffer(eb);
6386 }
6387 
release_extent_buffer(struct extent_buffer * eb)6388 static int release_extent_buffer(struct extent_buffer *eb)
6389 	__releases(&eb->refs_lock)
6390 {
6391 	lockdep_assert_held(&eb->refs_lock);
6392 
6393 	WARN_ON(atomic_read(&eb->refs) == 0);
6394 	if (atomic_dec_and_test(&eb->refs)) {
6395 		if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
6396 			struct btrfs_fs_info *fs_info = eb->fs_info;
6397 
6398 			spin_unlock(&eb->refs_lock);
6399 
6400 			spin_lock(&fs_info->buffer_lock);
6401 			radix_tree_delete(&fs_info->buffer_radix,
6402 					  eb->start >> fs_info->sectorsize_bits);
6403 			spin_unlock(&fs_info->buffer_lock);
6404 		} else {
6405 			spin_unlock(&eb->refs_lock);
6406 		}
6407 
6408 		btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
6409 		/* Should be safe to release our pages at this point */
6410 		btrfs_release_extent_buffer_pages(eb);
6411 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6412 		if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
6413 			__free_extent_buffer(eb);
6414 			return 1;
6415 		}
6416 #endif
6417 		call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
6418 		return 1;
6419 	}
6420 	spin_unlock(&eb->refs_lock);
6421 
6422 	return 0;
6423 }
6424 
free_extent_buffer(struct extent_buffer * eb)6425 void free_extent_buffer(struct extent_buffer *eb)
6426 {
6427 	int refs;
6428 	int old;
6429 	if (!eb)
6430 		return;
6431 
6432 	while (1) {
6433 		refs = atomic_read(&eb->refs);
6434 		if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
6435 		    || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
6436 			refs == 1))
6437 			break;
6438 		old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
6439 		if (old == refs)
6440 			return;
6441 	}
6442 
6443 	spin_lock(&eb->refs_lock);
6444 	if (atomic_read(&eb->refs) == 2 &&
6445 	    test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
6446 	    !extent_buffer_under_io(eb) &&
6447 	    test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6448 		atomic_dec(&eb->refs);
6449 
6450 	/*
6451 	 * I know this is terrible, but it's temporary until we stop tracking
6452 	 * the uptodate bits and such for the extent buffers.
6453 	 */
6454 	release_extent_buffer(eb);
6455 }
6456 
free_extent_buffer_stale(struct extent_buffer * eb)6457 void free_extent_buffer_stale(struct extent_buffer *eb)
6458 {
6459 	if (!eb)
6460 		return;
6461 
6462 	spin_lock(&eb->refs_lock);
6463 	set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
6464 
6465 	if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
6466 	    test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6467 		atomic_dec(&eb->refs);
6468 	release_extent_buffer(eb);
6469 }
6470 
btree_clear_page_dirty(struct page * page)6471 static void btree_clear_page_dirty(struct page *page)
6472 {
6473 	ASSERT(PageDirty(page));
6474 	ASSERT(PageLocked(page));
6475 	clear_page_dirty_for_io(page);
6476 	xa_lock_irq(&page->mapping->i_pages);
6477 	if (!PageDirty(page))
6478 		__xa_clear_mark(&page->mapping->i_pages,
6479 				page_index(page), PAGECACHE_TAG_DIRTY);
6480 	xa_unlock_irq(&page->mapping->i_pages);
6481 }
6482 
clear_subpage_extent_buffer_dirty(const struct extent_buffer * eb)6483 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
6484 {
6485 	struct btrfs_fs_info *fs_info = eb->fs_info;
6486 	struct page *page = eb->pages[0];
6487 	bool last;
6488 
6489 	/* btree_clear_page_dirty() needs page locked */
6490 	lock_page(page);
6491 	last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
6492 						  eb->len);
6493 	if (last)
6494 		btree_clear_page_dirty(page);
6495 	unlock_page(page);
6496 	WARN_ON(atomic_read(&eb->refs) == 0);
6497 }
6498 
clear_extent_buffer_dirty(const struct extent_buffer * eb)6499 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
6500 {
6501 	int i;
6502 	int num_pages;
6503 	struct page *page;
6504 
6505 	if (eb->fs_info->nodesize < PAGE_SIZE)
6506 		return clear_subpage_extent_buffer_dirty(eb);
6507 
6508 	num_pages = num_extent_pages(eb);
6509 
6510 	for (i = 0; i < num_pages; i++) {
6511 		page = eb->pages[i];
6512 		if (!PageDirty(page))
6513 			continue;
6514 		lock_page(page);
6515 		btree_clear_page_dirty(page);
6516 		ClearPageError(page);
6517 		unlock_page(page);
6518 	}
6519 	WARN_ON(atomic_read(&eb->refs) == 0);
6520 }
6521 
set_extent_buffer_dirty(struct extent_buffer * eb)6522 bool set_extent_buffer_dirty(struct extent_buffer *eb)
6523 {
6524 	int i;
6525 	int num_pages;
6526 	bool was_dirty;
6527 
6528 	check_buffer_tree_ref(eb);
6529 
6530 	was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
6531 
6532 	num_pages = num_extent_pages(eb);
6533 	WARN_ON(atomic_read(&eb->refs) == 0);
6534 	WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
6535 
6536 	if (!was_dirty) {
6537 		bool subpage = eb->fs_info->nodesize < PAGE_SIZE;
6538 
6539 		/*
6540 		 * For subpage case, we can have other extent buffers in the
6541 		 * same page, and in clear_subpage_extent_buffer_dirty() we
6542 		 * have to clear page dirty without subpage lock held.
6543 		 * This can cause race where our page gets dirty cleared after
6544 		 * we just set it.
6545 		 *
6546 		 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
6547 		 * its page for other reasons, we can use page lock to prevent
6548 		 * the above race.
6549 		 */
6550 		if (subpage)
6551 			lock_page(eb->pages[0]);
6552 		for (i = 0; i < num_pages; i++)
6553 			btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
6554 					     eb->start, eb->len);
6555 		if (subpage)
6556 			unlock_page(eb->pages[0]);
6557 	}
6558 #ifdef CONFIG_BTRFS_DEBUG
6559 	for (i = 0; i < num_pages; i++)
6560 		ASSERT(PageDirty(eb->pages[i]));
6561 #endif
6562 
6563 	return was_dirty;
6564 }
6565 
clear_extent_buffer_uptodate(struct extent_buffer * eb)6566 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
6567 {
6568 	struct btrfs_fs_info *fs_info = eb->fs_info;
6569 	struct page *page;
6570 	int num_pages;
6571 	int i;
6572 
6573 	clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6574 	num_pages = num_extent_pages(eb);
6575 	for (i = 0; i < num_pages; i++) {
6576 		page = eb->pages[i];
6577 		if (!page)
6578 			continue;
6579 
6580 		/*
6581 		 * This is special handling for metadata subpage, as regular
6582 		 * btrfs_is_subpage() can not handle cloned/dummy metadata.
6583 		 */
6584 		if (fs_info->nodesize >= PAGE_SIZE)
6585 			ClearPageUptodate(page);
6586 		else
6587 			btrfs_subpage_clear_uptodate(fs_info, page, eb->start,
6588 						     eb->len);
6589 	}
6590 }
6591 
set_extent_buffer_uptodate(struct extent_buffer * eb)6592 void set_extent_buffer_uptodate(struct extent_buffer *eb)
6593 {
6594 	struct btrfs_fs_info *fs_info = eb->fs_info;
6595 	struct page *page;
6596 	int num_pages;
6597 	int i;
6598 
6599 	set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6600 	num_pages = num_extent_pages(eb);
6601 	for (i = 0; i < num_pages; i++) {
6602 		page = eb->pages[i];
6603 
6604 		/*
6605 		 * This is special handling for metadata subpage, as regular
6606 		 * btrfs_is_subpage() can not handle cloned/dummy metadata.
6607 		 */
6608 		if (fs_info->nodesize >= PAGE_SIZE)
6609 			SetPageUptodate(page);
6610 		else
6611 			btrfs_subpage_set_uptodate(fs_info, page, eb->start,
6612 						   eb->len);
6613 	}
6614 }
6615 
read_extent_buffer_subpage(struct extent_buffer * eb,int wait,int mirror_num)6616 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
6617 				      int mirror_num)
6618 {
6619 	struct btrfs_fs_info *fs_info = eb->fs_info;
6620 	struct extent_io_tree *io_tree;
6621 	struct page *page = eb->pages[0];
6622 	struct btrfs_bio_ctrl bio_ctrl = { 0 };
6623 	int ret = 0;
6624 
6625 	ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
6626 	ASSERT(PagePrivate(page));
6627 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
6628 
6629 	if (wait == WAIT_NONE) {
6630 		if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1))
6631 			return -EAGAIN;
6632 	} else {
6633 		ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6634 		if (ret < 0)
6635 			return ret;
6636 	}
6637 
6638 	ret = 0;
6639 	if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
6640 	    PageUptodate(page) ||
6641 	    btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
6642 		set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6643 		unlock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6644 		return ret;
6645 	}
6646 
6647 	clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6648 	eb->read_mirror = 0;
6649 	atomic_set(&eb->io_pages, 1);
6650 	check_buffer_tree_ref(eb);
6651 	btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
6652 
6653 	btrfs_subpage_start_reader(fs_info, page, eb->start, eb->len);
6654 	ret = submit_extent_page(REQ_OP_READ | REQ_META, NULL, &bio_ctrl,
6655 				 page, eb->start, eb->len,
6656 				 eb->start - page_offset(page),
6657 				 end_bio_extent_readpage, mirror_num, 0,
6658 				 true);
6659 	if (ret) {
6660 		/*
6661 		 * In the endio function, if we hit something wrong we will
6662 		 * increase the io_pages, so here we need to decrease it for
6663 		 * error path.
6664 		 */
6665 		atomic_dec(&eb->io_pages);
6666 	}
6667 	if (bio_ctrl.bio) {
6668 		submit_one_bio(bio_ctrl.bio, mirror_num, 0);
6669 		bio_ctrl.bio = NULL;
6670 	}
6671 	if (ret || wait != WAIT_COMPLETE)
6672 		return ret;
6673 
6674 	wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
6675 	if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6676 		ret = -EIO;
6677 	return ret;
6678 }
6679 
read_extent_buffer_pages(struct extent_buffer * eb,int wait,int mirror_num)6680 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
6681 {
6682 	int i;
6683 	struct page *page;
6684 	int err;
6685 	int ret = 0;
6686 	int locked_pages = 0;
6687 	int all_uptodate = 1;
6688 	int num_pages;
6689 	unsigned long num_reads = 0;
6690 	struct btrfs_bio_ctrl bio_ctrl = { 0 };
6691 
6692 	if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6693 		return 0;
6694 
6695 	/*
6696 	 * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
6697 	 * operation, which could potentially still be in flight.  In this case
6698 	 * we simply want to return an error.
6699 	 */
6700 	if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
6701 		return -EIO;
6702 
6703 	if (eb->fs_info->nodesize < PAGE_SIZE)
6704 		return read_extent_buffer_subpage(eb, wait, mirror_num);
6705 
6706 	num_pages = num_extent_pages(eb);
6707 	for (i = 0; i < num_pages; i++) {
6708 		page = eb->pages[i];
6709 		if (wait == WAIT_NONE) {
6710 			/*
6711 			 * WAIT_NONE is only utilized by readahead. If we can't
6712 			 * acquire the lock atomically it means either the eb
6713 			 * is being read out or under modification.
6714 			 * Either way the eb will be or has been cached,
6715 			 * readahead can exit safely.
6716 			 */
6717 			if (!trylock_page(page))
6718 				goto unlock_exit;
6719 		} else {
6720 			lock_page(page);
6721 		}
6722 		locked_pages++;
6723 	}
6724 	/*
6725 	 * We need to firstly lock all pages to make sure that
6726 	 * the uptodate bit of our pages won't be affected by
6727 	 * clear_extent_buffer_uptodate().
6728 	 */
6729 	for (i = 0; i < num_pages; i++) {
6730 		page = eb->pages[i];
6731 		if (!PageUptodate(page)) {
6732 			num_reads++;
6733 			all_uptodate = 0;
6734 		}
6735 	}
6736 
6737 	if (all_uptodate) {
6738 		set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6739 		goto unlock_exit;
6740 	}
6741 
6742 	clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6743 	eb->read_mirror = 0;
6744 	atomic_set(&eb->io_pages, num_reads);
6745 	/*
6746 	 * It is possible for release_folio to clear the TREE_REF bit before we
6747 	 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
6748 	 */
6749 	check_buffer_tree_ref(eb);
6750 	for (i = 0; i < num_pages; i++) {
6751 		page = eb->pages[i];
6752 
6753 		if (!PageUptodate(page)) {
6754 			if (ret) {
6755 				atomic_dec(&eb->io_pages);
6756 				unlock_page(page);
6757 				continue;
6758 			}
6759 
6760 			ClearPageError(page);
6761 			err = submit_extent_page(REQ_OP_READ | REQ_META, NULL,
6762 					 &bio_ctrl, page, page_offset(page),
6763 					 PAGE_SIZE, 0, end_bio_extent_readpage,
6764 					 mirror_num, 0, false);
6765 			if (err) {
6766 				/*
6767 				 * We failed to submit the bio so it's the
6768 				 * caller's responsibility to perform cleanup
6769 				 * i.e unlock page/set error bit.
6770 				 */
6771 				ret = err;
6772 				SetPageError(page);
6773 				unlock_page(page);
6774 				atomic_dec(&eb->io_pages);
6775 			}
6776 		} else {
6777 			unlock_page(page);
6778 		}
6779 	}
6780 
6781 	if (bio_ctrl.bio) {
6782 		submit_one_bio(bio_ctrl.bio, mirror_num, bio_ctrl.compress_type);
6783 		bio_ctrl.bio = NULL;
6784 	}
6785 
6786 	if (ret || wait != WAIT_COMPLETE)
6787 		return ret;
6788 
6789 	for (i = 0; i < num_pages; i++) {
6790 		page = eb->pages[i];
6791 		wait_on_page_locked(page);
6792 		if (!PageUptodate(page))
6793 			ret = -EIO;
6794 	}
6795 
6796 	return ret;
6797 
6798 unlock_exit:
6799 	while (locked_pages > 0) {
6800 		locked_pages--;
6801 		page = eb->pages[locked_pages];
6802 		unlock_page(page);
6803 	}
6804 	return ret;
6805 }
6806 
report_eb_range(const struct extent_buffer * eb,unsigned long start,unsigned long len)6807 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
6808 			    unsigned long len)
6809 {
6810 	btrfs_warn(eb->fs_info,
6811 		"access to eb bytenr %llu len %lu out of range start %lu len %lu",
6812 		eb->start, eb->len, start, len);
6813 	WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
6814 
6815 	return true;
6816 }
6817 
6818 /*
6819  * Check if the [start, start + len) range is valid before reading/writing
6820  * the eb.
6821  * NOTE: @start and @len are offset inside the eb, not logical address.
6822  *
6823  * Caller should not touch the dst/src memory if this function returns error.
6824  */
check_eb_range(const struct extent_buffer * eb,unsigned long start,unsigned long len)6825 static inline int check_eb_range(const struct extent_buffer *eb,
6826 				 unsigned long start, unsigned long len)
6827 {
6828 	unsigned long offset;
6829 
6830 	/* start, start + len should not go beyond eb->len nor overflow */
6831 	if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
6832 		return report_eb_range(eb, start, len);
6833 
6834 	return false;
6835 }
6836 
read_extent_buffer(const struct extent_buffer * eb,void * dstv,unsigned long start,unsigned long len)6837 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
6838 			unsigned long start, unsigned long len)
6839 {
6840 	size_t cur;
6841 	size_t offset;
6842 	struct page *page;
6843 	char *kaddr;
6844 	char *dst = (char *)dstv;
6845 	unsigned long i = get_eb_page_index(start);
6846 
6847 	if (check_eb_range(eb, start, len))
6848 		return;
6849 
6850 	offset = get_eb_offset_in_page(eb, start);
6851 
6852 	while (len > 0) {
6853 		page = eb->pages[i];
6854 
6855 		cur = min(len, (PAGE_SIZE - offset));
6856 		kaddr = page_address(page);
6857 		memcpy(dst, kaddr + offset, cur);
6858 
6859 		dst += cur;
6860 		len -= cur;
6861 		offset = 0;
6862 		i++;
6863 	}
6864 }
6865 
read_extent_buffer_to_user_nofault(const struct extent_buffer * eb,void __user * dstv,unsigned long start,unsigned long len)6866 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
6867 				       void __user *dstv,
6868 				       unsigned long start, unsigned long len)
6869 {
6870 	size_t cur;
6871 	size_t offset;
6872 	struct page *page;
6873 	char *kaddr;
6874 	char __user *dst = (char __user *)dstv;
6875 	unsigned long i = get_eb_page_index(start);
6876 	int ret = 0;
6877 
6878 	WARN_ON(start > eb->len);
6879 	WARN_ON(start + len > eb->start + eb->len);
6880 
6881 	offset = get_eb_offset_in_page(eb, start);
6882 
6883 	while (len > 0) {
6884 		page = eb->pages[i];
6885 
6886 		cur = min(len, (PAGE_SIZE - offset));
6887 		kaddr = page_address(page);
6888 		if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
6889 			ret = -EFAULT;
6890 			break;
6891 		}
6892 
6893 		dst += cur;
6894 		len -= cur;
6895 		offset = 0;
6896 		i++;
6897 	}
6898 
6899 	return ret;
6900 }
6901 
memcmp_extent_buffer(const struct extent_buffer * eb,const void * ptrv,unsigned long start,unsigned long len)6902 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
6903 			 unsigned long start, unsigned long len)
6904 {
6905 	size_t cur;
6906 	size_t offset;
6907 	struct page *page;
6908 	char *kaddr;
6909 	char *ptr = (char *)ptrv;
6910 	unsigned long i = get_eb_page_index(start);
6911 	int ret = 0;
6912 
6913 	if (check_eb_range(eb, start, len))
6914 		return -EINVAL;
6915 
6916 	offset = get_eb_offset_in_page(eb, start);
6917 
6918 	while (len > 0) {
6919 		page = eb->pages[i];
6920 
6921 		cur = min(len, (PAGE_SIZE - offset));
6922 
6923 		kaddr = page_address(page);
6924 		ret = memcmp(ptr, kaddr + offset, cur);
6925 		if (ret)
6926 			break;
6927 
6928 		ptr += cur;
6929 		len -= cur;
6930 		offset = 0;
6931 		i++;
6932 	}
6933 	return ret;
6934 }
6935 
6936 /*
6937  * Check that the extent buffer is uptodate.
6938  *
6939  * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
6940  * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
6941  */
assert_eb_page_uptodate(const struct extent_buffer * eb,struct page * page)6942 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
6943 				    struct page *page)
6944 {
6945 	struct btrfs_fs_info *fs_info = eb->fs_info;
6946 
6947 	/*
6948 	 * If we are using the commit root we could potentially clear a page
6949 	 * Uptodate while we're using the extent buffer that we've previously
6950 	 * looked up.  We don't want to complain in this case, as the page was
6951 	 * valid before, we just didn't write it out.  Instead we want to catch
6952 	 * the case where we didn't actually read the block properly, which
6953 	 * would have !PageUptodate && !PageError, as we clear PageError before
6954 	 * reading.
6955 	 */
6956 	if (fs_info->nodesize < PAGE_SIZE) {
6957 		bool uptodate, error;
6958 
6959 		uptodate = btrfs_subpage_test_uptodate(fs_info, page,
6960 						       eb->start, eb->len);
6961 		error = btrfs_subpage_test_error(fs_info, page, eb->start, eb->len);
6962 		WARN_ON(!uptodate && !error);
6963 	} else {
6964 		WARN_ON(!PageUptodate(page) && !PageError(page));
6965 	}
6966 }
6967 
write_extent_buffer_chunk_tree_uuid(const struct extent_buffer * eb,const void * srcv)6968 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
6969 		const void *srcv)
6970 {
6971 	char *kaddr;
6972 
6973 	assert_eb_page_uptodate(eb, eb->pages[0]);
6974 	kaddr = page_address(eb->pages[0]) +
6975 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header,
6976 						   chunk_tree_uuid));
6977 	memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
6978 }
6979 
write_extent_buffer_fsid(const struct extent_buffer * eb,const void * srcv)6980 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
6981 {
6982 	char *kaddr;
6983 
6984 	assert_eb_page_uptodate(eb, eb->pages[0]);
6985 	kaddr = page_address(eb->pages[0]) +
6986 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header, fsid));
6987 	memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
6988 }
6989 
write_extent_buffer(const struct extent_buffer * eb,const void * srcv,unsigned long start,unsigned long len)6990 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
6991 			 unsigned long start, unsigned long len)
6992 {
6993 	size_t cur;
6994 	size_t offset;
6995 	struct page *page;
6996 	char *kaddr;
6997 	char *src = (char *)srcv;
6998 	unsigned long i = get_eb_page_index(start);
6999 
7000 	WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
7001 
7002 	if (check_eb_range(eb, start, len))
7003 		return;
7004 
7005 	offset = get_eb_offset_in_page(eb, start);
7006 
7007 	while (len > 0) {
7008 		page = eb->pages[i];
7009 		assert_eb_page_uptodate(eb, page);
7010 
7011 		cur = min(len, PAGE_SIZE - offset);
7012 		kaddr = page_address(page);
7013 		memcpy(kaddr + offset, src, cur);
7014 
7015 		src += cur;
7016 		len -= cur;
7017 		offset = 0;
7018 		i++;
7019 	}
7020 }
7021 
memzero_extent_buffer(const struct extent_buffer * eb,unsigned long start,unsigned long len)7022 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
7023 		unsigned long len)
7024 {
7025 	size_t cur;
7026 	size_t offset;
7027 	struct page *page;
7028 	char *kaddr;
7029 	unsigned long i = get_eb_page_index(start);
7030 
7031 	if (check_eb_range(eb, start, len))
7032 		return;
7033 
7034 	offset = get_eb_offset_in_page(eb, start);
7035 
7036 	while (len > 0) {
7037 		page = eb->pages[i];
7038 		assert_eb_page_uptodate(eb, page);
7039 
7040 		cur = min(len, PAGE_SIZE - offset);
7041 		kaddr = page_address(page);
7042 		memset(kaddr + offset, 0, cur);
7043 
7044 		len -= cur;
7045 		offset = 0;
7046 		i++;
7047 	}
7048 }
7049 
copy_extent_buffer_full(const struct extent_buffer * dst,const struct extent_buffer * src)7050 void copy_extent_buffer_full(const struct extent_buffer *dst,
7051 			     const struct extent_buffer *src)
7052 {
7053 	int i;
7054 	int num_pages;
7055 
7056 	ASSERT(dst->len == src->len);
7057 
7058 	if (dst->fs_info->nodesize >= PAGE_SIZE) {
7059 		num_pages = num_extent_pages(dst);
7060 		for (i = 0; i < num_pages; i++)
7061 			copy_page(page_address(dst->pages[i]),
7062 				  page_address(src->pages[i]));
7063 	} else {
7064 		size_t src_offset = get_eb_offset_in_page(src, 0);
7065 		size_t dst_offset = get_eb_offset_in_page(dst, 0);
7066 
7067 		ASSERT(src->fs_info->nodesize < PAGE_SIZE);
7068 		memcpy(page_address(dst->pages[0]) + dst_offset,
7069 		       page_address(src->pages[0]) + src_offset,
7070 		       src->len);
7071 	}
7072 }
7073 
copy_extent_buffer(const struct extent_buffer * dst,const struct extent_buffer * src,unsigned long dst_offset,unsigned long src_offset,unsigned long len)7074 void copy_extent_buffer(const struct extent_buffer *dst,
7075 			const struct extent_buffer *src,
7076 			unsigned long dst_offset, unsigned long src_offset,
7077 			unsigned long len)
7078 {
7079 	u64 dst_len = dst->len;
7080 	size_t cur;
7081 	size_t offset;
7082 	struct page *page;
7083 	char *kaddr;
7084 	unsigned long i = get_eb_page_index(dst_offset);
7085 
7086 	if (check_eb_range(dst, dst_offset, len) ||
7087 	    check_eb_range(src, src_offset, len))
7088 		return;
7089 
7090 	WARN_ON(src->len != dst_len);
7091 
7092 	offset = get_eb_offset_in_page(dst, dst_offset);
7093 
7094 	while (len > 0) {
7095 		page = dst->pages[i];
7096 		assert_eb_page_uptodate(dst, page);
7097 
7098 		cur = min(len, (unsigned long)(PAGE_SIZE - offset));
7099 
7100 		kaddr = page_address(page);
7101 		read_extent_buffer(src, kaddr + offset, src_offset, cur);
7102 
7103 		src_offset += cur;
7104 		len -= cur;
7105 		offset = 0;
7106 		i++;
7107 	}
7108 }
7109 
7110 /*
7111  * eb_bitmap_offset() - calculate the page and offset of the byte containing the
7112  * given bit number
7113  * @eb: the extent buffer
7114  * @start: offset of the bitmap item in the extent buffer
7115  * @nr: bit number
7116  * @page_index: return index of the page in the extent buffer that contains the
7117  * given bit number
7118  * @page_offset: return offset into the page given by page_index
7119  *
7120  * This helper hides the ugliness of finding the byte in an extent buffer which
7121  * contains a given bit.
7122  */
eb_bitmap_offset(const struct extent_buffer * eb,unsigned long start,unsigned long nr,unsigned long * page_index,size_t * page_offset)7123 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
7124 				    unsigned long start, unsigned long nr,
7125 				    unsigned long *page_index,
7126 				    size_t *page_offset)
7127 {
7128 	size_t byte_offset = BIT_BYTE(nr);
7129 	size_t offset;
7130 
7131 	/*
7132 	 * The byte we want is the offset of the extent buffer + the offset of
7133 	 * the bitmap item in the extent buffer + the offset of the byte in the
7134 	 * bitmap item.
7135 	 */
7136 	offset = start + offset_in_page(eb->start) + byte_offset;
7137 
7138 	*page_index = offset >> PAGE_SHIFT;
7139 	*page_offset = offset_in_page(offset);
7140 }
7141 
7142 /**
7143  * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
7144  * @eb: the extent buffer
7145  * @start: offset of the bitmap item in the extent buffer
7146  * @nr: bit number to test
7147  */
extent_buffer_test_bit(const struct extent_buffer * eb,unsigned long start,unsigned long nr)7148 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
7149 			   unsigned long nr)
7150 {
7151 	u8 *kaddr;
7152 	struct page *page;
7153 	unsigned long i;
7154 	size_t offset;
7155 
7156 	eb_bitmap_offset(eb, start, nr, &i, &offset);
7157 	page = eb->pages[i];
7158 	assert_eb_page_uptodate(eb, page);
7159 	kaddr = page_address(page);
7160 	return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
7161 }
7162 
7163 /**
7164  * extent_buffer_bitmap_set - set an area of a bitmap
7165  * @eb: the extent buffer
7166  * @start: offset of the bitmap item in the extent buffer
7167  * @pos: bit number of the first bit
7168  * @len: number of bits to set
7169  */
extent_buffer_bitmap_set(const struct extent_buffer * eb,unsigned long start,unsigned long pos,unsigned long len)7170 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
7171 			      unsigned long pos, unsigned long len)
7172 {
7173 	u8 *kaddr;
7174 	struct page *page;
7175 	unsigned long i;
7176 	size_t offset;
7177 	const unsigned int size = pos + len;
7178 	int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
7179 	u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
7180 
7181 	eb_bitmap_offset(eb, start, pos, &i, &offset);
7182 	page = eb->pages[i];
7183 	assert_eb_page_uptodate(eb, page);
7184 	kaddr = page_address(page);
7185 
7186 	while (len >= bits_to_set) {
7187 		kaddr[offset] |= mask_to_set;
7188 		len -= bits_to_set;
7189 		bits_to_set = BITS_PER_BYTE;
7190 		mask_to_set = ~0;
7191 		if (++offset >= PAGE_SIZE && len > 0) {
7192 			offset = 0;
7193 			page = eb->pages[++i];
7194 			assert_eb_page_uptodate(eb, page);
7195 			kaddr = page_address(page);
7196 		}
7197 	}
7198 	if (len) {
7199 		mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
7200 		kaddr[offset] |= mask_to_set;
7201 	}
7202 }
7203 
7204 
7205 /**
7206  * extent_buffer_bitmap_clear - clear an area of a bitmap
7207  * @eb: the extent buffer
7208  * @start: offset of the bitmap item in the extent buffer
7209  * @pos: bit number of the first bit
7210  * @len: number of bits to clear
7211  */
extent_buffer_bitmap_clear(const struct extent_buffer * eb,unsigned long start,unsigned long pos,unsigned long len)7212 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
7213 				unsigned long start, unsigned long pos,
7214 				unsigned long len)
7215 {
7216 	u8 *kaddr;
7217 	struct page *page;
7218 	unsigned long i;
7219 	size_t offset;
7220 	const unsigned int size = pos + len;
7221 	int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
7222 	u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
7223 
7224 	eb_bitmap_offset(eb, start, pos, &i, &offset);
7225 	page = eb->pages[i];
7226 	assert_eb_page_uptodate(eb, page);
7227 	kaddr = page_address(page);
7228 
7229 	while (len >= bits_to_clear) {
7230 		kaddr[offset] &= ~mask_to_clear;
7231 		len -= bits_to_clear;
7232 		bits_to_clear = BITS_PER_BYTE;
7233 		mask_to_clear = ~0;
7234 		if (++offset >= PAGE_SIZE && len > 0) {
7235 			offset = 0;
7236 			page = eb->pages[++i];
7237 			assert_eb_page_uptodate(eb, page);
7238 			kaddr = page_address(page);
7239 		}
7240 	}
7241 	if (len) {
7242 		mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
7243 		kaddr[offset] &= ~mask_to_clear;
7244 	}
7245 }
7246 
areas_overlap(unsigned long src,unsigned long dst,unsigned long len)7247 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
7248 {
7249 	unsigned long distance = (src > dst) ? src - dst : dst - src;
7250 	return distance < len;
7251 }
7252 
copy_pages(struct page * dst_page,struct page * src_page,unsigned long dst_off,unsigned long src_off,unsigned long len)7253 static void copy_pages(struct page *dst_page, struct page *src_page,
7254 		       unsigned long dst_off, unsigned long src_off,
7255 		       unsigned long len)
7256 {
7257 	char *dst_kaddr = page_address(dst_page);
7258 	char *src_kaddr;
7259 	int must_memmove = 0;
7260 
7261 	if (dst_page != src_page) {
7262 		src_kaddr = page_address(src_page);
7263 	} else {
7264 		src_kaddr = dst_kaddr;
7265 		if (areas_overlap(src_off, dst_off, len))
7266 			must_memmove = 1;
7267 	}
7268 
7269 	if (must_memmove)
7270 		memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
7271 	else
7272 		memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
7273 }
7274 
memcpy_extent_buffer(const struct extent_buffer * dst,unsigned long dst_offset,unsigned long src_offset,unsigned long len)7275 void memcpy_extent_buffer(const struct extent_buffer *dst,
7276 			  unsigned long dst_offset, unsigned long src_offset,
7277 			  unsigned long len)
7278 {
7279 	size_t cur;
7280 	size_t dst_off_in_page;
7281 	size_t src_off_in_page;
7282 	unsigned long dst_i;
7283 	unsigned long src_i;
7284 
7285 	if (check_eb_range(dst, dst_offset, len) ||
7286 	    check_eb_range(dst, src_offset, len))
7287 		return;
7288 
7289 	while (len > 0) {
7290 		dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
7291 		src_off_in_page = get_eb_offset_in_page(dst, src_offset);
7292 
7293 		dst_i = get_eb_page_index(dst_offset);
7294 		src_i = get_eb_page_index(src_offset);
7295 
7296 		cur = min(len, (unsigned long)(PAGE_SIZE -
7297 					       src_off_in_page));
7298 		cur = min_t(unsigned long, cur,
7299 			(unsigned long)(PAGE_SIZE - dst_off_in_page));
7300 
7301 		copy_pages(dst->pages[dst_i], dst->pages[src_i],
7302 			   dst_off_in_page, src_off_in_page, cur);
7303 
7304 		src_offset += cur;
7305 		dst_offset += cur;
7306 		len -= cur;
7307 	}
7308 }
7309 
memmove_extent_buffer(const struct extent_buffer * dst,unsigned long dst_offset,unsigned long src_offset,unsigned long len)7310 void memmove_extent_buffer(const struct extent_buffer *dst,
7311 			   unsigned long dst_offset, unsigned long src_offset,
7312 			   unsigned long len)
7313 {
7314 	size_t cur;
7315 	size_t dst_off_in_page;
7316 	size_t src_off_in_page;
7317 	unsigned long dst_end = dst_offset + len - 1;
7318 	unsigned long src_end = src_offset + len - 1;
7319 	unsigned long dst_i;
7320 	unsigned long src_i;
7321 
7322 	if (check_eb_range(dst, dst_offset, len) ||
7323 	    check_eb_range(dst, src_offset, len))
7324 		return;
7325 	if (dst_offset < src_offset) {
7326 		memcpy_extent_buffer(dst, dst_offset, src_offset, len);
7327 		return;
7328 	}
7329 	while (len > 0) {
7330 		dst_i = get_eb_page_index(dst_end);
7331 		src_i = get_eb_page_index(src_end);
7332 
7333 		dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
7334 		src_off_in_page = get_eb_offset_in_page(dst, src_end);
7335 
7336 		cur = min_t(unsigned long, len, src_off_in_page + 1);
7337 		cur = min(cur, dst_off_in_page + 1);
7338 		copy_pages(dst->pages[dst_i], dst->pages[src_i],
7339 			   dst_off_in_page - cur + 1,
7340 			   src_off_in_page - cur + 1, cur);
7341 
7342 		dst_end -= cur;
7343 		src_end -= cur;
7344 		len -= cur;
7345 	}
7346 }
7347 
7348 #define GANG_LOOKUP_SIZE	16
get_next_extent_buffer(struct btrfs_fs_info * fs_info,struct page * page,u64 bytenr)7349 static struct extent_buffer *get_next_extent_buffer(
7350 		struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
7351 {
7352 	struct extent_buffer *gang[GANG_LOOKUP_SIZE];
7353 	struct extent_buffer *found = NULL;
7354 	u64 page_start = page_offset(page);
7355 	u64 cur = page_start;
7356 
7357 	ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
7358 	lockdep_assert_held(&fs_info->buffer_lock);
7359 
7360 	while (cur < page_start + PAGE_SIZE) {
7361 		int ret;
7362 		int i;
7363 
7364 		ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
7365 				(void **)gang, cur >> fs_info->sectorsize_bits,
7366 				min_t(unsigned int, GANG_LOOKUP_SIZE,
7367 				      PAGE_SIZE / fs_info->nodesize));
7368 		if (ret == 0)
7369 			goto out;
7370 		for (i = 0; i < ret; i++) {
7371 			/* Already beyond page end */
7372 			if (gang[i]->start >= page_start + PAGE_SIZE)
7373 				goto out;
7374 			/* Found one */
7375 			if (gang[i]->start >= bytenr) {
7376 				found = gang[i];
7377 				goto out;
7378 			}
7379 		}
7380 		cur = gang[ret - 1]->start + gang[ret - 1]->len;
7381 	}
7382 out:
7383 	return found;
7384 }
7385 
try_release_subpage_extent_buffer(struct page * page)7386 static int try_release_subpage_extent_buffer(struct page *page)
7387 {
7388 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
7389 	u64 cur = page_offset(page);
7390 	const u64 end = page_offset(page) + PAGE_SIZE;
7391 	int ret;
7392 
7393 	while (cur < end) {
7394 		struct extent_buffer *eb = NULL;
7395 
7396 		/*
7397 		 * Unlike try_release_extent_buffer() which uses page->private
7398 		 * to grab buffer, for subpage case we rely on radix tree, thus
7399 		 * we need to ensure radix tree consistency.
7400 		 *
7401 		 * We also want an atomic snapshot of the radix tree, thus go
7402 		 * with spinlock rather than RCU.
7403 		 */
7404 		spin_lock(&fs_info->buffer_lock);
7405 		eb = get_next_extent_buffer(fs_info, page, cur);
7406 		if (!eb) {
7407 			/* No more eb in the page range after or at cur */
7408 			spin_unlock(&fs_info->buffer_lock);
7409 			break;
7410 		}
7411 		cur = eb->start + eb->len;
7412 
7413 		/*
7414 		 * The same as try_release_extent_buffer(), to ensure the eb
7415 		 * won't disappear out from under us.
7416 		 */
7417 		spin_lock(&eb->refs_lock);
7418 		if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7419 			spin_unlock(&eb->refs_lock);
7420 			spin_unlock(&fs_info->buffer_lock);
7421 			break;
7422 		}
7423 		spin_unlock(&fs_info->buffer_lock);
7424 
7425 		/*
7426 		 * If tree ref isn't set then we know the ref on this eb is a
7427 		 * real ref, so just return, this eb will likely be freed soon
7428 		 * anyway.
7429 		 */
7430 		if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7431 			spin_unlock(&eb->refs_lock);
7432 			break;
7433 		}
7434 
7435 		/*
7436 		 * Here we don't care about the return value, we will always
7437 		 * check the page private at the end.  And
7438 		 * release_extent_buffer() will release the refs_lock.
7439 		 */
7440 		release_extent_buffer(eb);
7441 	}
7442 	/*
7443 	 * Finally to check if we have cleared page private, as if we have
7444 	 * released all ebs in the page, the page private should be cleared now.
7445 	 */
7446 	spin_lock(&page->mapping->private_lock);
7447 	if (!PagePrivate(page))
7448 		ret = 1;
7449 	else
7450 		ret = 0;
7451 	spin_unlock(&page->mapping->private_lock);
7452 	return ret;
7453 
7454 }
7455 
try_release_extent_buffer(struct page * page)7456 int try_release_extent_buffer(struct page *page)
7457 {
7458 	struct extent_buffer *eb;
7459 
7460 	if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
7461 		return try_release_subpage_extent_buffer(page);
7462 
7463 	/*
7464 	 * We need to make sure nobody is changing page->private, as we rely on
7465 	 * page->private as the pointer to extent buffer.
7466 	 */
7467 	spin_lock(&page->mapping->private_lock);
7468 	if (!PagePrivate(page)) {
7469 		spin_unlock(&page->mapping->private_lock);
7470 		return 1;
7471 	}
7472 
7473 	eb = (struct extent_buffer *)page->private;
7474 	BUG_ON(!eb);
7475 
7476 	/*
7477 	 * This is a little awful but should be ok, we need to make sure that
7478 	 * the eb doesn't disappear out from under us while we're looking at
7479 	 * this page.
7480 	 */
7481 	spin_lock(&eb->refs_lock);
7482 	if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
7483 		spin_unlock(&eb->refs_lock);
7484 		spin_unlock(&page->mapping->private_lock);
7485 		return 0;
7486 	}
7487 	spin_unlock(&page->mapping->private_lock);
7488 
7489 	/*
7490 	 * If tree ref isn't set then we know the ref on this eb is a real ref,
7491 	 * so just return, this page will likely be freed soon anyway.
7492 	 */
7493 	if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7494 		spin_unlock(&eb->refs_lock);
7495 		return 0;
7496 	}
7497 
7498 	return release_extent_buffer(eb);
7499 }
7500 
7501 /*
7502  * btrfs_readahead_tree_block - attempt to readahead a child block
7503  * @fs_info:	the fs_info
7504  * @bytenr:	bytenr to read
7505  * @owner_root: objectid of the root that owns this eb
7506  * @gen:	generation for the uptodate check, can be 0
7507  * @level:	level for the eb
7508  *
7509  * Attempt to readahead a tree block at @bytenr.  If @gen is 0 then we do a
7510  * normal uptodate check of the eb, without checking the generation.  If we have
7511  * to read the block we will not block on anything.
7512  */
btrfs_readahead_tree_block(struct btrfs_fs_info * fs_info,u64 bytenr,u64 owner_root,u64 gen,int level)7513 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
7514 				u64 bytenr, u64 owner_root, u64 gen, int level)
7515 {
7516 	struct extent_buffer *eb;
7517 	int ret;
7518 
7519 	eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
7520 	if (IS_ERR(eb))
7521 		return;
7522 
7523 	if (btrfs_buffer_uptodate(eb, gen, 1)) {
7524 		free_extent_buffer(eb);
7525 		return;
7526 	}
7527 
7528 	ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
7529 	if (ret < 0)
7530 		free_extent_buffer_stale(eb);
7531 	else
7532 		free_extent_buffer(eb);
7533 }
7534 
7535 /*
7536  * btrfs_readahead_node_child - readahead a node's child block
7537  * @node:	parent node we're reading from
7538  * @slot:	slot in the parent node for the child we want to read
7539  *
7540  * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
7541  * the slot in the node provided.
7542  */
btrfs_readahead_node_child(struct extent_buffer * node,int slot)7543 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
7544 {
7545 	btrfs_readahead_tree_block(node->fs_info,
7546 				   btrfs_node_blockptr(node, slot),
7547 				   btrfs_header_owner(node),
7548 				   btrfs_node_ptr_generation(node, slot),
7549 				   btrfs_header_level(node) - 1);
7550 }
7551