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