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