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