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