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