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