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