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