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