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