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