]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - fs/btrfs/extent_io.c
btrfs: simplify eb checksum verification in btrfs_validate_metadata_buffer
[mirror_ubuntu-jammy-kernel.git] / fs / btrfs / extent_io.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
c1d7c514 2
d1310b2e
CM
3#include <linux/bitops.h>
4#include <linux/slab.h>
5#include <linux/bio.h>
6#include <linux/mm.h>
d1310b2e
CM
7#include <linux/pagemap.h>
8#include <linux/page-flags.h>
d1310b2e
CM
9#include <linux/spinlock.h>
10#include <linux/blkdev.h>
11#include <linux/swap.h>
d1310b2e
CM
12#include <linux/writeback.h>
13#include <linux/pagevec.h>
268bb0ce 14#include <linux/prefetch.h>
90a887c9 15#include <linux/cleancache.h>
cea62800 16#include "misc.h"
d1310b2e 17#include "extent_io.h"
9c7d3a54 18#include "extent-io-tree.h"
d1310b2e 19#include "extent_map.h"
902b22f3
DW
20#include "ctree.h"
21#include "btrfs_inode.h"
4a54c8c1 22#include "volumes.h"
21adbd5c 23#include "check-integrity.h"
0b32f4bb 24#include "locking.h"
606686ee 25#include "rcu-string.h"
fe09e16c 26#include "backref.h"
6af49dbd 27#include "disk-io.h"
760f991f 28#include "subpage.h"
d3575156 29#include "zoned.h"
0bc09ca1 30#include "block-group.h"
d1310b2e 31
d1310b2e
CM
32static struct kmem_cache *extent_state_cache;
33static struct kmem_cache *extent_buffer_cache;
8ac9f7c1 34static struct bio_set btrfs_bioset;
d1310b2e 35
27a3507d
FM
36static inline bool extent_state_in_tree(const struct extent_state *state)
37{
38 return !RB_EMPTY_NODE(&state->rb_node);
39}
40
6d49ba1b 41#ifdef CONFIG_BTRFS_DEBUG
d1310b2e 42static LIST_HEAD(states);
d397712b 43static DEFINE_SPINLOCK(leak_lock);
6d49ba1b 44
3fd63727
JB
45static inline void btrfs_leak_debug_add(spinlock_t *lock,
46 struct list_head *new,
47 struct list_head *head)
6d49ba1b
ES
48{
49 unsigned long flags;
50
3fd63727 51 spin_lock_irqsave(lock, flags);
6d49ba1b 52 list_add(new, head);
3fd63727 53 spin_unlock_irqrestore(lock, flags);
6d49ba1b
ES
54}
55
3fd63727
JB
56static inline void btrfs_leak_debug_del(spinlock_t *lock,
57 struct list_head *entry)
6d49ba1b
ES
58{
59 unsigned long flags;
60
3fd63727 61 spin_lock_irqsave(lock, flags);
6d49ba1b 62 list_del(entry);
3fd63727 63 spin_unlock_irqrestore(lock, flags);
6d49ba1b
ES
64}
65
3fd63727 66void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
6d49ba1b 67{
6d49ba1b 68 struct extent_buffer *eb;
3fd63727 69 unsigned long flags;
6d49ba1b 70
8c38938c
JB
71 /*
72 * If we didn't get into open_ctree our allocated_ebs will not be
73 * initialized, so just skip this.
74 */
75 if (!fs_info->allocated_ebs.next)
76 return;
77
3fd63727
JB
78 spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
79 while (!list_empty(&fs_info->allocated_ebs)) {
80 eb = list_first_entry(&fs_info->allocated_ebs,
81 struct extent_buffer, leak_list);
8c38938c
JB
82 pr_err(
83 "BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
84 eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
85 btrfs_header_owner(eb));
33ca832f
JB
86 list_del(&eb->leak_list);
87 kmem_cache_free(extent_buffer_cache, eb);
88 }
3fd63727 89 spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
33ca832f
JB
90}
91
92static inline void btrfs_extent_state_leak_debug_check(void)
93{
94 struct extent_state *state;
95
6d49ba1b
ES
96 while (!list_empty(&states)) {
97 state = list_entry(states.next, struct extent_state, leak_list);
9ee49a04 98 pr_err("BTRFS: state leak: start %llu end %llu state %u in tree %d refs %d\n",
27a3507d
FM
99 state->start, state->end, state->state,
100 extent_state_in_tree(state),
b7ac31b7 101 refcount_read(&state->refs));
6d49ba1b
ES
102 list_del(&state->leak_list);
103 kmem_cache_free(extent_state_cache, state);
104 }
6d49ba1b 105}
8d599ae1 106
a5dee37d
JB
107#define btrfs_debug_check_extent_io_range(tree, start, end) \
108 __btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
8d599ae1 109static inline void __btrfs_debug_check_extent_io_range(const char *caller,
a5dee37d 110 struct extent_io_tree *tree, u64 start, u64 end)
8d599ae1 111{
65a680f6
NB
112 struct inode *inode = tree->private_data;
113 u64 isize;
114
115 if (!inode || !is_data_inode(inode))
116 return;
117
118 isize = i_size_read(inode);
119 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
120 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
121 "%s: ino %llu isize %llu odd range [%llu,%llu]",
122 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
123 }
8d599ae1 124}
6d49ba1b 125#else
3fd63727
JB
126#define btrfs_leak_debug_add(lock, new, head) do {} while (0)
127#define btrfs_leak_debug_del(lock, entry) do {} while (0)
33ca832f 128#define btrfs_extent_state_leak_debug_check() do {} while (0)
8d599ae1 129#define btrfs_debug_check_extent_io_range(c, s, e) do {} while (0)
4bef0848 130#endif
d1310b2e 131
d1310b2e
CM
132struct tree_entry {
133 u64 start;
134 u64 end;
d1310b2e
CM
135 struct rb_node rb_node;
136};
137
138struct extent_page_data {
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
bc98a42c 2384 if (sb_rdonly(fs_info->sb))
908960c6 2385 goto out;
4a54c8c1 2386
7870d082
JB
2387 spin_lock(&io_tree->lock);
2388 state = find_first_extent_bit_state(io_tree,
4a54c8c1
JS
2389 failrec->start,
2390 EXTENT_LOCKED);
7870d082 2391 spin_unlock(&io_tree->lock);
4a54c8c1 2392
883d0de4
MX
2393 if (state && state->start <= failrec->start &&
2394 state->end >= failrec->start + failrec->len - 1) {
3ec706c8
SB
2395 num_copies = btrfs_num_copies(fs_info, failrec->logical,
2396 failrec->len);
4a54c8c1 2397 if (num_copies > 1) {
7870d082
JB
2398 repair_io_failure(fs_info, ino, start, failrec->len,
2399 failrec->logical, page, pg_offset,
2400 failrec->failed_mirror);
4a54c8c1
JS
2401 }
2402 }
2403
2404out:
7870d082 2405 free_io_failure(failure_tree, io_tree, failrec);
4a54c8c1 2406
454ff3de 2407 return 0;
4a54c8c1
JS
2408}
2409
f612496b
MX
2410/*
2411 * Can be called when
2412 * - hold extent lock
2413 * - under ordered extent
2414 * - the inode is freeing
2415 */
7ab7956e 2416void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
f612496b 2417{
7ab7956e 2418 struct extent_io_tree *failure_tree = &inode->io_failure_tree;
f612496b
MX
2419 struct io_failure_record *failrec;
2420 struct extent_state *state, *next;
2421
2422 if (RB_EMPTY_ROOT(&failure_tree->state))
2423 return;
2424
2425 spin_lock(&failure_tree->lock);
2426 state = find_first_extent_bit_state(failure_tree, start, EXTENT_DIRTY);
2427 while (state) {
2428 if (state->start > end)
2429 break;
2430
2431 ASSERT(state->end <= end);
2432
2433 next = next_state(state);
2434
47dc196a 2435 failrec = state->failrec;
f612496b
MX
2436 free_extent_state(state);
2437 kfree(failrec);
2438
2439 state = next;
2440 }
2441 spin_unlock(&failure_tree->lock);
2442}
2443
3526302f 2444static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
150e4b05 2445 u64 start)
4a54c8c1 2446{
ab8d0fc4 2447 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2fe6303e 2448 struct io_failure_record *failrec;
4a54c8c1 2449 struct extent_map *em;
4a54c8c1
JS
2450 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
2451 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2452 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
150e4b05 2453 const u32 sectorsize = fs_info->sectorsize;
4a54c8c1 2454 int ret;
4a54c8c1
JS
2455 u64 logical;
2456
2279a270 2457 failrec = get_state_failrec(failure_tree, start);
3526302f 2458 if (!IS_ERR(failrec)) {
ab8d0fc4 2459 btrfs_debug(fs_info,
1245835d
QW
2460 "Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu",
2461 failrec->logical, failrec->start, failrec->len);
4a54c8c1
JS
2462 /*
2463 * when data can be on disk more than twice, add to failrec here
2464 * (e.g. with a list for failed_mirror) to make
2465 * clean_io_failure() clean all those errors at once.
2466 */
3526302f
NB
2467
2468 return failrec;
4a54c8c1 2469 }
2fe6303e 2470
3526302f
NB
2471 failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
2472 if (!failrec)
2473 return ERR_PTR(-ENOMEM);
2fe6303e 2474
3526302f 2475 failrec->start = start;
150e4b05 2476 failrec->len = sectorsize;
3526302f
NB
2477 failrec->this_mirror = 0;
2478 failrec->bio_flags = 0;
3526302f
NB
2479
2480 read_lock(&em_tree->lock);
2481 em = lookup_extent_mapping(em_tree, start, failrec->len);
2482 if (!em) {
2483 read_unlock(&em_tree->lock);
2484 kfree(failrec);
2485 return ERR_PTR(-EIO);
2486 }
2487
2488 if (em->start > start || em->start + em->len <= start) {
2489 free_extent_map(em);
2490 em = NULL;
2491 }
2492 read_unlock(&em_tree->lock);
2493 if (!em) {
2494 kfree(failrec);
2495 return ERR_PTR(-EIO);
2496 }
2497
2498 logical = start - em->start;
2499 logical = em->block_start + logical;
2500 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
2501 logical = em->block_start;
2502 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
2503 extent_set_compress_type(&failrec->bio_flags, em->compress_type);
2504 }
2505
2506 btrfs_debug(fs_info,
2507 "Get IO Failure Record: (new) logical=%llu, start=%llu, len=%llu",
2508 logical, start, failrec->len);
2509
2510 failrec->logical = logical;
2511 free_extent_map(em);
2512
2513 /* Set the bits in the private failure tree */
150e4b05 2514 ret = set_extent_bits(failure_tree, start, start + sectorsize - 1,
3526302f
NB
2515 EXTENT_LOCKED | EXTENT_DIRTY);
2516 if (ret >= 0) {
2517 ret = set_state_failrec(failure_tree, start, failrec);
2518 /* Set the bits in the inode's tree */
150e4b05
QW
2519 ret = set_extent_bits(tree, start, start + sectorsize - 1,
2520 EXTENT_DAMAGED);
3526302f
NB
2521 } else if (ret < 0) {
2522 kfree(failrec);
2523 return ERR_PTR(ret);
2524 }
2525
2526 return failrec;
2fe6303e
MX
2527}
2528
1245835d 2529static bool btrfs_check_repairable(struct inode *inode,
ce06d3ec
OS
2530 struct io_failure_record *failrec,
2531 int failed_mirror)
2fe6303e 2532{
ab8d0fc4 2533 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2fe6303e
MX
2534 int num_copies;
2535
ab8d0fc4 2536 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
4a54c8c1
JS
2537 if (num_copies == 1) {
2538 /*
2539 * we only have a single copy of the data, so don't bother with
2540 * all the retry and error correction code that follows. no
2541 * matter what the error is, it is very likely to persist.
2542 */
ab8d0fc4
JM
2543 btrfs_debug(fs_info,
2544 "Check Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
2545 num_copies, failrec->this_mirror, failed_mirror);
c3cfb656 2546 return false;
4a54c8c1
JS
2547 }
2548
1245835d
QW
2549 /* The failure record should only contain one sector */
2550 ASSERT(failrec->len == fs_info->sectorsize);
2551
4a54c8c1 2552 /*
1245835d
QW
2553 * There are two premises:
2554 * a) deliver good data to the caller
2555 * b) correct the bad sectors on disk
2556 *
2557 * Since we're only doing repair for one sector, we only need to get
2558 * a good copy of the failed sector and if we succeed, we have setup
2559 * everything for repair_io_failure to do the rest for us.
4a54c8c1 2560 */
1245835d
QW
2561 failrec->failed_mirror = failed_mirror;
2562 failrec->this_mirror++;
2563 if (failrec->this_mirror == failed_mirror)
4a54c8c1 2564 failrec->this_mirror++;
4a54c8c1 2565
facc8a22 2566 if (failrec->this_mirror > num_copies) {
ab8d0fc4
JM
2567 btrfs_debug(fs_info,
2568 "Check Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
2569 num_copies, failrec->this_mirror, failed_mirror);
c3cfb656 2570 return false;
4a54c8c1
JS
2571 }
2572
c3cfb656 2573 return true;
2fe6303e
MX
2574}
2575
150e4b05
QW
2576int btrfs_repair_one_sector(struct inode *inode,
2577 struct bio *failed_bio, u32 bio_offset,
2578 struct page *page, unsigned int pgoff,
2579 u64 start, int failed_mirror,
2580 submit_bio_hook_t *submit_bio_hook)
2fe6303e
MX
2581{
2582 struct io_failure_record *failrec;
77d5d689 2583 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2fe6303e 2584 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
7870d082 2585 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
77d5d689 2586 struct btrfs_io_bio *failed_io_bio = btrfs_io_bio(failed_bio);
7ffd27e3 2587 const int icsum = bio_offset >> fs_info->sectorsize_bits;
77d5d689
OS
2588 struct bio *repair_bio;
2589 struct btrfs_io_bio *repair_io_bio;
4e4cbee9 2590 blk_status_t status;
2fe6303e 2591
77d5d689
OS
2592 btrfs_debug(fs_info,
2593 "repair read error: read error at %llu", start);
2fe6303e 2594
1f7ad75b 2595 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2fe6303e 2596
150e4b05 2597 failrec = btrfs_get_io_failure_record(inode, start);
3526302f 2598 if (IS_ERR(failrec))
150e4b05 2599 return PTR_ERR(failrec);
2fe6303e 2600
1245835d
QW
2601
2602 if (!btrfs_check_repairable(inode, failrec, failed_mirror)) {
7870d082 2603 free_io_failure(failure_tree, tree, failrec);
150e4b05 2604 return -EIO;
2fe6303e
MX
2605 }
2606
77d5d689
OS
2607 repair_bio = btrfs_io_bio_alloc(1);
2608 repair_io_bio = btrfs_io_bio(repair_bio);
2609 repair_bio->bi_opf = REQ_OP_READ;
77d5d689
OS
2610 repair_bio->bi_end_io = failed_bio->bi_end_io;
2611 repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
2612 repair_bio->bi_private = failed_bio->bi_private;
2fe6303e 2613
77d5d689 2614 if (failed_io_bio->csum) {
223486c2 2615 const u32 csum_size = fs_info->csum_size;
77d5d689
OS
2616
2617 repair_io_bio->csum = repair_io_bio->csum_inline;
2618 memcpy(repair_io_bio->csum,
2619 failed_io_bio->csum + csum_size * icsum, csum_size);
2620 }
2fe6303e 2621
77d5d689
OS
2622 bio_add_page(repair_bio, page, failrec->len, pgoff);
2623 repair_io_bio->logical = failrec->start;
2624 repair_io_bio->iter = repair_bio->bi_iter;
4a54c8c1 2625
ab8d0fc4 2626 btrfs_debug(btrfs_sb(inode->i_sb),
1245835d
QW
2627 "repair read error: submitting new read to mirror %d",
2628 failrec->this_mirror);
4a54c8c1 2629
77d5d689
OS
2630 status = submit_bio_hook(inode, repair_bio, failrec->this_mirror,
2631 failrec->bio_flags);
4e4cbee9 2632 if (status) {
7870d082 2633 free_io_failure(failure_tree, tree, failrec);
77d5d689 2634 bio_put(repair_bio);
6c387ab2 2635 }
150e4b05
QW
2636 return blk_status_to_errno(status);
2637}
2638
2639static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
2640{
2641 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2642
2643 ASSERT(page_offset(page) <= start &&
2644 start + len <= page_offset(page) + PAGE_SIZE);
2645
2646 /*
2647 * For subapge metadata case, all btrfs_page_* helpers need page to
2648 * have page::private populated.
2649 * But we can have rare case where the last eb in the page is only
2650 * referred by the IO, and it gets released immedately after it's
2651 * read and verified.
2652 *
2653 * This can detach the page private completely.
2654 * In that case, we can just skip the page status update completely,
2655 * as the page has no eb anymore.
2656 */
2657 if (fs_info->sectorsize < PAGE_SIZE && unlikely(!PagePrivate(page))) {
2658 ASSERT(!is_data_inode(page->mapping->host));
2659 return;
2660 }
2661 if (uptodate) {
2662 btrfs_page_set_uptodate(fs_info, page, start, len);
2663 } else {
2664 btrfs_page_clear_uptodate(fs_info, page, start, len);
2665 btrfs_page_set_error(fs_info, page, start, len);
2666 }
2667
2668 if (fs_info->sectorsize == PAGE_SIZE)
2669 unlock_page(page);
2670 else if (is_data_inode(page->mapping->host))
2671 /*
2672 * For subpage data, unlock the page if we're the last reader.
2673 * For subpage metadata, page lock is not utilized for read.
2674 */
2675 btrfs_subpage_end_reader(fs_info, page, start, len);
2676}
2677
2678static blk_status_t submit_read_repair(struct inode *inode,
2679 struct bio *failed_bio, u32 bio_offset,
2680 struct page *page, unsigned int pgoff,
2681 u64 start, u64 end, int failed_mirror,
2682 unsigned int error_bitmap,
2683 submit_bio_hook_t *submit_bio_hook)
2684{
2685 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2686 const u32 sectorsize = fs_info->sectorsize;
2687 const int nr_bits = (end + 1 - start) >> fs_info->sectorsize_bits;
2688 int error = 0;
2689 int i;
2690
2691 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
2692
2693 /* We're here because we had some read errors or csum mismatch */
2694 ASSERT(error_bitmap);
2695
2696 /*
2697 * We only get called on buffered IO, thus page must be mapped and bio
2698 * must not be cloned.
2699 */
2700 ASSERT(page->mapping && !bio_flagged(failed_bio, BIO_CLONED));
2701
2702 /* Iterate through all the sectors in the range */
2703 for (i = 0; i < nr_bits; i++) {
2704 const unsigned int offset = i * sectorsize;
2705 struct extent_state *cached = NULL;
2706 bool uptodate = false;
2707 int ret;
2708
2709 if (!(error_bitmap & (1U << i))) {
2710 /*
2711 * This sector has no error, just end the page read
2712 * and unlock the range.
2713 */
2714 uptodate = true;
2715 goto next;
2716 }
2717
2718 ret = btrfs_repair_one_sector(inode, failed_bio,
2719 bio_offset + offset,
2720 page, pgoff + offset, start + offset,
2721 failed_mirror, submit_bio_hook);
2722 if (!ret) {
2723 /*
2724 * We have submitted the read repair, the page release
2725 * will be handled by the endio function of the
2726 * submitted repair bio.
2727 * Thus we don't need to do any thing here.
2728 */
2729 continue;
2730 }
2731 /*
2732 * Repair failed, just record the error but still continue.
2733 * Or the remaining sectors will not be properly unlocked.
2734 */
2735 if (!error)
2736 error = ret;
2737next:
2738 end_page_read(page, uptodate, start + offset, sectorsize);
2739 if (uptodate)
2740 set_extent_uptodate(&BTRFS_I(inode)->io_tree,
2741 start + offset,
2742 start + offset + sectorsize - 1,
2743 &cached, GFP_ATOMIC);
2744 unlock_extent_cached_atomic(&BTRFS_I(inode)->io_tree,
2745 start + offset,
2746 start + offset + sectorsize - 1,
2747 &cached);
2748 }
2749 return errno_to_blk_status(error);
4a54c8c1
JS
2750}
2751
d1310b2e
CM
2752/* lots and lots of room for performance fixes in the end_bio funcs */
2753
b5227c07 2754void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
87826df0
JM
2755{
2756 int uptodate = (err == 0);
3e2426bd 2757 int ret = 0;
87826df0 2758
c629732d 2759 btrfs_writepage_endio_finish_ordered(page, start, end, uptodate);
87826df0 2760
87826df0 2761 if (!uptodate) {
87826df0
JM
2762 ClearPageUptodate(page);
2763 SetPageError(page);
bff5baf8 2764 ret = err < 0 ? err : -EIO;
5dca6eea 2765 mapping_set_error(page->mapping, ret);
87826df0 2766 }
87826df0
JM
2767}
2768
d1310b2e
CM
2769/*
2770 * after a writepage IO is done, we need to:
2771 * clear the uptodate bits on error
2772 * clear the writeback bits in the extent tree for this IO
2773 * end_page_writeback if the page has no more pending IO
2774 *
2775 * Scheduling is not allowed, so the extent state tree is expected
2776 * to have one and only one object corresponding to this IO.
2777 */
4246a0b6 2778static void end_bio_extent_writepage(struct bio *bio)
d1310b2e 2779{
4e4cbee9 2780 int error = blk_status_to_errno(bio->bi_status);
2c30c71b 2781 struct bio_vec *bvec;
d1310b2e
CM
2782 u64 start;
2783 u64 end;
6dc4f100 2784 struct bvec_iter_all iter_all;
d8e3fb10 2785 bool first_bvec = true;
d1310b2e 2786
c09abff8 2787 ASSERT(!bio_flagged(bio, BIO_CLONED));
2b070cfe 2788 bio_for_each_segment_all(bvec, bio, iter_all) {
d1310b2e 2789 struct page *page = bvec->bv_page;
0b246afa
JM
2790 struct inode *inode = page->mapping->host;
2791 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
902b22f3 2792
17a5adcc
AO
2793 /* We always issue full-page reads, but if some block
2794 * in a page fails to read, blk_update_request() will
2795 * advance bv_offset and adjust bv_len to compensate.
2796 * Print a warning for nonzero offsets, and an error
2797 * if they don't add up to a full page. */
09cbfeaf
KS
2798 if (bvec->bv_offset || bvec->bv_len != PAGE_SIZE) {
2799 if (bvec->bv_offset + bvec->bv_len != PAGE_SIZE)
0b246afa 2800 btrfs_err(fs_info,
efe120a0
FH
2801 "partial page write in btrfs with offset %u and length %u",
2802 bvec->bv_offset, bvec->bv_len);
2803 else
0b246afa 2804 btrfs_info(fs_info,
5d163e0e 2805 "incomplete page write in btrfs with offset %u and length %u",
efe120a0
FH
2806 bvec->bv_offset, bvec->bv_len);
2807 }
d1310b2e 2808
17a5adcc
AO
2809 start = page_offset(page);
2810 end = start + bvec->bv_offset + bvec->bv_len - 1;
d1310b2e 2811
d8e3fb10
NA
2812 if (first_bvec) {
2813 btrfs_record_physical_zoned(inode, start, bio);
2814 first_bvec = false;
2815 }
2816
4e4cbee9 2817 end_extent_writepage(page, error, start, end);
17a5adcc 2818 end_page_writeback(page);
2c30c71b 2819 }
2b1f55b0 2820
d1310b2e 2821 bio_put(bio);
d1310b2e
CM
2822}
2823
94e8c95c
QW
2824/*
2825 * Record previously processed extent range
2826 *
2827 * For endio_readpage_release_extent() to handle a full extent range, reducing
2828 * the extent io operations.
2829 */
2830struct processed_extent {
2831 struct btrfs_inode *inode;
2832 /* Start of the range in @inode */
2833 u64 start;
2e626e56 2834 /* End of the range in @inode */
94e8c95c
QW
2835 u64 end;
2836 bool uptodate;
2837};
2838
2839/*
2840 * Try to release processed extent range
2841 *
2842 * May not release the extent range right now if the current range is
2843 * contiguous to processed extent.
2844 *
2845 * Will release processed extent when any of @inode, @uptodate, the range is
2846 * no longer contiguous to the processed range.
2847 *
2848 * Passing @inode == NULL will force processed extent to be released.
2849 */
2850static void endio_readpage_release_extent(struct processed_extent *processed,
2851 struct btrfs_inode *inode, u64 start, u64 end,
2852 bool uptodate)
883d0de4
MX
2853{
2854 struct extent_state *cached = NULL;
94e8c95c
QW
2855 struct extent_io_tree *tree;
2856
2857 /* The first extent, initialize @processed */
2858 if (!processed->inode)
2859 goto update;
883d0de4 2860
94e8c95c
QW
2861 /*
2862 * Contiguous to processed extent, just uptodate the end.
2863 *
2864 * Several things to notice:
2865 *
2866 * - bio can be merged as long as on-disk bytenr is contiguous
2867 * This means we can have page belonging to other inodes, thus need to
2868 * check if the inode still matches.
2869 * - bvec can contain range beyond current page for multi-page bvec
2870 * Thus we need to do processed->end + 1 >= start check
2871 */
2872 if (processed->inode == inode && processed->uptodate == uptodate &&
2873 processed->end + 1 >= start && end >= processed->end) {
2874 processed->end = end;
2875 return;
2876 }
2877
2878 tree = &processed->inode->io_tree;
2879 /*
2880 * Now we don't have range contiguous to the processed range, release
2881 * the processed range now.
2882 */
2883 if (processed->uptodate && tree->track_uptodate)
2884 set_extent_uptodate(tree, processed->start, processed->end,
2885 &cached, GFP_ATOMIC);
2886 unlock_extent_cached_atomic(tree, processed->start, processed->end,
2887 &cached);
2888
2889update:
2890 /* Update processed to current range */
2891 processed->inode = inode;
2892 processed->start = start;
2893 processed->end = end;
2894 processed->uptodate = uptodate;
883d0de4
MX
2895}
2896
92082d40
QW
2897static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
2898{
2899 ASSERT(PageLocked(page));
2900 if (fs_info->sectorsize == PAGE_SIZE)
2901 return;
2902
2903 ASSERT(PagePrivate(page));
2904 btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
2905}
2906
d9bb77d5
QW
2907/*
2908 * Find extent buffer for a givne bytenr.
2909 *
2910 * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
2911 * in endio context.
2912 */
2913static struct extent_buffer *find_extent_buffer_readpage(
2914 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
2915{
2916 struct extent_buffer *eb;
2917
2918 /*
2919 * For regular sectorsize, we can use page->private to grab extent
2920 * buffer
2921 */
2922 if (fs_info->sectorsize == PAGE_SIZE) {
2923 ASSERT(PagePrivate(page) && page->private);
2924 return (struct extent_buffer *)page->private;
2925 }
2926
2927 /* For subpage case, we need to lookup buffer radix tree */
2928 rcu_read_lock();
2929 eb = radix_tree_lookup(&fs_info->buffer_radix,
2930 bytenr >> fs_info->sectorsize_bits);
2931 rcu_read_unlock();
2932 ASSERT(eb);
2933 return eb;
2934}
2935
d1310b2e
CM
2936/*
2937 * after a readpage IO is done, we need to:
2938 * clear the uptodate bits on error
2939 * set the uptodate bits if things worked
2940 * set the page up to date if all extents in the tree are uptodate
2941 * clear the lock bit in the extent tree
2942 * unlock the page if there are no other extents locked for it
2943 *
2944 * Scheduling is not allowed, so the extent state tree is expected
2945 * to have one and only one object corresponding to this IO.
2946 */
4246a0b6 2947static void end_bio_extent_readpage(struct bio *bio)
d1310b2e 2948{
2c30c71b 2949 struct bio_vec *bvec;
facc8a22 2950 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7870d082 2951 struct extent_io_tree *tree, *failure_tree;
94e8c95c 2952 struct processed_extent processed = { 0 };
7ffd27e3
QW
2953 /*
2954 * The offset to the beginning of a bio, since one bio can never be
2955 * larger than UINT_MAX, u32 here is enough.
2956 */
2957 u32 bio_offset = 0;
5cf1ab56 2958 int mirror;
d1310b2e 2959 int ret;
6dc4f100 2960 struct bvec_iter_all iter_all;
d1310b2e 2961
c09abff8 2962 ASSERT(!bio_flagged(bio, BIO_CLONED));
2b070cfe 2963 bio_for_each_segment_all(bvec, bio, iter_all) {
150e4b05 2964 bool uptodate = !bio->bi_status;
d1310b2e 2965 struct page *page = bvec->bv_page;
a71754fc 2966 struct inode *inode = page->mapping->host;
ab8d0fc4 2967 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7ffd27e3 2968 const u32 sectorsize = fs_info->sectorsize;
150e4b05 2969 unsigned int error_bitmap = (unsigned int)-1;
7ffd27e3
QW
2970 u64 start;
2971 u64 end;
2972 u32 len;
507903b8 2973
ab8d0fc4
JM
2974 btrfs_debug(fs_info,
2975 "end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
1201b58b 2976 bio->bi_iter.bi_sector, bio->bi_status,
ab8d0fc4 2977 io_bio->mirror_num);
a71754fc 2978 tree = &BTRFS_I(inode)->io_tree;
7870d082 2979 failure_tree = &BTRFS_I(inode)->io_failure_tree;
902b22f3 2980
8b8bbd46
QW
2981 /*
2982 * We always issue full-sector reads, but if some block in a
2983 * page fails to read, blk_update_request() will advance
2984 * bv_offset and adjust bv_len to compensate. Print a warning
2985 * for unaligned offsets, and an error if they don't add up to
2986 * a full sector.
2987 */
2988 if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
2989 btrfs_err(fs_info,
2990 "partial page read in btrfs with offset %u and length %u",
2991 bvec->bv_offset, bvec->bv_len);
2992 else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
2993 sectorsize))
2994 btrfs_info(fs_info,
2995 "incomplete page read with offset %u and length %u",
2996 bvec->bv_offset, bvec->bv_len);
2997
2998 start = page_offset(page) + bvec->bv_offset;
2999 end = start + bvec->bv_len - 1;
facc8a22 3000 len = bvec->bv_len;
d1310b2e 3001
9be3395b 3002 mirror = io_bio->mirror_num;
78e62c02 3003 if (likely(uptodate)) {
150e4b05
QW
3004 if (is_data_inode(inode)) {
3005 error_bitmap = btrfs_verify_data_csum(io_bio,
5e295768 3006 bio_offset, page, start, end);
150e4b05
QW
3007 ret = error_bitmap;
3008 } else {
9a446d6a 3009 ret = btrfs_validate_metadata_buffer(io_bio,
8e1dc982 3010 page, start, end, mirror);
150e4b05 3011 }
5ee0844d 3012 if (ret)
150e4b05 3013 uptodate = false;
5ee0844d 3014 else
7870d082
JB
3015 clean_io_failure(BTRFS_I(inode)->root->fs_info,
3016 failure_tree, tree, start,
3017 page,
3018 btrfs_ino(BTRFS_I(inode)), 0);
d1310b2e 3019 }
ea466794 3020
f2a09da9
MX
3021 if (likely(uptodate))
3022 goto readpage_ok;
3023
be17b3af 3024 if (is_data_inode(inode)) {
f4a8e656 3025 /*
150e4b05
QW
3026 * btrfs_submit_read_repair() will handle all the good
3027 * and bad sectors, we just continue to the next bvec.
f4a8e656 3028 */
150e4b05
QW
3029 submit_read_repair(inode, bio, bio_offset, page,
3030 start - page_offset(page), start,
3031 end, mirror, error_bitmap,
3032 btrfs_submit_data_bio);
3033
3034 ASSERT(bio_offset + len > bio_offset);
3035 bio_offset += len;
3036 continue;
78e62c02
NB
3037 } else {
3038 struct extent_buffer *eb;
3039
d9bb77d5 3040 eb = find_extent_buffer_readpage(fs_info, page, start);
78e62c02
NB
3041 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
3042 eb->read_mirror = mirror;
3043 atomic_dec(&eb->io_pages);
3044 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD,
3045 &eb->bflags))
3046 btree_readahead_hook(eb, -EIO);
7e38326f 3047 }
f2a09da9 3048readpage_ok:
883d0de4 3049 if (likely(uptodate)) {
a71754fc 3050 loff_t i_size = i_size_read(inode);
09cbfeaf 3051 pgoff_t end_index = i_size >> PAGE_SHIFT;
a71754fc 3052
c28ea613
QW
3053 /*
3054 * Zero out the remaining part if this range straddles
3055 * i_size.
3056 *
3057 * Here we should only zero the range inside the bvec,
3058 * not touch anything else.
3059 *
3060 * NOTE: i_size is exclusive while end is inclusive.
3061 */
3062 if (page->index == end_index && i_size <= end) {
3063 u32 zero_start = max(offset_in_page(i_size),
d2dcc8ed 3064 offset_in_page(start));
c28ea613
QW
3065
3066 zero_user_segment(page, zero_start,
3067 offset_in_page(end) + 1);
3068 }
70dec807 3069 }
7ffd27e3
QW
3070 ASSERT(bio_offset + len > bio_offset);
3071 bio_offset += len;
883d0de4 3072
e09caaf9 3073 /* Update page status and unlock */
92082d40 3074 end_page_read(page, uptodate, start, len);
94e8c95c
QW
3075 endio_readpage_release_extent(&processed, BTRFS_I(inode),
3076 start, end, uptodate);
2c30c71b 3077 }
94e8c95c
QW
3078 /* Release the last extent */
3079 endio_readpage_release_extent(&processed, NULL, 0, 0, false);
b3a0dd50 3080 btrfs_io_bio_free_csum(io_bio);
d1310b2e 3081 bio_put(bio);
d1310b2e
CM
3082}
3083
9be3395b 3084/*
184f999e
DS
3085 * Initialize the members up to but not including 'bio'. Use after allocating a
3086 * new bio by bio_alloc_bioset as it does not initialize the bytes outside of
3087 * 'bio' because use of __GFP_ZERO is not supported.
9be3395b 3088 */
184f999e 3089static inline void btrfs_io_bio_init(struct btrfs_io_bio *btrfs_bio)
d1310b2e 3090{
184f999e
DS
3091 memset(btrfs_bio, 0, offsetof(struct btrfs_io_bio, bio));
3092}
d1310b2e 3093
9be3395b 3094/*
6e707bcd
DS
3095 * The following helpers allocate a bio. As it's backed by a bioset, it'll
3096 * never fail. We're returning a bio right now but you can call btrfs_io_bio
3097 * for the appropriate container_of magic
9be3395b 3098 */
e749af44 3099struct bio *btrfs_bio_alloc(u64 first_byte)
d1310b2e
CM
3100{
3101 struct bio *bio;
d1310b2e 3102
a8affc03 3103 bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_VECS, &btrfs_bioset);
c821e7f3 3104 bio->bi_iter.bi_sector = first_byte >> 9;
184f999e 3105 btrfs_io_bio_init(btrfs_io_bio(bio));
d1310b2e
CM
3106 return bio;
3107}
3108
8b6c1d56 3109struct bio *btrfs_bio_clone(struct bio *bio)
9be3395b 3110{
23ea8e5a
MX
3111 struct btrfs_io_bio *btrfs_bio;
3112 struct bio *new;
9be3395b 3113
6e707bcd 3114 /* Bio allocation backed by a bioset does not fail */
8ac9f7c1 3115 new = bio_clone_fast(bio, GFP_NOFS, &btrfs_bioset);
6e707bcd 3116 btrfs_bio = btrfs_io_bio(new);
184f999e 3117 btrfs_io_bio_init(btrfs_bio);
6e707bcd 3118 btrfs_bio->iter = bio->bi_iter;
23ea8e5a
MX
3119 return new;
3120}
9be3395b 3121
c5e4c3d7 3122struct bio *btrfs_io_bio_alloc(unsigned int nr_iovecs)
9be3395b 3123{
facc8a22
MX
3124 struct bio *bio;
3125
6e707bcd 3126 /* Bio allocation backed by a bioset does not fail */
8ac9f7c1 3127 bio = bio_alloc_bioset(GFP_NOFS, nr_iovecs, &btrfs_bioset);
184f999e 3128 btrfs_io_bio_init(btrfs_io_bio(bio));
facc8a22 3129 return bio;
9be3395b
CM
3130}
3131
e477094f 3132struct bio *btrfs_bio_clone_partial(struct bio *orig, int offset, int size)
2f8e9140
LB
3133{
3134 struct bio *bio;
3135 struct btrfs_io_bio *btrfs_bio;
3136
3137 /* this will never fail when it's backed by a bioset */
8ac9f7c1 3138 bio = bio_clone_fast(orig, GFP_NOFS, &btrfs_bioset);
2f8e9140
LB
3139 ASSERT(bio);
3140
3141 btrfs_bio = btrfs_io_bio(bio);
184f999e 3142 btrfs_io_bio_init(btrfs_bio);
2f8e9140
LB
3143
3144 bio_trim(bio, offset >> 9, size >> 9);
17347cec 3145 btrfs_bio->iter = bio->bi_iter;
2f8e9140
LB
3146 return bio;
3147}
9be3395b 3148
953651eb
NA
3149/**
3150 * Attempt to add a page to bio
3151 *
3152 * @bio: destination bio
3153 * @page: page to add to the bio
3154 * @disk_bytenr: offset of the new bio or to check whether we are adding
3155 * a contiguous page to the previous one
3156 * @pg_offset: starting offset in the page
3157 * @size: portion of page that we want to write
3158 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3159 * @bio_flags: flags of the current bio to see if we can merge them
3160 * @return: true if page was added, false otherwise
3161 *
3162 * Attempt to add a page to bio considering stripe alignment etc.
3163 *
3164 * Return true if successfully page added. Otherwise, return false.
3165 */
3166static bool btrfs_bio_add_page(struct bio *bio, struct page *page,
3167 u64 disk_bytenr, unsigned int size,
3168 unsigned int pg_offset,
3169 unsigned long prev_bio_flags,
3170 unsigned long bio_flags)
3171{
3172 const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
3173 bool contig;
e1326f03 3174 int ret;
953651eb
NA
3175
3176 if (prev_bio_flags != bio_flags)
3177 return false;
3178
3179 if (prev_bio_flags & EXTENT_BIO_COMPRESSED)
3180 contig = bio->bi_iter.bi_sector == sector;
3181 else
3182 contig = bio_end_sector(bio) == sector;
3183 if (!contig)
3184 return false;
3185
3186 if (btrfs_bio_fits_in_stripe(page, size, bio, bio_flags))
3187 return false;
3188
cacb2cea
JT
3189 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
3190 struct page *first_page = bio_first_bvec_all(bio)->bv_page;
3191
3192 if (!btrfs_bio_fits_in_ordered_extent(first_page, bio, size))
3193 return false;
e1326f03 3194 ret = bio_add_zone_append_page(bio, page, size, pg_offset);
cacb2cea 3195 } else {
e1326f03 3196 ret = bio_add_page(bio, page, size, pg_offset);
cacb2cea 3197 }
e1326f03
NA
3198
3199 return ret == size;
953651eb
NA
3200}
3201
4b81ba48
DS
3202/*
3203 * @opf: bio REQ_OP_* and REQ_* flags as one value
b8b3d625
DS
3204 * @wbc: optional writeback control for io accounting
3205 * @page: page to add to the bio
0c64c33c
QW
3206 * @disk_bytenr: logical bytenr where the write will be
3207 * @size: portion of page that we want to write to
b8b3d625
DS
3208 * @pg_offset: offset of the new bio or to check whether we are adding
3209 * a contiguous page to the previous one
5c2b1fd7 3210 * @bio_ret: must be valid pointer, newly allocated bio will be stored there
b8b3d625
DS
3211 * @end_io_func: end_io callback for new bio
3212 * @mirror_num: desired mirror to read/write
3213 * @prev_bio_flags: flags of previous bio to see if we can merge the current one
3214 * @bio_flags: flags of the current bio to see if we can merge them
4b81ba48 3215 */
0ceb34bf 3216static int submit_extent_page(unsigned int opf,
da2f0f74 3217 struct writeback_control *wbc,
0c64c33c 3218 struct page *page, u64 disk_bytenr,
6c5a4e2c 3219 size_t size, unsigned long pg_offset,
d1310b2e 3220 struct bio **bio_ret,
f188591e 3221 bio_end_io_t end_io_func,
c8b97818
CM
3222 int mirror_num,
3223 unsigned long prev_bio_flags,
005efedf
FM
3224 unsigned long bio_flags,
3225 bool force_bio_submit)
d1310b2e
CM
3226{
3227 int ret = 0;
3228 struct bio *bio;
e940e9a7 3229 size_t io_size = min_t(size_t, size, PAGE_SIZE);
e1326f03
NA
3230 struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3231 struct extent_io_tree *tree = &inode->io_tree;
3232 struct btrfs_fs_info *fs_info = inode->root->fs_info;
d1310b2e 3233
5c2b1fd7
DS
3234 ASSERT(bio_ret);
3235
3236 if (*bio_ret) {
d1310b2e 3237 bio = *bio_ret;
953651eb
NA
3238 if (force_bio_submit ||
3239 !btrfs_bio_add_page(bio, page, disk_bytenr, io_size,
3240 pg_offset, prev_bio_flags, bio_flags)) {
1f7ad75b 3241 ret = submit_one_bio(bio, mirror_num, prev_bio_flags);
289454ad
NA
3242 if (ret < 0) {
3243 *bio_ret = NULL;
79787eaa 3244 return ret;
289454ad 3245 }
d1310b2e
CM
3246 bio = NULL;
3247 } else {
da2f0f74 3248 if (wbc)
e940e9a7 3249 wbc_account_cgroup_owner(wbc, page, io_size);
d1310b2e
CM
3250 return 0;
3251 }
3252 }
c8b97818 3253
0c64c33c 3254 bio = btrfs_bio_alloc(disk_bytenr);
e940e9a7 3255 bio_add_page(bio, page, io_size, pg_offset);
d1310b2e
CM
3256 bio->bi_end_io = end_io_func;
3257 bio->bi_private = tree;
e6959b93 3258 bio->bi_write_hint = page->mapping->host->i_write_hint;
4b81ba48 3259 bio->bi_opf = opf;
da2f0f74 3260 if (wbc) {
429aebc0
DS
3261 struct block_device *bdev;
3262
e1326f03 3263 bdev = fs_info->fs_devices->latest_bdev;
429aebc0 3264 bio_set_dev(bio, bdev);
da2f0f74 3265 wbc_init_bio(wbc, bio);
e940e9a7 3266 wbc_account_cgroup_owner(wbc, page, io_size);
da2f0f74 3267 }
e1326f03 3268 if (btrfs_is_zoned(fs_info) && bio_op(bio) == REQ_OP_ZONE_APPEND) {
e7ff9e6b 3269 struct btrfs_device *device;
e1326f03 3270
e7ff9e6b
JT
3271 device = btrfs_zoned_get_device(fs_info, disk_bytenr, io_size);
3272 if (IS_ERR(device))
3273 return PTR_ERR(device);
e1326f03 3274
e7ff9e6b 3275 btrfs_io_bio(bio)->device = device;
e1326f03 3276 }
70dec807 3277
5c2b1fd7 3278 *bio_ret = bio;
d1310b2e
CM
3279
3280 return ret;
3281}
3282
760f991f
QW
3283static int attach_extent_buffer_page(struct extent_buffer *eb,
3284 struct page *page,
3285 struct btrfs_subpage *prealloc)
d1310b2e 3286{
760f991f
QW
3287 struct btrfs_fs_info *fs_info = eb->fs_info;
3288 int ret = 0;
3289
0d01e247
QW
3290 /*
3291 * If the page is mapped to btree inode, we should hold the private
3292 * lock to prevent race.
3293 * For cloned or dummy extent buffers, their pages are not mapped and
3294 * will not race with any other ebs.
3295 */
3296 if (page->mapping)
3297 lockdep_assert_held(&page->mapping->private_lock);
3298
760f991f
QW
3299 if (fs_info->sectorsize == PAGE_SIZE) {
3300 if (!PagePrivate(page))
3301 attach_page_private(page, eb);
3302 else
3303 WARN_ON(page->private != (unsigned long)eb);
3304 return 0;
3305 }
3306
3307 /* Already mapped, just free prealloc */
3308 if (PagePrivate(page)) {
3309 btrfs_free_subpage(prealloc);
3310 return 0;
3311 }
3312
3313 if (prealloc)
3314 /* Has preallocated memory for subpage */
3315 attach_page_private(page, prealloc);
d1b89bc0 3316 else
760f991f
QW
3317 /* Do new allocation to attach subpage */
3318 ret = btrfs_attach_subpage(fs_info, page,
3319 BTRFS_SUBPAGE_METADATA);
3320 return ret;
d1310b2e
CM
3321}
3322
32443de3 3323int set_page_extent_mapped(struct page *page)
d1310b2e 3324{
32443de3
QW
3325 struct btrfs_fs_info *fs_info;
3326
3327 ASSERT(page->mapping);
3328
3329 if (PagePrivate(page))
3330 return 0;
3331
3332 fs_info = btrfs_sb(page->mapping->host->i_sb);
3333
3334 if (fs_info->sectorsize < PAGE_SIZE)
3335 return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
3336
3337 attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
3338 return 0;
3339}
3340
3341void clear_page_extent_mapped(struct page *page)
3342{
3343 struct btrfs_fs_info *fs_info;
3344
3345 ASSERT(page->mapping);
3346
d1b89bc0 3347 if (!PagePrivate(page))
32443de3
QW
3348 return;
3349
3350 fs_info = btrfs_sb(page->mapping->host->i_sb);
3351 if (fs_info->sectorsize < PAGE_SIZE)
3352 return btrfs_detach_subpage(fs_info, page);
3353
3354 detach_page_private(page);
d1310b2e
CM
3355}
3356
125bac01
MX
3357static struct extent_map *
3358__get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
1a5ee1e6 3359 u64 start, u64 len, struct extent_map **em_cached)
125bac01
MX
3360{
3361 struct extent_map *em;
3362
3363 if (em_cached && *em_cached) {
3364 em = *em_cached;
cbc0e928 3365 if (extent_map_in_tree(em) && start >= em->start &&
125bac01 3366 start < extent_map_end(em)) {
490b54d6 3367 refcount_inc(&em->refs);
125bac01
MX
3368 return em;
3369 }
3370
3371 free_extent_map(em);
3372 *em_cached = NULL;
3373 }
3374
1a5ee1e6 3375 em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
125bac01
MX
3376 if (em_cached && !IS_ERR_OR_NULL(em)) {
3377 BUG_ON(*em_cached);
490b54d6 3378 refcount_inc(&em->refs);
125bac01
MX
3379 *em_cached = em;
3380 }
3381 return em;
3382}
d1310b2e
CM
3383/*
3384 * basic readpage implementation. Locked extent state structs are inserted
3385 * into the tree that are removed when the IO is done (by the end_io
3386 * handlers)
79787eaa 3387 * XXX JDM: This needs looking at to ensure proper page locking
baf863b9 3388 * return 0 on success, otherwise return error
d1310b2e 3389 */
0f208812
NB
3390int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
3391 struct bio **bio, unsigned long *bio_flags,
3392 unsigned int read_flags, u64 *prev_em_start)
d1310b2e
CM
3393{
3394 struct inode *inode = page->mapping->host;
92082d40 3395 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4eee4fa4 3396 u64 start = page_offset(page);
8eec8296 3397 const u64 end = start + PAGE_SIZE - 1;
d1310b2e
CM
3398 u64 cur = start;
3399 u64 extent_offset;
3400 u64 last_byte = i_size_read(inode);
3401 u64 block_start;
3402 u64 cur_end;
d1310b2e 3403 struct extent_map *em;
baf863b9 3404 int ret = 0;
d1310b2e 3405 int nr = 0;
306e16ce 3406 size_t pg_offset = 0;
d1310b2e
CM
3407 size_t iosize;
3408 size_t blocksize = inode->i_sb->s_blocksize;
7f042a83 3409 unsigned long this_bio_flag = 0;
f657a31c 3410 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
ae6957eb 3411
32443de3
QW
3412 ret = set_page_extent_mapped(page);
3413 if (ret < 0) {
3414 unlock_extent(tree, start, end);
92082d40
QW
3415 btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
3416 unlock_page(page);
32443de3
QW
3417 goto out;
3418 }
d1310b2e 3419
90a887c9
DM
3420 if (!PageUptodate(page)) {
3421 if (cleancache_get_page(page) == 0) {
3422 BUG_ON(blocksize != PAGE_SIZE);
9974090b 3423 unlock_extent(tree, start, end);
92082d40 3424 unlock_page(page);
90a887c9
DM
3425 goto out;
3426 }
3427 }
3428
09cbfeaf 3429 if (page->index == last_byte >> PAGE_SHIFT) {
7073017a 3430 size_t zero_offset = offset_in_page(last_byte);
c8b97818
CM
3431
3432 if (zero_offset) {
09cbfeaf 3433 iosize = PAGE_SIZE - zero_offset;
d048b9c2 3434 memzero_page(page, zero_offset, iosize);
c8b97818 3435 flush_dcache_page(page);
c8b97818
CM
3436 }
3437 }
92082d40 3438 begin_page_read(fs_info, page);
d1310b2e 3439 while (cur <= end) {
005efedf 3440 bool force_bio_submit = false;
0c64c33c 3441 u64 disk_bytenr;
c8f2f24b 3442
d1310b2e 3443 if (cur >= last_byte) {
507903b8
AJ
3444 struct extent_state *cached = NULL;
3445
09cbfeaf 3446 iosize = PAGE_SIZE - pg_offset;
d048b9c2 3447 memzero_page(page, pg_offset, iosize);
d1310b2e 3448 flush_dcache_page(page);
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) {
507903b8
AJ
3531 struct extent_state *cached = NULL;
3532
d048b9c2 3533 memzero_page(page, pg_offset, iosize);
d1310b2e 3534 flush_dcache_page(page);
d1310b2e
CM
3535
3536 set_extent_uptodate(tree, cur, cur + iosize - 1,
507903b8 3537 &cached, GFP_NOFS);
7f042a83 3538 unlock_extent_cached(tree, cur,
e43bbe5e 3539 cur + iosize - 1, &cached);
92082d40 3540 end_page_read(page, true, cur, iosize);
d1310b2e 3541 cur = cur + iosize;
306e16ce 3542 pg_offset += iosize;
d1310b2e
CM
3543 continue;
3544 }
3545 /* the get_extent function already copied into the page */
9655d298
CM
3546 if (test_range_bit(tree, cur, cur_end,
3547 EXTENT_UPTODATE, 1, NULL)) {
a1b32a59 3548 check_page_uptodate(tree, page);
7f042a83 3549 unlock_extent(tree, cur, cur + iosize - 1);
92082d40 3550 end_page_read(page, true, cur, iosize);
d1310b2e 3551 cur = cur + iosize;
306e16ce 3552 pg_offset += iosize;
d1310b2e
CM
3553 continue;
3554 }
70dec807
CM
3555 /* we have an inline extent but it didn't get marked up
3556 * to date. Error out
3557 */
3558 if (block_start == EXTENT_MAP_INLINE) {
7f042a83 3559 unlock_extent(tree, cur, cur + iosize - 1);
92082d40 3560 end_page_read(page, false, cur, iosize);
70dec807 3561 cur = cur + iosize;
306e16ce 3562 pg_offset += iosize;
70dec807
CM
3563 continue;
3564 }
d1310b2e 3565
0ceb34bf 3566 ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
0c64c33c 3567 page, disk_bytenr, iosize,
fa17ed06 3568 pg_offset, bio,
fd513000 3569 end_bio_extent_readpage, 0,
c8b97818 3570 *bio_flags,
005efedf
FM
3571 this_bio_flag,
3572 force_bio_submit);
c8f2f24b
JB
3573 if (!ret) {
3574 nr++;
3575 *bio_flags = this_bio_flag;
3576 } else {
7f042a83 3577 unlock_extent(tree, cur, cur + iosize - 1);
92082d40 3578 end_page_read(page, false, cur, iosize);
baf863b9 3579 goto out;
edd33c99 3580 }
d1310b2e 3581 cur = cur + iosize;
306e16ce 3582 pg_offset += iosize;
d1310b2e 3583 }
90a887c9 3584out:
baf863b9 3585 return ret;
d1310b2e
CM
3586}
3587
b6660e80 3588static inline void contiguous_readpages(struct page *pages[], int nr_pages,
9974090b 3589 u64 start, u64 end,
125bac01 3590 struct extent_map **em_cached,
d3fac6ba 3591 struct bio **bio,
1f7ad75b 3592 unsigned long *bio_flags,
808f80b4 3593 u64 *prev_em_start)
9974090b 3594{
23d31bd4 3595 struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
9974090b
MX
3596 int index;
3597
b272ae22 3598 btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
9974090b
MX
3599
3600 for (index = 0; index < nr_pages; index++) {
0f208812
NB
3601 btrfs_do_readpage(pages[index], em_cached, bio, bio_flags,
3602 REQ_RAHEAD, prev_em_start);
09cbfeaf 3603 put_page(pages[index]);
9974090b
MX
3604 }
3605}
3606
3d4b9496 3607static void update_nr_written(struct writeback_control *wbc,
a9132667 3608 unsigned long nr_written)
11c8349b
CM
3609{
3610 wbc->nr_to_write -= nr_written;
11c8349b
CM
3611}
3612
d1310b2e 3613/*
40f76580
CM
3614 * helper for __extent_writepage, doing all of the delayed allocation setup.
3615 *
5eaad97a 3616 * This returns 1 if btrfs_run_delalloc_range function did all the work required
40f76580
CM
3617 * to write the page (copy into inline extent). In this case the IO has
3618 * been started and the page is already unlocked.
3619 *
3620 * This returns 0 if all went well (page still locked)
3621 * This returns < 0 if there were errors (page still locked)
d1310b2e 3622 */
cd4c0bf9 3623static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
8cc0237a
NB
3624 struct page *page, struct writeback_control *wbc,
3625 u64 delalloc_start, unsigned long *nr_written)
40f76580 3626{
09cbfeaf 3627 u64 page_end = delalloc_start + PAGE_SIZE - 1;
3522e903 3628 bool found;
40f76580
CM
3629 u64 delalloc_to_write = 0;
3630 u64 delalloc_end = 0;
3631 int ret;
3632 int page_started = 0;
3633
40f76580
CM
3634
3635 while (delalloc_end < page_end) {
cd4c0bf9 3636 found = find_lock_delalloc_range(&inode->vfs_inode, page,
40f76580 3637 &delalloc_start,
917aacec 3638 &delalloc_end);
3522e903 3639 if (!found) {
40f76580
CM
3640 delalloc_start = delalloc_end + 1;
3641 continue;
3642 }
cd4c0bf9 3643 ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
5eaad97a 3644 delalloc_end, &page_started, nr_written, wbc);
40f76580
CM
3645 if (ret) {
3646 SetPageError(page);
5eaad97a
NB
3647 /*
3648 * btrfs_run_delalloc_range should return < 0 for error
3649 * but just in case, we use > 0 here meaning the IO is
3650 * started, so we don't want to return > 0 unless
3651 * things are going well.
40f76580 3652 */
b69d1ee9 3653 return ret < 0 ? ret : -EIO;
40f76580
CM
3654 }
3655 /*
ea1754a0
KS
3656 * delalloc_end is already one less than the total length, so
3657 * we don't subtract one from PAGE_SIZE
40f76580
CM
3658 */
3659 delalloc_to_write += (delalloc_end - delalloc_start +
ea1754a0 3660 PAGE_SIZE) >> PAGE_SHIFT;
40f76580
CM
3661 delalloc_start = delalloc_end + 1;
3662 }
3663 if (wbc->nr_to_write < delalloc_to_write) {
3664 int thresh = 8192;
3665
3666 if (delalloc_to_write < thresh * 2)
3667 thresh = delalloc_to_write;
3668 wbc->nr_to_write = min_t(u64, delalloc_to_write,
3669 thresh);
3670 }
3671
3672 /* did the fill delalloc function already unlock and start
3673 * the IO?
3674 */
3675 if (page_started) {
3676 /*
3677 * we've unlocked the page, so we can't update
3678 * the mapping's writeback index, just update
3679 * nr_to_write.
3680 */
3681 wbc->nr_to_write -= *nr_written;
3682 return 1;
3683 }
3684
b69d1ee9 3685 return 0;
40f76580
CM
3686}
3687
3688/*
3689 * helper for __extent_writepage. This calls the writepage start hooks,
3690 * and does the loop to map the page into extents and bios.
3691 *
3692 * We return 1 if the IO is started and the page is unlocked,
3693 * 0 if all went well (page still locked)
3694 * < 0 if there were errors (page still locked)
3695 */
d4580fe2 3696static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
40f76580
CM
3697 struct page *page,
3698 struct writeback_control *wbc,
3699 struct extent_page_data *epd,
3700 loff_t i_size,
3701 unsigned long nr_written,
57e5ffeb 3702 int *nr_ret)
d1310b2e 3703{
6bc5636a 3704 struct btrfs_fs_info *fs_info = inode->root->fs_info;
d4580fe2 3705 struct extent_io_tree *tree = &inode->io_tree;
4eee4fa4 3706 u64 start = page_offset(page);
6bc5636a 3707 u64 end = start + PAGE_SIZE - 1;
d1310b2e
CM
3708 u64 cur = start;
3709 u64 extent_offset;
d1310b2e 3710 u64 block_start;
d1310b2e 3711 struct extent_map *em;
40f76580
CM
3712 int ret = 0;
3713 int nr = 0;
d8e3fb10 3714 u32 opf = REQ_OP_WRITE;
57e5ffeb 3715 const unsigned int write_flags = wbc_to_write_flags(wbc);
40f76580 3716 bool compressed;
c8b97818 3717
6bc5636a 3718 ret = btrfs_writepage_cow_fixup(page, start, end);
d75855b4
NB
3719 if (ret) {
3720 /* Fixup worker will requeue */
5ab58055 3721 redirty_page_for_writepage(wbc, page);
d75855b4
NB
3722 update_nr_written(wbc, nr_written);
3723 unlock_page(page);
3724 return 1;
247e743c
CM
3725 }
3726
11c8349b
CM
3727 /*
3728 * we don't want to touch the inode after unlocking the page,
3729 * so we update the mapping writeback index now
3730 */
3d4b9496 3731 update_nr_written(wbc, nr_written + 1);
771ed689 3732
d1310b2e 3733 while (cur <= end) {
0c64c33c 3734 u64 disk_bytenr;
40f76580 3735 u64 em_end;
6bc5636a 3736 u32 iosize;
58409edd 3737
40f76580 3738 if (cur >= i_size) {
6bc5636a 3739 btrfs_writepage_endio_finish_ordered(page, cur, end, 1);
d1310b2e
CM
3740 break;
3741 }
d4580fe2 3742 em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
c704005d 3743 if (IS_ERR_OR_NULL(em)) {
d1310b2e 3744 SetPageError(page);
61391d56 3745 ret = PTR_ERR_OR_ZERO(em);
d1310b2e
CM
3746 break;
3747 }
3748
3749 extent_offset = cur - em->start;
40f76580 3750 em_end = extent_map_end(em);
6bc5636a
QW
3751 ASSERT(cur <= em_end);
3752 ASSERT(cur < end);
3753 ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
3754 ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
d1310b2e 3755 block_start = em->block_start;
c8b97818 3756 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6bc5636a
QW
3757 disk_bytenr = em->block_start + extent_offset;
3758
3759 /* Note that em_end from extent_map_end() is exclusive */
3760 iosize = min(em_end, end + 1) - cur;
d8e3fb10 3761
e380adfc 3762 if (btrfs_use_zone_append(inode, em->block_start))
d8e3fb10
NA
3763 opf = REQ_OP_ZONE_APPEND;
3764
d1310b2e
CM
3765 free_extent_map(em);
3766 em = NULL;
3767
c8b97818
CM
3768 /*
3769 * compressed and inline extents are written through other
3770 * paths in the FS
3771 */
3772 if (compressed || block_start == EXTENT_MAP_HOLE ||
d1310b2e 3773 block_start == EXTENT_MAP_INLINE) {
c8b04030 3774 if (compressed)
c8b97818 3775 nr++;
c8b04030
OS
3776 else
3777 btrfs_writepage_endio_finish_ordered(page, cur,
3778 cur + iosize - 1, 1);
c8b97818 3779 cur += iosize;
d1310b2e
CM
3780 continue;
3781 }
c8b97818 3782
5cdc84bf 3783 btrfs_set_range_writeback(tree, cur, cur + iosize - 1);
58409edd 3784 if (!PageWriteback(page)) {
d4580fe2 3785 btrfs_err(inode->root->fs_info,
58409edd
DS
3786 "page %lu not writeback, cur %llu end %llu",
3787 page->index, cur, end);
d1310b2e 3788 }
7f3c74fb 3789
d8e3fb10
NA
3790 ret = submit_extent_page(opf | write_flags, wbc, page,
3791 disk_bytenr, iosize,
6bc5636a 3792 cur - page_offset(page), &epd->bio,
58409edd
DS
3793 end_bio_extent_writepage,
3794 0, 0, 0, false);
fe01aa65 3795 if (ret) {
58409edd 3796 SetPageError(page);
fe01aa65
TK
3797 if (PageWriteback(page))
3798 end_page_writeback(page);
3799 }
d1310b2e 3800
6bc5636a 3801 cur += iosize;
d1310b2e
CM
3802 nr++;
3803 }
40f76580 3804 *nr_ret = nr;
40f76580
CM
3805 return ret;
3806}
3807
3808/*
3809 * the writepage semantics are similar to regular writepage. extent
3810 * records are inserted to lock ranges in the tree, and as dirty areas
3811 * are found, they are marked writeback. Then the lock bits are removed
3812 * and the end_io handler clears the writeback ranges
3065976b
QW
3813 *
3814 * Return 0 if everything goes well.
3815 * Return <0 for error.
40f76580
CM
3816 */
3817static int __extent_writepage(struct page *page, struct writeback_control *wbc,
aab6e9ed 3818 struct extent_page_data *epd)
40f76580
CM
3819{
3820 struct inode *inode = page->mapping->host;
40f76580 3821 u64 start = page_offset(page);
09cbfeaf 3822 u64 page_end = start + PAGE_SIZE - 1;
40f76580
CM
3823 int ret;
3824 int nr = 0;
eb70d222 3825 size_t pg_offset;
40f76580 3826 loff_t i_size = i_size_read(inode);
09cbfeaf 3827 unsigned long end_index = i_size >> PAGE_SHIFT;
40f76580
CM
3828 unsigned long nr_written = 0;
3829
40f76580
CM
3830 trace___extent_writepage(page, inode, wbc);
3831
3832 WARN_ON(!PageLocked(page));
3833
3834 ClearPageError(page);
3835
7073017a 3836 pg_offset = offset_in_page(i_size);
40f76580
CM
3837 if (page->index > end_index ||
3838 (page->index == end_index && !pg_offset)) {
09cbfeaf 3839 page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
40f76580
CM
3840 unlock_page(page);
3841 return 0;
3842 }
3843
3844 if (page->index == end_index) {
d048b9c2 3845 memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
40f76580
CM
3846 flush_dcache_page(page);
3847 }
3848
32443de3
QW
3849 ret = set_page_extent_mapped(page);
3850 if (ret < 0) {
3851 SetPageError(page);
3852 goto done;
3853 }
40f76580 3854
7789a55a 3855 if (!epd->extent_locked) {
cd4c0bf9
NB
3856 ret = writepage_delalloc(BTRFS_I(inode), page, wbc, start,
3857 &nr_written);
7789a55a 3858 if (ret == 1)
169d2c87 3859 return 0;
7789a55a
NB
3860 if (ret)
3861 goto done;
3862 }
40f76580 3863
d4580fe2
NB
3864 ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
3865 nr_written, &nr);
40f76580 3866 if (ret == 1)
169d2c87 3867 return 0;
40f76580 3868
d1310b2e
CM
3869done:
3870 if (nr == 0) {
3871 /* make sure the mapping tag for page dirty gets cleared */
3872 set_page_writeback(page);
3873 end_page_writeback(page);
3874 }
61391d56
FM
3875 if (PageError(page)) {
3876 ret = ret < 0 ? ret : -EIO;
3877 end_extent_writepage(page, ret, start, page_end);
3878 }
d1310b2e 3879 unlock_page(page);
3065976b 3880 ASSERT(ret <= 0);
40f76580 3881 return ret;
d1310b2e
CM
3882}
3883
fd8b2b61 3884void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
0b32f4bb 3885{
74316201
N
3886 wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
3887 TASK_UNINTERRUPTIBLE);
0b32f4bb
JB
3888}
3889
18dfa711
FM
3890static void end_extent_buffer_writeback(struct extent_buffer *eb)
3891{
3892 clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
3893 smp_mb__after_atomic();
3894 wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
3895}
3896
2e3c2513 3897/*
a3efb2f0 3898 * Lock extent buffer status and pages for writeback.
2e3c2513 3899 *
a3efb2f0
QW
3900 * May try to flush write bio if we can't get the lock.
3901 *
3902 * Return 0 if the extent buffer doesn't need to be submitted.
3903 * (E.g. the extent buffer is not dirty)
3904 * Return >0 is the extent buffer is submitted to bio.
3905 * Return <0 if something went wrong, no page is locked.
2e3c2513 3906 */
9df76fb5 3907static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
0e378df1 3908 struct extent_page_data *epd)
0b32f4bb 3909{
9df76fb5 3910 struct btrfs_fs_info *fs_info = eb->fs_info;
2e3c2513 3911 int i, num_pages, failed_page_nr;
0b32f4bb
JB
3912 int flush = 0;
3913 int ret = 0;
3914
3915 if (!btrfs_try_tree_write_lock(eb)) {
f4340622 3916 ret = flush_write_bio(epd);
2e3c2513
QW
3917 if (ret < 0)
3918 return ret;
3919 flush = 1;
0b32f4bb
JB
3920 btrfs_tree_lock(eb);
3921 }
3922
3923 if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
3924 btrfs_tree_unlock(eb);
3925 if (!epd->sync_io)
3926 return 0;
3927 if (!flush) {
f4340622 3928 ret = flush_write_bio(epd);
2e3c2513
QW
3929 if (ret < 0)
3930 return ret;
0b32f4bb
JB
3931 flush = 1;
3932 }
a098d8e8
CM
3933 while (1) {
3934 wait_on_extent_buffer_writeback(eb);
3935 btrfs_tree_lock(eb);
3936 if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
3937 break;
0b32f4bb 3938 btrfs_tree_unlock(eb);
0b32f4bb
JB
3939 }
3940 }
3941
51561ffe
JB
3942 /*
3943 * We need to do this to prevent races in people who check if the eb is
3944 * under IO since we can end up having no IO bits set for a short period
3945 * of time.
3946 */
3947 spin_lock(&eb->refs_lock);
0b32f4bb
JB
3948 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3949 set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
51561ffe 3950 spin_unlock(&eb->refs_lock);
0b32f4bb 3951 btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
104b4e51
NB
3952 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3953 -eb->len,
3954 fs_info->dirty_metadata_batch);
0b32f4bb 3955 ret = 1;
51561ffe
JB
3956 } else {
3957 spin_unlock(&eb->refs_lock);
0b32f4bb
JB
3958 }
3959
3960 btrfs_tree_unlock(eb);
3961
f3156df9
QW
3962 /*
3963 * Either we don't need to submit any tree block, or we're submitting
3964 * subpage eb.
3965 * Subpage metadata doesn't use page locking at all, so we can skip
3966 * the page locking.
3967 */
3968 if (!ret || fs_info->sectorsize < PAGE_SIZE)
0b32f4bb
JB
3969 return ret;
3970
65ad0104 3971 num_pages = num_extent_pages(eb);
0b32f4bb 3972 for (i = 0; i < num_pages; i++) {
fb85fc9a 3973 struct page *p = eb->pages[i];
0b32f4bb
JB
3974
3975 if (!trylock_page(p)) {
3976 if (!flush) {
18dfa711
FM
3977 int err;
3978
3979 err = flush_write_bio(epd);
3980 if (err < 0) {
3981 ret = err;
2e3c2513
QW
3982 failed_page_nr = i;
3983 goto err_unlock;
3984 }
0b32f4bb
JB
3985 flush = 1;
3986 }
3987 lock_page(p);
3988 }
3989 }
3990
3991 return ret;
2e3c2513
QW
3992err_unlock:
3993 /* Unlock already locked pages */
3994 for (i = 0; i < failed_page_nr; i++)
3995 unlock_page(eb->pages[i]);
18dfa711
FM
3996 /*
3997 * Clear EXTENT_BUFFER_WRITEBACK and wake up anyone waiting on it.
3998 * Also set back EXTENT_BUFFER_DIRTY so future attempts to this eb can
3999 * be made and undo everything done before.
4000 */
4001 btrfs_tree_lock(eb);
4002 spin_lock(&eb->refs_lock);
4003 set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4004 end_extent_buffer_writeback(eb);
4005 spin_unlock(&eb->refs_lock);
4006 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, eb->len,
4007 fs_info->dirty_metadata_batch);
4008 btrfs_clear_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
4009 btrfs_tree_unlock(eb);
2e3c2513 4010 return ret;
0b32f4bb
JB
4011}
4012
5a2c6075 4013static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
656f30db 4014{
5a2c6075 4015 struct btrfs_fs_info *fs_info = eb->fs_info;
656f30db 4016
5a2c6075 4017 btrfs_page_set_error(fs_info, page, eb->start, eb->len);
656f30db
FM
4018 if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
4019 return;
4020
eb5b64f1
DZ
4021 /*
4022 * If we error out, we should add back the dirty_metadata_bytes
4023 * to make it consistent.
4024 */
eb5b64f1
DZ
4025 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4026 eb->len, fs_info->dirty_metadata_batch);
4027
656f30db
FM
4028 /*
4029 * If writeback for a btree extent that doesn't belong to a log tree
4030 * failed, increment the counter transaction->eb_write_errors.
4031 * We do this because while the transaction is running and before it's
4032 * committing (when we call filemap_fdata[write|wait]_range against
4033 * the btree inode), we might have
4034 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
4035 * returns an error or an error happens during writeback, when we're
4036 * committing the transaction we wouldn't know about it, since the pages
4037 * can be no longer dirty nor marked anymore for writeback (if a
4038 * subsequent modification to the extent buffer didn't happen before the
4039 * transaction commit), which makes filemap_fdata[write|wait]_range not
4040 * able to find the pages tagged with SetPageError at transaction
4041 * commit time. So if this happens we must abort the transaction,
4042 * otherwise we commit a super block with btree roots that point to
4043 * btree nodes/leafs whose content on disk is invalid - either garbage
4044 * or the content of some node/leaf from a past generation that got
4045 * cowed or deleted and is no longer valid.
4046 *
4047 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
4048 * not be enough - we need to distinguish between log tree extents vs
4049 * non-log tree extents, and the next filemap_fdatawait_range() call
4050 * will catch and clear such errors in the mapping - and that call might
4051 * be from a log sync and not from a transaction commit. Also, checking
4052 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
4053 * not done and would not be reliable - the eb might have been released
4054 * from memory and reading it back again means that flag would not be
4055 * set (since it's a runtime flag, not persisted on disk).
4056 *
4057 * Using the flags below in the btree inode also makes us achieve the
4058 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
4059 * writeback for all dirty pages and before filemap_fdatawait_range()
4060 * is called, the writeback for all dirty pages had already finished
4061 * with errors - because we were not using AS_EIO/AS_ENOSPC,
4062 * filemap_fdatawait_range() would return success, as it could not know
4063 * that writeback errors happened (the pages were no longer tagged for
4064 * writeback).
4065 */
4066 switch (eb->log_index) {
4067 case -1:
5a2c6075 4068 set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
656f30db
FM
4069 break;
4070 case 0:
5a2c6075 4071 set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
656f30db
FM
4072 break;
4073 case 1:
5a2c6075 4074 set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
656f30db
FM
4075 break;
4076 default:
4077 BUG(); /* unexpected, logic error */
4078 }
4079}
4080
2f3186d8
QW
4081/*
4082 * The endio specific version which won't touch any unsafe spinlock in endio
4083 * context.
4084 */
4085static struct extent_buffer *find_extent_buffer_nolock(
4086 struct btrfs_fs_info *fs_info, u64 start)
4087{
4088 struct extent_buffer *eb;
4089
4090 rcu_read_lock();
4091 eb = radix_tree_lookup(&fs_info->buffer_radix,
4092 start >> fs_info->sectorsize_bits);
4093 if (eb && atomic_inc_not_zero(&eb->refs)) {
4094 rcu_read_unlock();
4095 return eb;
4096 }
4097 rcu_read_unlock();
4098 return NULL;
4099}
4100
4101/*
4102 * The endio function for subpage extent buffer write.
4103 *
4104 * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
4105 * after all extent buffers in the page has finished their writeback.
4106 */
4107static void end_bio_subpage_eb_writepage(struct btrfs_fs_info *fs_info,
4108 struct bio *bio)
4109{
4110 struct bio_vec *bvec;
4111 struct bvec_iter_all iter_all;
4112
4113 ASSERT(!bio_flagged(bio, BIO_CLONED));
4114 bio_for_each_segment_all(bvec, bio, iter_all) {
4115 struct page *page = bvec->bv_page;
4116 u64 bvec_start = page_offset(page) + bvec->bv_offset;
4117 u64 bvec_end = bvec_start + bvec->bv_len - 1;
4118 u64 cur_bytenr = bvec_start;
4119
4120 ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
4121
4122 /* Iterate through all extent buffers in the range */
4123 while (cur_bytenr <= bvec_end) {
4124 struct extent_buffer *eb;
4125 int done;
4126
4127 /*
4128 * Here we can't use find_extent_buffer(), as it may
4129 * try to lock eb->refs_lock, which is not safe in endio
4130 * context.
4131 */
4132 eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
4133 ASSERT(eb);
4134
4135 cur_bytenr = eb->start + eb->len;
4136
4137 ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
4138 done = atomic_dec_and_test(&eb->io_pages);
4139 ASSERT(done);
4140
4141 if (bio->bi_status ||
4142 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
4143 ClearPageUptodate(page);
4144 set_btree_ioerr(page, eb);
4145 }
4146
4147 btrfs_subpage_clear_writeback(fs_info, page, eb->start,
4148 eb->len);
4149 end_extent_buffer_writeback(eb);
4150 /*
4151 * free_extent_buffer() will grab spinlock which is not
4152 * safe in endio context. Thus here we manually dec
4153 * the ref.
4154 */
4155 atomic_dec(&eb->refs);
4156 }
4157 }
4158 bio_put(bio);
4159}
4160
4246a0b6 4161static void end_bio_extent_buffer_writepage(struct bio *bio)
0b32f4bb 4162{
2f3186d8 4163 struct btrfs_fs_info *fs_info;
2c30c71b 4164 struct bio_vec *bvec;
0b32f4bb 4165 struct extent_buffer *eb;
2b070cfe 4166 int done;
6dc4f100 4167 struct bvec_iter_all iter_all;
0b32f4bb 4168
2f3186d8
QW
4169 fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
4170 if (fs_info->sectorsize < PAGE_SIZE)
4171 return end_bio_subpage_eb_writepage(fs_info, bio);
4172
c09abff8 4173 ASSERT(!bio_flagged(bio, BIO_CLONED));
2b070cfe 4174 bio_for_each_segment_all(bvec, bio, iter_all) {
0b32f4bb
JB
4175 struct page *page = bvec->bv_page;
4176
0b32f4bb
JB
4177 eb = (struct extent_buffer *)page->private;
4178 BUG_ON(!eb);
4179 done = atomic_dec_and_test(&eb->io_pages);
4180
4e4cbee9 4181 if (bio->bi_status ||
4246a0b6 4182 test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
0b32f4bb 4183 ClearPageUptodate(page);
5a2c6075 4184 set_btree_ioerr(page, eb);
0b32f4bb
JB
4185 }
4186
4187 end_page_writeback(page);
4188
4189 if (!done)
4190 continue;
4191
4192 end_extent_buffer_writeback(eb);
2c30c71b 4193 }
0b32f4bb
JB
4194
4195 bio_put(bio);
0b32f4bb
JB
4196}
4197
35b6ddfa
QW
4198/*
4199 * Unlike the work in write_one_eb(), we rely completely on extent locking.
4200 * Page locking is only utilized at minimum to keep the VMM code happy.
4201 *
4202 * Caller should still call write_one_eb() other than this function directly.
4203 * As write_one_eb() has extra preparation before submitting the extent buffer.
4204 */
4205static int write_one_subpage_eb(struct extent_buffer *eb,
4206 struct writeback_control *wbc,
4207 struct extent_page_data *epd)
4208{
4209 struct btrfs_fs_info *fs_info = eb->fs_info;
4210 struct page *page = eb->pages[0];
4211 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
4212 bool no_dirty_ebs = false;
4213 int ret;
4214
4215 /* clear_page_dirty_for_io() in subpage helper needs page locked */
4216 lock_page(page);
4217 btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
4218
4219 /* Check if this is the last dirty bit to update nr_written */
4220 no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
4221 eb->start, eb->len);
4222 if (no_dirty_ebs)
4223 clear_page_dirty_for_io(page);
4224
4225 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc, page,
4226 eb->start, eb->len, eb->start - page_offset(page),
4227 &epd->bio, end_bio_extent_buffer_writepage, 0, 0, 0,
4228 false);
4229 if (ret) {
4230 btrfs_subpage_clear_writeback(fs_info, page, eb->start, eb->len);
4231 set_btree_ioerr(page, eb);
4232 unlock_page(page);
4233
4234 if (atomic_dec_and_test(&eb->io_pages))
4235 end_extent_buffer_writeback(eb);
4236 return -EIO;
4237 }
4238 unlock_page(page);
4239 /*
4240 * Submission finished without problem, if no range of the page is
4241 * dirty anymore, we have submitted a page. Update nr_written in wbc.
4242 */
4243 if (no_dirty_ebs)
4244 update_nr_written(wbc, 1);
4245 return ret;
4246}
4247
0e378df1 4248static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
0b32f4bb
JB
4249 struct writeback_control *wbc,
4250 struct extent_page_data *epd)
4251{
0c64c33c 4252 u64 disk_bytenr = eb->start;
851cd173 4253 u32 nritems;
cc5e31a4 4254 int i, num_pages;
851cd173 4255 unsigned long start, end;
ff40adf7 4256 unsigned int write_flags = wbc_to_write_flags(wbc) | REQ_META;
d7dbe9e7 4257 int ret = 0;
0b32f4bb 4258
656f30db 4259 clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
65ad0104 4260 num_pages = num_extent_pages(eb);
0b32f4bb 4261 atomic_set(&eb->io_pages, num_pages);
de0022b9 4262
851cd173
LB
4263 /* set btree blocks beyond nritems with 0 to avoid stale content. */
4264 nritems = btrfs_header_nritems(eb);
3eb548ee 4265 if (btrfs_header_level(eb) > 0) {
3eb548ee
LB
4266 end = btrfs_node_key_ptr_offset(nritems);
4267
b159fa28 4268 memzero_extent_buffer(eb, end, eb->len - end);
851cd173
LB
4269 } else {
4270 /*
4271 * leaf:
4272 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
4273 */
4274 start = btrfs_item_nr_offset(nritems);
8f881e8c 4275 end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
b159fa28 4276 memzero_extent_buffer(eb, start, end - start);
3eb548ee
LB
4277 }
4278
35b6ddfa
QW
4279 if (eb->fs_info->sectorsize < PAGE_SIZE)
4280 return write_one_subpage_eb(eb, wbc, epd);
4281
0b32f4bb 4282 for (i = 0; i < num_pages; i++) {
fb85fc9a 4283 struct page *p = eb->pages[i];
0b32f4bb
JB
4284
4285 clear_page_dirty_for_io(p);
4286 set_page_writeback(p);
0ceb34bf 4287 ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
0c64c33c 4288 p, disk_bytenr, PAGE_SIZE, 0,
c2df8bb4 4289 &epd->bio,
1f7ad75b 4290 end_bio_extent_buffer_writepage,
18fdc679 4291 0, 0, 0, false);
0b32f4bb 4292 if (ret) {
5a2c6075 4293 set_btree_ioerr(p, eb);
fe01aa65
TK
4294 if (PageWriteback(p))
4295 end_page_writeback(p);
0b32f4bb
JB
4296 if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
4297 end_extent_buffer_writeback(eb);
4298 ret = -EIO;
4299 break;
4300 }
0c64c33c 4301 disk_bytenr += PAGE_SIZE;
3d4b9496 4302 update_nr_written(wbc, 1);
0b32f4bb
JB
4303 unlock_page(p);
4304 }
4305
4306 if (unlikely(ret)) {
4307 for (; i < num_pages; i++) {
bbf65cf0 4308 struct page *p = eb->pages[i];
81465028 4309 clear_page_dirty_for_io(p);
0b32f4bb
JB
4310 unlock_page(p);
4311 }
4312 }
4313
4314 return ret;
4315}
4316
c4aec299
QW
4317/*
4318 * Submit one subpage btree page.
4319 *
4320 * The main difference to submit_eb_page() is:
4321 * - Page locking
4322 * For subpage, we don't rely on page locking at all.
4323 *
4324 * - Flush write bio
4325 * We only flush bio if we may be unable to fit current extent buffers into
4326 * current bio.
4327 *
4328 * Return >=0 for the number of submitted extent buffers.
4329 * Return <0 for fatal error.
4330 */
4331static int submit_eb_subpage(struct page *page,
4332 struct writeback_control *wbc,
4333 struct extent_page_data *epd)
4334{
4335 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
4336 int submitted = 0;
4337 u64 page_start = page_offset(page);
4338 int bit_start = 0;
4339 const int nbits = BTRFS_SUBPAGE_BITMAP_SIZE;
4340 int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
4341 int ret;
4342
4343 /* Lock and write each dirty extent buffers in the range */
4344 while (bit_start < nbits) {
4345 struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
4346 struct extent_buffer *eb;
4347 unsigned long flags;
4348 u64 start;
4349
4350 /*
4351 * Take private lock to ensure the subpage won't be detached
4352 * in the meantime.
4353 */
4354 spin_lock(&page->mapping->private_lock);
4355 if (!PagePrivate(page)) {
4356 spin_unlock(&page->mapping->private_lock);
4357 break;
4358 }
4359 spin_lock_irqsave(&subpage->lock, flags);
4360 if (!((1 << bit_start) & subpage->dirty_bitmap)) {
4361 spin_unlock_irqrestore(&subpage->lock, flags);
4362 spin_unlock(&page->mapping->private_lock);
4363 bit_start++;
4364 continue;
4365 }
4366
4367 start = page_start + bit_start * fs_info->sectorsize;
4368 bit_start += sectors_per_node;
4369
4370 /*
4371 * Here we just want to grab the eb without touching extra
4372 * spin locks, so call find_extent_buffer_nolock().
4373 */
4374 eb = find_extent_buffer_nolock(fs_info, start);
4375 spin_unlock_irqrestore(&subpage->lock, flags);
4376 spin_unlock(&page->mapping->private_lock);
4377
4378 /*
4379 * The eb has already reached 0 refs thus find_extent_buffer()
4380 * doesn't return it. We don't need to write back such eb
4381 * anyway.
4382 */
4383 if (!eb)
4384 continue;
4385
4386 ret = lock_extent_buffer_for_io(eb, epd);
4387 if (ret == 0) {
4388 free_extent_buffer(eb);
4389 continue;
4390 }
4391 if (ret < 0) {
4392 free_extent_buffer(eb);
4393 goto cleanup;
4394 }
4395 ret = write_one_eb(eb, wbc, epd);
4396 free_extent_buffer(eb);
4397 if (ret < 0)
4398 goto cleanup;
4399 submitted++;
4400 }
4401 return submitted;
4402
4403cleanup:
4404 /* We hit error, end bio for the submitted extent buffers */
4405 end_write_bio(epd, ret);
4406 return ret;
4407}
4408
f91e0d0c
QW
4409/*
4410 * Submit all page(s) of one extent buffer.
4411 *
4412 * @page: the page of one extent buffer
4413 * @eb_context: to determine if we need to submit this page, if current page
4414 * belongs to this eb, we don't need to submit
4415 *
4416 * The caller should pass each page in their bytenr order, and here we use
4417 * @eb_context to determine if we have submitted pages of one extent buffer.
4418 *
4419 * If we have, we just skip until we hit a new page that doesn't belong to
4420 * current @eb_context.
4421 *
4422 * If not, we submit all the page(s) of the extent buffer.
4423 *
4424 * Return >0 if we have submitted the extent buffer successfully.
4425 * Return 0 if we don't need to submit the page, as it's already submitted by
4426 * previous call.
4427 * Return <0 for fatal error.
4428 */
4429static int submit_eb_page(struct page *page, struct writeback_control *wbc,
4430 struct extent_page_data *epd,
4431 struct extent_buffer **eb_context)
4432{
4433 struct address_space *mapping = page->mapping;
0bc09ca1 4434 struct btrfs_block_group *cache = NULL;
f91e0d0c
QW
4435 struct extent_buffer *eb;
4436 int ret;
4437
4438 if (!PagePrivate(page))
4439 return 0;
4440
c4aec299
QW
4441 if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
4442 return submit_eb_subpage(page, wbc, epd);
4443
f91e0d0c
QW
4444 spin_lock(&mapping->private_lock);
4445 if (!PagePrivate(page)) {
4446 spin_unlock(&mapping->private_lock);
4447 return 0;
4448 }
4449
4450 eb = (struct extent_buffer *)page->private;
4451
4452 /*
4453 * Shouldn't happen and normally this would be a BUG_ON but no point
4454 * crashing the machine for something we can survive anyway.
4455 */
4456 if (WARN_ON(!eb)) {
4457 spin_unlock(&mapping->private_lock);
4458 return 0;
4459 }
4460
4461 if (eb == *eb_context) {
4462 spin_unlock(&mapping->private_lock);
4463 return 0;
4464 }
4465 ret = atomic_inc_not_zero(&eb->refs);
4466 spin_unlock(&mapping->private_lock);
4467 if (!ret)
4468 return 0;
4469
0bc09ca1
NA
4470 if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
4471 /*
4472 * If for_sync, this hole will be filled with
4473 * trasnsaction commit.
4474 */
4475 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4476 ret = -EAGAIN;
4477 else
4478 ret = 0;
4479 free_extent_buffer(eb);
4480 return ret;
4481 }
4482
f91e0d0c
QW
4483 *eb_context = eb;
4484
4485 ret = lock_extent_buffer_for_io(eb, epd);
4486 if (ret <= 0) {
0bc09ca1
NA
4487 btrfs_revert_meta_write_pointer(cache, eb);
4488 if (cache)
4489 btrfs_put_block_group(cache);
f91e0d0c
QW
4490 free_extent_buffer(eb);
4491 return ret;
4492 }
0bc09ca1
NA
4493 if (cache)
4494 btrfs_put_block_group(cache);
f91e0d0c
QW
4495 ret = write_one_eb(eb, wbc, epd);
4496 free_extent_buffer(eb);
4497 if (ret < 0)
4498 return ret;
4499 return 1;
4500}
4501
0b32f4bb
JB
4502int btree_write_cache_pages(struct address_space *mapping,
4503 struct writeback_control *wbc)
4504{
f91e0d0c 4505 struct extent_buffer *eb_context = NULL;
0b32f4bb
JB
4506 struct extent_page_data epd = {
4507 .bio = NULL,
0b32f4bb
JB
4508 .extent_locked = 0,
4509 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
4510 };
b3ff8f1d 4511 struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
0b32f4bb
JB
4512 int ret = 0;
4513 int done = 0;
4514 int nr_to_write_done = 0;
4515 struct pagevec pvec;
4516 int nr_pages;
4517 pgoff_t index;
4518 pgoff_t end; /* Inclusive */
4519 int scanned = 0;
10bbd235 4520 xa_mark_t tag;
0b32f4bb 4521
86679820 4522 pagevec_init(&pvec);
0b32f4bb
JB
4523 if (wbc->range_cyclic) {
4524 index = mapping->writeback_index; /* Start from prev offset */
4525 end = -1;
556755a8
JB
4526 /*
4527 * Start from the beginning does not need to cycle over the
4528 * range, mark it as scanned.
4529 */
4530 scanned = (index == 0);
0b32f4bb 4531 } else {
09cbfeaf
KS
4532 index = wbc->range_start >> PAGE_SHIFT;
4533 end = wbc->range_end >> PAGE_SHIFT;
0b32f4bb
JB
4534 scanned = 1;
4535 }
4536 if (wbc->sync_mode == WB_SYNC_ALL)
4537 tag = PAGECACHE_TAG_TOWRITE;
4538 else
4539 tag = PAGECACHE_TAG_DIRTY;
0bc09ca1 4540 btrfs_zoned_meta_io_lock(fs_info);
0b32f4bb
JB
4541retry:
4542 if (wbc->sync_mode == WB_SYNC_ALL)
4543 tag_pages_for_writeback(mapping, index, end);
4544 while (!done && !nr_to_write_done && (index <= end) &&
4006f437 4545 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
67fd707f 4546 tag))) {
0b32f4bb
JB
4547 unsigned i;
4548
0b32f4bb
JB
4549 for (i = 0; i < nr_pages; i++) {
4550 struct page *page = pvec.pages[i];
4551
f91e0d0c
QW
4552 ret = submit_eb_page(page, wbc, &epd, &eb_context);
4553 if (ret == 0)
0b32f4bb 4554 continue;
f91e0d0c 4555 if (ret < 0) {
0b32f4bb 4556 done = 1;
0b32f4bb
JB
4557 break;
4558 }
0b32f4bb
JB
4559
4560 /*
4561 * the filesystem may choose to bump up nr_to_write.
4562 * We have to make sure to honor the new nr_to_write
4563 * at any time
4564 */
4565 nr_to_write_done = wbc->nr_to_write <= 0;
4566 }
4567 pagevec_release(&pvec);
4568 cond_resched();
4569 }
4570 if (!scanned && !done) {
4571 /*
4572 * We hit the last page and there is more work to be done: wrap
4573 * back to the start of the file
4574 */
4575 scanned = 1;
4576 index = 0;
4577 goto retry;
4578 }
2b952eea
QW
4579 if (ret < 0) {
4580 end_write_bio(&epd, ret);
0bc09ca1 4581 goto out;
2b952eea 4582 }
b3ff8f1d
QW
4583 /*
4584 * If something went wrong, don't allow any metadata write bio to be
4585 * submitted.
4586 *
4587 * This would prevent use-after-free if we had dirty pages not
4588 * cleaned up, which can still happen by fuzzed images.
4589 *
4590 * - Bad extent tree
4591 * Allowing existing tree block to be allocated for other trees.
4592 *
4593 * - Log tree operations
4594 * Exiting tree blocks get allocated to log tree, bumps its
4595 * generation, then get cleaned in tree re-balance.
4596 * Such tree block will not be written back, since it's clean,
4597 * thus no WRITTEN flag set.
4598 * And after log writes back, this tree block is not traced by
4599 * any dirty extent_io_tree.
4600 *
4601 * - Offending tree block gets re-dirtied from its original owner
4602 * Since it has bumped generation, no WRITTEN flag, it can be
4603 * reused without COWing. This tree block will not be traced
4604 * by btrfs_transaction::dirty_pages.
4605 *
4606 * Now such dirty tree block will not be cleaned by any dirty
4607 * extent io tree. Thus we don't want to submit such wild eb
4608 * if the fs already has error.
4609 */
4610 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
4611 ret = flush_write_bio(&epd);
4612 } else {
fbabd4a3 4613 ret = -EROFS;
b3ff8f1d
QW
4614 end_write_bio(&epd, ret);
4615 }
0bc09ca1
NA
4616out:
4617 btrfs_zoned_meta_io_unlock(fs_info);
0b32f4bb
JB
4618 return ret;
4619}
4620
d1310b2e 4621/**
3bed2da1
NB
4622 * Walk the list of dirty pages of the given address space and write all of them.
4623 *
d1310b2e 4624 * @mapping: address space structure to write
3bed2da1
NB
4625 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
4626 * @epd: holds context for the write, namely the bio
d1310b2e
CM
4627 *
4628 * If a page is already under I/O, write_cache_pages() skips it, even
4629 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
4630 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
4631 * and msync() need to guarantee that all the data which was dirty at the time
4632 * the call was made get new I/O started against them. If wbc->sync_mode is
4633 * WB_SYNC_ALL then we were called for data integrity and we must wait for
4634 * existing IO to complete.
4635 */
4242b64a 4636static int extent_write_cache_pages(struct address_space *mapping,
4bef0848 4637 struct writeback_control *wbc,
aab6e9ed 4638 struct extent_page_data *epd)
d1310b2e 4639{
7fd1a3f7 4640 struct inode *inode = mapping->host;
d1310b2e
CM
4641 int ret = 0;
4642 int done = 0;
f85d7d6c 4643 int nr_to_write_done = 0;
d1310b2e
CM
4644 struct pagevec pvec;
4645 int nr_pages;
4646 pgoff_t index;
4647 pgoff_t end; /* Inclusive */
a9132667
LB
4648 pgoff_t done_index;
4649 int range_whole = 0;
d1310b2e 4650 int scanned = 0;
10bbd235 4651 xa_mark_t tag;
d1310b2e 4652
7fd1a3f7
JB
4653 /*
4654 * We have to hold onto the inode so that ordered extents can do their
4655 * work when the IO finishes. The alternative to this is failing to add
4656 * an ordered extent if the igrab() fails there and that is a huge pain
4657 * to deal with, so instead just hold onto the inode throughout the
4658 * writepages operation. If it fails here we are freeing up the inode
4659 * anyway and we'd rather not waste our time writing out stuff that is
4660 * going to be truncated anyway.
4661 */
4662 if (!igrab(inode))
4663 return 0;
4664
86679820 4665 pagevec_init(&pvec);
d1310b2e
CM
4666 if (wbc->range_cyclic) {
4667 index = mapping->writeback_index; /* Start from prev offset */
4668 end = -1;
556755a8
JB
4669 /*
4670 * Start from the beginning does not need to cycle over the
4671 * range, mark it as scanned.
4672 */
4673 scanned = (index == 0);
d1310b2e 4674 } else {
09cbfeaf
KS
4675 index = wbc->range_start >> PAGE_SHIFT;
4676 end = wbc->range_end >> PAGE_SHIFT;
a9132667
LB
4677 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
4678 range_whole = 1;
d1310b2e
CM
4679 scanned = 1;
4680 }
3cd24c69
EL
4681
4682 /*
4683 * We do the tagged writepage as long as the snapshot flush bit is set
4684 * and we are the first one who do the filemap_flush() on this inode.
4685 *
4686 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
4687 * not race in and drop the bit.
4688 */
4689 if (range_whole && wbc->nr_to_write == LONG_MAX &&
4690 test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
4691 &BTRFS_I(inode)->runtime_flags))
4692 wbc->tagged_writepages = 1;
4693
4694 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
f7aaa06b
JB
4695 tag = PAGECACHE_TAG_TOWRITE;
4696 else
4697 tag = PAGECACHE_TAG_DIRTY;
d1310b2e 4698retry:
3cd24c69 4699 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
f7aaa06b 4700 tag_pages_for_writeback(mapping, index, end);
a9132667 4701 done_index = index;
f85d7d6c 4702 while (!done && !nr_to_write_done && (index <= end) &&
67fd707f
JK
4703 (nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
4704 &index, end, tag))) {
d1310b2e
CM
4705 unsigned i;
4706
d1310b2e
CM
4707 for (i = 0; i < nr_pages; i++) {
4708 struct page *page = pvec.pages[i];
4709
f7bddf1e 4710 done_index = page->index + 1;
d1310b2e 4711 /*
b93b0163
MW
4712 * At this point we hold neither the i_pages lock nor
4713 * the page lock: the page may be truncated or
4714 * invalidated (changing page->mapping to NULL),
4715 * or even swizzled back from swapper_space to
4716 * tmpfs file mapping
d1310b2e 4717 */
c8f2f24b 4718 if (!trylock_page(page)) {
f4340622
QW
4719 ret = flush_write_bio(epd);
4720 BUG_ON(ret < 0);
c8f2f24b 4721 lock_page(page);
01d658f2 4722 }
d1310b2e
CM
4723
4724 if (unlikely(page->mapping != mapping)) {
4725 unlock_page(page);
4726 continue;
4727 }
4728
d2c3f4f6 4729 if (wbc->sync_mode != WB_SYNC_NONE) {
f4340622
QW
4730 if (PageWriteback(page)) {
4731 ret = flush_write_bio(epd);
4732 BUG_ON(ret < 0);
4733 }
d1310b2e 4734 wait_on_page_writeback(page);
d2c3f4f6 4735 }
d1310b2e
CM
4736
4737 if (PageWriteback(page) ||
4738 !clear_page_dirty_for_io(page)) {
4739 unlock_page(page);
4740 continue;
4741 }
4742
aab6e9ed 4743 ret = __extent_writepage(page, wbc, epd);
a9132667 4744 if (ret < 0) {
a9132667
LB
4745 done = 1;
4746 break;
4747 }
f85d7d6c
CM
4748
4749 /*
4750 * the filesystem may choose to bump up nr_to_write.
4751 * We have to make sure to honor the new nr_to_write
4752 * at any time
4753 */
4754 nr_to_write_done = wbc->nr_to_write <= 0;
d1310b2e
CM
4755 }
4756 pagevec_release(&pvec);
4757 cond_resched();
4758 }
894b36e3 4759 if (!scanned && !done) {
d1310b2e
CM
4760 /*
4761 * We hit the last page and there is more work to be done: wrap
4762 * back to the start of the file
4763 */
4764 scanned = 1;
4765 index = 0;
42ffb0bf
JB
4766
4767 /*
4768 * If we're looping we could run into a page that is locked by a
4769 * writer and that writer could be waiting on writeback for a
4770 * page in our current bio, and thus deadlock, so flush the
4771 * write bio here.
4772 */
4773 ret = flush_write_bio(epd);
4774 if (!ret)
4775 goto retry;
d1310b2e 4776 }
a9132667
LB
4777
4778 if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
4779 mapping->writeback_index = done_index;
4780
7fd1a3f7 4781 btrfs_add_delayed_iput(inode);
894b36e3 4782 return ret;
d1310b2e 4783}
d1310b2e 4784
0a9b0e53 4785int extent_write_full_page(struct page *page, struct writeback_control *wbc)
d1310b2e
CM
4786{
4787 int ret;
d1310b2e
CM
4788 struct extent_page_data epd = {
4789 .bio = NULL,
771ed689 4790 .extent_locked = 0,
ffbd517d 4791 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
d1310b2e 4792 };
d1310b2e 4793
d1310b2e 4794 ret = __extent_writepage(page, wbc, &epd);
3065976b
QW
4795 ASSERT(ret <= 0);
4796 if (ret < 0) {
4797 end_write_bio(&epd, ret);
4798 return ret;
4799 }
d1310b2e 4800
3065976b
QW
4801 ret = flush_write_bio(&epd);
4802 ASSERT(ret <= 0);
d1310b2e
CM
4803 return ret;
4804}
d1310b2e 4805
5e3ee236 4806int extent_write_locked_range(struct inode *inode, u64 start, u64 end,
771ed689
CM
4807 int mode)
4808{
4809 int ret = 0;
4810 struct address_space *mapping = inode->i_mapping;
4811 struct page *page;
09cbfeaf
KS
4812 unsigned long nr_pages = (end - start + PAGE_SIZE) >>
4813 PAGE_SHIFT;
771ed689
CM
4814
4815 struct extent_page_data epd = {
4816 .bio = NULL,
771ed689 4817 .extent_locked = 1,
ffbd517d 4818 .sync_io = mode == WB_SYNC_ALL,
771ed689
CM
4819 };
4820 struct writeback_control wbc_writepages = {
771ed689 4821 .sync_mode = mode,
771ed689
CM
4822 .nr_to_write = nr_pages * 2,
4823 .range_start = start,
4824 .range_end = end + 1,
ec39f769
CM
4825 /* We're called from an async helper function */
4826 .punt_to_cgroup = 1,
4827 .no_cgroup_owner = 1,
771ed689
CM
4828 };
4829
dbb70bec 4830 wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
d397712b 4831 while (start <= end) {
09cbfeaf 4832 page = find_get_page(mapping, start >> PAGE_SHIFT);
771ed689
CM
4833 if (clear_page_dirty_for_io(page))
4834 ret = __extent_writepage(page, &wbc_writepages, &epd);
4835 else {
7087a9d8 4836 btrfs_writepage_endio_finish_ordered(page, start,
c629732d 4837 start + PAGE_SIZE - 1, 1);
771ed689
CM
4838 unlock_page(page);
4839 }
09cbfeaf
KS
4840 put_page(page);
4841 start += PAGE_SIZE;
771ed689
CM
4842 }
4843
02c6db4f 4844 ASSERT(ret <= 0);
dbb70bec
CM
4845 if (ret == 0)
4846 ret = flush_write_bio(&epd);
4847 else
02c6db4f 4848 end_write_bio(&epd, ret);
dbb70bec
CM
4849
4850 wbc_detach_inode(&wbc_writepages);
771ed689
CM
4851 return ret;
4852}
d1310b2e 4853
8ae225a8 4854int extent_writepages(struct address_space *mapping,
d1310b2e
CM
4855 struct writeback_control *wbc)
4856{
4857 int ret = 0;
4858 struct extent_page_data epd = {
4859 .bio = NULL,
771ed689 4860 .extent_locked = 0,
ffbd517d 4861 .sync_io = wbc->sync_mode == WB_SYNC_ALL,
d1310b2e
CM
4862 };
4863
935db853 4864 ret = extent_write_cache_pages(mapping, wbc, &epd);
a2a72fbd
QW
4865 ASSERT(ret <= 0);
4866 if (ret < 0) {
4867 end_write_bio(&epd, ret);
4868 return ret;
4869 }
4870 ret = flush_write_bio(&epd);
d1310b2e
CM
4871 return ret;
4872}
d1310b2e 4873
ba206a02 4874void extent_readahead(struct readahead_control *rac)
d1310b2e
CM
4875{
4876 struct bio *bio = NULL;
c8b97818 4877 unsigned long bio_flags = 0;
67c9684f 4878 struct page *pagepool[16];
125bac01 4879 struct extent_map *em_cached = NULL;
808f80b4 4880 u64 prev_em_start = (u64)-1;
ba206a02 4881 int nr;
d1310b2e 4882
ba206a02 4883 while ((nr = readahead_page_batch(rac, pagepool))) {
32c0a6bc
MWO
4884 u64 contig_start = readahead_pos(rac);
4885 u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
e65ef21e 4886
ba206a02
MWO
4887 contiguous_readpages(pagepool, nr, contig_start, contig_end,
4888 &em_cached, &bio, &bio_flags, &prev_em_start);
d1310b2e 4889 }
67c9684f 4890
125bac01
MX
4891 if (em_cached)
4892 free_extent_map(em_cached);
4893
ba206a02
MWO
4894 if (bio) {
4895 if (submit_one_bio(bio, 0, bio_flags))
4896 return;
4897 }
d1310b2e 4898}
d1310b2e
CM
4899
4900/*
4901 * basic invalidatepage code, this waits on any locked or writeback
4902 * ranges corresponding to the page, and then deletes any extent state
4903 * records from the tree
4904 */
4905int extent_invalidatepage(struct extent_io_tree *tree,
4906 struct page *page, unsigned long offset)
4907{
2ac55d41 4908 struct extent_state *cached_state = NULL;
4eee4fa4 4909 u64 start = page_offset(page);
09cbfeaf 4910 u64 end = start + PAGE_SIZE - 1;
d1310b2e
CM
4911 size_t blocksize = page->mapping->host->i_sb->s_blocksize;
4912
829ddec9
QW
4913 /* This function is only called for the btree inode */
4914 ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
4915
fda2832f 4916 start += ALIGN(offset, blocksize);
d1310b2e
CM
4917 if (start > end)
4918 return 0;
4919
ff13db41 4920 lock_extent_bits(tree, start, end, &cached_state);
1edbb734 4921 wait_on_page_writeback(page);
829ddec9
QW
4922
4923 /*
4924 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
4925 * so here we only need to unlock the extent range to free any
4926 * existing extent state.
4927 */
4928 unlock_extent_cached(tree, start, end, &cached_state);
d1310b2e
CM
4929 return 0;
4930}
d1310b2e 4931
7b13b7b1
CM
4932/*
4933 * a helper for releasepage, this tests for areas of the page that
4934 * are locked or under IO and drops the related state bits if it is safe
4935 * to drop the page.
4936 */
29c68b2d 4937static int try_release_extent_state(struct extent_io_tree *tree,
48a3b636 4938 struct page *page, gfp_t mask)
7b13b7b1 4939{
4eee4fa4 4940 u64 start = page_offset(page);
09cbfeaf 4941 u64 end = start + PAGE_SIZE - 1;
7b13b7b1
CM
4942 int ret = 1;
4943
8882679e 4944 if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
7b13b7b1 4945 ret = 0;
8882679e 4946 } else {
11ef160f 4947 /*
2766ff61
FM
4948 * At this point we can safely clear everything except the
4949 * locked bit, the nodatasum bit and the delalloc new bit.
4950 * The delalloc new bit will be cleared by ordered extent
4951 * completion.
11ef160f 4952 */
66b0c887 4953 ret = __clear_extent_bit(tree, start, end,
2766ff61
FM
4954 ~(EXTENT_LOCKED | EXTENT_NODATASUM | EXTENT_DELALLOC_NEW),
4955 0, 0, NULL, mask, NULL);
e3f24cc5
CM
4956
4957 /* if clear_extent_bit failed for enomem reasons,
4958 * we can't allow the release to continue.
4959 */
4960 if (ret < 0)
4961 ret = 0;
4962 else
4963 ret = 1;
7b13b7b1
CM
4964 }
4965 return ret;
4966}
7b13b7b1 4967
d1310b2e
CM
4968/*
4969 * a helper for releasepage. As long as there are no locked extents
4970 * in the range corresponding to the page, both state records and extent
4971 * map records are removed
4972 */
477a30ba 4973int try_release_extent_mapping(struct page *page, gfp_t mask)
d1310b2e
CM
4974{
4975 struct extent_map *em;
4eee4fa4 4976 u64 start = page_offset(page);
09cbfeaf 4977 u64 end = start + PAGE_SIZE - 1;
bd3599a0
FM
4978 struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
4979 struct extent_io_tree *tree = &btrfs_inode->io_tree;
4980 struct extent_map_tree *map = &btrfs_inode->extent_tree;
7b13b7b1 4981
d0164adc 4982 if (gfpflags_allow_blocking(mask) &&
ee22184b 4983 page->mapping->host->i_size > SZ_16M) {
39b5637f 4984 u64 len;
70dec807 4985 while (start <= end) {
fbc2bd7e
FM
4986 struct btrfs_fs_info *fs_info;
4987 u64 cur_gen;
4988
39b5637f 4989 len = end - start + 1;
890871be 4990 write_lock(&map->lock);
39b5637f 4991 em = lookup_extent_mapping(map, start, len);
285190d9 4992 if (!em) {
890871be 4993 write_unlock(&map->lock);
70dec807
CM
4994 break;
4995 }
7f3c74fb
CM
4996 if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
4997 em->start != start) {
890871be 4998 write_unlock(&map->lock);
70dec807
CM
4999 free_extent_map(em);
5000 break;
5001 }
3d6448e6
FM
5002 if (test_range_bit(tree, em->start,
5003 extent_map_end(em) - 1,
5004 EXTENT_LOCKED, 0, NULL))
5005 goto next;
5006 /*
5007 * If it's not in the list of modified extents, used
5008 * by a fast fsync, we can remove it. If it's being
5009 * logged we can safely remove it since fsync took an
5010 * extra reference on the em.
5011 */
5012 if (list_empty(&em->list) ||
fbc2bd7e
FM
5013 test_bit(EXTENT_FLAG_LOGGING, &em->flags))
5014 goto remove_em;
5015 /*
5016 * If it's in the list of modified extents, remove it
5017 * only if its generation is older then the current one,
5018 * in which case we don't need it for a fast fsync.
5019 * Otherwise don't remove it, we could be racing with an
5020 * ongoing fast fsync that could miss the new extent.
5021 */
5022 fs_info = btrfs_inode->root->fs_info;
5023 spin_lock(&fs_info->trans_lock);
5024 cur_gen = fs_info->generation;
5025 spin_unlock(&fs_info->trans_lock);
5026 if (em->generation >= cur_gen)
5027 goto next;
5028remove_em:
5e548b32
FM
5029 /*
5030 * We only remove extent maps that are not in the list of
5031 * modified extents or that are in the list but with a
5032 * generation lower then the current generation, so there
5033 * is no need to set the full fsync flag on the inode (it
5034 * hurts the fsync performance for workloads with a data
5035 * size that exceeds or is close to the system's memory).
5036 */
fbc2bd7e
FM
5037 remove_extent_mapping(map, em);
5038 /* once for the rb tree */
5039 free_extent_map(em);
3d6448e6 5040next:
70dec807 5041 start = extent_map_end(em);
890871be 5042 write_unlock(&map->lock);
70dec807
CM
5043
5044 /* once for us */
d1310b2e 5045 free_extent_map(em);
9f47eb54
PM
5046
5047 cond_resched(); /* Allow large-extent preemption. */
d1310b2e 5048 }
d1310b2e 5049 }
29c68b2d 5050 return try_release_extent_state(tree, page, mask);
d1310b2e 5051}
d1310b2e 5052
ec29ed5b
CM
5053/*
5054 * helper function for fiemap, which doesn't want to see any holes.
5055 * This maps until we find something past 'last'
5056 */
f1bbde8d 5057static struct extent_map *get_extent_skip_holes(struct btrfs_inode *inode,
e3350e16 5058 u64 offset, u64 last)
ec29ed5b 5059{
f1bbde8d 5060 u64 sectorsize = btrfs_inode_sectorsize(inode);
ec29ed5b
CM
5061 struct extent_map *em;
5062 u64 len;
5063
5064 if (offset >= last)
5065 return NULL;
5066
67871254 5067 while (1) {
ec29ed5b
CM
5068 len = last - offset;
5069 if (len == 0)
5070 break;
fda2832f 5071 len = ALIGN(len, sectorsize);
f1bbde8d 5072 em = btrfs_get_extent_fiemap(inode, offset, len);
c704005d 5073 if (IS_ERR_OR_NULL(em))
ec29ed5b
CM
5074 return em;
5075
5076 /* if this isn't a hole return it */
4a2d25cd 5077 if (em->block_start != EXTENT_MAP_HOLE)
ec29ed5b 5078 return em;
ec29ed5b
CM
5079
5080 /* this is a hole, advance to the next extent */
5081 offset = extent_map_end(em);
5082 free_extent_map(em);
5083 if (offset >= last)
5084 break;
5085 }
5086 return NULL;
5087}
5088
4751832d
QW
5089/*
5090 * To cache previous fiemap extent
5091 *
5092 * Will be used for merging fiemap extent
5093 */
5094struct fiemap_cache {
5095 u64 offset;
5096 u64 phys;
5097 u64 len;
5098 u32 flags;
5099 bool cached;
5100};
5101
5102/*
5103 * Helper to submit fiemap extent.
5104 *
5105 * Will try to merge current fiemap extent specified by @offset, @phys,
5106 * @len and @flags with cached one.
5107 * And only when we fails to merge, cached one will be submitted as
5108 * fiemap extent.
5109 *
5110 * Return value is the same as fiemap_fill_next_extent().
5111 */
5112static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
5113 struct fiemap_cache *cache,
5114 u64 offset, u64 phys, u64 len, u32 flags)
5115{
5116 int ret = 0;
5117
5118 if (!cache->cached)
5119 goto assign;
5120
5121 /*
5122 * Sanity check, extent_fiemap() should have ensured that new
52042d8e 5123 * fiemap extent won't overlap with cached one.
4751832d
QW
5124 * Not recoverable.
5125 *
5126 * NOTE: Physical address can overlap, due to compression
5127 */
5128 if (cache->offset + cache->len > offset) {
5129 WARN_ON(1);
5130 return -EINVAL;
5131 }
5132
5133 /*
5134 * Only merges fiemap extents if
5135 * 1) Their logical addresses are continuous
5136 *
5137 * 2) Their physical addresses are continuous
5138 * So truly compressed (physical size smaller than logical size)
5139 * extents won't get merged with each other
5140 *
5141 * 3) Share same flags except FIEMAP_EXTENT_LAST
5142 * So regular extent won't get merged with prealloc extent
5143 */
5144 if (cache->offset + cache->len == offset &&
5145 cache->phys + cache->len == phys &&
5146 (cache->flags & ~FIEMAP_EXTENT_LAST) ==
5147 (flags & ~FIEMAP_EXTENT_LAST)) {
5148 cache->len += len;
5149 cache->flags |= flags;
5150 goto try_submit_last;
5151 }
5152
5153 /* Not mergeable, need to submit cached one */
5154 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5155 cache->len, cache->flags);
5156 cache->cached = false;
5157 if (ret)
5158 return ret;
5159assign:
5160 cache->cached = true;
5161 cache->offset = offset;
5162 cache->phys = phys;
5163 cache->len = len;
5164 cache->flags = flags;
5165try_submit_last:
5166 if (cache->flags & FIEMAP_EXTENT_LAST) {
5167 ret = fiemap_fill_next_extent(fieinfo, cache->offset,
5168 cache->phys, cache->len, cache->flags);
5169 cache->cached = false;
5170 }
5171 return ret;
5172}
5173
5174/*
848c23b7 5175 * Emit last fiemap cache
4751832d 5176 *
848c23b7
QW
5177 * The last fiemap cache may still be cached in the following case:
5178 * 0 4k 8k
5179 * |<- Fiemap range ->|
5180 * |<------------ First extent ----------->|
5181 *
5182 * In this case, the first extent range will be cached but not emitted.
5183 * So we must emit it before ending extent_fiemap().
4751832d 5184 */
5c5aff98 5185static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
848c23b7 5186 struct fiemap_cache *cache)
4751832d
QW
5187{
5188 int ret;
5189
5190 if (!cache->cached)
5191 return 0;
5192
4751832d
QW
5193 ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
5194 cache->len, cache->flags);
5195 cache->cached = false;
5196 if (ret > 0)
5197 ret = 0;
5198 return ret;
5199}
5200
facee0a0 5201int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
bab16e21 5202 u64 start, u64 len)
1506fcc8 5203{
975f84fe 5204 int ret = 0;
15c7745c 5205 u64 off;
1506fcc8
YS
5206 u64 max = start + len;
5207 u32 flags = 0;
975f84fe
JB
5208 u32 found_type;
5209 u64 last;
ec29ed5b 5210 u64 last_for_get_extent = 0;
1506fcc8 5211 u64 disko = 0;
facee0a0 5212 u64 isize = i_size_read(&inode->vfs_inode);
975f84fe 5213 struct btrfs_key found_key;
1506fcc8 5214 struct extent_map *em = NULL;
2ac55d41 5215 struct extent_state *cached_state = NULL;
975f84fe 5216 struct btrfs_path *path;
facee0a0 5217 struct btrfs_root *root = inode->root;
4751832d 5218 struct fiemap_cache cache = { 0 };
5911c8fe
DS
5219 struct ulist *roots;
5220 struct ulist *tmp_ulist;
1506fcc8 5221 int end = 0;
ec29ed5b
CM
5222 u64 em_start = 0;
5223 u64 em_len = 0;
5224 u64 em_end = 0;
1506fcc8
YS
5225
5226 if (len == 0)
5227 return -EINVAL;
5228
975f84fe
JB
5229 path = btrfs_alloc_path();
5230 if (!path)
5231 return -ENOMEM;
975f84fe 5232
5911c8fe
DS
5233 roots = ulist_alloc(GFP_KERNEL);
5234 tmp_ulist = ulist_alloc(GFP_KERNEL);
5235 if (!roots || !tmp_ulist) {
5236 ret = -ENOMEM;
5237 goto out_free_ulist;
5238 }
5239
15c7745c
BB
5240 /*
5241 * We can't initialize that to 'start' as this could miss extents due
5242 * to extent item merging
5243 */
5244 off = 0;
facee0a0
NB
5245 start = round_down(start, btrfs_inode_sectorsize(inode));
5246 len = round_up(max, btrfs_inode_sectorsize(inode)) - start;
4d479cf0 5247
ec29ed5b
CM
5248 /*
5249 * lookup the last file extent. We're not using i_size here
5250 * because there might be preallocation past i_size
5251 */
facee0a0
NB
5252 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode), -1,
5253 0);
975f84fe 5254 if (ret < 0) {
5911c8fe 5255 goto out_free_ulist;
2d324f59
LB
5256 } else {
5257 WARN_ON(!ret);
5258 if (ret == 1)
5259 ret = 0;
975f84fe 5260 }
2d324f59 5261
975f84fe 5262 path->slots[0]--;
975f84fe 5263 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
962a298f 5264 found_type = found_key.type;
975f84fe 5265
ec29ed5b 5266 /* No extents, but there might be delalloc bits */
facee0a0 5267 if (found_key.objectid != btrfs_ino(inode) ||
975f84fe 5268 found_type != BTRFS_EXTENT_DATA_KEY) {
ec29ed5b
CM
5269 /* have to trust i_size as the end */
5270 last = (u64)-1;
5271 last_for_get_extent = isize;
5272 } else {
5273 /*
5274 * remember the start of the last extent. There are a
5275 * bunch of different factors that go into the length of the
5276 * extent, so its much less complex to remember where it started
5277 */
5278 last = found_key.offset;
5279 last_for_get_extent = last + 1;
975f84fe 5280 }
fe09e16c 5281 btrfs_release_path(path);
975f84fe 5282
ec29ed5b
CM
5283 /*
5284 * we might have some extents allocated but more delalloc past those
5285 * extents. so, we trust isize unless the start of the last extent is
5286 * beyond isize
5287 */
5288 if (last < isize) {
5289 last = (u64)-1;
5290 last_for_get_extent = isize;
5291 }
5292
facee0a0 5293 lock_extent_bits(&inode->io_tree, start, start + len - 1,
d0082371 5294 &cached_state);
ec29ed5b 5295
facee0a0 5296 em = get_extent_skip_holes(inode, start, last_for_get_extent);
1506fcc8
YS
5297 if (!em)
5298 goto out;
5299 if (IS_ERR(em)) {
5300 ret = PTR_ERR(em);
5301 goto out;
5302 }
975f84fe 5303
1506fcc8 5304 while (!end) {
b76bb701 5305 u64 offset_in_extent = 0;
ea8efc74
CM
5306
5307 /* break if the extent we found is outside the range */
5308 if (em->start >= max || extent_map_end(em) < off)
5309 break;
5310
5311 /*
5312 * get_extent may return an extent that starts before our
5313 * requested range. We have to make sure the ranges
5314 * we return to fiemap always move forward and don't
5315 * overlap, so adjust the offsets here
5316 */
5317 em_start = max(em->start, off);
1506fcc8 5318
ea8efc74
CM
5319 /*
5320 * record the offset from the start of the extent
b76bb701
JB
5321 * for adjusting the disk offset below. Only do this if the
5322 * extent isn't compressed since our in ram offset may be past
5323 * what we have actually allocated on disk.
ea8efc74 5324 */
b76bb701
JB
5325 if (!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5326 offset_in_extent = em_start - em->start;
ec29ed5b 5327 em_end = extent_map_end(em);
ea8efc74 5328 em_len = em_end - em_start;
1506fcc8 5329 flags = 0;
f0986318
FM
5330 if (em->block_start < EXTENT_MAP_LAST_BYTE)
5331 disko = em->block_start + offset_in_extent;
5332 else
5333 disko = 0;
1506fcc8 5334
ea8efc74
CM
5335 /*
5336 * bump off for our next call to get_extent
5337 */
5338 off = extent_map_end(em);
5339 if (off >= max)
5340 end = 1;
5341
93dbfad7 5342 if (em->block_start == EXTENT_MAP_LAST_BYTE) {
1506fcc8
YS
5343 end = 1;
5344 flags |= FIEMAP_EXTENT_LAST;
93dbfad7 5345 } else if (em->block_start == EXTENT_MAP_INLINE) {
1506fcc8
YS
5346 flags |= (FIEMAP_EXTENT_DATA_INLINE |
5347 FIEMAP_EXTENT_NOT_ALIGNED);
93dbfad7 5348 } else if (em->block_start == EXTENT_MAP_DELALLOC) {
1506fcc8
YS
5349 flags |= (FIEMAP_EXTENT_DELALLOC |
5350 FIEMAP_EXTENT_UNKNOWN);
dc046b10
JB
5351 } else if (fieinfo->fi_extents_max) {
5352 u64 bytenr = em->block_start -
5353 (em->start - em->orig_start);
fe09e16c 5354
fe09e16c
LB
5355 /*
5356 * As btrfs supports shared space, this information
5357 * can be exported to userspace tools via
dc046b10
JB
5358 * flag FIEMAP_EXTENT_SHARED. If fi_extents_max == 0
5359 * then we're just getting a count and we can skip the
5360 * lookup stuff.
fe09e16c 5361 */
facee0a0 5362 ret = btrfs_check_shared(root, btrfs_ino(inode),
5911c8fe 5363 bytenr, roots, tmp_ulist);
dc046b10 5364 if (ret < 0)
fe09e16c 5365 goto out_free;
dc046b10 5366 if (ret)
fe09e16c 5367 flags |= FIEMAP_EXTENT_SHARED;
dc046b10 5368 ret = 0;
1506fcc8
YS
5369 }
5370 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
5371 flags |= FIEMAP_EXTENT_ENCODED;
0d2b2372
JB
5372 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5373 flags |= FIEMAP_EXTENT_UNWRITTEN;
1506fcc8 5374
1506fcc8
YS
5375 free_extent_map(em);
5376 em = NULL;
ec29ed5b
CM
5377 if ((em_start >= last) || em_len == (u64)-1 ||
5378 (last == (u64)-1 && isize <= em_end)) {
1506fcc8
YS
5379 flags |= FIEMAP_EXTENT_LAST;
5380 end = 1;
5381 }
5382
ec29ed5b 5383 /* now scan forward to see if this is really the last extent. */
facee0a0 5384 em = get_extent_skip_holes(inode, off, last_for_get_extent);
ec29ed5b
CM
5385 if (IS_ERR(em)) {
5386 ret = PTR_ERR(em);
5387 goto out;
5388 }
5389 if (!em) {
975f84fe
JB
5390 flags |= FIEMAP_EXTENT_LAST;
5391 end = 1;
5392 }
4751832d
QW
5393 ret = emit_fiemap_extent(fieinfo, &cache, em_start, disko,
5394 em_len, flags);
26e726af
CS
5395 if (ret) {
5396 if (ret == 1)
5397 ret = 0;
ec29ed5b 5398 goto out_free;
26e726af 5399 }
1506fcc8
YS
5400 }
5401out_free:
4751832d 5402 if (!ret)
5c5aff98 5403 ret = emit_last_fiemap_cache(fieinfo, &cache);
1506fcc8
YS
5404 free_extent_map(em);
5405out:
facee0a0 5406 unlock_extent_cached(&inode->io_tree, start, start + len - 1,
e43bbe5e 5407 &cached_state);
5911c8fe
DS
5408
5409out_free_ulist:
e02d48ea 5410 btrfs_free_path(path);
5911c8fe
DS
5411 ulist_free(roots);
5412 ulist_free(tmp_ulist);
1506fcc8
YS
5413 return ret;
5414}
5415
727011e0
CM
5416static void __free_extent_buffer(struct extent_buffer *eb)
5417{
727011e0
CM
5418 kmem_cache_free(extent_buffer_cache, eb);
5419}
5420
2b48966a 5421int extent_buffer_under_io(const struct extent_buffer *eb)
db7f3436
JB
5422{
5423 return (atomic_read(&eb->io_pages) ||
5424 test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
5425 test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5426}
5427
8ff8466d 5428static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
db7f3436 5429{
8ff8466d 5430 struct btrfs_subpage *subpage;
db7f3436 5431
8ff8466d 5432 lockdep_assert_held(&page->mapping->private_lock);
db7f3436 5433
8ff8466d
QW
5434 if (PagePrivate(page)) {
5435 subpage = (struct btrfs_subpage *)page->private;
5436 if (atomic_read(&subpage->eb_refs))
5437 return true;
5438 }
5439 return false;
5440}
db7f3436 5441
8ff8466d
QW
5442static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
5443{
5444 struct btrfs_fs_info *fs_info = eb->fs_info;
5445 const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
5446
5447 /*
5448 * For mapped eb, we're going to change the page private, which should
5449 * be done under the private_lock.
5450 */
5451 if (mapped)
5452 spin_lock(&page->mapping->private_lock);
5453
5454 if (!PagePrivate(page)) {
5d2361db 5455 if (mapped)
8ff8466d
QW
5456 spin_unlock(&page->mapping->private_lock);
5457 return;
5458 }
5459
5460 if (fs_info->sectorsize == PAGE_SIZE) {
5d2361db
FL
5461 /*
5462 * We do this since we'll remove the pages after we've
5463 * removed the eb from the radix tree, so we could race
5464 * and have this page now attached to the new eb. So
5465 * only clear page_private if it's still connected to
5466 * this eb.
5467 */
5468 if (PagePrivate(page) &&
5469 page->private == (unsigned long)eb) {
5470 BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5471 BUG_ON(PageDirty(page));
5472 BUG_ON(PageWriteback(page));
db7f3436 5473 /*
5d2361db
FL
5474 * We need to make sure we haven't be attached
5475 * to a new eb.
db7f3436 5476 */
d1b89bc0 5477 detach_page_private(page);
db7f3436 5478 }
5d2361db
FL
5479 if (mapped)
5480 spin_unlock(&page->mapping->private_lock);
8ff8466d
QW
5481 return;
5482 }
5483
5484 /*
5485 * For subpage, we can have dummy eb with page private. In this case,
5486 * we can directly detach the private as such page is only attached to
5487 * one dummy eb, no sharing.
5488 */
5489 if (!mapped) {
5490 btrfs_detach_subpage(fs_info, page);
5491 return;
5492 }
5493
5494 btrfs_page_dec_eb_refs(fs_info, page);
5495
5496 /*
5497 * We can only detach the page private if there are no other ebs in the
5498 * page range.
5499 */
5500 if (!page_range_has_eb(fs_info, page))
5501 btrfs_detach_subpage(fs_info, page);
5502
5503 spin_unlock(&page->mapping->private_lock);
5504}
5505
5506/* Release all pages attached to the extent buffer */
5507static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
5508{
5509 int i;
5510 int num_pages;
5511
5512 ASSERT(!extent_buffer_under_io(eb));
5513
5514 num_pages = num_extent_pages(eb);
5515 for (i = 0; i < num_pages; i++) {
5516 struct page *page = eb->pages[i];
5517
5518 if (!page)
5519 continue;
5520
5521 detach_extent_buffer_page(eb, page);
5d2361db 5522
01327610 5523 /* One for when we allocated the page */
09cbfeaf 5524 put_page(page);
d64766fd 5525 }
db7f3436
JB
5526}
5527
5528/*
5529 * Helper for releasing the extent buffer.
5530 */
5531static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
5532{
55ac0139 5533 btrfs_release_extent_buffer_pages(eb);
8c38938c 5534 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
db7f3436
JB
5535 __free_extent_buffer(eb);
5536}
5537
f28491e0
JB
5538static struct extent_buffer *
5539__alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
23d79d81 5540 unsigned long len)
d1310b2e
CM
5541{
5542 struct extent_buffer *eb = NULL;
5543
d1b5c567 5544 eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
d1310b2e
CM
5545 eb->start = start;
5546 eb->len = len;
f28491e0 5547 eb->fs_info = fs_info;
815a51c7 5548 eb->bflags = 0;
196d59ab 5549 init_rwsem(&eb->lock);
b4ce94de 5550
3fd63727
JB
5551 btrfs_leak_debug_add(&fs_info->eb_leak_lock, &eb->leak_list,
5552 &fs_info->allocated_ebs);
d3575156 5553 INIT_LIST_HEAD(&eb->release_list);
6d49ba1b 5554
3083ee2e 5555 spin_lock_init(&eb->refs_lock);
d1310b2e 5556 atomic_set(&eb->refs, 1);
0b32f4bb 5557 atomic_set(&eb->io_pages, 0);
727011e0 5558
deb67895 5559 ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
d1310b2e
CM
5560
5561 return eb;
5562}
5563
2b48966a 5564struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
815a51c7 5565{
cc5e31a4 5566 int i;
815a51c7
JS
5567 struct page *p;
5568 struct extent_buffer *new;
cc5e31a4 5569 int num_pages = num_extent_pages(src);
815a51c7 5570
3f556f78 5571 new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
815a51c7
JS
5572 if (new == NULL)
5573 return NULL;
5574
62c053fb
QW
5575 /*
5576 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
5577 * btrfs_release_extent_buffer() have different behavior for
5578 * UNMAPPED subpage extent buffer.
5579 */
5580 set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
5581
815a51c7 5582 for (i = 0; i < num_pages; i++) {
760f991f
QW
5583 int ret;
5584
9ec72677 5585 p = alloc_page(GFP_NOFS);
db7f3436
JB
5586 if (!p) {
5587 btrfs_release_extent_buffer(new);
5588 return NULL;
5589 }
760f991f
QW
5590 ret = attach_extent_buffer_page(new, p, NULL);
5591 if (ret < 0) {
5592 put_page(p);
5593 btrfs_release_extent_buffer(new);
5594 return NULL;
5595 }
815a51c7 5596 WARN_ON(PageDirty(p));
815a51c7 5597 new->pages[i] = p;
fba1acf9 5598 copy_page(page_address(p), page_address(src->pages[i]));
815a51c7 5599 }
92d83e94 5600 set_extent_buffer_uptodate(new);
815a51c7
JS
5601
5602 return new;
5603}
5604
0f331229
OS
5605struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
5606 u64 start, unsigned long len)
815a51c7
JS
5607{
5608 struct extent_buffer *eb;
cc5e31a4
DS
5609 int num_pages;
5610 int i;
815a51c7 5611
3f556f78 5612 eb = __alloc_extent_buffer(fs_info, start, len);
815a51c7
JS
5613 if (!eb)
5614 return NULL;
5615
65ad0104 5616 num_pages = num_extent_pages(eb);
815a51c7 5617 for (i = 0; i < num_pages; i++) {
09bc1f0f
QW
5618 int ret;
5619
9ec72677 5620 eb->pages[i] = alloc_page(GFP_NOFS);
815a51c7
JS
5621 if (!eb->pages[i])
5622 goto err;
09bc1f0f
QW
5623 ret = attach_extent_buffer_page(eb, eb->pages[i], NULL);
5624 if (ret < 0)
5625 goto err;
815a51c7
JS
5626 }
5627 set_extent_buffer_uptodate(eb);
5628 btrfs_set_header_nritems(eb, 0);
b0132a3b 5629 set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
815a51c7
JS
5630
5631 return eb;
5632err:
09bc1f0f
QW
5633 for (; i > 0; i--) {
5634 detach_extent_buffer_page(eb, eb->pages[i - 1]);
84167d19 5635 __free_page(eb->pages[i - 1]);
09bc1f0f 5636 }
815a51c7
JS
5637 __free_extent_buffer(eb);
5638 return NULL;
5639}
5640
0f331229 5641struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
da17066c 5642 u64 start)
0f331229 5643{
da17066c 5644 return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
0f331229
OS
5645}
5646
0b32f4bb
JB
5647static void check_buffer_tree_ref(struct extent_buffer *eb)
5648{
242e18c7 5649 int refs;
6bf9cd2e
BB
5650 /*
5651 * The TREE_REF bit is first set when the extent_buffer is added
5652 * to the radix tree. It is also reset, if unset, when a new reference
5653 * is created by find_extent_buffer.
0b32f4bb 5654 *
6bf9cd2e
BB
5655 * It is only cleared in two cases: freeing the last non-tree
5656 * reference to the extent_buffer when its STALE bit is set or
5657 * calling releasepage when the tree reference is the only reference.
0b32f4bb 5658 *
6bf9cd2e
BB
5659 * In both cases, care is taken to ensure that the extent_buffer's
5660 * pages are not under io. However, releasepage can be concurrently
5661 * called with creating new references, which is prone to race
5662 * conditions between the calls to check_buffer_tree_ref in those
5663 * codepaths and clearing TREE_REF in try_release_extent_buffer.
0b32f4bb 5664 *
6bf9cd2e
BB
5665 * The actual lifetime of the extent_buffer in the radix tree is
5666 * adequately protected by the refcount, but the TREE_REF bit and
5667 * its corresponding reference are not. To protect against this
5668 * class of races, we call check_buffer_tree_ref from the codepaths
5669 * which trigger io after they set eb->io_pages. Note that once io is
5670 * initiated, TREE_REF can no longer be cleared, so that is the
5671 * moment at which any such race is best fixed.
0b32f4bb 5672 */
242e18c7
CM
5673 refs = atomic_read(&eb->refs);
5674 if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
5675 return;
5676
594831c4
JB
5677 spin_lock(&eb->refs_lock);
5678 if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
0b32f4bb 5679 atomic_inc(&eb->refs);
594831c4 5680 spin_unlock(&eb->refs_lock);
0b32f4bb
JB
5681}
5682
2457aec6
MG
5683static void mark_extent_buffer_accessed(struct extent_buffer *eb,
5684 struct page *accessed)
5df4235e 5685{
cc5e31a4 5686 int num_pages, i;
5df4235e 5687
0b32f4bb
JB
5688 check_buffer_tree_ref(eb);
5689
65ad0104 5690 num_pages = num_extent_pages(eb);
5df4235e 5691 for (i = 0; i < num_pages; i++) {
fb85fc9a
DS
5692 struct page *p = eb->pages[i];
5693
2457aec6
MG
5694 if (p != accessed)
5695 mark_page_accessed(p);
5df4235e
JB
5696 }
5697}
5698
f28491e0
JB
5699struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
5700 u64 start)
452c75c3
CS
5701{
5702 struct extent_buffer *eb;
5703
2f3186d8
QW
5704 eb = find_extent_buffer_nolock(fs_info, start);
5705 if (!eb)
5706 return NULL;
5707 /*
5708 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
5709 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
5710 * another task running free_extent_buffer() might have seen that flag
5711 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
5712 * writeback flags not set) and it's still in the tree (flag
5713 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
5714 * decrementing the extent buffer's reference count twice. So here we
5715 * could race and increment the eb's reference count, clear its stale
5716 * flag, mark it as dirty and drop our reference before the other task
5717 * finishes executing free_extent_buffer, which would later result in
5718 * an attempt to free an extent buffer that is dirty.
5719 */
5720 if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
5721 spin_lock(&eb->refs_lock);
5722 spin_unlock(&eb->refs_lock);
452c75c3 5723 }
2f3186d8
QW
5724 mark_extent_buffer_accessed(eb, NULL);
5725 return eb;
452c75c3
CS
5726}
5727
faa2dbf0
JB
5728#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5729struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
da17066c 5730 u64 start)
faa2dbf0
JB
5731{
5732 struct extent_buffer *eb, *exists = NULL;
5733 int ret;
5734
5735 eb = find_extent_buffer(fs_info, start);
5736 if (eb)
5737 return eb;
da17066c 5738 eb = alloc_dummy_extent_buffer(fs_info, start);
faa2dbf0 5739 if (!eb)
b6293c82 5740 return ERR_PTR(-ENOMEM);
faa2dbf0
JB
5741 eb->fs_info = fs_info;
5742again:
e1860a77 5743 ret = radix_tree_preload(GFP_NOFS);
b6293c82
DC
5744 if (ret) {
5745 exists = ERR_PTR(ret);
faa2dbf0 5746 goto free_eb;
b6293c82 5747 }
faa2dbf0
JB
5748 spin_lock(&fs_info->buffer_lock);
5749 ret = radix_tree_insert(&fs_info->buffer_radix,
478ef886 5750 start >> fs_info->sectorsize_bits, eb);
faa2dbf0
JB
5751 spin_unlock(&fs_info->buffer_lock);
5752 radix_tree_preload_end();
5753 if (ret == -EEXIST) {
5754 exists = find_extent_buffer(fs_info, start);
5755 if (exists)
5756 goto free_eb;
5757 else
5758 goto again;
5759 }
5760 check_buffer_tree_ref(eb);
5761 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
5762
faa2dbf0
JB
5763 return eb;
5764free_eb:
5765 btrfs_release_extent_buffer(eb);
5766 return exists;
5767}
5768#endif
5769
81982210
QW
5770static struct extent_buffer *grab_extent_buffer(
5771 struct btrfs_fs_info *fs_info, struct page *page)
c0f0a9e7
QW
5772{
5773 struct extent_buffer *exists;
5774
81982210
QW
5775 /*
5776 * For subpage case, we completely rely on radix tree to ensure we
5777 * don't try to insert two ebs for the same bytenr. So here we always
5778 * return NULL and just continue.
5779 */
5780 if (fs_info->sectorsize < PAGE_SIZE)
5781 return NULL;
5782
c0f0a9e7
QW
5783 /* Page not yet attached to an extent buffer */
5784 if (!PagePrivate(page))
5785 return NULL;
5786
5787 /*
5788 * We could have already allocated an eb for this page and attached one
5789 * so lets see if we can get a ref on the existing eb, and if we can we
5790 * know it's good and we can just return that one, else we know we can
5791 * just overwrite page->private.
5792 */
5793 exists = (struct extent_buffer *)page->private;
5794 if (atomic_inc_not_zero(&exists->refs))
5795 return exists;
5796
5797 WARN_ON(PageDirty(page));
5798 detach_page_private(page);
5799 return NULL;
5800}
5801
f28491e0 5802struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
3fbaf258 5803 u64 start, u64 owner_root, int level)
d1310b2e 5804{
da17066c 5805 unsigned long len = fs_info->nodesize;
cc5e31a4
DS
5806 int num_pages;
5807 int i;
09cbfeaf 5808 unsigned long index = start >> PAGE_SHIFT;
d1310b2e 5809 struct extent_buffer *eb;
6af118ce 5810 struct extent_buffer *exists = NULL;
d1310b2e 5811 struct page *p;
f28491e0 5812 struct address_space *mapping = fs_info->btree_inode->i_mapping;
d1310b2e 5813 int uptodate = 1;
19fe0a8b 5814 int ret;
d1310b2e 5815
da17066c 5816 if (!IS_ALIGNED(start, fs_info->sectorsize)) {
c871b0f2
LB
5817 btrfs_err(fs_info, "bad tree block start %llu", start);
5818 return ERR_PTR(-EINVAL);
5819 }
5820
e9306ad4
QW
5821#if BITS_PER_LONG == 32
5822 if (start >= MAX_LFS_FILESIZE) {
5823 btrfs_err_rl(fs_info,
5824 "extent buffer %llu is beyond 32bit page cache limit", start);
5825 btrfs_err_32bit_limit(fs_info);
5826 return ERR_PTR(-EOVERFLOW);
5827 }
5828 if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
5829 btrfs_warn_32bit_limit(fs_info);
5830#endif
5831
1aaac38c
QW
5832 if (fs_info->sectorsize < PAGE_SIZE &&
5833 offset_in_page(start) + len > PAGE_SIZE) {
5834 btrfs_err(fs_info,
5835 "tree block crosses page boundary, start %llu nodesize %lu",
5836 start, len);
5837 return ERR_PTR(-EINVAL);
5838 }
5839
f28491e0 5840 eb = find_extent_buffer(fs_info, start);
452c75c3 5841 if (eb)
6af118ce 5842 return eb;
6af118ce 5843
23d79d81 5844 eb = __alloc_extent_buffer(fs_info, start, len);
2b114d1d 5845 if (!eb)
c871b0f2 5846 return ERR_PTR(-ENOMEM);
e114c545 5847 btrfs_set_buffer_lockdep_class(owner_root, eb, level);
d1310b2e 5848
65ad0104 5849 num_pages = num_extent_pages(eb);
727011e0 5850 for (i = 0; i < num_pages; i++, index++) {
760f991f
QW
5851 struct btrfs_subpage *prealloc = NULL;
5852
d1b5c567 5853 p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
c871b0f2
LB
5854 if (!p) {
5855 exists = ERR_PTR(-ENOMEM);
6af118ce 5856 goto free_eb;
c871b0f2 5857 }
4f2de97a 5858
760f991f
QW
5859 /*
5860 * Preallocate page->private for subpage case, so that we won't
5861 * allocate memory with private_lock hold. The memory will be
5862 * freed by attach_extent_buffer_page() or freed manually if
5863 * we exit earlier.
5864 *
5865 * Although we have ensured one subpage eb can only have one
5866 * page, but it may change in the future for 16K page size
5867 * support, so we still preallocate the memory in the loop.
5868 */
5869 ret = btrfs_alloc_subpage(fs_info, &prealloc,
5870 BTRFS_SUBPAGE_METADATA);
5871 if (ret < 0) {
5872 unlock_page(p);
5873 put_page(p);
5874 exists = ERR_PTR(ret);
5875 goto free_eb;
5876 }
5877
4f2de97a 5878 spin_lock(&mapping->private_lock);
81982210 5879 exists = grab_extent_buffer(fs_info, p);
c0f0a9e7
QW
5880 if (exists) {
5881 spin_unlock(&mapping->private_lock);
5882 unlock_page(p);
5883 put_page(p);
5884 mark_extent_buffer_accessed(exists, p);
760f991f 5885 btrfs_free_subpage(prealloc);
c0f0a9e7 5886 goto free_eb;
d1310b2e 5887 }
760f991f
QW
5888 /* Should not fail, as we have preallocated the memory */
5889 ret = attach_extent_buffer_page(eb, p, prealloc);
5890 ASSERT(!ret);
8ff8466d
QW
5891 /*
5892 * To inform we have extra eb under allocation, so that
5893 * detach_extent_buffer_page() won't release the page private
5894 * when the eb hasn't yet been inserted into radix tree.
5895 *
5896 * The ref will be decreased when the eb released the page, in
5897 * detach_extent_buffer_page().
5898 * Thus needs no special handling in error path.
5899 */
5900 btrfs_page_inc_eb_refs(fs_info, p);
4f2de97a 5901 spin_unlock(&mapping->private_lock);
760f991f 5902
1e5eb3d6 5903 WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
727011e0 5904 eb->pages[i] = p;
d1310b2e
CM
5905 if (!PageUptodate(p))
5906 uptodate = 0;
eb14ab8e
CM
5907
5908 /*
b16d011e
NB
5909 * We can't unlock the pages just yet since the extent buffer
5910 * hasn't been properly inserted in the radix tree, this
5911 * opens a race with btree_releasepage which can free a page
5912 * while we are still filling in all pages for the buffer and
5913 * we could crash.
eb14ab8e 5914 */
d1310b2e
CM
5915 }
5916 if (uptodate)
b4ce94de 5917 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
115391d2 5918again:
e1860a77 5919 ret = radix_tree_preload(GFP_NOFS);
c871b0f2
LB
5920 if (ret) {
5921 exists = ERR_PTR(ret);
19fe0a8b 5922 goto free_eb;
c871b0f2 5923 }
19fe0a8b 5924
f28491e0
JB
5925 spin_lock(&fs_info->buffer_lock);
5926 ret = radix_tree_insert(&fs_info->buffer_radix,
478ef886 5927 start >> fs_info->sectorsize_bits, eb);
f28491e0 5928 spin_unlock(&fs_info->buffer_lock);
452c75c3 5929 radix_tree_preload_end();
19fe0a8b 5930 if (ret == -EEXIST) {
f28491e0 5931 exists = find_extent_buffer(fs_info, start);
452c75c3
CS
5932 if (exists)
5933 goto free_eb;
5934 else
115391d2 5935 goto again;
6af118ce 5936 }
6af118ce 5937 /* add one reference for the tree */
0b32f4bb 5938 check_buffer_tree_ref(eb);
34b41ace 5939 set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
eb14ab8e
CM
5940
5941 /*
b16d011e
NB
5942 * Now it's safe to unlock the pages because any calls to
5943 * btree_releasepage will correctly detect that a page belongs to a
5944 * live buffer and won't free them prematurely.
eb14ab8e 5945 */
28187ae5
NB
5946 for (i = 0; i < num_pages; i++)
5947 unlock_page(eb->pages[i]);
d1310b2e
CM
5948 return eb;
5949
6af118ce 5950free_eb:
5ca64f45 5951 WARN_ON(!atomic_dec_and_test(&eb->refs));
727011e0
CM
5952 for (i = 0; i < num_pages; i++) {
5953 if (eb->pages[i])
5954 unlock_page(eb->pages[i]);
5955 }
eb14ab8e 5956
897ca6e9 5957 btrfs_release_extent_buffer(eb);
6af118ce 5958 return exists;
d1310b2e 5959}
d1310b2e 5960
3083ee2e
JB
5961static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
5962{
5963 struct extent_buffer *eb =
5964 container_of(head, struct extent_buffer, rcu_head);
5965
5966 __free_extent_buffer(eb);
5967}
5968
f7a52a40 5969static int release_extent_buffer(struct extent_buffer *eb)
5ce48d0f 5970 __releases(&eb->refs_lock)
3083ee2e 5971{
07e21c4d
NB
5972 lockdep_assert_held(&eb->refs_lock);
5973
3083ee2e
JB
5974 WARN_ON(atomic_read(&eb->refs) == 0);
5975 if (atomic_dec_and_test(&eb->refs)) {
34b41ace 5976 if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
f28491e0 5977 struct btrfs_fs_info *fs_info = eb->fs_info;
3083ee2e 5978
815a51c7 5979 spin_unlock(&eb->refs_lock);
3083ee2e 5980
f28491e0
JB
5981 spin_lock(&fs_info->buffer_lock);
5982 radix_tree_delete(&fs_info->buffer_radix,
478ef886 5983 eb->start >> fs_info->sectorsize_bits);
f28491e0 5984 spin_unlock(&fs_info->buffer_lock);
34b41ace
JB
5985 } else {
5986 spin_unlock(&eb->refs_lock);
815a51c7 5987 }
3083ee2e 5988
8c38938c 5989 btrfs_leak_debug_del(&eb->fs_info->eb_leak_lock, &eb->leak_list);
3083ee2e 5990 /* Should be safe to release our pages at this point */
55ac0139 5991 btrfs_release_extent_buffer_pages(eb);
bcb7e449 5992#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
b0132a3b 5993 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
bcb7e449
JB
5994 __free_extent_buffer(eb);
5995 return 1;
5996 }
5997#endif
3083ee2e 5998 call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
e64860aa 5999 return 1;
3083ee2e
JB
6000 }
6001 spin_unlock(&eb->refs_lock);
e64860aa
JB
6002
6003 return 0;
3083ee2e
JB
6004}
6005
d1310b2e
CM
6006void free_extent_buffer(struct extent_buffer *eb)
6007{
242e18c7
CM
6008 int refs;
6009 int old;
d1310b2e
CM
6010 if (!eb)
6011 return;
6012
242e18c7
CM
6013 while (1) {
6014 refs = atomic_read(&eb->refs);
46cc775e
NB
6015 if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
6016 || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
6017 refs == 1))
242e18c7
CM
6018 break;
6019 old = atomic_cmpxchg(&eb->refs, refs, refs - 1);
6020 if (old == refs)
6021 return;
6022 }
6023
3083ee2e
JB
6024 spin_lock(&eb->refs_lock);
6025 if (atomic_read(&eb->refs) == 2 &&
6026 test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
0b32f4bb 6027 !extent_buffer_under_io(eb) &&
3083ee2e
JB
6028 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6029 atomic_dec(&eb->refs);
6030
6031 /*
6032 * I know this is terrible, but it's temporary until we stop tracking
6033 * the uptodate bits and such for the extent buffers.
6034 */
f7a52a40 6035 release_extent_buffer(eb);
3083ee2e
JB
6036}
6037
6038void free_extent_buffer_stale(struct extent_buffer *eb)
6039{
6040 if (!eb)
d1310b2e
CM
6041 return;
6042
3083ee2e
JB
6043 spin_lock(&eb->refs_lock);
6044 set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
6045
0b32f4bb 6046 if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
3083ee2e
JB
6047 test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
6048 atomic_dec(&eb->refs);
f7a52a40 6049 release_extent_buffer(eb);
d1310b2e 6050}
d1310b2e 6051
0d27797e
QW
6052static void btree_clear_page_dirty(struct page *page)
6053{
6054 ASSERT(PageDirty(page));
6055 ASSERT(PageLocked(page));
6056 clear_page_dirty_for_io(page);
6057 xa_lock_irq(&page->mapping->i_pages);
6058 if (!PageDirty(page))
6059 __xa_clear_mark(&page->mapping->i_pages,
6060 page_index(page), PAGECACHE_TAG_DIRTY);
6061 xa_unlock_irq(&page->mapping->i_pages);
6062}
6063
6064static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
6065{
6066 struct btrfs_fs_info *fs_info = eb->fs_info;
6067 struct page *page = eb->pages[0];
6068 bool last;
6069
6070 /* btree_clear_page_dirty() needs page locked */
6071 lock_page(page);
6072 last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
6073 eb->len);
6074 if (last)
6075 btree_clear_page_dirty(page);
6076 unlock_page(page);
6077 WARN_ON(atomic_read(&eb->refs) == 0);
6078}
6079
2b48966a 6080void clear_extent_buffer_dirty(const struct extent_buffer *eb)
d1310b2e 6081{
cc5e31a4
DS
6082 int i;
6083 int num_pages;
d1310b2e
CM
6084 struct page *page;
6085
0d27797e
QW
6086 if (eb->fs_info->sectorsize < PAGE_SIZE)
6087 return clear_subpage_extent_buffer_dirty(eb);
6088
65ad0104 6089 num_pages = num_extent_pages(eb);
d1310b2e
CM
6090
6091 for (i = 0; i < num_pages; i++) {
fb85fc9a 6092 page = eb->pages[i];
b9473439 6093 if (!PageDirty(page))
d2c3f4f6 6094 continue;
a61e6f29 6095 lock_page(page);
0d27797e 6096 btree_clear_page_dirty(page);
bf0da8c1 6097 ClearPageError(page);
a61e6f29 6098 unlock_page(page);
d1310b2e 6099 }
0b32f4bb 6100 WARN_ON(atomic_read(&eb->refs) == 0);
d1310b2e 6101}
d1310b2e 6102
abb57ef3 6103bool set_extent_buffer_dirty(struct extent_buffer *eb)
d1310b2e 6104{
cc5e31a4
DS
6105 int i;
6106 int num_pages;
abb57ef3 6107 bool was_dirty;
d1310b2e 6108
0b32f4bb
JB
6109 check_buffer_tree_ref(eb);
6110
b9473439 6111 was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
0b32f4bb 6112
65ad0104 6113 num_pages = num_extent_pages(eb);
3083ee2e 6114 WARN_ON(atomic_read(&eb->refs) == 0);
0b32f4bb
JB
6115 WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
6116
0d27797e
QW
6117 if (!was_dirty) {
6118 bool subpage = eb->fs_info->sectorsize < PAGE_SIZE;
51995c39 6119
0d27797e
QW
6120 /*
6121 * For subpage case, we can have other extent buffers in the
6122 * same page, and in clear_subpage_extent_buffer_dirty() we
6123 * have to clear page dirty without subpage lock held.
6124 * This can cause race where our page gets dirty cleared after
6125 * we just set it.
6126 *
6127 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
6128 * its page for other reasons, we can use page lock to prevent
6129 * the above race.
6130 */
6131 if (subpage)
6132 lock_page(eb->pages[0]);
6133 for (i = 0; i < num_pages; i++)
6134 btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
6135 eb->start, eb->len);
6136 if (subpage)
6137 unlock_page(eb->pages[0]);
6138 }
51995c39
LB
6139#ifdef CONFIG_BTRFS_DEBUG
6140 for (i = 0; i < num_pages; i++)
6141 ASSERT(PageDirty(eb->pages[i]));
6142#endif
6143
b9473439 6144 return was_dirty;
d1310b2e 6145}
d1310b2e 6146
69ba3927 6147void clear_extent_buffer_uptodate(struct extent_buffer *eb)
1259ab75 6148{
251f2acc 6149 struct btrfs_fs_info *fs_info = eb->fs_info;
1259ab75 6150 struct page *page;
cc5e31a4 6151 int num_pages;
251f2acc 6152 int i;
1259ab75 6153
b4ce94de 6154 clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
65ad0104 6155 num_pages = num_extent_pages(eb);
1259ab75 6156 for (i = 0; i < num_pages; i++) {
fb85fc9a 6157 page = eb->pages[i];
33958dc6 6158 if (page)
251f2acc
QW
6159 btrfs_page_clear_uptodate(fs_info, page,
6160 eb->start, eb->len);
1259ab75 6161 }
1259ab75
CM
6162}
6163
09c25a8c 6164void set_extent_buffer_uptodate(struct extent_buffer *eb)
d1310b2e 6165{
251f2acc 6166 struct btrfs_fs_info *fs_info = eb->fs_info;
d1310b2e 6167 struct page *page;
cc5e31a4 6168 int num_pages;
251f2acc 6169 int i;
d1310b2e 6170
0b32f4bb 6171 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
65ad0104 6172 num_pages = num_extent_pages(eb);
d1310b2e 6173 for (i = 0; i < num_pages; i++) {
fb85fc9a 6174 page = eb->pages[i];
251f2acc 6175 btrfs_page_set_uptodate(fs_info, page, eb->start, eb->len);
d1310b2e 6176 }
d1310b2e 6177}
d1310b2e 6178
4012daf7
QW
6179static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
6180 int mirror_num)
6181{
6182 struct btrfs_fs_info *fs_info = eb->fs_info;
6183 struct extent_io_tree *io_tree;
6184 struct page *page = eb->pages[0];
6185 struct bio *bio = NULL;
6186 int ret = 0;
6187
6188 ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
6189 ASSERT(PagePrivate(page));
6190 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
6191
6192 if (wait == WAIT_NONE) {
dc56219f
GR
6193 if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1))
6194 return -EAGAIN;
4012daf7
QW
6195 } else {
6196 ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6197 if (ret < 0)
6198 return ret;
6199 }
6200
6201 ret = 0;
6202 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
6203 PageUptodate(page) ||
6204 btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
6205 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
6206 unlock_extent(io_tree, eb->start, eb->start + eb->len - 1);
6207 return ret;
6208 }
6209
6210 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6211 eb->read_mirror = 0;
6212 atomic_set(&eb->io_pages, 1);
6213 check_buffer_tree_ref(eb);
6214 btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
6215
6216 ret = submit_extent_page(REQ_OP_READ | REQ_META, NULL, page, eb->start,
6217 eb->len, eb->start - page_offset(page), &bio,
6218 end_bio_extent_readpage, mirror_num, 0, 0,
6219 true);
6220 if (ret) {
6221 /*
6222 * In the endio function, if we hit something wrong we will
6223 * increase the io_pages, so here we need to decrease it for
6224 * error path.
6225 */
6226 atomic_dec(&eb->io_pages);
6227 }
6228 if (bio) {
6229 int tmp;
6230
6231 tmp = submit_one_bio(bio, mirror_num, 0);
6232 if (tmp < 0)
6233 return tmp;
6234 }
6235 if (ret || wait != WAIT_COMPLETE)
6236 return ret;
6237
6238 wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
6239 if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
6240 ret = -EIO;
6241 return ret;
6242}
6243
c2ccfbc6 6244int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
d1310b2e 6245{
cc5e31a4 6246 int i;
d1310b2e
CM
6247 struct page *page;
6248 int err;
6249 int ret = 0;
ce9adaa5
CM
6250 int locked_pages = 0;
6251 int all_uptodate = 1;
cc5e31a4 6252 int num_pages;
727011e0 6253 unsigned long num_reads = 0;
a86c12c7 6254 struct bio *bio = NULL;
c8b97818 6255 unsigned long bio_flags = 0;
a86c12c7 6256
b4ce94de 6257 if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
d1310b2e
CM
6258 return 0;
6259
4012daf7
QW
6260 if (eb->fs_info->sectorsize < PAGE_SIZE)
6261 return read_extent_buffer_subpage(eb, wait, mirror_num);
6262
65ad0104 6263 num_pages = num_extent_pages(eb);
8436ea91 6264 for (i = 0; i < num_pages; i++) {
fb85fc9a 6265 page = eb->pages[i];
bb82ab88 6266 if (wait == WAIT_NONE) {
2c4d8cb7
QW
6267 /*
6268 * WAIT_NONE is only utilized by readahead. If we can't
6269 * acquire the lock atomically it means either the eb
6270 * is being read out or under modification.
6271 * Either way the eb will be or has been cached,
6272 * readahead can exit safely.
6273 */
2db04966 6274 if (!trylock_page(page))
ce9adaa5 6275 goto unlock_exit;
d1310b2e
CM
6276 } else {
6277 lock_page(page);
6278 }
ce9adaa5 6279 locked_pages++;
2571e739
LB
6280 }
6281 /*
6282 * We need to firstly lock all pages to make sure that
6283 * the uptodate bit of our pages won't be affected by
6284 * clear_extent_buffer_uptodate().
6285 */
8436ea91 6286 for (i = 0; i < num_pages; i++) {
2571e739 6287 page = eb->pages[i];
727011e0
CM
6288 if (!PageUptodate(page)) {
6289 num_reads++;
ce9adaa5 6290 all_uptodate = 0;
727011e0 6291 }
ce9adaa5 6292 }
2571e739 6293
ce9adaa5 6294 if (all_uptodate) {
8436ea91 6295 set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
ce9adaa5
CM
6296 goto unlock_exit;
6297 }
6298
656f30db 6299 clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5cf1ab56 6300 eb->read_mirror = 0;
0b32f4bb 6301 atomic_set(&eb->io_pages, num_reads);
6bf9cd2e
BB
6302 /*
6303 * It is possible for releasepage to clear the TREE_REF bit before we
6304 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
6305 */
6306 check_buffer_tree_ref(eb);
8436ea91 6307 for (i = 0; i < num_pages; i++) {
fb85fc9a 6308 page = eb->pages[i];
baf863b9 6309
ce9adaa5 6310 if (!PageUptodate(page)) {
baf863b9
LB
6311 if (ret) {
6312 atomic_dec(&eb->io_pages);
6313 unlock_page(page);
6314 continue;
6315 }
6316
f188591e 6317 ClearPageError(page);
0420177c
NB
6318 err = submit_extent_page(REQ_OP_READ | REQ_META, NULL,
6319 page, page_offset(page), PAGE_SIZE, 0,
6320 &bio, end_bio_extent_readpage,
6321 mirror_num, 0, 0, false);
baf863b9 6322 if (err) {
baf863b9 6323 /*
0420177c
NB
6324 * We failed to submit the bio so it's the
6325 * caller's responsibility to perform cleanup
6326 * i.e unlock page/set error bit.
baf863b9 6327 */
0420177c
NB
6328 ret = err;
6329 SetPageError(page);
6330 unlock_page(page);
baf863b9
LB
6331 atomic_dec(&eb->io_pages);
6332 }
d1310b2e
CM
6333 } else {
6334 unlock_page(page);
6335 }
6336 }
6337
355808c2 6338 if (bio) {
1f7ad75b 6339 err = submit_one_bio(bio, mirror_num, bio_flags);
79787eaa
JM
6340 if (err)
6341 return err;
355808c2 6342 }
a86c12c7 6343
bb82ab88 6344 if (ret || wait != WAIT_COMPLETE)
d1310b2e 6345 return ret;
d397712b 6346
8436ea91 6347 for (i = 0; i < num_pages; i++) {
fb85fc9a 6348 page = eb->pages[i];
d1310b2e 6349 wait_on_page_locked(page);
d397712b 6350 if (!PageUptodate(page))
d1310b2e 6351 ret = -EIO;
d1310b2e 6352 }
d397712b 6353
d1310b2e 6354 return ret;
ce9adaa5
CM
6355
6356unlock_exit:
d397712b 6357 while (locked_pages > 0) {
ce9adaa5 6358 locked_pages--;
8436ea91
JB
6359 page = eb->pages[locked_pages];
6360 unlock_page(page);
ce9adaa5
CM
6361 }
6362 return ret;
d1310b2e 6363}
d1310b2e 6364
f98b6215
QW
6365static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
6366 unsigned long len)
6367{
6368 btrfs_warn(eb->fs_info,
6369 "access to eb bytenr %llu len %lu out of range start %lu len %lu",
6370 eb->start, eb->len, start, len);
6371 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
6372
6373 return true;
6374}
6375
6376/*
6377 * Check if the [start, start + len) range is valid before reading/writing
6378 * the eb.
6379 * NOTE: @start and @len are offset inside the eb, not logical address.
6380 *
6381 * Caller should not touch the dst/src memory if this function returns error.
6382 */
6383static inline int check_eb_range(const struct extent_buffer *eb,
6384 unsigned long start, unsigned long len)
6385{
6386 unsigned long offset;
6387
6388 /* start, start + len should not go beyond eb->len nor overflow */
6389 if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
6390 return report_eb_range(eb, start, len);
6391
6392 return false;
6393}
6394
1cbb1f45
JM
6395void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
6396 unsigned long start, unsigned long len)
d1310b2e
CM
6397{
6398 size_t cur;
6399 size_t offset;
6400 struct page *page;
6401 char *kaddr;
6402 char *dst = (char *)dstv;
884b07d0 6403 unsigned long i = get_eb_page_index(start);
d1310b2e 6404
f98b6215 6405 if (check_eb_range(eb, start, len))
f716abd5 6406 return;
d1310b2e 6407
884b07d0 6408 offset = get_eb_offset_in_page(eb, start);
d1310b2e 6409
d397712b 6410 while (len > 0) {
fb85fc9a 6411 page = eb->pages[i];
d1310b2e 6412
09cbfeaf 6413 cur = min(len, (PAGE_SIZE - offset));
a6591715 6414 kaddr = page_address(page);
d1310b2e 6415 memcpy(dst, kaddr + offset, cur);
d1310b2e
CM
6416
6417 dst += cur;
6418 len -= cur;
6419 offset = 0;
6420 i++;
6421 }
6422}
d1310b2e 6423
a48b73ec
JB
6424int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
6425 void __user *dstv,
6426 unsigned long start, unsigned long len)
550ac1d8
GH
6427{
6428 size_t cur;
6429 size_t offset;
6430 struct page *page;
6431 char *kaddr;
6432 char __user *dst = (char __user *)dstv;
884b07d0 6433 unsigned long i = get_eb_page_index(start);
550ac1d8
GH
6434 int ret = 0;
6435
6436 WARN_ON(start > eb->len);
6437 WARN_ON(start + len > eb->start + eb->len);
6438
884b07d0 6439 offset = get_eb_offset_in_page(eb, start);
550ac1d8
GH
6440
6441 while (len > 0) {
fb85fc9a 6442 page = eb->pages[i];
550ac1d8 6443
09cbfeaf 6444 cur = min(len, (PAGE_SIZE - offset));
550ac1d8 6445 kaddr = page_address(page);
a48b73ec 6446 if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
550ac1d8
GH
6447 ret = -EFAULT;
6448 break;
6449 }
6450
6451 dst += cur;
6452 len -= cur;
6453 offset = 0;
6454 i++;
6455 }
6456
6457 return ret;
6458}
6459
1cbb1f45
JM
6460int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
6461 unsigned long start, unsigned long len)
d1310b2e
CM
6462{
6463 size_t cur;
6464 size_t offset;
6465 struct page *page;
6466 char *kaddr;
6467 char *ptr = (char *)ptrv;
884b07d0 6468 unsigned long i = get_eb_page_index(start);
d1310b2e
CM
6469 int ret = 0;
6470
f98b6215
QW
6471 if (check_eb_range(eb, start, len))
6472 return -EINVAL;
d1310b2e 6473
884b07d0 6474 offset = get_eb_offset_in_page(eb, start);
d1310b2e 6475
d397712b 6476 while (len > 0) {
fb85fc9a 6477 page = eb->pages[i];
d1310b2e 6478
09cbfeaf 6479 cur = min(len, (PAGE_SIZE - offset));
d1310b2e 6480
a6591715 6481 kaddr = page_address(page);
d1310b2e 6482 ret = memcmp(ptr, kaddr + offset, cur);
d1310b2e
CM
6483 if (ret)
6484 break;
6485
6486 ptr += cur;
6487 len -= cur;
6488 offset = 0;
6489 i++;
6490 }
6491 return ret;
6492}
d1310b2e 6493
b8f95771
QW
6494/*
6495 * Check that the extent buffer is uptodate.
6496 *
6497 * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
6498 * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
6499 */
6500static void assert_eb_page_uptodate(const struct extent_buffer *eb,
6501 struct page *page)
6502{
6503 struct btrfs_fs_info *fs_info = eb->fs_info;
6504
6505 if (fs_info->sectorsize < PAGE_SIZE) {
6506 bool uptodate;
6507
6508 uptodate = btrfs_subpage_test_uptodate(fs_info, page,
6509 eb->start, eb->len);
6510 WARN_ON(!uptodate);
6511 } else {
6512 WARN_ON(!PageUptodate(page));
6513 }
6514}
6515
2b48966a 6516void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
f157bf76
DS
6517 const void *srcv)
6518{
6519 char *kaddr;
6520
b8f95771 6521 assert_eb_page_uptodate(eb, eb->pages[0]);
884b07d0 6522 kaddr = page_address(eb->pages[0]) + get_eb_offset_in_page(eb, 0);
f157bf76
DS
6523 memcpy(kaddr + offsetof(struct btrfs_header, chunk_tree_uuid), srcv,
6524 BTRFS_FSID_SIZE);
6525}
6526
2b48966a 6527void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
f157bf76
DS
6528{
6529 char *kaddr;
6530
b8f95771 6531 assert_eb_page_uptodate(eb, eb->pages[0]);
884b07d0 6532 kaddr = page_address(eb->pages[0]) + get_eb_offset_in_page(eb, 0);
f157bf76
DS
6533 memcpy(kaddr + offsetof(struct btrfs_header, fsid), srcv,
6534 BTRFS_FSID_SIZE);
6535}
6536
2b48966a 6537void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
d1310b2e
CM
6538 unsigned long start, unsigned long len)
6539{
6540 size_t cur;
6541 size_t offset;
6542 struct page *page;
6543 char *kaddr;
6544 char *src = (char *)srcv;
884b07d0 6545 unsigned long i = get_eb_page_index(start);
d1310b2e 6546
d3575156
NA
6547 WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
6548
f98b6215
QW
6549 if (check_eb_range(eb, start, len))
6550 return;
d1310b2e 6551
884b07d0 6552 offset = get_eb_offset_in_page(eb, start);
d1310b2e 6553
d397712b 6554 while (len > 0) {
fb85fc9a 6555 page = eb->pages[i];
b8f95771 6556 assert_eb_page_uptodate(eb, page);
d1310b2e 6557
09cbfeaf 6558 cur = min(len, PAGE_SIZE - offset);
a6591715 6559 kaddr = page_address(page);
d1310b2e 6560 memcpy(kaddr + offset, src, cur);
d1310b2e
CM
6561
6562 src += cur;
6563 len -= cur;
6564 offset = 0;
6565 i++;
6566 }
6567}
d1310b2e 6568
2b48966a 6569void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
b159fa28 6570 unsigned long len)
d1310b2e
CM
6571{
6572 size_t cur;
6573 size_t offset;
6574 struct page *page;
6575 char *kaddr;
884b07d0 6576 unsigned long i = get_eb_page_index(start);
d1310b2e 6577
f98b6215
QW
6578 if (check_eb_range(eb, start, len))
6579 return;
d1310b2e 6580
884b07d0 6581 offset = get_eb_offset_in_page(eb, start);
d1310b2e 6582
d397712b 6583 while (len > 0) {
fb85fc9a 6584 page = eb->pages[i];
b8f95771 6585 assert_eb_page_uptodate(eb, page);
d1310b2e 6586
09cbfeaf 6587 cur = min(len, PAGE_SIZE - offset);
a6591715 6588 kaddr = page_address(page);
b159fa28 6589 memset(kaddr + offset, 0, cur);
d1310b2e
CM
6590
6591 len -= cur;
6592 offset = 0;
6593 i++;
6594 }
6595}
d1310b2e 6596
2b48966a
DS
6597void copy_extent_buffer_full(const struct extent_buffer *dst,
6598 const struct extent_buffer *src)
58e8012c
DS
6599{
6600 int i;
cc5e31a4 6601 int num_pages;
58e8012c
DS
6602
6603 ASSERT(dst->len == src->len);
6604
884b07d0
QW
6605 if (dst->fs_info->sectorsize == PAGE_SIZE) {
6606 num_pages = num_extent_pages(dst);
6607 for (i = 0; i < num_pages; i++)
6608 copy_page(page_address(dst->pages[i]),
6609 page_address(src->pages[i]));
6610 } else {
6611 size_t src_offset = get_eb_offset_in_page(src, 0);
6612 size_t dst_offset = get_eb_offset_in_page(dst, 0);
6613
6614 ASSERT(src->fs_info->sectorsize < PAGE_SIZE);
6615 memcpy(page_address(dst->pages[0]) + dst_offset,
6616 page_address(src->pages[0]) + src_offset,
6617 src->len);
6618 }
58e8012c
DS
6619}
6620
2b48966a
DS
6621void copy_extent_buffer(const struct extent_buffer *dst,
6622 const struct extent_buffer *src,
d1310b2e
CM
6623 unsigned long dst_offset, unsigned long src_offset,
6624 unsigned long len)
6625{
6626 u64 dst_len = dst->len;
6627 size_t cur;
6628 size_t offset;
6629 struct page *page;
6630 char *kaddr;
884b07d0 6631 unsigned long i = get_eb_page_index(dst_offset);
d1310b2e 6632
f98b6215
QW
6633 if (check_eb_range(dst, dst_offset, len) ||
6634 check_eb_range(src, src_offset, len))
6635 return;
6636
d1310b2e
CM
6637 WARN_ON(src->len != dst_len);
6638
884b07d0 6639 offset = get_eb_offset_in_page(dst, dst_offset);
d1310b2e 6640
d397712b 6641 while (len > 0) {
fb85fc9a 6642 page = dst->pages[i];
b8f95771 6643 assert_eb_page_uptodate(dst, page);
d1310b2e 6644
09cbfeaf 6645 cur = min(len, (unsigned long)(PAGE_SIZE - offset));
d1310b2e 6646
a6591715 6647 kaddr = page_address(page);
d1310b2e 6648 read_extent_buffer(src, kaddr + offset, src_offset, cur);
d1310b2e
CM
6649
6650 src_offset += cur;
6651 len -= cur;
6652 offset = 0;
6653 i++;
6654 }
6655}
d1310b2e 6656
3e1e8bb7
OS
6657/*
6658 * eb_bitmap_offset() - calculate the page and offset of the byte containing the
6659 * given bit number
6660 * @eb: the extent buffer
6661 * @start: offset of the bitmap item in the extent buffer
6662 * @nr: bit number
6663 * @page_index: return index of the page in the extent buffer that contains the
6664 * given bit number
6665 * @page_offset: return offset into the page given by page_index
6666 *
6667 * This helper hides the ugliness of finding the byte in an extent buffer which
6668 * contains a given bit.
6669 */
2b48966a 6670static inline void eb_bitmap_offset(const struct extent_buffer *eb,
3e1e8bb7
OS
6671 unsigned long start, unsigned long nr,
6672 unsigned long *page_index,
6673 size_t *page_offset)
6674{
3e1e8bb7
OS
6675 size_t byte_offset = BIT_BYTE(nr);
6676 size_t offset;
6677
6678 /*
6679 * The byte we want is the offset of the extent buffer + the offset of
6680 * the bitmap item in the extent buffer + the offset of the byte in the
6681 * bitmap item.
6682 */
884b07d0 6683 offset = start + offset_in_page(eb->start) + byte_offset;
3e1e8bb7 6684
09cbfeaf 6685 *page_index = offset >> PAGE_SHIFT;
7073017a 6686 *page_offset = offset_in_page(offset);
3e1e8bb7
OS
6687}
6688
6689/**
6690 * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
6691 * @eb: the extent buffer
6692 * @start: offset of the bitmap item in the extent buffer
6693 * @nr: bit number to test
6694 */
2b48966a 6695int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
3e1e8bb7
OS
6696 unsigned long nr)
6697{
2fe1d551 6698 u8 *kaddr;
3e1e8bb7
OS
6699 struct page *page;
6700 unsigned long i;
6701 size_t offset;
6702
6703 eb_bitmap_offset(eb, start, nr, &i, &offset);
6704 page = eb->pages[i];
b8f95771 6705 assert_eb_page_uptodate(eb, page);
3e1e8bb7
OS
6706 kaddr = page_address(page);
6707 return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
6708}
6709
6710/**
6711 * extent_buffer_bitmap_set - set an area of a bitmap
6712 * @eb: the extent buffer
6713 * @start: offset of the bitmap item in the extent buffer
6714 * @pos: bit number of the first bit
6715 * @len: number of bits to set
6716 */
2b48966a 6717void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
3e1e8bb7
OS
6718 unsigned long pos, unsigned long len)
6719{
2fe1d551 6720 u8 *kaddr;
3e1e8bb7
OS
6721 struct page *page;
6722 unsigned long i;
6723 size_t offset;
6724 const unsigned int size = pos + len;
6725 int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
2fe1d551 6726 u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
3e1e8bb7
OS
6727
6728 eb_bitmap_offset(eb, start, pos, &i, &offset);
6729 page = eb->pages[i];
b8f95771 6730 assert_eb_page_uptodate(eb, page);
3e1e8bb7
OS
6731 kaddr = page_address(page);
6732
6733 while (len >= bits_to_set) {
6734 kaddr[offset] |= mask_to_set;
6735 len -= bits_to_set;
6736 bits_to_set = BITS_PER_BYTE;
9c894696 6737 mask_to_set = ~0;
09cbfeaf 6738 if (++offset >= PAGE_SIZE && len > 0) {
3e1e8bb7
OS
6739 offset = 0;
6740 page = eb->pages[++i];
b8f95771 6741 assert_eb_page_uptodate(eb, page);
3e1e8bb7
OS
6742 kaddr = page_address(page);
6743 }
6744 }
6745 if (len) {
6746 mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
6747 kaddr[offset] |= mask_to_set;
6748 }
6749}
6750
6751
6752/**
6753 * extent_buffer_bitmap_clear - clear an area of a bitmap
6754 * @eb: the extent buffer
6755 * @start: offset of the bitmap item in the extent buffer
6756 * @pos: bit number of the first bit
6757 * @len: number of bits to clear
6758 */
2b48966a
DS
6759void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
6760 unsigned long start, unsigned long pos,
6761 unsigned long len)
3e1e8bb7 6762{
2fe1d551 6763 u8 *kaddr;
3e1e8bb7
OS
6764 struct page *page;
6765 unsigned long i;
6766 size_t offset;
6767 const unsigned int size = pos + len;
6768 int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
2fe1d551 6769 u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
3e1e8bb7
OS
6770
6771 eb_bitmap_offset(eb, start, pos, &i, &offset);
6772 page = eb->pages[i];
b8f95771 6773 assert_eb_page_uptodate(eb, page);
3e1e8bb7
OS
6774 kaddr = page_address(page);
6775
6776 while (len >= bits_to_clear) {
6777 kaddr[offset] &= ~mask_to_clear;
6778 len -= bits_to_clear;
6779 bits_to_clear = BITS_PER_BYTE;
9c894696 6780 mask_to_clear = ~0;
09cbfeaf 6781 if (++offset >= PAGE_SIZE && len > 0) {
3e1e8bb7
OS
6782 offset = 0;
6783 page = eb->pages[++i];
b8f95771 6784 assert_eb_page_uptodate(eb, page);
3e1e8bb7
OS
6785 kaddr = page_address(page);
6786 }
6787 }
6788 if (len) {
6789 mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
6790 kaddr[offset] &= ~mask_to_clear;
6791 }
6792}
6793
3387206f
ST
6794static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
6795{
6796 unsigned long distance = (src > dst) ? src - dst : dst - src;
6797 return distance < len;
6798}
6799
d1310b2e
CM
6800static void copy_pages(struct page *dst_page, struct page *src_page,
6801 unsigned long dst_off, unsigned long src_off,
6802 unsigned long len)
6803{
a6591715 6804 char *dst_kaddr = page_address(dst_page);
d1310b2e 6805 char *src_kaddr;
727011e0 6806 int must_memmove = 0;
d1310b2e 6807
3387206f 6808 if (dst_page != src_page) {
a6591715 6809 src_kaddr = page_address(src_page);
3387206f 6810 } else {
d1310b2e 6811 src_kaddr = dst_kaddr;
727011e0
CM
6812 if (areas_overlap(src_off, dst_off, len))
6813 must_memmove = 1;
3387206f 6814 }
d1310b2e 6815
727011e0
CM
6816 if (must_memmove)
6817 memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
6818 else
6819 memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
d1310b2e
CM
6820}
6821
2b48966a
DS
6822void memcpy_extent_buffer(const struct extent_buffer *dst,
6823 unsigned long dst_offset, unsigned long src_offset,
6824 unsigned long len)
d1310b2e
CM
6825{
6826 size_t cur;
6827 size_t dst_off_in_page;
6828 size_t src_off_in_page;
d1310b2e
CM
6829 unsigned long dst_i;
6830 unsigned long src_i;
6831
f98b6215
QW
6832 if (check_eb_range(dst, dst_offset, len) ||
6833 check_eb_range(dst, src_offset, len))
6834 return;
d1310b2e 6835
d397712b 6836 while (len > 0) {
884b07d0
QW
6837 dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
6838 src_off_in_page = get_eb_offset_in_page(dst, src_offset);
d1310b2e 6839
884b07d0
QW
6840 dst_i = get_eb_page_index(dst_offset);
6841 src_i = get_eb_page_index(src_offset);
d1310b2e 6842
09cbfeaf 6843 cur = min(len, (unsigned long)(PAGE_SIZE -
d1310b2e
CM
6844 src_off_in_page));
6845 cur = min_t(unsigned long, cur,
09cbfeaf 6846 (unsigned long)(PAGE_SIZE - dst_off_in_page));
d1310b2e 6847
fb85fc9a 6848 copy_pages(dst->pages[dst_i], dst->pages[src_i],
d1310b2e
CM
6849 dst_off_in_page, src_off_in_page, cur);
6850
6851 src_offset += cur;
6852 dst_offset += cur;
6853 len -= cur;
6854 }
6855}
d1310b2e 6856
2b48966a
DS
6857void memmove_extent_buffer(const struct extent_buffer *dst,
6858 unsigned long dst_offset, unsigned long src_offset,
6859 unsigned long len)
d1310b2e
CM
6860{
6861 size_t cur;
6862 size_t dst_off_in_page;
6863 size_t src_off_in_page;
6864 unsigned long dst_end = dst_offset + len - 1;
6865 unsigned long src_end = src_offset + len - 1;
d1310b2e
CM
6866 unsigned long dst_i;
6867 unsigned long src_i;
6868
f98b6215
QW
6869 if (check_eb_range(dst, dst_offset, len) ||
6870 check_eb_range(dst, src_offset, len))
6871 return;
727011e0 6872 if (dst_offset < src_offset) {
d1310b2e
CM
6873 memcpy_extent_buffer(dst, dst_offset, src_offset, len);
6874 return;
6875 }
d397712b 6876 while (len > 0) {
884b07d0
QW
6877 dst_i = get_eb_page_index(dst_end);
6878 src_i = get_eb_page_index(src_end);
d1310b2e 6879
884b07d0
QW
6880 dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
6881 src_off_in_page = get_eb_offset_in_page(dst, src_end);
d1310b2e
CM
6882
6883 cur = min_t(unsigned long, len, src_off_in_page + 1);
6884 cur = min(cur, dst_off_in_page + 1);
fb85fc9a 6885 copy_pages(dst->pages[dst_i], dst->pages[src_i],
d1310b2e
CM
6886 dst_off_in_page - cur + 1,
6887 src_off_in_page - cur + 1, cur);
6888
6889 dst_end -= cur;
6890 src_end -= cur;
6891 len -= cur;
6892 }
6893}
6af118ce 6894
d1e86e3f
QW
6895static struct extent_buffer *get_next_extent_buffer(
6896 struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
6897{
6898 struct extent_buffer *gang[BTRFS_SUBPAGE_BITMAP_SIZE];
6899 struct extent_buffer *found = NULL;
6900 u64 page_start = page_offset(page);
6901 int ret;
6902 int i;
6903
6904 ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
6905 ASSERT(PAGE_SIZE / fs_info->nodesize <= BTRFS_SUBPAGE_BITMAP_SIZE);
6906 lockdep_assert_held(&fs_info->buffer_lock);
6907
6908 ret = radix_tree_gang_lookup(&fs_info->buffer_radix, (void **)gang,
6909 bytenr >> fs_info->sectorsize_bits,
6910 PAGE_SIZE / fs_info->nodesize);
6911 for (i = 0; i < ret; i++) {
6912 /* Already beyond page end */
6913 if (gang[i]->start >= page_start + PAGE_SIZE)
6914 break;
6915 /* Found one */
6916 if (gang[i]->start >= bytenr) {
6917 found = gang[i];
6918 break;
6919 }
6920 }
6921 return found;
6922}
6923
6924static int try_release_subpage_extent_buffer(struct page *page)
6925{
6926 struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
6927 u64 cur = page_offset(page);
6928 const u64 end = page_offset(page) + PAGE_SIZE;
6929 int ret;
6930
6931 while (cur < end) {
6932 struct extent_buffer *eb = NULL;
6933
6934 /*
6935 * Unlike try_release_extent_buffer() which uses page->private
6936 * to grab buffer, for subpage case we rely on radix tree, thus
6937 * we need to ensure radix tree consistency.
6938 *
6939 * We also want an atomic snapshot of the radix tree, thus go
6940 * with spinlock rather than RCU.
6941 */
6942 spin_lock(&fs_info->buffer_lock);
6943 eb = get_next_extent_buffer(fs_info, page, cur);
6944 if (!eb) {
6945 /* No more eb in the page range after or at cur */
6946 spin_unlock(&fs_info->buffer_lock);
6947 break;
6948 }
6949 cur = eb->start + eb->len;
6950
6951 /*
6952 * The same as try_release_extent_buffer(), to ensure the eb
6953 * won't disappear out from under us.
6954 */
6955 spin_lock(&eb->refs_lock);
6956 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
6957 spin_unlock(&eb->refs_lock);
6958 spin_unlock(&fs_info->buffer_lock);
6959 break;
6960 }
6961 spin_unlock(&fs_info->buffer_lock);
6962
6963 /*
6964 * If tree ref isn't set then we know the ref on this eb is a
6965 * real ref, so just return, this eb will likely be freed soon
6966 * anyway.
6967 */
6968 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
6969 spin_unlock(&eb->refs_lock);
6970 break;
6971 }
6972
6973 /*
6974 * Here we don't care about the return value, we will always
6975 * check the page private at the end. And
6976 * release_extent_buffer() will release the refs_lock.
6977 */
6978 release_extent_buffer(eb);
6979 }
6980 /*
6981 * Finally to check if we have cleared page private, as if we have
6982 * released all ebs in the page, the page private should be cleared now.
6983 */
6984 spin_lock(&page->mapping->private_lock);
6985 if (!PagePrivate(page))
6986 ret = 1;
6987 else
6988 ret = 0;
6989 spin_unlock(&page->mapping->private_lock);
6990 return ret;
6991
6992}
6993
f7a52a40 6994int try_release_extent_buffer(struct page *page)
19fe0a8b 6995{
6af118ce 6996 struct extent_buffer *eb;
6af118ce 6997
d1e86e3f
QW
6998 if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
6999 return try_release_subpage_extent_buffer(page);
7000
3083ee2e 7001 /*
d1e86e3f
QW
7002 * We need to make sure nobody is changing page->private, as we rely on
7003 * page->private as the pointer to extent buffer.
3083ee2e
JB
7004 */
7005 spin_lock(&page->mapping->private_lock);
7006 if (!PagePrivate(page)) {
7007 spin_unlock(&page->mapping->private_lock);
4f2de97a 7008 return 1;
45f49bce 7009 }
6af118ce 7010
3083ee2e
JB
7011 eb = (struct extent_buffer *)page->private;
7012 BUG_ON(!eb);
19fe0a8b
MX
7013
7014 /*
3083ee2e
JB
7015 * This is a little awful but should be ok, we need to make sure that
7016 * the eb doesn't disappear out from under us while we're looking at
7017 * this page.
19fe0a8b 7018 */
3083ee2e 7019 spin_lock(&eb->refs_lock);
0b32f4bb 7020 if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
3083ee2e
JB
7021 spin_unlock(&eb->refs_lock);
7022 spin_unlock(&page->mapping->private_lock);
7023 return 0;
b9473439 7024 }
3083ee2e 7025 spin_unlock(&page->mapping->private_lock);
897ca6e9 7026
19fe0a8b 7027 /*
3083ee2e
JB
7028 * If tree ref isn't set then we know the ref on this eb is a real ref,
7029 * so just return, this page will likely be freed soon anyway.
19fe0a8b 7030 */
3083ee2e
JB
7031 if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
7032 spin_unlock(&eb->refs_lock);
7033 return 0;
b9473439 7034 }
19fe0a8b 7035
f7a52a40 7036 return release_extent_buffer(eb);
6af118ce 7037}
bfb484d9
JB
7038
7039/*
7040 * btrfs_readahead_tree_block - attempt to readahead a child block
7041 * @fs_info: the fs_info
7042 * @bytenr: bytenr to read
3fbaf258 7043 * @owner_root: objectid of the root that owns this eb
bfb484d9 7044 * @gen: generation for the uptodate check, can be 0
3fbaf258 7045 * @level: level for the eb
bfb484d9
JB
7046 *
7047 * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
7048 * normal uptodate check of the eb, without checking the generation. If we have
7049 * to read the block we will not block on anything.
7050 */
7051void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
3fbaf258 7052 u64 bytenr, u64 owner_root, u64 gen, int level)
bfb484d9
JB
7053{
7054 struct extent_buffer *eb;
7055 int ret;
7056
3fbaf258 7057 eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
bfb484d9
JB
7058 if (IS_ERR(eb))
7059 return;
7060
7061 if (btrfs_buffer_uptodate(eb, gen, 1)) {
7062 free_extent_buffer(eb);
7063 return;
7064 }
7065
7066 ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
7067 if (ret < 0)
7068 free_extent_buffer_stale(eb);
7069 else
7070 free_extent_buffer(eb);
7071}
7072
7073/*
7074 * btrfs_readahead_node_child - readahead a node's child block
7075 * @node: parent node we're reading from
7076 * @slot: slot in the parent node for the child we want to read
7077 *
7078 * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
7079 * the slot in the node provided.
7080 */
7081void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
7082{
7083 btrfs_readahead_tree_block(node->fs_info,
7084 btrfs_node_blockptr(node, slot),
3fbaf258
JB
7085 btrfs_header_owner(node),
7086 btrfs_node_ptr_generation(node, slot),
7087 btrfs_header_level(node) - 1);
bfb484d9 7088}