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/spinlock.h>
10 #include <linux/blkdev.h>
11 #include <linux/swap.h>
12 #include <linux/writeback.h>
13 #include <linux/pagevec.h>
14 #include <linux/prefetch.h>
15 #include <linux/cleancache.h>
16 #include "extent_io.h"
17 #include "extent_map.h"
18 #include "ctree.h"
19 #include "btrfs_inode.h"
20 #include "volumes.h"
21 #include "check-integrity.h"
22 #include "locking.h"
23 #include "rcu-string.h"
24 #include "backref.h"
25 #include "disk-io.h"
26 
27 static struct kmem_cache *extent_state_cache;
28 static struct kmem_cache *extent_buffer_cache;
29 static struct bio_set btrfs_bioset;
30 
extent_state_in_tree(const struct extent_state * state)31 static inline bool extent_state_in_tree(const struct extent_state *state)
32 {
33 	return !RB_EMPTY_NODE(&state->rb_node);
34 }
35 
36 #ifdef CONFIG_BTRFS_DEBUG
37 static LIST_HEAD(buffers);
38 static LIST_HEAD(states);
39 
40 static DEFINE_SPINLOCK(leak_lock);
41 
42 static inline
btrfs_leak_debug_add(struct list_head * new,struct list_head * head)43 void btrfs_leak_debug_add(struct list_head *new, struct list_head *head)
44 {
45 	unsigned long flags;
46 
47 	spin_lock_irqsave(&leak_lock, flags);
48 	list_add(new, head);
49 	spin_unlock_irqrestore(&leak_lock, flags);
50 }
51 
52 static inline
btrfs_leak_debug_del(struct list_head * entry)53 void btrfs_leak_debug_del(struct list_head *entry)
54 {
55 	unsigned long flags;
56 
57 	spin_lock_irqsave(&leak_lock, flags);
58 	list_del(entry);
59 	spin_unlock_irqrestore(&leak_lock, flags);
60 }
61 
62 static inline
btrfs_leak_debug_check(void)63 void btrfs_leak_debug_check(void)
64 {
65 	struct extent_state *state;
66 	struct extent_buffer *eb;
67 
68 	while (!list_empty(&states)) {
69 		state = list_entry(states.next, struct extent_state, leak_list);
70 		pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
71 		       state->start, state->end, state->state,
72 		       extent_state_in_tree(state),
73 		       refcount_read(&state->refs));
74 		list_del(&state->leak_list);
75 		kmem_cache_free(extent_state_cache, state);
76 	}
77 
78 	while (!list_empty(&buffers)) {
79 		eb = list_entry(buffers.next, struct extent_buffer, leak_list);
80 		pr_err("BTRFS: buffer leak start %llu len %lu refs %d bflags %lu\n",
81 		       eb->start, eb->len, atomic_read(&eb->refs), eb->bflags);
82 		list_del(&eb->leak_list);
83 		kmem_cache_free(extent_buffer_cache, eb);
84 	}
85 }
86 
87 #define btrfs_debug_check_extent_io_range(tree, start, end)		\
88 	__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)89 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
90 		struct extent_io_tree *tree, u64 start, u64 end)
91 {
92 	if (tree->ops && tree->ops->check_extent_io_range)
93 		tree->ops->check_extent_io_range(tree->private_data, caller,
94 						 start, end);
95 }
96 #else
97 #define btrfs_leak_debug_add(new, head)	do {} while (0)
98 #define btrfs_leak_debug_del(entry)	do {} while (0)
99 #define btrfs_leak_debug_check()	do {} while (0)
100 #define btrfs_debug_check_extent_io_range(c, s, e)	do {} while (0)
101 #endif
102 
103 #define BUFFER_LRU_MAX 64
104 
105 struct tree_entry {
106 	u64 start;
107 	u64 end;
108 	struct rb_node rb_node;
109 };
110 
111 struct extent_page_data {
112 	struct bio *bio;
113 	struct extent_io_tree *tree;
114 	/* tells writepage not to lock the state bits for this range
115 	 * it still does the unlocking
116 	 */
117 	unsigned int extent_locked:1;
118 
119 	/* tells the submit_bio code to use REQ_SYNC */
120 	unsigned int sync_io:1;
121 };
122 
add_extent_changeset(struct extent_state * state,unsigned bits,struct extent_changeset * changeset,int set)123 static int add_extent_changeset(struct extent_state *state, unsigned bits,
124 				 struct extent_changeset *changeset,
125 				 int set)
126 {
127 	int ret;
128 
129 	if (!changeset)
130 		return 0;
131 	if (set && (state->state & bits) == bits)
132 		return 0;
133 	if (!set && (state->state & bits) == 0)
134 		return 0;
135 	changeset->bytes_changed += state->end - state->start + 1;
136 	ret = ulist_add(&changeset->range_changed, state->start, state->end,
137 			GFP_ATOMIC);
138 	return ret;
139 }
140 
submit_one_bio(struct bio * bio,int mirror_num,unsigned long bio_flags)141 static int __must_check submit_one_bio(struct bio *bio, int mirror_num,
142 				       unsigned long bio_flags)
143 {
144 	blk_status_t ret = 0;
145 	struct bio_vec *bvec = bio_last_bvec_all(bio);
146 	struct page *page = bvec->bv_page;
147 	struct extent_io_tree *tree = bio->bi_private;
148 	u64 start;
149 
150 	start = page_offset(page) + bvec->bv_offset;
151 
152 	bio->bi_private = NULL;
153 
154 	if (tree->ops)
155 		ret = tree->ops->submit_bio_hook(tree->private_data, bio,
156 					   mirror_num, bio_flags, start);
157 	else
158 		btrfsic_submit_bio(bio);
159 
160 	return blk_status_to_errno(ret);
161 }
162 
163 /* Cleanup unsubmitted bios */
end_write_bio(struct extent_page_data * epd,int ret)164 static void end_write_bio(struct extent_page_data *epd, int ret)
165 {
166 	if (epd->bio) {
167 		epd->bio->bi_status = errno_to_blk_status(ret);
168 		bio_endio(epd->bio);
169 		epd->bio = NULL;
170 	}
171 }
172 
173 /*
174  * Submit bio from extent page data via submit_one_bio
175  *
176  * Return 0 if everything is OK.
177  * Return <0 for error.
178  */
flush_write_bio(struct extent_page_data * epd)179 static int __must_check flush_write_bio(struct extent_page_data *epd)
180 {
181 	int ret = 0;
182 
183 	if (epd->bio) {
184 		ret = submit_one_bio(epd->bio, 0, 0);
185 		/*
186 		 * Clean up of epd->bio is handled by its endio function.
187 		 * And endio is either triggered by successful bio execution
188 		 * or the error handler of submit bio hook.
189 		 * So at this point, no matter what happened, we don't need
190 		 * to clean up epd->bio.
191 		 */
192 		epd->bio = NULL;
193 	}
194 	return ret;
195 }
196 
extent_io_init(void)197 int __init extent_io_init(void)
198 {
199 	extent_state_cache = kmem_cache_create("btrfs_extent_state",
200 			sizeof(struct extent_state), 0,
201 			SLAB_MEM_SPREAD, NULL);
202 	if (!extent_state_cache)
203 		return -ENOMEM;
204 
205 	extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
206 			sizeof(struct extent_buffer), 0,
207 			SLAB_MEM_SPREAD, NULL);
208 	if (!extent_buffer_cache)
209 		goto free_state_cache;
210 
211 	if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
212 			offsetof(struct btrfs_io_bio, bio),
213 			BIOSET_NEED_BVECS))
214 		goto free_buffer_cache;
215 
216 	if (bioset_integrity_create(&btrfs_bioset, BIO_POOL_SIZE))
217 		goto free_bioset;
218 
219 	return 0;
220 
221 free_bioset:
222 	bioset_exit(&btrfs_bioset);
223 
224 free_buffer_cache:
225 	kmem_cache_destroy(extent_buffer_cache);
226 	extent_buffer_cache = NULL;
227 
228 free_state_cache:
229 	kmem_cache_destroy(extent_state_cache);
230 	extent_state_cache = NULL;
231 	return -ENOMEM;
232 }
233 
extent_io_exit(void)234 void __cold extent_io_exit(void)
235 {
236 	btrfs_leak_debug_check();
237 
238 	/*
239 	 * Make sure all delayed rcu free are flushed before we
240 	 * destroy caches.
241 	 */
242 	rcu_barrier();
243 	kmem_cache_destroy(extent_state_cache);
244 	kmem_cache_destroy(extent_buffer_cache);
245 	bioset_exit(&btrfs_bioset);
246 }
247 
extent_io_tree_init(struct extent_io_tree * tree,void * private_data)248 void extent_io_tree_init(struct extent_io_tree *tree,
249 			 void *private_data)
250 {
251 	tree->state = RB_ROOT;
252 	tree->ops = NULL;
253 	tree->dirty_bytes = 0;
254 	spin_lock_init(&tree->lock);
255 	tree->private_data = private_data;
256 }
257 
alloc_extent_state(gfp_t mask)258 static struct extent_state *alloc_extent_state(gfp_t mask)
259 {
260 	struct extent_state *state;
261 
262 	/*
263 	 * The given mask might be not appropriate for the slab allocator,
264 	 * drop the unsupported bits
265 	 */
266 	mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
267 	state = kmem_cache_alloc(extent_state_cache, mask);
268 	if (!state)
269 		return state;
270 	state->state = 0;
271 	state->failrec = NULL;
272 	RB_CLEAR_NODE(&state->rb_node);
273 	btrfs_leak_debug_add(&state->leak_list, &states);
274 	refcount_set(&state->refs, 1);
275 	init_waitqueue_head(&state->wq);
276 	trace_alloc_extent_state(state, mask, _RET_IP_);
277 	return state;
278 }
279 
free_extent_state(struct extent_state * state)280 void free_extent_state(struct extent_state *state)
281 {
282 	if (!state)
283 		return;
284 	if (refcount_dec_and_test(&state->refs)) {
285 		WARN_ON(extent_state_in_tree(state));
286 		btrfs_leak_debug_del(&state->leak_list);
287 		trace_free_extent_state(state, _RET_IP_);
288 		kmem_cache_free(extent_state_cache, state);
289 	}
290 }
291 
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)292 static struct rb_node *tree_insert(struct rb_root *root,
293 				   struct rb_node *search_start,
294 				   u64 offset,
295 				   struct rb_node *node,
296 				   struct rb_node ***p_in,
297 				   struct rb_node **parent_in)
298 {
299 	struct rb_node **p;
300 	struct rb_node *parent = NULL;
301 	struct tree_entry *entry;
302 
303 	if (p_in && parent_in) {
304 		p = *p_in;
305 		parent = *parent_in;
306 		goto do_insert;
307 	}
308 
309 	p = search_start ? &search_start : &root->rb_node;
310 	while (*p) {
311 		parent = *p;
312 		entry = rb_entry(parent, struct tree_entry, rb_node);
313 
314 		if (offset < entry->start)
315 			p = &(*p)->rb_left;
316 		else if (offset > entry->end)
317 			p = &(*p)->rb_right;
318 		else
319 			return parent;
320 	}
321 
322 do_insert:
323 	rb_link_node(node, parent, p);
324 	rb_insert_color(node, root);
325 	return NULL;
326 }
327 
__etree_search(struct extent_io_tree * tree,u64 offset,struct rb_node ** prev_ret,struct rb_node ** next_ret,struct rb_node *** p_ret,struct rb_node ** parent_ret)328 static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
329 				      struct rb_node **prev_ret,
330 				      struct rb_node **next_ret,
331 				      struct rb_node ***p_ret,
332 				      struct rb_node **parent_ret)
333 {
334 	struct rb_root *root = &tree->state;
335 	struct rb_node **n = &root->rb_node;
336 	struct rb_node *prev = NULL;
337 	struct rb_node *orig_prev = NULL;
338 	struct tree_entry *entry;
339 	struct tree_entry *prev_entry = NULL;
340 
341 	while (*n) {
342 		prev = *n;
343 		entry = rb_entry(prev, struct tree_entry, rb_node);
344 		prev_entry = entry;
345 
346 		if (offset < entry->start)
347 			n = &(*n)->rb_left;
348 		else if (offset > entry->end)
349 			n = &(*n)->rb_right;
350 		else
351 			return *n;
352 	}
353 
354 	if (p_ret)
355 		*p_ret = n;
356 	if (parent_ret)
357 		*parent_ret = prev;
358 
359 	if (prev_ret) {
360 		orig_prev = prev;
361 		while (prev && offset > prev_entry->end) {
362 			prev = rb_next(prev);
363 			prev_entry = rb_entry(prev, struct tree_entry, rb_node);
364 		}
365 		*prev_ret = prev;
366 		prev = orig_prev;
367 	}
368 
369 	if (next_ret) {
370 		prev_entry = rb_entry(prev, struct tree_entry, rb_node);
371 		while (prev && offset < prev_entry->start) {
372 			prev = rb_prev(prev);
373 			prev_entry = rb_entry(prev, struct tree_entry, rb_node);
374 		}
375 		*next_ret = prev;
376 	}
377 	return NULL;
378 }
379 
380 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)381 tree_search_for_insert(struct extent_io_tree *tree,
382 		       u64 offset,
383 		       struct rb_node ***p_ret,
384 		       struct rb_node **parent_ret)
385 {
386 	struct rb_node *prev = NULL;
387 	struct rb_node *ret;
388 
389 	ret = __etree_search(tree, offset, &prev, NULL, p_ret, parent_ret);
390 	if (!ret)
391 		return prev;
392 	return ret;
393 }
394 
tree_search(struct extent_io_tree * tree,u64 offset)395 static inline struct rb_node *tree_search(struct extent_io_tree *tree,
396 					  u64 offset)
397 {
398 	return tree_search_for_insert(tree, offset, NULL, NULL);
399 }
400 
merge_cb(struct extent_io_tree * tree,struct extent_state * new,struct extent_state * other)401 static void merge_cb(struct extent_io_tree *tree, struct extent_state *new,
402 		     struct extent_state *other)
403 {
404 	if (tree->ops && tree->ops->merge_extent_hook)
405 		tree->ops->merge_extent_hook(tree->private_data, new, other);
406 }
407 
408 /*
409  * utility function to look for merge candidates inside a given range.
410  * Any extents with matching state are merged together into a single
411  * extent in the tree.  Extents with EXTENT_IO in their state field
412  * are not merged because the end_io handlers need to be able to do
413  * operations on them without sleeping (or doing allocations/splits).
414  *
415  * This should be called with the tree lock held.
416  */
merge_state(struct extent_io_tree * tree,struct extent_state * state)417 static void merge_state(struct extent_io_tree *tree,
418 		        struct extent_state *state)
419 {
420 	struct extent_state *other;
421 	struct rb_node *other_node;
422 
423 	if (state->state & (EXTENT_IOBITS | EXTENT_BOUNDARY))
424 		return;
425 
426 	other_node = rb_prev(&state->rb_node);
427 	if (other_node) {
428 		other = rb_entry(other_node, struct extent_state, rb_node);
429 		if (other->end == state->start - 1 &&
430 		    other->state == state->state) {
431 			merge_cb(tree, state, other);
432 			state->start = other->start;
433 			rb_erase(&other->rb_node, &tree->state);
434 			RB_CLEAR_NODE(&other->rb_node);
435 			free_extent_state(other);
436 		}
437 	}
438 	other_node = rb_next(&state->rb_node);
439 	if (other_node) {
440 		other = rb_entry(other_node, struct extent_state, rb_node);
441 		if (other->start == state->end + 1 &&
442 		    other->state == state->state) {
443 			merge_cb(tree, state, other);
444 			state->end = other->end;
445 			rb_erase(&other->rb_node, &tree->state);
446 			RB_CLEAR_NODE(&other->rb_node);
447 			free_extent_state(other);
448 		}
449 	}
450 }
451 
set_state_cb(struct extent_io_tree * tree,struct extent_state * state,unsigned * bits)452 static void set_state_cb(struct extent_io_tree *tree,
453 			 struct extent_state *state, unsigned *bits)
454 {
455 	if (tree->ops && tree->ops->set_bit_hook)
456 		tree->ops->set_bit_hook(tree->private_data, state, bits);
457 }
458 
clear_state_cb(struct extent_io_tree * tree,struct extent_state * state,unsigned * bits)459 static void clear_state_cb(struct extent_io_tree *tree,
460 			   struct extent_state *state, unsigned *bits)
461 {
462 	if (tree->ops && tree->ops->clear_bit_hook)
463 		tree->ops->clear_bit_hook(tree->private_data, state, bits);
464 }
465 
466 static void set_state_bits(struct extent_io_tree *tree,
467 			   struct extent_state *state, unsigned *bits,
468 			   struct extent_changeset *changeset);
469 
470 /*
471  * insert an extent_state struct into the tree.  'bits' are set on the
472  * struct before it is inserted.
473  *
474  * This may return -EEXIST if the extent is already there, in which case the
475  * state struct is freed.
476  *
477  * The tree lock is not taken internally.  This is a utility function and
478  * probably isn't what you want to call (see set/clear_extent_bit).
479  */
insert_state(struct extent_io_tree * tree,struct extent_state * state,u64 start,u64 end,struct rb_node *** p,struct rb_node ** parent,unsigned * bits,struct extent_changeset * changeset)480 static int insert_state(struct extent_io_tree *tree,
481 			struct extent_state *state, u64 start, u64 end,
482 			struct rb_node ***p,
483 			struct rb_node **parent,
484 			unsigned *bits, struct extent_changeset *changeset)
485 {
486 	struct rb_node *node;
487 
488 	if (end < start)
489 		WARN(1, KERN_ERR "BTRFS: end < start %llu %llu\n",
490 		       end, start);
491 	state->start = start;
492 	state->end = end;
493 
494 	set_state_bits(tree, state, bits, changeset);
495 
496 	node = tree_insert(&tree->state, NULL, end, &state->rb_node, p, parent);
497 	if (node) {
498 		struct extent_state *found;
499 		found = rb_entry(node, struct extent_state, rb_node);
500 		pr_err("BTRFS: found node %llu %llu on insert of %llu %llu\n",
501 		       found->start, found->end, start, end);
502 		return -EEXIST;
503 	}
504 	merge_state(tree, state);
505 	return 0;
506 }
507 
split_cb(struct extent_io_tree * tree,struct extent_state * orig,u64 split)508 static void split_cb(struct extent_io_tree *tree, struct extent_state *orig,
509 		     u64 split)
510 {
511 	if (tree->ops && tree->ops->split_extent_hook)
512 		tree->ops->split_extent_hook(tree->private_data, orig, split);
513 }
514 
515 /*
516  * split a given extent state struct in two, inserting the preallocated
517  * struct 'prealloc' as the newly created second half.  'split' indicates an
518  * offset inside 'orig' where it should be split.
519  *
520  * Before calling,
521  * the tree has 'orig' at [orig->start, orig->end].  After calling, there
522  * are two extent state structs in the tree:
523  * prealloc: [orig->start, split - 1]
524  * orig: [ split, orig->end ]
525  *
526  * The tree locks are not taken by this function. They need to be held
527  * by the caller.
528  */
split_state(struct extent_io_tree * tree,struct extent_state * orig,struct extent_state * prealloc,u64 split)529 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
530 		       struct extent_state *prealloc, u64 split)
531 {
532 	struct rb_node *node;
533 
534 	split_cb(tree, orig, split);
535 
536 	prealloc->start = orig->start;
537 	prealloc->end = split - 1;
538 	prealloc->state = orig->state;
539 	orig->start = split;
540 
541 	node = tree_insert(&tree->state, &orig->rb_node, prealloc->end,
542 			   &prealloc->rb_node, NULL, NULL);
543 	if (node) {
544 		free_extent_state(prealloc);
545 		return -EEXIST;
546 	}
547 	return 0;
548 }
549 
next_state(struct extent_state * state)550 static struct extent_state *next_state(struct extent_state *state)
551 {
552 	struct rb_node *next = rb_next(&state->rb_node);
553 	if (next)
554 		return rb_entry(next, struct extent_state, rb_node);
555 	else
556 		return NULL;
557 }
558 
559 /*
560  * utility function to clear some bits in an extent state struct.
561  * it will optionally wake up any one waiting on this state (wake == 1).
562  *
563  * If no bits are set on the state struct after clearing things, the
564  * struct is freed and removed from the tree
565  */
clear_state_bit(struct extent_io_tree * tree,struct extent_state * state,unsigned * bits,int wake,struct extent_changeset * changeset)566 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
567 					    struct extent_state *state,
568 					    unsigned *bits, int wake,
569 					    struct extent_changeset *changeset)
570 {
571 	struct extent_state *next;
572 	unsigned bits_to_clear = *bits & ~EXTENT_CTLBITS;
573 	int ret;
574 
575 	if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
576 		u64 range = state->end - state->start + 1;
577 		WARN_ON(range > tree->dirty_bytes);
578 		tree->dirty_bytes -= range;
579 	}
580 	clear_state_cb(tree, state, bits);
581 	ret = add_extent_changeset(state, bits_to_clear, changeset, 0);
582 	BUG_ON(ret < 0);
583 	state->state &= ~bits_to_clear;
584 	if (wake)
585 		wake_up(&state->wq);
586 	if (state->state == 0) {
587 		next = next_state(state);
588 		if (extent_state_in_tree(state)) {
589 			rb_erase(&state->rb_node, &tree->state);
590 			RB_CLEAR_NODE(&state->rb_node);
591 			free_extent_state(state);
592 		} else {
593 			WARN_ON(1);
594 		}
595 	} else {
596 		merge_state(tree, state);
597 		next = next_state(state);
598 	}
599 	return next;
600 }
601 
602 static struct extent_state *
alloc_extent_state_atomic(struct extent_state * prealloc)603 alloc_extent_state_atomic(struct extent_state *prealloc)
604 {
605 	if (!prealloc)
606 		prealloc = alloc_extent_state(GFP_ATOMIC);
607 
608 	return prealloc;
609 }
610 
extent_io_tree_panic(struct extent_io_tree * tree,int err)611 static void extent_io_tree_panic(struct extent_io_tree *tree, int err)
612 {
613 	struct inode *inode = tree->private_data;
614 
615 	btrfs_panic(btrfs_sb(inode->i_sb), err,
616 	"locking error: extent tree was modified by another thread while locked");
617 }
618 
619 /*
620  * clear some bits on a range in the tree.  This may require splitting
621  * or inserting elements in the tree, so the gfp mask is used to
622  * indicate which allocations or sleeping are allowed.
623  *
624  * pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
625  * the given range from the tree regardless of state (ie for truncate).
626  *
627  * the range [start, end] is inclusive.
628  *
629  * This takes the tree lock, and returns 0 on success and < 0 on error.
630  */
__clear_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,unsigned bits,int wake,int delete,struct extent_state ** cached_state,gfp_t mask,struct extent_changeset * changeset)631 int __clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
632 			      unsigned bits, int wake, int delete,
633 			      struct extent_state **cached_state,
634 			      gfp_t mask, struct extent_changeset *changeset)
635 {
636 	struct extent_state *state;
637 	struct extent_state *cached;
638 	struct extent_state *prealloc = NULL;
639 	struct rb_node *node;
640 	u64 last_end;
641 	int err;
642 	int clear = 0;
643 
644 	btrfs_debug_check_extent_io_range(tree, start, end);
645 
646 	if (bits & EXTENT_DELALLOC)
647 		bits |= EXTENT_NORESERVE;
648 
649 	if (delete)
650 		bits |= ~EXTENT_CTLBITS;
651 	bits |= EXTENT_FIRST_DELALLOC;
652 
653 	if (bits & (EXTENT_IOBITS | EXTENT_BOUNDARY))
654 		clear = 1;
655 again:
656 	if (!prealloc && gfpflags_allow_blocking(mask)) {
657 		/*
658 		 * Don't care for allocation failure here because we might end
659 		 * up not needing the pre-allocated extent state at all, which
660 		 * is the case if we only have in the tree extent states that
661 		 * cover our input range and don't cover too any other range.
662 		 * If we end up needing a new extent state we allocate it later.
663 		 */
664 		prealloc = alloc_extent_state(mask);
665 	}
666 
667 	spin_lock(&tree->lock);
668 	if (cached_state) {
669 		cached = *cached_state;
670 
671 		if (clear) {
672 			*cached_state = NULL;
673 			cached_state = NULL;
674 		}
675 
676 		if (cached && extent_state_in_tree(cached) &&
677 		    cached->start <= start && cached->end > start) {
678 			if (clear)
679 				refcount_dec(&cached->refs);
680 			state = cached;
681 			goto hit_next;
682 		}
683 		if (clear)
684 			free_extent_state(cached);
685 	}
686 	/*
687 	 * this search will find the extents that end after
688 	 * our range starts
689 	 */
690 	node = tree_search(tree, start);
691 	if (!node)
692 		goto out;
693 	state = rb_entry(node, struct extent_state, rb_node);
694 hit_next:
695 	if (state->start > end)
696 		goto out;
697 	WARN_ON(state->end < start);
698 	last_end = state->end;
699 
700 	/* the state doesn't have the wanted bits, go ahead */
701 	if (!(state->state & bits)) {
702 		state = next_state(state);
703 		goto next;
704 	}
705 
706 	/*
707 	 *     | ---- desired range ---- |
708 	 *  | state | or
709 	 *  | ------------- state -------------- |
710 	 *
711 	 * We need to split the extent we found, and may flip
712 	 * bits on second half.
713 	 *
714 	 * If the extent we found extends past our range, we
715 	 * just split and search again.  It'll get split again
716 	 * the next time though.
717 	 *
718 	 * If the extent we found is inside our range, we clear
719 	 * the desired bit on it.
720 	 */
721 
722 	if (state->start < start) {
723 		prealloc = alloc_extent_state_atomic(prealloc);
724 		BUG_ON(!prealloc);
725 		err = split_state(tree, state, prealloc, start);
726 		if (err)
727 			extent_io_tree_panic(tree, err);
728 
729 		prealloc = NULL;
730 		if (err)
731 			goto out;
732 		if (state->end <= end) {
733 			state = clear_state_bit(tree, state, &bits, wake,
734 						changeset);
735 			goto next;
736 		}
737 		goto search_again;
738 	}
739 	/*
740 	 * | ---- desired range ---- |
741 	 *                        | state |
742 	 * We need to split the extent, and clear the bit
743 	 * on the first half
744 	 */
745 	if (state->start <= end && state->end > end) {
746 		prealloc = alloc_extent_state_atomic(prealloc);
747 		BUG_ON(!prealloc);
748 		err = split_state(tree, state, prealloc, end + 1);
749 		if (err)
750 			extent_io_tree_panic(tree, err);
751 
752 		if (wake)
753 			wake_up(&state->wq);
754 
755 		clear_state_bit(tree, prealloc, &bits, wake, changeset);
756 
757 		prealloc = NULL;
758 		goto out;
759 	}
760 
761 	state = clear_state_bit(tree, state, &bits, wake, changeset);
762 next:
763 	if (last_end == (u64)-1)
764 		goto out;
765 	start = last_end + 1;
766 	if (start <= end && state && !need_resched())
767 		goto hit_next;
768 
769 search_again:
770 	if (start > end)
771 		goto out;
772 	spin_unlock(&tree->lock);
773 	if (gfpflags_allow_blocking(mask))
774 		cond_resched();
775 	goto again;
776 
777 out:
778 	spin_unlock(&tree->lock);
779 	if (prealloc)
780 		free_extent_state(prealloc);
781 
782 	return 0;
783 
784 }
785 
wait_on_state(struct extent_io_tree * tree,struct extent_state * state)786 static void wait_on_state(struct extent_io_tree *tree,
787 			  struct extent_state *state)
788 		__releases(tree->lock)
789 		__acquires(tree->lock)
790 {
791 	DEFINE_WAIT(wait);
792 	prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
793 	spin_unlock(&tree->lock);
794 	schedule();
795 	spin_lock(&tree->lock);
796 	finish_wait(&state->wq, &wait);
797 }
798 
799 /*
800  * waits for one or more bits to clear on a range in the state tree.
801  * The range [start, end] is inclusive.
802  * The tree lock is taken by this function
803  */
wait_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,unsigned long bits)804 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
805 			    unsigned long bits)
806 {
807 	struct extent_state *state;
808 	struct rb_node *node;
809 
810 	btrfs_debug_check_extent_io_range(tree, start, end);
811 
812 	spin_lock(&tree->lock);
813 again:
814 	while (1) {
815 		/*
816 		 * this search will find all the extents that end after
817 		 * our range starts
818 		 */
819 		node = tree_search(tree, start);
820 process_node:
821 		if (!node)
822 			break;
823 
824 		state = rb_entry(node, struct extent_state, rb_node);
825 
826 		if (state->start > end)
827 			goto out;
828 
829 		if (state->state & bits) {
830 			start = state->start;
831 			refcount_inc(&state->refs);
832 			wait_on_state(tree, state);
833 			free_extent_state(state);
834 			goto again;
835 		}
836 		start = state->end + 1;
837 
838 		if (start > end)
839 			break;
840 
841 		if (!cond_resched_lock(&tree->lock)) {
842 			node = rb_next(node);
843 			goto process_node;
844 		}
845 	}
846 out:
847 	spin_unlock(&tree->lock);
848 }
849 
set_state_bits(struct extent_io_tree * tree,struct extent_state * state,unsigned * bits,struct extent_changeset * changeset)850 static void set_state_bits(struct extent_io_tree *tree,
851 			   struct extent_state *state,
852 			   unsigned *bits, struct extent_changeset *changeset)
853 {
854 	unsigned bits_to_set = *bits & ~EXTENT_CTLBITS;
855 	int ret;
856 
857 	set_state_cb(tree, state, bits);
858 	if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
859 		u64 range = state->end - state->start + 1;
860 		tree->dirty_bytes += range;
861 	}
862 	ret = add_extent_changeset(state, bits_to_set, changeset, 1);
863 	BUG_ON(ret < 0);
864 	state->state |= bits_to_set;
865 }
866 
cache_state_if_flags(struct extent_state * state,struct extent_state ** cached_ptr,unsigned flags)867 static void cache_state_if_flags(struct extent_state *state,
868 				 struct extent_state **cached_ptr,
869 				 unsigned flags)
870 {
871 	if (cached_ptr && !(*cached_ptr)) {
872 		if (!flags || (state->state & flags)) {
873 			*cached_ptr = state;
874 			refcount_inc(&state->refs);
875 		}
876 	}
877 }
878 
cache_state(struct extent_state * state,struct extent_state ** cached_ptr)879 static void cache_state(struct extent_state *state,
880 			struct extent_state **cached_ptr)
881 {
882 	return cache_state_if_flags(state, cached_ptr,
883 				    EXTENT_IOBITS | EXTENT_BOUNDARY);
884 }
885 
886 /*
887  * set some bits on a range in the tree.  This may require allocations or
888  * sleeping, so the gfp mask is used to indicate what is allowed.
889  *
890  * If any of the exclusive bits are set, this will fail with -EEXIST if some
891  * part of the range already has the desired bits set.  The start of the
892  * existing range is returned in failed_start in this case.
893  *
894  * [start, end] is inclusive This takes the tree lock.
895  */
896 
897 static int __must_check
__set_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,unsigned bits,unsigned exclusive_bits,u64 * failed_start,struct extent_state ** cached_state,gfp_t mask,struct extent_changeset * changeset)898 __set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
899 		 unsigned bits, unsigned exclusive_bits,
900 		 u64 *failed_start, struct extent_state **cached_state,
901 		 gfp_t mask, struct extent_changeset *changeset)
902 {
903 	struct extent_state *state;
904 	struct extent_state *prealloc = NULL;
905 	struct rb_node *node;
906 	struct rb_node **p;
907 	struct rb_node *parent;
908 	int err = 0;
909 	u64 last_start;
910 	u64 last_end;
911 
912 	btrfs_debug_check_extent_io_range(tree, start, end);
913 
914 	bits |= EXTENT_FIRST_DELALLOC;
915 again:
916 	if (!prealloc && gfpflags_allow_blocking(mask)) {
917 		/*
918 		 * Don't care for allocation failure here because we might end
919 		 * up not needing the pre-allocated extent state at all, which
920 		 * is the case if we only have in the tree extent states that
921 		 * cover our input range and don't cover too any other range.
922 		 * If we end up needing a new extent state we allocate it later.
923 		 */
924 		prealloc = alloc_extent_state(mask);
925 	}
926 
927 	spin_lock(&tree->lock);
928 	if (cached_state && *cached_state) {
929 		state = *cached_state;
930 		if (state->start <= start && state->end > start &&
931 		    extent_state_in_tree(state)) {
932 			node = &state->rb_node;
933 			goto hit_next;
934 		}
935 	}
936 	/*
937 	 * this search will find all the extents that end after
938 	 * our range starts.
939 	 */
940 	node = tree_search_for_insert(tree, start, &p, &parent);
941 	if (!node) {
942 		prealloc = alloc_extent_state_atomic(prealloc);
943 		BUG_ON(!prealloc);
944 		err = insert_state(tree, prealloc, start, end,
945 				   &p, &parent, &bits, changeset);
946 		if (err)
947 			extent_io_tree_panic(tree, err);
948 
949 		cache_state(prealloc, cached_state);
950 		prealloc = NULL;
951 		goto out;
952 	}
953 	state = rb_entry(node, struct extent_state, rb_node);
954 hit_next:
955 	last_start = state->start;
956 	last_end = state->end;
957 
958 	/*
959 	 * | ---- desired range ---- |
960 	 * | state |
961 	 *
962 	 * Just lock what we found and keep going
963 	 */
964 	if (state->start == start && state->end <= end) {
965 		if (state->state & exclusive_bits) {
966 			*failed_start = state->start;
967 			err = -EEXIST;
968 			goto out;
969 		}
970 
971 		set_state_bits(tree, state, &bits, changeset);
972 		cache_state(state, cached_state);
973 		merge_state(tree, state);
974 		if (last_end == (u64)-1)
975 			goto out;
976 		start = last_end + 1;
977 		state = next_state(state);
978 		if (start < end && state && state->start == start &&
979 		    !need_resched())
980 			goto hit_next;
981 		goto search_again;
982 	}
983 
984 	/*
985 	 *     | ---- desired range ---- |
986 	 * | state |
987 	 *   or
988 	 * | ------------- state -------------- |
989 	 *
990 	 * We need to split the extent we found, and may flip bits on
991 	 * second half.
992 	 *
993 	 * If the extent we found extends past our
994 	 * range, we just split and search again.  It'll get split
995 	 * again the next time though.
996 	 *
997 	 * If the extent we found is inside our range, we set the
998 	 * desired bit on it.
999 	 */
1000 	if (state->start < start) {
1001 		if (state->state & exclusive_bits) {
1002 			*failed_start = start;
1003 			err = -EEXIST;
1004 			goto out;
1005 		}
1006 
1007 		prealloc = alloc_extent_state_atomic(prealloc);
1008 		BUG_ON(!prealloc);
1009 		err = split_state(tree, state, prealloc, start);
1010 		if (err)
1011 			extent_io_tree_panic(tree, err);
1012 
1013 		prealloc = NULL;
1014 		if (err)
1015 			goto out;
1016 		if (state->end <= end) {
1017 			set_state_bits(tree, state, &bits, changeset);
1018 			cache_state(state, cached_state);
1019 			merge_state(tree, state);
1020 			if (last_end == (u64)-1)
1021 				goto out;
1022 			start = last_end + 1;
1023 			state = next_state(state);
1024 			if (start < end && state && state->start == start &&
1025 			    !need_resched())
1026 				goto hit_next;
1027 		}
1028 		goto search_again;
1029 	}
1030 	/*
1031 	 * | ---- desired range ---- |
1032 	 *     | state | or               | state |
1033 	 *
1034 	 * There's a hole, we need to insert something in it and
1035 	 * ignore the extent we found.
1036 	 */
1037 	if (state->start > start) {
1038 		u64 this_end;
1039 		if (end < last_start)
1040 			this_end = end;
1041 		else
1042 			this_end = last_start - 1;
1043 
1044 		prealloc = alloc_extent_state_atomic(prealloc);
1045 		BUG_ON(!prealloc);
1046 
1047 		/*
1048 		 * Avoid to free 'prealloc' if it can be merged with
1049 		 * the later extent.
1050 		 */
1051 		err = insert_state(tree, prealloc, start, this_end,
1052 				   NULL, NULL, &bits, changeset);
1053 		if (err)
1054 			extent_io_tree_panic(tree, err);
1055 
1056 		cache_state(prealloc, cached_state);
1057 		prealloc = NULL;
1058 		start = this_end + 1;
1059 		goto search_again;
1060 	}
1061 	/*
1062 	 * | ---- desired range ---- |
1063 	 *                        | state |
1064 	 * We need to split the extent, and set the bit
1065 	 * on the first half
1066 	 */
1067 	if (state->start <= end && state->end > end) {
1068 		if (state->state & exclusive_bits) {
1069 			*failed_start = start;
1070 			err = -EEXIST;
1071 			goto out;
1072 		}
1073 
1074 		prealloc = alloc_extent_state_atomic(prealloc);
1075 		BUG_ON(!prealloc);
1076 		err = split_state(tree, state, prealloc, end + 1);
1077 		if (err)
1078 			extent_io_tree_panic(tree, err);
1079 
1080 		set_state_bits(tree, prealloc, &bits, changeset);
1081 		cache_state(prealloc, cached_state);
1082 		merge_state(tree, prealloc);
1083 		prealloc = NULL;
1084 		goto out;
1085 	}
1086 
1087 search_again:
1088 	if (start > end)
1089 		goto out;
1090 	spin_unlock(&tree->lock);
1091 	if (gfpflags_allow_blocking(mask))
1092 		cond_resched();
1093 	goto again;
1094 
1095 out:
1096 	spin_unlock(&tree->lock);
1097 	if (prealloc)
1098 		free_extent_state(prealloc);
1099 
1100 	return err;
1101 
1102 }
1103 
set_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,unsigned bits,u64 * failed_start,struct extent_state ** cached_state,gfp_t mask)1104 int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1105 		   unsigned bits, u64 * failed_start,
1106 		   struct extent_state **cached_state, gfp_t mask)
1107 {
1108 	return __set_extent_bit(tree, start, end, bits, 0, failed_start,
1109 				cached_state, mask, NULL);
1110 }
1111 
1112 
1113 /**
1114  * convert_extent_bit - convert all bits in a given range from one bit to
1115  * 			another
1116  * @tree:	the io tree to search
1117  * @start:	the start offset in bytes
1118  * @end:	the end offset in bytes (inclusive)
1119  * @bits:	the bits to set in this range
1120  * @clear_bits:	the bits to clear in this range
1121  * @cached_state:	state that we're going to cache
1122  *
1123  * This will go through and set bits for the given range.  If any states exist
1124  * already in this range they are set with the given bit and cleared of the
1125  * clear_bits.  This is only meant to be used by things that are mergeable, ie
1126  * converting from say DELALLOC to DIRTY.  This is not meant to be used with
1127  * boundary bits like LOCK.
1128  *
1129  * All allocations are done with GFP_NOFS.
1130  */
convert_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,unsigned bits,unsigned clear_bits,struct extent_state ** cached_state)1131 int convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1132 		       unsigned bits, unsigned clear_bits,
1133 		       struct extent_state **cached_state)
1134 {
1135 	struct extent_state *state;
1136 	struct extent_state *prealloc = NULL;
1137 	struct rb_node *node;
1138 	struct rb_node **p;
1139 	struct rb_node *parent;
1140 	int err = 0;
1141 	u64 last_start;
1142 	u64 last_end;
1143 	bool first_iteration = true;
1144 
1145 	btrfs_debug_check_extent_io_range(tree, start, end);
1146 
1147 again:
1148 	if (!prealloc) {
1149 		/*
1150 		 * Best effort, don't worry if extent state allocation fails
1151 		 * here for the first iteration. We might have a cached state
1152 		 * that matches exactly the target range, in which case no
1153 		 * extent state allocations are needed. We'll only know this
1154 		 * after locking the tree.
1155 		 */
1156 		prealloc = alloc_extent_state(GFP_NOFS);
1157 		if (!prealloc && !first_iteration)
1158 			return -ENOMEM;
1159 	}
1160 
1161 	spin_lock(&tree->lock);
1162 	if (cached_state && *cached_state) {
1163 		state = *cached_state;
1164 		if (state->start <= start && state->end > start &&
1165 		    extent_state_in_tree(state)) {
1166 			node = &state->rb_node;
1167 			goto hit_next;
1168 		}
1169 	}
1170 
1171 	/*
1172 	 * this search will find all the extents that end after
1173 	 * our range starts.
1174 	 */
1175 	node = tree_search_for_insert(tree, start, &p, &parent);
1176 	if (!node) {
1177 		prealloc = alloc_extent_state_atomic(prealloc);
1178 		if (!prealloc) {
1179 			err = -ENOMEM;
1180 			goto out;
1181 		}
1182 		err = insert_state(tree, prealloc, start, end,
1183 				   &p, &parent, &bits, NULL);
1184 		if (err)
1185 			extent_io_tree_panic(tree, err);
1186 		cache_state(prealloc, cached_state);
1187 		prealloc = NULL;
1188 		goto out;
1189 	}
1190 	state = rb_entry(node, struct extent_state, rb_node);
1191 hit_next:
1192 	last_start = state->start;
1193 	last_end = state->end;
1194 
1195 	/*
1196 	 * | ---- desired range ---- |
1197 	 * | state |
1198 	 *
1199 	 * Just lock what we found and keep going
1200 	 */
1201 	if (state->start == start && state->end <= end) {
1202 		set_state_bits(tree, state, &bits, NULL);
1203 		cache_state(state, cached_state);
1204 		state = clear_state_bit(tree, state, &clear_bits, 0, NULL);
1205 		if (last_end == (u64)-1)
1206 			goto out;
1207 		start = last_end + 1;
1208 		if (start < end && state && state->start == start &&
1209 		    !need_resched())
1210 			goto hit_next;
1211 		goto search_again;
1212 	}
1213 
1214 	/*
1215 	 *     | ---- desired range ---- |
1216 	 * | state |
1217 	 *   or
1218 	 * | ------------- state -------------- |
1219 	 *
1220 	 * We need to split the extent we found, and may flip bits on
1221 	 * second half.
1222 	 *
1223 	 * If the extent we found extends past our
1224 	 * range, we just split and search again.  It'll get split
1225 	 * again the next time though.
1226 	 *
1227 	 * If the extent we found is inside our range, we set the
1228 	 * desired bit on it.
1229 	 */
1230 	if (state->start < start) {
1231 		prealloc = alloc_extent_state_atomic(prealloc);
1232 		if (!prealloc) {
1233 			err = -ENOMEM;
1234 			goto out;
1235 		}
1236 		err = split_state(tree, state, prealloc, start);
1237 		if (err)
1238 			extent_io_tree_panic(tree, err);
1239 		prealloc = NULL;
1240 		if (err)
1241 			goto out;
1242 		if (state->end <= end) {
1243 			set_state_bits(tree, state, &bits, NULL);
1244 			cache_state(state, cached_state);
1245 			state = clear_state_bit(tree, state, &clear_bits, 0,
1246 						NULL);
1247 			if (last_end == (u64)-1)
1248 				goto out;
1249 			start = last_end + 1;
1250 			if (start < end && state && state->start == start &&
1251 			    !need_resched())
1252 				goto hit_next;
1253 		}
1254 		goto search_again;
1255 	}
1256 	/*
1257 	 * | ---- desired range ---- |
1258 	 *     | state | or               | state |
1259 	 *
1260 	 * There's a hole, we need to insert something in it and
1261 	 * ignore the extent we found.
1262 	 */
1263 	if (state->start > start) {
1264 		u64 this_end;
1265 		if (end < last_start)
1266 			this_end = end;
1267 		else
1268 			this_end = last_start - 1;
1269 
1270 		prealloc = alloc_extent_state_atomic(prealloc);
1271 		if (!prealloc) {
1272 			err = -ENOMEM;
1273 			goto out;
1274 		}
1275 
1276 		/*
1277 		 * Avoid to free 'prealloc' if it can be merged with
1278 		 * the later extent.
1279 		 */
1280 		err = insert_state(tree, prealloc, start, this_end,
1281 				   NULL, NULL, &bits, NULL);
1282 		if (err)
1283 			extent_io_tree_panic(tree, err);
1284 		cache_state(prealloc, cached_state);
1285 		prealloc = NULL;
1286 		start = this_end + 1;
1287 		goto search_again;
1288 	}
1289 	/*
1290 	 * | ---- desired range ---- |
1291 	 *                        | state |
1292 	 * We need to split the extent, and set the bit
1293 	 * on the first half
1294 	 */
1295 	if (state->start <= end && state->end > end) {
1296 		prealloc = alloc_extent_state_atomic(prealloc);
1297 		if (!prealloc) {
1298 			err = -ENOMEM;
1299 			goto out;
1300 		}
1301 
1302 		err = split_state(tree, state, prealloc, end + 1);
1303 		if (err)
1304 			extent_io_tree_panic(tree, err);
1305 
1306 		set_state_bits(tree, prealloc, &bits, NULL);
1307 		cache_state(prealloc, cached_state);
1308 		clear_state_bit(tree, prealloc, &clear_bits, 0, NULL);
1309 		prealloc = NULL;
1310 		goto out;
1311 	}
1312 
1313 search_again:
1314 	if (start > end)
1315 		goto out;
1316 	spin_unlock(&tree->lock);
1317 	cond_resched();
1318 	first_iteration = false;
1319 	goto again;
1320 
1321 out:
1322 	spin_unlock(&tree->lock);
1323 	if (prealloc)
1324 		free_extent_state(prealloc);
1325 
1326 	return err;
1327 }
1328 
1329 /* wrappers around set/clear extent bit */
set_record_extent_bits(struct extent_io_tree * tree,u64 start,u64 end,unsigned bits,struct extent_changeset * changeset)1330 int set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1331 			   unsigned bits, struct extent_changeset *changeset)
1332 {
1333 	/*
1334 	 * We don't support EXTENT_LOCKED yet, as current changeset will
1335 	 * record any bits changed, so for EXTENT_LOCKED case, it will
1336 	 * either fail with -EEXIST or changeset will record the whole
1337 	 * range.
1338 	 */
1339 	BUG_ON(bits & EXTENT_LOCKED);
1340 
1341 	return __set_extent_bit(tree, start, end, bits, 0, NULL, NULL, GFP_NOFS,
1342 				changeset);
1343 }
1344 
clear_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,unsigned bits,int wake,int delete,struct extent_state ** cached)1345 int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1346 		     unsigned bits, int wake, int delete,
1347 		     struct extent_state **cached)
1348 {
1349 	return __clear_extent_bit(tree, start, end, bits, wake, delete,
1350 				  cached, GFP_NOFS, NULL);
1351 }
1352 
clear_record_extent_bits(struct extent_io_tree * tree,u64 start,u64 end,unsigned bits,struct extent_changeset * changeset)1353 int clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1354 		unsigned bits, struct extent_changeset *changeset)
1355 {
1356 	/*
1357 	 * Don't support EXTENT_LOCKED case, same reason as
1358 	 * set_record_extent_bits().
1359 	 */
1360 	BUG_ON(bits & EXTENT_LOCKED);
1361 
1362 	return __clear_extent_bit(tree, start, end, bits, 0, 0, NULL, GFP_NOFS,
1363 				  changeset);
1364 }
1365 
1366 /*
1367  * either insert or lock state struct between start and end use mask to tell
1368  * us if waiting is desired.
1369  */
lock_extent_bits(struct extent_io_tree * tree,u64 start,u64 end,struct extent_state ** cached_state)1370 int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1371 		     struct extent_state **cached_state)
1372 {
1373 	int err;
1374 	u64 failed_start;
1375 
1376 	while (1) {
1377 		err = __set_extent_bit(tree, start, end, EXTENT_LOCKED,
1378 				       EXTENT_LOCKED, &failed_start,
1379 				       cached_state, GFP_NOFS, NULL);
1380 		if (err == -EEXIST) {
1381 			wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
1382 			start = failed_start;
1383 		} else
1384 			break;
1385 		WARN_ON(start > end);
1386 	}
1387 	return err;
1388 }
1389 
try_lock_extent(struct extent_io_tree * tree,u64 start,u64 end)1390 int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end)
1391 {
1392 	int err;
1393 	u64 failed_start;
1394 
1395 	err = __set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
1396 			       &failed_start, NULL, GFP_NOFS, NULL);
1397 	if (err == -EEXIST) {
1398 		if (failed_start > start)
1399 			clear_extent_bit(tree, start, failed_start - 1,
1400 					 EXTENT_LOCKED, 1, 0, NULL);
1401 		return 0;
1402 	}
1403 	return 1;
1404 }
1405 
extent_range_clear_dirty_for_io(struct inode * inode,u64 start,u64 end)1406 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
1407 {
1408 	unsigned long index = start >> PAGE_SHIFT;
1409 	unsigned long end_index = end >> PAGE_SHIFT;
1410 	struct page *page;
1411 
1412 	while (index <= end_index) {
1413 		page = find_get_page(inode->i_mapping, index);
1414 		BUG_ON(!page); /* Pages should be in the extent_io_tree */
1415 		clear_page_dirty_for_io(page);
1416 		put_page(page);
1417 		index++;
1418 	}
1419 }
1420 
extent_range_redirty_for_io(struct inode * inode,u64 start,u64 end)1421 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
1422 {
1423 	unsigned long index = start >> PAGE_SHIFT;
1424 	unsigned long end_index = end >> PAGE_SHIFT;
1425 	struct page *page;
1426 
1427 	while (index <= end_index) {
1428 		page = find_get_page(inode->i_mapping, index);
1429 		BUG_ON(!page); /* Pages should be in the extent_io_tree */
1430 		__set_page_dirty_nobuffers(page);
1431 		account_page_redirty(page);
1432 		put_page(page);
1433 		index++;
1434 	}
1435 }
1436 
1437 /* find the first state struct with 'bits' set after 'start', and
1438  * return it.  tree->lock must be held.  NULL will returned if
1439  * nothing was found after 'start'
1440  */
1441 static struct extent_state *
find_first_extent_bit_state(struct extent_io_tree * tree,u64 start,unsigned bits)1442 find_first_extent_bit_state(struct extent_io_tree *tree,
1443 			    u64 start, unsigned bits)
1444 {
1445 	struct rb_node *node;
1446 	struct extent_state *state;
1447 
1448 	/*
1449 	 * this search will find all the extents that end after
1450 	 * our range starts.
1451 	 */
1452 	node = tree_search(tree, start);
1453 	if (!node)
1454 		goto out;
1455 
1456 	while (1) {
1457 		state = rb_entry(node, struct extent_state, rb_node);
1458 		if (state->end >= start && (state->state & bits))
1459 			return state;
1460 
1461 		node = rb_next(node);
1462 		if (!node)
1463 			break;
1464 	}
1465 out:
1466 	return NULL;
1467 }
1468 
1469 /*
1470  * find the first offset in the io tree with 'bits' set. zero is
1471  * returned if we find something, and *start_ret and *end_ret are
1472  * set to reflect the state struct that was found.
1473  *
1474  * If nothing was found, 1 is returned. If found something, return 0.
1475  */
find_first_extent_bit(struct extent_io_tree * tree,u64 start,u64 * start_ret,u64 * end_ret,unsigned bits,struct extent_state ** cached_state)1476 int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1477 			  u64 *start_ret, u64 *end_ret, unsigned bits,
1478 			  struct extent_state **cached_state)
1479 {
1480 	struct extent_state *state;
1481 	struct rb_node *n;
1482 	int ret = 1;
1483 
1484 	spin_lock(&tree->lock);
1485 	if (cached_state && *cached_state) {
1486 		state = *cached_state;
1487 		if (state->end == start - 1 && extent_state_in_tree(state)) {
1488 			n = rb_next(&state->rb_node);
1489 			while (n) {
1490 				state = rb_entry(n, struct extent_state,
1491 						 rb_node);
1492 				if (state->state & bits)
1493 					goto got_it;
1494 				n = rb_next(n);
1495 			}
1496 			free_extent_state(*cached_state);
1497 			*cached_state = NULL;
1498 			goto out;
1499 		}
1500 		free_extent_state(*cached_state);
1501 		*cached_state = NULL;
1502 	}
1503 
1504 	state = find_first_extent_bit_state(tree, start, bits);
1505 got_it:
1506 	if (state) {
1507 		cache_state_if_flags(state, cached_state, 0);
1508 		*start_ret = state->start;
1509 		*end_ret = state->end;
1510 		ret = 0;
1511 	}
1512 out:
1513 	spin_unlock(&tree->lock);
1514 	return ret;
1515 }
1516 
1517 /*
1518  * find a contiguous range of bytes in the file marked as delalloc, not
1519  * more than 'max_bytes'.  start and end are used to return the range,
1520  *
1521  * 1 is returned if we find something, 0 if nothing was in the tree
1522  */
find_delalloc_range(struct extent_io_tree * tree,u64 * start,u64 * end,u64 max_bytes,struct extent_state ** cached_state)1523 static noinline u64 find_delalloc_range(struct extent_io_tree *tree,
1524 					u64 *start, u64 *end, u64 max_bytes,
1525 					struct extent_state **cached_state)
1526 {
1527 	struct rb_node *node;
1528 	struct extent_state *state;
1529 	u64 cur_start = *start;
1530 	u64 found = 0;
1531 	u64 total_bytes = 0;
1532 
1533 	spin_lock(&tree->lock);
1534 
1535 	/*
1536 	 * this search will find all the extents that end after
1537 	 * our range starts.
1538 	 */
1539 	node = tree_search(tree, cur_start);
1540 	if (!node) {
1541 		if (!found)
1542 			*end = (u64)-1;
1543 		goto out;
1544 	}
1545 
1546 	while (1) {
1547 		state = rb_entry(node, struct extent_state, rb_node);
1548 		if (found && (state->start != cur_start ||
1549 			      (state->state & EXTENT_BOUNDARY))) {
1550 			goto out;
1551 		}
1552 		if (!(state->state & EXTENT_DELALLOC)) {
1553 			if (!found)
1554 				*end = state->end;
1555 			goto out;
1556 		}
1557 		if (!found) {
1558 			*start = state->start;
1559 			*cached_state = state;
1560 			refcount_inc(&state->refs);
1561 		}
1562 		found++;
1563 		*end = state->end;
1564 		cur_start = state->end + 1;
1565 		node = rb_next(node);
1566 		total_bytes += state->end - state->start + 1;
1567 		if (total_bytes >= max_bytes)
1568 			break;
1569 		if (!node)
1570 			break;
1571 	}
1572 out:
1573 	spin_unlock(&tree->lock);
1574 	return found;
1575 }
1576 
1577 static int __process_pages_contig(struct address_space *mapping,
1578 				  struct page *locked_page,
1579 				  pgoff_t start_index, pgoff_t end_index,
1580 				  unsigned long page_ops, pgoff_t *index_ret);
1581 
__unlock_for_delalloc(struct inode * inode,struct page * locked_page,u64 start,u64 end)1582 static noinline void __unlock_for_delalloc(struct inode *inode,
1583 					   struct page *locked_page,
1584 					   u64 start, u64 end)
1585 {
1586 	unsigned long index = start >> PAGE_SHIFT;
1587 	unsigned long end_index = end >> PAGE_SHIFT;
1588 
1589 	ASSERT(locked_page);
1590 	if (index == locked_page->index && end_index == index)
1591 		return;
1592 
1593 	__process_pages_contig(inode->i_mapping, locked_page, index, end_index,
1594 			       PAGE_UNLOCK, NULL);
1595 }
1596 
lock_delalloc_pages(struct inode * inode,struct page * locked_page,u64 delalloc_start,u64 delalloc_end)1597 static noinline int lock_delalloc_pages(struct inode *inode,
1598 					struct page *locked_page,
1599 					u64 delalloc_start,
1600 					u64 delalloc_end)
1601 {
1602 	unsigned long index = delalloc_start >> PAGE_SHIFT;
1603 	unsigned long index_ret = index;
1604 	unsigned long end_index = delalloc_end >> PAGE_SHIFT;
1605 	int ret;
1606 
1607 	ASSERT(locked_page);
1608 	if (index == locked_page->index && index == end_index)
1609 		return 0;
1610 
1611 	ret = __process_pages_contig(inode->i_mapping, locked_page, index,
1612 				     end_index, PAGE_LOCK, &index_ret);
1613 	if (ret == -EAGAIN)
1614 		__unlock_for_delalloc(inode, locked_page, delalloc_start,
1615 				      (u64)index_ret << PAGE_SHIFT);
1616 	return ret;
1617 }
1618 
1619 /*
1620  * find a contiguous range of bytes in the file marked as delalloc, not
1621  * more than 'max_bytes'.  start and end are used to return the range,
1622  *
1623  * 1 is returned if we find something, 0 if nothing was in the tree
1624  */
find_lock_delalloc_range(struct inode * inode,struct extent_io_tree * tree,struct page * locked_page,u64 * start,u64 * end,u64 max_bytes)1625 STATIC u64 find_lock_delalloc_range(struct inode *inode,
1626 				    struct extent_io_tree *tree,
1627 				    struct page *locked_page, u64 *start,
1628 				    u64 *end, u64 max_bytes)
1629 {
1630 	u64 delalloc_start;
1631 	u64 delalloc_end;
1632 	u64 found;
1633 	struct extent_state *cached_state = NULL;
1634 	int ret;
1635 	int loops = 0;
1636 
1637 again:
1638 	/* step one, find a bunch of delalloc bytes starting at start */
1639 	delalloc_start = *start;
1640 	delalloc_end = 0;
1641 	found = find_delalloc_range(tree, &delalloc_start, &delalloc_end,
1642 				    max_bytes, &cached_state);
1643 	if (!found || delalloc_end <= *start) {
1644 		*start = delalloc_start;
1645 		*end = delalloc_end;
1646 		free_extent_state(cached_state);
1647 		return 0;
1648 	}
1649 
1650 	/*
1651 	 * start comes from the offset of locked_page.  We have to lock
1652 	 * pages in order, so we can't process delalloc bytes before
1653 	 * locked_page
1654 	 */
1655 	if (delalloc_start < *start)
1656 		delalloc_start = *start;
1657 
1658 	/*
1659 	 * make sure to limit the number of pages we try to lock down
1660 	 */
1661 	if (delalloc_end + 1 - delalloc_start > max_bytes)
1662 		delalloc_end = delalloc_start + max_bytes - 1;
1663 
1664 	/* step two, lock all the pages after the page that has start */
1665 	ret = lock_delalloc_pages(inode, locked_page,
1666 				  delalloc_start, delalloc_end);
1667 	if (ret == -EAGAIN) {
1668 		/* some of the pages are gone, lets avoid looping by
1669 		 * shortening the size of the delalloc range we're searching
1670 		 */
1671 		free_extent_state(cached_state);
1672 		cached_state = NULL;
1673 		if (!loops) {
1674 			max_bytes = PAGE_SIZE;
1675 			loops = 1;
1676 			goto again;
1677 		} else {
1678 			found = 0;
1679 			goto out_failed;
1680 		}
1681 	}
1682 	BUG_ON(ret); /* Only valid values are 0 and -EAGAIN */
1683 
1684 	/* step three, lock the state bits for the whole range */
1685 	lock_extent_bits(tree, delalloc_start, delalloc_end, &cached_state);
1686 
1687 	/* then test to make sure it is all still delalloc */
1688 	ret = test_range_bit(tree, delalloc_start, delalloc_end,
1689 			     EXTENT_DELALLOC, 1, cached_state);
1690 	if (!ret) {
1691 		unlock_extent_cached(tree, delalloc_start, delalloc_end,
1692 				     &cached_state);
1693 		__unlock_for_delalloc(inode, locked_page,
1694 			      delalloc_start, delalloc_end);
1695 		cond_resched();
1696 		goto again;
1697 	}
1698 	free_extent_state(cached_state);
1699 	*start = delalloc_start;
1700 	*end = delalloc_end;
1701 out_failed:
1702 	return found;
1703 }
1704 
__process_pages_contig(struct address_space * mapping,struct page * locked_page,pgoff_t start_index,pgoff_t end_index,unsigned long page_ops,pgoff_t * index_ret)1705 static int __process_pages_contig(struct address_space *mapping,
1706 				  struct page *locked_page,
1707 				  pgoff_t start_index, pgoff_t end_index,
1708 				  unsigned long page_ops, pgoff_t *index_ret)
1709 {
1710 	unsigned long nr_pages = end_index - start_index + 1;
1711 	unsigned long pages_locked = 0;
1712 	pgoff_t index = start_index;
1713 	struct page *pages[16];
1714 	unsigned ret;
1715 	int err = 0;
1716 	int i;
1717 
1718 	if (page_ops & PAGE_LOCK) {
1719 		ASSERT(page_ops == PAGE_LOCK);
1720 		ASSERT(index_ret && *index_ret == start_index);
1721 	}
1722 
1723 	if ((page_ops & PAGE_SET_ERROR) && nr_pages > 0)
1724 		mapping_set_error(mapping, -EIO);
1725 
1726 	while (nr_pages > 0) {
1727 		ret = find_get_pages_contig(mapping, index,
1728 				     min_t(unsigned long,
1729 				     nr_pages, ARRAY_SIZE(pages)), pages);
1730 		if (ret == 0) {
1731 			/*
1732 			 * Only if we're going to lock these pages,
1733 			 * can we find nothing at @index.
1734 			 */
1735 			ASSERT(page_ops & PAGE_LOCK);
1736 			err = -EAGAIN;
1737 			goto out;
1738 		}
1739 
1740 		for (i = 0; i < ret; i++) {
1741 			if (page_ops & PAGE_SET_PRIVATE2)
1742 				SetPagePrivate2(pages[i]);
1743 
1744 			if (pages[i] == locked_page) {
1745 				put_page(pages[i]);
1746 				pages_locked++;
1747 				continue;
1748 			}
1749 			if (page_ops & PAGE_CLEAR_DIRTY)
1750 				clear_page_dirty_for_io(pages[i]);
1751 			if (page_ops & PAGE_SET_WRITEBACK)
1752 				set_page_writeback(pages[i]);
1753 			if (page_ops & PAGE_SET_ERROR)
1754 				SetPageError(pages[i]);
1755 			if (page_ops & PAGE_END_WRITEBACK)
1756 				end_page_writeback(pages[i]);
1757 			if (page_ops & PAGE_UNLOCK)
1758 				unlock_page(pages[i]);
1759 			if (page_ops & PAGE_LOCK) {
1760 				lock_page(pages[i]);
1761 				if (!PageDirty(pages[i]) ||
1762 				    pages[i]->mapping != mapping) {
1763 					unlock_page(pages[i]);
1764 					for (; i < ret; i++)
1765 						put_page(pages[i]);
1766 					err = -EAGAIN;
1767 					goto out;
1768 				}
1769 			}
1770 			put_page(pages[i]);
1771 			pages_locked++;
1772 		}
1773 		nr_pages -= ret;
1774 		index += ret;
1775 		cond_resched();
1776 	}
1777 out:
1778 	if (err && index_ret)
1779 		*index_ret = start_index + pages_locked - 1;
1780 	return err;
1781 }
1782 
extent_clear_unlock_delalloc(struct inode * inode,u64 start,u64 end,u64 delalloc_end,struct page * locked_page,unsigned clear_bits,unsigned long page_ops)1783 void extent_clear_unlock_delalloc(struct inode *inode, u64 start, u64 end,
1784 				 u64 delalloc_end, struct page *locked_page,
1785 				 unsigned clear_bits,
1786 				 unsigned long page_ops)
1787 {
1788 	clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits, 1, 0,
1789 			 NULL);
1790 
1791 	__process_pages_contig(inode->i_mapping, locked_page,
1792 			       start >> PAGE_SHIFT, end >> PAGE_SHIFT,
1793 			       page_ops, NULL);
1794 }
1795 
1796 /*
1797  * count the number of bytes in the tree that have a given bit(s)
1798  * set.  This can be fairly slow, except for EXTENT_DIRTY which is
1799  * cached.  The total number found is returned.
1800  */
count_range_bits(struct extent_io_tree * tree,u64 * start,u64 search_end,u64 max_bytes,unsigned bits,int contig)1801 u64 count_range_bits(struct extent_io_tree *tree,
1802 		     u64 *start, u64 search_end, u64 max_bytes,
1803 		     unsigned bits, int contig)
1804 {
1805 	struct rb_node *node;
1806 	struct extent_state *state;
1807 	u64 cur_start = *start;
1808 	u64 total_bytes = 0;
1809 	u64 last = 0;
1810 	int found = 0;
1811 
1812 	if (WARN_ON(search_end <= cur_start))
1813 		return 0;
1814 
1815 	spin_lock(&tree->lock);
1816 	if (cur_start == 0 && bits == EXTENT_DIRTY) {
1817 		total_bytes = tree->dirty_bytes;
1818 		goto out;
1819 	}
1820 	/*
1821 	 * this search will find all the extents that end after
1822 	 * our range starts.
1823 	 */
1824 	node = tree_search(tree, cur_start);
1825 	if (!node)
1826 		goto out;
1827 
1828 	while (1) {
1829 		state = rb_entry(node, struct extent_state, rb_node);
1830 		if (state->start > search_end)
1831 			break;
1832 		if (contig && found && state->start > last + 1)
1833 			break;
1834 		if (state->end >= cur_start && (state->state & bits) == bits) {
1835 			total_bytes += min(search_end, state->end) + 1 -
1836 				       max(cur_start, state->start);
1837 			if (total_bytes >= max_bytes)
1838 				break;
1839 			if (!found) {
1840 				*start = max(cur_start, state->start);
1841 				found = 1;
1842 			}
1843 			last = state->end;
1844 		} else if (contig && found) {
1845 			break;
1846 		}
1847 		node = rb_next(node);
1848 		if (!node)
1849 			break;
1850 	}
1851 out:
1852 	spin_unlock(&tree->lock);
1853 	return total_bytes;
1854 }
1855 
1856 /*
1857  * set the private field for a given byte offset in the tree.  If there isn't
1858  * an extent_state there already, this does nothing.
1859  */
set_state_failrec(struct extent_io_tree * tree,u64 start,struct io_failure_record * failrec)1860 static noinline int set_state_failrec(struct extent_io_tree *tree, u64 start,
1861 		struct io_failure_record *failrec)
1862 {
1863 	struct rb_node *node;
1864 	struct extent_state *state;
1865 	int ret = 0;
1866 
1867 	spin_lock(&tree->lock);
1868 	/*
1869 	 * this search will find all the extents that end after
1870 	 * our range starts.
1871 	 */
1872 	node = tree_search(tree, start);
1873 	if (!node) {
1874 		ret = -ENOENT;
1875 		goto out;
1876 	}
1877 	state = rb_entry(node, struct extent_state, rb_node);
1878 	if (state->start != start) {
1879 		ret = -ENOENT;
1880 		goto out;
1881 	}
1882 	state->failrec = failrec;
1883 out:
1884 	spin_unlock(&tree->lock);
1885 	return ret;
1886 }
1887 
get_state_failrec(struct extent_io_tree * tree,u64 start,struct io_failure_record ** failrec)1888 static noinline int get_state_failrec(struct extent_io_tree *tree, u64 start,
1889 		struct io_failure_record **failrec)
1890 {
1891 	struct rb_node *node;
1892 	struct extent_state *state;
1893 	int ret = 0;
1894 
1895 	spin_lock(&tree->lock);
1896 	/*
1897 	 * this search will find all the extents that end after
1898 	 * our range starts.
1899 	 */
1900 	node = tree_search(tree, start);
1901 	if (!node) {
1902 		ret = -ENOENT;
1903 		goto out;
1904 	}
1905 	state = rb_entry(node, struct extent_state, rb_node);
1906 	if (state->start != start) {
1907 		ret = -ENOENT;
1908 		goto out;
1909 	}
1910 	*failrec = state->failrec;
1911 out:
1912 	spin_unlock(&tree->lock);
1913 	return ret;
1914 }
1915 
1916 /*
1917  * searches a range in the state tree for a given mask.
1918  * If 'filled' == 1, this returns 1 only if every extent in the tree
1919  * has the bits set.  Otherwise, 1 is returned if any bit in the
1920  * range is found set.
1921  */
test_range_bit(struct extent_io_tree * tree,u64 start,u64 end,unsigned bits,int filled,struct extent_state * cached)1922 int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
1923 		   unsigned bits, int filled, struct extent_state *cached)
1924 {
1925 	struct extent_state *state = NULL;
1926 	struct rb_node *node;
1927 	int bitset = 0;
1928 
1929 	spin_lock(&tree->lock);
1930 	if (cached && extent_state_in_tree(cached) && cached->start <= start &&
1931 	    cached->end > start)
1932 		node = &cached->rb_node;
1933 	else
1934 		node = tree_search(tree, start);
1935 	while (node && start <= end) {
1936 		state = rb_entry(node, struct extent_state, rb_node);
1937 
1938 		if (filled && state->start > start) {
1939 			bitset = 0;
1940 			break;
1941 		}
1942 
1943 		if (state->start > end)
1944 			break;
1945 
1946 		if (state->state & bits) {
1947 			bitset = 1;
1948 			if (!filled)
1949 				break;
1950 		} else if (filled) {
1951 			bitset = 0;
1952 			break;
1953 		}
1954 
1955 		if (state->end == (u64)-1)
1956 			break;
1957 
1958 		start = state->end + 1;
1959 		if (start > end)
1960 			break;
1961 		node = rb_next(node);
1962 		if (!node) {
1963 			if (filled)
1964 				bitset = 0;
1965 			break;
1966 		}
1967 	}
1968 	spin_unlock(&tree->lock);
1969 	return bitset;
1970 }
1971 
1972 /*
1973  * helper function to set a given page up to date if all the
1974  * extents in the tree for that page are up to date
1975  */
check_page_uptodate(struct extent_io_tree * tree,struct page * page)1976 static void check_page_uptodate(struct extent_io_tree *tree, struct page *page)
1977 {
1978 	u64 start = page_offset(page);
1979 	u64 end = start + PAGE_SIZE - 1;
1980 	if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
1981 		SetPageUptodate(page);
1982 }
1983 
free_io_failure(struct extent_io_tree * failure_tree,struct extent_io_tree * io_tree,struct io_failure_record * rec)1984 int free_io_failure(struct extent_io_tree *failure_tree,
1985 		    struct extent_io_tree *io_tree,
1986 		    struct io_failure_record *rec)
1987 {
1988 	int ret;
1989 	int err = 0;
1990 
1991 	set_state_failrec(failure_tree, rec->start, NULL);
1992 	ret = clear_extent_bits(failure_tree, rec->start,
1993 				rec->start + rec->len - 1,
1994 				EXTENT_LOCKED | EXTENT_DIRTY);
1995 	if (ret)
1996 		err = ret;
1997 
1998 	ret = clear_extent_bits(io_tree, rec->start,
1999 				rec->start + rec->len - 1,
2000 				EXTENT_DAMAGED);
2001 	if (ret && !err)
2002 		err = ret;
2003 
2004 	kfree(rec);
2005 	return err;
2006 }
2007 
2008 /*
2009  * this bypasses the standard btrfs submit functions deliberately, as
2010  * the standard behavior is to write all copies in a raid setup. here we only
2011  * want to write the one bad copy. so we do the mapping for ourselves and issue
2012  * submit_bio directly.
2013  * to avoid any synchronization issues, wait for the data after writing, which
2014  * actually prevents the read that triggered the error from finishing.
2015  * currently, there can be no more than two copies of every data bit. thus,
2016  * exactly one rewrite is required.
2017  */
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)2018 int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
2019 		      u64 length, u64 logical, struct page *page,
2020 		      unsigned int pg_offset, int mirror_num)
2021 {
2022 	struct bio *bio;
2023 	struct btrfs_device *dev;
2024 	u64 map_length = 0;
2025 	u64 sector;
2026 	struct btrfs_bio *bbio = NULL;
2027 	int ret;
2028 
2029 	ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
2030 	BUG_ON(!mirror_num);
2031 
2032 	bio = btrfs_io_bio_alloc(1);
2033 	bio->bi_iter.bi_size = 0;
2034 	map_length = length;
2035 
2036 	/*
2037 	 * Avoid races with device replace and make sure our bbio has devices
2038 	 * associated to its stripes that don't go away while we are doing the
2039 	 * read repair operation.
2040 	 */
2041 	btrfs_bio_counter_inc_blocked(fs_info);
2042 	if (btrfs_is_parity_mirror(fs_info, logical, length)) {
2043 		/*
2044 		 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
2045 		 * to update all raid stripes, but here we just want to correct
2046 		 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
2047 		 * stripe's dev and sector.
2048 		 */
2049 		ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
2050 				      &map_length, &bbio, 0);
2051 		if (ret) {
2052 			btrfs_bio_counter_dec(fs_info);
2053 			bio_put(bio);
2054 			return -EIO;
2055 		}
2056 		ASSERT(bbio->mirror_num == 1);
2057 	} else {
2058 		ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
2059 				      &map_length, &bbio, mirror_num);
2060 		if (ret) {
2061 			btrfs_bio_counter_dec(fs_info);
2062 			bio_put(bio);
2063 			return -EIO;
2064 		}
2065 		BUG_ON(mirror_num != bbio->mirror_num);
2066 	}
2067 
2068 	sector = bbio->stripes[bbio->mirror_num - 1].physical >> 9;
2069 	bio->bi_iter.bi_sector = sector;
2070 	dev = bbio->stripes[bbio->mirror_num - 1].dev;
2071 	btrfs_put_bbio(bbio);
2072 	if (!dev || !dev->bdev ||
2073 	    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
2074 		btrfs_bio_counter_dec(fs_info);
2075 		bio_put(bio);
2076 		return -EIO;
2077 	}
2078 	bio_set_dev(bio, dev->bdev);
2079 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
2080 	bio_add_page(bio, page, length, pg_offset);
2081 
2082 	if (btrfsic_submit_bio_wait(bio)) {
2083 		/* try to remap that extent elsewhere? */
2084 		btrfs_bio_counter_dec(fs_info);
2085 		bio_put(bio);
2086 		btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
2087 		return -EIO;
2088 	}
2089 
2090 	btrfs_info_rl_in_rcu(fs_info,
2091 		"read error corrected: ino %llu off %llu (dev %s sector %llu)",
2092 				  ino, start,
2093 				  rcu_str_deref(dev->name), sector);
2094 	btrfs_bio_counter_dec(fs_info);
2095 	bio_put(bio);
2096 	return 0;
2097 }
2098 
repair_eb_io_failure(struct btrfs_fs_info * fs_info,struct extent_buffer * eb,int mirror_num)2099 int repair_eb_io_failure(struct btrfs_fs_info *fs_info,
2100 			 struct extent_buffer *eb, int mirror_num)
2101 {
2102 	u64 start = eb->start;
2103 	int i, num_pages = num_extent_pages(eb);
2104 	int ret = 0;
2105 
2106 	if (sb_rdonly(fs_info->sb))
2107 		return -EROFS;
2108 
2109 	for (i = 0; i < num_pages; i++) {
2110 		struct page *p = eb->pages[i];
2111 
2112 		ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
2113 					start - page_offset(p), mirror_num);
2114 		if (ret)
2115 			break;
2116 		start += PAGE_SIZE;
2117 	}
2118 
2119 	return ret;
2120 }
2121 
2122 /*
2123  * each time an IO finishes, we do a fast check in the IO failure tree
2124  * to see if we need to process or clean up an io_failure_record
2125  */
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)2126 int clean_io_failure(struct btrfs_fs_info *fs_info,
2127 		     struct extent_io_tree *failure_tree,
2128 		     struct extent_io_tree *io_tree, u64 start,
2129 		     struct page *page, u64 ino, unsigned int pg_offset)
2130 {
2131 	u64 private;
2132 	struct io_failure_record *failrec;
2133 	struct extent_state *state;
2134 	int num_copies;
2135 	int ret;
2136 
2137 	private = 0;
2138 	ret = count_range_bits(failure_tree, &private, (u64)-1, 1,
2139 			       EXTENT_DIRTY, 0);
2140 	if (!ret)
2141 		return 0;
2142 
2143 	ret = get_state_failrec(failure_tree, start, &failrec);
2144 	if (ret)
2145 		return 0;
2146 
2147 	BUG_ON(!failrec->this_mirror);
2148 
2149 	if (failrec->in_validation) {
2150 		/* there was no real error, just free the record */
2151 		btrfs_debug(fs_info,
2152 			"clean_io_failure: freeing dummy error at %llu",
2153 			failrec->start);
2154 		goto out;
2155 	}
2156 	if (sb_rdonly(fs_info->sb))
2157 		goto out;
2158 
2159 	spin_lock(&io_tree->lock);
2160 	state = find_first_extent_bit_state(io_tree,
2161 					    failrec->start,
2162 					    EXTENT_LOCKED);
2163 	spin_unlock(&io_tree->lock);
2164 
2165 	if (state && state->start <= failrec->start &&
2166 	    state->end >= failrec->start + failrec->len - 1) {
2167 		num_copies = btrfs_num_copies(fs_info, failrec->logical,
2168 					      failrec->len);
2169 		if (num_copies > 1)  {
2170 			repair_io_failure(fs_info, ino, start, failrec->len,
2171 					  failrec->logical, page, pg_offset,
2172 					  failrec->failed_mirror);
2173 		}
2174 	}
2175 
2176 out:
2177 	free_io_failure(failure_tree, io_tree, failrec);
2178 
2179 	return 0;
2180 }
2181 
2182 /*
2183  * Can be called when
2184  * - hold extent lock
2185  * - under ordered extent
2186  * - the inode is freeing
2187  */
btrfs_free_io_failure_record(struct btrfs_inode * inode,u64 start,u64 end)2188 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
2189 {
2190 	struct extent_io_tree *failure_tree = &inode->io_failure_tree;
2191 	struct io_failure_record *failrec;
2192 	struct extent_state *state, *next;
2193 
2194 	if (RB_EMPTY_ROOT(&failure_tree->state))
2195 		return;
2196 
2197 	spin_lock(&failure_tree->lock);
2198 	state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2199 	while (state) {
2200 		if (state->start > end)
2201 			break;
2202 
2203 		ASSERT(state->end <= end);
2204 
2205 		next = next_state(state);
2206 
2207 		failrec = state->failrec;
2208 		free_extent_state(state);
2209 		kfree(failrec);
2210 
2211 		state = next;
2212 	}
2213 	spin_unlock(&failure_tree->lock);
2214 }
2215 
btrfs_get_io_failure_record(struct inode * inode,u64 start,u64 end,struct io_failure_record ** failrec_ret)2216 int btrfs_get_io_failure_record(struct inode *inode, u64 start, u64 end,
2217 		struct io_failure_record **failrec_ret)
2218 {
2219 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2220 	struct io_failure_record *failrec;
2221 	struct extent_map *em;
2222 	struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2223 	struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2224 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2225 	int ret;
2226 	u64 logical;
2227 
2228 	ret = get_state_failrec(failure_tree, start, &failrec);
2229 	if (ret) {
2230 		failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2231 		if (!failrec)
2232 			return -ENOMEM;
2233 
2234 		failrec->start = start;
2235 		failrec->len = end - start + 1;
2236 		failrec->this_mirror = 0;
2237 		failrec->bio_flags = 0;
2238 		failrec->in_validation = 0;
2239 
2240 		read_lock(&em_tree->lock);
2241 		em = lookup_extent_mapping(em_tree, start, failrec->len);
2242 		if (!em) {
2243 			read_unlock(&em_tree->lock);
2244 			kfree(failrec);
2245 			return -EIO;
2246 		}
2247 
2248 		if (em->start > start || em->start + em->len <= start) {
2249 			free_extent_map(em);
2250 			em = NULL;
2251 		}
2252 		read_unlock(&em_tree->lock);
2253 		if (!em) {
2254 			kfree(failrec);
2255 			return -EIO;
2256 		}
2257 
2258 		logical = start - em->start;
2259 		logical = em->block_start + logical;
2260 		if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2261 			logical = em->block_start;
2262 			failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2263 			extent_set_compress_type(&failrec->bio_flags,
2264 						 em->compress_type);
2265 		}
2266 
2267 		btrfs_debug(fs_info,
2268 			"Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2269 			logical, start, failrec->len);
2270 
2271 		failrec->logical = logical;
2272 		free_extent_map(em);
2273 
2274 		/* set the bits in the private failure tree */
2275 		ret = set_extent_bits(failure_tree, start, end,
2276 					EXTENT_LOCKED | EXTENT_DIRTY);
2277 		if (ret >= 0)
2278 			ret = set_state_failrec(failure_tree, start, failrec);
2279 		/* set the bits in the inode's tree */
2280 		if (ret >= 0)
2281 			ret = set_extent_bits(tree, start, end, EXTENT_DAMAGED);
2282 		if (ret < 0) {
2283 			kfree(failrec);
2284 			return ret;
2285 		}
2286 	} else {
2287 		btrfs_debug(fs_info,
2288 			"Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu, validation=%d",
2289 			failrec->logical, failrec->start, failrec->len,
2290 			failrec->in_validation);
2291 		/*
2292 		 * when data can be on disk more than twice, add to failrec here
2293 		 * (e.g. with a list for failed_mirror) to make
2294 		 * clean_io_failure() clean all those errors at once.
2295 		 */
2296 	}
2297 
2298 	*failrec_ret = failrec;
2299 
2300 	return 0;
2301 }
2302 
btrfs_check_repairable(struct inode * inode,unsigned failed_bio_pages,struct io_failure_record * failrec,int failed_mirror)2303 bool btrfs_check_repairable(struct inode *inode, unsigned failed_bio_pages,
2304 			   struct io_failure_record *failrec, int failed_mirror)
2305 {
2306 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2307 	int num_copies;
2308 
2309 	num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
2310 	if (num_copies == 1) {
2311 		/*
2312 		 * we only have a single copy of the data, so don't bother with
2313 		 * all the retry and error correction code that follows. no
2314 		 * matter what the error is, it is very likely to persist.
2315 		 */
2316 		btrfs_debug(fs_info,
2317 			"Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2318 			num_copies, failrec->this_mirror, failed_mirror);
2319 		return false;
2320 	}
2321 
2322 	/*
2323 	 * there are two premises:
2324 	 *	a) deliver good data to the caller
2325 	 *	b) correct the bad sectors on disk
2326 	 */
2327 	if (failed_bio_pages > 1) {
2328 		/*
2329 		 * to fulfill b), we need to know the exact failing sectors, as
2330 		 * we don't want to rewrite any more than the failed ones. thus,
2331 		 * we need separate read requests for the failed bio
2332 		 *
2333 		 * if the following BUG_ON triggers, our validation request got
2334 		 * merged. we need separate requests for our algorithm to work.
2335 		 */
2336 		BUG_ON(failrec->in_validation);
2337 		failrec->in_validation = 1;
2338 		failrec->this_mirror = failed_mirror;
2339 	} else {
2340 		/*
2341 		 * we're ready to fulfill a) and b) alongside. get a good copy
2342 		 * of the failed sector and if we succeed, we have setup
2343 		 * everything for repair_io_failure to do the rest for us.
2344 		 */
2345 		if (failrec->in_validation) {
2346 			BUG_ON(failrec->this_mirror != failed_mirror);
2347 			failrec->in_validation = 0;
2348 			failrec->this_mirror = 0;
2349 		}
2350 		failrec->failed_mirror = failed_mirror;
2351 		failrec->this_mirror++;
2352 		if (failrec->this_mirror == failed_mirror)
2353 			failrec->this_mirror++;
2354 	}
2355 
2356 	if (failrec->this_mirror > num_copies) {
2357 		btrfs_debug(fs_info,
2358 			"Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2359 			num_copies, failrec->this_mirror, failed_mirror);
2360 		return false;
2361 	}
2362 
2363 	return true;
2364 }
2365 
2366 
btrfs_create_repair_bio(struct inode * inode,struct bio * failed_bio,struct io_failure_record * failrec,struct page * page,int pg_offset,int icsum,bio_end_io_t * endio_func,void * data)2367 struct bio *btrfs_create_repair_bio(struct inode *inode, struct bio *failed_bio,
2368 				    struct io_failure_record *failrec,
2369 				    struct page *page, int pg_offset, int icsum,
2370 				    bio_end_io_t *endio_func, void *data)
2371 {
2372 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2373 	struct bio *bio;
2374 	struct btrfs_io_bio *btrfs_failed_bio;
2375 	struct btrfs_io_bio *btrfs_bio;
2376 
2377 	bio = btrfs_io_bio_alloc(1);
2378 	bio->bi_end_io = endio_func;
2379 	bio->bi_iter.bi_sector = failrec->logical >> 9;
2380 	bio_set_dev(bio, fs_info->fs_devices->latest_bdev);
2381 	bio->bi_iter.bi_size = 0;
2382 	bio->bi_private = data;
2383 
2384 	btrfs_failed_bio = btrfs_io_bio(failed_bio);
2385 	if (btrfs_failed_bio->csum) {
2386 		u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
2387 
2388 		btrfs_bio = btrfs_io_bio(bio);
2389 		btrfs_bio->csum = btrfs_bio->csum_inline;
2390 		icsum *= csum_size;
2391 		memcpy(btrfs_bio->csum, btrfs_failed_bio->csum + icsum,
2392 		       csum_size);
2393 	}
2394 
2395 	bio_add_page(bio, page, failrec->len, pg_offset);
2396 
2397 	return bio;
2398 }
2399 
2400 /*
2401  * this is a generic handler for readpage errors (default
2402  * readpage_io_failed_hook). if other copies exist, read those and write back
2403  * good data to the failed position. does not investigate in remapping the
2404  * failed extent elsewhere, hoping the device will be smart enough to do this as
2405  * needed
2406  */
2407 
bio_readpage_error(struct bio * failed_bio,u64 phy_offset,struct page * page,u64 start,u64 end,int failed_mirror)2408 static int bio_readpage_error(struct bio *failed_bio, u64 phy_offset,
2409 			      struct page *page, u64 start, u64 end,
2410 			      int failed_mirror)
2411 {
2412 	struct io_failure_record *failrec;
2413 	struct inode *inode = page->mapping->host;
2414 	struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2415 	struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2416 	struct bio *bio;
2417 	int read_mode = 0;
2418 	blk_status_t status;
2419 	int ret;
2420 	unsigned failed_bio_pages = bio_pages_all(failed_bio);
2421 
2422 	BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2423 
2424 	ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
2425 	if (ret)
2426 		return ret;
2427 
2428 	if (!btrfs_check_repairable(inode, failed_bio_pages, failrec,
2429 				    failed_mirror)) {
2430 		free_io_failure(failure_tree, tree, failrec);
2431 		return -EIO;
2432 	}
2433 
2434 	if (failed_bio_pages > 1)
2435 		read_mode |= REQ_FAILFAST_DEV;
2436 
2437 	phy_offset >>= inode->i_sb->s_blocksize_bits;
2438 	bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
2439 				      start - page_offset(page),
2440 				      (int)phy_offset, failed_bio->bi_end_io,
2441 				      NULL);
2442 	bio->bi_opf = REQ_OP_READ | read_mode;
2443 
2444 	btrfs_debug(btrfs_sb(inode->i_sb),
2445 		"Repair Read Error: submitting new read[%#x] to this_mirror=%d, in_validation=%d",
2446 		read_mode, failrec->this_mirror, failrec->in_validation);
2447 
2448 	status = tree->ops->submit_bio_hook(tree->private_data, bio, failrec->this_mirror,
2449 					 failrec->bio_flags, 0);
2450 	if (status) {
2451 		free_io_failure(failure_tree, tree, failrec);
2452 		bio_put(bio);
2453 		ret = blk_status_to_errno(status);
2454 	}
2455 
2456 	return ret;
2457 }
2458 
2459 /* lots and lots of room for performance fixes in the end_bio funcs */
2460 
end_extent_writepage(struct page * page,int err,u64 start,u64 end)2461 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
2462 {
2463 	int uptodate = (err == 0);
2464 	struct extent_io_tree *tree;
2465 	int ret = 0;
2466 
2467 	tree = &BTRFS_I(page->mapping->host)->io_tree;
2468 
2469 	if (tree->ops && tree->ops->writepage_end_io_hook)
2470 		tree->ops->writepage_end_io_hook(page, start, end, NULL,
2471 				uptodate);
2472 
2473 	if (!uptodate) {
2474 		ClearPageUptodate(page);
2475 		SetPageError(page);
2476 		ret = err < 0 ? err : -EIO;
2477 		mapping_set_error(page->mapping, ret);
2478 	}
2479 }
2480 
2481 /*
2482  * after a writepage IO is done, we need to:
2483  * clear the uptodate bits on error
2484  * clear the writeback bits in the extent tree for this IO
2485  * end_page_writeback if the page has no more pending IO
2486  *
2487  * Scheduling is not allowed, so the extent state tree is expected
2488  * to have one and only one object corresponding to this IO.
2489  */
end_bio_extent_writepage(struct bio * bio)2490 static void end_bio_extent_writepage(struct bio *bio)
2491 {
2492 	int error = blk_status_to_errno(bio->bi_status);
2493 	struct bio_vec *bvec;
2494 	u64 start;
2495 	u64 end;
2496 	int i;
2497 
2498 	ASSERT(!bio_flagged(bio, BIO_CLONED));
2499 	bio_for_each_segment_all(bvec, bio, i) {
2500 		struct page *page = bvec->bv_page;
2501 		struct inode *inode = page->mapping->host;
2502 		struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2503 
2504 		/* We always issue full-page reads, but if some block
2505 		 * in a page fails to read, blk_update_request() will
2506 		 * advance bv_offset and adjust bv_len to compensate.
2507 		 * Print a warning for nonzero offsets, and an error
2508 		 * if they don't add up to a full page.  */
2509 		if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2510 			if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2511 				btrfs_err(fs_info,
2512 				   "partial page write in btrfs with offset %u and length %u",
2513 					bvec->bv_offset, bvec->bv_len);
2514 			else
2515 				btrfs_info(fs_info,
2516 				   "incomplete page write in btrfs with offset %u and length %u",
2517 					bvec->bv_offset, bvec->bv_len);
2518 		}
2519 
2520 		start = page_offset(page);
2521 		end = start + bvec->bv_offset + bvec->bv_len - 1;
2522 
2523 		end_extent_writepage(page, error, start, end);
2524 		end_page_writeback(page);
2525 	}
2526 
2527 	bio_put(bio);
2528 }
2529 
2530 static void
endio_readpage_release_extent(struct extent_io_tree * tree,u64 start,u64 len,int uptodate)2531 endio_readpage_release_extent(struct extent_io_tree *tree, u64 start, u64 len,
2532 			      int uptodate)
2533 {
2534 	struct extent_state *cached = NULL;
2535 	u64 end = start + len - 1;
2536 
2537 	if (uptodate && tree->track_uptodate)
2538 		set_extent_uptodate(tree, start, end, &cached, GFP_ATOMIC);
2539 	unlock_extent_cached_atomic(tree, start, end, &cached);
2540 }
2541 
2542 /*
2543  * after a readpage IO is done, we need to:
2544  * clear the uptodate bits on error
2545  * set the uptodate bits if things worked
2546  * set the page up to date if all extents in the tree are uptodate
2547  * clear the lock bit in the extent tree
2548  * unlock the page if there are no other extents locked for it
2549  *
2550  * Scheduling is not allowed, so the extent state tree is expected
2551  * to have one and only one object corresponding to this IO.
2552  */
end_bio_extent_readpage(struct bio * bio)2553 static void end_bio_extent_readpage(struct bio *bio)
2554 {
2555 	struct bio_vec *bvec;
2556 	int uptodate = !bio->bi_status;
2557 	struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
2558 	struct extent_io_tree *tree, *failure_tree;
2559 	u64 offset = 0;
2560 	u64 start;
2561 	u64 end;
2562 	u64 len;
2563 	u64 extent_start = 0;
2564 	u64 extent_len = 0;
2565 	int mirror;
2566 	int ret;
2567 	int i;
2568 
2569 	ASSERT(!bio_flagged(bio, BIO_CLONED));
2570 	bio_for_each_segment_all(bvec, bio, i) {
2571 		struct page *page = bvec->bv_page;
2572 		struct inode *inode = page->mapping->host;
2573 		struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2574 
2575 		btrfs_debug(fs_info,
2576 			"end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
2577 			(u64)bio->bi_iter.bi_sector, bio->bi_status,
2578 			io_bio->mirror_num);
2579 		tree = &BTRFS_I(inode)->io_tree;
2580 		failure_tree = &BTRFS_I(inode)->io_failure_tree;
2581 
2582 		/* We always issue full-page reads, but if some block
2583 		 * in a page fails to read, blk_update_request() will
2584 		 * advance bv_offset and adjust bv_len to compensate.
2585 		 * Print a warning for nonzero offsets, and an error
2586 		 * if they don't add up to a full page.  */
2587 		if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2588 			if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
2589 				btrfs_err(fs_info,
2590 					"partial page read in btrfs with offset %u and length %u",
2591 					bvec->bv_offset, bvec->bv_len);
2592 			else
2593 				btrfs_info(fs_info,
2594 					"incomplete page read in btrfs with offset %u and length %u",
2595 					bvec->bv_offset, bvec->bv_len);
2596 		}
2597 
2598 		start = page_offset(page);
2599 		end = start + bvec->bv_offset + bvec->bv_len - 1;
2600 		len = bvec->bv_len;
2601 
2602 		mirror = io_bio->mirror_num;
2603 		if (likely(uptodate && tree->ops)) {
2604 			ret = tree->ops->readpage_end_io_hook(io_bio, offset,
2605 							      page, start, end,
2606 							      mirror);
2607 			if (ret)
2608 				uptodate = 0;
2609 			else
2610 				clean_io_failure(BTRFS_I(inode)->root->fs_info,
2611 						 failure_tree, tree, start,
2612 						 page,
2613 						 btrfs_ino(BTRFS_I(inode)), 0);
2614 		}
2615 
2616 		if (likely(uptodate))
2617 			goto readpage_ok;
2618 
2619 		if (tree->ops) {
2620 			ret = tree->ops->readpage_io_failed_hook(page, mirror);
2621 			if (ret == -EAGAIN) {
2622 				/*
2623 				 * Data inode's readpage_io_failed_hook() always
2624 				 * returns -EAGAIN.
2625 				 *
2626 				 * The generic bio_readpage_error handles errors
2627 				 * the following way: If possible, new read
2628 				 * requests are created and submitted and will
2629 				 * end up in end_bio_extent_readpage as well (if
2630 				 * we're lucky, not in the !uptodate case). In
2631 				 * that case it returns 0 and we just go on with
2632 				 * the next page in our bio. If it can't handle
2633 				 * the error it will return -EIO and we remain
2634 				 * responsible for that page.
2635 				 */
2636 				ret = bio_readpage_error(bio, offset, page,
2637 							 start, end, mirror);
2638 				if (ret == 0) {
2639 					uptodate = !bio->bi_status;
2640 					offset += len;
2641 					continue;
2642 				}
2643 			}
2644 
2645 			/*
2646 			 * metadata's readpage_io_failed_hook() always returns
2647 			 * -EIO and fixes nothing.  -EIO is also returned if
2648 			 * data inode error could not be fixed.
2649 			 */
2650 			ASSERT(ret == -EIO);
2651 		}
2652 readpage_ok:
2653 		if (likely(uptodate)) {
2654 			loff_t i_size = i_size_read(inode);
2655 			pgoff_t end_index = i_size >> PAGE_SHIFT;
2656 			unsigned off;
2657 
2658 			/* Zero out the end if this page straddles i_size */
2659 			off = i_size & (PAGE_SIZE-1);
2660 			if (page->index == end_index && off)
2661 				zero_user_segment(page, off, PAGE_SIZE);
2662 			SetPageUptodate(page);
2663 		} else {
2664 			ClearPageUptodate(page);
2665 			SetPageError(page);
2666 		}
2667 		unlock_page(page);
2668 		offset += len;
2669 
2670 		if (unlikely(!uptodate)) {
2671 			if (extent_len) {
2672 				endio_readpage_release_extent(tree,
2673 							      extent_start,
2674 							      extent_len, 1);
2675 				extent_start = 0;
2676 				extent_len = 0;
2677 			}
2678 			endio_readpage_release_extent(tree, start,
2679 						      end - start + 1, 0);
2680 		} else if (!extent_len) {
2681 			extent_start = start;
2682 			extent_len = end + 1 - start;
2683 		} else if (extent_start + extent_len == start) {
2684 			extent_len += end + 1 - start;
2685 		} else {
2686 			endio_readpage_release_extent(tree, extent_start,
2687 						      extent_len, uptodate);
2688 			extent_start = start;
2689 			extent_len = end + 1 - start;
2690 		}
2691 	}
2692 
2693 	if (extent_len)
2694 		endio_readpage_release_extent(tree, extent_start, extent_len,
2695 					      uptodate);
2696 	if (io_bio->end_io)
2697 		io_bio->end_io(io_bio, blk_status_to_errno(bio->bi_status));
2698 	bio_put(bio);
2699 }
2700 
2701 /*
2702  * Initialize the members up to but not including 'bio'. Use after allocating a
2703  * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
2704  * 'bio' because use of __GFP_ZERO is not supported.
2705  */
btrfs_io_bio_init(struct btrfs_io_bio * btrfs_bio)2706 static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
2707 {
2708 	memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
2709 }
2710 
2711 /*
2712  * The following helpers allocate a bio. As it's backed by a bioset, it'll
2713  * never fail.  We're returning a bio right now but you can call btrfs_io_bio
2714  * for the appropriate container_of magic
2715  */
btrfs_bio_alloc(struct block_device * bdev,u64 first_byte)2716 struct bio *btrfs_bio_alloc(struct block_device *bdev, u64 first_byte)
2717 {
2718 	struct bio *bio;
2719 
2720 	bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_PAGES, &btrfs_bioset);
2721 	bio_set_dev(bio, bdev);
2722 	bio->bi_iter.bi_sector = first_byte >> 9;
2723 	btrfs_io_bio_init(btrfs_io_bio(bio));
2724 	return bio;
2725 }
2726 
btrfs_bio_clone(struct bio * bio)2727 struct bio *btrfs_bio_clone(struct bio *bio)
2728 {
2729 	struct btrfs_io_bio *btrfs_bio;
2730 	struct bio *new;
2731 
2732 	/* Bio allocation backed by a bioset does not fail */
2733 	new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
2734 	btrfs_bio = btrfs_io_bio(new);
2735 	btrfs_io_bio_init(btrfs_bio);
2736 	btrfs_bio->iter = bio->bi_iter;
2737 	return new;
2738 }
2739 
btrfs_io_bio_alloc(unsigned int nr_iovecs)2740 struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
2741 {
2742 	struct bio *bio;
2743 
2744 	/* Bio allocation backed by a bioset does not fail */
2745 	bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
2746 	btrfs_io_bio_init(btrfs_io_bio(bio));
2747 	return bio;
2748 }
2749 
btrfs_bio_clone_partial(struct bio * orig,int offset,int size)2750 struct bio *btrfs_bio_clone_partial(struct bio *orig, int offset, int size)
2751 {
2752 	struct bio *bio;
2753 	struct btrfs_io_bio *btrfs_bio;
2754 
2755 	/* this will never fail when it's backed by a bioset */
2756 	bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
2757 	ASSERT(bio);
2758 
2759 	btrfs_bio = btrfs_io_bio(bio);
2760 	btrfs_io_bio_init(btrfs_bio);
2761 
2762 	bio_trim(bio, offset >> 9, size >> 9);
2763 	btrfs_bio->iter = bio->bi_iter;
2764 	return bio;
2765 }
2766 
2767 /*
2768  * @opf:	bio REQ_OP_* and REQ_* flags as one value
2769  * @tree:	tree so we can call our merge_bio hook
2770  * @wbc:	optional writeback control for io accounting
2771  * @page:	page to add to the bio
2772  * @pg_offset:	offset of the new bio or to check whether we are adding
2773  *              a contiguous page to the previous one
2774  * @size:	portion of page that we want to write
2775  * @offset:	starting offset in the page
2776  * @bdev:	attach newly created bios to this bdev
2777  * @bio_ret:	must be valid pointer, newly allocated bio will be stored there
2778  * @end_io_func:     end_io callback for new bio
2779  * @mirror_num:	     desired mirror to read/write
2780  * @prev_bio_flags:  flags of previous bio to see if we can merge the current one
2781  * @bio_flags:	flags of the current bio to see if we can merge them
2782  */
submit_extent_page(unsigned int opf,struct extent_io_tree * tree,struct writeback_control * wbc,struct page * page,u64 offset,size_t size,unsigned long pg_offset,struct block_device * bdev,struct bio ** bio_ret,bio_end_io_t end_io_func,int mirror_num,unsigned long prev_bio_flags,unsigned long bio_flags,bool force_bio_submit)2783 static int submit_extent_page(unsigned int opf, struct extent_io_tree *tree,
2784 			      struct writeback_control *wbc,
2785 			      struct page *page, u64 offset,
2786 			      size_t size, unsigned long pg_offset,
2787 			      struct block_device *bdev,
2788 			      struct bio **bio_ret,
2789 			      bio_end_io_t end_io_func,
2790 			      int mirror_num,
2791 			      unsigned long prev_bio_flags,
2792 			      unsigned long bio_flags,
2793 			      bool force_bio_submit)
2794 {
2795 	int ret = 0;
2796 	struct bio *bio;
2797 	size_t page_size = min_t(size_t, size, PAGE_SIZE);
2798 	sector_t sector = offset >> 9;
2799 
2800 	ASSERT(bio_ret);
2801 
2802 	if (*bio_ret) {
2803 		bool contig;
2804 		bool can_merge = true;
2805 
2806 		bio = *bio_ret;
2807 		if (prev_bio_flags & EXTENT_BIO_COMPRESSED)
2808 			contig = bio->bi_iter.bi_sector == sector;
2809 		else
2810 			contig = bio_end_sector(bio) == sector;
2811 
2812 		if (tree->ops && btrfs_merge_bio_hook(page, offset, page_size,
2813 						      bio, bio_flags))
2814 			can_merge = false;
2815 
2816 		if (prev_bio_flags != bio_flags || !contig || !can_merge ||
2817 		    force_bio_submit ||
2818 		    bio_add_page(bio, page, page_size, pg_offset) < page_size) {
2819 			ret = submit_one_bio(bio, mirror_num, prev_bio_flags);
2820 			if (ret < 0) {
2821 				*bio_ret = NULL;
2822 				return ret;
2823 			}
2824 			bio = NULL;
2825 		} else {
2826 			if (wbc)
2827 				wbc_account_io(wbc, page, page_size);
2828 			return 0;
2829 		}
2830 	}
2831 
2832 	bio = btrfs_bio_alloc(bdev, offset);
2833 	bio_add_page(bio, page, page_size, pg_offset);
2834 	bio->bi_end_io = end_io_func;
2835 	bio->bi_private = tree;
2836 	bio->bi_write_hint = page->mapping->host->i_write_hint;
2837 	bio->bi_opf = opf;
2838 	if (wbc) {
2839 		wbc_init_bio(wbc, bio);
2840 		wbc_account_io(wbc, page, page_size);
2841 	}
2842 
2843 	*bio_ret = bio;
2844 
2845 	return ret;
2846 }
2847 
attach_extent_buffer_page(struct extent_buffer * eb,struct page * page)2848 static void attach_extent_buffer_page(struct extent_buffer *eb,
2849 				      struct page *page)
2850 {
2851 	if (!PagePrivate(page)) {
2852 		SetPagePrivate(page);
2853 		get_page(page);
2854 		set_page_private(page, (unsigned long)eb);
2855 	} else {
2856 		WARN_ON(page->private != (unsigned long)eb);
2857 	}
2858 }
2859 
set_page_extent_mapped(struct page * page)2860 void set_page_extent_mapped(struct page *page)
2861 {
2862 	if (!PagePrivate(page)) {
2863 		SetPagePrivate(page);
2864 		get_page(page);
2865 		set_page_private(page, EXTENT_PAGE_PRIVATE);
2866 	}
2867 }
2868 
2869 static struct extent_map *
__get_extent_map(struct inode * inode,struct page * page,size_t pg_offset,u64 start,u64 len,get_extent_t * get_extent,struct extent_map ** em_cached)2870 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
2871 		 u64 start, u64 len, get_extent_t *get_extent,
2872 		 struct extent_map **em_cached)
2873 {
2874 	struct extent_map *em;
2875 
2876 	if (em_cached && *em_cached) {
2877 		em = *em_cached;
2878 		if (extent_map_in_tree(em) && start >= em->start &&
2879 		    start < extent_map_end(em)) {
2880 			refcount_inc(&em->refs);
2881 			return em;
2882 		}
2883 
2884 		free_extent_map(em);
2885 		*em_cached = NULL;
2886 	}
2887 
2888 	em = get_extent(BTRFS_I(inode), page, pg_offset, start, len, 0);
2889 	if (em_cached && !IS_ERR_OR_NULL(em)) {
2890 		BUG_ON(*em_cached);
2891 		refcount_inc(&em->refs);
2892 		*em_cached = em;
2893 	}
2894 	return em;
2895 }
2896 /*
2897  * basic readpage implementation.  Locked extent state structs are inserted
2898  * into the tree that are removed when the IO is done (by the end_io
2899  * handlers)
2900  * XXX JDM: This needs looking at to ensure proper page locking
2901  * return 0 on success, otherwise return error
2902  */
__do_readpage(struct extent_io_tree * tree,struct page * page,get_extent_t * get_extent,struct extent_map ** em_cached,struct bio ** bio,int mirror_num,unsigned long * bio_flags,unsigned int read_flags,u64 * prev_em_start)2903 static int __do_readpage(struct extent_io_tree *tree,
2904 			 struct page *page,
2905 			 get_extent_t *get_extent,
2906 			 struct extent_map **em_cached,
2907 			 struct bio **bio, int mirror_num,
2908 			 unsigned long *bio_flags, unsigned int read_flags,
2909 			 u64 *prev_em_start)
2910 {
2911 	struct inode *inode = page->mapping->host;
2912 	u64 start = page_offset(page);
2913 	const u64 end = start + PAGE_SIZE - 1;
2914 	u64 cur = start;
2915 	u64 extent_offset;
2916 	u64 last_byte = i_size_read(inode);
2917 	u64 block_start;
2918 	u64 cur_end;
2919 	struct extent_map *em;
2920 	struct block_device *bdev;
2921 	int ret = 0;
2922 	int nr = 0;
2923 	size_t pg_offset = 0;
2924 	size_t iosize;
2925 	size_t disk_io_size;
2926 	size_t blocksize = inode->i_sb->s_blocksize;
2927 	unsigned long this_bio_flag = 0;
2928 
2929 	set_page_extent_mapped(page);
2930 
2931 	if (!PageUptodate(page)) {
2932 		if (cleancache_get_page(page) == 0) {
2933 			BUG_ON(blocksize != PAGE_SIZE);
2934 			unlock_extent(tree, start, end);
2935 			goto out;
2936 		}
2937 	}
2938 
2939 	if (page->index == last_byte >> PAGE_SHIFT) {
2940 		char *userpage;
2941 		size_t zero_offset = last_byte & (PAGE_SIZE - 1);
2942 
2943 		if (zero_offset) {
2944 			iosize = PAGE_SIZE - zero_offset;
2945 			userpage = kmap_atomic(page);
2946 			memset(userpage + zero_offset, 0, iosize);
2947 			flush_dcache_page(page);
2948 			kunmap_atomic(userpage);
2949 		}
2950 	}
2951 	while (cur <= end) {
2952 		bool force_bio_submit = false;
2953 		u64 offset;
2954 
2955 		if (cur >= last_byte) {
2956 			char *userpage;
2957 			struct extent_state *cached = NULL;
2958 
2959 			iosize = PAGE_SIZE - pg_offset;
2960 			userpage = kmap_atomic(page);
2961 			memset(userpage + pg_offset, 0, iosize);
2962 			flush_dcache_page(page);
2963 			kunmap_atomic(userpage);
2964 			set_extent_uptodate(tree, cur, cur + iosize - 1,
2965 					    &cached, GFP_NOFS);
2966 			unlock_extent_cached(tree, cur,
2967 					     cur + iosize - 1, &cached);
2968 			break;
2969 		}
2970 		em = __get_extent_map(inode, page, pg_offset, cur,
2971 				      end - cur + 1, get_extent, em_cached);
2972 		if (IS_ERR_OR_NULL(em)) {
2973 			SetPageError(page);
2974 			unlock_extent(tree, cur, end);
2975 			break;
2976 		}
2977 		extent_offset = cur - em->start;
2978 		BUG_ON(extent_map_end(em) <= cur);
2979 		BUG_ON(end < cur);
2980 
2981 		if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2982 			this_bio_flag |= EXTENT_BIO_COMPRESSED;
2983 			extent_set_compress_type(&this_bio_flag,
2984 						 em->compress_type);
2985 		}
2986 
2987 		iosize = min(extent_map_end(em) - cur, end - cur + 1);
2988 		cur_end = min(extent_map_end(em) - 1, end);
2989 		iosize = ALIGN(iosize, blocksize);
2990 		if (this_bio_flag & EXTENT_BIO_COMPRESSED) {
2991 			disk_io_size = em->block_len;
2992 			offset = em->block_start;
2993 		} else {
2994 			offset = em->block_start + extent_offset;
2995 			disk_io_size = iosize;
2996 		}
2997 		bdev = em->bdev;
2998 		block_start = em->block_start;
2999 		if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3000 			block_start = EXTENT_MAP_HOLE;
3001 
3002 		/*
3003 		 * If we have a file range that points to a compressed extent
3004 		 * and it's followed by a consecutive file range that points to
3005 		 * to the same compressed extent (possibly with a different
3006 		 * offset and/or length, so it either points to the whole extent
3007 		 * or only part of it), we must make sure we do not submit a
3008 		 * single bio to populate the pages for the 2 ranges because
3009 		 * this makes the compressed extent read zero out the pages
3010 		 * belonging to the 2nd range. Imagine the following scenario:
3011 		 *
3012 		 *  File layout
3013 		 *  [0 - 8K]                     [8K - 24K]
3014 		 *    |                               |
3015 		 *    |                               |
3016 		 * points to extent X,         points to extent X,
3017 		 * offset 4K, length of 8K     offset 0, length 16K
3018 		 *
3019 		 * [extent X, compressed length = 4K uncompressed length = 16K]
3020 		 *
3021 		 * If the bio to read the compressed extent covers both ranges,
3022 		 * it will decompress extent X into the pages belonging to the
3023 		 * first range and then it will stop, zeroing out the remaining
3024 		 * pages that belong to the other range that points to extent X.
3025 		 * So here we make sure we submit 2 bios, one for the first
3026 		 * range and another one for the third range. Both will target
3027 		 * the same physical extent from disk, but we can't currently
3028 		 * make the compressed bio endio callback populate the pages
3029 		 * for both ranges because each compressed bio is tightly
3030 		 * coupled with a single extent map, and each range can have
3031 		 * an extent map with a different offset value relative to the
3032 		 * uncompressed data of our extent and different lengths. This
3033 		 * is a corner case so we prioritize correctness over
3034 		 * non-optimal behavior (submitting 2 bios for the same extent).
3035 		 */
3036 		if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
3037 		    prev_em_start && *prev_em_start != (u64)-1 &&
3038 		    *prev_em_start != em->start)
3039 			force_bio_submit = true;
3040 
3041 		if (prev_em_start)
3042 			*prev_em_start = em->start;
3043 
3044 		free_extent_map(em);
3045 		em = NULL;
3046 
3047 		/* we've found a hole, just zero and go on */
3048 		if (block_start == EXTENT_MAP_HOLE) {
3049 			char *userpage;
3050 			struct extent_state *cached = NULL;
3051 
3052 			userpage = kmap_atomic(page);
3053 			memset(userpage + pg_offset, 0, iosize);
3054 			flush_dcache_page(page);
3055 			kunmap_atomic(userpage);
3056 
3057 			set_extent_uptodate(tree, cur, cur + iosize - 1,
3058 					    &cached, GFP_NOFS);
3059 			unlock_extent_cached(tree, cur,
3060 					     cur + iosize - 1, &cached);
3061 			cur = cur + iosize;
3062 			pg_offset += iosize;
3063 			continue;
3064 		}
3065 		/* the get_extent function already copied into the page */
3066 		if (test_range_bit(tree, cur, cur_end,
3067 				   EXTENT_UPTODATE, 1, NULL)) {
3068 			check_page_uptodate(tree, page);
3069 			unlock_extent(tree, cur, cur + iosize - 1);
3070 			cur = cur + iosize;
3071 			pg_offset += iosize;
3072 			continue;
3073 		}
3074 		/* we have an inline extent but it didn't get marked up
3075 		 * to date.  Error out
3076 		 */
3077 		if (block_start == EXTENT_MAP_INLINE) {
3078 			SetPageError(page);
3079 			unlock_extent(tree, cur, cur + iosize - 1);
3080 			cur = cur + iosize;
3081 			pg_offset += iosize;
3082 			continue;
3083 		}
3084 
3085 		ret = submit_extent_page(REQ_OP_READ | read_flags, tree, NULL,
3086 					 page, offset, disk_io_size,
3087 					 pg_offset, bdev, bio,
3088 					 end_bio_extent_readpage, mirror_num,
3089 					 *bio_flags,
3090 					 this_bio_flag,
3091 					 force_bio_submit);
3092 		if (!ret) {
3093 			nr++;
3094 			*bio_flags = this_bio_flag;
3095 		} else {
3096 			SetPageError(page);
3097 			unlock_extent(tree, cur, cur + iosize - 1);
3098 			goto out;
3099 		}
3100 		cur = cur + iosize;
3101 		pg_offset += iosize;
3102 	}
3103 out:
3104 	if (!nr) {
3105 		if (!PageError(page))
3106 			SetPageUptodate(page);
3107 		unlock_page(page);
3108 	}
3109 	return ret;
3110 }
3111 
__do_contiguous_readpages(struct extent_io_tree * tree,struct page * pages[],int nr_pages,u64 start,u64 end,struct extent_map ** em_cached,struct bio ** bio,unsigned long * bio_flags,u64 * prev_em_start)3112 static inline void __do_contiguous_readpages(struct extent_io_tree *tree,
3113 					     struct page *pages[], int nr_pages,
3114 					     u64 start, u64 end,
3115 					     struct extent_map **em_cached,
3116 					     struct bio **bio,
3117 					     unsigned long *bio_flags,
3118 					     u64 *prev_em_start)
3119 {
3120 	struct inode *inode;
3121 	struct btrfs_ordered_extent *ordered;
3122 	int index;
3123 
3124 	inode = pages[0]->mapping->host;
3125 	while (1) {
3126 		lock_extent(tree, start, end);
3127 		ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
3128 						     end - start + 1);
3129 		if (!ordered)
3130 			break;
3131 		unlock_extent(tree, start, end);
3132 		btrfs_start_ordered_extent(inode, ordered, 1);
3133 		btrfs_put_ordered_extent(ordered);
3134 	}
3135 
3136 	for (index = 0; index < nr_pages; index++) {
3137 		__do_readpage(tree, pages[index], btrfs_get_extent, em_cached,
3138 				bio, 0, bio_flags, REQ_RAHEAD, prev_em_start);
3139 		put_page(pages[index]);
3140 	}
3141 }
3142 
__extent_readpages(struct extent_io_tree * tree,struct page * pages[],int nr_pages,struct extent_map ** em_cached,struct bio ** bio,unsigned long * bio_flags,u64 * prev_em_start)3143 static void __extent_readpages(struct extent_io_tree *tree,
3144 			       struct page *pages[],
3145 			       int nr_pages,
3146 			       struct extent_map **em_cached,
3147 			       struct bio **bio, unsigned long *bio_flags,
3148 			       u64 *prev_em_start)
3149 {
3150 	u64 start = 0;
3151 	u64 end = 0;
3152 	u64 page_start;
3153 	int index;
3154 	int first_index = 0;
3155 
3156 	for (index = 0; index < nr_pages; index++) {
3157 		page_start = page_offset(pages[index]);
3158 		if (!end) {
3159 			start = page_start;
3160 			end = start + PAGE_SIZE - 1;
3161 			first_index = index;
3162 		} else if (end + 1 == page_start) {
3163 			end += PAGE_SIZE;
3164 		} else {
3165 			__do_contiguous_readpages(tree, &pages[first_index],
3166 						  index - first_index, start,
3167 						  end, em_cached,
3168 						  bio, bio_flags,
3169 						  prev_em_start);
3170 			start = page_start;
3171 			end = start + PAGE_SIZE - 1;
3172 			first_index = index;
3173 		}
3174 	}
3175 
3176 	if (end)
3177 		__do_contiguous_readpages(tree, &pages[first_index],
3178 					  index - first_index, start,
3179 					  end, em_cached, bio,
3180 					  bio_flags, prev_em_start);
3181 }
3182 
__extent_read_full_page(struct extent_io_tree * tree,struct page * page,get_extent_t * get_extent,struct bio ** bio,int mirror_num,unsigned long * bio_flags,unsigned int read_flags)3183 static int __extent_read_full_page(struct extent_io_tree *tree,
3184 				   struct page *page,
3185 				   get_extent_t *get_extent,
3186 				   struct bio **bio, int mirror_num,
3187 				   unsigned long *bio_flags,
3188 				   unsigned int read_flags)
3189 {
3190 	struct inode *inode = page->mapping->host;
3191 	struct btrfs_ordered_extent *ordered;
3192 	u64 start = page_offset(page);
3193 	u64 end = start + PAGE_SIZE - 1;
3194 	int ret;
3195 
3196 	while (1) {
3197 		lock_extent(tree, start, end);
3198 		ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
3199 						PAGE_SIZE);
3200 		if (!ordered)
3201 			break;
3202 		unlock_extent(tree, start, end);
3203 		btrfs_start_ordered_extent(inode, ordered, 1);
3204 		btrfs_put_ordered_extent(ordered);
3205 	}
3206 
3207 	ret = __do_readpage(tree, page, get_extent, NULL, bio, mirror_num,
3208 			    bio_flags, read_flags, NULL);
3209 	return ret;
3210 }
3211 
extent_read_full_page(struct extent_io_tree * tree,struct page * page,get_extent_t * get_extent,int mirror_num)3212 int extent_read_full_page(struct extent_io_tree *tree, struct page *page,
3213 			    get_extent_t *get_extent, int mirror_num)
3214 {
3215 	struct bio *bio = NULL;
3216 	unsigned long bio_flags = 0;
3217 	int ret;
3218 
3219 	ret = __extent_read_full_page(tree, page, get_extent, &bio, mirror_num,
3220 				      &bio_flags, 0);
3221 	if (bio)
3222 		ret = submit_one_bio(bio, mirror_num, bio_flags);
3223 	return ret;
3224 }
3225 
update_nr_written(struct writeback_control * wbc,unsigned long nr_written)3226 static void update_nr_written(struct writeback_control *wbc,
3227 			      unsigned long nr_written)
3228 {
3229 	wbc->nr_to_write -= nr_written;
3230 }
3231 
3232 /*
3233  * helper for __extent_writepage, doing all of the delayed allocation setup.
3234  *
3235  * This returns 1 if btrfs_run_delalloc_range function did all the work required
3236  * to write the page (copy into inline extent).  In this case the IO has
3237  * been started and the page is already unlocked.
3238  *
3239  * This returns 0 if all went well (page still locked)
3240  * This returns < 0 if there were errors (page still locked)
3241  */
writepage_delalloc(struct inode * inode,struct page * page,struct writeback_control * wbc,struct extent_page_data * epd,u64 delalloc_start,unsigned long * nr_written)3242 static noinline_for_stack int writepage_delalloc(struct inode *inode,
3243 			      struct page *page, struct writeback_control *wbc,
3244 			      struct extent_page_data *epd,
3245 			      u64 delalloc_start,
3246 			      unsigned long *nr_written)
3247 {
3248 	struct extent_io_tree *tree = epd->tree;
3249 	u64 page_end = delalloc_start + PAGE_SIZE - 1;
3250 	u64 nr_delalloc;
3251 	u64 delalloc_to_write = 0;
3252 	u64 delalloc_end = 0;
3253 	int ret;
3254 	int page_started = 0;
3255 
3256 	if (epd->extent_locked)
3257 		return 0;
3258 
3259 	while (delalloc_end < page_end) {
3260 		nr_delalloc = find_lock_delalloc_range(inode, tree,
3261 					       page,
3262 					       &delalloc_start,
3263 					       &delalloc_end,
3264 					       BTRFS_MAX_EXTENT_SIZE);
3265 		if (nr_delalloc == 0) {
3266 			delalloc_start = delalloc_end + 1;
3267 			continue;
3268 		}
3269 		ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
3270 				delalloc_end, &page_started, nr_written, wbc);
3271 		/* File system has been set read-only */
3272 		if (ret) {
3273 			SetPageError(page);
3274 			/*
3275 			 * btrfs_run_delalloc_range should return < 0 for error
3276 			 * but just in case, we use > 0 here meaning the IO is
3277 			 * started, so we don't want to return > 0 unless
3278 			 * things are going well.
3279 			 */
3280 			ret = ret < 0 ? ret : -EIO;
3281 			goto done;
3282 		}
3283 		/*
3284 		 * delalloc_end is already one less than the total length, so
3285 		 * we don't subtract one from PAGE_SIZE
3286 		 */
3287 		delalloc_to_write += (delalloc_end - delalloc_start +
3288 				      PAGE_SIZE) >> PAGE_SHIFT;
3289 		delalloc_start = delalloc_end + 1;
3290 	}
3291 	if (wbc->nr_to_write < delalloc_to_write) {
3292 		int thresh = 8192;
3293 
3294 		if (delalloc_to_write < thresh * 2)
3295 			thresh = delalloc_to_write;
3296 		wbc->nr_to_write = min_t(u64, delalloc_to_write,
3297 					 thresh);
3298 	}
3299 
3300 	/* did the fill delalloc function already unlock and start
3301 	 * the IO?
3302 	 */
3303 	if (page_started) {
3304 		/*
3305 		 * we've unlocked the page, so we can't update
3306 		 * the mapping's writeback index, just update
3307 		 * nr_to_write.
3308 		 */
3309 		wbc->nr_to_write -= *nr_written;
3310 		return 1;
3311 	}
3312 
3313 	ret = 0;
3314 
3315 done:
3316 	return ret;
3317 }
3318 
3319 /*
3320  * helper for __extent_writepage.  This calls the writepage start hooks,
3321  * and does the loop to map the page into extents and bios.
3322  *
3323  * We return 1 if the IO is started and the page is unlocked,
3324  * 0 if all went well (page still locked)
3325  * < 0 if there were errors (page still locked)
3326  */
__extent_writepage_io(struct inode * inode,struct page * page,struct writeback_control * wbc,struct extent_page_data * epd,loff_t i_size,unsigned long nr_written,unsigned int write_flags,int * nr_ret)3327 static noinline_for_stack int __extent_writepage_io(struct inode *inode,
3328 				 struct page *page,
3329 				 struct writeback_control *wbc,
3330 				 struct extent_page_data *epd,
3331 				 loff_t i_size,
3332 				 unsigned long nr_written,
3333 				 unsigned int write_flags, int *nr_ret)
3334 {
3335 	struct extent_io_tree *tree = epd->tree;
3336 	u64 start = page_offset(page);
3337 	u64 page_end = start + PAGE_SIZE - 1;
3338 	u64 end;
3339 	u64 cur = start;
3340 	u64 extent_offset;
3341 	u64 block_start;
3342 	u64 iosize;
3343 	struct extent_map *em;
3344 	struct block_device *bdev;
3345 	size_t pg_offset = 0;
3346 	size_t blocksize;
3347 	int ret = 0;
3348 	int nr = 0;
3349 	bool compressed;
3350 
3351 	if (tree->ops && tree->ops->writepage_start_hook) {
3352 		ret = tree->ops->writepage_start_hook(page, start,
3353 						      page_end);
3354 		if (ret) {
3355 			/* Fixup worker will requeue */
3356 			if (ret == -EBUSY)
3357 				wbc->pages_skipped++;
3358 			else
3359 				redirty_page_for_writepage(wbc, page);
3360 
3361 			update_nr_written(wbc, nr_written);
3362 			unlock_page(page);
3363 			return 1;
3364 		}
3365 	}
3366 
3367 	/*
3368 	 * we don't want to touch the inode after unlocking the page,
3369 	 * so we update the mapping writeback index now
3370 	 */
3371 	update_nr_written(wbc, nr_written + 1);
3372 
3373 	end = page_end;
3374 	if (i_size <= start) {
3375 		if (tree->ops && tree->ops->writepage_end_io_hook)
3376 			tree->ops->writepage_end_io_hook(page, start,
3377 							 page_end, NULL, 1);
3378 		goto done;
3379 	}
3380 
3381 	blocksize = inode->i_sb->s_blocksize;
3382 
3383 	while (cur <= end) {
3384 		u64 em_end;
3385 		u64 offset;
3386 
3387 		if (cur >= i_size) {
3388 			if (tree->ops && tree->ops->writepage_end_io_hook)
3389 				tree->ops->writepage_end_io_hook(page, cur,
3390 							 page_end, NULL, 1);
3391 			break;
3392 		}
3393 		em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, cur,
3394 				     end - cur + 1, 1);
3395 		if (IS_ERR_OR_NULL(em)) {
3396 			SetPageError(page);
3397 			ret = PTR_ERR_OR_ZERO(em);
3398 			break;
3399 		}
3400 
3401 		extent_offset = cur - em->start;
3402 		em_end = extent_map_end(em);
3403 		BUG_ON(em_end <= cur);
3404 		BUG_ON(end < cur);
3405 		iosize = min(em_end - cur, end - cur + 1);
3406 		iosize = ALIGN(iosize, blocksize);
3407 		offset = em->block_start + extent_offset;
3408 		bdev = em->bdev;
3409 		block_start = em->block_start;
3410 		compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3411 		free_extent_map(em);
3412 		em = NULL;
3413 
3414 		/*
3415 		 * compressed and inline extents are written through other
3416 		 * paths in the FS
3417 		 */
3418 		if (compressed || block_start == EXTENT_MAP_HOLE ||
3419 		    block_start == EXTENT_MAP_INLINE) {
3420 			/*
3421 			 * end_io notification does not happen here for
3422 			 * compressed extents
3423 			 */
3424 			if (!compressed && tree->ops &&
3425 			    tree->ops->writepage_end_io_hook)
3426 				tree->ops->writepage_end_io_hook(page, cur,
3427 							 cur + iosize - 1,
3428 							 NULL, 1);
3429 			else if (compressed) {
3430 				/* we don't want to end_page_writeback on
3431 				 * a compressed extent.  this happens
3432 				 * elsewhere
3433 				 */
3434 				nr++;
3435 			}
3436 
3437 			cur += iosize;
3438 			pg_offset += iosize;
3439 			continue;
3440 		}
3441 
3442 		btrfs_set_range_writeback(tree, cur, cur + iosize - 1);
3443 		if (!PageWriteback(page)) {
3444 			btrfs_err(BTRFS_I(inode)->root->fs_info,
3445 				   "page %lu not writeback, cur %llu end %llu",
3446 			       page->index, cur, end);
3447 		}
3448 
3449 		ret = submit_extent_page(REQ_OP_WRITE | write_flags, tree, wbc,
3450 					 page, offset, iosize, pg_offset,
3451 					 bdev, &epd->bio,
3452 					 end_bio_extent_writepage,
3453 					 0, 0, 0, false);
3454 		if (ret) {
3455 			SetPageError(page);
3456 			if (PageWriteback(page))
3457 				end_page_writeback(page);
3458 		}
3459 
3460 		cur = cur + iosize;
3461 		pg_offset += iosize;
3462 		nr++;
3463 	}
3464 done:
3465 	*nr_ret = nr;
3466 	return ret;
3467 }
3468 
3469 /*
3470  * the writepage semantics are similar to regular writepage.  extent
3471  * records are inserted to lock ranges in the tree, and as dirty areas
3472  * are found, they are marked writeback.  Then the lock bits are removed
3473  * and the end_io handler clears the writeback ranges
3474  *
3475  * Return 0 if everything goes well.
3476  * Return <0 for error.
3477  */
__extent_writepage(struct page * page,struct writeback_control * wbc,struct extent_page_data * epd)3478 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
3479 			      struct extent_page_data *epd)
3480 {
3481 	struct inode *inode = page->mapping->host;
3482 	u64 start = page_offset(page);
3483 	u64 page_end = start + PAGE_SIZE - 1;
3484 	int ret;
3485 	int nr = 0;
3486 	size_t pg_offset = 0;
3487 	loff_t i_size = i_size_read(inode);
3488 	unsigned long end_index = i_size >> PAGE_SHIFT;
3489 	unsigned int write_flags = 0;
3490 	unsigned long nr_written = 0;
3491 
3492 	write_flags = wbc_to_write_flags(wbc);
3493 
3494 	trace___extent_writepage(page, inode, wbc);
3495 
3496 	WARN_ON(!PageLocked(page));
3497 
3498 	ClearPageError(page);
3499 
3500 	pg_offset = i_size & (PAGE_SIZE - 1);
3501 	if (page->index > end_index ||
3502 	   (page->index == end_index && !pg_offset)) {
3503 		page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
3504 		unlock_page(page);
3505 		return 0;
3506 	}
3507 
3508 	if (page->index == end_index) {
3509 		char *userpage;
3510 
3511 		userpage = kmap_atomic(page);
3512 		memset(userpage + pg_offset, 0,
3513 		       PAGE_SIZE - pg_offset);
3514 		kunmap_atomic(userpage);
3515 		flush_dcache_page(page);
3516 	}
3517 
3518 	pg_offset = 0;
3519 
3520 	set_page_extent_mapped(page);
3521 
3522 	ret = writepage_delalloc(inode, page, wbc, epd, start, &nr_written);
3523 	if (ret == 1)
3524 		goto done_unlocked;
3525 	if (ret)
3526 		goto done;
3527 
3528 	ret = __extent_writepage_io(inode, page, wbc, epd,
3529 				    i_size, nr_written, write_flags, &nr);
3530 	if (ret == 1)
3531 		goto done_unlocked;
3532 
3533 done:
3534 	if (nr == 0) {
3535 		/* make sure the mapping tag for page dirty gets cleared */
3536 		set_page_writeback(page);
3537 		end_page_writeback(page);
3538 	}
3539 	if (PageError(page)) {
3540 		ret = ret < 0 ? ret : -EIO;
3541 		end_extent_writepage(page, ret, start, page_end);
3542 	}
3543 	unlock_page(page);
3544 	ASSERT(ret <= 0);
3545 	return ret;
3546 
3547 done_unlocked:
3548 	return 0;
3549 }
3550 
wait_on_extent_buffer_writeback(struct extent_buffer * eb)3551 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
3552 {
3553 	wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
3554 		       TASK_UNINTERRUPTIBLE);
3555 }
3556 
end_extent_buffer_writeback(struct extent_buffer * eb)3557 static void end_extent_buffer_writeback(struct extent_buffer *eb)
3558 {
3559 	clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3560 	smp_mb__after_atomic();
3561 	wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3562 }
3563 
3564 /*
3565  * Lock eb pages and flush the bio if we can't the locks
3566  *
3567  * Return  0 if nothing went wrong
3568  * Return >0 is same as 0, except bio is not submitted
3569  * Return <0 if something went wrong, no page is locked
3570  */
3571 static noinline_for_stack int
lock_extent_buffer_for_io(struct extent_buffer * eb,struct btrfs_fs_info * fs_info,struct extent_page_data * epd)3572 lock_extent_buffer_for_io(struct extent_buffer *eb,
3573 			  struct btrfs_fs_info *fs_info,
3574 			  struct extent_page_data *epd)
3575 {
3576 	int i, num_pages, failed_page_nr;
3577 	int flush = 0;
3578 	int ret = 0;
3579 
3580 	if (!btrfs_try_tree_write_lock(eb)) {
3581 		ret = flush_write_bio(epd);
3582 		if (ret < 0)
3583 			return ret;
3584 		flush = 1;
3585 		btrfs_tree_lock(eb);
3586 	}
3587 
3588 	if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
3589 		btrfs_tree_unlock(eb);
3590 		if (!epd->sync_io)
3591 			return 0;
3592 		if (!flush) {
3593 			ret = flush_write_bio(epd);
3594 			if (ret < 0)
3595 				return ret;
3596 			flush = 1;
3597 		}
3598 		while (1) {
3599 			wait_on_extent_buffer_writeback(eb);
3600 			btrfs_tree_lock(eb);
3601 			if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
3602 				break;
3603 			btrfs_tree_unlock(eb);
3604 		}
3605 	}
3606 
3607 	/*
3608 	 * We need to do this to prevent races in people who check if the eb is
3609 	 * under IO since we can end up having no IO bits set for a short period
3610 	 * of time.
3611 	 */
3612 	spin_lock(&eb->refs_lock);
3613 	if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3614 		set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3615 		spin_unlock(&eb->refs_lock);
3616 		btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3617 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3618 					 -eb->len,
3619 					 fs_info->dirty_metadata_batch);
3620 		ret = 1;
3621 	} else {
3622 		spin_unlock(&eb->refs_lock);
3623 	}
3624 
3625 	btrfs_tree_unlock(eb);
3626 
3627 	if (!ret)
3628 		return ret;
3629 
3630 	num_pages = num_extent_pages(eb);
3631 	for (i = 0; i < num_pages; i++) {
3632 		struct page *p = eb->pages[i];
3633 
3634 		if (!trylock_page(p)) {
3635 			if (!flush) {
3636 				int err;
3637 
3638 				err = flush_write_bio(epd);
3639 				if (err < 0) {
3640 					ret = err;
3641 					failed_page_nr = i;
3642 					goto err_unlock;
3643 				}
3644 				flush = 1;
3645 			}
3646 			lock_page(p);
3647 		}
3648 	}
3649 
3650 	return ret;
3651 err_unlock:
3652 	/* Unlock already locked pages */
3653 	for (i = 0; i < failed_page_nr; i++)
3654 		unlock_page(eb->pages[i]);
3655 	/*
3656 	 * Clear EXTENT_BUFFER_WRITEBACK and wake up anyone waiting on it.
3657 	 * Also set back EXTENT_BUFFER_DIRTY so future attempts to this eb can
3658 	 * be made and undo everything done before.
3659 	 */
3660 	btrfs_tree_lock(eb);
3661 	spin_lock(&eb->refs_lock);
3662 	set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
3663 	end_extent_buffer_writeback(eb);
3664 	spin_unlock(&eb->refs_lock);
3665 	percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, eb->len,
3666 				 fs_info->dirty_metadata_batch);
3667 	btrfs_clear_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3668 	btrfs_tree_unlock(eb);
3669 	return ret;
3670 }
3671 
set_btree_ioerr(struct page * page)3672 static void set_btree_ioerr(struct page *page)
3673 {
3674 	struct extent_buffer *eb = (struct extent_buffer *)page->private;
3675 
3676 	SetPageError(page);
3677 	if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
3678 		return;
3679 
3680 	/*
3681 	 * If writeback for a btree extent that doesn't belong to a log tree
3682 	 * failed, increment the counter transaction->eb_write_errors.
3683 	 * We do this because while the transaction is running and before it's
3684 	 * committing (when we call filemap_fdata[write|wait]_range against
3685 	 * the btree inode), we might have
3686 	 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
3687 	 * returns an error or an error happens during writeback, when we're
3688 	 * committing the transaction we wouldn't know about it, since the pages
3689 	 * can be no longer dirty nor marked anymore for writeback (if a
3690 	 * subsequent modification to the extent buffer didn't happen before the
3691 	 * transaction commit), which makes filemap_fdata[write|wait]_range not
3692 	 * able to find the pages tagged with SetPageError at transaction
3693 	 * commit time. So if this happens we must abort the transaction,
3694 	 * otherwise we commit a super block with btree roots that point to
3695 	 * btree nodes/leafs whose content on disk is invalid - either garbage
3696 	 * or the content of some node/leaf from a past generation that got
3697 	 * cowed or deleted and is no longer valid.
3698 	 *
3699 	 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
3700 	 * not be enough - we need to distinguish between log tree extents vs
3701 	 * non-log tree extents, and the next filemap_fdatawait_range() call
3702 	 * will catch and clear such errors in the mapping - and that call might
3703 	 * be from a log sync and not from a transaction commit. Also, checking
3704 	 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
3705 	 * not done and would not be reliable - the eb might have been released
3706 	 * from memory and reading it back again means that flag would not be
3707 	 * set (since it's a runtime flag, not persisted on disk).
3708 	 *
3709 	 * Using the flags below in the btree inode also makes us achieve the
3710 	 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
3711 	 * writeback for all dirty pages and before filemap_fdatawait_range()
3712 	 * is called, the writeback for all dirty pages had already finished
3713 	 * with errors - because we were not using AS_EIO/AS_ENOSPC,
3714 	 * filemap_fdatawait_range() would return success, as it could not know
3715 	 * that writeback errors happened (the pages were no longer tagged for
3716 	 * writeback).
3717 	 */
3718 	switch (eb->log_index) {
3719 	case -1:
3720 		set_bit(BTRFS_FS_BTREE_ERR, &eb->fs_info->flags);
3721 		break;
3722 	case 0:
3723 		set_bit(BTRFS_FS_LOG1_ERR, &eb->fs_info->flags);
3724 		break;
3725 	case 1:
3726 		set_bit(BTRFS_FS_LOG2_ERR, &eb->fs_info->flags);
3727 		break;
3728 	default:
3729 		BUG(); /* unexpected, logic error */
3730 	}
3731 }
3732 
end_bio_extent_buffer_writepage(struct bio * bio)3733 static void end_bio_extent_buffer_writepage(struct bio *bio)
3734 {
3735 	struct bio_vec *bvec;
3736 	struct extent_buffer *eb;
3737 	int i, done;
3738 
3739 	ASSERT(!bio_flagged(bio, BIO_CLONED));
3740 	bio_for_each_segment_all(bvec, bio, i) {
3741 		struct page *page = bvec->bv_page;
3742 
3743 		eb = (struct extent_buffer *)page->private;
3744 		BUG_ON(!eb);
3745 		done = atomic_dec_and_test(&eb->io_pages);
3746 
3747 		if (bio->bi_status ||
3748 		    test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
3749 			ClearPageUptodate(page);
3750 			set_btree_ioerr(page);
3751 		}
3752 
3753 		end_page_writeback(page);
3754 
3755 		if (!done)
3756 			continue;
3757 
3758 		end_extent_buffer_writeback(eb);
3759 	}
3760 
3761 	bio_put(bio);
3762 }
3763 
write_one_eb(struct extent_buffer * eb,struct btrfs_fs_info * fs_info,struct writeback_control * wbc,struct extent_page_data * epd)3764 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
3765 			struct btrfs_fs_info *fs_info,
3766 			struct writeback_control *wbc,
3767 			struct extent_page_data *epd)
3768 {
3769 	struct block_device *bdev = fs_info->fs_devices->latest_bdev;
3770 	struct extent_io_tree *tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
3771 	u64 offset = eb->start;
3772 	u32 nritems;
3773 	int i, num_pages;
3774 	unsigned long start, end;
3775 	unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
3776 	int ret = 0;
3777 
3778 	clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
3779 	num_pages = num_extent_pages(eb);
3780 	atomic_set(&eb->io_pages, num_pages);
3781 
3782 	/* set btree blocks beyond nritems with 0 to avoid stale content. */
3783 	nritems = btrfs_header_nritems(eb);
3784 	if (btrfs_header_level(eb) > 0) {
3785 		end = btrfs_node_key_ptr_offset(nritems);
3786 
3787 		memzero_extent_buffer(eb, end, eb->len - end);
3788 	} else {
3789 		/*
3790 		 * leaf:
3791 		 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
3792 		 */
3793 		start = btrfs_item_nr_offset(nritems);
3794 		end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(fs_info, eb);
3795 		memzero_extent_buffer(eb, start, end - start);
3796 	}
3797 
3798 	for (i = 0; i < num_pages; i++) {
3799 		struct page *p = eb->pages[i];
3800 
3801 		clear_page_dirty_for_io(p);
3802 		set_page_writeback(p);
3803 		ret = submit_extent_page(REQ_OP_WRITE | write_flags, tree, wbc,
3804 					 p, offset, PAGE_SIZE, 0, bdev,
3805 					 &epd->bio,
3806 					 end_bio_extent_buffer_writepage,
3807 					 0, 0, 0, false);
3808 		if (ret) {
3809 			set_btree_ioerr(p);
3810 			if (PageWriteback(p))
3811 				end_page_writeback(p);
3812 			if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
3813 				end_extent_buffer_writeback(eb);
3814 			ret = -EIO;
3815 			break;
3816 		}
3817 		offset += PAGE_SIZE;
3818 		update_nr_written(wbc, 1);
3819 		unlock_page(p);
3820 	}
3821 
3822 	if (unlikely(ret)) {
3823 		for (; i < num_pages; i++) {
3824 			struct page *p = eb->pages[i];
3825 			clear_page_dirty_for_io(p);
3826 			unlock_page(p);
3827 		}
3828 	}
3829 
3830 	return ret;
3831 }
3832 
btree_write_cache_pages(struct address_space * mapping,struct writeback_control * wbc)3833 int btree_write_cache_pages(struct address_space *mapping,
3834 				   struct writeback_control *wbc)
3835 {
3836 	struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
3837 	struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
3838 	struct extent_buffer *eb, *prev_eb = NULL;
3839 	struct extent_page_data epd = {
3840 		.bio = NULL,
3841 		.tree = tree,
3842 		.extent_locked = 0,
3843 		.sync_io = wbc->sync_mode == WB_SYNC_ALL,
3844 	};
3845 	int ret = 0;
3846 	int done = 0;
3847 	int nr_to_write_done = 0;
3848 	struct pagevec pvec;
3849 	int nr_pages;
3850 	pgoff_t index;
3851 	pgoff_t end;		/* Inclusive */
3852 	int scanned = 0;
3853 	int tag;
3854 
3855 	pagevec_init(&pvec);
3856 	if (wbc->range_cyclic) {
3857 		index = mapping->writeback_index; /* Start from prev offset */
3858 		end = -1;
3859 	} else {
3860 		index = wbc->range_start >> PAGE_SHIFT;
3861 		end = wbc->range_end >> PAGE_SHIFT;
3862 		scanned = 1;
3863 	}
3864 	if (wbc->sync_mode == WB_SYNC_ALL)
3865 		tag = PAGECACHE_TAG_TOWRITE;
3866 	else
3867 		tag = PAGECACHE_TAG_DIRTY;
3868 retry:
3869 	if (wbc->sync_mode == WB_SYNC_ALL)
3870 		tag_pages_for_writeback(mapping, index, end);
3871 	while (!done && !nr_to_write_done && (index <= end) &&
3872 	       (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
3873 			tag))) {
3874 		unsigned i;
3875 
3876 		scanned = 1;
3877 		for (i = 0; i < nr_pages; i++) {
3878 			struct page *page = pvec.pages[i];
3879 
3880 			if (!PagePrivate(page))
3881 				continue;
3882 
3883 			spin_lock(&mapping->private_lock);
3884 			if (!PagePrivate(page)) {
3885 				spin_unlock(&mapping->private_lock);
3886 				continue;
3887 			}
3888 
3889 			eb = (struct extent_buffer *)page->private;
3890 
3891 			/*
3892 			 * Shouldn't happen and normally this would be a BUG_ON
3893 			 * but no sense in crashing the users box for something
3894 			 * we can survive anyway.
3895 			 */
3896 			if (WARN_ON(!eb)) {
3897 				spin_unlock(&mapping->private_lock);
3898 				continue;
3899 			}
3900 
3901 			if (eb == prev_eb) {
3902 				spin_unlock(&mapping->private_lock);
3903 				continue;
3904 			}
3905 
3906 			ret = atomic_inc_not_zero(&eb->refs);
3907 			spin_unlock(&mapping->private_lock);
3908 			if (!ret)
3909 				continue;
3910 
3911 			prev_eb = eb;
3912 			ret = lock_extent_buffer_for_io(eb, fs_info, &epd);
3913 			if (!ret) {
3914 				free_extent_buffer(eb);
3915 				continue;
3916 			} else if (ret < 0) {
3917 				done = 1;
3918 				free_extent_buffer(eb);
3919 				break;
3920 			}
3921 
3922 			ret = write_one_eb(eb, fs_info, wbc, &epd);
3923 			if (ret) {
3924 				done = 1;
3925 				free_extent_buffer(eb);
3926 				break;
3927 			}
3928 			free_extent_buffer(eb);
3929 
3930 			/*
3931 			 * The filesystem may choose to bump up nr_to_write.
3932 			 * We have to make sure to honor the new nr_to_write
3933 			 * at any time.
3934 			 */
3935 			nr_to_write_done = (wbc->sync_mode == WB_SYNC_NONE &&
3936 					    wbc->nr_to_write <= 0);
3937 		}
3938 		pagevec_release(&pvec);
3939 		cond_resched();
3940 	}
3941 	if (!scanned && !done) {
3942 		/*
3943 		 * We hit the last page and there is more work to be done: wrap
3944 		 * back to the start of the file
3945 		 */
3946 		scanned = 1;
3947 		index = 0;
3948 		goto retry;
3949 	}
3950 	ASSERT(ret <= 0);
3951 	if (ret < 0) {
3952 		end_write_bio(&epd, ret);
3953 		return ret;
3954 	}
3955 	/*
3956 	 * If something went wrong, don't allow any metadata write bio to be
3957 	 * submitted.
3958 	 *
3959 	 * This would prevent use-after-free if we had dirty pages not
3960 	 * cleaned up, which can still happen by fuzzed images.
3961 	 *
3962 	 * - Bad extent tree
3963 	 *   Allowing existing tree block to be allocated for other trees.
3964 	 *
3965 	 * - Log tree operations
3966 	 *   Exiting tree blocks get allocated to log tree, bumps its
3967 	 *   generation, then get cleaned in tree re-balance.
3968 	 *   Such tree block will not be written back, since it's clean,
3969 	 *   thus no WRITTEN flag set.
3970 	 *   And after log writes back, this tree block is not traced by
3971 	 *   any dirty extent_io_tree.
3972 	 *
3973 	 * - Offending tree block gets re-dirtied from its original owner
3974 	 *   Since it has bumped generation, no WRITTEN flag, it can be
3975 	 *   reused without COWing. This tree block will not be traced
3976 	 *   by btrfs_transaction::dirty_pages.
3977 	 *
3978 	 *   Now such dirty tree block will not be cleaned by any dirty
3979 	 *   extent io tree. Thus we don't want to submit such wild eb
3980 	 *   if the fs already has error.
3981 	 */
3982 	if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
3983 		ret = flush_write_bio(&epd);
3984 	} else {
3985 		ret = -EUCLEAN;
3986 		end_write_bio(&epd, ret);
3987 	}
3988 	return ret;
3989 }
3990 
3991 /**
3992  * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
3993  * @mapping: address space structure to write
3994  * @wbc: subtract the number of written pages from *@wbc->nr_to_write
3995  * @data: data passed to __extent_writepage function
3996  *
3997  * If a page is already under I/O, write_cache_pages() skips it, even
3998  * if it's dirty.  This is desirable behaviour for memory-cleaning writeback,
3999  * but it is INCORRECT for data-integrity system calls such as fsync().  fsync()
4000  * and msync() need to guarantee that all the data which was dirty at the time
4001  * the call was made get new I/O started against them.  If wbc->sync_mode is
4002  * WB_SYNC_ALL then we were called for data integrity and we must wait for
4003  * existing IO to complete.
4004  */
extent_write_cache_pages(struct address_space * mapping,struct writeback_control * wbc,struct extent_page_data * epd)4005 static int extent_write_cache_pages(struct address_space *mapping,
4006 			     struct writeback_control *wbc,
4007 			     struct extent_page_data *epd)
4008 {
4009 	struct inode *inode = mapping->host;
4010 	int ret = 0;
4011 	int done = 0;
4012 	int nr_to_write_done = 0;
4013 	struct pagevec pvec;
4014 	int nr_pages;
4015 	pgoff_t index;
4016 	pgoff_t end;		/* Inclusive */
4017 	pgoff_t done_index;
4018 	int range_whole = 0;
4019 	int scanned = 0;
4020 	int tag;
4021 
4022 	/*
4023 	 * We have to hold onto the inode so that ordered extents can do their
4024 	 * work when the IO finishes.  The alternative to this is failing to add
4025 	 * an ordered extent if the igrab() fails there and that is a huge pain
4026 	 * to deal with, so instead just hold onto the inode throughout the
4027 	 * writepages operation.  If it fails here we are freeing up the inode
4028 	 * anyway and we'd rather not waste our time writing out stuff that is
4029 	 * going to be truncated anyway.
4030 	 */
4031 	if (!igrab(inode))
4032 		return 0;
4033 
4034 	pagevec_init(&pvec);
4035 	if (wbc->range_cyclic) {
4036 		index = mapping->writeback_index; /* Start from prev offset */
4037 		end = -1;
4038 	} else {
4039 		index = wbc->range_start >> PAGE_SHIFT;
4040 		end = wbc->range_end >> PAGE_SHIFT;
4041 		if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4042 			range_whole = 1;
4043 		scanned = 1;
4044 	}
4045 
4046 	/*
4047 	 * We do the tagged writepage as long as the snapshot flush bit is set
4048 	 * and we are the first one who do the filemap_flush() on this inode.
4049 	 *
4050 	 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4051 	 * not race in and drop the bit.
4052 	 */
4053 	if (range_whole && wbc->nr_to_write == LONG_MAX &&
4054 	    test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4055 			       &BTRFS_I(inode)->runtime_flags))
4056 		wbc->tagged_writepages = 1;
4057 
4058 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4059 		tag = PAGECACHE_TAG_TOWRITE;
4060 	else
4061 		tag = PAGECACHE_TAG_DIRTY;
4062 retry:
4063 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4064 		tag_pages_for_writeback(mapping, index, end);
4065 	done_index = index;
4066 	while (!done && !nr_to_write_done && (index <= end) &&
4067 			(nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4068 						&index, end, tag))) {
4069 		unsigned i;
4070 
4071 		scanned = 1;
4072 		for (i = 0; i < nr_pages; i++) {
4073 			struct page *page = pvec.pages[i];
4074 
4075 			done_index = page->index + 1;
4076 			/*
4077 			 * At this point we hold neither the i_pages lock nor
4078 			 * the page lock: the page may be truncated or
4079 			 * invalidated (changing page->mapping to NULL),
4080 			 * or even swizzled back from swapper_space to
4081 			 * tmpfs file mapping
4082 			 */
4083 			if (!trylock_page(page)) {
4084 				ret = flush_write_bio(epd);
4085 				BUG_ON(ret < 0);
4086 				lock_page(page);
4087 			}
4088 
4089 			if (unlikely(page->mapping != mapping)) {
4090 				unlock_page(page);
4091 				continue;
4092 			}
4093 
4094 			if (wbc->sync_mode != WB_SYNC_NONE) {
4095 				if (PageWriteback(page)) {
4096 					ret = flush_write_bio(epd);
4097 					BUG_ON(ret < 0);
4098 				}
4099 				wait_on_page_writeback(page);
4100 			}
4101 
4102 			if (PageWriteback(page) ||
4103 			    !clear_page_dirty_for_io(page)) {
4104 				unlock_page(page);
4105 				continue;
4106 			}
4107 
4108 			ret = __extent_writepage(page, wbc, epd);
4109 
4110 			if (unlikely(ret == AOP_WRITEPAGE_ACTIVATE)) {
4111 				unlock_page(page);
4112 				ret = 0;
4113 			}
4114 			if (ret < 0) {
4115 				done = 1;
4116 				break;
4117 			}
4118 
4119 			/*
4120 			 * the filesystem may choose to bump up nr_to_write.
4121 			 * We have to make sure to honor the new nr_to_write
4122 			 * at any time
4123 			 */
4124 			nr_to_write_done = wbc->nr_to_write <= 0;
4125 		}
4126 		pagevec_release(&pvec);
4127 		cond_resched();
4128 	}
4129 	if (!scanned && !done) {
4130 		/*
4131 		 * We hit the last page and there is more work to be done: wrap
4132 		 * back to the start of the file
4133 		 */
4134 		scanned = 1;
4135 		index = 0;
4136 
4137 		/*
4138 		 * If we're looping we could run into a page that is locked by a
4139 		 * writer and that writer could be waiting on writeback for a
4140 		 * page in our current bio, and thus deadlock, so flush the
4141 		 * write bio here.
4142 		 */
4143 		ret = flush_write_bio(epd);
4144 		if (!ret)
4145 			goto retry;
4146 	}
4147 
4148 	if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
4149 		mapping->writeback_index = done_index;
4150 
4151 	btrfs_add_delayed_iput(inode);
4152 	return ret;
4153 }
4154 
extent_write_full_page(struct page * page,struct writeback_control * wbc)4155 int extent_write_full_page(struct page *page, struct writeback_control *wbc)
4156 {
4157 	int ret;
4158 	struct extent_page_data epd = {
4159 		.bio = NULL,
4160 		.tree = &BTRFS_I(page->mapping->host)->io_tree,
4161 		.extent_locked = 0,
4162 		.sync_io = wbc->sync_mode == WB_SYNC_ALL,
4163 	};
4164 
4165 	ret = __extent_writepage(page, wbc, &epd);
4166 	ASSERT(ret <= 0);
4167 	if (ret < 0) {
4168 		end_write_bio(&epd, ret);
4169 		return ret;
4170 	}
4171 
4172 	ret = flush_write_bio(&epd);
4173 	ASSERT(ret <= 0);
4174 	return ret;
4175 }
4176 
extent_write_locked_range(struct inode * inode,u64 start,u64 end,int mode)4177 int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
4178 			      int mode)
4179 {
4180 	int ret = 0;
4181 	int flush_ret;
4182 	struct address_space *mapping = inode->i_mapping;
4183 	struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
4184 	struct page *page;
4185 	unsigned long nr_pages = (end - start + PAGE_SIZE) >>
4186 		PAGE_SHIFT;
4187 
4188 	struct extent_page_data epd = {
4189 		.bio = NULL,
4190 		.tree = tree,
4191 		.extent_locked = 1,
4192 		.sync_io = mode == WB_SYNC_ALL,
4193 	};
4194 	struct writeback_control wbc_writepages = {
4195 		.sync_mode	= mode,
4196 		.nr_to_write	= nr_pages * 2,
4197 		.range_start	= start,
4198 		.range_end	= end + 1,
4199 	};
4200 
4201 	while (start <= end) {
4202 		page = find_get_page(mapping, start >> PAGE_SHIFT);
4203 		if (clear_page_dirty_for_io(page))
4204 			ret = __extent_writepage(page, &wbc_writepages, &epd);
4205 		else {
4206 			if (tree->ops && tree->ops->writepage_end_io_hook)
4207 				tree->ops->writepage_end_io_hook(page, start,
4208 						 start + PAGE_SIZE - 1,
4209 						 NULL, 1);
4210 			unlock_page(page);
4211 		}
4212 		put_page(page);
4213 		start += PAGE_SIZE;
4214 	}
4215 
4216 	flush_ret = flush_write_bio(&epd);
4217 	BUG_ON(flush_ret < 0);
4218 	return ret;
4219 }
4220 
extent_writepages(struct address_space * mapping,struct writeback_control * wbc)4221 int extent_writepages(struct address_space *mapping,
4222 		      struct writeback_control *wbc)
4223 {
4224 	int ret = 0;
4225 	int flush_ret;
4226 	struct extent_page_data epd = {
4227 		.bio = NULL,
4228 		.tree = &BTRFS_I(mapping->host)->io_tree,
4229 		.extent_locked = 0,
4230 		.sync_io = wbc->sync_mode == WB_SYNC_ALL,
4231 	};
4232 
4233 	ret = extent_write_cache_pages(mapping, wbc, &epd);
4234 	flush_ret = flush_write_bio(&epd);
4235 	BUG_ON(flush_ret < 0);
4236 	return ret;
4237 }
4238 
extent_readpages(struct address_space * mapping,struct list_head * pages,unsigned nr_pages)4239 int extent_readpages(struct address_space *mapping, struct list_head *pages,
4240 		     unsigned nr_pages)
4241 {
4242 	struct bio *bio = NULL;
4243 	unsigned page_idx;
4244 	unsigned long bio_flags = 0;
4245 	struct page *pagepool[16];
4246 	struct page *page;
4247 	struct extent_map *em_cached = NULL;
4248 	struct extent_io_tree *tree = &BTRFS_I(mapping->host)->io_tree;
4249 	int nr = 0;
4250 	u64 prev_em_start = (u64)-1;
4251 
4252 	for (page_idx = 0; page_idx < nr_pages; page_idx++) {
4253 		page = list_entry(pages->prev, struct page, lru);
4254 
4255 		prefetchw(&page->flags);
4256 		list_del(&page->lru);
4257 		if (add_to_page_cache_lru(page, mapping,
4258 					page->index,
4259 					readahead_gfp_mask(mapping))) {
4260 			put_page(page);
4261 			continue;
4262 		}
4263 
4264 		pagepool[nr++] = page;
4265 		if (nr < ARRAY_SIZE(pagepool))
4266 			continue;
4267 		__extent_readpages(tree, pagepool, nr, &em_cached, &bio,
4268 				&bio_flags, &prev_em_start);
4269 		nr = 0;
4270 	}
4271 	if (nr)
4272 		__extent_readpages(tree, pagepool, nr, &em_cached, &bio,
4273 				&bio_flags, &prev_em_start);
4274 
4275 	if (em_cached)
4276 		free_extent_map(em_cached);
4277 
4278 	BUG_ON(!list_empty(pages));
4279 	if (bio)
4280 		return submit_one_bio(bio, 0, bio_flags);
4281 	return 0;
4282 }
4283 
4284 /*
4285  * basic invalidatepage code, this waits on any locked or writeback
4286  * ranges corresponding to the page, and then deletes any extent state
4287  * records from the tree
4288  */
extent_invalidatepage(struct extent_io_tree * tree,struct page * page,unsigned long offset)4289 int extent_invalidatepage(struct extent_io_tree *tree,
4290 			  struct page *page, unsigned long offset)
4291 {
4292 	struct extent_state *cached_state = NULL;
4293 	u64 start = page_offset(page);
4294 	u64 end = start + PAGE_SIZE - 1;
4295 	size_t blocksize = page->mapping->host->i_sb->s_blocksize;
4296 
4297 	start += ALIGN(offset, blocksize);
4298 	if (start > end)
4299 		return 0;
4300 
4301 	lock_extent_bits(tree, start, end, &cached_state);
4302 	wait_on_page_writeback(page);
4303 	clear_extent_bit(tree, start, end,
4304 			 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
4305 			 EXTENT_DO_ACCOUNTING,
4306 			 1, 1, &cached_state);
4307 	return 0;
4308 }
4309 
4310 /*
4311  * a helper for releasepage, this tests for areas of the page that
4312  * are locked or under IO and drops the related state bits if it is safe
4313  * to drop the page.
4314  */
try_release_extent_state(struct extent_io_tree * tree,struct page * page,gfp_t mask)4315 static int try_release_extent_state(struct extent_io_tree *tree,
4316 				    struct page *page, gfp_t mask)
4317 {
4318 	u64 start = page_offset(page);
4319 	u64 end = start + PAGE_SIZE - 1;
4320 	int ret = 1;
4321 
4322 	if (test_range_bit(tree, start, end,
4323 			   EXTENT_IOBITS, 0, NULL))
4324 		ret = 0;
4325 	else {
4326 		/*
4327 		 * at this point we can safely clear everything except the
4328 		 * locked bit and the nodatasum bit
4329 		 */
4330 		ret = __clear_extent_bit(tree, start, end,
4331 				 ~(EXTENT_LOCKED | EXTENT_NODATASUM),
4332 				 0, 0, NULL, mask, NULL);
4333 
4334 		/* if clear_extent_bit failed for enomem reasons,
4335 		 * we can't allow the release to continue.
4336 		 */
4337 		if (ret < 0)
4338 			ret = 0;
4339 		else
4340 			ret = 1;
4341 	}
4342 	return ret;
4343 }
4344 
4345 /*
4346  * a helper for releasepage.  As long as there are no locked extents
4347  * in the range corresponding to the page, both state records and extent
4348  * map records are removed
4349  */
try_release_extent_mapping(struct page * page,gfp_t mask)4350 int try_release_extent_mapping(struct page *page, gfp_t mask)
4351 {
4352 	struct extent_map *em;
4353 	u64 start = page_offset(page);
4354 	u64 end = start + PAGE_SIZE - 1;
4355 	struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
4356 	struct extent_io_tree *tree = &btrfs_inode->io_tree;
4357 	struct extent_map_tree *map = &btrfs_inode->extent_tree;
4358 
4359 	if (gfpflags_allow_blocking(mask) &&
4360 	    page->mapping->host->i_size > SZ_16M) {
4361 		u64 len;
4362 		while (start <= end) {
4363 			len = end - start + 1;
4364 			write_lock(&map->lock);
4365 			em = lookup_extent_mapping(map, start, len);
4366 			if (!em) {
4367 				write_unlock(&map->lock);
4368 				break;
4369 			}
4370 			if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
4371 			    em->start != start) {
4372 				write_unlock(&map->lock);
4373 				free_extent_map(em);
4374 				break;
4375 			}
4376 			if (!test_range_bit(tree, em->start,
4377 					    extent_map_end(em) - 1,
4378 					    EXTENT_LOCKED | EXTENT_WRITEBACK,
4379 					    0, NULL)) {
4380 				set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4381 					&btrfs_inode->runtime_flags);
4382 				remove_extent_mapping(map, em);
4383 				/* once for the rb tree */
4384 				free_extent_map(em);
4385 			}
4386 			start = extent_map_end(em);
4387 			write_unlock(&map->lock);
4388 
4389 			/* once for us */
4390 			free_extent_map(em);
4391 
4392 			cond_resched(); /* Allow large-extent preemption. */
4393 		}
4394 	}
4395 	return try_release_extent_state(tree, page, mask);
4396 }
4397 
4398 /*
4399  * helper function for fiemap, which doesn't want to see any holes.
4400  * This maps until we find something past 'last'
4401  */
get_extent_skip_holes(struct inode * inode,u64 offset,u64 last)4402 static struct extent_map *get_extent_skip_holes(struct inode *inode,
4403 						u64 offset, u64 last)
4404 {
4405 	u64 sectorsize = btrfs_inode_sectorsize(inode);
4406 	struct extent_map *em;
4407 	u64 len;
4408 
4409 	if (offset >= last)
4410 		return NULL;
4411 
4412 	while (1) {
4413 		len = last - offset;
4414 		if (len == 0)
4415 			break;
4416 		len = ALIGN(len, sectorsize);
4417 		em = btrfs_get_extent_fiemap(BTRFS_I(inode), NULL, 0, offset,
4418 				len, 0);
4419 		if (IS_ERR_OR_NULL(em))
4420 			return em;
4421 
4422 		/* if this isn't a hole return it */
4423 		if (em->block_start != EXTENT_MAP_HOLE)
4424 			return em;
4425 
4426 		/* this is a hole, advance to the next extent */
4427 		offset = extent_map_end(em);
4428 		free_extent_map(em);
4429 		if (offset >= last)
4430 			break;
4431 	}
4432 	return NULL;
4433 }
4434 
4435 /*
4436  * To cache previous fiemap extent
4437  *
4438  * Will be used for merging fiemap extent
4439  */
4440 struct fiemap_cache {
4441 	u64 offset;
4442 	u64 phys;
4443 	u64 len;
4444 	u32 flags;
4445 	bool cached;
4446 };
4447 
4448 /*
4449  * Helper to submit fiemap extent.
4450  *
4451  * Will try to merge current fiemap extent specified by @offset, @phys,
4452  * @len and @flags with cached one.
4453  * And only when we fails to merge, cached one will be submitted as
4454  * fiemap extent.
4455  *
4456  * Return value is the same as fiemap_fill_next_extent().
4457  */
emit_fiemap_extent(struct fiemap_extent_info * fieinfo,struct fiemap_cache * cache,u64 offset,u64 phys,u64 len,u32 flags)4458 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
4459 				struct fiemap_cache *cache,
4460 				u64 offset, u64 phys, u64 len, u32 flags)
4461 {
4462 	int ret = 0;
4463 
4464 	if (!cache->cached)
4465 		goto assign;
4466 
4467 	/*
4468 	 * Sanity check, extent_fiemap() should have ensured that new
4469 	 * fiemap extent won't overlap with cahced one.
4470 	 * Not recoverable.
4471 	 *
4472 	 * NOTE: Physical address can overlap, due to compression
4473 	 */
4474 	if (cache->offset + cache->len > offset) {
4475 		WARN_ON(1);
4476 		return -EINVAL;
4477 	}
4478 
4479 	/*
4480 	 * Only merges fiemap extents if
4481 	 * 1) Their logical addresses are continuous
4482 	 *
4483 	 * 2) Their physical addresses are continuous
4484 	 *    So truly compressed (physical size smaller than logical size)
4485 	 *    extents won't get merged with each other
4486 	 *
4487 	 * 3) Share same flags except FIEMAP_EXTENT_LAST
4488 	 *    So regular extent won't get merged with prealloc extent
4489 	 */
4490 	if (cache->offset + cache->len  == offset &&
4491 	    cache->phys + cache->len == phys  &&
4492 	    (cache->flags & ~FIEMAP_EXTENT_LAST) ==
4493 			(flags & ~FIEMAP_EXTENT_LAST)) {
4494 		cache->len += len;
4495 		cache->flags |= flags;
4496 		goto try_submit_last;
4497 	}
4498 
4499 	/* Not mergeable, need to submit cached one */
4500 	ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4501 				      cache->len, cache->flags);
4502 	cache->cached = false;
4503 	if (ret)
4504 		return ret;
4505 assign:
4506 	cache->cached = true;
4507 	cache->offset = offset;
4508 	cache->phys = phys;
4509 	cache->len = len;
4510 	cache->flags = flags;
4511 try_submit_last:
4512 	if (cache->flags & FIEMAP_EXTENT_LAST) {
4513 		ret = fiemap_fill_next_extent(fieinfo, cache->offset,
4514 				cache->phys, cache->len, cache->flags);
4515 		cache->cached = false;
4516 	}
4517 	return ret;
4518 }
4519 
4520 /*
4521  * Emit last fiemap cache
4522  *
4523  * The last fiemap cache may still be cached in the following case:
4524  * 0		      4k		    8k
4525  * |<- Fiemap range ->|
4526  * |<------------  First extent ----------->|
4527  *
4528  * In this case, the first extent range will be cached but not emitted.
4529  * So we must emit it before ending extent_fiemap().
4530  */
emit_last_fiemap_cache(struct btrfs_fs_info * fs_info,struct fiemap_extent_info * fieinfo,struct fiemap_cache * cache)4531 static int emit_last_fiemap_cache(struct btrfs_fs_info *fs_info,
4532 				  struct fiemap_extent_info *fieinfo,
4533 				  struct fiemap_cache *cache)
4534 {
4535 	int ret;
4536 
4537 	if (!cache->cached)
4538 		return 0;
4539 
4540 	ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4541 				      cache->len, cache->flags);
4542 	cache->cached = false;
4543 	if (ret > 0)
4544 		ret = 0;
4545 	return ret;
4546 }
4547 
extent_fiemap(struct inode * inode,struct fiemap_extent_info * fieinfo,__u64 start,__u64 len)4548 int extent_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4549 		__u64 start, __u64 len)
4550 {
4551 	int ret = 0;
4552 	u64 off = start;
4553 	u64 max = start + len;
4554 	u32 flags = 0;
4555 	u32 found_type;
4556 	u64 last;
4557 	u64 last_for_get_extent = 0;
4558 	u64 disko = 0;
4559 	u64 isize = i_size_read(inode);
4560 	struct btrfs_key found_key;
4561 	struct extent_map *em = NULL;
4562 	struct extent_state *cached_state = NULL;
4563 	struct btrfs_path *path;
4564 	struct btrfs_root *root = BTRFS_I(inode)->root;
4565 	struct fiemap_cache cache = { 0 };
4566 	int end = 0;
4567 	u64 em_start = 0;
4568 	u64 em_len = 0;
4569 	u64 em_end = 0;
4570 
4571 	if (len == 0)
4572 		return -EINVAL;
4573 
4574 	path = btrfs_alloc_path();
4575 	if (!path)
4576 		return -ENOMEM;
4577 	path->leave_spinning = 1;
4578 
4579 	start = round_down(start, btrfs_inode_sectorsize(inode));
4580 	len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
4581 
4582 	/*
4583 	 * lookup the last file extent.  We're not using i_size here
4584 	 * because there might be preallocation past i_size
4585 	 */
4586 	ret = btrfs_lookup_file_extent(NULL, root, path,
4587 			btrfs_ino(BTRFS_I(inode)), -1, 0);
4588 	if (ret < 0) {
4589 		btrfs_free_path(path);
4590 		return ret;
4591 	} else {
4592 		WARN_ON(!ret);
4593 		if (ret == 1)
4594 			ret = 0;
4595 	}
4596 
4597 	path->slots[0]--;
4598 	btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
4599 	found_type = found_key.type;
4600 
4601 	/* No extents, but there might be delalloc bits */
4602 	if (found_key.objectid != btrfs_ino(BTRFS_I(inode)) ||
4603 	    found_type != BTRFS_EXTENT_DATA_KEY) {
4604 		/* have to trust i_size as the end */
4605 		last = (u64)-1;
4606 		last_for_get_extent = isize;
4607 	} else {
4608 		/*
4609 		 * remember the start of the last extent.  There are a
4610 		 * bunch of different factors that go into the length of the
4611 		 * extent, so its much less complex to remember where it started
4612 		 */
4613 		last = found_key.offset;
4614 		last_for_get_extent = last + 1;
4615 	}
4616 	btrfs_release_path(path);
4617 
4618 	/*
4619 	 * we might have some extents allocated but more delalloc past those
4620 	 * extents.  so, we trust isize unless the start of the last extent is
4621 	 * beyond isize
4622 	 */
4623 	if (last < isize) {
4624 		last = (u64)-1;
4625 		last_for_get_extent = isize;
4626 	}
4627 
4628 	lock_extent_bits(&BTRFS_I(inode)->io_tree, start, start + len - 1,
4629 			 &cached_state);
4630 
4631 	em = get_extent_skip_holes(inode, start, last_for_get_extent);
4632 	if (!em)
4633 		goto out;
4634 	if (IS_ERR(em)) {
4635 		ret = PTR_ERR(em);
4636 		goto out;
4637 	}
4638 
4639 	while (!end) {
4640 		u64 offset_in_extent = 0;
4641 
4642 		/* break if the extent we found is outside the range */
4643 		if (em->start >= max || extent_map_end(em) < off)
4644 			break;
4645 
4646 		/*
4647 		 * get_extent may return an extent that starts before our
4648 		 * requested range.  We have to make sure the ranges
4649 		 * we return to fiemap always move forward and don't
4650 		 * overlap, so adjust the offsets here
4651 		 */
4652 		em_start = max(em->start, off);
4653 
4654 		/*
4655 		 * record the offset from the start of the extent
4656 		 * for adjusting the disk offset below.  Only do this if the
4657 		 * extent isn't compressed since our in ram offset may be past
4658 		 * what we have actually allocated on disk.
4659 		 */
4660 		if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4661 			offset_in_extent = em_start - em->start;
4662 		em_end = extent_map_end(em);
4663 		em_len = em_end - em_start;
4664 		flags = 0;
4665 		if (em->block_start < EXTENT_MAP_LAST_BYTE)
4666 			disko = em->block_start + offset_in_extent;
4667 		else
4668 			disko = 0;
4669 
4670 		/*
4671 		 * bump off for our next call to get_extent
4672 		 */
4673 		off = extent_map_end(em);
4674 		if (off >= max)
4675 			end = 1;
4676 
4677 		if (em->block_start == EXTENT_MAP_LAST_BYTE) {
4678 			end = 1;
4679 			flags |= FIEMAP_EXTENT_LAST;
4680 		} else if (em->block_start == EXTENT_MAP_INLINE) {
4681 			flags |= (FIEMAP_EXTENT_DATA_INLINE |
4682 				  FIEMAP_EXTENT_NOT_ALIGNED);
4683 		} else if (em->block_start == EXTENT_MAP_DELALLOC) {
4684 			flags |= (FIEMAP_EXTENT_DELALLOC |
4685 				  FIEMAP_EXTENT_UNKNOWN);
4686 		} else if (fieinfo->fi_extents_max) {
4687 			u64 bytenr = em->block_start -
4688 				(em->start - em->orig_start);
4689 
4690 			/*
4691 			 * As btrfs supports shared space, this information
4692 			 * can be exported to userspace tools via
4693 			 * flag FIEMAP_EXTENT_SHARED.  If fi_extents_max == 0
4694 			 * then we're just getting a count and we can skip the
4695 			 * lookup stuff.
4696 			 */
4697 			ret = btrfs_check_shared(root,
4698 						 btrfs_ino(BTRFS_I(inode)),
4699 						 bytenr);
4700 			if (ret < 0)
4701 				goto out_free;
4702 			if (ret)
4703 				flags |= FIEMAP_EXTENT_SHARED;
4704 			ret = 0;
4705 		}
4706 		if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
4707 			flags |= FIEMAP_EXTENT_ENCODED;
4708 		if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4709 			flags |= FIEMAP_EXTENT_UNWRITTEN;
4710 
4711 		free_extent_map(em);
4712 		em = NULL;
4713 		if ((em_start >= last) || em_len == (u64)-1 ||
4714 		   (last == (u64)-1 && isize <= em_end)) {
4715 			flags |= FIEMAP_EXTENT_LAST;
4716 			end = 1;
4717 		}
4718 
4719 		/* now scan forward to see if this is really the last extent. */
4720 		em = get_extent_skip_holes(inode, off, last_for_get_extent);
4721 		if (IS_ERR(em)) {
4722 			ret = PTR_ERR(em);
4723 			goto out;
4724 		}
4725 		if (!em) {
4726 			flags |= FIEMAP_EXTENT_LAST;
4727 			end = 1;
4728 		}
4729 		ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
4730 					   em_len, flags);
4731 		if (ret) {
4732 			if (ret == 1)
4733 				ret = 0;
4734 			goto out_free;
4735 		}
4736 	}
4737 out_free:
4738 	if (!ret)
4739 		ret = emit_last_fiemap_cache(root->fs_info, fieinfo, &cache);
4740 	free_extent_map(em);
4741 out:
4742 	btrfs_free_path(path);
4743 	unlock_extent_cached(&BTRFS_I(inode)->io_tree, start, start + len - 1,
4744 			     &cached_state);
4745 	return ret;
4746 }
4747 
__free_extent_buffer(struct extent_buffer * eb)4748 static void __free_extent_buffer(struct extent_buffer *eb)
4749 {
4750 	btrfs_leak_debug_del(&eb->leak_list);
4751 	kmem_cache_free(extent_buffer_cache, eb);
4752 }
4753 
extent_buffer_under_io(struct extent_buffer * eb)4754 int extent_buffer_under_io(struct extent_buffer *eb)
4755 {
4756 	return (atomic_read(&eb->io_pages) ||
4757 		test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
4758 		test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4759 }
4760 
4761 /*
4762  * Release all pages attached to the extent buffer.
4763  */
btrfs_release_extent_buffer_pages(struct extent_buffer * eb)4764 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
4765 {
4766 	int i;
4767 	int num_pages;
4768 	int mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4769 
4770 	BUG_ON(extent_buffer_under_io(eb));
4771 
4772 	num_pages = num_extent_pages(eb);
4773 	for (i = 0; i < num_pages; i++) {
4774 		struct page *page = eb->pages[i];
4775 
4776 		if (!page)
4777 			continue;
4778 		if (mapped)
4779 			spin_lock(&page->mapping->private_lock);
4780 		/*
4781 		 * We do this since we'll remove the pages after we've
4782 		 * removed the eb from the radix tree, so we could race
4783 		 * and have this page now attached to the new eb.  So
4784 		 * only clear page_private if it's still connected to
4785 		 * this eb.
4786 		 */
4787 		if (PagePrivate(page) &&
4788 		    page->private == (unsigned long)eb) {
4789 			BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4790 			BUG_ON(PageDirty(page));
4791 			BUG_ON(PageWriteback(page));
4792 			/*
4793 			 * We need to make sure we haven't be attached
4794 			 * to a new eb.
4795 			 */
4796 			ClearPagePrivate(page);
4797 			set_page_private(page, 0);
4798 			/* One for the page private */
4799 			put_page(page);
4800 		}
4801 
4802 		if (mapped)
4803 			spin_unlock(&page->mapping->private_lock);
4804 
4805 		/* One for when we allocated the page */
4806 		put_page(page);
4807 	}
4808 }
4809 
4810 /*
4811  * Helper for releasing the extent buffer.
4812  */
btrfs_release_extent_buffer(struct extent_buffer * eb)4813 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
4814 {
4815 	btrfs_release_extent_buffer_pages(eb);
4816 	__free_extent_buffer(eb);
4817 }
4818 
4819 static struct extent_buffer *
__alloc_extent_buffer(struct btrfs_fs_info * fs_info,u64 start,unsigned long len)4820 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
4821 		      unsigned long len)
4822 {
4823 	struct extent_buffer *eb = NULL;
4824 
4825 	eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
4826 	eb->start = start;
4827 	eb->len = len;
4828 	eb->fs_info = fs_info;
4829 	eb->bflags = 0;
4830 	rwlock_init(&eb->lock);
4831 	atomic_set(&eb->write_locks, 0);
4832 	atomic_set(&eb->read_locks, 0);
4833 	atomic_set(&eb->blocking_readers, 0);
4834 	atomic_set(&eb->blocking_writers, 0);
4835 	atomic_set(&eb->spinning_readers, 0);
4836 	atomic_set(&eb->spinning_writers, 0);
4837 	eb->lock_nested = 0;
4838 	init_waitqueue_head(&eb->write_lock_wq);
4839 	init_waitqueue_head(&eb->read_lock_wq);
4840 
4841 	btrfs_leak_debug_add(&eb->leak_list, &buffers);
4842 
4843 	spin_lock_init(&eb->refs_lock);
4844 	atomic_set(&eb->refs, 1);
4845 	atomic_set(&eb->io_pages, 0);
4846 
4847 	/*
4848 	 * Sanity checks, currently the maximum is 64k covered by 16x 4k pages
4849 	 */
4850 	BUILD_BUG_ON(BTRFS_MAX_METADATA_BLOCKSIZE
4851 		> MAX_INLINE_EXTENT_BUFFER_SIZE);
4852 	BUG_ON(len > MAX_INLINE_EXTENT_BUFFER_SIZE);
4853 
4854 	return eb;
4855 }
4856 
btrfs_clone_extent_buffer(struct extent_buffer * src)4857 struct extent_buffer *btrfs_clone_extent_buffer(struct extent_buffer *src)
4858 {
4859 	int i;
4860 	struct page *p;
4861 	struct extent_buffer *new;
4862 	int num_pages = num_extent_pages(src);
4863 
4864 	new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
4865 	if (new == NULL)
4866 		return NULL;
4867 
4868 	for (i = 0; i < num_pages; i++) {
4869 		p = alloc_page(GFP_NOFS);
4870 		if (!p) {
4871 			btrfs_release_extent_buffer(new);
4872 			return NULL;
4873 		}
4874 		attach_extent_buffer_page(new, p);
4875 		WARN_ON(PageDirty(p));
4876 		SetPageUptodate(p);
4877 		new->pages[i] = p;
4878 		copy_page(page_address(p), page_address(src->pages[i]));
4879 	}
4880 
4881 	set_bit(EXTENT_BUFFER_UPTODATE, &new->bflags);
4882 	set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
4883 
4884 	return new;
4885 }
4886 
__alloc_dummy_extent_buffer(struct btrfs_fs_info * fs_info,u64 start,unsigned long len)4887 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4888 						  u64 start, unsigned long len)
4889 {
4890 	struct extent_buffer *eb;
4891 	int num_pages;
4892 	int i;
4893 
4894 	eb = __alloc_extent_buffer(fs_info, start, len);
4895 	if (!eb)
4896 		return NULL;
4897 
4898 	num_pages = num_extent_pages(eb);
4899 	for (i = 0; i < num_pages; i++) {
4900 		eb->pages[i] = alloc_page(GFP_NOFS);
4901 		if (!eb->pages[i])
4902 			goto err;
4903 	}
4904 	set_extent_buffer_uptodate(eb);
4905 	btrfs_set_header_nritems(eb, 0);
4906 	set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4907 
4908 	return eb;
4909 err:
4910 	for (; i > 0; i--)
4911 		__free_page(eb->pages[i - 1]);
4912 	__free_extent_buffer(eb);
4913 	return NULL;
4914 }
4915 
alloc_dummy_extent_buffer(struct btrfs_fs_info * fs_info,u64 start)4916 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4917 						u64 start)
4918 {
4919 	return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
4920 }
4921 
check_buffer_tree_ref(struct extent_buffer * eb)4922 static void check_buffer_tree_ref(struct extent_buffer *eb)
4923 {
4924 	int refs;
4925 	/*
4926 	 * The TREE_REF bit is first set when the extent_buffer is added
4927 	 * to the radix tree. It is also reset, if unset, when a new reference
4928 	 * is created by find_extent_buffer.
4929 	 *
4930 	 * It is only cleared in two cases: freeing the last non-tree
4931 	 * reference to the extent_buffer when its STALE bit is set or
4932 	 * calling releasepage when the tree reference is the only reference.
4933 	 *
4934 	 * In both cases, care is taken to ensure that the extent_buffer's
4935 	 * pages are not under io. However, releasepage can be concurrently
4936 	 * called with creating new references, which is prone to race
4937 	 * conditions between the calls to check_buffer_tree_ref in those
4938 	 * codepaths and clearing TREE_REF in try_release_extent_buffer.
4939 	 *
4940 	 * The actual lifetime of the extent_buffer in the radix tree is
4941 	 * adequately protected by the refcount, but the TREE_REF bit and
4942 	 * its corresponding reference are not. To protect against this
4943 	 * class of races, we call check_buffer_tree_ref from the codepaths
4944 	 * which trigger io after they set eb->io_pages. Note that once io is
4945 	 * initiated, TREE_REF can no longer be cleared, so that is the
4946 	 * moment at which any such race is best fixed.
4947 	 */
4948 	refs = atomic_read(&eb->refs);
4949 	if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4950 		return;
4951 
4952 	spin_lock(&eb->refs_lock);
4953 	if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4954 		atomic_inc(&eb->refs);
4955 	spin_unlock(&eb->refs_lock);
4956 }
4957 
mark_extent_buffer_accessed(struct extent_buffer * eb,struct page * accessed)4958 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
4959 		struct page *accessed)
4960 {
4961 	int num_pages, i;
4962 
4963 	check_buffer_tree_ref(eb);
4964 
4965 	num_pages = num_extent_pages(eb);
4966 	for (i = 0; i < num_pages; i++) {
4967 		struct page *p = eb->pages[i];
4968 
4969 		if (p != accessed)
4970 			mark_page_accessed(p);
4971 	}
4972 }
4973 
find_extent_buffer(struct btrfs_fs_info * fs_info,u64 start)4974 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
4975 					 u64 start)
4976 {
4977 	struct extent_buffer *eb;
4978 
4979 	rcu_read_lock();
4980 	eb = radix_tree_lookup(&fs_info->buffer_radix,
4981 			       start >> PAGE_SHIFT);
4982 	if (eb && atomic_inc_not_zero(&eb->refs)) {
4983 		rcu_read_unlock();
4984 		/*
4985 		 * Lock our eb's refs_lock to avoid races with
4986 		 * free_extent_buffer. When we get our eb it might be flagged
4987 		 * with EXTENT_BUFFER_STALE and another task running
4988 		 * free_extent_buffer might have seen that flag set,
4989 		 * eb->refs == 2, that the buffer isn't under IO (dirty and
4990 		 * writeback flags not set) and it's still in the tree (flag
4991 		 * EXTENT_BUFFER_TREE_REF set), therefore being in the process
4992 		 * of decrementing the extent buffer's reference count twice.
4993 		 * So here we could race and increment the eb's reference count,
4994 		 * clear its stale flag, mark it as dirty and drop our reference
4995 		 * before the other task finishes executing free_extent_buffer,
4996 		 * which would later result in an attempt to free an extent
4997 		 * buffer that is dirty.
4998 		 */
4999 		if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
5000 			spin_lock(&eb->refs_lock);
5001 			spin_unlock(&eb->refs_lock);
5002 		}
5003 		mark_extent_buffer_accessed(eb, NULL);
5004 		return eb;
5005 	}
5006 	rcu_read_unlock();
5007 
5008 	return NULL;
5009 }
5010 
5011 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
alloc_test_extent_buffer(struct btrfs_fs_info * fs_info,u64 start)5012 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
5013 					u64 start)
5014 {
5015 	struct extent_buffer *eb, *exists = NULL;
5016 	int ret;
5017 
5018 	eb = find_extent_buffer(fs_info, start);
5019 	if (eb)
5020 		return eb;
5021 	eb = alloc_dummy_extent_buffer(fs_info, start);
5022 	if (!eb)
5023 		return ERR_PTR(-ENOMEM);
5024 	eb->fs_info = fs_info;
5025 again:
5026 	ret = radix_tree_preload(GFP_NOFS);
5027 	if (ret) {
5028 		exists = ERR_PTR(ret);
5029 		goto free_eb;
5030 	}
5031 	spin_lock(&fs_info->buffer_lock);
5032 	ret = radix_tree_insert(&fs_info->buffer_radix,
5033 				start >> PAGE_SHIFT, eb);
5034 	spin_unlock(&fs_info->buffer_lock);
5035 	radix_tree_preload_end();
5036 	if (ret == -EEXIST) {
5037 		exists = find_extent_buffer(fs_info, start);
5038 		if (exists)
5039 			goto free_eb;
5040 		else
5041 			goto again;
5042 	}
5043 	check_buffer_tree_ref(eb);
5044 	set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5045 
5046 	/*
5047 	 * We will free dummy extent buffer's if they come into
5048 	 * free_extent_buffer with a ref count of 2, but if we are using this we
5049 	 * want the buffers to stay in memory until we're done with them, so
5050 	 * bump the ref count again.
5051 	 */
5052 	atomic_inc(&eb->refs);
5053 	return eb;
5054 free_eb:
5055 	btrfs_release_extent_buffer(eb);
5056 	return exists;
5057 }
5058 #endif
5059 
alloc_extent_buffer(struct btrfs_fs_info * fs_info,u64 start)5060 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
5061 					  u64 start)
5062 {
5063 	unsigned long len = fs_info->nodesize;
5064 	int num_pages;
5065 	int i;
5066 	unsigned long index = start >> PAGE_SHIFT;
5067 	struct extent_buffer *eb;
5068 	struct extent_buffer *exists = NULL;
5069 	struct page *p;
5070 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
5071 	int uptodate = 1;
5072 	int ret;
5073 
5074 	if (!IS_ALIGNED(start, fs_info->sectorsize)) {
5075 		btrfs_err(fs_info, "bad tree block start %llu", start);
5076 		return ERR_PTR(-EINVAL);
5077 	}
5078 
5079 	eb = find_extent_buffer(fs_info, start);
5080 	if (eb)
5081 		return eb;
5082 
5083 	eb = __alloc_extent_buffer(fs_info, start, len);
5084 	if (!eb)
5085 		return ERR_PTR(-ENOMEM);
5086 
5087 	num_pages = num_extent_pages(eb);
5088 	for (i = 0; i < num_pages; i++, index++) {
5089 		p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
5090 		if (!p) {
5091 			exists = ERR_PTR(-ENOMEM);
5092 			goto free_eb;
5093 		}
5094 
5095 		spin_lock(&mapping->private_lock);
5096 		if (PagePrivate(p)) {
5097 			/*
5098 			 * We could have already allocated an eb for this page
5099 			 * and attached one so lets see if we can get a ref on
5100 			 * the existing eb, and if we can we know it's good and
5101 			 * we can just return that one, else we know we can just
5102 			 * overwrite page->private.
5103 			 */
5104 			exists = (struct extent_buffer *)p->private;
5105 			if (atomic_inc_not_zero(&exists->refs)) {
5106 				spin_unlock(&mapping->private_lock);
5107 				unlock_page(p);
5108 				put_page(p);
5109 				mark_extent_buffer_accessed(exists, p);
5110 				goto free_eb;
5111 			}
5112 			exists = NULL;
5113 
5114 			/*
5115 			 * Do this so attach doesn't complain and we need to
5116 			 * drop the ref the old guy had.
5117 			 */
5118 			ClearPagePrivate(p);
5119 			WARN_ON(PageDirty(p));
5120 			put_page(p);
5121 		}
5122 		attach_extent_buffer_page(eb, p);
5123 		spin_unlock(&mapping->private_lock);
5124 		WARN_ON(PageDirty(p));
5125 		eb->pages[i] = p;
5126 		if (!PageUptodate(p))
5127 			uptodate = 0;
5128 
5129 		/*
5130 		 * We can't unlock the pages just yet since the extent buffer
5131 		 * hasn't been properly inserted in the radix tree, this
5132 		 * opens a race with btree_releasepage which can free a page
5133 		 * while we are still filling in all pages for the buffer and
5134 		 * we could crash.
5135 		 */
5136 	}
5137 	if (uptodate)
5138 		set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5139 again:
5140 	ret = radix_tree_preload(GFP_NOFS);
5141 	if (ret) {
5142 		exists = ERR_PTR(ret);
5143 		goto free_eb;
5144 	}
5145 
5146 	spin_lock(&fs_info->buffer_lock);
5147 	ret = radix_tree_insert(&fs_info->buffer_radix,
5148 				start >> PAGE_SHIFT, eb);
5149 	spin_unlock(&fs_info->buffer_lock);
5150 	radix_tree_preload_end();
5151 	if (ret == -EEXIST) {
5152 		exists = find_extent_buffer(fs_info, start);
5153 		if (exists)
5154 			goto free_eb;
5155 		else
5156 			goto again;
5157 	}
5158 	/* add one reference for the tree */
5159 	check_buffer_tree_ref(eb);
5160 	set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5161 
5162 	/*
5163 	 * Now it's safe to unlock the pages because any calls to
5164 	 * btree_releasepage will correctly detect that a page belongs to a
5165 	 * live buffer and won't free them prematurely.
5166 	 */
5167 	for (i = 0; i < num_pages; i++)
5168 		unlock_page(eb->pages[i]);
5169 	return eb;
5170 
5171 free_eb:
5172 	WARN_ON(!atomic_dec_and_test(&eb->refs));
5173 	for (i = 0; i < num_pages; i++) {
5174 		if (eb->pages[i])
5175 			unlock_page(eb->pages[i]);
5176 	}
5177 
5178 	btrfs_release_extent_buffer(eb);
5179 	return exists;
5180 }
5181 
btrfs_release_extent_buffer_rcu(struct rcu_head * head)5182 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
5183 {
5184 	struct extent_buffer *eb =
5185 			container_of(head, struct extent_buffer, rcu_head);
5186 
5187 	__free_extent_buffer(eb);
5188 }
5189 
release_extent_buffer(struct extent_buffer * eb)5190 static int release_extent_buffer(struct extent_buffer *eb)
5191 {
5192 	lockdep_assert_held(&eb->refs_lock);
5193 
5194 	WARN_ON(atomic_read(&eb->refs) == 0);
5195 	if (atomic_dec_and_test(&eb->refs)) {
5196 		if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
5197 			struct btrfs_fs_info *fs_info = eb->fs_info;
5198 
5199 			spin_unlock(&eb->refs_lock);
5200 
5201 			spin_lock(&fs_info->buffer_lock);
5202 			radix_tree_delete(&fs_info->buffer_radix,
5203 					  eb->start >> PAGE_SHIFT);
5204 			spin_unlock(&fs_info->buffer_lock);
5205 		} else {
5206 			spin_unlock(&eb->refs_lock);
5207 		}
5208 
5209 		/* Should be safe to release our pages at this point */
5210 		btrfs_release_extent_buffer_pages(eb);
5211 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5212 		if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
5213 			__free_extent_buffer(eb);
5214 			return 1;
5215 		}
5216 #endif
5217 		call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
5218 		return 1;
5219 	}
5220 	spin_unlock(&eb->refs_lock);
5221 
5222 	return 0;
5223 }
5224 
free_extent_buffer(struct extent_buffer * eb)5225 void free_extent_buffer(struct extent_buffer *eb)
5226 {
5227 	int refs;
5228 	int old;
5229 	if (!eb)
5230 		return;
5231 
5232 	while (1) {
5233 		refs = atomic_read(&eb->refs);
5234 		if (refs <= 3)
5235 			break;
5236 		old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
5237 		if (old == refs)
5238 			return;
5239 	}
5240 
5241 	spin_lock(&eb->refs_lock);
5242 	if (atomic_read(&eb->refs) == 2 &&
5243 	    test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))
5244 		atomic_dec(&eb->refs);
5245 
5246 	if (atomic_read(&eb->refs) == 2 &&
5247 	    test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
5248 	    !extent_buffer_under_io(eb) &&
5249 	    test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5250 		atomic_dec(&eb->refs);
5251 
5252 	/*
5253 	 * I know this is terrible, but it's temporary until we stop tracking
5254 	 * the uptodate bits and such for the extent buffers.
5255 	 */
5256 	release_extent_buffer(eb);
5257 }
5258 
free_extent_buffer_stale(struct extent_buffer * eb)5259 void free_extent_buffer_stale(struct extent_buffer *eb)
5260 {
5261 	if (!eb)
5262 		return;
5263 
5264 	spin_lock(&eb->refs_lock);
5265 	set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
5266 
5267 	if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
5268 	    test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5269 		atomic_dec(&eb->refs);
5270 	release_extent_buffer(eb);
5271 }
5272 
clear_extent_buffer_dirty(struct extent_buffer * eb)5273 void clear_extent_buffer_dirty(struct extent_buffer *eb)
5274 {
5275 	int i;
5276 	int num_pages;
5277 	struct page *page;
5278 
5279 	num_pages = num_extent_pages(eb);
5280 
5281 	for (i = 0; i < num_pages; i++) {
5282 		page = eb->pages[i];
5283 		if (!PageDirty(page))
5284 			continue;
5285 
5286 		lock_page(page);
5287 		WARN_ON(!PagePrivate(page));
5288 
5289 		clear_page_dirty_for_io(page);
5290 		xa_lock_irq(&page->mapping->i_pages);
5291 		if (!PageDirty(page)) {
5292 			radix_tree_tag_clear(&page->mapping->i_pages,
5293 						page_index(page),
5294 						PAGECACHE_TAG_DIRTY);
5295 		}
5296 		xa_unlock_irq(&page->mapping->i_pages);
5297 		ClearPageError(page);
5298 		unlock_page(page);
5299 	}
5300 	WARN_ON(atomic_read(&eb->refs) == 0);
5301 }
5302 
set_extent_buffer_dirty(struct extent_buffer * eb)5303 int set_extent_buffer_dirty(struct extent_buffer *eb)
5304 {
5305 	int i;
5306 	int num_pages;
5307 	int was_dirty = 0;
5308 
5309 	check_buffer_tree_ref(eb);
5310 
5311 	was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
5312 
5313 	num_pages = num_extent_pages(eb);
5314 	WARN_ON(atomic_read(&eb->refs) == 0);
5315 	WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
5316 
5317 	for (i = 0; i < num_pages; i++)
5318 		set_page_dirty(eb->pages[i]);
5319 	return was_dirty;
5320 }
5321 
clear_extent_buffer_uptodate(struct extent_buffer * eb)5322 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
5323 {
5324 	int i;
5325 	struct page *page;
5326 	int num_pages;
5327 
5328 	clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5329 	num_pages = num_extent_pages(eb);
5330 	for (i = 0; i < num_pages; i++) {
5331 		page = eb->pages[i];
5332 		if (page)
5333 			ClearPageUptodate(page);
5334 	}
5335 }
5336 
set_extent_buffer_uptodate(struct extent_buffer * eb)5337 void set_extent_buffer_uptodate(struct extent_buffer *eb)
5338 {
5339 	int i;
5340 	struct page *page;
5341 	int num_pages;
5342 
5343 	set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5344 	num_pages = num_extent_pages(eb);
5345 	for (i = 0; i < num_pages; i++) {
5346 		page = eb->pages[i];
5347 		SetPageUptodate(page);
5348 	}
5349 }
5350 
read_extent_buffer_pages(struct extent_io_tree * tree,struct extent_buffer * eb,int wait,int mirror_num)5351 int read_extent_buffer_pages(struct extent_io_tree *tree,
5352 			     struct extent_buffer *eb, int wait, int mirror_num)
5353 {
5354 	int i;
5355 	struct page *page;
5356 	int err;
5357 	int ret = 0;
5358 	int locked_pages = 0;
5359 	int all_uptodate = 1;
5360 	int num_pages;
5361 	unsigned long num_reads = 0;
5362 	struct bio *bio = NULL;
5363 	unsigned long bio_flags = 0;
5364 
5365 	if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5366 		return 0;
5367 
5368 	num_pages = num_extent_pages(eb);
5369 	for (i = 0; i < num_pages; i++) {
5370 		page = eb->pages[i];
5371 		if (wait == WAIT_NONE) {
5372 			if (!trylock_page(page))
5373 				goto unlock_exit;
5374 		} else {
5375 			lock_page(page);
5376 		}
5377 		locked_pages++;
5378 	}
5379 	/*
5380 	 * We need to firstly lock all pages to make sure that
5381 	 * the uptodate bit of our pages won't be affected by
5382 	 * clear_extent_buffer_uptodate().
5383 	 */
5384 	for (i = 0; i < num_pages; i++) {
5385 		page = eb->pages[i];
5386 		if (!PageUptodate(page)) {
5387 			num_reads++;
5388 			all_uptodate = 0;
5389 		}
5390 	}
5391 
5392 	if (all_uptodate) {
5393 		set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5394 		goto unlock_exit;
5395 	}
5396 
5397 	clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5398 	eb->read_mirror = 0;
5399 	atomic_set(&eb->io_pages, num_reads);
5400 	/*
5401 	 * It is possible for releasepage to clear the TREE_REF bit before we
5402 	 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
5403 	 */
5404 	check_buffer_tree_ref(eb);
5405 	for (i = 0; i < num_pages; i++) {
5406 		page = eb->pages[i];
5407 
5408 		if (!PageUptodate(page)) {
5409 			if (ret) {
5410 				atomic_dec(&eb->io_pages);
5411 				unlock_page(page);
5412 				continue;
5413 			}
5414 
5415 			ClearPageError(page);
5416 			err = __extent_read_full_page(tree, page,
5417 						      btree_get_extent, &bio,
5418 						      mirror_num, &bio_flags,
5419 						      REQ_META);
5420 			if (err) {
5421 				ret = err;
5422 				/*
5423 				 * We use &bio in above __extent_read_full_page,
5424 				 * so we ensure that if it returns error, the
5425 				 * current page fails to add itself to bio and
5426 				 * it's been unlocked.
5427 				 *
5428 				 * We must dec io_pages by ourselves.
5429 				 */
5430 				atomic_dec(&eb->io_pages);
5431 			}
5432 		} else {
5433 			unlock_page(page);
5434 		}
5435 	}
5436 
5437 	if (bio) {
5438 		err = submit_one_bio(bio, mirror_num, bio_flags);
5439 		if (err)
5440 			return err;
5441 	}
5442 
5443 	if (ret || wait != WAIT_COMPLETE)
5444 		return ret;
5445 
5446 	for (i = 0; i < num_pages; i++) {
5447 		page = eb->pages[i];
5448 		wait_on_page_locked(page);
5449 		if (!PageUptodate(page))
5450 			ret = -EIO;
5451 	}
5452 
5453 	return ret;
5454 
5455 unlock_exit:
5456 	while (locked_pages > 0) {
5457 		locked_pages--;
5458 		page = eb->pages[locked_pages];
5459 		unlock_page(page);
5460 	}
5461 	return ret;
5462 }
5463 
read_extent_buffer(const struct extent_buffer * eb,void * dstv,unsigned long start,unsigned long len)5464 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
5465 			unsigned long start, unsigned long len)
5466 {
5467 	size_t cur;
5468 	size_t offset;
5469 	struct page *page;
5470 	char *kaddr;
5471 	char *dst = (char *)dstv;
5472 	size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5473 	unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5474 
5475 	if (start + len > eb->len) {
5476 		WARN(1, KERN_ERR "btrfs bad mapping eb start %llu len %lu, wanted %lu %lu\n",
5477 		     eb->start, eb->len, start, len);
5478 		memset(dst, 0, len);
5479 		return;
5480 	}
5481 
5482 	offset = (start_offset + start) & (PAGE_SIZE - 1);
5483 
5484 	while (len > 0) {
5485 		page = eb->pages[i];
5486 
5487 		cur = min(len, (PAGE_SIZE - offset));
5488 		kaddr = page_address(page);
5489 		memcpy(dst, kaddr + offset, cur);
5490 
5491 		dst += cur;
5492 		len -= cur;
5493 		offset = 0;
5494 		i++;
5495 	}
5496 }
5497 
read_extent_buffer_to_user_nofault(const struct extent_buffer * eb,void __user * dstv,unsigned long start,unsigned long len)5498 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
5499 				       void __user *dstv,
5500 				       unsigned long start, unsigned long len)
5501 {
5502 	size_t cur;
5503 	size_t offset;
5504 	struct page *page;
5505 	char *kaddr;
5506 	char __user *dst = (char __user *)dstv;
5507 	size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5508 	unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5509 	int ret = 0;
5510 
5511 	WARN_ON(start > eb->len);
5512 	WARN_ON(start + len > eb->start + eb->len);
5513 
5514 	offset = (start_offset + start) & (PAGE_SIZE - 1);
5515 
5516 	while (len > 0) {
5517 		page = eb->pages[i];
5518 
5519 		cur = min(len, (PAGE_SIZE - offset));
5520 		kaddr = page_address(page);
5521 		if (probe_user_write(dst, kaddr + offset, cur)) {
5522 			ret = -EFAULT;
5523 			break;
5524 		}
5525 
5526 		dst += cur;
5527 		len -= cur;
5528 		offset = 0;
5529 		i++;
5530 	}
5531 
5532 	return ret;
5533 }
5534 
5535 /*
5536  * return 0 if the item is found within a page.
5537  * return 1 if the item spans two pages.
5538  * return -EINVAL otherwise.
5539  */
map_private_extent_buffer(const struct extent_buffer * eb,unsigned long start,unsigned long min_len,char ** map,unsigned long * map_start,unsigned long * map_len)5540 int map_private_extent_buffer(const struct extent_buffer *eb,
5541 			      unsigned long start, unsigned long min_len,
5542 			      char **map, unsigned long *map_start,
5543 			      unsigned long *map_len)
5544 {
5545 	size_t offset = start & (PAGE_SIZE - 1);
5546 	char *kaddr;
5547 	struct page *p;
5548 	size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5549 	unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5550 	unsigned long end_i = (start_offset + start + min_len - 1) >>
5551 		PAGE_SHIFT;
5552 
5553 	if (start + min_len > eb->len) {
5554 		WARN(1, KERN_ERR "btrfs bad mapping eb start %llu len %lu, wanted %lu %lu\n",
5555 		       eb->start, eb->len, start, min_len);
5556 		return -EINVAL;
5557 	}
5558 
5559 	if (i != end_i)
5560 		return 1;
5561 
5562 	if (i == 0) {
5563 		offset = start_offset;
5564 		*map_start = 0;
5565 	} else {
5566 		offset = 0;
5567 		*map_start = ((u64)i << PAGE_SHIFT) - start_offset;
5568 	}
5569 
5570 	p = eb->pages[i];
5571 	kaddr = page_address(p);
5572 	*map = kaddr + offset;
5573 	*map_len = PAGE_SIZE - offset;
5574 	return 0;
5575 }
5576 
memcmp_extent_buffer(const struct extent_buffer * eb,const void * ptrv,unsigned long start,unsigned long len)5577 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
5578 			 unsigned long start, unsigned long len)
5579 {
5580 	size_t cur;
5581 	size_t offset;
5582 	struct page *page;
5583 	char *kaddr;
5584 	char *ptr = (char *)ptrv;
5585 	size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5586 	unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5587 	int ret = 0;
5588 
5589 	WARN_ON(start > eb->len);
5590 	WARN_ON(start + len > eb->start + eb->len);
5591 
5592 	offset = (start_offset + start) & (PAGE_SIZE - 1);
5593 
5594 	while (len > 0) {
5595 		page = eb->pages[i];
5596 
5597 		cur = min(len, (PAGE_SIZE - offset));
5598 
5599 		kaddr = page_address(page);
5600 		ret = memcmp(ptr, kaddr + offset, cur);
5601 		if (ret)
5602 			break;
5603 
5604 		ptr += cur;
5605 		len -= cur;
5606 		offset = 0;
5607 		i++;
5608 	}
5609 	return ret;
5610 }
5611 
write_extent_buffer_chunk_tree_uuid(struct extent_buffer * eb,const void * srcv)5612 void write_extent_buffer_chunk_tree_uuid(struct extent_buffer *eb,
5613 		const void *srcv)
5614 {
5615 	char *kaddr;
5616 
5617 	WARN_ON(!PageUptodate(eb->pages[0]));
5618 	kaddr = page_address(eb->pages[0]);
5619 	memcpy(kaddr + offsetof(struct btrfs_header, chunk_tree_uuid), srcv,
5620 			BTRFS_FSID_SIZE);
5621 }
5622 
write_extent_buffer_fsid(struct extent_buffer * eb,const void * srcv)5623 void write_extent_buffer_fsid(struct extent_buffer *eb, const void *srcv)
5624 {
5625 	char *kaddr;
5626 
5627 	WARN_ON(!PageUptodate(eb->pages[0]));
5628 	kaddr = page_address(eb->pages[0]);
5629 	memcpy(kaddr + offsetof(struct btrfs_header, fsid), srcv,
5630 			BTRFS_FSID_SIZE);
5631 }
5632 
write_extent_buffer(struct extent_buffer * eb,const void * srcv,unsigned long start,unsigned long len)5633 void write_extent_buffer(struct extent_buffer *eb, const void *srcv,
5634 			 unsigned long start, unsigned long len)
5635 {
5636 	size_t cur;
5637 	size_t offset;
5638 	struct page *page;
5639 	char *kaddr;
5640 	char *src = (char *)srcv;
5641 	size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5642 	unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5643 
5644 	WARN_ON(start > eb->len);
5645 	WARN_ON(start + len > eb->start + eb->len);
5646 
5647 	offset = (start_offset + start) & (PAGE_SIZE - 1);
5648 
5649 	while (len > 0) {
5650 		page = eb->pages[i];
5651 		WARN_ON(!PageUptodate(page));
5652 
5653 		cur = min(len, PAGE_SIZE - offset);
5654 		kaddr = page_address(page);
5655 		memcpy(kaddr + offset, src, cur);
5656 
5657 		src += cur;
5658 		len -= cur;
5659 		offset = 0;
5660 		i++;
5661 	}
5662 }
5663 
memzero_extent_buffer(struct extent_buffer * eb,unsigned long start,unsigned long len)5664 void memzero_extent_buffer(struct extent_buffer *eb, unsigned long start,
5665 		unsigned long len)
5666 {
5667 	size_t cur;
5668 	size_t offset;
5669 	struct page *page;
5670 	char *kaddr;
5671 	size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5672 	unsigned long i = (start_offset + start) >> PAGE_SHIFT;
5673 
5674 	WARN_ON(start > eb->len);
5675 	WARN_ON(start + len > eb->start + eb->len);
5676 
5677 	offset = (start_offset + start) & (PAGE_SIZE - 1);
5678 
5679 	while (len > 0) {
5680 		page = eb->pages[i];
5681 		WARN_ON(!PageUptodate(page));
5682 
5683 		cur = min(len, PAGE_SIZE - offset);
5684 		kaddr = page_address(page);
5685 		memset(kaddr + offset, 0, cur);
5686 
5687 		len -= cur;
5688 		offset = 0;
5689 		i++;
5690 	}
5691 }
5692 
copy_extent_buffer_full(struct extent_buffer * dst,struct extent_buffer * src)5693 void copy_extent_buffer_full(struct extent_buffer *dst,
5694 			     struct extent_buffer *src)
5695 {
5696 	int i;
5697 	int num_pages;
5698 
5699 	ASSERT(dst->len == src->len);
5700 
5701 	num_pages = num_extent_pages(dst);
5702 	for (i = 0; i < num_pages; i++)
5703 		copy_page(page_address(dst->pages[i]),
5704 				page_address(src->pages[i]));
5705 }
5706 
copy_extent_buffer(struct extent_buffer * dst,struct extent_buffer * src,unsigned long dst_offset,unsigned long src_offset,unsigned long len)5707 void copy_extent_buffer(struct extent_buffer *dst, struct extent_buffer *src,
5708 			unsigned long dst_offset, unsigned long src_offset,
5709 			unsigned long len)
5710 {
5711 	u64 dst_len = dst->len;
5712 	size_t cur;
5713 	size_t offset;
5714 	struct page *page;
5715 	char *kaddr;
5716 	size_t start_offset = dst->start & ((u64)PAGE_SIZE - 1);
5717 	unsigned long i = (start_offset + dst_offset) >> PAGE_SHIFT;
5718 
5719 	WARN_ON(src->len != dst_len);
5720 
5721 	offset = (start_offset + dst_offset) &
5722 		(PAGE_SIZE - 1);
5723 
5724 	while (len > 0) {
5725 		page = dst->pages[i];
5726 		WARN_ON(!PageUptodate(page));
5727 
5728 		cur = min(len, (unsigned long)(PAGE_SIZE - offset));
5729 
5730 		kaddr = page_address(page);
5731 		read_extent_buffer(src, kaddr + offset, src_offset, cur);
5732 
5733 		src_offset += cur;
5734 		len -= cur;
5735 		offset = 0;
5736 		i++;
5737 	}
5738 }
5739 
5740 /*
5741  * eb_bitmap_offset() - calculate the page and offset of the byte containing the
5742  * given bit number
5743  * @eb: the extent buffer
5744  * @start: offset of the bitmap item in the extent buffer
5745  * @nr: bit number
5746  * @page_index: return index of the page in the extent buffer that contains the
5747  * given bit number
5748  * @page_offset: return offset into the page given by page_index
5749  *
5750  * This helper hides the ugliness of finding the byte in an extent buffer which
5751  * contains a given bit.
5752  */
eb_bitmap_offset(struct extent_buffer * eb,unsigned long start,unsigned long nr,unsigned long * page_index,size_t * page_offset)5753 static inline void eb_bitmap_offset(struct extent_buffer *eb,
5754 				    unsigned long start, unsigned long nr,
5755 				    unsigned long *page_index,
5756 				    size_t *page_offset)
5757 {
5758 	size_t start_offset = eb->start & ((u64)PAGE_SIZE - 1);
5759 	size_t byte_offset = BIT_BYTE(nr);
5760 	size_t offset;
5761 
5762 	/*
5763 	 * The byte we want is the offset of the extent buffer + the offset of
5764 	 * the bitmap item in the extent buffer + the offset of the byte in the
5765 	 * bitmap item.
5766 	 */
5767 	offset = start_offset + start + byte_offset;
5768 
5769 	*page_index = offset >> PAGE_SHIFT;
5770 	*page_offset = offset & (PAGE_SIZE - 1);
5771 }
5772 
5773 /**
5774  * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
5775  * @eb: the extent buffer
5776  * @start: offset of the bitmap item in the extent buffer
5777  * @nr: bit number to test
5778  */
extent_buffer_test_bit(struct extent_buffer * eb,unsigned long start,unsigned long nr)5779 int extent_buffer_test_bit(struct extent_buffer *eb, unsigned long start,
5780 			   unsigned long nr)
5781 {
5782 	u8 *kaddr;
5783 	struct page *page;
5784 	unsigned long i;
5785 	size_t offset;
5786 
5787 	eb_bitmap_offset(eb, start, nr, &i, &offset);
5788 	page = eb->pages[i];
5789 	WARN_ON(!PageUptodate(page));
5790 	kaddr = page_address(page);
5791 	return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
5792 }
5793 
5794 /**
5795  * extent_buffer_bitmap_set - set an area of a bitmap
5796  * @eb: the extent buffer
5797  * @start: offset of the bitmap item in the extent buffer
5798  * @pos: bit number of the first bit
5799  * @len: number of bits to set
5800  */
extent_buffer_bitmap_set(struct extent_buffer * eb,unsigned long start,unsigned long pos,unsigned long len)5801 void extent_buffer_bitmap_set(struct extent_buffer *eb, unsigned long start,
5802 			      unsigned long pos, unsigned long len)
5803 {
5804 	u8 *kaddr;
5805 	struct page *page;
5806 	unsigned long i;
5807 	size_t offset;
5808 	const unsigned int size = pos + len;
5809 	int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5810 	u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
5811 
5812 	eb_bitmap_offset(eb, start, pos, &i, &offset);
5813 	page = eb->pages[i];
5814 	WARN_ON(!PageUptodate(page));
5815 	kaddr = page_address(page);
5816 
5817 	while (len >= bits_to_set) {
5818 		kaddr[offset] |= mask_to_set;
5819 		len -= bits_to_set;
5820 		bits_to_set = BITS_PER_BYTE;
5821 		mask_to_set = ~0;
5822 		if (++offset >= PAGE_SIZE && len > 0) {
5823 			offset = 0;
5824 			page = eb->pages[++i];
5825 			WARN_ON(!PageUptodate(page));
5826 			kaddr = page_address(page);
5827 		}
5828 	}
5829 	if (len) {
5830 		mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
5831 		kaddr[offset] |= mask_to_set;
5832 	}
5833 }
5834 
5835 
5836 /**
5837  * extent_buffer_bitmap_clear - clear an area of a bitmap
5838  * @eb: the extent buffer
5839  * @start: offset of the bitmap item in the extent buffer
5840  * @pos: bit number of the first bit
5841  * @len: number of bits to clear
5842  */
extent_buffer_bitmap_clear(struct extent_buffer * eb,unsigned long start,unsigned long pos,unsigned long len)5843 void extent_buffer_bitmap_clear(struct extent_buffer *eb, unsigned long start,
5844 				unsigned long pos, unsigned long len)
5845 {
5846 	u8 *kaddr;
5847 	struct page *page;
5848 	unsigned long i;
5849 	size_t offset;
5850 	const unsigned int size = pos + len;
5851 	int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5852 	u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
5853 
5854 	eb_bitmap_offset(eb, start, pos, &i, &offset);
5855 	page = eb->pages[i];
5856 	WARN_ON(!PageUptodate(page));
5857 	kaddr = page_address(page);
5858 
5859 	while (len >= bits_to_clear) {
5860 		kaddr[offset] &= ~mask_to_clear;
5861 		len -= bits_to_clear;
5862 		bits_to_clear = BITS_PER_BYTE;
5863 		mask_to_clear = ~0;
5864 		if (++offset >= PAGE_SIZE && len > 0) {
5865 			offset = 0;
5866 			page = eb->pages[++i];
5867 			WARN_ON(!PageUptodate(page));
5868 			kaddr = page_address(page);
5869 		}
5870 	}
5871 	if (len) {
5872 		mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
5873 		kaddr[offset] &= ~mask_to_clear;
5874 	}
5875 }
5876 
areas_overlap(unsigned long src,unsigned long dst,unsigned long len)5877 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
5878 {
5879 	unsigned long distance = (src > dst) ? src - dst : dst - src;
5880 	return distance < len;
5881 }
5882 
copy_pages(struct page * dst_page,struct page * src_page,unsigned long dst_off,unsigned long src_off,unsigned long len)5883 static void copy_pages(struct page *dst_page, struct page *src_page,
5884 		       unsigned long dst_off, unsigned long src_off,
5885 		       unsigned long len)
5886 {
5887 	char *dst_kaddr = page_address(dst_page);
5888 	char *src_kaddr;
5889 	int must_memmove = 0;
5890 
5891 	if (dst_page != src_page) {
5892 		src_kaddr = page_address(src_page);
5893 	} else {
5894 		src_kaddr = dst_kaddr;
5895 		if (areas_overlap(src_off, dst_off, len))
5896 			must_memmove = 1;
5897 	}
5898 
5899 	if (must_memmove)
5900 		memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
5901 	else
5902 		memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
5903 }
5904 
memcpy_extent_buffer(struct extent_buffer * dst,unsigned long dst_offset,unsigned long src_offset,unsigned long len)5905 void memcpy_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
5906 			   unsigned long src_offset, unsigned long len)
5907 {
5908 	struct btrfs_fs_info *fs_info = dst->fs_info;
5909 	size_t cur;
5910 	size_t dst_off_in_page;
5911 	size_t src_off_in_page;
5912 	size_t start_offset = dst->start & ((u64)PAGE_SIZE - 1);
5913 	unsigned long dst_i;
5914 	unsigned long src_i;
5915 
5916 	if (src_offset + len > dst->len) {
5917 		btrfs_err(fs_info,
5918 			"memmove bogus src_offset %lu move len %lu dst len %lu",
5919 			 src_offset, len, dst->len);
5920 		BUG_ON(1);
5921 	}
5922 	if (dst_offset + len > dst->len) {
5923 		btrfs_err(fs_info,
5924 			"memmove bogus dst_offset %lu move len %lu dst len %lu",
5925 			 dst_offset, len, dst->len);
5926 		BUG_ON(1);
5927 	}
5928 
5929 	while (len > 0) {
5930 		dst_off_in_page = (start_offset + dst_offset) &
5931 			(PAGE_SIZE - 1);
5932 		src_off_in_page = (start_offset + src_offset) &
5933 			(PAGE_SIZE - 1);
5934 
5935 		dst_i = (start_offset + dst_offset) >> PAGE_SHIFT;
5936 		src_i = (start_offset + src_offset) >> PAGE_SHIFT;
5937 
5938 		cur = min(len, (unsigned long)(PAGE_SIZE -
5939 					       src_off_in_page));
5940 		cur = min_t(unsigned long, cur,
5941 			(unsigned long)(PAGE_SIZE - dst_off_in_page));
5942 
5943 		copy_pages(dst->pages[dst_i], dst->pages[src_i],
5944 			   dst_off_in_page, src_off_in_page, cur);
5945 
5946 		src_offset += cur;
5947 		dst_offset += cur;
5948 		len -= cur;
5949 	}
5950 }
5951 
memmove_extent_buffer(struct extent_buffer * dst,unsigned long dst_offset,unsigned long src_offset,unsigned long len)5952 void memmove_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
5953 			   unsigned long src_offset, unsigned long len)
5954 {
5955 	struct btrfs_fs_info *fs_info = dst->fs_info;
5956 	size_t cur;
5957 	size_t dst_off_in_page;
5958 	size_t src_off_in_page;
5959 	unsigned long dst_end = dst_offset + len - 1;
5960 	unsigned long src_end = src_offset + len - 1;
5961 	size_t start_offset = dst->start & ((u64)PAGE_SIZE - 1);
5962 	unsigned long dst_i;
5963 	unsigned long src_i;
5964 
5965 	if (src_offset + len > dst->len) {
5966 		btrfs_err(fs_info,
5967 			  "memmove bogus src_offset %lu move len %lu len %lu",
5968 			  src_offset, len, dst->len);
5969 		BUG_ON(1);
5970 	}
5971 	if (dst_offset + len > dst->len) {
5972 		btrfs_err(fs_info,
5973 			  "memmove bogus dst_offset %lu move len %lu len %lu",
5974 			  dst_offset, len, dst->len);
5975 		BUG_ON(1);
5976 	}
5977 	if (dst_offset < src_offset) {
5978 		memcpy_extent_buffer(dst, dst_offset, src_offset, len);
5979 		return;
5980 	}
5981 	while (len > 0) {
5982 		dst_i = (start_offset + dst_end) >> PAGE_SHIFT;
5983 		src_i = (start_offset + src_end) >> PAGE_SHIFT;
5984 
5985 		dst_off_in_page = (start_offset + dst_end) &
5986 			(PAGE_SIZE - 1);
5987 		src_off_in_page = (start_offset + src_end) &
5988 			(PAGE_SIZE - 1);
5989 
5990 		cur = min_t(unsigned long, len, src_off_in_page + 1);
5991 		cur = min(cur, dst_off_in_page + 1);
5992 		copy_pages(dst->pages[dst_i], dst->pages[src_i],
5993 			   dst_off_in_page - cur + 1,
5994 			   src_off_in_page - cur + 1, cur);
5995 
5996 		dst_end -= cur;
5997 		src_end -= cur;
5998 		len -= cur;
5999 	}
6000 }
6001 
try_release_extent_buffer(struct page * page)6002 int try_release_extent_buffer(struct page *page)
6003 {
6004 	struct extent_buffer *eb;
6005 
6006 	/*
6007 	 * We need to make sure nobody is attaching this page to an eb right
6008 	 * now.
6009 	 */
6010 	spin_lock(&page->mapping->private_lock);
6011 	if (!PagePrivate(page)) {
6012 		spin_unlock(&page->mapping->private_lock);
6013 		return 1;
6014 	}
6015 
6016 	eb = (struct extent_buffer *)page->private;
6017 	BUG_ON(!eb);
6018 
6019 	/*
6020 	 * This is a little awful but should be ok, we need to make sure that
6021 	 * the eb doesn't disappear out from under us while we're looking at
6022 	 * this page.
6023 	 */
6024 	spin_lock(&eb->refs_lock);
6025 	if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
6026 		spin_unlock(&eb->refs_lock);
6027 		spin_unlock(&page->mapping->private_lock);
6028 		return 0;
6029 	}
6030 	spin_unlock(&page->mapping->private_lock);
6031 
6032 	/*
6033 	 * If tree ref isn't set then we know the ref on this eb is a real ref,
6034 	 * so just return, this page will likely be freed soon anyway.
6035 	 */
6036 	if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6037 		spin_unlock(&eb->refs_lock);
6038 		return 0;
6039 	}
6040 
6041 	return release_extent_buffer(eb);
6042 }
6043