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