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