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