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