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