btrfs: add and use readahead_batch_length
[linux-2.6-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
5a2c6075 4015static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
656f30db 4016{
5a2c6075 4017 struct btrfs_fs_info *fs_info = eb->fs_info;
656f30db 4018
5a2c6075 4019 btrfs_page_set_error(fs_info, page, eb->start, eb->len);
656f30db
FM
4020 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
4021 return;
4022
eb5b64f1
DZ
4023 /*
4024 * If we error out, we should add back the dirty_metadata_bytes
4025 * to make it consistent.
4026 */
eb5b64f1
DZ
4027 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4028 eb->len, fs_info->dirty_metadata_batch);
4029
656f30db
FM
4030 /*
4031 * If writeback for a btree extent that doesn't belong to a log tree
4032 * failed, increment the counter transaction->eb_write_errors.
4033 * We do this because while the transaction is running and before it's
4034 * committing (when we call filemap_fdata[write|wait]_range against
4035 * the btree inode), we might have
4036 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
4037 * returns an error or an error happens during writeback, when we're
4038 * committing the transaction we wouldn't know about it, since the pages
4039 * can be no longer dirty nor marked anymore for writeback (if a
4040 * subsequent modification to the extent buffer didn't happen before the
4041 * transaction commit), which makes filemap_fdata[write|wait]_range not
4042 * able to find the pages tagged with SetPageError at transaction
4043 * commit time. So if this happens we must abort the transaction,
4044 * otherwise we commit a super block with btree roots that point to
4045 * btree nodes/leafs whose content on disk is invalid - either garbage
4046 * or the content of some node/leaf from a past generation that got
4047 * cowed or deleted and is no longer valid.
4048 *
4049 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
4050 * not be enough - we need to distinguish between log tree extents vs
4051 * non-log tree extents, and the next filemap_fdatawait_range() call
4052 * will catch and clear such errors in the mapping - and that call might
4053 * be from a log sync and not from a transaction commit. Also, checking
4054 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
4055 * not done and would not be reliable - the eb might have been released
4056 * from memory and reading it back again means that flag would not be
4057 * set (since it's a runtime flag, not persisted on disk).
4058 *
4059 * Using the flags below in the btree inode also makes us achieve the
4060 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
4061 * writeback for all dirty pages and before filemap_fdatawait_range()
4062 * is called, the writeback for all dirty pages had already finished
4063 * with errors - because we were not using AS_EIO/AS_ENOSPC,
4064 * filemap_fdatawait_range() would return success, as it could not know
4065 * that writeback errors happened (the pages were no longer tagged for
4066 * writeback).
4067 */
4068 switch (eb->log_index) {
4069 case -1:
5a2c6075 4070 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
656f30db
FM
4071 break;
4072 case 0:
5a2c6075 4073 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
656f30db
FM
4074 break;
4075 case 1:
5a2c6075 4076 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
656f30db
FM
4077 break;
4078 default:
4079 BUG(); /* unexpected, logic error */
4080 }
4081}
4082
4246a0b6 4083static void end_bio_extent_buffer_writepage(struct bio *bio)
0b32f4bb 4084{
2c30c71b 4085 struct bio_vec *bvec;
0b32f4bb 4086 struct extent_buffer *eb;
2b070cfe 4087 int done;
6dc4f100 4088 struct bvec_iter_all iter_all;
0b32f4bb 4089
c09abff8 4090 ASSERT(!bio_flagged(bio, BIO_CLONED));
2b070cfe 4091 bio_for_each_segment_all(bvec, bio, iter_all) {
0b32f4bb
JB
4092 struct page *page = bvec->bv_page;
4093
0b32f4bb
JB
4094 eb = (struct extent_buffer *)page->private;
4095 BUG_ON(!eb);
4096 done = atomic_dec_and_test(&eb->io_pages);
4097
4e4cbee9 4098 if (bio->bi_status ||
4246a0b6 4099 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
0b32f4bb 4100 ClearPageUptodate(page);
5a2c6075 4101 set_btree_ioerr(page, eb);
0b32f4bb
JB
4102 }
4103
4104 end_page_writeback(page);
4105
4106 if (!done)
4107 continue;
4108
4109 end_extent_buffer_writeback(eb);
2c30c71b 4110 }
0b32f4bb
JB
4111
4112 bio_put(bio);
0b32f4bb
JB
4113}
4114
0e378df1 4115static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
0b32f4bb
JB
4116 struct writeback_control *wbc,
4117 struct extent_page_data *epd)
4118{
0c64c33c 4119 u64 disk_bytenr = eb->start;
851cd173 4120 u32 nritems;
cc5e31a4 4121 int i, num_pages;
851cd173 4122 unsigned long start, end;
ff40adf7 4123 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
d7dbe9e7 4124 int ret = 0;
0b32f4bb 4125
656f30db 4126 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
65ad0104 4127 num_pages = num_extent_pages(eb);
0b32f4bb 4128 atomic_set(&eb->io_pages, num_pages);
de0022b9 4129
851cd173
LB
4130 /* set btree blocks beyond nritems with 0 to avoid stale content. */
4131 nritems = btrfs_header_nritems(eb);
3eb548ee 4132 if (btrfs_header_level(eb) > 0) {
3eb548ee
LB
4133 end = btrfs_node_key_ptr_offset(nritems);
4134
b159fa28 4135 memzero_extent_buffer(eb, end, eb->len - end);
851cd173
LB
4136 } else {
4137 /*
4138 * leaf:
4139 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
4140 */
4141 start = btrfs_item_nr_offset(nritems);
8f881e8c 4142 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
b159fa28 4143 memzero_extent_buffer(eb, start, end - start);
3eb548ee
LB
4144 }
4145
0b32f4bb 4146 for (i = 0; i < num_pages; i++) {
fb85fc9a 4147 struct page *p = eb->pages[i];
0b32f4bb
JB
4148
4149 clear_page_dirty_for_io(p);
4150 set_page_writeback(p);
0ceb34bf 4151 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
0c64c33c 4152 p, disk_bytenr, PAGE_SIZE, 0,
c2df8bb4 4153 &epd->bio,
1f7ad75b 4154 end_bio_extent_buffer_writepage,
18fdc679 4155 0, 0, 0, false);
0b32f4bb 4156 if (ret) {
5a2c6075 4157 set_btree_ioerr(p, eb);
fe01aa65
TK
4158 if (PageWriteback(p))
4159 end_page_writeback(p);
0b32f4bb
JB
4160 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
4161 end_extent_buffer_writeback(eb);
4162 ret = -EIO;
4163 break;
4164 }
0c64c33c 4165 disk_bytenr += PAGE_SIZE;
3d4b9496 4166 update_nr_written(wbc, 1);
0b32f4bb
JB
4167 unlock_page(p);
4168 }
4169
4170 if (unlikely(ret)) {
4171 for (; i < num_pages; i++) {
bbf65cf0 4172 struct page *p = eb->pages[i];
81465028 4173 clear_page_dirty_for_io(p);
0b32f4bb
JB
4174 unlock_page(p);
4175 }
4176 }
4177
4178 return ret;
4179}
4180
f91e0d0c
QW
4181/*
4182 * Submit all page(s) of one extent buffer.
4183 *
4184 * @page: the page of one extent buffer
4185 * @eb_context: to determine if we need to submit this page, if current page
4186 * belongs to this eb, we don't need to submit
4187 *
4188 * The caller should pass each page in their bytenr order, and here we use
4189 * @eb_context to determine if we have submitted pages of one extent buffer.
4190 *
4191 * If we have, we just skip until we hit a new page that doesn't belong to
4192 * current @eb_context.
4193 *
4194 * If not, we submit all the page(s) of the extent buffer.
4195 *
4196 * Return >0 if we have submitted the extent buffer successfully.
4197 * Return 0 if we don't need to submit the page, as it's already submitted by
4198 * previous call.
4199 * Return <0 for fatal error.
4200 */
4201static int submit_eb_page(struct page *page, struct writeback_control *wbc,
4202 struct extent_page_data *epd,
4203 struct extent_buffer **eb_context)
4204{
4205 struct address_space *mapping = page->mapping;
0bc09ca1 4206 struct btrfs_block_group *cache = NULL;
f91e0d0c
QW
4207 struct extent_buffer *eb;
4208 int ret;
4209
4210 if (!PagePrivate(page))
4211 return 0;
4212
4213 spin_lock(&mapping->private_lock);
4214 if (!PagePrivate(page)) {
4215 spin_unlock(&mapping->private_lock);
4216 return 0;
4217 }
4218
4219 eb = (struct extent_buffer *)page->private;
4220
4221 /*
4222 * Shouldn't happen and normally this would be a BUG_ON but no point
4223 * crashing the machine for something we can survive anyway.
4224 */
4225 if (WARN_ON(!eb)) {
4226 spin_unlock(&mapping->private_lock);
4227 return 0;
4228 }
4229
4230 if (eb == *eb_context) {
4231 spin_unlock(&mapping->private_lock);
4232 return 0;
4233 }
4234 ret = atomic_inc_not_zero(&eb->refs);
4235 spin_unlock(&mapping->private_lock);
4236 if (!ret)
4237 return 0;
4238
0bc09ca1
NA
4239 if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
4240 /*
4241 * If for_sync, this hole will be filled with
4242 * trasnsaction commit.
4243 */
4244 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4245 ret = -EAGAIN;
4246 else
4247 ret = 0;
4248 free_extent_buffer(eb);
4249 return ret;
4250 }
4251
f91e0d0c
QW
4252 *eb_context = eb;
4253
4254 ret = lock_extent_buffer_for_io(eb, epd);
4255 if (ret <= 0) {
0bc09ca1
NA
4256 btrfs_revert_meta_write_pointer(cache, eb);
4257 if (cache)
4258 btrfs_put_block_group(cache);
f91e0d0c
QW
4259 free_extent_buffer(eb);
4260 return ret;
4261 }
0bc09ca1
NA
4262 if (cache)
4263 btrfs_put_block_group(cache);
f91e0d0c
QW
4264 ret = write_one_eb(eb, wbc, epd);
4265 free_extent_buffer(eb);
4266 if (ret < 0)
4267 return ret;
4268 return 1;
4269}
4270
0b32f4bb
JB
4271int btree_write_cache_pages(struct address_space *mapping,
4272 struct writeback_control *wbc)
4273{
f91e0d0c 4274 struct extent_buffer *eb_context = NULL;
0b32f4bb
JB
4275 struct extent_page_data epd = {
4276 .bio = NULL,
0b32f4bb
JB
4277 .extent_locked = 0,
4278 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4279 };
b3ff8f1d 4280 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
0b32f4bb
JB
4281 int ret = 0;
4282 int done = 0;
4283 int nr_to_write_done = 0;
4284 struct pagevec pvec;
4285 int nr_pages;
4286 pgoff_t index;
4287 pgoff_t end; /* Inclusive */
4288 int scanned = 0;
10bbd235 4289 xa_mark_t tag;
0b32f4bb 4290
86679820 4291 pagevec_init(&pvec);
0b32f4bb
JB
4292 if (wbc->range_cyclic) {
4293 index = mapping->writeback_index; /* Start from prev offset */
4294 end = -1;
556755a8
JB
4295 /*
4296 * Start from the beginning does not need to cycle over the
4297 * range, mark it as scanned.
4298 */
4299 scanned = (index == 0);
0b32f4bb 4300 } else {
09cbfeaf
KS
4301 index = wbc->range_start >> PAGE_SHIFT;
4302 end = wbc->range_end >> PAGE_SHIFT;
0b32f4bb
JB
4303 scanned = 1;
4304 }
4305 if (wbc->sync_mode == WB_SYNC_ALL)
4306 tag = PAGECACHE_TAG_TOWRITE;
4307 else
4308 tag = PAGECACHE_TAG_DIRTY;
0bc09ca1 4309 btrfs_zoned_meta_io_lock(fs_info);
0b32f4bb
JB
4310retry:
4311 if (wbc->sync_mode == WB_SYNC_ALL)
4312 tag_pages_for_writeback(mapping, index, end);
4313 while (!done && !nr_to_write_done && (index <= end) &&
4006f437 4314 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
67fd707f 4315 tag))) {
0b32f4bb
JB
4316 unsigned i;
4317
0b32f4bb
JB
4318 for (i = 0; i < nr_pages; i++) {
4319 struct page *page = pvec.pages[i];
4320
f91e0d0c
QW
4321 ret = submit_eb_page(page, wbc, &epd, &eb_context);
4322 if (ret == 0)
0b32f4bb 4323 continue;
f91e0d0c 4324 if (ret < 0) {
0b32f4bb 4325 done = 1;
0b32f4bb
JB
4326 break;
4327 }
0b32f4bb
JB
4328
4329 /*
4330 * the filesystem may choose to bump up nr_to_write.
4331 * We have to make sure to honor the new nr_to_write
4332 * at any time
4333 */
4334 nr_to_write_done = wbc->nr_to_write <= 0;
4335 }
4336 pagevec_release(&pvec);
4337 cond_resched();
4338 }
4339 if (!scanned && !done) {
4340 /*
4341 * We hit the last page and there is more work to be done: wrap
4342 * back to the start of the file
4343 */
4344 scanned = 1;
4345 index = 0;
4346 goto retry;
4347 }
2b952eea
QW
4348 if (ret < 0) {
4349 end_write_bio(&epd, ret);
0bc09ca1 4350 goto out;
2b952eea 4351 }
b3ff8f1d
QW
4352 /*
4353 * If something went wrong, don't allow any metadata write bio to be
4354 * submitted.
4355 *
4356 * This would prevent use-after-free if we had dirty pages not
4357 * cleaned up, which can still happen by fuzzed images.
4358 *
4359 * - Bad extent tree
4360 * Allowing existing tree block to be allocated for other trees.
4361 *
4362 * - Log tree operations
4363 * Exiting tree blocks get allocated to log tree, bumps its
4364 * generation, then get cleaned in tree re-balance.
4365 * Such tree block will not be written back, since it's clean,
4366 * thus no WRITTEN flag set.
4367 * And after log writes back, this tree block is not traced by
4368 * any dirty extent_io_tree.
4369 *
4370 * - Offending tree block gets re-dirtied from its original owner
4371 * Since it has bumped generation, no WRITTEN flag, it can be
4372 * reused without COWing. This tree block will not be traced
4373 * by btrfs_transaction::dirty_pages.
4374 *
4375 * Now such dirty tree block will not be cleaned by any dirty
4376 * extent io tree. Thus we don't want to submit such wild eb
4377 * if the fs already has error.
4378 */
4379 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
4380 ret = flush_write_bio(&epd);
4381 } else {
fbabd4a3 4382 ret = -EROFS;
b3ff8f1d
QW
4383 end_write_bio(&epd, ret);
4384 }
0bc09ca1
NA
4385out:
4386 btrfs_zoned_meta_io_unlock(fs_info);
0b32f4bb
JB
4387 return ret;
4388}
4389
d1310b2e 4390/**
3bed2da1
NB
4391 * Walk the list of dirty pages of the given address space and write all of them.
4392 *
d1310b2e 4393 * @mapping: address space structure to write
3bed2da1
NB
4394 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4395 * @epd: holds context for the write, namely the bio
d1310b2e
CM
4396 *
4397 * If a page is already under I/O, write_cache_pages() skips it, even
4398 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4399 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4400 * and msync() need to guarantee that all the data which was dirty at the time
4401 * the call was made get new I/O started against them. If wbc->sync_mode is
4402 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4403 * existing IO to complete.
4404 */
4242b64a 4405static int extent_write_cache_pages(struct address_space *mapping,
4bef0848 4406 struct writeback_control *wbc,
aab6e9ed 4407 struct extent_page_data *epd)
d1310b2e 4408{
7fd1a3f7 4409 struct inode *inode = mapping->host;
d1310b2e
CM
4410 int ret = 0;
4411 int done = 0;
f85d7d6c 4412 int nr_to_write_done = 0;
d1310b2e
CM
4413 struct pagevec pvec;
4414 int nr_pages;
4415 pgoff_t index;
4416 pgoff_t end; /* Inclusive */
a9132667
LB
4417 pgoff_t done_index;
4418 int range_whole = 0;
d1310b2e 4419 int scanned = 0;
10bbd235 4420 xa_mark_t tag;
d1310b2e 4421
7fd1a3f7
JB
4422 /*
4423 * We have to hold onto the inode so that ordered extents can do their
4424 * work when the IO finishes. The alternative to this is failing to add
4425 * an ordered extent if the igrab() fails there and that is a huge pain
4426 * to deal with, so instead just hold onto the inode throughout the
4427 * writepages operation. If it fails here we are freeing up the inode
4428 * anyway and we'd rather not waste our time writing out stuff that is
4429 * going to be truncated anyway.
4430 */
4431 if (!igrab(inode))
4432 return 0;
4433
86679820 4434 pagevec_init(&pvec);
d1310b2e
CM
4435 if (wbc->range_cyclic) {
4436 index = mapping->writeback_index; /* Start from prev offset */
4437 end = -1;
556755a8
JB
4438 /*
4439 * Start from the beginning does not need to cycle over the
4440 * range, mark it as scanned.
4441 */
4442 scanned = (index == 0);
d1310b2e 4443 } else {
09cbfeaf
KS
4444 index = wbc->range_start >> PAGE_SHIFT;
4445 end = wbc->range_end >> PAGE_SHIFT;
a9132667
LB
4446 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4447 range_whole = 1;
d1310b2e
CM
4448 scanned = 1;
4449 }
3cd24c69
EL
4450
4451 /*
4452 * We do the tagged writepage as long as the snapshot flush bit is set
4453 * and we are the first one who do the filemap_flush() on this inode.
4454 *
4455 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4456 * not race in and drop the bit.
4457 */
4458 if (range_whole && wbc->nr_to_write == LONG_MAX &&
4459 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4460 &BTRFS_I(inode)->runtime_flags))
4461 wbc->tagged_writepages = 1;
4462
4463 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
f7aaa06b
JB
4464 tag = PAGECACHE_TAG_TOWRITE;
4465 else
4466 tag = PAGECACHE_TAG_DIRTY;
d1310b2e 4467retry:
3cd24c69 4468 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
f7aaa06b 4469 tag_pages_for_writeback(mapping, index, end);
a9132667 4470 done_index = index;
f85d7d6c 4471 while (!done && !nr_to_write_done && (index <= end) &&
67fd707f
JK
4472 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4473 &index, end, tag))) {
d1310b2e
CM
4474 unsigned i;
4475
d1310b2e
CM
4476 for (i = 0; i < nr_pages; i++) {
4477 struct page *page = pvec.pages[i];
4478
f7bddf1e 4479 done_index = page->index + 1;
d1310b2e 4480 /*
b93b0163
MW
4481 * At this point we hold neither the i_pages lock nor
4482 * the page lock: the page may be truncated or
4483 * invalidated (changing page->mapping to NULL),
4484 * or even swizzled back from swapper_space to
4485 * tmpfs file mapping
d1310b2e 4486 */
c8f2f24b 4487 if (!trylock_page(page)) {
f4340622
QW
4488 ret = flush_write_bio(epd);
4489 BUG_ON(ret < 0);
c8f2f24b 4490 lock_page(page);
01d658f2 4491 }
d1310b2e
CM
4492
4493 if (unlikely(page->mapping != mapping)) {
4494 unlock_page(page);
4495 continue;
4496 }
4497
d2c3f4f6 4498 if (wbc->sync_mode != WB_SYNC_NONE) {
f4340622
QW
4499 if (PageWriteback(page)) {
4500 ret = flush_write_bio(epd);
4501 BUG_ON(ret < 0);
4502 }
d1310b2e 4503 wait_on_page_writeback(page);
d2c3f4f6 4504 }
d1310b2e
CM
4505
4506 if (PageWriteback(page) ||
4507 !clear_page_dirty_for_io(page)) {
4508 unlock_page(page);
4509 continue;
4510 }
4511
aab6e9ed 4512 ret = __extent_writepage(page, wbc, epd);
a9132667 4513 if (ret < 0) {
a9132667
LB
4514 done = 1;
4515 break;
4516 }
f85d7d6c
CM
4517
4518 /*
4519 * the filesystem may choose to bump up nr_to_write.
4520 * We have to make sure to honor the new nr_to_write
4521 * at any time
4522 */
4523 nr_to_write_done = wbc->nr_to_write <= 0;
d1310b2e
CM
4524 }
4525 pagevec_release(&pvec);
4526 cond_resched();
4527 }
894b36e3 4528 if (!scanned && !done) {
d1310b2e
CM
4529 /*
4530 * We hit the last page and there is more work to be done: wrap
4531 * back to the start of the file
4532 */
4533 scanned = 1;
4534 index = 0;
42ffb0bf
JB
4535
4536 /*
4537 * If we're looping we could run into a page that is locked by a
4538 * writer and that writer could be waiting on writeback for a
4539 * page in our current bio, and thus deadlock, so flush the
4540 * write bio here.
4541 */
4542 ret = flush_write_bio(epd);
4543 if (!ret)
4544 goto retry;
d1310b2e 4545 }
a9132667
LB
4546
4547 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
4548 mapping->writeback_index = done_index;
4549
7fd1a3f7 4550 btrfs_add_delayed_iput(inode);
894b36e3 4551 return ret;
d1310b2e 4552}
d1310b2e 4553
0a9b0e53 4554int extent_write_full_page(struct page *page, struct writeback_control *wbc)
d1310b2e
CM
4555{
4556 int ret;
d1310b2e
CM
4557 struct extent_page_data epd = {
4558 .bio = NULL,
771ed689 4559 .extent_locked = 0,
ffbd517d 4560 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
d1310b2e 4561 };
d1310b2e 4562
d1310b2e 4563 ret = __extent_writepage(page, wbc, &epd);
3065976b
QW
4564 ASSERT(ret <= 0);
4565 if (ret < 0) {
4566 end_write_bio(&epd, ret);
4567 return ret;
4568 }
d1310b2e 4569
3065976b
QW
4570 ret = flush_write_bio(&epd);
4571 ASSERT(ret <= 0);
d1310b2e
CM
4572 return ret;
4573}
d1310b2e 4574
5e3ee236 4575int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
771ed689
CM
4576 int mode)
4577{
4578 int ret = 0;
4579 struct address_space *mapping = inode->i_mapping;
4580 struct page *page;
09cbfeaf
KS
4581 unsigned long nr_pages = (end - start + PAGE_SIZE) >>
4582 PAGE_SHIFT;
771ed689
CM
4583
4584 struct extent_page_data epd = {
4585 .bio = NULL,
771ed689 4586 .extent_locked = 1,
ffbd517d 4587 .sync_io = mode == WB_SYNC_ALL,
771ed689
CM
4588 };
4589 struct writeback_control wbc_writepages = {
771ed689 4590 .sync_mode = mode,
771ed689
CM
4591 .nr_to_write = nr_pages * 2,
4592 .range_start = start,
4593 .range_end = end + 1,
ec39f769
CM
4594 /* We're called from an async helper function */
4595 .punt_to_cgroup = 1,
4596 .no_cgroup_owner = 1,
771ed689
CM
4597 };
4598
dbb70bec 4599 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
d397712b 4600 while (start <= end) {
09cbfeaf 4601 page = find_get_page(mapping, start >> PAGE_SHIFT);
771ed689
CM
4602 if (clear_page_dirty_for_io(page))
4603 ret = __extent_writepage(page, &wbc_writepages, &epd);
4604 else {
7087a9d8 4605 btrfs_writepage_endio_finish_ordered(page, start,
c629732d 4606 start + PAGE_SIZE - 1, 1);
771ed689
CM
4607 unlock_page(page);
4608 }
09cbfeaf
KS
4609 put_page(page);
4610 start += PAGE_SIZE;
771ed689
CM
4611 }
4612
02c6db4f 4613 ASSERT(ret <= 0);
dbb70bec
CM
4614 if (ret == 0)
4615 ret = flush_write_bio(&epd);
4616 else
02c6db4f 4617 end_write_bio(&epd, ret);
dbb70bec
CM
4618
4619 wbc_detach_inode(&wbc_writepages);
771ed689
CM
4620 return ret;
4621}
d1310b2e 4622
8ae225a8 4623int extent_writepages(struct address_space *mapping,
d1310b2e
CM
4624 struct writeback_control *wbc)
4625{
4626 int ret = 0;
4627 struct extent_page_data epd = {
4628 .bio = NULL,
771ed689 4629 .extent_locked = 0,
ffbd517d 4630 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
d1310b2e
CM
4631 };
4632
935db853 4633 ret = extent_write_cache_pages(mapping, wbc, &epd);
a2a72fbd
QW
4634 ASSERT(ret <= 0);
4635 if (ret < 0) {
4636 end_write_bio(&epd, ret);
4637 return ret;
4638 }
4639 ret = flush_write_bio(&epd);
d1310b2e
CM
4640 return ret;
4641}
d1310b2e 4642
ba206a02 4643void extent_readahead(struct readahead_control *rac)
d1310b2e
CM
4644{
4645 struct bio *bio = NULL;
c8b97818 4646 unsigned long bio_flags = 0;
67c9684f 4647 struct page *pagepool[16];
125bac01 4648 struct extent_map *em_cached = NULL;
808f80b4 4649 u64 prev_em_start = (u64)-1;
ba206a02 4650 int nr;
d1310b2e 4651
ba206a02 4652 while ((nr = readahead_page_batch(rac, pagepool))) {
32c0a6bc
MWO
4653 u64 contig_start = readahead_pos(rac);
4654 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
e65ef21e 4655
ba206a02
MWO
4656 contiguous_readpages(pagepool, nr, contig_start, contig_end,
4657 &em_cached, &bio, &bio_flags, &prev_em_start);
d1310b2e 4658 }
67c9684f 4659
125bac01
MX
4660 if (em_cached)
4661 free_extent_map(em_cached);
4662
ba206a02
MWO
4663 if (bio) {
4664 if (submit_one_bio(bio, 0, bio_flags))
4665 return;
4666 }
d1310b2e 4667}
d1310b2e
CM
4668
4669/*
4670 * basic invalidatepage code, this waits on any locked or writeback
4671 * ranges corresponding to the page, and then deletes any extent state
4672 * records from the tree
4673 */
4674int extent_invalidatepage(struct extent_io_tree *tree,
4675 struct page *page, unsigned long offset)
4676{
2ac55d41 4677 struct extent_state *cached_state = NULL;
4eee4fa4 4678 u64 start = page_offset(page);
09cbfeaf 4679 u64 end = start + PAGE_SIZE - 1;
d1310b2e
CM
4680 size_t blocksize = page->mapping->host->i_sb->s_blocksize;
4681
829ddec9
QW
4682 /* This function is only called for the btree inode */
4683 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
4684
fda2832f 4685 start += ALIGN(offset, blocksize);
d1310b2e
CM
4686 if (start > end)
4687 return 0;
4688
ff13db41 4689 lock_extent_bits(tree, start, end, &cached_state);
1edbb734 4690 wait_on_page_writeback(page);
829ddec9
QW
4691
4692 /*
4693 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
4694 * so here we only need to unlock the extent range to free any
4695 * existing extent state.
4696 */
4697 unlock_extent_cached(tree, start, end, &cached_state);
d1310b2e
CM
4698 return 0;
4699}
d1310b2e 4700
7b13b7b1
CM
4701/*
4702 * a helper for releasepage, this tests for areas of the page that
4703 * are locked or under IO and drops the related state bits if it is safe
4704 * to drop the page.
4705 */
29c68b2d 4706static int try_release_extent_state(struct extent_io_tree *tree,
48a3b636 4707 struct page *page, gfp_t mask)
7b13b7b1 4708{
4eee4fa4 4709 u64 start = page_offset(page);
09cbfeaf 4710 u64 end = start + PAGE_SIZE - 1;
7b13b7b1
CM
4711 int ret = 1;
4712
8882679e 4713 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
7b13b7b1 4714 ret = 0;
8882679e 4715 } else {
11ef160f 4716 /*
2766ff61
FM
4717 * At this point we can safely clear everything except the
4718 * locked bit, the nodatasum bit and the delalloc new bit.
4719 * The delalloc new bit will be cleared by ordered extent
4720 * completion.
11ef160f 4721 */
66b0c887 4722 ret = __clear_extent_bit(tree, start, end,
2766ff61
FM
4723 ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW),
4724 0, 0, NULL, mask, NULL);
e3f24cc5
CM
4725
4726 /* if clear_extent_bit failed for enomem reasons,
4727 * we can't allow the release to continue.
4728 */
4729 if (ret < 0)
4730 ret = 0;
4731 else
4732 ret = 1;
7b13b7b1
CM
4733 }
4734 return ret;
4735}
7b13b7b1 4736
d1310b2e
CM
4737/*
4738 * a helper for releasepage. As long as there are no locked extents
4739 * in the range corresponding to the page, both state records and extent
4740 * map records are removed
4741 */
477a30ba 4742int try_release_extent_mapping(struct page *page, gfp_t mask)
d1310b2e
CM
4743{
4744 struct extent_map *em;
4eee4fa4 4745 u64 start = page_offset(page);
09cbfeaf 4746 u64 end = start + PAGE_SIZE - 1;
bd3599a0
FM
4747 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
4748 struct extent_io_tree *tree = &btrfs_inode->io_tree;
4749 struct extent_map_tree *map = &btrfs_inode->extent_tree;
7b13b7b1 4750
d0164adc 4751 if (gfpflags_allow_blocking(mask) &&
ee22184b 4752 page->mapping->host->i_size > SZ_16M) {
39b5637f 4753 u64 len;
70dec807 4754 while (start <= end) {
fbc2bd7e
FM
4755 struct btrfs_fs_info *fs_info;
4756 u64 cur_gen;
4757
39b5637f 4758 len = end - start + 1;
890871be 4759 write_lock(&map->lock);
39b5637f 4760 em = lookup_extent_mapping(map, start, len);
285190d9 4761 if (!em) {
890871be 4762 write_unlock(&map->lock);
70dec807
CM
4763 break;
4764 }
7f3c74fb
CM
4765 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
4766 em->start != start) {
890871be 4767 write_unlock(&map->lock);
70dec807
CM
4768 free_extent_map(em);
4769 break;
4770 }
3d6448e6
FM
4771 if (test_range_bit(tree, em->start,
4772 extent_map_end(em) - 1,
4773 EXTENT_LOCKED, 0, NULL))
4774 goto next;
4775 /*
4776 * If it's not in the list of modified extents, used
4777 * by a fast fsync, we can remove it. If it's being
4778 * logged we can safely remove it since fsync took an
4779 * extra reference on the em.
4780 */
4781 if (list_empty(&em->list) ||
fbc2bd7e
FM
4782 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
4783 goto remove_em;
4784 /*
4785 * If it's in the list of modified extents, remove it
4786 * only if its generation is older then the current one,
4787 * in which case we don't need it for a fast fsync.
4788 * Otherwise don't remove it, we could be racing with an
4789 * ongoing fast fsync that could miss the new extent.
4790 */
4791 fs_info = btrfs_inode->root->fs_info;
4792 spin_lock(&fs_info->trans_lock);
4793 cur_gen = fs_info->generation;
4794 spin_unlock(&fs_info->trans_lock);
4795 if (em->generation >= cur_gen)
4796 goto next;
4797remove_em:
5e548b32
FM
4798 /*
4799 * We only remove extent maps that are not in the list of
4800 * modified extents or that are in the list but with a
4801 * generation lower then the current generation, so there
4802 * is no need to set the full fsync flag on the inode (it
4803 * hurts the fsync performance for workloads with a data
4804 * size that exceeds or is close to the system's memory).
4805 */
fbc2bd7e
FM
4806 remove_extent_mapping(map, em);
4807 /* once for the rb tree */
4808 free_extent_map(em);
3d6448e6 4809next:
70dec807 4810 start = extent_map_end(em);
890871be 4811 write_unlock(&map->lock);
70dec807
CM
4812
4813 /* once for us */
d1310b2e 4814 free_extent_map(em);
9f47eb54
PM
4815
4816 cond_resched(); /* Allow large-extent preemption. */
d1310b2e 4817 }
d1310b2e 4818 }
29c68b2d 4819 return try_release_extent_state(tree, page, mask);
d1310b2e 4820}
d1310b2e 4821
ec29ed5b
CM
4822/*
4823 * helper function for fiemap, which doesn't want to see any holes.
4824 * This maps until we find something past 'last'
4825 */
f1bbde8d 4826static struct extent_map *get_extent_skip_holes(struct btrfs_inode *inode,
e3350e16 4827 u64 offset, u64 last)
ec29ed5b 4828{
f1bbde8d 4829 u64 sectorsize = btrfs_inode_sectorsize(inode);
ec29ed5b
CM
4830 struct extent_map *em;
4831 u64 len;
4832
4833 if (offset >= last)
4834 return NULL;
4835
67871254 4836 while (1) {
ec29ed5b
CM
4837 len = last - offset;
4838 if (len == 0)
4839 break;
fda2832f 4840 len = ALIGN(len, sectorsize);
f1bbde8d 4841 em = btrfs_get_extent_fiemap(inode, offset, len);
c704005d 4842 if (IS_ERR_OR_NULL(em))
ec29ed5b
CM
4843 return em;
4844
4845 /* if this isn't a hole return it */
4a2d25cd 4846 if (em->block_start != EXTENT_MAP_HOLE)
ec29ed5b 4847 return em;
ec29ed5b
CM
4848
4849 /* this is a hole, advance to the next extent */
4850 offset = extent_map_end(em);
4851 free_extent_map(em);
4852 if (offset >= last)
4853 break;
4854 }
4855 return NULL;
4856}
4857
4751832d
QW
4858/*
4859 * To cache previous fiemap extent
4860 *
4861 * Will be used for merging fiemap extent
4862 */
4863struct fiemap_cache {
4864 u64 offset;
4865 u64 phys;
4866 u64 len;
4867 u32 flags;
4868 bool cached;
4869};
4870
4871/*
4872 * Helper to submit fiemap extent.
4873 *
4874 * Will try to merge current fiemap extent specified by @offset, @phys,
4875 * @len and @flags with cached one.
4876 * And only when we fails to merge, cached one will be submitted as
4877 * fiemap extent.
4878 *
4879 * Return value is the same as fiemap_fill_next_extent().
4880 */
4881static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
4882 struct fiemap_cache *cache,
4883 u64 offset, u64 phys, u64 len, u32 flags)
4884{
4885 int ret = 0;
4886
4887 if (!cache->cached)
4888 goto assign;
4889
4890 /*
4891 * Sanity check, extent_fiemap() should have ensured that new
52042d8e 4892 * fiemap extent won't overlap with cached one.
4751832d
QW
4893 * Not recoverable.
4894 *
4895 * NOTE: Physical address can overlap, due to compression
4896 */
4897 if (cache->offset + cache->len > offset) {
4898 WARN_ON(1);
4899 return -EINVAL;
4900 }
4901
4902 /*
4903 * Only merges fiemap extents if
4904 * 1) Their logical addresses are continuous
4905 *
4906 * 2) Their physical addresses are continuous
4907 * So truly compressed (physical size smaller than logical size)
4908 * extents won't get merged with each other
4909 *
4910 * 3) Share same flags except FIEMAP_EXTENT_LAST
4911 * So regular extent won't get merged with prealloc extent
4912 */
4913 if (cache->offset + cache->len == offset &&
4914 cache->phys + cache->len == phys &&
4915 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
4916 (flags & ~FIEMAP_EXTENT_LAST)) {
4917 cache->len += len;
4918 cache->flags |= flags;
4919 goto try_submit_last;
4920 }
4921
4922 /* Not mergeable, need to submit cached one */
4923 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4924 cache->len, cache->flags);
4925 cache->cached = false;
4926 if (ret)
4927 return ret;
4928assign:
4929 cache->cached = true;
4930 cache->offset = offset;
4931 cache->phys = phys;
4932 cache->len = len;
4933 cache->flags = flags;
4934try_submit_last:
4935 if (cache->flags & FIEMAP_EXTENT_LAST) {
4936 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
4937 cache->phys, cache->len, cache->flags);
4938 cache->cached = false;
4939 }
4940 return ret;
4941}
4942
4943/*
848c23b7 4944 * Emit last fiemap cache
4751832d 4945 *
848c23b7
QW
4946 * The last fiemap cache may still be cached in the following case:
4947 * 0 4k 8k
4948 * |<- Fiemap range ->|
4949 * |<------------ First extent ----------->|
4950 *
4951 * In this case, the first extent range will be cached but not emitted.
4952 * So we must emit it before ending extent_fiemap().
4751832d 4953 */
5c5aff98 4954static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
848c23b7 4955 struct fiemap_cache *cache)
4751832d
QW
4956{
4957 int ret;
4958
4959 if (!cache->cached)
4960 return 0;
4961
4751832d
QW
4962 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
4963 cache->len, cache->flags);
4964 cache->cached = false;
4965 if (ret > 0)
4966 ret = 0;
4967 return ret;
4968}
4969
facee0a0 4970int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
bab16e21 4971 u64 start, u64 len)
1506fcc8 4972{
975f84fe 4973 int ret = 0;
1506fcc8
YS
4974 u64 off = start;
4975 u64 max = start + len;
4976 u32 flags = 0;
975f84fe
JB
4977 u32 found_type;
4978 u64 last;
ec29ed5b 4979 u64 last_for_get_extent = 0;
1506fcc8 4980 u64 disko = 0;
facee0a0 4981 u64 isize = i_size_read(&inode->vfs_inode);
975f84fe 4982 struct btrfs_key found_key;
1506fcc8 4983 struct extent_map *em = NULL;
2ac55d41 4984 struct extent_state *cached_state = NULL;
975f84fe 4985 struct btrfs_path *path;
facee0a0 4986 struct btrfs_root *root = inode->root;
4751832d 4987 struct fiemap_cache cache = { 0 };
5911c8fe
DS
4988 struct ulist *roots;
4989 struct ulist *tmp_ulist;
1506fcc8 4990 int end = 0;
ec29ed5b
CM
4991 u64 em_start = 0;
4992 u64 em_len = 0;
4993 u64 em_end = 0;
1506fcc8
YS
4994
4995 if (len == 0)
4996 return -EINVAL;
4997
975f84fe
JB
4998 path = btrfs_alloc_path();
4999 if (!path)
5000 return -ENOMEM;
975f84fe 5001
5911c8fe
DS
5002 roots = ulist_alloc(GFP_KERNEL);
5003 tmp_ulist = ulist_alloc(GFP_KERNEL);
5004 if (!roots || !tmp_ulist) {
5005 ret = -ENOMEM;
5006 goto out_free_ulist;
5007 }
5008
facee0a0
NB
5009 start = round_down(start, btrfs_inode_sectorsize(inode));
5010 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
4d479cf0 5011
ec29ed5b
CM
5012 /*
5013 * lookup the last file extent. We're not using i_size here
5014 * because there might be preallocation past i_size
5015 */
facee0a0
NB
5016 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode), -1,
5017 0);
975f84fe 5018 if (ret < 0) {
5911c8fe 5019 goto out_free_ulist;
2d324f59
LB
5020 } else {
5021 WARN_ON(!ret);
5022 if (ret == 1)
5023 ret = 0;
975f84fe 5024 }
2d324f59 5025
975f84fe 5026 path->slots[0]--;
975f84fe 5027 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
962a298f 5028 found_type = found_key.type;
975f84fe 5029
ec29ed5b 5030 /* No extents, but there might be delalloc bits */
facee0a0 5031 if (found_key.objectid != btrfs_ino(inode) ||
975f84fe 5032 found_type != BTRFS_EXTENT_DATA_KEY) {
ec29ed5b
CM
5033 /* have to trust i_size as the end */
5034 last = (u64)-1;
5035 last_for_get_extent = isize;
5036 } else {
5037 /*
5038 * remember the start of the last extent. There are a
5039 * bunch of different factors that go into the length of the
5040 * extent, so its much less complex to remember where it started
5041 */
5042 last = found_key.offset;
5043 last_for_get_extent = last + 1;
975f84fe 5044 }
fe09e16c 5045 btrfs_release_path(path);
975f84fe 5046
ec29ed5b
CM
5047 /*
5048 * we might have some extents allocated but more delalloc past those
5049 * extents. so, we trust isize unless the start of the last extent is
5050 * beyond isize
5051 */
5052 if (last < isize) {
5053 last = (u64)-1;
5054 last_for_get_extent = isize;
5055 }
5056
facee0a0 5057 lock_extent_bits(&inode->io_tree, start, start + len - 1,
d0082371 5058 &cached_state);
ec29ed5b 5059
facee0a0 5060 em = get_extent_skip_holes(inode, start, last_for_get_extent);
1506fcc8
YS
5061 if (!em)
5062 goto out;
5063 if (IS_ERR(em)) {
5064 ret = PTR_ERR(em);
5065 goto out;
5066 }
975f84fe 5067
1506fcc8 5068 while (!end) {
b76bb701 5069 u64 offset_in_extent = 0;
ea8efc74
CM
5070
5071 /* break if the extent we found is outside the range */
5072 if (em->start >= max || extent_map_end(em) < off)
5073 break;
5074
5075 /*
5076 * get_extent may return an extent that starts before our
5077 * requested range. We have to make sure the ranges
5078 * we return to fiemap always move forward and don't
5079 * overlap, so adjust the offsets here
5080 */
5081 em_start = max(em->start, off);
1506fcc8 5082
ea8efc74
CM
5083 /*
5084 * record the offset from the start of the extent
b76bb701
JB
5085 * for adjusting the disk offset below. Only do this if the
5086 * extent isn't compressed since our in ram offset may be past
5087 * what we have actually allocated on disk.
ea8efc74 5088 */
b76bb701
JB
5089 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5090 offset_in_extent = em_start - em->start;
ec29ed5b 5091 em_end = extent_map_end(em);
ea8efc74 5092 em_len = em_end - em_start;
1506fcc8 5093 flags = 0;
f0986318
FM
5094 if (em->block_start < EXTENT_MAP_LAST_BYTE)
5095 disko = em->block_start + offset_in_extent;
5096 else
5097 disko = 0;
1506fcc8 5098
ea8efc74
CM
5099 /*
5100 * bump off for our next call to get_extent
5101 */
5102 off = extent_map_end(em);
5103 if (off >= max)
5104 end = 1;
5105
93dbfad7 5106 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
1506fcc8
YS
5107 end = 1;
5108 flags |= FIEMAP_EXTENT_LAST;
93dbfad7 5109 } else if (em->block_start == EXTENT_MAP_INLINE) {
1506fcc8
YS
5110 flags |= (FIEMAP_EXTENT_DATA_INLINE |
5111 FIEMAP_EXTENT_NOT_ALIGNED);
93dbfad7 5112 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
1506fcc8
YS
5113 flags |= (FIEMAP_EXTENT_DELALLOC |
5114 FIEMAP_EXTENT_UNKNOWN);
dc046b10
JB
5115 } else if (fieinfo->fi_extents_max) {
5116 u64 bytenr = em->block_start -
5117 (em->start - em->orig_start);
fe09e16c 5118
fe09e16c
LB
5119 /*
5120 * As btrfs supports shared space, this information
5121 * can be exported to userspace tools via
dc046b10
JB
5122 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
5123 * then we're just getting a count and we can skip the
5124 * lookup stuff.
fe09e16c 5125 */
facee0a0 5126 ret = btrfs_check_shared(root, btrfs_ino(inode),
5911c8fe 5127 bytenr, roots, tmp_ulist);
dc046b10 5128 if (ret < 0)
fe09e16c 5129 goto out_free;
dc046b10 5130 if (ret)
fe09e16c 5131 flags |= FIEMAP_EXTENT_SHARED;
dc046b10 5132 ret = 0;
1506fcc8
YS
5133 }
5134 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5135 flags |= FIEMAP_EXTENT_ENCODED;
0d2b2372
JB
5136 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5137 flags |= FIEMAP_EXTENT_UNWRITTEN;
1506fcc8 5138
1506fcc8
YS
5139 free_extent_map(em);
5140 em = NULL;
ec29ed5b
CM
5141 if ((em_start >= last) || em_len == (u64)-1 ||
5142 (last == (u64)-1 && isize <= em_end)) {
1506fcc8
YS
5143 flags |= FIEMAP_EXTENT_LAST;
5144 end = 1;
5145 }
5146
ec29ed5b 5147 /* now scan forward to see if this is really the last extent. */
facee0a0 5148 em = get_extent_skip_holes(inode, off, last_for_get_extent);
ec29ed5b
CM
5149 if (IS_ERR(em)) {
5150 ret = PTR_ERR(em);
5151 goto out;
5152 }
5153 if (!em) {
975f84fe
JB
5154 flags |= FIEMAP_EXTENT_LAST;
5155 end = 1;
5156 }
4751832d
QW
5157 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
5158 em_len, flags);
26e726af
CS
5159 if (ret) {
5160 if (ret == 1)
5161 ret = 0;
ec29ed5b 5162 goto out_free;
26e726af 5163 }
1506fcc8
YS
5164 }
5165out_free:
4751832d 5166 if (!ret)
5c5aff98 5167 ret = emit_last_fiemap_cache(fieinfo, &cache);
1506fcc8
YS
5168 free_extent_map(em);
5169out:
facee0a0 5170 unlock_extent_cached(&inode->io_tree, start, start + len - 1,
e43bbe5e 5171 &cached_state);
5911c8fe
DS
5172
5173out_free_ulist:
e02d48ea 5174 btrfs_free_path(path);
5911c8fe
DS
5175 ulist_free(roots);
5176 ulist_free(tmp_ulist);
1506fcc8
YS
5177 return ret;
5178}
5179
727011e0
CM
5180static void __free_extent_buffer(struct extent_buffer *eb)
5181{
727011e0
CM
5182 kmem_cache_free(extent_buffer_cache, eb);
5183}
5184
2b48966a 5185int extent_buffer_under_io(const struct extent_buffer *eb)
db7f3436
JB
5186{
5187 return (atomic_read(&eb->io_pages) ||
5188 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
5189 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5190}
5191
8ff8466d 5192static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
db7f3436 5193{
8ff8466d 5194 struct btrfs_subpage *subpage;
db7f3436 5195
8ff8466d 5196 lockdep_assert_held(&page->mapping->private_lock);
db7f3436 5197
8ff8466d
QW
5198 if (PagePrivate(page)) {
5199 subpage = (struct btrfs_subpage *)page->private;
5200 if (atomic_read(&subpage->eb_refs))
5201 return true;
5202 }
5203 return false;
5204}
db7f3436 5205
8ff8466d
QW
5206static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
5207{
5208 struct btrfs_fs_info *fs_info = eb->fs_info;
5209 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5210
5211 /*
5212 * For mapped eb, we're going to change the page private, which should
5213 * be done under the private_lock.
5214 */
5215 if (mapped)
5216 spin_lock(&page->mapping->private_lock);
5217
5218 if (!PagePrivate(page)) {
5d2361db 5219 if (mapped)
8ff8466d
QW
5220 spin_unlock(&page->mapping->private_lock);
5221 return;
5222 }
5223
5224 if (fs_info->sectorsize == PAGE_SIZE) {
5d2361db
FL
5225 /*
5226 * We do this since we'll remove the pages after we've
5227 * removed the eb from the radix tree, so we could race
5228 * and have this page now attached to the new eb. So
5229 * only clear page_private if it's still connected to
5230 * this eb.
5231 */
5232 if (PagePrivate(page) &&
5233 page->private == (unsigned long)eb) {
5234 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5235 BUG_ON(PageDirty(page));
5236 BUG_ON(PageWriteback(page));
db7f3436 5237 /*
5d2361db
FL
5238 * We need to make sure we haven't be attached
5239 * to a new eb.
db7f3436 5240 */
d1b89bc0 5241 detach_page_private(page);
db7f3436 5242 }
5d2361db
FL
5243 if (mapped)
5244 spin_unlock(&page->mapping->private_lock);
8ff8466d
QW
5245 return;
5246 }
5247
5248 /*
5249 * For subpage, we can have dummy eb with page private. In this case,
5250 * we can directly detach the private as such page is only attached to
5251 * one dummy eb, no sharing.
5252 */
5253 if (!mapped) {
5254 btrfs_detach_subpage(fs_info, page);
5255 return;
5256 }
5257
5258 btrfs_page_dec_eb_refs(fs_info, page);
5259
5260 /*
5261 * We can only detach the page private if there are no other ebs in the
5262 * page range.
5263 */
5264 if (!page_range_has_eb(fs_info, page))
5265 btrfs_detach_subpage(fs_info, page);
5266
5267 spin_unlock(&page->mapping->private_lock);
5268}
5269
5270/* Release all pages attached to the extent buffer */
5271static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
5272{
5273 int i;
5274 int num_pages;
5275
5276 ASSERT(!extent_buffer_under_io(eb));
5277
5278 num_pages = num_extent_pages(eb);
5279 for (i = 0; i < num_pages; i++) {
5280 struct page *page = eb->pages[i];
5281
5282 if (!page)
5283 continue;
5284
5285 detach_extent_buffer_page(eb, page);
5d2361db 5286
01327610 5287 /* One for when we allocated the page */
09cbfeaf 5288 put_page(page);
d64766fd 5289 }
db7f3436
JB
5290}
5291
5292/*
5293 * Helper for releasing the extent buffer.
5294 */
5295static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
5296{
55ac0139 5297 btrfs_release_extent_buffer_pages(eb);
8c38938c 5298 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
db7f3436
JB
5299 __free_extent_buffer(eb);
5300}
5301
f28491e0
JB
5302static struct extent_buffer *
5303__alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
23d79d81 5304 unsigned long len)
d1310b2e
CM
5305{
5306 struct extent_buffer *eb = NULL;
5307
d1b5c567 5308 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
d1310b2e
CM
5309 eb->start = start;
5310 eb->len = len;
f28491e0 5311 eb->fs_info = fs_info;
815a51c7 5312 eb->bflags = 0;
196d59ab 5313 init_rwsem(&eb->lock);
b4ce94de 5314
3fd63727
JB
5315 btrfs_leak_debug_add(&fs_info->eb_leak_lock, &eb->leak_list,
5316 &fs_info->allocated_ebs);
d3575156 5317 INIT_LIST_HEAD(&eb->release_list);
6d49ba1b 5318
3083ee2e 5319 spin_lock_init(&eb->refs_lock);
d1310b2e 5320 atomic_set(&eb->refs, 1);
0b32f4bb 5321 atomic_set(&eb->io_pages, 0);
727011e0 5322
deb67895 5323 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
d1310b2e
CM
5324
5325 return eb;
5326}
5327
2b48966a 5328struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
815a51c7 5329{
cc5e31a4 5330 int i;
815a51c7
JS
5331 struct page *p;
5332 struct extent_buffer *new;
cc5e31a4 5333 int num_pages = num_extent_pages(src);
815a51c7 5334
3f556f78 5335 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
815a51c7
JS
5336 if (new == NULL)
5337 return NULL;
5338
62c053fb
QW
5339 /*
5340 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
5341 * btrfs_release_extent_buffer() have different behavior for
5342 * UNMAPPED subpage extent buffer.
5343 */
5344 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
5345
815a51c7 5346 for (i = 0; i < num_pages; i++) {
760f991f
QW
5347 int ret;
5348
9ec72677 5349 p = alloc_page(GFP_NOFS);
db7f3436
JB
5350 if (!p) {
5351 btrfs_release_extent_buffer(new);
5352 return NULL;
5353 }
760f991f
QW
5354 ret = attach_extent_buffer_page(new, p, NULL);
5355 if (ret < 0) {
5356 put_page(p);
5357 btrfs_release_extent_buffer(new);
5358 return NULL;
5359 }
815a51c7 5360 WARN_ON(PageDirty(p));
815a51c7 5361 new->pages[i] = p;
fba1acf9 5362 copy_page(page_address(p), page_address(src->pages[i]));
815a51c7 5363 }
92d83e94 5364 set_extent_buffer_uptodate(new);
815a51c7
JS
5365
5366 return new;
5367}
5368
0f331229
OS
5369struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5370 u64 start, unsigned long len)
815a51c7
JS
5371{
5372 struct extent_buffer *eb;
cc5e31a4
DS
5373 int num_pages;
5374 int i;
815a51c7 5375
3f556f78 5376 eb = __alloc_extent_buffer(fs_info, start, len);
815a51c7
JS
5377 if (!eb)
5378 return NULL;
5379
65ad0104 5380 num_pages = num_extent_pages(eb);
815a51c7 5381 for (i = 0; i < num_pages; i++) {
09bc1f0f
QW
5382 int ret;
5383
9ec72677 5384 eb->pages[i] = alloc_page(GFP_NOFS);
815a51c7
JS
5385 if (!eb->pages[i])
5386 goto err;
09bc1f0f
QW
5387 ret = attach_extent_buffer_page(eb, eb->pages[i], NULL);
5388 if (ret < 0)
5389 goto err;
815a51c7
JS
5390 }
5391 set_extent_buffer_uptodate(eb);
5392 btrfs_set_header_nritems(eb, 0);
b0132a3b 5393 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
815a51c7
JS
5394
5395 return eb;
5396err:
09bc1f0f
QW
5397 for (; i > 0; i--) {
5398 detach_extent_buffer_page(eb, eb->pages[i - 1]);
84167d19 5399 __free_page(eb->pages[i - 1]);
09bc1f0f 5400 }
815a51c7
JS
5401 __free_extent_buffer(eb);
5402 return NULL;
5403}
5404
0f331229 5405struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
da17066c 5406 u64 start)
0f331229 5407{
da17066c 5408 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
0f331229
OS
5409}
5410
0b32f4bb
JB
5411static void check_buffer_tree_ref(struct extent_buffer *eb)
5412{
242e18c7 5413 int refs;
6bf9cd2e
BB
5414 /*
5415 * The TREE_REF bit is first set when the extent_buffer is added
5416 * to the radix tree. It is also reset, if unset, when a new reference
5417 * is created by find_extent_buffer.
0b32f4bb 5418 *
6bf9cd2e
BB
5419 * It is only cleared in two cases: freeing the last non-tree
5420 * reference to the extent_buffer when its STALE bit is set or
5421 * calling releasepage when the tree reference is the only reference.
0b32f4bb 5422 *
6bf9cd2e
BB
5423 * In both cases, care is taken to ensure that the extent_buffer's
5424 * pages are not under io. However, releasepage can be concurrently
5425 * called with creating new references, which is prone to race
5426 * conditions between the calls to check_buffer_tree_ref in those
5427 * codepaths and clearing TREE_REF in try_release_extent_buffer.
0b32f4bb 5428 *
6bf9cd2e
BB
5429 * The actual lifetime of the extent_buffer in the radix tree is
5430 * adequately protected by the refcount, but the TREE_REF bit and
5431 * its corresponding reference are not. To protect against this
5432 * class of races, we call check_buffer_tree_ref from the codepaths
5433 * which trigger io after they set eb->io_pages. Note that once io is
5434 * initiated, TREE_REF can no longer be cleared, so that is the
5435 * moment at which any such race is best fixed.
0b32f4bb 5436 */
242e18c7
CM
5437 refs = atomic_read(&eb->refs);
5438 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5439 return;
5440
594831c4
JB
5441 spin_lock(&eb->refs_lock);
5442 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
0b32f4bb 5443 atomic_inc(&eb->refs);
594831c4 5444 spin_unlock(&eb->refs_lock);
0b32f4bb
JB
5445}
5446
2457aec6
MG
5447static void mark_extent_buffer_accessed(struct extent_buffer *eb,
5448 struct page *accessed)
5df4235e 5449{
cc5e31a4 5450 int num_pages, i;
5df4235e 5451
0b32f4bb
JB
5452 check_buffer_tree_ref(eb);
5453
65ad0104 5454 num_pages = num_extent_pages(eb);
5df4235e 5455 for (i = 0; i < num_pages; i++) {
fb85fc9a
DS
5456 struct page *p = eb->pages[i];
5457
2457aec6
MG
5458 if (p != accessed)
5459 mark_page_accessed(p);
5df4235e
JB
5460 }
5461}
5462
f28491e0
JB
5463struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
5464 u64 start)
452c75c3
CS
5465{
5466 struct extent_buffer *eb;
5467
5468 rcu_read_lock();
f28491e0 5469 eb = radix_tree_lookup(&fs_info->buffer_radix,
478ef886 5470 start >> fs_info->sectorsize_bits);
452c75c3
CS
5471 if (eb && atomic_inc_not_zero(&eb->refs)) {
5472 rcu_read_unlock();
062c19e9
FM
5473 /*
5474 * Lock our eb's refs_lock to avoid races with
5475 * free_extent_buffer. When we get our eb it might be flagged
5476 * with EXTENT_BUFFER_STALE and another task running
5477 * free_extent_buffer might have seen that flag set,
5478 * eb->refs == 2, that the buffer isn't under IO (dirty and
5479 * writeback flags not set) and it's still in the tree (flag
5480 * EXTENT_BUFFER_TREE_REF set), therefore being in the process
5481 * of decrementing the extent buffer's reference count twice.
5482 * So here we could race and increment the eb's reference count,
5483 * clear its stale flag, mark it as dirty and drop our reference
5484 * before the other task finishes executing free_extent_buffer,
5485 * which would later result in an attempt to free an extent
5486 * buffer that is dirty.
5487 */
5488 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
5489 spin_lock(&eb->refs_lock);
5490 spin_unlock(&eb->refs_lock);
5491 }
2457aec6 5492 mark_extent_buffer_accessed(eb, NULL);
452c75c3
CS
5493 return eb;
5494 }
5495 rcu_read_unlock();
5496
5497 return NULL;
5498}
5499
faa2dbf0
JB
5500#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5501struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
da17066c 5502 u64 start)
faa2dbf0
JB
5503{
5504 struct extent_buffer *eb, *exists = NULL;
5505 int ret;
5506
5507 eb = find_extent_buffer(fs_info, start);
5508 if (eb)
5509 return eb;
da17066c 5510 eb = alloc_dummy_extent_buffer(fs_info, start);
faa2dbf0 5511 if (!eb)
b6293c82 5512 return ERR_PTR(-ENOMEM);
faa2dbf0
JB
5513 eb->fs_info = fs_info;
5514again:
e1860a77 5515 ret = radix_tree_preload(GFP_NOFS);
b6293c82
DC
5516 if (ret) {
5517 exists = ERR_PTR(ret);
faa2dbf0 5518 goto free_eb;
b6293c82 5519 }
faa2dbf0
JB
5520 spin_lock(&fs_info->buffer_lock);
5521 ret = radix_tree_insert(&fs_info->buffer_radix,
478ef886 5522 start >> fs_info->sectorsize_bits, eb);
faa2dbf0
JB
5523 spin_unlock(&fs_info->buffer_lock);
5524 radix_tree_preload_end();
5525 if (ret == -EEXIST) {
5526 exists = find_extent_buffer(fs_info, start);
5527 if (exists)
5528 goto free_eb;
5529 else
5530 goto again;
5531 }
5532 check_buffer_tree_ref(eb);
5533 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5534
faa2dbf0
JB
5535 return eb;
5536free_eb:
5537 btrfs_release_extent_buffer(eb);
5538 return exists;
5539}
5540#endif
5541
81982210
QW
5542static struct extent_buffer *grab_extent_buffer(
5543 struct btrfs_fs_info *fs_info, struct page *page)
c0f0a9e7
QW
5544{
5545 struct extent_buffer *exists;
5546
81982210
QW
5547 /*
5548 * For subpage case, we completely rely on radix tree to ensure we
5549 * don't try to insert two ebs for the same bytenr. So here we always
5550 * return NULL and just continue.
5551 */
5552 if (fs_info->sectorsize < PAGE_SIZE)
5553 return NULL;
5554
c0f0a9e7
QW
5555 /* Page not yet attached to an extent buffer */
5556 if (!PagePrivate(page))
5557 return NULL;
5558
5559 /*
5560 * We could have already allocated an eb for this page and attached one
5561 * so lets see if we can get a ref on the existing eb, and if we can we
5562 * know it's good and we can just return that one, else we know we can
5563 * just overwrite page->private.
5564 */
5565 exists = (struct extent_buffer *)page->private;
5566 if (atomic_inc_not_zero(&exists->refs))
5567 return exists;
5568
5569 WARN_ON(PageDirty(page));
5570 detach_page_private(page);
5571 return NULL;
5572}
5573
f28491e0 5574struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
3fbaf258 5575 u64 start, u64 owner_root, int level)
d1310b2e 5576{
da17066c 5577 unsigned long len = fs_info->nodesize;
cc5e31a4
DS
5578 int num_pages;
5579 int i;
09cbfeaf 5580 unsigned long index = start >> PAGE_SHIFT;
d1310b2e 5581 struct extent_buffer *eb;
6af118ce 5582 struct extent_buffer *exists = NULL;
d1310b2e 5583 struct page *p;
f28491e0 5584 struct address_space *mapping = fs_info->btree_inode->i_mapping;
d1310b2e 5585 int uptodate = 1;
19fe0a8b 5586 int ret;
d1310b2e 5587
da17066c 5588 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
c871b0f2
LB
5589 btrfs_err(fs_info, "bad tree block start %llu", start);
5590 return ERR_PTR(-EINVAL);
5591 }
5592
1aaac38c
QW
5593 if (fs_info->sectorsize < PAGE_SIZE &&
5594 offset_in_page(start) + len > PAGE_SIZE) {
5595 btrfs_err(fs_info,
5596 "tree block crosses page boundary, start %llu nodesize %lu",
5597 start, len);
5598 return ERR_PTR(-EINVAL);
5599 }
5600
f28491e0 5601 eb = find_extent_buffer(fs_info, start);
452c75c3 5602 if (eb)
6af118ce 5603 return eb;
6af118ce 5604
23d79d81 5605 eb = __alloc_extent_buffer(fs_info, start, len);
2b114d1d 5606 if (!eb)
c871b0f2 5607 return ERR_PTR(-ENOMEM);
e114c545 5608 btrfs_set_buffer_lockdep_class(owner_root, eb, level);
d1310b2e 5609
65ad0104 5610 num_pages = num_extent_pages(eb);
727011e0 5611 for (i = 0; i < num_pages; i++, index++) {
760f991f
QW
5612 struct btrfs_subpage *prealloc = NULL;
5613
d1b5c567 5614 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
c871b0f2
LB
5615 if (!p) {
5616 exists = ERR_PTR(-ENOMEM);
6af118ce 5617 goto free_eb;
c871b0f2 5618 }
4f2de97a 5619
760f991f
QW
5620 /*
5621 * Preallocate page->private for subpage case, so that we won't
5622 * allocate memory with private_lock hold. The memory will be
5623 * freed by attach_extent_buffer_page() or freed manually if
5624 * we exit earlier.
5625 *
5626 * Although we have ensured one subpage eb can only have one
5627 * page, but it may change in the future for 16K page size
5628 * support, so we still preallocate the memory in the loop.
5629 */
5630 ret = btrfs_alloc_subpage(fs_info, &prealloc,
5631 BTRFS_SUBPAGE_METADATA);
5632 if (ret < 0) {
5633 unlock_page(p);
5634 put_page(p);
5635 exists = ERR_PTR(ret);
5636 goto free_eb;
5637 }
5638
4f2de97a 5639 spin_lock(&mapping->private_lock);
81982210 5640 exists = grab_extent_buffer(fs_info, p);
c0f0a9e7
QW
5641 if (exists) {
5642 spin_unlock(&mapping->private_lock);
5643 unlock_page(p);
5644 put_page(p);
5645 mark_extent_buffer_accessed(exists, p);
760f991f 5646 btrfs_free_subpage(prealloc);
c0f0a9e7 5647 goto free_eb;
d1310b2e 5648 }
760f991f
QW
5649 /* Should not fail, as we have preallocated the memory */
5650 ret = attach_extent_buffer_page(eb, p, prealloc);
5651 ASSERT(!ret);
8ff8466d
QW
5652 /*
5653 * To inform we have extra eb under allocation, so that
5654 * detach_extent_buffer_page() won't release the page private
5655 * when the eb hasn't yet been inserted into radix tree.
5656 *
5657 * The ref will be decreased when the eb released the page, in
5658 * detach_extent_buffer_page().
5659 * Thus needs no special handling in error path.
5660 */
5661 btrfs_page_inc_eb_refs(fs_info, p);
4f2de97a 5662 spin_unlock(&mapping->private_lock);
760f991f 5663
1e5eb3d6 5664 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
727011e0 5665 eb->pages[i] = p;
d1310b2e
CM
5666 if (!PageUptodate(p))
5667 uptodate = 0;
eb14ab8e
CM
5668
5669 /*
b16d011e
NB
5670 * We can't unlock the pages just yet since the extent buffer
5671 * hasn't been properly inserted in the radix tree, this
5672 * opens a race with btree_releasepage which can free a page
5673 * while we are still filling in all pages for the buffer and
5674 * we could crash.
eb14ab8e 5675 */
d1310b2e
CM
5676 }
5677 if (uptodate)
b4ce94de 5678 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
115391d2 5679again:
e1860a77 5680 ret = radix_tree_preload(GFP_NOFS);
c871b0f2
LB
5681 if (ret) {
5682 exists = ERR_PTR(ret);
19fe0a8b 5683 goto free_eb;
c871b0f2 5684 }
19fe0a8b 5685
f28491e0
JB
5686 spin_lock(&fs_info->buffer_lock);
5687 ret = radix_tree_insert(&fs_info->buffer_radix,
478ef886 5688 start >> fs_info->sectorsize_bits, eb);
f28491e0 5689 spin_unlock(&fs_info->buffer_lock);
452c75c3 5690 radix_tree_preload_end();
19fe0a8b 5691 if (ret == -EEXIST) {
f28491e0 5692 exists = find_extent_buffer(fs_info, start);
452c75c3
CS
5693 if (exists)
5694 goto free_eb;
5695 else
115391d2 5696 goto again;
6af118ce 5697 }
6af118ce 5698 /* add one reference for the tree */
0b32f4bb 5699 check_buffer_tree_ref(eb);
34b41ace 5700 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
eb14ab8e
CM
5701
5702 /*
b16d011e
NB
5703 * Now it's safe to unlock the pages because any calls to
5704 * btree_releasepage will correctly detect that a page belongs to a
5705 * live buffer and won't free them prematurely.
eb14ab8e 5706 */
28187ae5
NB
5707 for (i = 0; i < num_pages; i++)
5708 unlock_page(eb->pages[i]);
d1310b2e
CM
5709 return eb;
5710
6af118ce 5711free_eb:
5ca64f45 5712 WARN_ON(!atomic_dec_and_test(&eb->refs));
727011e0
CM
5713 for (i = 0; i < num_pages; i++) {
5714 if (eb->pages[i])
5715 unlock_page(eb->pages[i]);
5716 }
eb14ab8e 5717
897ca6e9 5718 btrfs_release_extent_buffer(eb);
6af118ce 5719 return exists;
d1310b2e 5720}
d1310b2e 5721
3083ee2e
JB
5722static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
5723{
5724 struct extent_buffer *eb =
5725 container_of(head, struct extent_buffer, rcu_head);
5726
5727 __free_extent_buffer(eb);
5728}
5729
f7a52a40 5730static int release_extent_buffer(struct extent_buffer *eb)
5ce48d0f 5731 __releases(&eb->refs_lock)
3083ee2e 5732{
07e21c4d
NB
5733 lockdep_assert_held(&eb->refs_lock);
5734
3083ee2e
JB
5735 WARN_ON(atomic_read(&eb->refs) == 0);
5736 if (atomic_dec_and_test(&eb->refs)) {
34b41ace 5737 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
f28491e0 5738 struct btrfs_fs_info *fs_info = eb->fs_info;
3083ee2e 5739
815a51c7 5740 spin_unlock(&eb->refs_lock);
3083ee2e 5741
f28491e0
JB
5742 spin_lock(&fs_info->buffer_lock);
5743 radix_tree_delete(&fs_info->buffer_radix,
478ef886 5744 eb->start >> fs_info->sectorsize_bits);
f28491e0 5745 spin_unlock(&fs_info->buffer_lock);
34b41ace
JB
5746 } else {
5747 spin_unlock(&eb->refs_lock);
815a51c7 5748 }
3083ee2e 5749
8c38938c 5750 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
3083ee2e 5751 /* Should be safe to release our pages at this point */
55ac0139 5752 btrfs_release_extent_buffer_pages(eb);
bcb7e449 5753#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
b0132a3b 5754 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
bcb7e449
JB
5755 __free_extent_buffer(eb);
5756 return 1;
5757 }
5758#endif
3083ee2e 5759 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
e64860aa 5760 return 1;
3083ee2e
JB
5761 }
5762 spin_unlock(&eb->refs_lock);
e64860aa
JB
5763
5764 return 0;
3083ee2e
JB
5765}
5766
d1310b2e
CM
5767void free_extent_buffer(struct extent_buffer *eb)
5768{
242e18c7
CM
5769 int refs;
5770 int old;
d1310b2e
CM
5771 if (!eb)
5772 return;
5773
242e18c7
CM
5774 while (1) {
5775 refs = atomic_read(&eb->refs);
46cc775e
NB
5776 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
5777 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
5778 refs == 1))
242e18c7
CM
5779 break;
5780 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
5781 if (old == refs)
5782 return;
5783 }
5784
3083ee2e
JB
5785 spin_lock(&eb->refs_lock);
5786 if (atomic_read(&eb->refs) == 2 &&
5787 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
0b32f4bb 5788 !extent_buffer_under_io(eb) &&
3083ee2e
JB
5789 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5790 atomic_dec(&eb->refs);
5791
5792 /*
5793 * I know this is terrible, but it's temporary until we stop tracking
5794 * the uptodate bits and such for the extent buffers.
5795 */
f7a52a40 5796 release_extent_buffer(eb);
3083ee2e
JB
5797}
5798
5799void free_extent_buffer_stale(struct extent_buffer *eb)
5800{
5801 if (!eb)
d1310b2e
CM
5802 return;
5803
3083ee2e
JB
5804 spin_lock(&eb->refs_lock);
5805 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
5806
0b32f4bb 5807 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
3083ee2e
JB
5808 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5809 atomic_dec(&eb->refs);
f7a52a40 5810 release_extent_buffer(eb);
d1310b2e 5811}
d1310b2e 5812
0d27797e
QW
5813static void btree_clear_page_dirty(struct page *page)
5814{
5815 ASSERT(PageDirty(page));
5816 ASSERT(PageLocked(page));
5817 clear_page_dirty_for_io(page);
5818 xa_lock_irq(&page->mapping->i_pages);
5819 if (!PageDirty(page))
5820 __xa_clear_mark(&page->mapping->i_pages,
5821 page_index(page), PAGECACHE_TAG_DIRTY);
5822 xa_unlock_irq(&page->mapping->i_pages);
5823}
5824
5825static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
5826{
5827 struct btrfs_fs_info *fs_info = eb->fs_info;
5828 struct page *page = eb->pages[0];
5829 bool last;
5830
5831 /* btree_clear_page_dirty() needs page locked */
5832 lock_page(page);
5833 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
5834 eb->len);
5835 if (last)
5836 btree_clear_page_dirty(page);
5837 unlock_page(page);
5838 WARN_ON(atomic_read(&eb->refs) == 0);
5839}
5840
2b48966a 5841void clear_extent_buffer_dirty(const struct extent_buffer *eb)
d1310b2e 5842{
cc5e31a4
DS
5843 int i;
5844 int num_pages;
d1310b2e
CM
5845 struct page *page;
5846
0d27797e
QW
5847 if (eb->fs_info->sectorsize < PAGE_SIZE)
5848 return clear_subpage_extent_buffer_dirty(eb);
5849
65ad0104 5850 num_pages = num_extent_pages(eb);
d1310b2e
CM
5851
5852 for (i = 0; i < num_pages; i++) {
fb85fc9a 5853 page = eb->pages[i];
b9473439 5854 if (!PageDirty(page))
d2c3f4f6 5855 continue;
a61e6f29 5856 lock_page(page);
0d27797e 5857 btree_clear_page_dirty(page);
bf0da8c1 5858 ClearPageError(page);
a61e6f29 5859 unlock_page(page);
d1310b2e 5860 }
0b32f4bb 5861 WARN_ON(atomic_read(&eb->refs) == 0);
d1310b2e 5862}
d1310b2e 5863
abb57ef3 5864bool set_extent_buffer_dirty(struct extent_buffer *eb)
d1310b2e 5865{
cc5e31a4
DS
5866 int i;
5867 int num_pages;
abb57ef3 5868 bool was_dirty;
d1310b2e 5869
0b32f4bb
JB
5870 check_buffer_tree_ref(eb);
5871
b9473439 5872 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
0b32f4bb 5873
65ad0104 5874 num_pages = num_extent_pages(eb);
3083ee2e 5875 WARN_ON(atomic_read(&eb->refs) == 0);
0b32f4bb
JB
5876 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
5877
0d27797e
QW
5878 if (!was_dirty) {
5879 bool subpage = eb->fs_info->sectorsize < PAGE_SIZE;
51995c39 5880
0d27797e
QW
5881 /*
5882 * For subpage case, we can have other extent buffers in the
5883 * same page, and in clear_subpage_extent_buffer_dirty() we
5884 * have to clear page dirty without subpage lock held.
5885 * This can cause race where our page gets dirty cleared after
5886 * we just set it.
5887 *
5888 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
5889 * its page for other reasons, we can use page lock to prevent
5890 * the above race.
5891 */
5892 if (subpage)
5893 lock_page(eb->pages[0]);
5894 for (i = 0; i < num_pages; i++)
5895 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
5896 eb->start, eb->len);
5897 if (subpage)
5898 unlock_page(eb->pages[0]);
5899 }
51995c39
LB
5900#ifdef CONFIG_BTRFS_DEBUG
5901 for (i = 0; i < num_pages; i++)
5902 ASSERT(PageDirty(eb->pages[i]));
5903#endif
5904
b9473439 5905 return was_dirty;
d1310b2e 5906}
d1310b2e 5907
69ba3927 5908void clear_extent_buffer_uptodate(struct extent_buffer *eb)
1259ab75 5909{
251f2acc 5910 struct btrfs_fs_info *fs_info = eb->fs_info;
1259ab75 5911 struct page *page;
cc5e31a4 5912 int num_pages;
251f2acc 5913 int i;
1259ab75 5914
b4ce94de 5915 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
65ad0104 5916 num_pages = num_extent_pages(eb);
1259ab75 5917 for (i = 0; i < num_pages; i++) {
fb85fc9a 5918 page = eb->pages[i];
33958dc6 5919 if (page)
251f2acc
QW
5920 btrfs_page_clear_uptodate(fs_info, page,
5921 eb->start, eb->len);
1259ab75 5922 }
1259ab75
CM
5923}
5924
09c25a8c 5925void set_extent_buffer_uptodate(struct extent_buffer *eb)
d1310b2e 5926{
251f2acc 5927 struct btrfs_fs_info *fs_info = eb->fs_info;
d1310b2e 5928 struct page *page;
cc5e31a4 5929 int num_pages;
251f2acc 5930 int i;
d1310b2e 5931
0b32f4bb 5932 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
65ad0104 5933 num_pages = num_extent_pages(eb);
d1310b2e 5934 for (i = 0; i < num_pages; i++) {
fb85fc9a 5935 page = eb->pages[i];
251f2acc 5936 btrfs_page_set_uptodate(fs_info, page, eb->start, eb->len);
d1310b2e 5937 }
d1310b2e 5938}
d1310b2e 5939
4012daf7
QW
5940static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
5941 int mirror_num)
5942{
5943 struct btrfs_fs_info *fs_info = eb->fs_info;
5944 struct extent_io_tree *io_tree;
5945 struct page *page = eb->pages[0];
5946 struct bio *bio = NULL;
5947 int ret = 0;
5948
5949 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
5950 ASSERT(PagePrivate(page));
5951 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
5952
5953 if (wait == WAIT_NONE) {
5954 ret = try_lock_extent(io_tree, eb->start,
5955 eb->start + eb->len - 1);
5956 if (ret <= 0)
5957 return ret;
5958 } else {
5959 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1);
5960 if (ret < 0)
5961 return ret;
5962 }
5963
5964 ret = 0;
5965 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
5966 PageUptodate(page) ||
5967 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
5968 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5969 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1);
5970 return ret;
5971 }
5972
5973 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5974 eb->read_mirror = 0;
5975 atomic_set(&eb->io_pages, 1);
5976 check_buffer_tree_ref(eb);
5977 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
5978
5979 ret = submit_extent_page(REQ_OP_READ | REQ_META, NULL, page, eb->start,
5980 eb->len, eb->start - page_offset(page), &bio,
5981 end_bio_extent_readpage, mirror_num, 0, 0,
5982 true);
5983 if (ret) {
5984 /*
5985 * In the endio function, if we hit something wrong we will
5986 * increase the io_pages, so here we need to decrease it for
5987 * error path.
5988 */
5989 atomic_dec(&eb->io_pages);
5990 }
5991 if (bio) {
5992 int tmp;
5993
5994 tmp = submit_one_bio(bio, mirror_num, 0);
5995 if (tmp < 0)
5996 return tmp;
5997 }
5998 if (ret || wait != WAIT_COMPLETE)
5999 return ret;
6000
6001 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
6002 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6003 ret = -EIO;
6004 return ret;
6005}
6006
c2ccfbc6 6007int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
d1310b2e 6008{
cc5e31a4 6009 int i;
d1310b2e
CM
6010 struct page *page;
6011 int err;
6012 int ret = 0;
ce9adaa5
CM
6013 int locked_pages = 0;
6014 int all_uptodate = 1;
cc5e31a4 6015 int num_pages;
727011e0 6016 unsigned long num_reads = 0;
a86c12c7 6017 struct bio *bio = NULL;
c8b97818 6018 unsigned long bio_flags = 0;
a86c12c7 6019
b4ce94de 6020 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
d1310b2e
CM
6021 return 0;
6022
4012daf7
QW
6023 if (eb->fs_info->sectorsize < PAGE_SIZE)
6024 return read_extent_buffer_subpage(eb, wait, mirror_num);
6025
65ad0104 6026 num_pages = num_extent_pages(eb);
8436ea91 6027 for (i = 0; i < num_pages; i++) {
fb85fc9a 6028 page = eb->pages[i];
bb82ab88 6029 if (wait == WAIT_NONE) {
2c4d8cb7
QW
6030 /*
6031 * WAIT_NONE is only utilized by readahead. If we can't
6032 * acquire the lock atomically it means either the eb
6033 * is being read out or under modification.
6034 * Either way the eb will be or has been cached,
6035 * readahead can exit safely.
6036 */
2db04966 6037 if (!trylock_page(page))
ce9adaa5 6038 goto unlock_exit;
d1310b2e
CM
6039 } else {
6040 lock_page(page);
6041 }
ce9adaa5 6042 locked_pages++;
2571e739
LB
6043 }
6044 /*
6045 * We need to firstly lock all pages to make sure that
6046 * the uptodate bit of our pages won't be affected by
6047 * clear_extent_buffer_uptodate().
6048 */
8436ea91 6049 for (i = 0; i < num_pages; i++) {
2571e739 6050 page = eb->pages[i];
727011e0
CM
6051 if (!PageUptodate(page)) {
6052 num_reads++;
ce9adaa5 6053 all_uptodate = 0;
727011e0 6054 }
ce9adaa5 6055 }
2571e739 6056
ce9adaa5 6057 if (all_uptodate) {
8436ea91 6058 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
ce9adaa5
CM
6059 goto unlock_exit;
6060 }
6061
656f30db 6062 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5cf1ab56 6063 eb->read_mirror = 0;
0b32f4bb 6064 atomic_set(&eb->io_pages, num_reads);
6bf9cd2e
BB
6065 /*
6066 * It is possible for releasepage to clear the TREE_REF bit before we
6067 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
6068 */
6069 check_buffer_tree_ref(eb);
8436ea91 6070 for (i = 0; i < num_pages; i++) {
fb85fc9a 6071 page = eb->pages[i];
baf863b9 6072
ce9adaa5 6073 if (!PageUptodate(page)) {
baf863b9
LB
6074 if (ret) {
6075 atomic_dec(&eb->io_pages);
6076 unlock_page(page);
6077 continue;
6078 }
6079
f188591e 6080 ClearPageError(page);
0420177c
NB
6081 err = submit_extent_page(REQ_OP_READ | REQ_META, NULL,
6082 page, page_offset(page), PAGE_SIZE, 0,
6083 &bio, end_bio_extent_readpage,
6084 mirror_num, 0, 0, false);
baf863b9 6085 if (err) {
baf863b9 6086 /*
0420177c
NB
6087 * We failed to submit the bio so it's the
6088 * caller's responsibility to perform cleanup
6089 * i.e unlock page/set error bit.
baf863b9 6090 */
0420177c
NB
6091 ret = err;
6092 SetPageError(page);
6093 unlock_page(page);
baf863b9
LB
6094 atomic_dec(&eb->io_pages);
6095 }
d1310b2e
CM
6096 } else {
6097 unlock_page(page);
6098 }
6099 }
6100
355808c2 6101 if (bio) {
1f7ad75b 6102 err = submit_one_bio(bio, mirror_num, bio_flags);
79787eaa
JM
6103 if (err)
6104 return err;
355808c2 6105 }
a86c12c7 6106
bb82ab88 6107 if (ret || wait != WAIT_COMPLETE)
d1310b2e 6108 return ret;
d397712b 6109
8436ea91 6110 for (i = 0; i < num_pages; i++) {
fb85fc9a 6111 page = eb->pages[i];
d1310b2e 6112 wait_on_page_locked(page);
d397712b 6113 if (!PageUptodate(page))
d1310b2e 6114 ret = -EIO;
d1310b2e 6115 }
d397712b 6116
d1310b2e 6117 return ret;
ce9adaa5
CM
6118
6119unlock_exit:
d397712b 6120 while (locked_pages > 0) {
ce9adaa5 6121 locked_pages--;
8436ea91
JB
6122 page = eb->pages[locked_pages];
6123 unlock_page(page);
ce9adaa5
CM
6124 }
6125 return ret;
d1310b2e 6126}
d1310b2e 6127
f98b6215
QW
6128static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
6129 unsigned long len)
6130{
6131 btrfs_warn(eb->fs_info,
6132 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
6133 eb->start, eb->len, start, len);
6134 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
6135
6136 return true;
6137}
6138
6139/*
6140 * Check if the [start, start + len) range is valid before reading/writing
6141 * the eb.
6142 * NOTE: @start and @len are offset inside the eb, not logical address.
6143 *
6144 * Caller should not touch the dst/src memory if this function returns error.
6145 */
6146static inline int check_eb_range(const struct extent_buffer *eb,
6147 unsigned long start, unsigned long len)
6148{
6149 unsigned long offset;
6150
6151 /* start, start + len should not go beyond eb->len nor overflow */
6152 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
6153 return report_eb_range(eb, start, len);
6154
6155 return false;
6156}
6157
1cbb1f45
JM
6158void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
6159 unsigned long start, unsigned long len)
d1310b2e
CM
6160{
6161 size_t cur;
6162 size_t offset;
6163 struct page *page;
6164 char *kaddr;
6165 char *dst = (char *)dstv;
884b07d0 6166 unsigned long i = get_eb_page_index(start);
d1310b2e 6167
f98b6215 6168 if (check_eb_range(eb, start, len))
f716abd5 6169 return;
d1310b2e 6170
884b07d0 6171 offset = get_eb_offset_in_page(eb, start);
d1310b2e 6172
d397712b 6173 while (len > 0) {
fb85fc9a 6174 page = eb->pages[i];
d1310b2e 6175
09cbfeaf 6176 cur = min(len, (PAGE_SIZE - offset));
a6591715 6177 kaddr = page_address(page);
d1310b2e 6178 memcpy(dst, kaddr + offset, cur);
d1310b2e
CM
6179
6180 dst += cur;
6181 len -= cur;
6182 offset = 0;
6183 i++;
6184 }
6185}
d1310b2e 6186
a48b73ec
JB
6187int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
6188 void __user *dstv,
6189 unsigned long start, unsigned long len)
550ac1d8
GH
6190{
6191 size_t cur;
6192 size_t offset;
6193 struct page *page;
6194 char *kaddr;
6195 char __user *dst = (char __user *)dstv;
884b07d0 6196 unsigned long i = get_eb_page_index(start);
550ac1d8
GH
6197 int ret = 0;
6198
6199 WARN_ON(start > eb->len);
6200 WARN_ON(start + len > eb->start + eb->len);
6201
884b07d0 6202 offset = get_eb_offset_in_page(eb, start);
550ac1d8
GH
6203
6204 while (len > 0) {
fb85fc9a 6205 page = eb->pages[i];
550ac1d8 6206
09cbfeaf 6207 cur = min(len, (PAGE_SIZE - offset));
550ac1d8 6208 kaddr = page_address(page);
a48b73ec 6209 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
550ac1d8
GH
6210 ret = -EFAULT;
6211 break;
6212 }
6213
6214 dst += cur;
6215 len -= cur;
6216 offset = 0;
6217 i++;
6218 }
6219
6220 return ret;
6221}
6222
1cbb1f45
JM
6223int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
6224 unsigned long start, unsigned long len)
d1310b2e
CM
6225{
6226 size_t cur;
6227 size_t offset;
6228 struct page *page;
6229 char *kaddr;
6230 char *ptr = (char *)ptrv;
884b07d0 6231 unsigned long i = get_eb_page_index(start);
d1310b2e
CM
6232 int ret = 0;
6233
f98b6215
QW
6234 if (check_eb_range(eb, start, len))
6235 return -EINVAL;
d1310b2e 6236
884b07d0 6237 offset = get_eb_offset_in_page(eb, start);
d1310b2e 6238
d397712b 6239 while (len > 0) {
fb85fc9a 6240 page = eb->pages[i];
d1310b2e 6241
09cbfeaf 6242 cur = min(len, (PAGE_SIZE - offset));
d1310b2e 6243
a6591715 6244 kaddr = page_address(page);
d1310b2e 6245 ret = memcmp(ptr, kaddr + offset, cur);
d1310b2e
CM
6246 if (ret)
6247 break;
6248
6249 ptr += cur;
6250 len -= cur;
6251 offset = 0;
6252 i++;
6253 }
6254 return ret;
6255}
d1310b2e 6256
b8f95771
QW
6257/*
6258 * Check that the extent buffer is uptodate.
6259 *
6260 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
6261 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
6262 */
6263static void assert_eb_page_uptodate(const struct extent_buffer *eb,
6264 struct page *page)
6265{
6266 struct btrfs_fs_info *fs_info = eb->fs_info;
6267
6268 if (fs_info->sectorsize < PAGE_SIZE) {
6269 bool uptodate;
6270
6271 uptodate = btrfs_subpage_test_uptodate(fs_info, page,
6272 eb->start, eb->len);
6273 WARN_ON(!uptodate);
6274 } else {
6275 WARN_ON(!PageUptodate(page));
6276 }
6277}
6278
2b48966a 6279void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
f157bf76
DS
6280 const void *srcv)
6281{
6282 char *kaddr;
6283
b8f95771 6284 assert_eb_page_uptodate(eb, eb->pages[0]);
884b07d0 6285 kaddr = page_address(eb->pages[0]) + get_eb_offset_in_page(eb, 0);
f157bf76
DS
6286 memcpy(kaddr + offsetof(struct btrfs_header, chunk_tree_uuid), srcv,
6287 BTRFS_FSID_SIZE);
6288}
6289
2b48966a 6290void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
f157bf76
DS
6291{
6292 char *kaddr;
6293
b8f95771 6294 assert_eb_page_uptodate(eb, eb->pages[0]);
884b07d0 6295 kaddr = page_address(eb->pages[0]) + get_eb_offset_in_page(eb, 0);
f157bf76
DS
6296 memcpy(kaddr + offsetof(struct btrfs_header, fsid), srcv,
6297 BTRFS_FSID_SIZE);
6298}
6299
2b48966a 6300void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
d1310b2e
CM
6301 unsigned long start, unsigned long len)
6302{
6303 size_t cur;
6304 size_t offset;
6305 struct page *page;
6306 char *kaddr;
6307 char *src = (char *)srcv;
884b07d0 6308 unsigned long i = get_eb_page_index(start);
d1310b2e 6309
d3575156
NA
6310 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
6311
f98b6215
QW
6312 if (check_eb_range(eb, start, len))
6313 return;
d1310b2e 6314
884b07d0 6315 offset = get_eb_offset_in_page(eb, start);
d1310b2e 6316
d397712b 6317 while (len > 0) {
fb85fc9a 6318 page = eb->pages[i];
b8f95771 6319 assert_eb_page_uptodate(eb, page);
d1310b2e 6320
09cbfeaf 6321 cur = min(len, PAGE_SIZE - offset);
a6591715 6322 kaddr = page_address(page);
d1310b2e 6323 memcpy(kaddr + offset, src, cur);
d1310b2e
CM
6324
6325 src += cur;
6326 len -= cur;
6327 offset = 0;
6328 i++;
6329 }
6330}
d1310b2e 6331
2b48966a 6332void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
b159fa28 6333 unsigned long len)
d1310b2e
CM
6334{
6335 size_t cur;
6336 size_t offset;
6337 struct page *page;
6338 char *kaddr;
884b07d0 6339 unsigned long i = get_eb_page_index(start);
d1310b2e 6340
f98b6215
QW
6341 if (check_eb_range(eb, start, len))
6342 return;
d1310b2e 6343
884b07d0 6344 offset = get_eb_offset_in_page(eb, start);
d1310b2e 6345
d397712b 6346 while (len > 0) {
fb85fc9a 6347 page = eb->pages[i];
b8f95771 6348 assert_eb_page_uptodate(eb, page);
d1310b2e 6349
09cbfeaf 6350 cur = min(len, PAGE_SIZE - offset);
a6591715 6351 kaddr = page_address(page);
b159fa28 6352 memset(kaddr + offset, 0, cur);
d1310b2e
CM
6353
6354 len -= cur;
6355 offset = 0;
6356 i++;
6357 }
6358}
d1310b2e 6359
2b48966a
DS
6360void copy_extent_buffer_full(const struct extent_buffer *dst,
6361 const struct extent_buffer *src)
58e8012c
DS
6362{
6363 int i;
cc5e31a4 6364 int num_pages;
58e8012c
DS
6365
6366 ASSERT(dst->len == src->len);
6367
884b07d0
QW
6368 if (dst->fs_info->sectorsize == PAGE_SIZE) {
6369 num_pages = num_extent_pages(dst);
6370 for (i = 0; i < num_pages; i++)
6371 copy_page(page_address(dst->pages[i]),
6372 page_address(src->pages[i]));
6373 } else {
6374 size_t src_offset = get_eb_offset_in_page(src, 0);
6375 size_t dst_offset = get_eb_offset_in_page(dst, 0);
6376
6377 ASSERT(src->fs_info->sectorsize < PAGE_SIZE);
6378 memcpy(page_address(dst->pages[0]) + dst_offset,
6379 page_address(src->pages[0]) + src_offset,
6380 src->len);
6381 }
58e8012c
DS
6382}
6383
2b48966a
DS
6384void copy_extent_buffer(const struct extent_buffer *dst,
6385 const struct extent_buffer *src,
d1310b2e
CM
6386 unsigned long dst_offset, unsigned long src_offset,
6387 unsigned long len)
6388{
6389 u64 dst_len = dst->len;
6390 size_t cur;
6391 size_t offset;
6392 struct page *page;
6393 char *kaddr;
884b07d0 6394 unsigned long i = get_eb_page_index(dst_offset);
d1310b2e 6395
f98b6215
QW
6396 if (check_eb_range(dst, dst_offset, len) ||
6397 check_eb_range(src, src_offset, len))
6398 return;
6399
d1310b2e
CM
6400 WARN_ON(src->len != dst_len);
6401
884b07d0 6402 offset = get_eb_offset_in_page(dst, dst_offset);
d1310b2e 6403
d397712b 6404 while (len > 0) {
fb85fc9a 6405 page = dst->pages[i];
b8f95771 6406 assert_eb_page_uptodate(dst, page);
d1310b2e 6407
09cbfeaf 6408 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
d1310b2e 6409
a6591715 6410 kaddr = page_address(page);
d1310b2e 6411 read_extent_buffer(src, kaddr + offset, src_offset, cur);
d1310b2e
CM
6412
6413 src_offset += cur;
6414 len -= cur;
6415 offset = 0;
6416 i++;
6417 }
6418}
d1310b2e 6419
3e1e8bb7
OS
6420/*
6421 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
6422 * given bit number
6423 * @eb: the extent buffer
6424 * @start: offset of the bitmap item in the extent buffer
6425 * @nr: bit number
6426 * @page_index: return index of the page in the extent buffer that contains the
6427 * given bit number
6428 * @page_offset: return offset into the page given by page_index
6429 *
6430 * This helper hides the ugliness of finding the byte in an extent buffer which
6431 * contains a given bit.
6432 */
2b48966a 6433static inline void eb_bitmap_offset(const struct extent_buffer *eb,
3e1e8bb7
OS
6434 unsigned long start, unsigned long nr,
6435 unsigned long *page_index,
6436 size_t *page_offset)
6437{
3e1e8bb7
OS
6438 size_t byte_offset = BIT_BYTE(nr);
6439 size_t offset;
6440
6441 /*
6442 * The byte we want is the offset of the extent buffer + the offset of
6443 * the bitmap item in the extent buffer + the offset of the byte in the
6444 * bitmap item.
6445 */
884b07d0 6446 offset = start + offset_in_page(eb->start) + byte_offset;
3e1e8bb7 6447
09cbfeaf 6448 *page_index = offset >> PAGE_SHIFT;
7073017a 6449 *page_offset = offset_in_page(offset);
3e1e8bb7
OS
6450}
6451
6452/**
6453 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
6454 * @eb: the extent buffer
6455 * @start: offset of the bitmap item in the extent buffer
6456 * @nr: bit number to test
6457 */
2b48966a 6458int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
3e1e8bb7
OS
6459 unsigned long nr)
6460{
2fe1d551 6461 u8 *kaddr;
3e1e8bb7
OS
6462 struct page *page;
6463 unsigned long i;
6464 size_t offset;
6465
6466 eb_bitmap_offset(eb, start, nr, &i, &offset);
6467 page = eb->pages[i];
b8f95771 6468 assert_eb_page_uptodate(eb, page);
3e1e8bb7
OS
6469 kaddr = page_address(page);
6470 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
6471}
6472
6473/**
6474 * extent_buffer_bitmap_set - set an area of a bitmap
6475 * @eb: the extent buffer
6476 * @start: offset of the bitmap item in the extent buffer
6477 * @pos: bit number of the first bit
6478 * @len: number of bits to set
6479 */
2b48966a 6480void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
3e1e8bb7
OS
6481 unsigned long pos, unsigned long len)
6482{
2fe1d551 6483 u8 *kaddr;
3e1e8bb7
OS
6484 struct page *page;
6485 unsigned long i;
6486 size_t offset;
6487 const unsigned int size = pos + len;
6488 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
2fe1d551 6489 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
3e1e8bb7
OS
6490
6491 eb_bitmap_offset(eb, start, pos, &i, &offset);
6492 page = eb->pages[i];
b8f95771 6493 assert_eb_page_uptodate(eb, page);
3e1e8bb7
OS
6494 kaddr = page_address(page);
6495
6496 while (len >= bits_to_set) {
6497 kaddr[offset] |= mask_to_set;
6498 len -= bits_to_set;
6499 bits_to_set = BITS_PER_BYTE;
9c894696 6500 mask_to_set = ~0;
09cbfeaf 6501 if (++offset >= PAGE_SIZE && len > 0) {
3e1e8bb7
OS
6502 offset = 0;
6503 page = eb->pages[++i];
b8f95771 6504 assert_eb_page_uptodate(eb, page);
3e1e8bb7
OS
6505 kaddr = page_address(page);
6506 }
6507 }
6508 if (len) {
6509 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
6510 kaddr[offset] |= mask_to_set;
6511 }
6512}
6513
6514
6515/**
6516 * extent_buffer_bitmap_clear - clear an area of a bitmap
6517 * @eb: the extent buffer
6518 * @start: offset of the bitmap item in the extent buffer
6519 * @pos: bit number of the first bit
6520 * @len: number of bits to clear
6521 */
2b48966a
DS
6522void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
6523 unsigned long start, unsigned long pos,
6524 unsigned long len)
3e1e8bb7 6525{
2fe1d551 6526 u8 *kaddr;
3e1e8bb7
OS
6527 struct page *page;
6528 unsigned long i;
6529 size_t offset;
6530 const unsigned int size = pos + len;
6531 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
2fe1d551 6532 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
3e1e8bb7
OS
6533
6534 eb_bitmap_offset(eb, start, pos, &i, &offset);
6535 page = eb->pages[i];
b8f95771 6536 assert_eb_page_uptodate(eb, page);
3e1e8bb7
OS
6537 kaddr = page_address(page);
6538
6539 while (len >= bits_to_clear) {
6540 kaddr[offset] &= ~mask_to_clear;
6541 len -= bits_to_clear;
6542 bits_to_clear = BITS_PER_BYTE;
9c894696 6543 mask_to_clear = ~0;
09cbfeaf 6544 if (++offset >= PAGE_SIZE && len > 0) {
3e1e8bb7
OS
6545 offset = 0;
6546 page = eb->pages[++i];
b8f95771 6547 assert_eb_page_uptodate(eb, page);
3e1e8bb7
OS
6548 kaddr = page_address(page);
6549 }
6550 }
6551 if (len) {
6552 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
6553 kaddr[offset] &= ~mask_to_clear;
6554 }
6555}
6556
3387206f
ST
6557static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
6558{
6559 unsigned long distance = (src > dst) ? src - dst : dst - src;
6560 return distance < len;
6561}
6562
d1310b2e
CM
6563static void copy_pages(struct page *dst_page, struct page *src_page,
6564 unsigned long dst_off, unsigned long src_off,
6565 unsigned long len)
6566{
a6591715 6567 char *dst_kaddr = page_address(dst_page);
d1310b2e 6568 char *src_kaddr;
727011e0 6569 int must_memmove = 0;
d1310b2e 6570
3387206f 6571 if (dst_page != src_page) {
a6591715 6572 src_kaddr = page_address(src_page);
3387206f 6573 } else {
d1310b2e 6574 src_kaddr = dst_kaddr;
727011e0
CM
6575 if (areas_overlap(src_off, dst_off, len))
6576 must_memmove = 1;
3387206f 6577 }
d1310b2e 6578
727011e0
CM
6579 if (must_memmove)
6580 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
6581 else
6582 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
d1310b2e
CM
6583}
6584
2b48966a
DS
6585void memcpy_extent_buffer(const struct extent_buffer *dst,
6586 unsigned long dst_offset, unsigned long src_offset,
6587 unsigned long len)
d1310b2e
CM
6588{
6589 size_t cur;
6590 size_t dst_off_in_page;
6591 size_t src_off_in_page;
d1310b2e
CM
6592 unsigned long dst_i;
6593 unsigned long src_i;
6594
f98b6215
QW
6595 if (check_eb_range(dst, dst_offset, len) ||
6596 check_eb_range(dst, src_offset, len))
6597 return;
d1310b2e 6598
d397712b 6599 while (len > 0) {
884b07d0
QW
6600 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
6601 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
d1310b2e 6602
884b07d0
QW
6603 dst_i = get_eb_page_index(dst_offset);
6604 src_i = get_eb_page_index(src_offset);
d1310b2e 6605
09cbfeaf 6606 cur = min(len, (unsigned long)(PAGE_SIZE -
d1310b2e
CM
6607 src_off_in_page));
6608 cur = min_t(unsigned long, cur,
09cbfeaf 6609 (unsigned long)(PAGE_SIZE - dst_off_in_page));
d1310b2e 6610
fb85fc9a 6611 copy_pages(dst->pages[dst_i], dst->pages[src_i],
d1310b2e
CM
6612 dst_off_in_page, src_off_in_page, cur);
6613
6614 src_offset += cur;
6615 dst_offset += cur;
6616 len -= cur;
6617 }
6618}
d1310b2e 6619
2b48966a
DS
6620void memmove_extent_buffer(const struct extent_buffer *dst,
6621 unsigned long dst_offset, unsigned long src_offset,
6622 unsigned long len)
d1310b2e
CM
6623{
6624 size_t cur;
6625 size_t dst_off_in_page;
6626 size_t src_off_in_page;
6627 unsigned long dst_end = dst_offset + len - 1;
6628 unsigned long src_end = src_offset + len - 1;
d1310b2e
CM
6629 unsigned long dst_i;
6630 unsigned long src_i;
6631
f98b6215
QW
6632 if (check_eb_range(dst, dst_offset, len) ||
6633 check_eb_range(dst, src_offset, len))
6634 return;
727011e0 6635 if (dst_offset < src_offset) {
d1310b2e
CM
6636 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
6637 return;
6638 }
d397712b 6639 while (len > 0) {
884b07d0
QW
6640 dst_i = get_eb_page_index(dst_end);
6641 src_i = get_eb_page_index(src_end);
d1310b2e 6642
884b07d0
QW
6643 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
6644 src_off_in_page = get_eb_offset_in_page(dst, src_end);
d1310b2e
CM
6645
6646 cur = min_t(unsigned long, len, src_off_in_page + 1);
6647 cur = min(cur, dst_off_in_page + 1);
fb85fc9a 6648 copy_pages(dst->pages[dst_i], dst->pages[src_i],
d1310b2e
CM
6649 dst_off_in_page - cur + 1,
6650 src_off_in_page - cur + 1, cur);
6651
6652 dst_end -= cur;
6653 src_end -= cur;
6654 len -= cur;
6655 }
6656}
6af118ce 6657
d1e86e3f
QW
6658static struct extent_buffer *get_next_extent_buffer(
6659 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
6660{
6661 struct extent_buffer *gang[BTRFS_SUBPAGE_BITMAP_SIZE];
6662 struct extent_buffer *found = NULL;
6663 u64 page_start = page_offset(page);
6664 int ret;
6665 int i;
6666
6667 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
6668 ASSERT(PAGE_SIZE / fs_info->nodesize <= BTRFS_SUBPAGE_BITMAP_SIZE);
6669 lockdep_assert_held(&fs_info->buffer_lock);
6670
6671 ret = radix_tree_gang_lookup(&fs_info->buffer_radix, (void **)gang,
6672 bytenr >> fs_info->sectorsize_bits,
6673 PAGE_SIZE / fs_info->nodesize);
6674 for (i = 0; i < ret; i++) {
6675 /* Already beyond page end */
6676 if (gang[i]->start >= page_start + PAGE_SIZE)
6677 break;
6678 /* Found one */
6679 if (gang[i]->start >= bytenr) {
6680 found = gang[i];
6681 break;
6682 }
6683 }
6684 return found;
6685}
6686
6687static int try_release_subpage_extent_buffer(struct page *page)
6688{
6689 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
6690 u64 cur = page_offset(page);
6691 const u64 end = page_offset(page) + PAGE_SIZE;
6692 int ret;
6693
6694 while (cur < end) {
6695 struct extent_buffer *eb = NULL;
6696
6697 /*
6698 * Unlike try_release_extent_buffer() which uses page->private
6699 * to grab buffer, for subpage case we rely on radix tree, thus
6700 * we need to ensure radix tree consistency.
6701 *
6702 * We also want an atomic snapshot of the radix tree, thus go
6703 * with spinlock rather than RCU.
6704 */
6705 spin_lock(&fs_info->buffer_lock);
6706 eb = get_next_extent_buffer(fs_info, page, cur);
6707 if (!eb) {
6708 /* No more eb in the page range after or at cur */
6709 spin_unlock(&fs_info->buffer_lock);
6710 break;
6711 }
6712 cur = eb->start + eb->len;
6713
6714 /*
6715 * The same as try_release_extent_buffer(), to ensure the eb
6716 * won't disappear out from under us.
6717 */
6718 spin_lock(&eb->refs_lock);
6719 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
6720 spin_unlock(&eb->refs_lock);
6721 spin_unlock(&fs_info->buffer_lock);
6722 break;
6723 }
6724 spin_unlock(&fs_info->buffer_lock);
6725
6726 /*
6727 * If tree ref isn't set then we know the ref on this eb is a
6728 * real ref, so just return, this eb will likely be freed soon
6729 * anyway.
6730 */
6731 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6732 spin_unlock(&eb->refs_lock);
6733 break;
6734 }
6735
6736 /*
6737 * Here we don't care about the return value, we will always
6738 * check the page private at the end. And
6739 * release_extent_buffer() will release the refs_lock.
6740 */
6741 release_extent_buffer(eb);
6742 }
6743 /*
6744 * Finally to check if we have cleared page private, as if we have
6745 * released all ebs in the page, the page private should be cleared now.
6746 */
6747 spin_lock(&page->mapping->private_lock);
6748 if (!PagePrivate(page))
6749 ret = 1;
6750 else
6751 ret = 0;
6752 spin_unlock(&page->mapping->private_lock);
6753 return ret;
6754
6755}
6756
f7a52a40 6757int try_release_extent_buffer(struct page *page)
19fe0a8b 6758{
6af118ce 6759 struct extent_buffer *eb;
6af118ce 6760
d1e86e3f
QW
6761 if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
6762 return try_release_subpage_extent_buffer(page);
6763
3083ee2e 6764 /*
d1e86e3f
QW
6765 * We need to make sure nobody is changing page->private, as we rely on
6766 * page->private as the pointer to extent buffer.
3083ee2e
JB
6767 */
6768 spin_lock(&page->mapping->private_lock);
6769 if (!PagePrivate(page)) {
6770 spin_unlock(&page->mapping->private_lock);
4f2de97a 6771 return 1;
45f49bce 6772 }
6af118ce 6773
3083ee2e
JB
6774 eb = (struct extent_buffer *)page->private;
6775 BUG_ON(!eb);
19fe0a8b
MX
6776
6777 /*
3083ee2e
JB
6778 * This is a little awful but should be ok, we need to make sure that
6779 * the eb doesn't disappear out from under us while we're looking at
6780 * this page.
19fe0a8b 6781 */
3083ee2e 6782 spin_lock(&eb->refs_lock);
0b32f4bb 6783 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
3083ee2e
JB
6784 spin_unlock(&eb->refs_lock);
6785 spin_unlock(&page->mapping->private_lock);
6786 return 0;
b9473439 6787 }
3083ee2e 6788 spin_unlock(&page->mapping->private_lock);
897ca6e9 6789
19fe0a8b 6790 /*
3083ee2e
JB
6791 * If tree ref isn't set then we know the ref on this eb is a real ref,
6792 * so just return, this page will likely be freed soon anyway.
19fe0a8b 6793 */
3083ee2e
JB
6794 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6795 spin_unlock(&eb->refs_lock);
6796 return 0;
b9473439 6797 }
19fe0a8b 6798
f7a52a40 6799 return release_extent_buffer(eb);
6af118ce 6800}
bfb484d9
JB
6801
6802/*
6803 * btrfs_readahead_tree_block - attempt to readahead a child block
6804 * @fs_info: the fs_info
6805 * @bytenr: bytenr to read
3fbaf258 6806 * @owner_root: objectid of the root that owns this eb
bfb484d9 6807 * @gen: generation for the uptodate check, can be 0
3fbaf258 6808 * @level: level for the eb
bfb484d9
JB
6809 *
6810 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
6811 * normal uptodate check of the eb, without checking the generation. If we have
6812 * to read the block we will not block on anything.
6813 */
6814void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
3fbaf258 6815 u64 bytenr, u64 owner_root, u64 gen, int level)
bfb484d9
JB
6816{
6817 struct extent_buffer *eb;
6818 int ret;
6819
3fbaf258 6820 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
bfb484d9
JB
6821 if (IS_ERR(eb))
6822 return;
6823
6824 if (btrfs_buffer_uptodate(eb, gen, 1)) {
6825 free_extent_buffer(eb);
6826 return;
6827 }
6828
6829 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
6830 if (ret < 0)
6831 free_extent_buffer_stale(eb);
6832 else
6833 free_extent_buffer(eb);
6834}
6835
6836/*
6837 * btrfs_readahead_node_child - readahead a node's child block
6838 * @node: parent node we're reading from
6839 * @slot: slot in the parent node for the child we want to read
6840 *
6841 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
6842 * the slot in the node provided.
6843 */
6844void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
6845{
6846 btrfs_readahead_tree_block(node->fs_info,
6847 btrfs_node_blockptr(node, slot),
3fbaf258
JB
6848 btrfs_header_owner(node),
6849 btrfs_node_ptr_generation(node, slot),
6850 btrfs_header_level(node) - 1);
bfb484d9 6851}