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