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