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