]> Git Repo - J-linux.git/blob - mm/filemap.c
filemap: Use folio_put_refs() in filemap_free_folio()
[J-linux.git] / mm / filemap.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *      linux/mm/filemap.c
4  *
5  * Copyright (C) 1994-1999  Linus Torvalds
6  */
7
8 /*
9  * This file handles the generic file mmap semantics used by
10  * most "normal" filesystems (but you don't /have/ to use this:
11  * the NFS filesystem used to do this differently, for example)
12  */
13 #include <linux/export.h>
14 #include <linux/compiler.h>
15 #include <linux/dax.h>
16 #include <linux/fs.h>
17 #include <linux/sched/signal.h>
18 #include <linux/uaccess.h>
19 #include <linux/capability.h>
20 #include <linux/kernel_stat.h>
21 #include <linux/gfp.h>
22 #include <linux/mm.h>
23 #include <linux/swap.h>
24 #include <linux/mman.h>
25 #include <linux/pagemap.h>
26 #include <linux/file.h>
27 #include <linux/uio.h>
28 #include <linux/error-injection.h>
29 #include <linux/hash.h>
30 #include <linux/writeback.h>
31 #include <linux/backing-dev.h>
32 #include <linux/pagevec.h>
33 #include <linux/security.h>
34 #include <linux/cpuset.h>
35 #include <linux/hugetlb.h>
36 #include <linux/memcontrol.h>
37 #include <linux/cleancache.h>
38 #include <linux/shmem_fs.h>
39 #include <linux/rmap.h>
40 #include <linux/delayacct.h>
41 #include <linux/psi.h>
42 #include <linux/ramfs.h>
43 #include <linux/page_idle.h>
44 #include <asm/pgalloc.h>
45 #include <asm/tlbflush.h>
46 #include "internal.h"
47
48 #define CREATE_TRACE_POINTS
49 #include <trace/events/filemap.h>
50
51 /*
52  * FIXME: remove all knowledge of the buffer layer from the core VM
53  */
54 #include <linux/buffer_head.h> /* for try_to_free_buffers */
55
56 #include <asm/mman.h>
57
58 /*
59  * Shared mappings implemented 30.11.1994. It's not fully working yet,
60  * though.
61  *
62  * Shared mappings now work. 15.8.1995  Bruno.
63  *
64  * finished 'unifying' the page and buffer cache and SMP-threaded the
65  * page-cache, 21.05.1999, Ingo Molnar <[email protected]>
66  *
67  * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <[email protected]>
68  */
69
70 /*
71  * Lock ordering:
72  *
73  *  ->i_mmap_rwsem              (truncate_pagecache)
74  *    ->private_lock            (__free_pte->__set_page_dirty_buffers)
75  *      ->swap_lock             (exclusive_swap_page, others)
76  *        ->i_pages lock
77  *
78  *  ->i_rwsem
79  *    ->invalidate_lock         (acquired by fs in truncate path)
80  *      ->i_mmap_rwsem          (truncate->unmap_mapping_range)
81  *
82  *  ->mmap_lock
83  *    ->i_mmap_rwsem
84  *      ->page_table_lock or pte_lock   (various, mainly in memory.c)
85  *        ->i_pages lock        (arch-dependent flush_dcache_mmap_lock)
86  *
87  *  ->mmap_lock
88  *    ->invalidate_lock         (filemap_fault)
89  *      ->lock_page             (filemap_fault, access_process_vm)
90  *
91  *  ->i_rwsem                   (generic_perform_write)
92  *    ->mmap_lock               (fault_in_readable->do_page_fault)
93  *
94  *  bdi->wb.list_lock
95  *    sb_lock                   (fs/fs-writeback.c)
96  *    ->i_pages lock            (__sync_single_inode)
97  *
98  *  ->i_mmap_rwsem
99  *    ->anon_vma.lock           (vma_adjust)
100  *
101  *  ->anon_vma.lock
102  *    ->page_table_lock or pte_lock     (anon_vma_prepare and various)
103  *
104  *  ->page_table_lock or pte_lock
105  *    ->swap_lock               (try_to_unmap_one)
106  *    ->private_lock            (try_to_unmap_one)
107  *    ->i_pages lock            (try_to_unmap_one)
108  *    ->lruvec->lru_lock        (follow_page->mark_page_accessed)
109  *    ->lruvec->lru_lock        (check_pte_range->isolate_lru_page)
110  *    ->private_lock            (page_remove_rmap->set_page_dirty)
111  *    ->i_pages lock            (page_remove_rmap->set_page_dirty)
112  *    bdi.wb->list_lock         (page_remove_rmap->set_page_dirty)
113  *    ->inode->i_lock           (page_remove_rmap->set_page_dirty)
114  *    ->memcg->move_lock        (page_remove_rmap->lock_page_memcg)
115  *    bdi.wb->list_lock         (zap_pte_range->set_page_dirty)
116  *    ->inode->i_lock           (zap_pte_range->set_page_dirty)
117  *    ->private_lock            (zap_pte_range->__set_page_dirty_buffers)
118  *
119  * ->i_mmap_rwsem
120  *   ->tasklist_lock            (memory_failure, collect_procs_ao)
121  */
122
123 static void page_cache_delete(struct address_space *mapping,
124                                    struct folio *folio, void *shadow)
125 {
126         XA_STATE(xas, &mapping->i_pages, folio->index);
127         long nr = 1;
128
129         mapping_set_update(&xas, mapping);
130
131         /* hugetlb pages are represented by a single entry in the xarray */
132         if (!folio_test_hugetlb(folio)) {
133                 xas_set_order(&xas, folio->index, folio_order(folio));
134                 nr = folio_nr_pages(folio);
135         }
136
137         VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
138
139         xas_store(&xas, shadow);
140         xas_init_marks(&xas);
141
142         folio->mapping = NULL;
143         /* Leave page->index set: truncation lookup relies upon it */
144         mapping->nrpages -= nr;
145 }
146
147 static void filemap_unaccount_folio(struct address_space *mapping,
148                 struct folio *folio)
149 {
150         long nr;
151
152         /*
153          * if we're uptodate, flush out into the cleancache, otherwise
154          * invalidate any existing cleancache entries.  We can't leave
155          * stale data around in the cleancache once our page is gone
156          */
157         if (folio_test_uptodate(folio) && folio_test_mappedtodisk(folio))
158                 cleancache_put_page(&folio->page);
159         else
160                 cleancache_invalidate_page(mapping, &folio->page);
161
162         VM_BUG_ON_FOLIO(folio_mapped(folio), folio);
163         if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(folio_mapped(folio))) {
164                 int mapcount;
165
166                 pr_alert("BUG: Bad page cache in process %s  pfn:%05lx\n",
167                          current->comm, folio_pfn(folio));
168                 dump_page(&folio->page, "still mapped when deleted");
169                 dump_stack();
170                 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
171
172                 mapcount = page_mapcount(&folio->page);
173                 if (mapping_exiting(mapping) &&
174                     folio_ref_count(folio) >= mapcount + 2) {
175                         /*
176                          * All vmas have already been torn down, so it's
177                          * a good bet that actually the folio is unmapped,
178                          * and we'd prefer not to leak it: if we're wrong,
179                          * some other bad page check should catch it later.
180                          */
181                         page_mapcount_reset(&folio->page);
182                         folio_ref_sub(folio, mapcount);
183                 }
184         }
185
186         /* hugetlb folios do not participate in page cache accounting. */
187         if (folio_test_hugetlb(folio))
188                 return;
189
190         nr = folio_nr_pages(folio);
191
192         __lruvec_stat_mod_folio(folio, NR_FILE_PAGES, -nr);
193         if (folio_test_swapbacked(folio)) {
194                 __lruvec_stat_mod_folio(folio, NR_SHMEM, -nr);
195                 if (folio_test_pmd_mappable(folio))
196                         __lruvec_stat_mod_folio(folio, NR_SHMEM_THPS, -nr);
197         } else if (folio_test_pmd_mappable(folio)) {
198                 __lruvec_stat_mod_folio(folio, NR_FILE_THPS, -nr);
199                 filemap_nr_thps_dec(mapping);
200         }
201
202         /*
203          * At this point folio must be either written or cleaned by
204          * truncate.  Dirty folio here signals a bug and loss of
205          * unwritten data.
206          *
207          * This fixes dirty accounting after removing the folio entirely
208          * but leaves the dirty flag set: it has no effect for truncated
209          * folio and anyway will be cleared before returning folio to
210          * buddy allocator.
211          */
212         if (WARN_ON_ONCE(folio_test_dirty(folio)))
213                 folio_account_cleaned(folio, mapping,
214                                         inode_to_wb(mapping->host));
215 }
216
217 /*
218  * Delete a page from the page cache and free it. Caller has to make
219  * sure the page is locked and that nobody else uses it - or that usage
220  * is safe.  The caller must hold the i_pages lock.
221  */
222 void __filemap_remove_folio(struct folio *folio, void *shadow)
223 {
224         struct address_space *mapping = folio->mapping;
225
226         trace_mm_filemap_delete_from_page_cache(folio);
227         filemap_unaccount_folio(mapping, folio);
228         page_cache_delete(mapping, folio, shadow);
229 }
230
231 void filemap_free_folio(struct address_space *mapping, struct folio *folio)
232 {
233         void (*freepage)(struct page *);
234         int refs = 1;
235
236         freepage = mapping->a_ops->freepage;
237         if (freepage)
238                 freepage(&folio->page);
239
240         if (folio_test_large(folio) && !folio_test_hugetlb(folio))
241                 refs = folio_nr_pages(folio);
242         folio_put_refs(folio, refs);
243 }
244
245 /**
246  * filemap_remove_folio - Remove folio from page cache.
247  * @folio: The folio.
248  *
249  * This must be called only on folios that are locked and have been
250  * verified to be in the page cache.  It will never put the folio into
251  * the free list because the caller has a reference on the page.
252  */
253 void filemap_remove_folio(struct folio *folio)
254 {
255         struct address_space *mapping = folio->mapping;
256
257         BUG_ON(!folio_test_locked(folio));
258         spin_lock(&mapping->host->i_lock);
259         xa_lock_irq(&mapping->i_pages);
260         __filemap_remove_folio(folio, NULL);
261         xa_unlock_irq(&mapping->i_pages);
262         if (mapping_shrinkable(mapping))
263                 inode_add_lru(mapping->host);
264         spin_unlock(&mapping->host->i_lock);
265
266         filemap_free_folio(mapping, folio);
267 }
268
269 /*
270  * page_cache_delete_batch - delete several folios from page cache
271  * @mapping: the mapping to which folios belong
272  * @fbatch: batch of folios to delete
273  *
274  * The function walks over mapping->i_pages and removes folios passed in
275  * @fbatch from the mapping. The function expects @fbatch to be sorted
276  * by page index and is optimised for it to be dense.
277  * It tolerates holes in @fbatch (mapping entries at those indices are not
278  * modified).
279  *
280  * The function expects the i_pages lock to be held.
281  */
282 static void page_cache_delete_batch(struct address_space *mapping,
283                              struct folio_batch *fbatch)
284 {
285         XA_STATE(xas, &mapping->i_pages, fbatch->folios[0]->index);
286         long total_pages = 0;
287         int i = 0;
288         struct folio *folio;
289
290         mapping_set_update(&xas, mapping);
291         xas_for_each(&xas, folio, ULONG_MAX) {
292                 if (i >= folio_batch_count(fbatch))
293                         break;
294
295                 /* A swap/dax/shadow entry got inserted? Skip it. */
296                 if (xa_is_value(folio))
297                         continue;
298                 /*
299                  * A page got inserted in our range? Skip it. We have our
300                  * pages locked so they are protected from being removed.
301                  * If we see a page whose index is higher than ours, it
302                  * means our page has been removed, which shouldn't be
303                  * possible because we're holding the PageLock.
304                  */
305                 if (folio != fbatch->folios[i]) {
306                         VM_BUG_ON_FOLIO(folio->index >
307                                         fbatch->folios[i]->index, folio);
308                         continue;
309                 }
310
311                 WARN_ON_ONCE(!folio_test_locked(folio));
312
313                 folio->mapping = NULL;
314                 /* Leave folio->index set: truncation lookup relies on it */
315
316                 i++;
317                 xas_store(&xas, NULL);
318                 total_pages += folio_nr_pages(folio);
319         }
320         mapping->nrpages -= total_pages;
321 }
322
323 void delete_from_page_cache_batch(struct address_space *mapping,
324                                   struct folio_batch *fbatch)
325 {
326         int i;
327
328         if (!folio_batch_count(fbatch))
329                 return;
330
331         spin_lock(&mapping->host->i_lock);
332         xa_lock_irq(&mapping->i_pages);
333         for (i = 0; i < folio_batch_count(fbatch); i++) {
334                 struct folio *folio = fbatch->folios[i];
335
336                 trace_mm_filemap_delete_from_page_cache(folio);
337                 filemap_unaccount_folio(mapping, folio);
338         }
339         page_cache_delete_batch(mapping, fbatch);
340         xa_unlock_irq(&mapping->i_pages);
341         if (mapping_shrinkable(mapping))
342                 inode_add_lru(mapping->host);
343         spin_unlock(&mapping->host->i_lock);
344
345         for (i = 0; i < folio_batch_count(fbatch); i++)
346                 filemap_free_folio(mapping, fbatch->folios[i]);
347 }
348
349 int filemap_check_errors(struct address_space *mapping)
350 {
351         int ret = 0;
352         /* Check for outstanding write errors */
353         if (test_bit(AS_ENOSPC, &mapping->flags) &&
354             test_and_clear_bit(AS_ENOSPC, &mapping->flags))
355                 ret = -ENOSPC;
356         if (test_bit(AS_EIO, &mapping->flags) &&
357             test_and_clear_bit(AS_EIO, &mapping->flags))
358                 ret = -EIO;
359         return ret;
360 }
361 EXPORT_SYMBOL(filemap_check_errors);
362
363 static int filemap_check_and_keep_errors(struct address_space *mapping)
364 {
365         /* Check for outstanding write errors */
366         if (test_bit(AS_EIO, &mapping->flags))
367                 return -EIO;
368         if (test_bit(AS_ENOSPC, &mapping->flags))
369                 return -ENOSPC;
370         return 0;
371 }
372
373 /**
374  * filemap_fdatawrite_wbc - start writeback on mapping dirty pages in range
375  * @mapping:    address space structure to write
376  * @wbc:        the writeback_control controlling the writeout
377  *
378  * Call writepages on the mapping using the provided wbc to control the
379  * writeout.
380  *
381  * Return: %0 on success, negative error code otherwise.
382  */
383 int filemap_fdatawrite_wbc(struct address_space *mapping,
384                            struct writeback_control *wbc)
385 {
386         int ret;
387
388         if (!mapping_can_writeback(mapping) ||
389             !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
390                 return 0;
391
392         wbc_attach_fdatawrite_inode(wbc, mapping->host);
393         ret = do_writepages(mapping, wbc);
394         wbc_detach_inode(wbc);
395         return ret;
396 }
397 EXPORT_SYMBOL(filemap_fdatawrite_wbc);
398
399 /**
400  * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
401  * @mapping:    address space structure to write
402  * @start:      offset in bytes where the range starts
403  * @end:        offset in bytes where the range ends (inclusive)
404  * @sync_mode:  enable synchronous operation
405  *
406  * Start writeback against all of a mapping's dirty pages that lie
407  * within the byte offsets <start, end> inclusive.
408  *
409  * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
410  * opposed to a regular memory cleansing writeback.  The difference between
411  * these two operations is that if a dirty page/buffer is encountered, it must
412  * be waited upon, and not just skipped over.
413  *
414  * Return: %0 on success, negative error code otherwise.
415  */
416 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
417                                 loff_t end, int sync_mode)
418 {
419         struct writeback_control wbc = {
420                 .sync_mode = sync_mode,
421                 .nr_to_write = LONG_MAX,
422                 .range_start = start,
423                 .range_end = end,
424         };
425
426         return filemap_fdatawrite_wbc(mapping, &wbc);
427 }
428
429 static inline int __filemap_fdatawrite(struct address_space *mapping,
430         int sync_mode)
431 {
432         return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
433 }
434
435 int filemap_fdatawrite(struct address_space *mapping)
436 {
437         return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
438 }
439 EXPORT_SYMBOL(filemap_fdatawrite);
440
441 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
442                                 loff_t end)
443 {
444         return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
445 }
446 EXPORT_SYMBOL(filemap_fdatawrite_range);
447
448 /**
449  * filemap_flush - mostly a non-blocking flush
450  * @mapping:    target address_space
451  *
452  * This is a mostly non-blocking flush.  Not suitable for data-integrity
453  * purposes - I/O may not be started against all dirty pages.
454  *
455  * Return: %0 on success, negative error code otherwise.
456  */
457 int filemap_flush(struct address_space *mapping)
458 {
459         return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
460 }
461 EXPORT_SYMBOL(filemap_flush);
462
463 /**
464  * filemap_range_has_page - check if a page exists in range.
465  * @mapping:           address space within which to check
466  * @start_byte:        offset in bytes where the range starts
467  * @end_byte:          offset in bytes where the range ends (inclusive)
468  *
469  * Find at least one page in the range supplied, usually used to check if
470  * direct writing in this range will trigger a writeback.
471  *
472  * Return: %true if at least one page exists in the specified range,
473  * %false otherwise.
474  */
475 bool filemap_range_has_page(struct address_space *mapping,
476                            loff_t start_byte, loff_t end_byte)
477 {
478         struct page *page;
479         XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
480         pgoff_t max = end_byte >> PAGE_SHIFT;
481
482         if (end_byte < start_byte)
483                 return false;
484
485         rcu_read_lock();
486         for (;;) {
487                 page = xas_find(&xas, max);
488                 if (xas_retry(&xas, page))
489                         continue;
490                 /* Shadow entries don't count */
491                 if (xa_is_value(page))
492                         continue;
493                 /*
494                  * We don't need to try to pin this page; we're about to
495                  * release the RCU lock anyway.  It is enough to know that
496                  * there was a page here recently.
497                  */
498                 break;
499         }
500         rcu_read_unlock();
501
502         return page != NULL;
503 }
504 EXPORT_SYMBOL(filemap_range_has_page);
505
506 static void __filemap_fdatawait_range(struct address_space *mapping,
507                                      loff_t start_byte, loff_t end_byte)
508 {
509         pgoff_t index = start_byte >> PAGE_SHIFT;
510         pgoff_t end = end_byte >> PAGE_SHIFT;
511         struct pagevec pvec;
512         int nr_pages;
513
514         if (end_byte < start_byte)
515                 return;
516
517         pagevec_init(&pvec);
518         while (index <= end) {
519                 unsigned i;
520
521                 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
522                                 end, PAGECACHE_TAG_WRITEBACK);
523                 if (!nr_pages)
524                         break;
525
526                 for (i = 0; i < nr_pages; i++) {
527                         struct page *page = pvec.pages[i];
528
529                         wait_on_page_writeback(page);
530                         ClearPageError(page);
531                 }
532                 pagevec_release(&pvec);
533                 cond_resched();
534         }
535 }
536
537 /**
538  * filemap_fdatawait_range - wait for writeback to complete
539  * @mapping:            address space structure to wait for
540  * @start_byte:         offset in bytes where the range starts
541  * @end_byte:           offset in bytes where the range ends (inclusive)
542  *
543  * Walk the list of under-writeback pages of the given address space
544  * in the given range and wait for all of them.  Check error status of
545  * the address space and return it.
546  *
547  * Since the error status of the address space is cleared by this function,
548  * callers are responsible for checking the return value and handling and/or
549  * reporting the error.
550  *
551  * Return: error status of the address space.
552  */
553 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
554                             loff_t end_byte)
555 {
556         __filemap_fdatawait_range(mapping, start_byte, end_byte);
557         return filemap_check_errors(mapping);
558 }
559 EXPORT_SYMBOL(filemap_fdatawait_range);
560
561 /**
562  * filemap_fdatawait_range_keep_errors - wait for writeback to complete
563  * @mapping:            address space structure to wait for
564  * @start_byte:         offset in bytes where the range starts
565  * @end_byte:           offset in bytes where the range ends (inclusive)
566  *
567  * Walk the list of under-writeback pages of the given address space in the
568  * given range and wait for all of them.  Unlike filemap_fdatawait_range(),
569  * this function does not clear error status of the address space.
570  *
571  * Use this function if callers don't handle errors themselves.  Expected
572  * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
573  * fsfreeze(8)
574  */
575 int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
576                 loff_t start_byte, loff_t end_byte)
577 {
578         __filemap_fdatawait_range(mapping, start_byte, end_byte);
579         return filemap_check_and_keep_errors(mapping);
580 }
581 EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
582
583 /**
584  * file_fdatawait_range - wait for writeback to complete
585  * @file:               file pointing to address space structure to wait for
586  * @start_byte:         offset in bytes where the range starts
587  * @end_byte:           offset in bytes where the range ends (inclusive)
588  *
589  * Walk the list of under-writeback pages of the address space that file
590  * refers to, in the given range and wait for all of them.  Check error
591  * status of the address space vs. the file->f_wb_err cursor and return it.
592  *
593  * Since the error status of the file is advanced by this function,
594  * callers are responsible for checking the return value and handling and/or
595  * reporting the error.
596  *
597  * Return: error status of the address space vs. the file->f_wb_err cursor.
598  */
599 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
600 {
601         struct address_space *mapping = file->f_mapping;
602
603         __filemap_fdatawait_range(mapping, start_byte, end_byte);
604         return file_check_and_advance_wb_err(file);
605 }
606 EXPORT_SYMBOL(file_fdatawait_range);
607
608 /**
609  * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
610  * @mapping: address space structure to wait for
611  *
612  * Walk the list of under-writeback pages of the given address space
613  * and wait for all of them.  Unlike filemap_fdatawait(), this function
614  * does not clear error status of the address space.
615  *
616  * Use this function if callers don't handle errors themselves.  Expected
617  * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
618  * fsfreeze(8)
619  *
620  * Return: error status of the address space.
621  */
622 int filemap_fdatawait_keep_errors(struct address_space *mapping)
623 {
624         __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
625         return filemap_check_and_keep_errors(mapping);
626 }
627 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
628
629 /* Returns true if writeback might be needed or already in progress. */
630 static bool mapping_needs_writeback(struct address_space *mapping)
631 {
632         return mapping->nrpages;
633 }
634
635 bool filemap_range_has_writeback(struct address_space *mapping,
636                                  loff_t start_byte, loff_t end_byte)
637 {
638         XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
639         pgoff_t max = end_byte >> PAGE_SHIFT;
640         struct page *page;
641
642         if (end_byte < start_byte)
643                 return false;
644
645         rcu_read_lock();
646         xas_for_each(&xas, page, max) {
647                 if (xas_retry(&xas, page))
648                         continue;
649                 if (xa_is_value(page))
650                         continue;
651                 if (PageDirty(page) || PageLocked(page) || PageWriteback(page))
652                         break;
653         }
654         rcu_read_unlock();
655         return page != NULL;
656 }
657 EXPORT_SYMBOL_GPL(filemap_range_has_writeback);
658
659 /**
660  * filemap_write_and_wait_range - write out & wait on a file range
661  * @mapping:    the address_space for the pages
662  * @lstart:     offset in bytes where the range starts
663  * @lend:       offset in bytes where the range ends (inclusive)
664  *
665  * Write out and wait upon file offsets lstart->lend, inclusive.
666  *
667  * Note that @lend is inclusive (describes the last byte to be written) so
668  * that this function can be used to write to the very end-of-file (end = -1).
669  *
670  * Return: error status of the address space.
671  */
672 int filemap_write_and_wait_range(struct address_space *mapping,
673                                  loff_t lstart, loff_t lend)
674 {
675         int err = 0;
676
677         if (mapping_needs_writeback(mapping)) {
678                 err = __filemap_fdatawrite_range(mapping, lstart, lend,
679                                                  WB_SYNC_ALL);
680                 /*
681                  * Even if the above returned error, the pages may be
682                  * written partially (e.g. -ENOSPC), so we wait for it.
683                  * But the -EIO is special case, it may indicate the worst
684                  * thing (e.g. bug) happened, so we avoid waiting for it.
685                  */
686                 if (err != -EIO) {
687                         int err2 = filemap_fdatawait_range(mapping,
688                                                 lstart, lend);
689                         if (!err)
690                                 err = err2;
691                 } else {
692                         /* Clear any previously stored errors */
693                         filemap_check_errors(mapping);
694                 }
695         } else {
696                 err = filemap_check_errors(mapping);
697         }
698         return err;
699 }
700 EXPORT_SYMBOL(filemap_write_and_wait_range);
701
702 void __filemap_set_wb_err(struct address_space *mapping, int err)
703 {
704         errseq_t eseq = errseq_set(&mapping->wb_err, err);
705
706         trace_filemap_set_wb_err(mapping, eseq);
707 }
708 EXPORT_SYMBOL(__filemap_set_wb_err);
709
710 /**
711  * file_check_and_advance_wb_err - report wb error (if any) that was previously
712  *                                 and advance wb_err to current one
713  * @file: struct file on which the error is being reported
714  *
715  * When userland calls fsync (or something like nfsd does the equivalent), we
716  * want to report any writeback errors that occurred since the last fsync (or
717  * since the file was opened if there haven't been any).
718  *
719  * Grab the wb_err from the mapping. If it matches what we have in the file,
720  * then just quickly return 0. The file is all caught up.
721  *
722  * If it doesn't match, then take the mapping value, set the "seen" flag in
723  * it and try to swap it into place. If it works, or another task beat us
724  * to it with the new value, then update the f_wb_err and return the error
725  * portion. The error at this point must be reported via proper channels
726  * (a'la fsync, or NFS COMMIT operation, etc.).
727  *
728  * While we handle mapping->wb_err with atomic operations, the f_wb_err
729  * value is protected by the f_lock since we must ensure that it reflects
730  * the latest value swapped in for this file descriptor.
731  *
732  * Return: %0 on success, negative error code otherwise.
733  */
734 int file_check_and_advance_wb_err(struct file *file)
735 {
736         int err = 0;
737         errseq_t old = READ_ONCE(file->f_wb_err);
738         struct address_space *mapping = file->f_mapping;
739
740         /* Locklessly handle the common case where nothing has changed */
741         if (errseq_check(&mapping->wb_err, old)) {
742                 /* Something changed, must use slow path */
743                 spin_lock(&file->f_lock);
744                 old = file->f_wb_err;
745                 err = errseq_check_and_advance(&mapping->wb_err,
746                                                 &file->f_wb_err);
747                 trace_file_check_and_advance_wb_err(file, old);
748                 spin_unlock(&file->f_lock);
749         }
750
751         /*
752          * We're mostly using this function as a drop in replacement for
753          * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
754          * that the legacy code would have had on these flags.
755          */
756         clear_bit(AS_EIO, &mapping->flags);
757         clear_bit(AS_ENOSPC, &mapping->flags);
758         return err;
759 }
760 EXPORT_SYMBOL(file_check_and_advance_wb_err);
761
762 /**
763  * file_write_and_wait_range - write out & wait on a file range
764  * @file:       file pointing to address_space with pages
765  * @lstart:     offset in bytes where the range starts
766  * @lend:       offset in bytes where the range ends (inclusive)
767  *
768  * Write out and wait upon file offsets lstart->lend, inclusive.
769  *
770  * Note that @lend is inclusive (describes the last byte to be written) so
771  * that this function can be used to write to the very end-of-file (end = -1).
772  *
773  * After writing out and waiting on the data, we check and advance the
774  * f_wb_err cursor to the latest value, and return any errors detected there.
775  *
776  * Return: %0 on success, negative error code otherwise.
777  */
778 int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
779 {
780         int err = 0, err2;
781         struct address_space *mapping = file->f_mapping;
782
783         if (mapping_needs_writeback(mapping)) {
784                 err = __filemap_fdatawrite_range(mapping, lstart, lend,
785                                                  WB_SYNC_ALL);
786                 /* See comment of filemap_write_and_wait() */
787                 if (err != -EIO)
788                         __filemap_fdatawait_range(mapping, lstart, lend);
789         }
790         err2 = file_check_and_advance_wb_err(file);
791         if (!err)
792                 err = err2;
793         return err;
794 }
795 EXPORT_SYMBOL(file_write_and_wait_range);
796
797 /**
798  * replace_page_cache_page - replace a pagecache page with a new one
799  * @old:        page to be replaced
800  * @new:        page to replace with
801  *
802  * This function replaces a page in the pagecache with a new one.  On
803  * success it acquires the pagecache reference for the new page and
804  * drops it for the old page.  Both the old and new pages must be
805  * locked.  This function does not add the new page to the LRU, the
806  * caller must do that.
807  *
808  * The remove + add is atomic.  This function cannot fail.
809  */
810 void replace_page_cache_page(struct page *old, struct page *new)
811 {
812         struct folio *fold = page_folio(old);
813         struct folio *fnew = page_folio(new);
814         struct address_space *mapping = old->mapping;
815         void (*freepage)(struct page *) = mapping->a_ops->freepage;
816         pgoff_t offset = old->index;
817         XA_STATE(xas, &mapping->i_pages, offset);
818
819         VM_BUG_ON_PAGE(!PageLocked(old), old);
820         VM_BUG_ON_PAGE(!PageLocked(new), new);
821         VM_BUG_ON_PAGE(new->mapping, new);
822
823         get_page(new);
824         new->mapping = mapping;
825         new->index = offset;
826
827         mem_cgroup_migrate(fold, fnew);
828
829         xas_lock_irq(&xas);
830         xas_store(&xas, new);
831
832         old->mapping = NULL;
833         /* hugetlb pages do not participate in page cache accounting. */
834         if (!PageHuge(old))
835                 __dec_lruvec_page_state(old, NR_FILE_PAGES);
836         if (!PageHuge(new))
837                 __inc_lruvec_page_state(new, NR_FILE_PAGES);
838         if (PageSwapBacked(old))
839                 __dec_lruvec_page_state(old, NR_SHMEM);
840         if (PageSwapBacked(new))
841                 __inc_lruvec_page_state(new, NR_SHMEM);
842         xas_unlock_irq(&xas);
843         if (freepage)
844                 freepage(old);
845         put_page(old);
846 }
847 EXPORT_SYMBOL_GPL(replace_page_cache_page);
848
849 noinline int __filemap_add_folio(struct address_space *mapping,
850                 struct folio *folio, pgoff_t index, gfp_t gfp, void **shadowp)
851 {
852         XA_STATE(xas, &mapping->i_pages, index);
853         int huge = folio_test_hugetlb(folio);
854         int error;
855         bool charged = false;
856
857         VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
858         VM_BUG_ON_FOLIO(folio_test_swapbacked(folio), folio);
859         mapping_set_update(&xas, mapping);
860
861         folio_get(folio);
862         folio->mapping = mapping;
863         folio->index = index;
864
865         if (!huge) {
866                 error = mem_cgroup_charge(folio, NULL, gfp);
867                 VM_BUG_ON_FOLIO(index & (folio_nr_pages(folio) - 1), folio);
868                 if (error)
869                         goto error;
870                 charged = true;
871         }
872
873         gfp &= GFP_RECLAIM_MASK;
874
875         do {
876                 unsigned int order = xa_get_order(xas.xa, xas.xa_index);
877                 void *entry, *old = NULL;
878
879                 if (order > folio_order(folio))
880                         xas_split_alloc(&xas, xa_load(xas.xa, xas.xa_index),
881                                         order, gfp);
882                 xas_lock_irq(&xas);
883                 xas_for_each_conflict(&xas, entry) {
884                         old = entry;
885                         if (!xa_is_value(entry)) {
886                                 xas_set_err(&xas, -EEXIST);
887                                 goto unlock;
888                         }
889                 }
890
891                 if (old) {
892                         if (shadowp)
893                                 *shadowp = old;
894                         /* entry may have been split before we acquired lock */
895                         order = xa_get_order(xas.xa, xas.xa_index);
896                         if (order > folio_order(folio)) {
897                                 xas_split(&xas, old, order);
898                                 xas_reset(&xas);
899                         }
900                 }
901
902                 xas_store(&xas, folio);
903                 if (xas_error(&xas))
904                         goto unlock;
905
906                 mapping->nrpages++;
907
908                 /* hugetlb pages do not participate in page cache accounting */
909                 if (!huge)
910                         __lruvec_stat_add_folio(folio, NR_FILE_PAGES);
911 unlock:
912                 xas_unlock_irq(&xas);
913         } while (xas_nomem(&xas, gfp));
914
915         if (xas_error(&xas)) {
916                 error = xas_error(&xas);
917                 if (charged)
918                         mem_cgroup_uncharge(folio);
919                 goto error;
920         }
921
922         trace_mm_filemap_add_to_page_cache(folio);
923         return 0;
924 error:
925         folio->mapping = NULL;
926         /* Leave page->index set: truncation relies upon it */
927         folio_put(folio);
928         return error;
929 }
930 ALLOW_ERROR_INJECTION(__filemap_add_folio, ERRNO);
931
932 /**
933  * add_to_page_cache_locked - add a locked page to the pagecache
934  * @page:       page to add
935  * @mapping:    the page's address_space
936  * @offset:     page index
937  * @gfp_mask:   page allocation mode
938  *
939  * This function is used to add a page to the pagecache. It must be locked.
940  * This function does not add the page to the LRU.  The caller must do that.
941  *
942  * Return: %0 on success, negative error code otherwise.
943  */
944 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
945                 pgoff_t offset, gfp_t gfp_mask)
946 {
947         return __filemap_add_folio(mapping, page_folio(page), offset,
948                                           gfp_mask, NULL);
949 }
950 EXPORT_SYMBOL(add_to_page_cache_locked);
951
952 int filemap_add_folio(struct address_space *mapping, struct folio *folio,
953                                 pgoff_t index, gfp_t gfp)
954 {
955         void *shadow = NULL;
956         int ret;
957
958         __folio_set_locked(folio);
959         ret = __filemap_add_folio(mapping, folio, index, gfp, &shadow);
960         if (unlikely(ret))
961                 __folio_clear_locked(folio);
962         else {
963                 /*
964                  * The folio might have been evicted from cache only
965                  * recently, in which case it should be activated like
966                  * any other repeatedly accessed folio.
967                  * The exception is folios getting rewritten; evicting other
968                  * data from the working set, only to cache data that will
969                  * get overwritten with something else, is a waste of memory.
970                  */
971                 WARN_ON_ONCE(folio_test_active(folio));
972                 if (!(gfp & __GFP_WRITE) && shadow)
973                         workingset_refault(folio, shadow);
974                 folio_add_lru(folio);
975         }
976         return ret;
977 }
978 EXPORT_SYMBOL_GPL(filemap_add_folio);
979
980 #ifdef CONFIG_NUMA
981 struct folio *filemap_alloc_folio(gfp_t gfp, unsigned int order)
982 {
983         int n;
984         struct folio *folio;
985
986         if (cpuset_do_page_mem_spread()) {
987                 unsigned int cpuset_mems_cookie;
988                 do {
989                         cpuset_mems_cookie = read_mems_allowed_begin();
990                         n = cpuset_mem_spread_node();
991                         folio = __folio_alloc_node(gfp, order, n);
992                 } while (!folio && read_mems_allowed_retry(cpuset_mems_cookie));
993
994                 return folio;
995         }
996         return folio_alloc(gfp, order);
997 }
998 EXPORT_SYMBOL(filemap_alloc_folio);
999 #endif
1000
1001 /*
1002  * filemap_invalidate_lock_two - lock invalidate_lock for two mappings
1003  *
1004  * Lock exclusively invalidate_lock of any passed mapping that is not NULL.
1005  *
1006  * @mapping1: the first mapping to lock
1007  * @mapping2: the second mapping to lock
1008  */
1009 void filemap_invalidate_lock_two(struct address_space *mapping1,
1010                                  struct address_space *mapping2)
1011 {
1012         if (mapping1 > mapping2)
1013                 swap(mapping1, mapping2);
1014         if (mapping1)
1015                 down_write(&mapping1->invalidate_lock);
1016         if (mapping2 && mapping1 != mapping2)
1017                 down_write_nested(&mapping2->invalidate_lock, 1);
1018 }
1019 EXPORT_SYMBOL(filemap_invalidate_lock_two);
1020
1021 /*
1022  * filemap_invalidate_unlock_two - unlock invalidate_lock for two mappings
1023  *
1024  * Unlock exclusive invalidate_lock of any passed mapping that is not NULL.
1025  *
1026  * @mapping1: the first mapping to unlock
1027  * @mapping2: the second mapping to unlock
1028  */
1029 void filemap_invalidate_unlock_two(struct address_space *mapping1,
1030                                    struct address_space *mapping2)
1031 {
1032         if (mapping1)
1033                 up_write(&mapping1->invalidate_lock);
1034         if (mapping2 && mapping1 != mapping2)
1035                 up_write(&mapping2->invalidate_lock);
1036 }
1037 EXPORT_SYMBOL(filemap_invalidate_unlock_two);
1038
1039 /*
1040  * In order to wait for pages to become available there must be
1041  * waitqueues associated with pages. By using a hash table of
1042  * waitqueues where the bucket discipline is to maintain all
1043  * waiters on the same queue and wake all when any of the pages
1044  * become available, and for the woken contexts to check to be
1045  * sure the appropriate page became available, this saves space
1046  * at a cost of "thundering herd" phenomena during rare hash
1047  * collisions.
1048  */
1049 #define PAGE_WAIT_TABLE_BITS 8
1050 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
1051 static wait_queue_head_t folio_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
1052
1053 static wait_queue_head_t *folio_waitqueue(struct folio *folio)
1054 {
1055         return &folio_wait_table[hash_ptr(folio, PAGE_WAIT_TABLE_BITS)];
1056 }
1057
1058 void __init pagecache_init(void)
1059 {
1060         int i;
1061
1062         for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1063                 init_waitqueue_head(&folio_wait_table[i]);
1064
1065         page_writeback_init();
1066 }
1067
1068 /*
1069  * The page wait code treats the "wait->flags" somewhat unusually, because
1070  * we have multiple different kinds of waits, not just the usual "exclusive"
1071  * one.
1072  *
1073  * We have:
1074  *
1075  *  (a) no special bits set:
1076  *
1077  *      We're just waiting for the bit to be released, and when a waker
1078  *      calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up,
1079  *      and remove it from the wait queue.
1080  *
1081  *      Simple and straightforward.
1082  *
1083  *  (b) WQ_FLAG_EXCLUSIVE:
1084  *
1085  *      The waiter is waiting to get the lock, and only one waiter should
1086  *      be woken up to avoid any thundering herd behavior. We'll set the
1087  *      WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue.
1088  *
1089  *      This is the traditional exclusive wait.
1090  *
1091  *  (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
1092  *
1093  *      The waiter is waiting to get the bit, and additionally wants the
1094  *      lock to be transferred to it for fair lock behavior. If the lock
1095  *      cannot be taken, we stop walking the wait queue without waking
1096  *      the waiter.
1097  *
1098  *      This is the "fair lock handoff" case, and in addition to setting
1099  *      WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see
1100  *      that it now has the lock.
1101  */
1102 static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
1103 {
1104         unsigned int flags;
1105         struct wait_page_key *key = arg;
1106         struct wait_page_queue *wait_page
1107                 = container_of(wait, struct wait_page_queue, wait);
1108
1109         if (!wake_page_match(wait_page, key))
1110                 return 0;
1111
1112         /*
1113          * If it's a lock handoff wait, we get the bit for it, and
1114          * stop walking (and do not wake it up) if we can't.
1115          */
1116         flags = wait->flags;
1117         if (flags & WQ_FLAG_EXCLUSIVE) {
1118                 if (test_bit(key->bit_nr, &key->folio->flags))
1119                         return -1;
1120                 if (flags & WQ_FLAG_CUSTOM) {
1121                         if (test_and_set_bit(key->bit_nr, &key->folio->flags))
1122                                 return -1;
1123                         flags |= WQ_FLAG_DONE;
1124                 }
1125         }
1126
1127         /*
1128          * We are holding the wait-queue lock, but the waiter that
1129          * is waiting for this will be checking the flags without
1130          * any locking.
1131          *
1132          * So update the flags atomically, and wake up the waiter
1133          * afterwards to avoid any races. This store-release pairs
1134          * with the load-acquire in folio_wait_bit_common().
1135          */
1136         smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
1137         wake_up_state(wait->private, mode);
1138
1139         /*
1140          * Ok, we have successfully done what we're waiting for,
1141          * and we can unconditionally remove the wait entry.
1142          *
1143          * Note that this pairs with the "finish_wait()" in the
1144          * waiter, and has to be the absolute last thing we do.
1145          * After this list_del_init(&wait->entry) the wait entry
1146          * might be de-allocated and the process might even have
1147          * exited.
1148          */
1149         list_del_init_careful(&wait->entry);
1150         return (flags & WQ_FLAG_EXCLUSIVE) != 0;
1151 }
1152
1153 static void folio_wake_bit(struct folio *folio, int bit_nr)
1154 {
1155         wait_queue_head_t *q = folio_waitqueue(folio);
1156         struct wait_page_key key;
1157         unsigned long flags;
1158         wait_queue_entry_t bookmark;
1159
1160         key.folio = folio;
1161         key.bit_nr = bit_nr;
1162         key.page_match = 0;
1163
1164         bookmark.flags = 0;
1165         bookmark.private = NULL;
1166         bookmark.func = NULL;
1167         INIT_LIST_HEAD(&bookmark.entry);
1168
1169         spin_lock_irqsave(&q->lock, flags);
1170         __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1171
1172         while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1173                 /*
1174                  * Take a breather from holding the lock,
1175                  * allow pages that finish wake up asynchronously
1176                  * to acquire the lock and remove themselves
1177                  * from wait queue
1178                  */
1179                 spin_unlock_irqrestore(&q->lock, flags);
1180                 cpu_relax();
1181                 spin_lock_irqsave(&q->lock, flags);
1182                 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1183         }
1184
1185         /*
1186          * It is possible for other pages to have collided on the waitqueue
1187          * hash, so in that case check for a page match. That prevents a long-
1188          * term waiter
1189          *
1190          * It is still possible to miss a case here, when we woke page waiters
1191          * and removed them from the waitqueue, but there are still other
1192          * page waiters.
1193          */
1194         if (!waitqueue_active(q) || !key.page_match) {
1195                 folio_clear_waiters(folio);
1196                 /*
1197                  * It's possible to miss clearing Waiters here, when we woke
1198                  * our page waiters, but the hashed waitqueue has waiters for
1199                  * other pages on it.
1200                  *
1201                  * That's okay, it's a rare case. The next waker will clear it.
1202                  */
1203         }
1204         spin_unlock_irqrestore(&q->lock, flags);
1205 }
1206
1207 static void folio_wake(struct folio *folio, int bit)
1208 {
1209         if (!folio_test_waiters(folio))
1210                 return;
1211         folio_wake_bit(folio, bit);
1212 }
1213
1214 /*
1215  * A choice of three behaviors for folio_wait_bit_common():
1216  */
1217 enum behavior {
1218         EXCLUSIVE,      /* Hold ref to page and take the bit when woken, like
1219                          * __folio_lock() waiting on then setting PG_locked.
1220                          */
1221         SHARED,         /* Hold ref to page and check the bit when woken, like
1222                          * folio_wait_writeback() waiting on PG_writeback.
1223                          */
1224         DROP,           /* Drop ref to page before wait, no check when woken,
1225                          * like folio_put_wait_locked() on PG_locked.
1226                          */
1227 };
1228
1229 /*
1230  * Attempt to check (or get) the folio flag, and mark us done
1231  * if successful.
1232  */
1233 static inline bool folio_trylock_flag(struct folio *folio, int bit_nr,
1234                                         struct wait_queue_entry *wait)
1235 {
1236         if (wait->flags & WQ_FLAG_EXCLUSIVE) {
1237                 if (test_and_set_bit(bit_nr, &folio->flags))
1238                         return false;
1239         } else if (test_bit(bit_nr, &folio->flags))
1240                 return false;
1241
1242         wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
1243         return true;
1244 }
1245
1246 /* How many times do we accept lock stealing from under a waiter? */
1247 int sysctl_page_lock_unfairness = 5;
1248
1249 static inline int folio_wait_bit_common(struct folio *folio, int bit_nr,
1250                 int state, enum behavior behavior)
1251 {
1252         wait_queue_head_t *q = folio_waitqueue(folio);
1253         int unfairness = sysctl_page_lock_unfairness;
1254         struct wait_page_queue wait_page;
1255         wait_queue_entry_t *wait = &wait_page.wait;
1256         bool thrashing = false;
1257         bool delayacct = false;
1258         unsigned long pflags;
1259
1260         if (bit_nr == PG_locked &&
1261             !folio_test_uptodate(folio) && folio_test_workingset(folio)) {
1262                 if (!folio_test_swapbacked(folio)) {
1263                         delayacct_thrashing_start();
1264                         delayacct = true;
1265                 }
1266                 psi_memstall_enter(&pflags);
1267                 thrashing = true;
1268         }
1269
1270         init_wait(wait);
1271         wait->func = wake_page_function;
1272         wait_page.folio = folio;
1273         wait_page.bit_nr = bit_nr;
1274
1275 repeat:
1276         wait->flags = 0;
1277         if (behavior == EXCLUSIVE) {
1278                 wait->flags = WQ_FLAG_EXCLUSIVE;
1279                 if (--unfairness < 0)
1280                         wait->flags |= WQ_FLAG_CUSTOM;
1281         }
1282
1283         /*
1284          * Do one last check whether we can get the
1285          * page bit synchronously.
1286          *
1287          * Do the folio_set_waiters() marking before that
1288          * to let any waker we _just_ missed know they
1289          * need to wake us up (otherwise they'll never
1290          * even go to the slow case that looks at the
1291          * page queue), and add ourselves to the wait
1292          * queue if we need to sleep.
1293          *
1294          * This part needs to be done under the queue
1295          * lock to avoid races.
1296          */
1297         spin_lock_irq(&q->lock);
1298         folio_set_waiters(folio);
1299         if (!folio_trylock_flag(folio, bit_nr, wait))
1300                 __add_wait_queue_entry_tail(q, wait);
1301         spin_unlock_irq(&q->lock);
1302
1303         /*
1304          * From now on, all the logic will be based on
1305          * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to
1306          * see whether the page bit testing has already
1307          * been done by the wake function.
1308          *
1309          * We can drop our reference to the folio.
1310          */
1311         if (behavior == DROP)
1312                 folio_put(folio);
1313
1314         /*
1315          * Note that until the "finish_wait()", or until
1316          * we see the WQ_FLAG_WOKEN flag, we need to
1317          * be very careful with the 'wait->flags', because
1318          * we may race with a waker that sets them.
1319          */
1320         for (;;) {
1321                 unsigned int flags;
1322
1323                 set_current_state(state);
1324
1325                 /* Loop until we've been woken or interrupted */
1326                 flags = smp_load_acquire(&wait->flags);
1327                 if (!(flags & WQ_FLAG_WOKEN)) {
1328                         if (signal_pending_state(state, current))
1329                                 break;
1330
1331                         io_schedule();
1332                         continue;
1333                 }
1334
1335                 /* If we were non-exclusive, we're done */
1336                 if (behavior != EXCLUSIVE)
1337                         break;
1338
1339                 /* If the waker got the lock for us, we're done */
1340                 if (flags & WQ_FLAG_DONE)
1341                         break;
1342
1343                 /*
1344                  * Otherwise, if we're getting the lock, we need to
1345                  * try to get it ourselves.
1346                  *
1347                  * And if that fails, we'll have to retry this all.
1348                  */
1349                 if (unlikely(test_and_set_bit(bit_nr, folio_flags(folio, 0))))
1350                         goto repeat;
1351
1352                 wait->flags |= WQ_FLAG_DONE;
1353                 break;
1354         }
1355
1356         /*
1357          * If a signal happened, this 'finish_wait()' may remove the last
1358          * waiter from the wait-queues, but the folio waiters bit will remain
1359          * set. That's ok. The next wakeup will take care of it, and trying
1360          * to do it here would be difficult and prone to races.
1361          */
1362         finish_wait(q, wait);
1363
1364         if (thrashing) {
1365                 if (delayacct)
1366                         delayacct_thrashing_end();
1367                 psi_memstall_leave(&pflags);
1368         }
1369
1370         /*
1371          * NOTE! The wait->flags weren't stable until we've done the
1372          * 'finish_wait()', and we could have exited the loop above due
1373          * to a signal, and had a wakeup event happen after the signal
1374          * test but before the 'finish_wait()'.
1375          *
1376          * So only after the finish_wait() can we reliably determine
1377          * if we got woken up or not, so we can now figure out the final
1378          * return value based on that state without races.
1379          *
1380          * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
1381          * waiter, but an exclusive one requires WQ_FLAG_DONE.
1382          */
1383         if (behavior == EXCLUSIVE)
1384                 return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
1385
1386         return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
1387 }
1388
1389 void folio_wait_bit(struct folio *folio, int bit_nr)
1390 {
1391         folio_wait_bit_common(folio, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
1392 }
1393 EXPORT_SYMBOL(folio_wait_bit);
1394
1395 int folio_wait_bit_killable(struct folio *folio, int bit_nr)
1396 {
1397         return folio_wait_bit_common(folio, bit_nr, TASK_KILLABLE, SHARED);
1398 }
1399 EXPORT_SYMBOL(folio_wait_bit_killable);
1400
1401 /**
1402  * folio_put_wait_locked - Drop a reference and wait for it to be unlocked
1403  * @folio: The folio to wait for.
1404  * @state: The sleep state (TASK_KILLABLE, TASK_UNINTERRUPTIBLE, etc).
1405  *
1406  * The caller should hold a reference on @folio.  They expect the page to
1407  * become unlocked relatively soon, but do not wish to hold up migration
1408  * (for example) by holding the reference while waiting for the folio to
1409  * come unlocked.  After this function returns, the caller should not
1410  * dereference @folio.
1411  *
1412  * Return: 0 if the folio was unlocked or -EINTR if interrupted by a signal.
1413  */
1414 int folio_put_wait_locked(struct folio *folio, int state)
1415 {
1416         return folio_wait_bit_common(folio, PG_locked, state, DROP);
1417 }
1418
1419 /**
1420  * folio_add_wait_queue - Add an arbitrary waiter to a folio's wait queue
1421  * @folio: Folio defining the wait queue of interest
1422  * @waiter: Waiter to add to the queue
1423  *
1424  * Add an arbitrary @waiter to the wait queue for the nominated @folio.
1425  */
1426 void folio_add_wait_queue(struct folio *folio, wait_queue_entry_t *waiter)
1427 {
1428         wait_queue_head_t *q = folio_waitqueue(folio);
1429         unsigned long flags;
1430
1431         spin_lock_irqsave(&q->lock, flags);
1432         __add_wait_queue_entry_tail(q, waiter);
1433         folio_set_waiters(folio);
1434         spin_unlock_irqrestore(&q->lock, flags);
1435 }
1436 EXPORT_SYMBOL_GPL(folio_add_wait_queue);
1437
1438 #ifndef clear_bit_unlock_is_negative_byte
1439
1440 /*
1441  * PG_waiters is the high bit in the same byte as PG_lock.
1442  *
1443  * On x86 (and on many other architectures), we can clear PG_lock and
1444  * test the sign bit at the same time. But if the architecture does
1445  * not support that special operation, we just do this all by hand
1446  * instead.
1447  *
1448  * The read of PG_waiters has to be after (or concurrently with) PG_locked
1449  * being cleared, but a memory barrier should be unnecessary since it is
1450  * in the same byte as PG_locked.
1451  */
1452 static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1453 {
1454         clear_bit_unlock(nr, mem);
1455         /* smp_mb__after_atomic(); */
1456         return test_bit(PG_waiters, mem);
1457 }
1458
1459 #endif
1460
1461 /**
1462  * folio_unlock - Unlock a locked folio.
1463  * @folio: The folio.
1464  *
1465  * Unlocks the folio and wakes up any thread sleeping on the page lock.
1466  *
1467  * Context: May be called from interrupt or process context.  May not be
1468  * called from NMI context.
1469  */
1470 void folio_unlock(struct folio *folio)
1471 {
1472         /* Bit 7 allows x86 to check the byte's sign bit */
1473         BUILD_BUG_ON(PG_waiters != 7);
1474         BUILD_BUG_ON(PG_locked > 7);
1475         VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
1476         if (clear_bit_unlock_is_negative_byte(PG_locked, folio_flags(folio, 0)))
1477                 folio_wake_bit(folio, PG_locked);
1478 }
1479 EXPORT_SYMBOL(folio_unlock);
1480
1481 /**
1482  * folio_end_private_2 - Clear PG_private_2 and wake any waiters.
1483  * @folio: The folio.
1484  *
1485  * Clear the PG_private_2 bit on a folio and wake up any sleepers waiting for
1486  * it.  The folio reference held for PG_private_2 being set is released.
1487  *
1488  * This is, for example, used when a netfs folio is being written to a local
1489  * disk cache, thereby allowing writes to the cache for the same folio to be
1490  * serialised.
1491  */
1492 void folio_end_private_2(struct folio *folio)
1493 {
1494         VM_BUG_ON_FOLIO(!folio_test_private_2(folio), folio);
1495         clear_bit_unlock(PG_private_2, folio_flags(folio, 0));
1496         folio_wake_bit(folio, PG_private_2);
1497         folio_put(folio);
1498 }
1499 EXPORT_SYMBOL(folio_end_private_2);
1500
1501 /**
1502  * folio_wait_private_2 - Wait for PG_private_2 to be cleared on a folio.
1503  * @folio: The folio to wait on.
1504  *
1505  * Wait for PG_private_2 (aka PG_fscache) to be cleared on a folio.
1506  */
1507 void folio_wait_private_2(struct folio *folio)
1508 {
1509         while (folio_test_private_2(folio))
1510                 folio_wait_bit(folio, PG_private_2);
1511 }
1512 EXPORT_SYMBOL(folio_wait_private_2);
1513
1514 /**
1515  * folio_wait_private_2_killable - Wait for PG_private_2 to be cleared on a folio.
1516  * @folio: The folio to wait on.
1517  *
1518  * Wait for PG_private_2 (aka PG_fscache) to be cleared on a folio or until a
1519  * fatal signal is received by the calling task.
1520  *
1521  * Return:
1522  * - 0 if successful.
1523  * - -EINTR if a fatal signal was encountered.
1524  */
1525 int folio_wait_private_2_killable(struct folio *folio)
1526 {
1527         int ret = 0;
1528
1529         while (folio_test_private_2(folio)) {
1530                 ret = folio_wait_bit_killable(folio, PG_private_2);
1531                 if (ret < 0)
1532                         break;
1533         }
1534
1535         return ret;
1536 }
1537 EXPORT_SYMBOL(folio_wait_private_2_killable);
1538
1539 /**
1540  * folio_end_writeback - End writeback against a folio.
1541  * @folio: The folio.
1542  */
1543 void folio_end_writeback(struct folio *folio)
1544 {
1545         /*
1546          * folio_test_clear_reclaim() could be used here but it is an
1547          * atomic operation and overkill in this particular case. Failing
1548          * to shuffle a folio marked for immediate reclaim is too mild
1549          * a gain to justify taking an atomic operation penalty at the
1550          * end of every folio writeback.
1551          */
1552         if (folio_test_reclaim(folio)) {
1553                 folio_clear_reclaim(folio);
1554                 folio_rotate_reclaimable(folio);
1555         }
1556
1557         /*
1558          * Writeback does not hold a folio reference of its own, relying
1559          * on truncation to wait for the clearing of PG_writeback.
1560          * But here we must make sure that the folio is not freed and
1561          * reused before the folio_wake().
1562          */
1563         folio_get(folio);
1564         if (!__folio_end_writeback(folio))
1565                 BUG();
1566
1567         smp_mb__after_atomic();
1568         folio_wake(folio, PG_writeback);
1569         acct_reclaim_writeback(folio);
1570         folio_put(folio);
1571 }
1572 EXPORT_SYMBOL(folio_end_writeback);
1573
1574 /*
1575  * After completing I/O on a page, call this routine to update the page
1576  * flags appropriately
1577  */
1578 void page_endio(struct page *page, bool is_write, int err)
1579 {
1580         if (!is_write) {
1581                 if (!err) {
1582                         SetPageUptodate(page);
1583                 } else {
1584                         ClearPageUptodate(page);
1585                         SetPageError(page);
1586                 }
1587                 unlock_page(page);
1588         } else {
1589                 if (err) {
1590                         struct address_space *mapping;
1591
1592                         SetPageError(page);
1593                         mapping = page_mapping(page);
1594                         if (mapping)
1595                                 mapping_set_error(mapping, err);
1596                 }
1597                 end_page_writeback(page);
1598         }
1599 }
1600 EXPORT_SYMBOL_GPL(page_endio);
1601
1602 /**
1603  * __folio_lock - Get a lock on the folio, assuming we need to sleep to get it.
1604  * @folio: The folio to lock
1605  */
1606 void __folio_lock(struct folio *folio)
1607 {
1608         folio_wait_bit_common(folio, PG_locked, TASK_UNINTERRUPTIBLE,
1609                                 EXCLUSIVE);
1610 }
1611 EXPORT_SYMBOL(__folio_lock);
1612
1613 int __folio_lock_killable(struct folio *folio)
1614 {
1615         return folio_wait_bit_common(folio, PG_locked, TASK_KILLABLE,
1616                                         EXCLUSIVE);
1617 }
1618 EXPORT_SYMBOL_GPL(__folio_lock_killable);
1619
1620 static int __folio_lock_async(struct folio *folio, struct wait_page_queue *wait)
1621 {
1622         struct wait_queue_head *q = folio_waitqueue(folio);
1623         int ret = 0;
1624
1625         wait->folio = folio;
1626         wait->bit_nr = PG_locked;
1627
1628         spin_lock_irq(&q->lock);
1629         __add_wait_queue_entry_tail(q, &wait->wait);
1630         folio_set_waiters(folio);
1631         ret = !folio_trylock(folio);
1632         /*
1633          * If we were successful now, we know we're still on the
1634          * waitqueue as we're still under the lock. This means it's
1635          * safe to remove and return success, we know the callback
1636          * isn't going to trigger.
1637          */
1638         if (!ret)
1639                 __remove_wait_queue(q, &wait->wait);
1640         else
1641                 ret = -EIOCBQUEUED;
1642         spin_unlock_irq(&q->lock);
1643         return ret;
1644 }
1645
1646 /*
1647  * Return values:
1648  * true - folio is locked; mmap_lock is still held.
1649  * false - folio is not locked.
1650  *     mmap_lock has been released (mmap_read_unlock(), unless flags had both
1651  *     FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1652  *     which case mmap_lock is still held.
1653  *
1654  * If neither ALLOW_RETRY nor KILLABLE are set, will always return true
1655  * with the folio locked and the mmap_lock unperturbed.
1656  */
1657 bool __folio_lock_or_retry(struct folio *folio, struct mm_struct *mm,
1658                          unsigned int flags)
1659 {
1660         if (fault_flag_allow_retry_first(flags)) {
1661                 /*
1662                  * CAUTION! In this case, mmap_lock is not released
1663                  * even though return 0.
1664                  */
1665                 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1666                         return false;
1667
1668                 mmap_read_unlock(mm);
1669                 if (flags & FAULT_FLAG_KILLABLE)
1670                         folio_wait_locked_killable(folio);
1671                 else
1672                         folio_wait_locked(folio);
1673                 return false;
1674         }
1675         if (flags & FAULT_FLAG_KILLABLE) {
1676                 bool ret;
1677
1678                 ret = __folio_lock_killable(folio);
1679                 if (ret) {
1680                         mmap_read_unlock(mm);
1681                         return false;
1682                 }
1683         } else {
1684                 __folio_lock(folio);
1685         }
1686
1687         return true;
1688 }
1689
1690 /**
1691  * page_cache_next_miss() - Find the next gap in the page cache.
1692  * @mapping: Mapping.
1693  * @index: Index.
1694  * @max_scan: Maximum range to search.
1695  *
1696  * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1697  * gap with the lowest index.
1698  *
1699  * This function may be called under the rcu_read_lock.  However, this will
1700  * not atomically search a snapshot of the cache at a single point in time.
1701  * For example, if a gap is created at index 5, then subsequently a gap is
1702  * created at index 10, page_cache_next_miss covering both indices may
1703  * return 10 if called under the rcu_read_lock.
1704  *
1705  * Return: The index of the gap if found, otherwise an index outside the
1706  * range specified (in which case 'return - index >= max_scan' will be true).
1707  * In the rare case of index wrap-around, 0 will be returned.
1708  */
1709 pgoff_t page_cache_next_miss(struct address_space *mapping,
1710                              pgoff_t index, unsigned long max_scan)
1711 {
1712         XA_STATE(xas, &mapping->i_pages, index);
1713
1714         while (max_scan--) {
1715                 void *entry = xas_next(&xas);
1716                 if (!entry || xa_is_value(entry))
1717                         break;
1718                 if (xas.xa_index == 0)
1719                         break;
1720         }
1721
1722         return xas.xa_index;
1723 }
1724 EXPORT_SYMBOL(page_cache_next_miss);
1725
1726 /**
1727  * page_cache_prev_miss() - Find the previous gap in the page cache.
1728  * @mapping: Mapping.
1729  * @index: Index.
1730  * @max_scan: Maximum range to search.
1731  *
1732  * Search the range [max(index - max_scan + 1, 0), index] for the
1733  * gap with the highest index.
1734  *
1735  * This function may be called under the rcu_read_lock.  However, this will
1736  * not atomically search a snapshot of the cache at a single point in time.
1737  * For example, if a gap is created at index 10, then subsequently a gap is
1738  * created at index 5, page_cache_prev_miss() covering both indices may
1739  * return 5 if called under the rcu_read_lock.
1740  *
1741  * Return: The index of the gap if found, otherwise an index outside the
1742  * range specified (in which case 'index - return >= max_scan' will be true).
1743  * In the rare case of wrap-around, ULONG_MAX will be returned.
1744  */
1745 pgoff_t page_cache_prev_miss(struct address_space *mapping,
1746                              pgoff_t index, unsigned long max_scan)
1747 {
1748         XA_STATE(xas, &mapping->i_pages, index);
1749
1750         while (max_scan--) {
1751                 void *entry = xas_prev(&xas);
1752                 if (!entry || xa_is_value(entry))
1753                         break;
1754                 if (xas.xa_index == ULONG_MAX)
1755                         break;
1756         }
1757
1758         return xas.xa_index;
1759 }
1760 EXPORT_SYMBOL(page_cache_prev_miss);
1761
1762 /*
1763  * Lockless page cache protocol:
1764  * On the lookup side:
1765  * 1. Load the folio from i_pages
1766  * 2. Increment the refcount if it's not zero
1767  * 3. If the folio is not found by xas_reload(), put the refcount and retry
1768  *
1769  * On the removal side:
1770  * A. Freeze the page (by zeroing the refcount if nobody else has a reference)
1771  * B. Remove the page from i_pages
1772  * C. Return the page to the page allocator
1773  *
1774  * This means that any page may have its reference count temporarily
1775  * increased by a speculative page cache (or fast GUP) lookup as it can
1776  * be allocated by another user before the RCU grace period expires.
1777  * Because the refcount temporarily acquired here may end up being the
1778  * last refcount on the page, any page allocation must be freeable by
1779  * folio_put().
1780  */
1781
1782 /*
1783  * mapping_get_entry - Get a page cache entry.
1784  * @mapping: the address_space to search
1785  * @index: The page cache index.
1786  *
1787  * Looks up the page cache entry at @mapping & @index.  If it is a folio,
1788  * it is returned with an increased refcount.  If it is a shadow entry
1789  * of a previously evicted folio, or a swap entry from shmem/tmpfs,
1790  * it is returned without further action.
1791  *
1792  * Return: The folio, swap or shadow entry, %NULL if nothing is found.
1793  */
1794 static void *mapping_get_entry(struct address_space *mapping, pgoff_t index)
1795 {
1796         XA_STATE(xas, &mapping->i_pages, index);
1797         struct folio *folio;
1798
1799         rcu_read_lock();
1800 repeat:
1801         xas_reset(&xas);
1802         folio = xas_load(&xas);
1803         if (xas_retry(&xas, folio))
1804                 goto repeat;
1805         /*
1806          * A shadow entry of a recently evicted page, or a swap entry from
1807          * shmem/tmpfs.  Return it without attempting to raise page count.
1808          */
1809         if (!folio || xa_is_value(folio))
1810                 goto out;
1811
1812         if (!folio_try_get_rcu(folio))
1813                 goto repeat;
1814
1815         if (unlikely(folio != xas_reload(&xas))) {
1816                 folio_put(folio);
1817                 goto repeat;
1818         }
1819 out:
1820         rcu_read_unlock();
1821
1822         return folio;
1823 }
1824
1825 /**
1826  * __filemap_get_folio - Find and get a reference to a folio.
1827  * @mapping: The address_space to search.
1828  * @index: The page index.
1829  * @fgp_flags: %FGP flags modify how the folio is returned.
1830  * @gfp: Memory allocation flags to use if %FGP_CREAT is specified.
1831  *
1832  * Looks up the page cache entry at @mapping & @index.
1833  *
1834  * @fgp_flags can be zero or more of these flags:
1835  *
1836  * * %FGP_ACCESSED - The folio will be marked accessed.
1837  * * %FGP_LOCK - The folio is returned locked.
1838  * * %FGP_ENTRY - If there is a shadow / swap / DAX entry, return it
1839  *   instead of allocating a new folio to replace it.
1840  * * %FGP_CREAT - If no page is present then a new page is allocated using
1841  *   @gfp and added to the page cache and the VM's LRU list.
1842  *   The page is returned locked and with an increased refcount.
1843  * * %FGP_FOR_MMAP - The caller wants to do its own locking dance if the
1844  *   page is already in cache.  If the page was allocated, unlock it before
1845  *   returning so the caller can do the same dance.
1846  * * %FGP_WRITE - The page will be written to by the caller.
1847  * * %FGP_NOFS - __GFP_FS will get cleared in gfp.
1848  * * %FGP_NOWAIT - Don't get blocked by page lock.
1849  * * %FGP_STABLE - Wait for the folio to be stable (finished writeback)
1850  *
1851  * If %FGP_LOCK or %FGP_CREAT are specified then the function may sleep even
1852  * if the %GFP flags specified for %FGP_CREAT are atomic.
1853  *
1854  * If there is a page cache page, it is returned with an increased refcount.
1855  *
1856  * Return: The found folio or %NULL otherwise.
1857  */
1858 struct folio *__filemap_get_folio(struct address_space *mapping, pgoff_t index,
1859                 int fgp_flags, gfp_t gfp)
1860 {
1861         struct folio *folio;
1862
1863 repeat:
1864         folio = mapping_get_entry(mapping, index);
1865         if (xa_is_value(folio)) {
1866                 if (fgp_flags & FGP_ENTRY)
1867                         return folio;
1868                 folio = NULL;
1869         }
1870         if (!folio)
1871                 goto no_page;
1872
1873         if (fgp_flags & FGP_LOCK) {
1874                 if (fgp_flags & FGP_NOWAIT) {
1875                         if (!folio_trylock(folio)) {
1876                                 folio_put(folio);
1877                                 return NULL;
1878                         }
1879                 } else {
1880                         folio_lock(folio);
1881                 }
1882
1883                 /* Has the page been truncated? */
1884                 if (unlikely(folio->mapping != mapping)) {
1885                         folio_unlock(folio);
1886                         folio_put(folio);
1887                         goto repeat;
1888                 }
1889                 VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
1890         }
1891
1892         if (fgp_flags & FGP_ACCESSED)
1893                 folio_mark_accessed(folio);
1894         else if (fgp_flags & FGP_WRITE) {
1895                 /* Clear idle flag for buffer write */
1896                 if (folio_test_idle(folio))
1897                         folio_clear_idle(folio);
1898         }
1899
1900         if (fgp_flags & FGP_STABLE)
1901                 folio_wait_stable(folio);
1902 no_page:
1903         if (!folio && (fgp_flags & FGP_CREAT)) {
1904                 int err;
1905                 if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping))
1906                         gfp |= __GFP_WRITE;
1907                 if (fgp_flags & FGP_NOFS)
1908                         gfp &= ~__GFP_FS;
1909
1910                 folio = filemap_alloc_folio(gfp, 0);
1911                 if (!folio)
1912                         return NULL;
1913
1914                 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
1915                         fgp_flags |= FGP_LOCK;
1916
1917                 /* Init accessed so avoid atomic mark_page_accessed later */
1918                 if (fgp_flags & FGP_ACCESSED)
1919                         __folio_set_referenced(folio);
1920
1921                 err = filemap_add_folio(mapping, folio, index, gfp);
1922                 if (unlikely(err)) {
1923                         folio_put(folio);
1924                         folio = NULL;
1925                         if (err == -EEXIST)
1926                                 goto repeat;
1927                 }
1928
1929                 /*
1930                  * filemap_add_folio locks the page, and for mmap
1931                  * we expect an unlocked page.
1932                  */
1933                 if (folio && (fgp_flags & FGP_FOR_MMAP))
1934                         folio_unlock(folio);
1935         }
1936
1937         return folio;
1938 }
1939 EXPORT_SYMBOL(__filemap_get_folio);
1940
1941 static inline struct folio *find_get_entry(struct xa_state *xas, pgoff_t max,
1942                 xa_mark_t mark)
1943 {
1944         struct folio *folio;
1945
1946 retry:
1947         if (mark == XA_PRESENT)
1948                 folio = xas_find(xas, max);
1949         else
1950                 folio = xas_find_marked(xas, max, mark);
1951
1952         if (xas_retry(xas, folio))
1953                 goto retry;
1954         /*
1955          * A shadow entry of a recently evicted page, a swap
1956          * entry from shmem/tmpfs or a DAX entry.  Return it
1957          * without attempting to raise page count.
1958          */
1959         if (!folio || xa_is_value(folio))
1960                 return folio;
1961
1962         if (!folio_try_get_rcu(folio))
1963                 goto reset;
1964
1965         if (unlikely(folio != xas_reload(xas))) {
1966                 folio_put(folio);
1967                 goto reset;
1968         }
1969
1970         return folio;
1971 reset:
1972         xas_reset(xas);
1973         goto retry;
1974 }
1975
1976 /**
1977  * find_get_entries - gang pagecache lookup
1978  * @mapping:    The address_space to search
1979  * @start:      The starting page cache index
1980  * @end:        The final page index (inclusive).
1981  * @fbatch:     Where the resulting entries are placed.
1982  * @indices:    The cache indices corresponding to the entries in @entries
1983  *
1984  * find_get_entries() will search for and return a batch of entries in
1985  * the mapping.  The entries are placed in @fbatch.  find_get_entries()
1986  * takes a reference on any actual folios it returns.
1987  *
1988  * The entries have ascending indexes.  The indices may not be consecutive
1989  * due to not-present entries or large folios.
1990  *
1991  * Any shadow entries of evicted folios, or swap entries from
1992  * shmem/tmpfs, are included in the returned array.
1993  *
1994  * Return: The number of entries which were found.
1995  */
1996 unsigned find_get_entries(struct address_space *mapping, pgoff_t start,
1997                 pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
1998 {
1999         XA_STATE(xas, &mapping->i_pages, start);
2000         struct folio *folio;
2001
2002         rcu_read_lock();
2003         while ((folio = find_get_entry(&xas, end, XA_PRESENT)) != NULL) {
2004                 indices[fbatch->nr] = xas.xa_index;
2005                 if (!folio_batch_add(fbatch, folio))
2006                         break;
2007         }
2008         rcu_read_unlock();
2009
2010         return folio_batch_count(fbatch);
2011 }
2012
2013 /**
2014  * find_lock_entries - Find a batch of pagecache entries.
2015  * @mapping:    The address_space to search.
2016  * @start:      The starting page cache index.
2017  * @end:        The final page index (inclusive).
2018  * @fbatch:     Where the resulting entries are placed.
2019  * @indices:    The cache indices of the entries in @fbatch.
2020  *
2021  * find_lock_entries() will return a batch of entries from @mapping.
2022  * Swap, shadow and DAX entries are included.  Folios are returned
2023  * locked and with an incremented refcount.  Folios which are locked
2024  * by somebody else or under writeback are skipped.  Folios which are
2025  * partially outside the range are not returned.
2026  *
2027  * The entries have ascending indexes.  The indices may not be consecutive
2028  * due to not-present entries, large folios, folios which could not be
2029  * locked or folios under writeback.
2030  *
2031  * Return: The number of entries which were found.
2032  */
2033 unsigned find_lock_entries(struct address_space *mapping, pgoff_t start,
2034                 pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
2035 {
2036         XA_STATE(xas, &mapping->i_pages, start);
2037         struct folio *folio;
2038
2039         rcu_read_lock();
2040         while ((folio = find_get_entry(&xas, end, XA_PRESENT))) {
2041                 if (!xa_is_value(folio)) {
2042                         if (folio->index < start)
2043                                 goto put;
2044                         if (folio->index + folio_nr_pages(folio) - 1 > end)
2045                                 goto put;
2046                         if (!folio_trylock(folio))
2047                                 goto put;
2048                         if (folio->mapping != mapping ||
2049                             folio_test_writeback(folio))
2050                                 goto unlock;
2051                         VM_BUG_ON_FOLIO(!folio_contains(folio, xas.xa_index),
2052                                         folio);
2053                 }
2054                 indices[fbatch->nr] = xas.xa_index;
2055                 if (!folio_batch_add(fbatch, folio))
2056                         break;
2057                 continue;
2058 unlock:
2059                 folio_unlock(folio);
2060 put:
2061                 folio_put(folio);
2062         }
2063         rcu_read_unlock();
2064
2065         return folio_batch_count(fbatch);
2066 }
2067
2068 static inline
2069 bool folio_more_pages(struct folio *folio, pgoff_t index, pgoff_t max)
2070 {
2071         if (!folio_test_large(folio) || folio_test_hugetlb(folio))
2072                 return false;
2073         if (index >= max)
2074                 return false;
2075         return index < folio->index + folio_nr_pages(folio) - 1;
2076 }
2077
2078 /**
2079  * find_get_pages_range - gang pagecache lookup
2080  * @mapping:    The address_space to search
2081  * @start:      The starting page index
2082  * @end:        The final page index (inclusive)
2083  * @nr_pages:   The maximum number of pages
2084  * @pages:      Where the resulting pages are placed
2085  *
2086  * find_get_pages_range() will search for and return a group of up to @nr_pages
2087  * pages in the mapping starting at index @start and up to index @end
2088  * (inclusive).  The pages are placed at @pages.  find_get_pages_range() takes
2089  * a reference against the returned pages.
2090  *
2091  * The search returns a group of mapping-contiguous pages with ascending
2092  * indexes.  There may be holes in the indices due to not-present pages.
2093  * We also update @start to index the next page for the traversal.
2094  *
2095  * Return: the number of pages which were found. If this number is
2096  * smaller than @nr_pages, the end of specified range has been
2097  * reached.
2098  */
2099 unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
2100                               pgoff_t end, unsigned int nr_pages,
2101                               struct page **pages)
2102 {
2103         XA_STATE(xas, &mapping->i_pages, *start);
2104         struct folio *folio;
2105         unsigned ret = 0;
2106
2107         if (unlikely(!nr_pages))
2108                 return 0;
2109
2110         rcu_read_lock();
2111         while ((folio = find_get_entry(&xas, end, XA_PRESENT))) {
2112                 /* Skip over shadow, swap and DAX entries */
2113                 if (xa_is_value(folio))
2114                         continue;
2115
2116 again:
2117                 pages[ret] = folio_file_page(folio, xas.xa_index);
2118                 if (++ret == nr_pages) {
2119                         *start = xas.xa_index + 1;
2120                         goto out;
2121                 }
2122                 if (folio_more_pages(folio, xas.xa_index, end)) {
2123                         xas.xa_index++;
2124                         folio_ref_inc(folio);
2125                         goto again;
2126                 }
2127         }
2128
2129         /*
2130          * We come here when there is no page beyond @end. We take care to not
2131          * overflow the index @start as it confuses some of the callers. This
2132          * breaks the iteration when there is a page at index -1 but that is
2133          * already broken anyway.
2134          */
2135         if (end == (pgoff_t)-1)
2136                 *start = (pgoff_t)-1;
2137         else
2138                 *start = end + 1;
2139 out:
2140         rcu_read_unlock();
2141
2142         return ret;
2143 }
2144
2145 /**
2146  * find_get_pages_contig - gang contiguous pagecache lookup
2147  * @mapping:    The address_space to search
2148  * @index:      The starting page index
2149  * @nr_pages:   The maximum number of pages
2150  * @pages:      Where the resulting pages are placed
2151  *
2152  * find_get_pages_contig() works exactly like find_get_pages(), except
2153  * that the returned number of pages are guaranteed to be contiguous.
2154  *
2155  * Return: the number of pages which were found.
2156  */
2157 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
2158                                unsigned int nr_pages, struct page **pages)
2159 {
2160         XA_STATE(xas, &mapping->i_pages, index);
2161         struct folio *folio;
2162         unsigned int ret = 0;
2163
2164         if (unlikely(!nr_pages))
2165                 return 0;
2166
2167         rcu_read_lock();
2168         for (folio = xas_load(&xas); folio; folio = xas_next(&xas)) {
2169                 if (xas_retry(&xas, folio))
2170                         continue;
2171                 /*
2172                  * If the entry has been swapped out, we can stop looking.
2173                  * No current caller is looking for DAX entries.
2174                  */
2175                 if (xa_is_value(folio))
2176                         break;
2177
2178                 if (!folio_try_get_rcu(folio))
2179                         goto retry;
2180
2181                 if (unlikely(folio != xas_reload(&xas)))
2182                         goto put_page;
2183
2184 again:
2185                 pages[ret] = folio_file_page(folio, xas.xa_index);
2186                 if (++ret == nr_pages)
2187                         break;
2188                 if (folio_more_pages(folio, xas.xa_index, ULONG_MAX)) {
2189                         xas.xa_index++;
2190                         folio_ref_inc(folio);
2191                         goto again;
2192                 }
2193                 continue;
2194 put_page:
2195                 folio_put(folio);
2196 retry:
2197                 xas_reset(&xas);
2198         }
2199         rcu_read_unlock();
2200         return ret;
2201 }
2202 EXPORT_SYMBOL(find_get_pages_contig);
2203
2204 /**
2205  * find_get_pages_range_tag - Find and return head pages matching @tag.
2206  * @mapping:    the address_space to search
2207  * @index:      the starting page index
2208  * @end:        The final page index (inclusive)
2209  * @tag:        the tag index
2210  * @nr_pages:   the maximum number of pages
2211  * @pages:      where the resulting pages are placed
2212  *
2213  * Like find_get_pages(), except we only return head pages which are tagged
2214  * with @tag.  @index is updated to the index immediately after the last
2215  * page we return, ready for the next iteration.
2216  *
2217  * Return: the number of pages which were found.
2218  */
2219 unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
2220                         pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
2221                         struct page **pages)
2222 {
2223         XA_STATE(xas, &mapping->i_pages, *index);
2224         struct folio *folio;
2225         unsigned ret = 0;
2226
2227         if (unlikely(!nr_pages))
2228                 return 0;
2229
2230         rcu_read_lock();
2231         while ((folio = find_get_entry(&xas, end, tag))) {
2232                 /*
2233                  * Shadow entries should never be tagged, but this iteration
2234                  * is lockless so there is a window for page reclaim to evict
2235                  * a page we saw tagged.  Skip over it.
2236                  */
2237                 if (xa_is_value(folio))
2238                         continue;
2239
2240                 pages[ret] = &folio->page;
2241                 if (++ret == nr_pages) {
2242                         *index = folio->index + folio_nr_pages(folio);
2243                         goto out;
2244                 }
2245         }
2246
2247         /*
2248          * We come here when we got to @end. We take care to not overflow the
2249          * index @index as it confuses some of the callers. This breaks the
2250          * iteration when there is a page at index -1 but that is already
2251          * broken anyway.
2252          */
2253         if (end == (pgoff_t)-1)
2254                 *index = (pgoff_t)-1;
2255         else
2256                 *index = end + 1;
2257 out:
2258         rcu_read_unlock();
2259
2260         return ret;
2261 }
2262 EXPORT_SYMBOL(find_get_pages_range_tag);
2263
2264 /*
2265  * CD/DVDs are error prone. When a medium error occurs, the driver may fail
2266  * a _large_ part of the i/o request. Imagine the worst scenario:
2267  *
2268  *      ---R__________________________________________B__________
2269  *         ^ reading here                             ^ bad block(assume 4k)
2270  *
2271  * read(R) => miss => readahead(R...B) => media error => frustrating retries
2272  * => failing the whole request => read(R) => read(R+1) =>
2273  * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
2274  * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
2275  * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
2276  *
2277  * It is going insane. Fix it by quickly scaling down the readahead size.
2278  */
2279 static void shrink_readahead_size_eio(struct file_ra_state *ra)
2280 {
2281         ra->ra_pages /= 4;
2282 }
2283
2284 /*
2285  * filemap_get_read_batch - Get a batch of folios for read
2286  *
2287  * Get a batch of folios which represent a contiguous range of bytes in
2288  * the file.  No exceptional entries will be returned.  If @index is in
2289  * the middle of a folio, the entire folio will be returned.  The last
2290  * folio in the batch may have the readahead flag set or the uptodate flag
2291  * clear so that the caller can take the appropriate action.
2292  */
2293 static void filemap_get_read_batch(struct address_space *mapping,
2294                 pgoff_t index, pgoff_t max, struct folio_batch *fbatch)
2295 {
2296         XA_STATE(xas, &mapping->i_pages, index);
2297         struct folio *folio;
2298
2299         rcu_read_lock();
2300         for (folio = xas_load(&xas); folio; folio = xas_next(&xas)) {
2301                 if (xas_retry(&xas, folio))
2302                         continue;
2303                 if (xas.xa_index > max || xa_is_value(folio))
2304                         break;
2305                 if (!folio_try_get_rcu(folio))
2306                         goto retry;
2307
2308                 if (unlikely(folio != xas_reload(&xas)))
2309                         goto put_folio;
2310
2311                 if (!folio_batch_add(fbatch, folio))
2312                         break;
2313                 if (!folio_test_uptodate(folio))
2314                         break;
2315                 if (folio_test_readahead(folio))
2316                         break;
2317                 xas_advance(&xas, folio->index + folio_nr_pages(folio) - 1);
2318                 continue;
2319 put_folio:
2320                 folio_put(folio);
2321 retry:
2322                 xas_reset(&xas);
2323         }
2324         rcu_read_unlock();
2325 }
2326
2327 static int filemap_read_folio(struct file *file, struct address_space *mapping,
2328                 struct folio *folio)
2329 {
2330         int error;
2331
2332         /*
2333          * A previous I/O error may have been due to temporary failures,
2334          * eg. multipath errors.  PG_error will be set again if readpage
2335          * fails.
2336          */
2337         folio_clear_error(folio);
2338         /* Start the actual read. The read will unlock the page. */
2339         error = mapping->a_ops->readpage(file, &folio->page);
2340         if (error)
2341                 return error;
2342
2343         error = folio_wait_locked_killable(folio);
2344         if (error)
2345                 return error;
2346         if (folio_test_uptodate(folio))
2347                 return 0;
2348         shrink_readahead_size_eio(&file->f_ra);
2349         return -EIO;
2350 }
2351
2352 static bool filemap_range_uptodate(struct address_space *mapping,
2353                 loff_t pos, struct iov_iter *iter, struct folio *folio)
2354 {
2355         int count;
2356
2357         if (folio_test_uptodate(folio))
2358                 return true;
2359         /* pipes can't handle partially uptodate pages */
2360         if (iov_iter_is_pipe(iter))
2361                 return false;
2362         if (!mapping->a_ops->is_partially_uptodate)
2363                 return false;
2364         if (mapping->host->i_blkbits >= folio_shift(folio))
2365                 return false;
2366
2367         count = iter->count;
2368         if (folio_pos(folio) > pos) {
2369                 count -= folio_pos(folio) - pos;
2370                 pos = 0;
2371         } else {
2372                 pos -= folio_pos(folio);
2373         }
2374
2375         return mapping->a_ops->is_partially_uptodate(&folio->page, pos, count);
2376 }
2377
2378 static int filemap_update_page(struct kiocb *iocb,
2379                 struct address_space *mapping, struct iov_iter *iter,
2380                 struct folio *folio)
2381 {
2382         int error;
2383
2384         if (iocb->ki_flags & IOCB_NOWAIT) {
2385                 if (!filemap_invalidate_trylock_shared(mapping))
2386                         return -EAGAIN;
2387         } else {
2388                 filemap_invalidate_lock_shared(mapping);
2389         }
2390
2391         if (!folio_trylock(folio)) {
2392                 error = -EAGAIN;
2393                 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO))
2394                         goto unlock_mapping;
2395                 if (!(iocb->ki_flags & IOCB_WAITQ)) {
2396                         filemap_invalidate_unlock_shared(mapping);
2397                         /*
2398                          * This is where we usually end up waiting for a
2399                          * previously submitted readahead to finish.
2400                          */
2401                         folio_put_wait_locked(folio, TASK_KILLABLE);
2402                         return AOP_TRUNCATED_PAGE;
2403                 }
2404                 error = __folio_lock_async(folio, iocb->ki_waitq);
2405                 if (error)
2406                         goto unlock_mapping;
2407         }
2408
2409         error = AOP_TRUNCATED_PAGE;
2410         if (!folio->mapping)
2411                 goto unlock;
2412
2413         error = 0;
2414         if (filemap_range_uptodate(mapping, iocb->ki_pos, iter, folio))
2415                 goto unlock;
2416
2417         error = -EAGAIN;
2418         if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT | IOCB_WAITQ))
2419                 goto unlock;
2420
2421         error = filemap_read_folio(iocb->ki_filp, mapping, folio);
2422         goto unlock_mapping;
2423 unlock:
2424         folio_unlock(folio);
2425 unlock_mapping:
2426         filemap_invalidate_unlock_shared(mapping);
2427         if (error == AOP_TRUNCATED_PAGE)
2428                 folio_put(folio);
2429         return error;
2430 }
2431
2432 static int filemap_create_folio(struct file *file,
2433                 struct address_space *mapping, pgoff_t index,
2434                 struct folio_batch *fbatch)
2435 {
2436         struct folio *folio;
2437         int error;
2438
2439         folio = filemap_alloc_folio(mapping_gfp_mask(mapping), 0);
2440         if (!folio)
2441                 return -ENOMEM;
2442
2443         /*
2444          * Protect against truncate / hole punch. Grabbing invalidate_lock
2445          * here assures we cannot instantiate and bring uptodate new
2446          * pagecache folios after evicting page cache during truncate
2447          * and before actually freeing blocks.  Note that we could
2448          * release invalidate_lock after inserting the folio into
2449          * the page cache as the locked folio would then be enough to
2450          * synchronize with hole punching. But there are code paths
2451          * such as filemap_update_page() filling in partially uptodate
2452          * pages or ->readpages() that need to hold invalidate_lock
2453          * while mapping blocks for IO so let's hold the lock here as
2454          * well to keep locking rules simple.
2455          */
2456         filemap_invalidate_lock_shared(mapping);
2457         error = filemap_add_folio(mapping, folio, index,
2458                         mapping_gfp_constraint(mapping, GFP_KERNEL));
2459         if (error == -EEXIST)
2460                 error = AOP_TRUNCATED_PAGE;
2461         if (error)
2462                 goto error;
2463
2464         error = filemap_read_folio(file, mapping, folio);
2465         if (error)
2466                 goto error;
2467
2468         filemap_invalidate_unlock_shared(mapping);
2469         folio_batch_add(fbatch, folio);
2470         return 0;
2471 error:
2472         filemap_invalidate_unlock_shared(mapping);
2473         folio_put(folio);
2474         return error;
2475 }
2476
2477 static int filemap_readahead(struct kiocb *iocb, struct file *file,
2478                 struct address_space *mapping, struct folio *folio,
2479                 pgoff_t last_index)
2480 {
2481         DEFINE_READAHEAD(ractl, file, &file->f_ra, mapping, folio->index);
2482
2483         if (iocb->ki_flags & IOCB_NOIO)
2484                 return -EAGAIN;
2485         page_cache_async_ra(&ractl, folio, last_index - folio->index);
2486         return 0;
2487 }
2488
2489 static int filemap_get_pages(struct kiocb *iocb, struct iov_iter *iter,
2490                 struct folio_batch *fbatch)
2491 {
2492         struct file *filp = iocb->ki_filp;
2493         struct address_space *mapping = filp->f_mapping;
2494         struct file_ra_state *ra = &filp->f_ra;
2495         pgoff_t index = iocb->ki_pos >> PAGE_SHIFT;
2496         pgoff_t last_index;
2497         struct folio *folio;
2498         int err = 0;
2499
2500         last_index = DIV_ROUND_UP(iocb->ki_pos + iter->count, PAGE_SIZE);
2501 retry:
2502         if (fatal_signal_pending(current))
2503                 return -EINTR;
2504
2505         filemap_get_read_batch(mapping, index, last_index, fbatch);
2506         if (!folio_batch_count(fbatch)) {
2507                 if (iocb->ki_flags & IOCB_NOIO)
2508                         return -EAGAIN;
2509                 page_cache_sync_readahead(mapping, ra, filp, index,
2510                                 last_index - index);
2511                 filemap_get_read_batch(mapping, index, last_index, fbatch);
2512         }
2513         if (!folio_batch_count(fbatch)) {
2514                 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_WAITQ))
2515                         return -EAGAIN;
2516                 err = filemap_create_folio(filp, mapping,
2517                                 iocb->ki_pos >> PAGE_SHIFT, fbatch);
2518                 if (err == AOP_TRUNCATED_PAGE)
2519                         goto retry;
2520                 return err;
2521         }
2522
2523         folio = fbatch->folios[folio_batch_count(fbatch) - 1];
2524         if (folio_test_readahead(folio)) {
2525                 err = filemap_readahead(iocb, filp, mapping, folio, last_index);
2526                 if (err)
2527                         goto err;
2528         }
2529         if (!folio_test_uptodate(folio)) {
2530                 if ((iocb->ki_flags & IOCB_WAITQ) &&
2531                     folio_batch_count(fbatch) > 1)
2532                         iocb->ki_flags |= IOCB_NOWAIT;
2533                 err = filemap_update_page(iocb, mapping, iter, folio);
2534                 if (err)
2535                         goto err;
2536         }
2537
2538         return 0;
2539 err:
2540         if (err < 0)
2541                 folio_put(folio);
2542         if (likely(--fbatch->nr))
2543                 return 0;
2544         if (err == AOP_TRUNCATED_PAGE)
2545                 goto retry;
2546         return err;
2547 }
2548
2549 /**
2550  * filemap_read - Read data from the page cache.
2551  * @iocb: The iocb to read.
2552  * @iter: Destination for the data.
2553  * @already_read: Number of bytes already read by the caller.
2554  *
2555  * Copies data from the page cache.  If the data is not currently present,
2556  * uses the readahead and readpage address_space operations to fetch it.
2557  *
2558  * Return: Total number of bytes copied, including those already read by
2559  * the caller.  If an error happens before any bytes are copied, returns
2560  * a negative error number.
2561  */
2562 ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,
2563                 ssize_t already_read)
2564 {
2565         struct file *filp = iocb->ki_filp;
2566         struct file_ra_state *ra = &filp->f_ra;
2567         struct address_space *mapping = filp->f_mapping;
2568         struct inode *inode = mapping->host;
2569         struct folio_batch fbatch;
2570         int i, error = 0;
2571         bool writably_mapped;
2572         loff_t isize, end_offset;
2573
2574         if (unlikely(iocb->ki_pos >= inode->i_sb->s_maxbytes))
2575                 return 0;
2576         if (unlikely(!iov_iter_count(iter)))
2577                 return 0;
2578
2579         iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2580         folio_batch_init(&fbatch);
2581
2582         do {
2583                 cond_resched();
2584
2585                 /*
2586                  * If we've already successfully copied some data, then we
2587                  * can no longer safely return -EIOCBQUEUED. Hence mark
2588                  * an async read NOWAIT at that point.
2589                  */
2590                 if ((iocb->ki_flags & IOCB_WAITQ) && already_read)
2591                         iocb->ki_flags |= IOCB_NOWAIT;
2592
2593                 if (unlikely(iocb->ki_pos >= i_size_read(inode)))
2594                         break;
2595
2596                 error = filemap_get_pages(iocb, iter, &fbatch);
2597                 if (error < 0)
2598                         break;
2599
2600                 /*
2601                  * i_size must be checked after we know the pages are Uptodate.
2602                  *
2603                  * Checking i_size after the check allows us to calculate
2604                  * the correct value for "nr", which means the zero-filled
2605                  * part of the page is not copied back to userspace (unless
2606                  * another truncate extends the file - this is desired though).
2607                  */
2608                 isize = i_size_read(inode);
2609                 if (unlikely(iocb->ki_pos >= isize))
2610                         goto put_folios;
2611                 end_offset = min_t(loff_t, isize, iocb->ki_pos + iter->count);
2612
2613                 /*
2614                  * Once we start copying data, we don't want to be touching any
2615                  * cachelines that might be contended:
2616                  */
2617                 writably_mapped = mapping_writably_mapped(mapping);
2618
2619                 /*
2620                  * When a sequential read accesses a page several times, only
2621                  * mark it as accessed the first time.
2622                  */
2623                 if (iocb->ki_pos >> PAGE_SHIFT !=
2624                     ra->prev_pos >> PAGE_SHIFT)
2625                         folio_mark_accessed(fbatch.folios[0]);
2626
2627                 for (i = 0; i < folio_batch_count(&fbatch); i++) {
2628                         struct folio *folio = fbatch.folios[i];
2629                         size_t fsize = folio_size(folio);
2630                         size_t offset = iocb->ki_pos & (fsize - 1);
2631                         size_t bytes = min_t(loff_t, end_offset - iocb->ki_pos,
2632                                              fsize - offset);
2633                         size_t copied;
2634
2635                         if (end_offset < folio_pos(folio))
2636                                 break;
2637                         if (i > 0)
2638                                 folio_mark_accessed(folio);
2639                         /*
2640                          * If users can be writing to this folio using arbitrary
2641                          * virtual addresses, take care of potential aliasing
2642                          * before reading the folio on the kernel side.
2643                          */
2644                         if (writably_mapped)
2645                                 flush_dcache_folio(folio);
2646
2647                         copied = copy_folio_to_iter(folio, offset, bytes, iter);
2648
2649                         already_read += copied;
2650                         iocb->ki_pos += copied;
2651                         ra->prev_pos = iocb->ki_pos;
2652
2653                         if (copied < bytes) {
2654                                 error = -EFAULT;
2655                                 break;
2656                         }
2657                 }
2658 put_folios:
2659                 for (i = 0; i < folio_batch_count(&fbatch); i++)
2660                         folio_put(fbatch.folios[i]);
2661                 folio_batch_init(&fbatch);
2662         } while (iov_iter_count(iter) && iocb->ki_pos < isize && !error);
2663
2664         file_accessed(filp);
2665
2666         return already_read ? already_read : error;
2667 }
2668 EXPORT_SYMBOL_GPL(filemap_read);
2669
2670 /**
2671  * generic_file_read_iter - generic filesystem read routine
2672  * @iocb:       kernel I/O control block
2673  * @iter:       destination for the data read
2674  *
2675  * This is the "read_iter()" routine for all filesystems
2676  * that can use the page cache directly.
2677  *
2678  * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
2679  * be returned when no data can be read without waiting for I/O requests
2680  * to complete; it doesn't prevent readahead.
2681  *
2682  * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
2683  * requests shall be made for the read or for readahead.  When no data
2684  * can be read, -EAGAIN shall be returned.  When readahead would be
2685  * triggered, a partial, possibly empty read shall be returned.
2686  *
2687  * Return:
2688  * * number of bytes copied, even for partial reads
2689  * * negative error code (or 0 if IOCB_NOIO) if nothing was read
2690  */
2691 ssize_t
2692 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2693 {
2694         size_t count = iov_iter_count(iter);
2695         ssize_t retval = 0;
2696
2697         if (!count)
2698                 return 0; /* skip atime */
2699
2700         if (iocb->ki_flags & IOCB_DIRECT) {
2701                 struct file *file = iocb->ki_filp;
2702                 struct address_space *mapping = file->f_mapping;
2703                 struct inode *inode = mapping->host;
2704
2705                 if (iocb->ki_flags & IOCB_NOWAIT) {
2706                         if (filemap_range_needs_writeback(mapping, iocb->ki_pos,
2707                                                 iocb->ki_pos + count - 1))
2708                                 return -EAGAIN;
2709                 } else {
2710                         retval = filemap_write_and_wait_range(mapping,
2711                                                 iocb->ki_pos,
2712                                                 iocb->ki_pos + count - 1);
2713                         if (retval < 0)
2714                                 return retval;
2715                 }
2716
2717                 file_accessed(file);
2718
2719                 retval = mapping->a_ops->direct_IO(iocb, iter);
2720                 if (retval >= 0) {
2721                         iocb->ki_pos += retval;
2722                         count -= retval;
2723                 }
2724                 if (retval != -EIOCBQUEUED)
2725                         iov_iter_revert(iter, count - iov_iter_count(iter));
2726
2727                 /*
2728                  * Btrfs can have a short DIO read if we encounter
2729                  * compressed extents, so if there was an error, or if
2730                  * we've already read everything we wanted to, or if
2731                  * there was a short read because we hit EOF, go ahead
2732                  * and return.  Otherwise fallthrough to buffered io for
2733                  * the rest of the read.  Buffered reads will not work for
2734                  * DAX files, so don't bother trying.
2735                  */
2736                 if (retval < 0 || !count || IS_DAX(inode))
2737                         return retval;
2738                 if (iocb->ki_pos >= i_size_read(inode))
2739                         return retval;
2740         }
2741
2742         return filemap_read(iocb, iter, retval);
2743 }
2744 EXPORT_SYMBOL(generic_file_read_iter);
2745
2746 static inline loff_t folio_seek_hole_data(struct xa_state *xas,
2747                 struct address_space *mapping, struct folio *folio,
2748                 loff_t start, loff_t end, bool seek_data)
2749 {
2750         const struct address_space_operations *ops = mapping->a_ops;
2751         size_t offset, bsz = i_blocksize(mapping->host);
2752
2753         if (xa_is_value(folio) || folio_test_uptodate(folio))
2754                 return seek_data ? start : end;
2755         if (!ops->is_partially_uptodate)
2756                 return seek_data ? end : start;
2757
2758         xas_pause(xas);
2759         rcu_read_unlock();
2760         folio_lock(folio);
2761         if (unlikely(folio->mapping != mapping))
2762                 goto unlock;
2763
2764         offset = offset_in_folio(folio, start) & ~(bsz - 1);
2765
2766         do {
2767                 if (ops->is_partially_uptodate(&folio->page, offset, bsz) ==
2768                                                         seek_data)
2769                         break;
2770                 start = (start + bsz) & ~(bsz - 1);
2771                 offset += bsz;
2772         } while (offset < folio_size(folio));
2773 unlock:
2774         folio_unlock(folio);
2775         rcu_read_lock();
2776         return start;
2777 }
2778
2779 static inline size_t seek_folio_size(struct xa_state *xas, struct folio *folio)
2780 {
2781         if (xa_is_value(folio))
2782                 return PAGE_SIZE << xa_get_order(xas->xa, xas->xa_index);
2783         return folio_size(folio);
2784 }
2785
2786 /**
2787  * mapping_seek_hole_data - Seek for SEEK_DATA / SEEK_HOLE in the page cache.
2788  * @mapping: Address space to search.
2789  * @start: First byte to consider.
2790  * @end: Limit of search (exclusive).
2791  * @whence: Either SEEK_HOLE or SEEK_DATA.
2792  *
2793  * If the page cache knows which blocks contain holes and which blocks
2794  * contain data, your filesystem can use this function to implement
2795  * SEEK_HOLE and SEEK_DATA.  This is useful for filesystems which are
2796  * entirely memory-based such as tmpfs, and filesystems which support
2797  * unwritten extents.
2798  *
2799  * Return: The requested offset on success, or -ENXIO if @whence specifies
2800  * SEEK_DATA and there is no data after @start.  There is an implicit hole
2801  * after @end - 1, so SEEK_HOLE returns @end if all the bytes between @start
2802  * and @end contain data.
2803  */
2804 loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start,
2805                 loff_t end, int whence)
2806 {
2807         XA_STATE(xas, &mapping->i_pages, start >> PAGE_SHIFT);
2808         pgoff_t max = (end - 1) >> PAGE_SHIFT;
2809         bool seek_data = (whence == SEEK_DATA);
2810         struct folio *folio;
2811
2812         if (end <= start)
2813                 return -ENXIO;
2814
2815         rcu_read_lock();
2816         while ((folio = find_get_entry(&xas, max, XA_PRESENT))) {
2817                 loff_t pos = (u64)xas.xa_index << PAGE_SHIFT;
2818                 size_t seek_size;
2819
2820                 if (start < pos) {
2821                         if (!seek_data)
2822                                 goto unlock;
2823                         start = pos;
2824                 }
2825
2826                 seek_size = seek_folio_size(&xas, folio);
2827                 pos = round_up((u64)pos + 1, seek_size);
2828                 start = folio_seek_hole_data(&xas, mapping, folio, start, pos,
2829                                 seek_data);
2830                 if (start < pos)
2831                         goto unlock;
2832                 if (start >= end)
2833                         break;
2834                 if (seek_size > PAGE_SIZE)
2835                         xas_set(&xas, pos >> PAGE_SHIFT);
2836                 if (!xa_is_value(folio))
2837                         folio_put(folio);
2838         }
2839         if (seek_data)
2840                 start = -ENXIO;
2841 unlock:
2842         rcu_read_unlock();
2843         if (folio && !xa_is_value(folio))
2844                 folio_put(folio);
2845         if (start > end)
2846                 return end;
2847         return start;
2848 }
2849
2850 #ifdef CONFIG_MMU
2851 #define MMAP_LOTSAMISS  (100)
2852 /*
2853  * lock_folio_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock
2854  * @vmf - the vm_fault for this fault.
2855  * @folio - the folio to lock.
2856  * @fpin - the pointer to the file we may pin (or is already pinned).
2857  *
2858  * This works similar to lock_folio_or_retry in that it can drop the
2859  * mmap_lock.  It differs in that it actually returns the folio locked
2860  * if it returns 1 and 0 if it couldn't lock the folio.  If we did have
2861  * to drop the mmap_lock then fpin will point to the pinned file and
2862  * needs to be fput()'ed at a later point.
2863  */
2864 static int lock_folio_maybe_drop_mmap(struct vm_fault *vmf, struct folio *folio,
2865                                      struct file **fpin)
2866 {
2867         if (folio_trylock(folio))
2868                 return 1;
2869
2870         /*
2871          * NOTE! This will make us return with VM_FAULT_RETRY, but with
2872          * the mmap_lock still held. That's how FAULT_FLAG_RETRY_NOWAIT
2873          * is supposed to work. We have way too many special cases..
2874          */
2875         if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2876                 return 0;
2877
2878         *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2879         if (vmf->flags & FAULT_FLAG_KILLABLE) {
2880                 if (__folio_lock_killable(folio)) {
2881                         /*
2882                          * We didn't have the right flags to drop the mmap_lock,
2883                          * but all fault_handlers only check for fatal signals
2884                          * if we return VM_FAULT_RETRY, so we need to drop the
2885                          * mmap_lock here and return 0 if we don't have a fpin.
2886                          */
2887                         if (*fpin == NULL)
2888                                 mmap_read_unlock(vmf->vma->vm_mm);
2889                         return 0;
2890                 }
2891         } else
2892                 __folio_lock(folio);
2893
2894         return 1;
2895 }
2896
2897 /*
2898  * Synchronous readahead happens when we don't even find a page in the page
2899  * cache at all.  We don't want to perform IO under the mmap sem, so if we have
2900  * to drop the mmap sem we return the file that was pinned in order for us to do
2901  * that.  If we didn't pin a file then we return NULL.  The file that is
2902  * returned needs to be fput()'ed when we're done with it.
2903  */
2904 static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
2905 {
2906         struct file *file = vmf->vma->vm_file;
2907         struct file_ra_state *ra = &file->f_ra;
2908         struct address_space *mapping = file->f_mapping;
2909         DEFINE_READAHEAD(ractl, file, ra, mapping, vmf->pgoff);
2910         struct file *fpin = NULL;
2911         unsigned int mmap_miss;
2912
2913         /* If we don't want any read-ahead, don't bother */
2914         if (vmf->vma->vm_flags & VM_RAND_READ)
2915                 return fpin;
2916         if (!ra->ra_pages)
2917                 return fpin;
2918
2919         if (vmf->vma->vm_flags & VM_SEQ_READ) {
2920                 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2921                 page_cache_sync_ra(&ractl, ra->ra_pages);
2922                 return fpin;
2923         }
2924
2925         /* Avoid banging the cache line if not needed */
2926         mmap_miss = READ_ONCE(ra->mmap_miss);
2927         if (mmap_miss < MMAP_LOTSAMISS * 10)
2928                 WRITE_ONCE(ra->mmap_miss, ++mmap_miss);
2929
2930         /*
2931          * Do we miss much more than hit in this file? If so,
2932          * stop bothering with read-ahead. It will only hurt.
2933          */
2934         if (mmap_miss > MMAP_LOTSAMISS)
2935                 return fpin;
2936
2937         /*
2938          * mmap read-around
2939          */
2940         fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2941         ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2);
2942         ra->size = ra->ra_pages;
2943         ra->async_size = ra->ra_pages / 4;
2944         ractl._index = ra->start;
2945         do_page_cache_ra(&ractl, ra->size, ra->async_size);
2946         return fpin;
2947 }
2948
2949 /*
2950  * Asynchronous readahead happens when we find the page and PG_readahead,
2951  * so we want to possibly extend the readahead further.  We return the file that
2952  * was pinned if we have to drop the mmap_lock in order to do IO.
2953  */
2954 static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2955                                             struct folio *folio)
2956 {
2957         struct file *file = vmf->vma->vm_file;
2958         struct file_ra_state *ra = &file->f_ra;
2959         DEFINE_READAHEAD(ractl, file, ra, file->f_mapping, vmf->pgoff);
2960         struct file *fpin = NULL;
2961         unsigned int mmap_miss;
2962
2963         /* If we don't want any read-ahead, don't bother */
2964         if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
2965                 return fpin;
2966
2967         mmap_miss = READ_ONCE(ra->mmap_miss);
2968         if (mmap_miss)
2969                 WRITE_ONCE(ra->mmap_miss, --mmap_miss);
2970
2971         if (folio_test_readahead(folio)) {
2972                 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2973                 page_cache_async_ra(&ractl, folio, ra->ra_pages);
2974         }
2975         return fpin;
2976 }
2977
2978 /**
2979  * filemap_fault - read in file data for page fault handling
2980  * @vmf:        struct vm_fault containing details of the fault
2981  *
2982  * filemap_fault() is invoked via the vma operations vector for a
2983  * mapped memory region to read in file data during a page fault.
2984  *
2985  * The goto's are kind of ugly, but this streamlines the normal case of having
2986  * it in the page cache, and handles the special cases reasonably without
2987  * having a lot of duplicated code.
2988  *
2989  * vma->vm_mm->mmap_lock must be held on entry.
2990  *
2991  * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
2992  * may be dropped before doing I/O or by lock_folio_maybe_drop_mmap().
2993  *
2994  * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
2995  * has not been released.
2996  *
2997  * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
2998  *
2999  * Return: bitwise-OR of %VM_FAULT_ codes.
3000  */
3001 vm_fault_t filemap_fault(struct vm_fault *vmf)
3002 {
3003         int error;
3004         struct file *file = vmf->vma->vm_file;
3005         struct file *fpin = NULL;
3006         struct address_space *mapping = file->f_mapping;
3007         struct inode *inode = mapping->host;
3008         pgoff_t max_idx, index = vmf->pgoff;
3009         struct folio *folio;
3010         vm_fault_t ret = 0;
3011         bool mapping_locked = false;
3012
3013         max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3014         if (unlikely(index >= max_idx))
3015                 return VM_FAULT_SIGBUS;
3016
3017         /*
3018          * Do we have something in the page cache already?
3019          */
3020         folio = filemap_get_folio(mapping, index);
3021         if (likely(folio)) {
3022                 /*
3023                  * We found the page, so try async readahead before waiting for
3024                  * the lock.
3025                  */
3026                 if (!(vmf->flags & FAULT_FLAG_TRIED))
3027                         fpin = do_async_mmap_readahead(vmf, folio);
3028                 if (unlikely(!folio_test_uptodate(folio))) {
3029                         filemap_invalidate_lock_shared(mapping);
3030                         mapping_locked = true;
3031                 }
3032         } else {
3033                 /* No page in the page cache at all */
3034                 count_vm_event(PGMAJFAULT);
3035                 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
3036                 ret = VM_FAULT_MAJOR;
3037                 fpin = do_sync_mmap_readahead(vmf);
3038 retry_find:
3039                 /*
3040                  * See comment in filemap_create_folio() why we need
3041                  * invalidate_lock
3042                  */
3043                 if (!mapping_locked) {
3044                         filemap_invalidate_lock_shared(mapping);
3045                         mapping_locked = true;
3046                 }
3047                 folio = __filemap_get_folio(mapping, index,
3048                                           FGP_CREAT|FGP_FOR_MMAP,
3049                                           vmf->gfp_mask);
3050                 if (!folio) {
3051                         if (fpin)
3052                                 goto out_retry;
3053                         filemap_invalidate_unlock_shared(mapping);
3054                         return VM_FAULT_OOM;
3055                 }
3056         }
3057
3058         if (!lock_folio_maybe_drop_mmap(vmf, folio, &fpin))
3059                 goto out_retry;
3060
3061         /* Did it get truncated? */
3062         if (unlikely(folio->mapping != mapping)) {
3063                 folio_unlock(folio);
3064                 folio_put(folio);
3065                 goto retry_find;
3066         }
3067         VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
3068
3069         /*
3070          * We have a locked page in the page cache, now we need to check
3071          * that it's up-to-date. If not, it is going to be due to an error.
3072          */
3073         if (unlikely(!folio_test_uptodate(folio))) {
3074                 /*
3075                  * The page was in cache and uptodate and now it is not.
3076                  * Strange but possible since we didn't hold the page lock all
3077                  * the time. Let's drop everything get the invalidate lock and
3078                  * try again.
3079                  */
3080                 if (!mapping_locked) {
3081                         folio_unlock(folio);
3082                         folio_put(folio);
3083                         goto retry_find;
3084                 }
3085                 goto page_not_uptodate;
3086         }
3087
3088         /*
3089          * We've made it this far and we had to drop our mmap_lock, now is the
3090          * time to return to the upper layer and have it re-find the vma and
3091          * redo the fault.
3092          */
3093         if (fpin) {
3094                 folio_unlock(folio);
3095                 goto out_retry;
3096         }
3097         if (mapping_locked)
3098                 filemap_invalidate_unlock_shared(mapping);
3099
3100         /*
3101          * Found the page and have a reference on it.
3102          * We must recheck i_size under page lock.
3103          */
3104         max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3105         if (unlikely(index >= max_idx)) {
3106                 folio_unlock(folio);
3107                 folio_put(folio);
3108                 return VM_FAULT_SIGBUS;
3109         }
3110
3111         vmf->page = folio_file_page(folio, index);
3112         return ret | VM_FAULT_LOCKED;
3113
3114 page_not_uptodate:
3115         /*
3116          * Umm, take care of errors if the page isn't up-to-date.
3117          * Try to re-read it _once_. We do this synchronously,
3118          * because there really aren't any performance issues here
3119          * and we need to check for errors.
3120          */
3121         fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3122         error = filemap_read_folio(file, mapping, folio);
3123         if (fpin)
3124                 goto out_retry;
3125         folio_put(folio);
3126
3127         if (!error || error == AOP_TRUNCATED_PAGE)
3128                 goto retry_find;
3129         filemap_invalidate_unlock_shared(mapping);
3130
3131         return VM_FAULT_SIGBUS;
3132
3133 out_retry:
3134         /*
3135          * We dropped the mmap_lock, we need to return to the fault handler to
3136          * re-find the vma and come back and find our hopefully still populated
3137          * page.
3138          */
3139         if (folio)
3140                 folio_put(folio);
3141         if (mapping_locked)
3142                 filemap_invalidate_unlock_shared(mapping);
3143         if (fpin)
3144                 fput(fpin);
3145         return ret | VM_FAULT_RETRY;
3146 }
3147 EXPORT_SYMBOL(filemap_fault);
3148
3149 static bool filemap_map_pmd(struct vm_fault *vmf, struct page *page)
3150 {
3151         struct mm_struct *mm = vmf->vma->vm_mm;
3152
3153         /* Huge page is mapped? No need to proceed. */
3154         if (pmd_trans_huge(*vmf->pmd)) {
3155                 unlock_page(page);
3156                 put_page(page);
3157                 return true;
3158         }
3159
3160         if (pmd_none(*vmf->pmd) && PageTransHuge(page)) {
3161                 vm_fault_t ret = do_set_pmd(vmf, page);
3162                 if (!ret) {
3163                         /* The page is mapped successfully, reference consumed. */
3164                         unlock_page(page);
3165                         return true;
3166                 }
3167         }
3168
3169         if (pmd_none(*vmf->pmd))
3170                 pmd_install(mm, vmf->pmd, &vmf->prealloc_pte);
3171
3172         /* See comment in handle_pte_fault() */
3173         if (pmd_devmap_trans_unstable(vmf->pmd)) {
3174                 unlock_page(page);
3175                 put_page(page);
3176                 return true;
3177         }
3178
3179         return false;
3180 }
3181
3182 static struct folio *next_uptodate_page(struct folio *folio,
3183                                        struct address_space *mapping,
3184                                        struct xa_state *xas, pgoff_t end_pgoff)
3185 {
3186         unsigned long max_idx;
3187
3188         do {
3189                 if (!folio)
3190                         return NULL;
3191                 if (xas_retry(xas, folio))
3192                         continue;
3193                 if (xa_is_value(folio))
3194                         continue;
3195                 if (folio_test_locked(folio))
3196                         continue;
3197                 if (!folio_try_get_rcu(folio))
3198                         continue;
3199                 /* Has the page moved or been split? */
3200                 if (unlikely(folio != xas_reload(xas)))
3201                         goto skip;
3202                 if (!folio_test_uptodate(folio) || folio_test_readahead(folio))
3203                         goto skip;
3204                 if (!folio_trylock(folio))
3205                         goto skip;
3206                 if (folio->mapping != mapping)
3207                         goto unlock;
3208                 if (!folio_test_uptodate(folio))
3209                         goto unlock;
3210                 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
3211                 if (xas->xa_index >= max_idx)
3212                         goto unlock;
3213                 return folio;
3214 unlock:
3215                 folio_unlock(folio);
3216 skip:
3217                 folio_put(folio);
3218         } while ((folio = xas_next_entry(xas, end_pgoff)) != NULL);
3219
3220         return NULL;
3221 }
3222
3223 static inline struct folio *first_map_page(struct address_space *mapping,
3224                                           struct xa_state *xas,
3225                                           pgoff_t end_pgoff)
3226 {
3227         return next_uptodate_page(xas_find(xas, end_pgoff),
3228                                   mapping, xas, end_pgoff);
3229 }
3230
3231 static inline struct folio *next_map_page(struct address_space *mapping,
3232                                          struct xa_state *xas,
3233                                          pgoff_t end_pgoff)
3234 {
3235         return next_uptodate_page(xas_next_entry(xas, end_pgoff),
3236                                   mapping, xas, end_pgoff);
3237 }
3238
3239 vm_fault_t filemap_map_pages(struct vm_fault *vmf,
3240                              pgoff_t start_pgoff, pgoff_t end_pgoff)
3241 {
3242         struct vm_area_struct *vma = vmf->vma;
3243         struct file *file = vma->vm_file;
3244         struct address_space *mapping = file->f_mapping;
3245         pgoff_t last_pgoff = start_pgoff;
3246         unsigned long addr;
3247         XA_STATE(xas, &mapping->i_pages, start_pgoff);
3248         struct folio *folio;
3249         struct page *page;
3250         unsigned int mmap_miss = READ_ONCE(file->f_ra.mmap_miss);
3251         vm_fault_t ret = 0;
3252
3253         rcu_read_lock();
3254         folio = first_map_page(mapping, &xas, end_pgoff);
3255         if (!folio)
3256                 goto out;
3257
3258         if (filemap_map_pmd(vmf, &folio->page)) {
3259                 ret = VM_FAULT_NOPAGE;
3260                 goto out;
3261         }
3262
3263         addr = vma->vm_start + ((start_pgoff - vma->vm_pgoff) << PAGE_SHIFT);
3264         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl);
3265         do {
3266 again:
3267                 page = folio_file_page(folio, xas.xa_index);
3268                 if (PageHWPoison(page))
3269                         goto unlock;
3270
3271                 if (mmap_miss > 0)
3272                         mmap_miss--;
3273
3274                 addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
3275                 vmf->pte += xas.xa_index - last_pgoff;
3276                 last_pgoff = xas.xa_index;
3277
3278                 if (!pte_none(*vmf->pte))
3279                         goto unlock;
3280
3281                 /* We're about to handle the fault */
3282                 if (vmf->address == addr)
3283                         ret = VM_FAULT_NOPAGE;
3284
3285                 do_set_pte(vmf, page, addr);
3286                 /* no need to invalidate: a not-present page won't be cached */
3287                 update_mmu_cache(vma, addr, vmf->pte);
3288                 if (folio_more_pages(folio, xas.xa_index, end_pgoff)) {
3289                         xas.xa_index++;
3290                         folio_ref_inc(folio);
3291                         goto again;
3292                 }
3293                 folio_unlock(folio);
3294                 continue;
3295 unlock:
3296                 if (folio_more_pages(folio, xas.xa_index, end_pgoff)) {
3297                         xas.xa_index++;
3298                         goto again;
3299                 }
3300                 folio_unlock(folio);
3301                 folio_put(folio);
3302         } while ((folio = next_map_page(mapping, &xas, end_pgoff)) != NULL);
3303         pte_unmap_unlock(vmf->pte, vmf->ptl);
3304 out:
3305         rcu_read_unlock();
3306         WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss);
3307         return ret;
3308 }
3309 EXPORT_SYMBOL(filemap_map_pages);
3310
3311 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
3312 {
3313         struct address_space *mapping = vmf->vma->vm_file->f_mapping;
3314         struct folio *folio = page_folio(vmf->page);
3315         vm_fault_t ret = VM_FAULT_LOCKED;
3316
3317         sb_start_pagefault(mapping->host->i_sb);
3318         file_update_time(vmf->vma->vm_file);
3319         folio_lock(folio);
3320         if (folio->mapping != mapping) {
3321                 folio_unlock(folio);
3322                 ret = VM_FAULT_NOPAGE;
3323                 goto out;
3324         }
3325         /*
3326          * We mark the folio dirty already here so that when freeze is in
3327          * progress, we are guaranteed that writeback during freezing will
3328          * see the dirty folio and writeprotect it again.
3329          */
3330         folio_mark_dirty(folio);
3331         folio_wait_stable(folio);
3332 out:
3333         sb_end_pagefault(mapping->host->i_sb);
3334         return ret;
3335 }
3336
3337 const struct vm_operations_struct generic_file_vm_ops = {
3338         .fault          = filemap_fault,
3339         .map_pages      = filemap_map_pages,
3340         .page_mkwrite   = filemap_page_mkwrite,
3341 };
3342
3343 /* This is used for a general mmap of a disk file */
3344
3345 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3346 {
3347         struct address_space *mapping = file->f_mapping;
3348
3349         if (!mapping->a_ops->readpage)
3350                 return -ENOEXEC;
3351         file_accessed(file);
3352         vma->vm_ops = &generic_file_vm_ops;
3353         return 0;
3354 }
3355
3356 /*
3357  * This is for filesystems which do not implement ->writepage.
3358  */
3359 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3360 {
3361         if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
3362                 return -EINVAL;
3363         return generic_file_mmap(file, vma);
3364 }
3365 #else
3366 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
3367 {
3368         return VM_FAULT_SIGBUS;
3369 }
3370 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3371 {
3372         return -ENOSYS;
3373 }
3374 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3375 {
3376         return -ENOSYS;
3377 }
3378 #endif /* CONFIG_MMU */
3379
3380 EXPORT_SYMBOL(filemap_page_mkwrite);
3381 EXPORT_SYMBOL(generic_file_mmap);
3382 EXPORT_SYMBOL(generic_file_readonly_mmap);
3383
3384 static struct folio *do_read_cache_folio(struct address_space *mapping,
3385                 pgoff_t index, filler_t filler, void *data, gfp_t gfp)
3386 {
3387         struct folio *folio;
3388         int err;
3389 repeat:
3390         folio = filemap_get_folio(mapping, index);
3391         if (!folio) {
3392                 folio = filemap_alloc_folio(gfp, 0);
3393                 if (!folio)
3394                         return ERR_PTR(-ENOMEM);
3395                 err = filemap_add_folio(mapping, folio, index, gfp);
3396                 if (unlikely(err)) {
3397                         folio_put(folio);
3398                         if (err == -EEXIST)
3399                                 goto repeat;
3400                         /* Presumably ENOMEM for xarray node */
3401                         return ERR_PTR(err);
3402                 }
3403
3404 filler:
3405                 if (filler)
3406                         err = filler(data, &folio->page);
3407                 else
3408                         err = mapping->a_ops->readpage(data, &folio->page);
3409
3410                 if (err < 0) {
3411                         folio_put(folio);
3412                         return ERR_PTR(err);
3413                 }
3414
3415                 folio_wait_locked(folio);
3416                 if (!folio_test_uptodate(folio)) {
3417                         folio_put(folio);
3418                         return ERR_PTR(-EIO);
3419                 }
3420
3421                 goto out;
3422         }
3423         if (folio_test_uptodate(folio))
3424                 goto out;
3425
3426         if (!folio_trylock(folio)) {
3427                 folio_put_wait_locked(folio, TASK_UNINTERRUPTIBLE);
3428                 goto repeat;
3429         }
3430
3431         /* Folio was truncated from mapping */
3432         if (!folio->mapping) {
3433                 folio_unlock(folio);
3434                 folio_put(folio);
3435                 goto repeat;
3436         }
3437
3438         /* Someone else locked and filled the page in a very small window */
3439         if (folio_test_uptodate(folio)) {
3440                 folio_unlock(folio);
3441                 goto out;
3442         }
3443
3444         /*
3445          * A previous I/O error may have been due to temporary
3446          * failures.
3447          * Clear page error before actual read, PG_error will be
3448          * set again if read page fails.
3449          */
3450         folio_clear_error(folio);
3451         goto filler;
3452
3453 out:
3454         folio_mark_accessed(folio);
3455         return folio;
3456 }
3457
3458 /**
3459  * read_cache_folio - read into page cache, fill it if needed
3460  * @mapping:    the page's address_space
3461  * @index:      the page index
3462  * @filler:     function to perform the read
3463  * @data:       first arg to filler(data, page) function, often left as NULL
3464  *
3465  * Read into the page cache. If a page already exists, and PageUptodate() is
3466  * not set, try to fill the page and wait for it to become unlocked.
3467  *
3468  * If the page does not get brought uptodate, return -EIO.
3469  *
3470  * The function expects mapping->invalidate_lock to be already held.
3471  *
3472  * Return: up to date page on success, ERR_PTR() on failure.
3473  */
3474 struct folio *read_cache_folio(struct address_space *mapping, pgoff_t index,
3475                 filler_t filler, void *data)
3476 {
3477         return do_read_cache_folio(mapping, index, filler, data,
3478                         mapping_gfp_mask(mapping));
3479 }
3480 EXPORT_SYMBOL(read_cache_folio);
3481
3482 static struct page *do_read_cache_page(struct address_space *mapping,
3483                 pgoff_t index, filler_t *filler, void *data, gfp_t gfp)
3484 {
3485         struct folio *folio;
3486
3487         folio = do_read_cache_folio(mapping, index, filler, data, gfp);
3488         if (IS_ERR(folio))
3489                 return &folio->page;
3490         return folio_file_page(folio, index);
3491 }
3492
3493 struct page *read_cache_page(struct address_space *mapping,
3494                                 pgoff_t index, filler_t *filler, void *data)
3495 {
3496         return do_read_cache_page(mapping, index, filler, data,
3497                         mapping_gfp_mask(mapping));
3498 }
3499 EXPORT_SYMBOL(read_cache_page);
3500
3501 /**
3502  * read_cache_page_gfp - read into page cache, using specified page allocation flags.
3503  * @mapping:    the page's address_space
3504  * @index:      the page index
3505  * @gfp:        the page allocator flags to use if allocating
3506  *
3507  * This is the same as "read_mapping_page(mapping, index, NULL)", but with
3508  * any new page allocations done using the specified allocation flags.
3509  *
3510  * If the page does not get brought uptodate, return -EIO.
3511  *
3512  * The function expects mapping->invalidate_lock to be already held.
3513  *
3514  * Return: up to date page on success, ERR_PTR() on failure.
3515  */
3516 struct page *read_cache_page_gfp(struct address_space *mapping,
3517                                 pgoff_t index,
3518                                 gfp_t gfp)
3519 {
3520         return do_read_cache_page(mapping, index, NULL, NULL, gfp);
3521 }
3522 EXPORT_SYMBOL(read_cache_page_gfp);
3523
3524 int pagecache_write_begin(struct file *file, struct address_space *mapping,
3525                                 loff_t pos, unsigned len, unsigned flags,
3526                                 struct page **pagep, void **fsdata)
3527 {
3528         const struct address_space_operations *aops = mapping->a_ops;
3529
3530         return aops->write_begin(file, mapping, pos, len, flags,
3531                                                         pagep, fsdata);
3532 }
3533 EXPORT_SYMBOL(pagecache_write_begin);
3534
3535 int pagecache_write_end(struct file *file, struct address_space *mapping,
3536                                 loff_t pos, unsigned len, unsigned copied,
3537                                 struct page *page, void *fsdata)
3538 {
3539         const struct address_space_operations *aops = mapping->a_ops;
3540
3541         return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
3542 }
3543 EXPORT_SYMBOL(pagecache_write_end);
3544
3545 /*
3546  * Warn about a page cache invalidation failure during a direct I/O write.
3547  */
3548 void dio_warn_stale_pagecache(struct file *filp)
3549 {
3550         static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
3551         char pathname[128];
3552         char *path;
3553
3554         errseq_set(&filp->f_mapping->wb_err, -EIO);
3555         if (__ratelimit(&_rs)) {
3556                 path = file_path(filp, pathname, sizeof(pathname));
3557                 if (IS_ERR(path))
3558                         path = "(unknown)";
3559                 pr_crit("Page cache invalidation failure on direct I/O.  Possible data corruption due to collision with buffered I/O!\n");
3560                 pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
3561                         current->comm);
3562         }
3563 }
3564
3565 ssize_t
3566 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
3567 {
3568         struct file     *file = iocb->ki_filp;
3569         struct address_space *mapping = file->f_mapping;
3570         struct inode    *inode = mapping->host;
3571         loff_t          pos = iocb->ki_pos;
3572         ssize_t         written;
3573         size_t          write_len;
3574         pgoff_t         end;
3575
3576         write_len = iov_iter_count(from);
3577         end = (pos + write_len - 1) >> PAGE_SHIFT;
3578
3579         if (iocb->ki_flags & IOCB_NOWAIT) {
3580                 /* If there are pages to writeback, return */
3581                 if (filemap_range_has_page(file->f_mapping, pos,
3582                                            pos + write_len - 1))
3583                         return -EAGAIN;
3584         } else {
3585                 written = filemap_write_and_wait_range(mapping, pos,
3586                                                         pos + write_len - 1);
3587                 if (written)
3588                         goto out;
3589         }
3590
3591         /*
3592          * After a write we want buffered reads to be sure to go to disk to get
3593          * the new data.  We invalidate clean cached page from the region we're
3594          * about to write.  We do this *before* the write so that we can return
3595          * without clobbering -EIOCBQUEUED from ->direct_IO().
3596          */
3597         written = invalidate_inode_pages2_range(mapping,
3598                                         pos >> PAGE_SHIFT, end);
3599         /*
3600          * If a page can not be invalidated, return 0 to fall back
3601          * to buffered write.
3602          */
3603         if (written) {
3604                 if (written == -EBUSY)
3605                         return 0;
3606                 goto out;
3607         }
3608
3609         written = mapping->a_ops->direct_IO(iocb, from);
3610
3611         /*
3612          * Finally, try again to invalidate clean pages which might have been
3613          * cached by non-direct readahead, or faulted in by get_user_pages()
3614          * if the source of the write was an mmap'ed region of the file
3615          * we're writing.  Either one is a pretty crazy thing to do,
3616          * so we don't support it 100%.  If this invalidation
3617          * fails, tough, the write still worked...
3618          *
3619          * Most of the time we do not need this since dio_complete() will do
3620          * the invalidation for us. However there are some file systems that
3621          * do not end up with dio_complete() being called, so let's not break
3622          * them by removing it completely.
3623          *
3624          * Noticeable example is a blkdev_direct_IO().
3625          *
3626          * Skip invalidation for async writes or if mapping has no pages.
3627          */
3628         if (written > 0 && mapping->nrpages &&
3629             invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT, end))
3630                 dio_warn_stale_pagecache(file);
3631
3632         if (written > 0) {
3633                 pos += written;
3634                 write_len -= written;
3635                 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3636                         i_size_write(inode, pos);
3637                         mark_inode_dirty(inode);
3638                 }
3639                 iocb->ki_pos = pos;
3640         }
3641         if (written != -EIOCBQUEUED)
3642                 iov_iter_revert(from, write_len - iov_iter_count(from));
3643 out:
3644         return written;
3645 }
3646 EXPORT_SYMBOL(generic_file_direct_write);
3647
3648 ssize_t generic_perform_write(struct file *file,
3649                                 struct iov_iter *i, loff_t pos)
3650 {
3651         struct address_space *mapping = file->f_mapping;
3652         const struct address_space_operations *a_ops = mapping->a_ops;
3653         long status = 0;
3654         ssize_t written = 0;
3655         unsigned int flags = 0;
3656
3657         do {
3658                 struct page *page;
3659                 unsigned long offset;   /* Offset into pagecache page */
3660                 unsigned long bytes;    /* Bytes to write to page */
3661                 size_t copied;          /* Bytes copied from user */
3662                 void *fsdata;
3663
3664                 offset = (pos & (PAGE_SIZE - 1));
3665                 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3666                                                 iov_iter_count(i));
3667
3668 again:
3669                 /*
3670                  * Bring in the user page that we will copy from _first_.
3671                  * Otherwise there's a nasty deadlock on copying from the
3672                  * same page as we're writing to, without it being marked
3673                  * up-to-date.
3674                  */
3675                 if (unlikely(fault_in_iov_iter_readable(i, bytes))) {
3676                         status = -EFAULT;
3677                         break;
3678                 }
3679
3680                 if (fatal_signal_pending(current)) {
3681                         status = -EINTR;
3682                         break;
3683                 }
3684
3685                 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
3686                                                 &page, &fsdata);
3687                 if (unlikely(status < 0))
3688                         break;
3689
3690                 if (mapping_writably_mapped(mapping))
3691                         flush_dcache_page(page);
3692
3693                 copied = copy_page_from_iter_atomic(page, offset, bytes, i);
3694                 flush_dcache_page(page);
3695
3696                 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3697                                                 page, fsdata);
3698                 if (unlikely(status != copied)) {
3699                         iov_iter_revert(i, copied - max(status, 0L));
3700                         if (unlikely(status < 0))
3701                                 break;
3702                 }
3703                 cond_resched();
3704
3705                 if (unlikely(status == 0)) {
3706                         /*
3707                          * A short copy made ->write_end() reject the
3708                          * thing entirely.  Might be memory poisoning
3709                          * halfway through, might be a race with munmap,
3710                          * might be severe memory pressure.
3711                          */
3712                         if (copied)
3713                                 bytes = copied;
3714                         goto again;
3715                 }
3716                 pos += status;
3717                 written += status;
3718
3719                 balance_dirty_pages_ratelimited(mapping);
3720         } while (iov_iter_count(i));
3721
3722         return written ? written : status;
3723 }
3724 EXPORT_SYMBOL(generic_perform_write);
3725
3726 /**
3727  * __generic_file_write_iter - write data to a file
3728  * @iocb:       IO state structure (file, offset, etc.)
3729  * @from:       iov_iter with data to write
3730  *
3731  * This function does all the work needed for actually writing data to a
3732  * file. It does all basic checks, removes SUID from the file, updates
3733  * modification times and calls proper subroutines depending on whether we
3734  * do direct IO or a standard buffered write.
3735  *
3736  * It expects i_rwsem to be grabbed unless we work on a block device or similar
3737  * object which does not need locking at all.
3738  *
3739  * This function does *not* take care of syncing data in case of O_SYNC write.
3740  * A caller has to handle it. This is mainly due to the fact that we want to
3741  * avoid syncing under i_rwsem.
3742  *
3743  * Return:
3744  * * number of bytes written, even for truncated writes
3745  * * negative error code if no data has been written at all
3746  */
3747 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3748 {
3749         struct file *file = iocb->ki_filp;
3750         struct address_space *mapping = file->f_mapping;
3751         struct inode    *inode = mapping->host;
3752         ssize_t         written = 0;
3753         ssize_t         err;
3754         ssize_t         status;
3755
3756         /* We can write back this queue in page reclaim */
3757         current->backing_dev_info = inode_to_bdi(inode);
3758         err = file_remove_privs(file);
3759         if (err)
3760                 goto out;
3761
3762         err = file_update_time(file);
3763         if (err)
3764                 goto out;
3765
3766         if (iocb->ki_flags & IOCB_DIRECT) {
3767                 loff_t pos, endbyte;
3768
3769                 written = generic_file_direct_write(iocb, from);
3770                 /*
3771                  * If the write stopped short of completing, fall back to
3772                  * buffered writes.  Some filesystems do this for writes to
3773                  * holes, for example.  For DAX files, a buffered write will
3774                  * not succeed (even if it did, DAX does not handle dirty
3775                  * page-cache pages correctly).
3776                  */
3777                 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
3778                         goto out;
3779
3780                 status = generic_perform_write(file, from, pos = iocb->ki_pos);
3781                 /*
3782                  * If generic_perform_write() returned a synchronous error
3783                  * then we want to return the number of bytes which were
3784                  * direct-written, or the error code if that was zero.  Note
3785                  * that this differs from normal direct-io semantics, which
3786                  * will return -EFOO even if some bytes were written.
3787                  */
3788                 if (unlikely(status < 0)) {
3789                         err = status;
3790                         goto out;
3791                 }
3792                 /*
3793                  * We need to ensure that the page cache pages are written to
3794                  * disk and invalidated to preserve the expected O_DIRECT
3795                  * semantics.
3796                  */
3797                 endbyte = pos + status - 1;
3798                 err = filemap_write_and_wait_range(mapping, pos, endbyte);
3799                 if (err == 0) {
3800                         iocb->ki_pos = endbyte + 1;
3801                         written += status;
3802                         invalidate_mapping_pages(mapping,
3803                                                  pos >> PAGE_SHIFT,
3804                                                  endbyte >> PAGE_SHIFT);
3805                 } else {
3806                         /*
3807                          * We don't know how much we wrote, so just return
3808                          * the number of bytes which were direct-written
3809                          */
3810                 }
3811         } else {
3812                 written = generic_perform_write(file, from, iocb->ki_pos);
3813                 if (likely(written > 0))
3814                         iocb->ki_pos += written;
3815         }
3816 out:
3817         current->backing_dev_info = NULL;
3818         return written ? written : err;
3819 }
3820 EXPORT_SYMBOL(__generic_file_write_iter);
3821
3822 /**
3823  * generic_file_write_iter - write data to a file
3824  * @iocb:       IO state structure
3825  * @from:       iov_iter with data to write
3826  *
3827  * This is a wrapper around __generic_file_write_iter() to be used by most
3828  * filesystems. It takes care of syncing the file in case of O_SYNC file
3829  * and acquires i_rwsem as needed.
3830  * Return:
3831  * * negative error code if no data has been written at all of
3832  *   vfs_fsync_range() failed for a synchronous write
3833  * * number of bytes written, even for truncated writes
3834  */
3835 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3836 {
3837         struct file *file = iocb->ki_filp;
3838         struct inode *inode = file->f_mapping->host;
3839         ssize_t ret;
3840
3841         inode_lock(inode);
3842         ret = generic_write_checks(iocb, from);
3843         if (ret > 0)
3844                 ret = __generic_file_write_iter(iocb, from);
3845         inode_unlock(inode);
3846
3847         if (ret > 0)
3848                 ret = generic_write_sync(iocb, ret);
3849         return ret;
3850 }
3851 EXPORT_SYMBOL(generic_file_write_iter);
3852
3853 /**
3854  * filemap_release_folio() - Release fs-specific metadata on a folio.
3855  * @folio: The folio which the kernel is trying to free.
3856  * @gfp: Memory allocation flags (and I/O mode).
3857  *
3858  * The address_space is trying to release any data attached to a folio
3859  * (presumably at folio->private).
3860  *
3861  * This will also be called if the private_2 flag is set on a page,
3862  * indicating that the folio has other metadata associated with it.
3863  *
3864  * The @gfp argument specifies whether I/O may be performed to release
3865  * this page (__GFP_IO), and whether the call may block
3866  * (__GFP_RECLAIM & __GFP_FS).
3867  *
3868  * Return: %true if the release was successful, otherwise %false.
3869  */
3870 bool filemap_release_folio(struct folio *folio, gfp_t gfp)
3871 {
3872         struct address_space * const mapping = folio->mapping;
3873
3874         BUG_ON(!folio_test_locked(folio));
3875         if (folio_test_writeback(folio))
3876                 return false;
3877
3878         if (mapping && mapping->a_ops->releasepage)
3879                 return mapping->a_ops->releasepage(&folio->page, gfp);
3880         return try_to_free_buffers(&folio->page);
3881 }
3882 EXPORT_SYMBOL(filemap_release_folio);
This page took 0.254201 seconds and 4 git commands to generate.