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