1 // SPDX-License-Identifier: GPL-2.0-only
5 * Copyright (C) 1994-1999 Linus Torvalds
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)
13 #include <linux/export.h>
14 #include <linux/compiler.h>
15 #include <linux/dax.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>
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>
50 #define CREATE_TRACE_POINTS
51 #include <trace/events/filemap.h>
54 * FIXME: remove all knowledge of the buffer layer from the core VM
56 #include <linux/buffer_head.h> /* for try_to_free_buffers */
61 * Shared mappings implemented 30.11.1994. It's not fully working yet,
64 * Shared mappings now work. 15.8.1995 Bruno.
66 * finished 'unifying' the page and buffer cache and SMP-threaded the
67 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
69 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
75 * ->i_mmap_rwsem (truncate_pagecache)
76 * ->private_lock (__free_pte->__set_page_dirty_buffers)
77 * ->swap_lock (exclusive_swap_page, others)
81 * ->invalidate_lock (acquired by fs in truncate path)
82 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
86 * ->page_table_lock or pte_lock (various, mainly in memory.c)
87 * ->i_pages lock (arch-dependent flush_dcache_mmap_lock)
90 * ->invalidate_lock (filemap_fault)
91 * ->lock_page (filemap_fault, access_process_vm)
93 * ->i_rwsem (generic_perform_write)
94 * ->mmap_lock (fault_in_readable->do_page_fault)
97 * sb_lock (fs/fs-writeback.c)
98 * ->i_pages lock (__sync_single_inode)
101 * ->anon_vma.lock (vma_adjust)
104 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
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)
122 * ->tasklist_lock (memory_failure, collect_procs_ao)
125 static void page_cache_delete(struct address_space *mapping,
126 struct folio *folio, void *shadow)
128 XA_STATE(xas, &mapping->i_pages, folio->index);
131 mapping_set_update(&xas, mapping);
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);
139 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
141 xas_store(&xas, shadow);
142 xas_init_marks(&xas);
144 folio->mapping = NULL;
145 /* Leave page->index set: truncation lookup relies upon it */
146 mapping->nrpages -= nr;
149 static void filemap_unaccount_folio(struct address_space *mapping,
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
159 if (folio_test_uptodate(folio) && folio_test_mappedtodisk(folio))
160 cleancache_put_page(&folio->page);
162 cleancache_invalidate_page(mapping, &folio->page);
164 VM_BUG_ON_FOLIO(folio_mapped(folio), folio);
165 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(folio_mapped(folio))) {
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");
172 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
174 mapcount = page_mapcount(&folio->page);
175 if (mapping_exiting(mapping) &&
176 folio_ref_count(folio) >= mapcount + 2) {
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.
183 page_mapcount_reset(&folio->page);
184 folio_ref_sub(folio, mapcount);
188 /* hugetlb folios do not participate in page cache accounting. */
189 if (folio_test_hugetlb(folio))
192 nr = folio_nr_pages(folio);
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);
205 * At this point folio must be either written or cleaned by
206 * truncate. Dirty folio here signals a bug and loss of
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
214 if (WARN_ON_ONCE(folio_test_dirty(folio)))
215 folio_account_cleaned(folio, mapping,
216 inode_to_wb(mapping->host));
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.
224 void __filemap_remove_folio(struct folio *folio, void *shadow)
226 struct address_space *mapping = folio->mapping;
228 trace_mm_filemap_delete_from_page_cache(folio);
229 filemap_unaccount_folio(mapping, folio);
230 page_cache_delete(mapping, folio, shadow);
233 void filemap_free_folio(struct address_space *mapping, struct folio *folio)
235 void (*freepage)(struct page *);
237 freepage = mapping->a_ops->freepage;
239 freepage(&folio->page);
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);
250 * filemap_remove_folio - Remove folio from page cache.
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.
257 void filemap_remove_folio(struct folio *folio)
259 struct address_space *mapping = folio->mapping;
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);
270 filemap_free_folio(mapping, folio);
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
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
284 * The function expects the i_pages lock to be held.
286 static void page_cache_delete_batch(struct address_space *mapping,
287 struct folio_batch *fbatch)
289 XA_STATE(xas, &mapping->i_pages, fbatch->folios[0]->index);
290 long total_pages = 0;
294 mapping_set_update(&xas, mapping);
295 xas_for_each(&xas, folio, ULONG_MAX) {
296 if (i >= folio_batch_count(fbatch))
299 /* A swap/dax/shadow entry got inserted? Skip it. */
300 if (xa_is_value(folio))
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.
309 if (folio != fbatch->folios[i]) {
310 VM_BUG_ON_FOLIO(folio->index >
311 fbatch->folios[i]->index, folio);
315 WARN_ON_ONCE(!folio_test_locked(folio));
317 folio->mapping = NULL;
318 /* Leave folio->index set: truncation lookup relies on it */
321 xas_store(&xas, NULL);
322 total_pages += folio_nr_pages(folio);
324 mapping->nrpages -= total_pages;
327 void delete_from_page_cache_batch(struct address_space *mapping,
328 struct folio_batch *fbatch)
332 if (!folio_batch_count(fbatch))
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];
340 trace_mm_filemap_delete_from_page_cache(folio);
341 filemap_unaccount_folio(mapping, folio);
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);
349 for (i = 0; i < folio_batch_count(fbatch); i++)
350 filemap_free_folio(mapping, fbatch->folios[i]);
353 int filemap_check_errors(struct address_space *mapping)
356 /* Check for outstanding write errors */
357 if (test_bit(AS_ENOSPC, &mapping->flags) &&
358 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
360 if (test_bit(AS_EIO, &mapping->flags) &&
361 test_and_clear_bit(AS_EIO, &mapping->flags))
365 EXPORT_SYMBOL(filemap_check_errors);
367 static int filemap_check_and_keep_errors(struct address_space *mapping)
369 /* Check for outstanding write errors */
370 if (test_bit(AS_EIO, &mapping->flags))
372 if (test_bit(AS_ENOSPC, &mapping->flags))
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
382 * Call writepages on the mapping using the provided wbc to control the
385 * Return: %0 on success, negative error code otherwise.
387 int filemap_fdatawrite_wbc(struct address_space *mapping,
388 struct writeback_control *wbc)
392 if (!mapping_can_writeback(mapping) ||
393 !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
396 wbc_attach_fdatawrite_inode(wbc, mapping->host);
397 ret = do_writepages(mapping, wbc);
398 wbc_detach_inode(wbc);
401 EXPORT_SYMBOL(filemap_fdatawrite_wbc);
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
410 * Start writeback against all of a mapping's dirty pages that lie
411 * within the byte offsets <start, end> inclusive.
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.
418 * Return: %0 on success, negative error code otherwise.
420 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
421 loff_t end, int sync_mode)
423 struct writeback_control wbc = {
424 .sync_mode = sync_mode,
425 .nr_to_write = LONG_MAX,
426 .range_start = start,
430 return filemap_fdatawrite_wbc(mapping, &wbc);
433 static inline int __filemap_fdatawrite(struct address_space *mapping,
436 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
439 int filemap_fdatawrite(struct address_space *mapping)
441 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
443 EXPORT_SYMBOL(filemap_fdatawrite);
445 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
448 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
450 EXPORT_SYMBOL(filemap_fdatawrite_range);
453 * filemap_flush - mostly a non-blocking flush
454 * @mapping: target address_space
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.
459 * Return: %0 on success, negative error code otherwise.
461 int filemap_flush(struct address_space *mapping)
463 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
465 EXPORT_SYMBOL(filemap_flush);
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)
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.
476 * Return: %true if at least one page exists in the specified range,
479 bool filemap_range_has_page(struct address_space *mapping,
480 loff_t start_byte, loff_t end_byte)
483 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
484 pgoff_t max = end_byte >> PAGE_SHIFT;
486 if (end_byte < start_byte)
491 page = xas_find(&xas, max);
492 if (xas_retry(&xas, page))
494 /* Shadow entries don't count */
495 if (xa_is_value(page))
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.
508 EXPORT_SYMBOL(filemap_range_has_page);
510 static void __filemap_fdatawait_range(struct address_space *mapping,
511 loff_t start_byte, loff_t end_byte)
513 pgoff_t index = start_byte >> PAGE_SHIFT;
514 pgoff_t end = end_byte >> PAGE_SHIFT;
518 if (end_byte < start_byte)
522 while (index <= end) {
525 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
526 end, PAGECACHE_TAG_WRITEBACK);
530 for (i = 0; i < nr_pages; i++) {
531 struct page *page = pvec.pages[i];
533 wait_on_page_writeback(page);
534 ClearPageError(page);
536 pagevec_release(&pvec);
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)
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.
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.
555 * Return: error status of the address space.
557 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
560 __filemap_fdatawait_range(mapping, start_byte, end_byte);
561 return filemap_check_errors(mapping);
563 EXPORT_SYMBOL(filemap_fdatawait_range);
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)
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.
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),
579 int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
580 loff_t start_byte, loff_t end_byte)
582 __filemap_fdatawait_range(mapping, start_byte, end_byte);
583 return filemap_check_and_keep_errors(mapping);
585 EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
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)
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.
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.
601 * Return: error status of the address space vs. the file->f_wb_err cursor.
603 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
605 struct address_space *mapping = file->f_mapping;
607 __filemap_fdatawait_range(mapping, start_byte, end_byte);
608 return file_check_and_advance_wb_err(file);
610 EXPORT_SYMBOL(file_fdatawait_range);
613 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
614 * @mapping: address space structure to wait for
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.
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),
624 * Return: error status of the address space.
626 int filemap_fdatawait_keep_errors(struct address_space *mapping)
628 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
629 return filemap_check_and_keep_errors(mapping);
631 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
633 /* Returns true if writeback might be needed or already in progress. */
634 static bool mapping_needs_writeback(struct address_space *mapping)
636 return mapping->nrpages;
639 bool filemap_range_has_writeback(struct address_space *mapping,
640 loff_t start_byte, loff_t end_byte)
642 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
643 pgoff_t max = end_byte >> PAGE_SHIFT;
646 if (end_byte < start_byte)
650 xas_for_each(&xas, page, max) {
651 if (xas_retry(&xas, page))
653 if (xa_is_value(page))
655 if (PageDirty(page) || PageLocked(page) || PageWriteback(page))
661 EXPORT_SYMBOL_GPL(filemap_range_has_writeback);
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)
669 * Write out and wait upon file offsets lstart->lend, inclusive.
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).
674 * Return: error status of the address space.
676 int filemap_write_and_wait_range(struct address_space *mapping,
677 loff_t lstart, loff_t lend)
681 if (mapping_needs_writeback(mapping)) {
682 err = __filemap_fdatawrite_range(mapping, lstart, lend,
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.
691 int err2 = filemap_fdatawait_range(mapping,
696 /* Clear any previously stored errors */
697 filemap_check_errors(mapping);
700 err = filemap_check_errors(mapping);
704 EXPORT_SYMBOL(filemap_write_and_wait_range);
706 void __filemap_set_wb_err(struct address_space *mapping, int err)
708 errseq_t eseq = errseq_set(&mapping->wb_err, err);
710 trace_filemap_set_wb_err(mapping, eseq);
712 EXPORT_SYMBOL(__filemap_set_wb_err);
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
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).
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.
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.).
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.
736 * Return: %0 on success, negative error code otherwise.
738 int file_check_and_advance_wb_err(struct file *file)
741 errseq_t old = READ_ONCE(file->f_wb_err);
742 struct address_space *mapping = file->f_mapping;
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,
751 trace_file_check_and_advance_wb_err(file, old);
752 spin_unlock(&file->f_lock);
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.
760 clear_bit(AS_EIO, &mapping->flags);
761 clear_bit(AS_ENOSPC, &mapping->flags);
764 EXPORT_SYMBOL(file_check_and_advance_wb_err);
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)
772 * Write out and wait upon file offsets lstart->lend, inclusive.
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).
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.
780 * Return: %0 on success, negative error code otherwise.
782 int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
785 struct address_space *mapping = file->f_mapping;
787 if (mapping_needs_writeback(mapping)) {
788 err = __filemap_fdatawrite_range(mapping, lstart, lend,
790 /* See comment of filemap_write_and_wait() */
792 __filemap_fdatawait_range(mapping, lstart, lend);
794 err2 = file_check_and_advance_wb_err(file);
799 EXPORT_SYMBOL(file_write_and_wait_range);
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
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.
812 * The remove + add is atomic. This function cannot fail.
814 void replace_page_cache_page(struct page *old, struct page *new)
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);
823 VM_BUG_ON_PAGE(!PageLocked(old), old);
824 VM_BUG_ON_PAGE(!PageLocked(new), new);
825 VM_BUG_ON_PAGE(new->mapping, new);
828 new->mapping = mapping;
831 mem_cgroup_migrate(fold, fnew);
834 xas_store(&xas, new);
837 /* hugetlb pages do not participate in page cache accounting. */
839 __dec_lruvec_page_state(old, NR_FILE_PAGES);
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);
851 EXPORT_SYMBOL_GPL(replace_page_cache_page);
853 noinline int __filemap_add_folio(struct address_space *mapping,
854 struct folio *folio, pgoff_t index, gfp_t gfp, void **shadowp)
856 XA_STATE(xas, &mapping->i_pages, index);
857 int huge = folio_test_hugetlb(folio);
859 bool charged = false;
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);
866 folio->mapping = mapping;
867 folio->index = index;
870 error = mem_cgroup_charge(folio, NULL, gfp);
871 VM_BUG_ON_FOLIO(index & (folio_nr_pages(folio) - 1), folio);
877 gfp &= GFP_RECLAIM_MASK;
880 unsigned int order = xa_get_order(xas.xa, xas.xa_index);
881 void *entry, *old = NULL;
883 if (order > folio_order(folio))
884 xas_split_alloc(&xas, xa_load(xas.xa, xas.xa_index),
887 xas_for_each_conflict(&xas, entry) {
889 if (!xa_is_value(entry)) {
890 xas_set_err(&xas, -EEXIST);
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);
906 xas_store(&xas, folio);
912 /* hugetlb pages do not participate in page cache accounting */
914 __lruvec_stat_add_folio(folio, NR_FILE_PAGES);
916 xas_unlock_irq(&xas);
917 } while (xas_nomem(&xas, gfp));
919 if (xas_error(&xas)) {
920 error = xas_error(&xas);
922 mem_cgroup_uncharge(folio);
926 trace_mm_filemap_add_to_page_cache(folio);
929 folio->mapping = NULL;
930 /* Leave page->index set: truncation relies upon it */
934 ALLOW_ERROR_INJECTION(__filemap_add_folio, ERRNO);
937 * add_to_page_cache_locked - add a locked page to the pagecache
939 * @mapping: the page's address_space
940 * @offset: page index
941 * @gfp_mask: page allocation mode
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.
946 * Return: %0 on success, negative error code otherwise.
948 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
949 pgoff_t offset, gfp_t gfp_mask)
951 return __filemap_add_folio(mapping, page_folio(page), offset,
954 EXPORT_SYMBOL(add_to_page_cache_locked);
956 int filemap_add_folio(struct address_space *mapping, struct folio *folio,
957 pgoff_t index, gfp_t gfp)
962 __folio_set_locked(folio);
963 ret = __filemap_add_folio(mapping, folio, index, gfp, &shadow);
965 __folio_clear_locked(folio);
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.
975 WARN_ON_ONCE(folio_test_active(folio));
976 if (!(gfp & __GFP_WRITE) && shadow)
977 workingset_refault(folio, shadow);
978 folio_add_lru(folio);
982 EXPORT_SYMBOL_GPL(filemap_add_folio);
985 struct folio *filemap_alloc_folio(gfp_t gfp, unsigned int order)
990 if (cpuset_do_page_mem_spread()) {
991 unsigned int cpuset_mems_cookie;
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));
1000 return folio_alloc(gfp, order);
1002 EXPORT_SYMBOL(filemap_alloc_folio);
1006 * filemap_invalidate_lock_two - lock invalidate_lock for two mappings
1008 * Lock exclusively invalidate_lock of any passed mapping that is not NULL.
1010 * @mapping1: the first mapping to lock
1011 * @mapping2: the second mapping to lock
1013 void filemap_invalidate_lock_two(struct address_space *mapping1,
1014 struct address_space *mapping2)
1016 if (mapping1 > mapping2)
1017 swap(mapping1, mapping2);
1019 down_write(&mapping1->invalidate_lock);
1020 if (mapping2 && mapping1 != mapping2)
1021 down_write_nested(&mapping2->invalidate_lock, 1);
1023 EXPORT_SYMBOL(filemap_invalidate_lock_two);
1026 * filemap_invalidate_unlock_two - unlock invalidate_lock for two mappings
1028 * Unlock exclusive invalidate_lock of any passed mapping that is not NULL.
1030 * @mapping1: the first mapping to unlock
1031 * @mapping2: the second mapping to unlock
1033 void filemap_invalidate_unlock_two(struct address_space *mapping1,
1034 struct address_space *mapping2)
1037 up_write(&mapping1->invalidate_lock);
1038 if (mapping2 && mapping1 != mapping2)
1039 up_write(&mapping2->invalidate_lock);
1041 EXPORT_SYMBOL(filemap_invalidate_unlock_two);
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
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;
1057 static wait_queue_head_t *folio_waitqueue(struct folio *folio)
1059 return &folio_wait_table[hash_ptr(folio, PAGE_WAIT_TABLE_BITS)];
1062 void __init pagecache_init(void)
1066 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1067 init_waitqueue_head(&folio_wait_table[i]);
1069 page_writeback_init();
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"
1079 * (a) no special bits set:
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.
1085 * Simple and straightforward.
1087 * (b) WQ_FLAG_EXCLUSIVE:
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.
1093 * This is the traditional exclusive wait.
1095 * (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
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
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.
1106 static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
1109 struct wait_page_key *key = arg;
1110 struct wait_page_queue *wait_page
1111 = container_of(wait, struct wait_page_queue, wait);
1113 if (!wake_page_match(wait_page, key))
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.
1120 flags = wait->flags;
1121 if (flags & WQ_FLAG_EXCLUSIVE) {
1122 if (test_bit(key->bit_nr, &key->folio->flags))
1124 if (flags & WQ_FLAG_CUSTOM) {
1125 if (test_and_set_bit(key->bit_nr, &key->folio->flags))
1127 flags |= WQ_FLAG_DONE;
1132 * We are holding the wait-queue lock, but the waiter that
1133 * is waiting for this will be checking the flags without
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().
1140 smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
1141 wake_up_state(wait->private, mode);
1144 * Ok, we have successfully done what we're waiting for,
1145 * and we can unconditionally remove the wait entry.
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
1153 list_del_init_careful(&wait->entry);
1154 return (flags & WQ_FLAG_EXCLUSIVE) != 0;
1157 static void folio_wake_bit(struct folio *folio, int bit_nr)
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;
1165 key.bit_nr = bit_nr;
1169 bookmark.private = NULL;
1170 bookmark.func = NULL;
1171 INIT_LIST_HEAD(&bookmark.entry);
1173 spin_lock_irqsave(&q->lock, flags);
1174 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1176 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1178 * Take a breather from holding the lock,
1179 * allow pages that finish wake up asynchronously
1180 * to acquire the lock and remove themselves
1183 spin_unlock_irqrestore(&q->lock, flags);
1185 spin_lock_irqsave(&q->lock, flags);
1186 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
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-
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
1198 if (!waitqueue_active(q) || !key.page_match) {
1199 folio_clear_waiters(folio);
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.
1205 * That's okay, it's a rare case. The next waker will clear it.
1208 spin_unlock_irqrestore(&q->lock, flags);
1211 static void folio_wake(struct folio *folio, int bit)
1213 if (!folio_test_waiters(folio))
1215 folio_wake_bit(folio, bit);
1219 * A choice of three behaviors for folio_wait_bit_common():
1222 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
1223 * __folio_lock() waiting on then setting PG_locked.
1225 SHARED, /* Hold ref to page and check the bit when woken, like
1226 * folio_wait_writeback() waiting on PG_writeback.
1228 DROP, /* Drop ref to page before wait, no check when woken,
1229 * like folio_put_wait_locked() on PG_locked.
1234 * Attempt to check (or get) the folio flag, and mark us done
1237 static inline bool folio_trylock_flag(struct folio *folio, int bit_nr,
1238 struct wait_queue_entry *wait)
1240 if (wait->flags & WQ_FLAG_EXCLUSIVE) {
1241 if (test_and_set_bit(bit_nr, &folio->flags))
1243 } else if (test_bit(bit_nr, &folio->flags))
1246 wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
1250 /* How many times do we accept lock stealing from under a waiter? */
1251 int sysctl_page_lock_unfairness = 5;
1253 static inline int folio_wait_bit_common(struct folio *folio, int bit_nr,
1254 int state, enum behavior behavior)
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;
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();
1270 psi_memstall_enter(&pflags);
1275 wait->func = wake_page_function;
1276 wait_page.folio = folio;
1277 wait_page.bit_nr = bit_nr;
1281 if (behavior == EXCLUSIVE) {
1282 wait->flags = WQ_FLAG_EXCLUSIVE;
1283 if (--unfairness < 0)
1284 wait->flags |= WQ_FLAG_CUSTOM;
1288 * Do one last check whether we can get the
1289 * page bit synchronously.
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.
1298 * This part needs to be done under the queue
1299 * lock to avoid races.
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);
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.
1313 * We can drop our reference to the folio.
1315 if (behavior == DROP)
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.
1327 set_current_state(state);
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))
1339 /* If we were non-exclusive, we're done */
1340 if (behavior != EXCLUSIVE)
1343 /* If the waker got the lock for us, we're done */
1344 if (flags & WQ_FLAG_DONE)
1348 * Otherwise, if we're getting the lock, we need to
1349 * try to get it ourselves.
1351 * And if that fails, we'll have to retry this all.
1353 if (unlikely(test_and_set_bit(bit_nr, folio_flags(folio, 0))))
1356 wait->flags |= WQ_FLAG_DONE;
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.
1366 finish_wait(q, wait);
1370 delayacct_thrashing_end();
1371 psi_memstall_leave(&pflags);
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()'.
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.
1384 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
1385 * waiter, but an exclusive one requires WQ_FLAG_DONE.
1387 if (behavior == EXCLUSIVE)
1388 return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
1390 return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
1393 #ifdef CONFIG_MIGRATION
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.
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
1407 * Returns after unmapping and unlocking the pte/ptl with pte_unmap_unlock().
1409 * This follows the same logic as folio_wait_bit_common() so see the comments
1412 void migration_entry_wait_on_locked(swp_entry_t entry, pte_t *ptep,
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));
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();
1429 psi_memstall_enter(&pflags);
1434 wait->func = wake_page_function;
1435 wait_page.folio = folio;
1436 wait_page.bit_nr = PG_locked;
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);
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.
1451 pte_unmap_unlock(ptep, ptl);
1458 set_current_state(TASK_UNINTERRUPTIBLE);
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))
1472 finish_wait(q, wait);
1476 delayacct_thrashing_end();
1477 psi_memstall_leave(&pflags);
1482 void folio_wait_bit(struct folio *folio, int bit_nr)
1484 folio_wait_bit_common(folio, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
1486 EXPORT_SYMBOL(folio_wait_bit);
1488 int folio_wait_bit_killable(struct folio *folio, int bit_nr)
1490 return folio_wait_bit_common(folio, bit_nr, TASK_KILLABLE, SHARED);
1492 EXPORT_SYMBOL(folio_wait_bit_killable);
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).
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.
1505 * Return: 0 if the folio was unlocked or -EINTR if interrupted by a signal.
1507 int folio_put_wait_locked(struct folio *folio, int state)
1509 return folio_wait_bit_common(folio, PG_locked, state, DROP);
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
1517 * Add an arbitrary @waiter to the wait queue for the nominated @folio.
1519 void folio_add_wait_queue(struct folio *folio, wait_queue_entry_t *waiter)
1521 wait_queue_head_t *q = folio_waitqueue(folio);
1522 unsigned long flags;
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);
1529 EXPORT_SYMBOL_GPL(folio_add_wait_queue);
1531 #ifndef clear_bit_unlock_is_negative_byte
1534 * PG_waiters is the high bit in the same byte as PG_lock.
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
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.
1545 static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1547 clear_bit_unlock(nr, mem);
1548 /* smp_mb__after_atomic(); */
1549 return test_bit(PG_waiters, mem);
1555 * folio_unlock - Unlock a locked folio.
1556 * @folio: The folio.
1558 * Unlocks the folio and wakes up any thread sleeping on the page lock.
1560 * Context: May be called from interrupt or process context. May not be
1561 * called from NMI context.
1563 void folio_unlock(struct folio *folio)
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);
1572 EXPORT_SYMBOL(folio_unlock);
1575 * folio_end_private_2 - Clear PG_private_2 and wake any waiters.
1576 * @folio: The folio.
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.
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
1585 void folio_end_private_2(struct folio *folio)
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);
1592 EXPORT_SYMBOL(folio_end_private_2);
1595 * folio_wait_private_2 - Wait for PG_private_2 to be cleared on a folio.
1596 * @folio: The folio to wait on.
1598 * Wait for PG_private_2 (aka PG_fscache) to be cleared on a folio.
1600 void folio_wait_private_2(struct folio *folio)
1602 while (folio_test_private_2(folio))
1603 folio_wait_bit(folio, PG_private_2);
1605 EXPORT_SYMBOL(folio_wait_private_2);
1608 * folio_wait_private_2_killable - Wait for PG_private_2 to be cleared on a folio.
1609 * @folio: The folio to wait on.
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.
1615 * - 0 if successful.
1616 * - -EINTR if a fatal signal was encountered.
1618 int folio_wait_private_2_killable(struct folio *folio)
1622 while (folio_test_private_2(folio)) {
1623 ret = folio_wait_bit_killable(folio, PG_private_2);
1630 EXPORT_SYMBOL(folio_wait_private_2_killable);
1633 * folio_end_writeback - End writeback against a folio.
1634 * @folio: The folio.
1636 void folio_end_writeback(struct folio *folio)
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.
1645 if (folio_test_reclaim(folio)) {
1646 folio_clear_reclaim(folio);
1647 folio_rotate_reclaimable(folio);
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().
1657 if (!__folio_end_writeback(folio))
1660 smp_mb__after_atomic();
1661 folio_wake(folio, PG_writeback);
1662 acct_reclaim_writeback(folio);
1665 EXPORT_SYMBOL(folio_end_writeback);
1668 * After completing I/O on a page, call this routine to update the page
1669 * flags appropriately
1671 void page_endio(struct page *page, bool is_write, int err)
1675 SetPageUptodate(page);
1677 ClearPageUptodate(page);
1683 struct address_space *mapping;
1686 mapping = page_mapping(page);
1688 mapping_set_error(mapping, err);
1690 end_page_writeback(page);
1693 EXPORT_SYMBOL_GPL(page_endio);
1696 * __folio_lock - Get a lock on the folio, assuming we need to sleep to get it.
1697 * @folio: The folio to lock
1699 void __folio_lock(struct folio *folio)
1701 folio_wait_bit_common(folio, PG_locked, TASK_UNINTERRUPTIBLE,
1704 EXPORT_SYMBOL(__folio_lock);
1706 int __folio_lock_killable(struct folio *folio)
1708 return folio_wait_bit_common(folio, PG_locked, TASK_KILLABLE,
1711 EXPORT_SYMBOL_GPL(__folio_lock_killable);
1713 static int __folio_lock_async(struct folio *folio, struct wait_page_queue *wait)
1715 struct wait_queue_head *q = folio_waitqueue(folio);
1718 wait->folio = folio;
1719 wait->bit_nr = PG_locked;
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);
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.
1732 __remove_wait_queue(q, &wait->wait);
1735 spin_unlock_irq(&q->lock);
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.
1747 * If neither ALLOW_RETRY nor KILLABLE are set, will always return true
1748 * with the folio locked and the mmap_lock unperturbed.
1750 bool __folio_lock_or_retry(struct folio *folio, struct mm_struct *mm,
1753 if (fault_flag_allow_retry_first(flags)) {
1755 * CAUTION! In this case, mmap_lock is not released
1756 * even though return 0.
1758 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1761 mmap_read_unlock(mm);
1762 if (flags & FAULT_FLAG_KILLABLE)
1763 folio_wait_locked_killable(folio);
1765 folio_wait_locked(folio);
1768 if (flags & FAULT_FLAG_KILLABLE) {
1771 ret = __folio_lock_killable(folio);
1773 mmap_read_unlock(mm);
1777 __folio_lock(folio);
1784 * page_cache_next_miss() - Find the next gap in the page cache.
1785 * @mapping: Mapping.
1787 * @max_scan: Maximum range to search.
1789 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1790 * gap with the lowest index.
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.
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.
1802 pgoff_t page_cache_next_miss(struct address_space *mapping,
1803 pgoff_t index, unsigned long max_scan)
1805 XA_STATE(xas, &mapping->i_pages, index);
1807 while (max_scan--) {
1808 void *entry = xas_next(&xas);
1809 if (!entry || xa_is_value(entry))
1811 if (xas.xa_index == 0)
1815 return xas.xa_index;
1817 EXPORT_SYMBOL(page_cache_next_miss);
1820 * page_cache_prev_miss() - Find the previous gap in the page cache.
1821 * @mapping: Mapping.
1823 * @max_scan: Maximum range to search.
1825 * Search the range [max(index - max_scan + 1, 0), index] for the
1826 * gap with the highest index.
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.
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.
1838 pgoff_t page_cache_prev_miss(struct address_space *mapping,
1839 pgoff_t index, unsigned long max_scan)
1841 XA_STATE(xas, &mapping->i_pages, index);
1843 while (max_scan--) {
1844 void *entry = xas_prev(&xas);
1845 if (!entry || xa_is_value(entry))
1847 if (xas.xa_index == ULONG_MAX)
1851 return xas.xa_index;
1853 EXPORT_SYMBOL(page_cache_prev_miss);
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
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
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
1876 * mapping_get_entry - Get a page cache entry.
1877 * @mapping: the address_space to search
1878 * @index: The page cache index.
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.
1885 * Return: The folio, swap or shadow entry, %NULL if nothing is found.
1887 static void *mapping_get_entry(struct address_space *mapping, pgoff_t index)
1889 XA_STATE(xas, &mapping->i_pages, index);
1890 struct folio *folio;
1895 folio = xas_load(&xas);
1896 if (xas_retry(&xas, folio))
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.
1902 if (!folio || xa_is_value(folio))
1905 if (!folio_try_get_rcu(folio))
1908 if (unlikely(folio != xas_reload(&xas))) {
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.
1925 * Looks up the page cache entry at @mapping & @index.
1927 * @fgp_flags can be zero or more of these flags:
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)
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.
1947 * If there is a page cache page, it is returned with an increased refcount.
1949 * Return: The found folio or %NULL otherwise.
1951 struct folio *__filemap_get_folio(struct address_space *mapping, pgoff_t index,
1952 int fgp_flags, gfp_t gfp)
1954 struct folio *folio;
1957 folio = mapping_get_entry(mapping, index);
1958 if (xa_is_value(folio)) {
1959 if (fgp_flags & FGP_ENTRY)
1966 if (fgp_flags & FGP_LOCK) {
1967 if (fgp_flags & FGP_NOWAIT) {
1968 if (!folio_trylock(folio)) {
1976 /* Has the page been truncated? */
1977 if (unlikely(folio->mapping != mapping)) {
1978 folio_unlock(folio);
1982 VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
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);
1993 if (fgp_flags & FGP_STABLE)
1994 folio_wait_stable(folio);
1996 if (!folio && (fgp_flags & FGP_CREAT)) {
1998 if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping))
2000 if (fgp_flags & FGP_NOFS)
2003 folio = filemap_alloc_folio(gfp, 0);
2007 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
2008 fgp_flags |= FGP_LOCK;
2010 /* Init accessed so avoid atomic mark_page_accessed later */
2011 if (fgp_flags & FGP_ACCESSED)
2012 __folio_set_referenced(folio);
2014 err = filemap_add_folio(mapping, folio, index, gfp);
2015 if (unlikely(err)) {
2023 * filemap_add_folio locks the page, and for mmap
2024 * we expect an unlocked page.
2026 if (folio && (fgp_flags & FGP_FOR_MMAP))
2027 folio_unlock(folio);
2032 EXPORT_SYMBOL(__filemap_get_folio);
2034 static inline struct folio *find_get_entry(struct xa_state *xas, pgoff_t max,
2037 struct folio *folio;
2040 if (mark == XA_PRESENT)
2041 folio = xas_find(xas, max);
2043 folio = xas_find_marked(xas, max, mark);
2045 if (xas_retry(xas, folio))
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.
2052 if (!folio || xa_is_value(folio))
2055 if (!folio_try_get_rcu(folio))
2058 if (unlikely(folio != xas_reload(xas))) {
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
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.
2081 * The entries have ascending indexes. The indices may not be consecutive
2082 * due to not-present entries or large folios.
2084 * Any shadow entries of evicted folios, or swap entries from
2085 * shmem/tmpfs, are included in the returned array.
2087 * Return: The number of entries which were found.
2089 unsigned find_get_entries(struct address_space *mapping, pgoff_t start,
2090 pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
2092 XA_STATE(xas, &mapping->i_pages, start);
2093 struct folio *folio;
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))
2103 return folio_batch_count(fbatch);
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.
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.
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.
2124 * Return: The number of entries which were found.
2126 unsigned find_lock_entries(struct address_space *mapping, pgoff_t start,
2127 pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
2129 XA_STATE(xas, &mapping->i_pages, start);
2130 struct folio *folio;
2133 while ((folio = find_get_entry(&xas, end, XA_PRESENT))) {
2134 if (!xa_is_value(folio)) {
2135 if (folio->index < start)
2137 if (folio->index + folio_nr_pages(folio) - 1 > end)
2139 if (!folio_trylock(folio))
2141 if (folio->mapping != mapping ||
2142 folio_test_writeback(folio))
2144 VM_BUG_ON_FOLIO(!folio_contains(folio, xas.xa_index),
2147 indices[fbatch->nr] = xas.xa_index;
2148 if (!folio_batch_add(fbatch, folio))
2152 folio_unlock(folio);
2158 return folio_batch_count(fbatch);
2162 bool folio_more_pages(struct folio *folio, pgoff_t index, pgoff_t max)
2164 if (!folio_test_large(folio) || folio_test_hugetlb(folio))
2168 return index < folio->index + folio_nr_pages(folio) - 1;
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
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.
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.
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
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)
2196 XA_STATE(xas, &mapping->i_pages, *start);
2197 struct folio *folio;
2200 if (unlikely(!nr_pages))
2204 while ((folio = find_get_entry(&xas, end, XA_PRESENT))) {
2205 /* Skip over shadow, swap and DAX entries */
2206 if (xa_is_value(folio))
2210 pages[ret] = folio_file_page(folio, xas.xa_index);
2211 if (++ret == nr_pages) {
2212 *start = xas.xa_index + 1;
2215 if (folio_more_pages(folio, xas.xa_index, end)) {
2217 folio_ref_inc(folio);
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.
2228 if (end == (pgoff_t)-1)
2229 *start = (pgoff_t)-1;
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
2245 * find_get_pages_contig() works exactly like find_get_pages(), except
2246 * that the returned number of pages are guaranteed to be contiguous.
2248 * Return: the number of pages which were found.
2250 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
2251 unsigned int nr_pages, struct page **pages)
2253 XA_STATE(xas, &mapping->i_pages, index);
2254 struct folio *folio;
2255 unsigned int ret = 0;
2257 if (unlikely(!nr_pages))
2261 for (folio = xas_load(&xas); folio; folio = xas_next(&xas)) {
2262 if (xas_retry(&xas, folio))
2265 * If the entry has been swapped out, we can stop looking.
2266 * No current caller is looking for DAX entries.
2268 if (xa_is_value(folio))
2271 if (!folio_try_get_rcu(folio))
2274 if (unlikely(folio != xas_reload(&xas)))
2278 pages[ret] = folio_file_page(folio, xas.xa_index);
2279 if (++ret == nr_pages)
2281 if (folio_more_pages(folio, xas.xa_index, ULONG_MAX)) {
2283 folio_ref_inc(folio);
2295 EXPORT_SYMBOL(find_get_pages_contig);
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
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.
2310 * Return: the number of pages which were found.
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)
2316 XA_STATE(xas, &mapping->i_pages, *index);
2317 struct folio *folio;
2320 if (unlikely(!nr_pages))
2324 while ((folio = find_get_entry(&xas, end, tag))) {
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.
2330 if (xa_is_value(folio))
2333 pages[ret] = &folio->page;
2334 if (++ret == nr_pages) {
2335 *index = folio->index + folio_nr_pages(folio);
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
2346 if (end == (pgoff_t)-1)
2347 *index = (pgoff_t)-1;
2355 EXPORT_SYMBOL(find_get_pages_range_tag);
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:
2361 * ---R__________________________________________B__________
2362 * ^ reading here ^ bad block(assume 4k)
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) => ......
2370 * It is going insane. Fix it by quickly scaling down the readahead size.
2372 static void shrink_readahead_size_eio(struct file_ra_state *ra)
2378 * filemap_get_read_batch - Get a batch of folios for read
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.
2386 static void filemap_get_read_batch(struct address_space *mapping,
2387 pgoff_t index, pgoff_t max, struct folio_batch *fbatch)
2389 XA_STATE(xas, &mapping->i_pages, index);
2390 struct folio *folio;
2393 for (folio = xas_load(&xas); folio; folio = xas_next(&xas)) {
2394 if (xas_retry(&xas, folio))
2396 if (xas.xa_index > max || xa_is_value(folio))
2398 if (!folio_try_get_rcu(folio))
2401 if (unlikely(folio != xas_reload(&xas)))
2404 if (!folio_batch_add(fbatch, folio))
2406 if (!folio_test_uptodate(folio))
2408 if (folio_test_readahead(folio))
2410 xas_advance(&xas, folio->index + folio_nr_pages(folio) - 1);
2420 static int filemap_read_folio(struct file *file, struct address_space *mapping,
2421 struct folio *folio)
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
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);
2436 error = folio_wait_locked_killable(folio);
2439 if (folio_test_uptodate(folio))
2441 shrink_readahead_size_eio(&file->f_ra);
2445 static bool filemap_range_uptodate(struct address_space *mapping,
2446 loff_t pos, struct iov_iter *iter, struct folio *folio)
2450 if (folio_test_uptodate(folio))
2452 /* pipes can't handle partially uptodate pages */
2453 if (iov_iter_is_pipe(iter))
2455 if (!mapping->a_ops->is_partially_uptodate)
2457 if (mapping->host->i_blkbits >= folio_shift(folio))
2460 count = iter->count;
2461 if (folio_pos(folio) > pos) {
2462 count -= folio_pos(folio) - pos;
2465 pos -= folio_pos(folio);
2468 return mapping->a_ops->is_partially_uptodate(&folio->page, pos, count);
2471 static int filemap_update_page(struct kiocb *iocb,
2472 struct address_space *mapping, struct iov_iter *iter,
2473 struct folio *folio)
2477 if (iocb->ki_flags & IOCB_NOWAIT) {
2478 if (!filemap_invalidate_trylock_shared(mapping))
2481 filemap_invalidate_lock_shared(mapping);
2484 if (!folio_trylock(folio)) {
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);
2491 * This is where we usually end up waiting for a
2492 * previously submitted readahead to finish.
2494 folio_put_wait_locked(folio, TASK_KILLABLE);
2495 return AOP_TRUNCATED_PAGE;
2497 error = __folio_lock_async(folio, iocb->ki_waitq);
2499 goto unlock_mapping;
2502 error = AOP_TRUNCATED_PAGE;
2503 if (!folio->mapping)
2507 if (filemap_range_uptodate(mapping, iocb->ki_pos, iter, folio))
2511 if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT | IOCB_WAITQ))
2514 error = filemap_read_folio(iocb->ki_filp, mapping, folio);
2515 goto unlock_mapping;
2517 folio_unlock(folio);
2519 filemap_invalidate_unlock_shared(mapping);
2520 if (error == AOP_TRUNCATED_PAGE)
2525 static int filemap_create_folio(struct file *file,
2526 struct address_space *mapping, pgoff_t index,
2527 struct folio_batch *fbatch)
2529 struct folio *folio;
2532 folio = filemap_alloc_folio(mapping_gfp_mask(mapping), 0);
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.
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;
2557 error = filemap_read_folio(file, mapping, folio);
2561 filemap_invalidate_unlock_shared(mapping);
2562 folio_batch_add(fbatch, folio);
2565 filemap_invalidate_unlock_shared(mapping);
2570 static int filemap_readahead(struct kiocb *iocb, struct file *file,
2571 struct address_space *mapping, struct folio *folio,
2574 DEFINE_READAHEAD(ractl, file, &file->f_ra, mapping, folio->index);
2576 if (iocb->ki_flags & IOCB_NOIO)
2578 page_cache_async_ra(&ractl, folio, last_index - folio->index);
2582 static int filemap_get_pages(struct kiocb *iocb, struct iov_iter *iter,
2583 struct folio_batch *fbatch)
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;
2590 struct folio *folio;
2593 last_index = DIV_ROUND_UP(iocb->ki_pos + iter->count, PAGE_SIZE);
2595 if (fatal_signal_pending(current))
2598 filemap_get_read_batch(mapping, index, last_index, fbatch);
2599 if (!folio_batch_count(fbatch)) {
2600 if (iocb->ki_flags & IOCB_NOIO)
2602 page_cache_sync_readahead(mapping, ra, filp, index,
2603 last_index - index);
2604 filemap_get_read_batch(mapping, index, last_index, fbatch);
2606 if (!folio_batch_count(fbatch)) {
2607 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_WAITQ))
2609 err = filemap_create_folio(filp, mapping,
2610 iocb->ki_pos >> PAGE_SHIFT, fbatch);
2611 if (err == AOP_TRUNCATED_PAGE)
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);
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);
2635 if (likely(--fbatch->nr))
2637 if (err == AOP_TRUNCATED_PAGE)
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.
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.
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.
2655 ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,
2656 ssize_t already_read)
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;
2664 bool writably_mapped;
2665 loff_t isize, end_offset;
2667 if (unlikely(iocb->ki_pos >= inode->i_sb->s_maxbytes))
2669 if (unlikely(!iov_iter_count(iter)))
2672 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2673 folio_batch_init(&fbatch);
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.
2683 if ((iocb->ki_flags & IOCB_WAITQ) && already_read)
2684 iocb->ki_flags |= IOCB_NOWAIT;
2686 if (unlikely(iocb->ki_pos >= i_size_read(inode)))
2689 error = filemap_get_pages(iocb, iter, &fbatch);
2694 * i_size must be checked after we know the pages are Uptodate.
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).
2701 isize = i_size_read(inode);
2702 if (unlikely(iocb->ki_pos >= isize))
2704 end_offset = min_t(loff_t, isize, iocb->ki_pos + iter->count);
2707 * Once we start copying data, we don't want to be touching any
2708 * cachelines that might be contended:
2710 writably_mapped = mapping_writably_mapped(mapping);
2713 * When a sequential read accesses a page several times, only
2714 * mark it as accessed the first time.
2716 if (iocb->ki_pos >> PAGE_SHIFT !=
2717 ra->prev_pos >> PAGE_SHIFT)
2718 folio_mark_accessed(fbatch.folios[0]);
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,
2728 if (end_offset < folio_pos(folio))
2731 folio_mark_accessed(folio);
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.
2737 if (writably_mapped)
2738 flush_dcache_folio(folio);
2740 copied = copy_folio_to_iter(folio, offset, bytes, iter);
2742 already_read += copied;
2743 iocb->ki_pos += copied;
2744 ra->prev_pos = iocb->ki_pos;
2746 if (copied < bytes) {
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);
2757 file_accessed(filp);
2759 return already_read ? already_read : error;
2761 EXPORT_SYMBOL_GPL(filemap_read);
2764 * generic_file_read_iter - generic filesystem read routine
2765 * @iocb: kernel I/O control block
2766 * @iter: destination for the data read
2768 * This is the "read_iter()" routine for all filesystems
2769 * that can use the page cache directly.
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.
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.
2781 * * number of bytes copied, even for partial reads
2782 * * negative error code (or 0 if IOCB_NOIO) if nothing was read
2785 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2787 size_t count = iov_iter_count(iter);
2791 return 0; /* skip atime */
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;
2798 if (iocb->ki_flags & IOCB_NOWAIT) {
2799 if (filemap_range_needs_writeback(mapping, iocb->ki_pos,
2800 iocb->ki_pos + count - 1))
2803 retval = filemap_write_and_wait_range(mapping,
2805 iocb->ki_pos + count - 1);
2810 file_accessed(file);
2812 retval = mapping->a_ops->direct_IO(iocb, iter);
2814 iocb->ki_pos += retval;
2817 if (retval != -EIOCBQUEUED)
2818 iov_iter_revert(iter, count - iov_iter_count(iter));
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.
2829 if (retval < 0 || !count || IS_DAX(inode))
2831 if (iocb->ki_pos >= i_size_read(inode))
2835 return filemap_read(iocb, iter, retval);
2837 EXPORT_SYMBOL(generic_file_read_iter);
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)
2843 const struct address_space_operations *ops = mapping->a_ops;
2844 size_t offset, bsz = i_blocksize(mapping->host);
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;
2854 if (unlikely(folio->mapping != mapping))
2857 offset = offset_in_folio(folio, start) & ~(bsz - 1);
2860 if (ops->is_partially_uptodate(&folio->page, offset, bsz) ==
2863 start = (start + bsz) & ~(bsz - 1);
2865 } while (offset < folio_size(folio));
2867 folio_unlock(folio);
2872 static inline size_t seek_folio_size(struct xa_state *xas, struct folio *folio)
2874 if (xa_is_value(folio))
2875 return PAGE_SIZE << xa_get_order(xas->xa, xas->xa_index);
2876 return folio_size(folio);
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.
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.
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.
2897 loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start,
2898 loff_t end, int whence)
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;
2909 while ((folio = find_get_entry(&xas, max, XA_PRESENT))) {
2910 loff_t pos = (u64)xas.xa_index << PAGE_SHIFT;
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,
2927 if (seek_size > PAGE_SIZE)
2928 xas_set(&xas, pos >> PAGE_SHIFT);
2929 if (!xa_is_value(folio))
2936 if (folio && !xa_is_value(folio))
2944 #define MMAP_LOTSAMISS (100)
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).
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.
2957 static int lock_folio_maybe_drop_mmap(struct vm_fault *vmf, struct folio *folio,
2960 if (folio_trylock(folio))
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..
2968 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2971 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2972 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2973 if (__folio_lock_killable(folio)) {
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.
2981 mmap_read_unlock(vmf->vma->vm_mm);
2985 __folio_lock(folio);
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.
2997 static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
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;
3006 /* If we don't want any read-ahead, don't bother */
3007 if (vmf->vma->vm_flags & VM_RAND_READ)
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);
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);
3024 * Do we miss much more than hit in this file? If so,
3025 * stop bothering with read-ahead. It will only hurt.
3027 if (mmap_miss > MMAP_LOTSAMISS)
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);
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.
3047 static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
3048 struct folio *folio)
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;
3056 /* If we don't want any read-ahead, don't bother */
3057 if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
3060 mmap_miss = READ_ONCE(ra->mmap_miss);
3062 WRITE_ONCE(ra->mmap_miss, --mmap_miss);
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);
3072 * filemap_fault - read in file data for page fault handling
3073 * @vmf: struct vm_fault containing details of the fault
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.
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.
3082 * vma->vm_mm->mmap_lock must be held on entry.
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().
3087 * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
3088 * has not been released.
3090 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
3092 * Return: bitwise-OR of %VM_FAULT_ codes.
3094 vm_fault_t filemap_fault(struct vm_fault *vmf)
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;
3104 bool mapping_locked = false;
3106 max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3107 if (unlikely(index >= max_idx))
3108 return VM_FAULT_SIGBUS;
3111 * Do we have something in the page cache already?
3113 folio = filemap_get_folio(mapping, index);
3114 if (likely(folio)) {
3116 * We found the page, so try async readahead before waiting for
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;
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);
3133 * See comment in filemap_create_folio() why we need
3136 if (!mapping_locked) {
3137 filemap_invalidate_lock_shared(mapping);
3138 mapping_locked = true;
3140 folio = __filemap_get_folio(mapping, index,
3141 FGP_CREAT|FGP_FOR_MMAP,
3146 filemap_invalidate_unlock_shared(mapping);
3147 return VM_FAULT_OOM;
3151 if (!lock_folio_maybe_drop_mmap(vmf, folio, &fpin))
3154 /* Did it get truncated? */
3155 if (unlikely(folio->mapping != mapping)) {
3156 folio_unlock(folio);
3160 VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
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.
3166 if (unlikely(!folio_test_uptodate(folio))) {
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
3173 if (!mapping_locked) {
3174 folio_unlock(folio);
3178 goto page_not_uptodate;
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
3187 folio_unlock(folio);
3191 filemap_invalidate_unlock_shared(mapping);
3194 * Found the page and have a reference on it.
3195 * We must recheck i_size under page lock.
3197 max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3198 if (unlikely(index >= max_idx)) {
3199 folio_unlock(folio);
3201 return VM_FAULT_SIGBUS;
3204 vmf->page = folio_file_page(folio, index);
3205 return ret | VM_FAULT_LOCKED;
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.
3214 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3215 error = filemap_read_folio(file, mapping, folio);
3220 if (!error || error == AOP_TRUNCATED_PAGE)
3222 filemap_invalidate_unlock_shared(mapping);
3224 return VM_FAULT_SIGBUS;
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
3235 filemap_invalidate_unlock_shared(mapping);
3238 return ret | VM_FAULT_RETRY;
3240 EXPORT_SYMBOL(filemap_fault);
3242 static bool filemap_map_pmd(struct vm_fault *vmf, struct page *page)
3244 struct mm_struct *mm = vmf->vma->vm_mm;
3246 /* Huge page is mapped? No need to proceed. */
3247 if (pmd_trans_huge(*vmf->pmd)) {
3253 if (pmd_none(*vmf->pmd) && PageTransHuge(page)) {
3254 vm_fault_t ret = do_set_pmd(vmf, page);
3256 /* The page is mapped successfully, reference consumed. */
3262 if (pmd_none(*vmf->pmd))
3263 pmd_install(mm, vmf->pmd, &vmf->prealloc_pte);
3265 /* See comment in handle_pte_fault() */
3266 if (pmd_devmap_trans_unstable(vmf->pmd)) {
3275 static struct folio *next_uptodate_page(struct folio *folio,
3276 struct address_space *mapping,
3277 struct xa_state *xas, pgoff_t end_pgoff)
3279 unsigned long max_idx;
3284 if (xas_retry(xas, folio))
3286 if (xa_is_value(folio))
3288 if (folio_test_locked(folio))
3290 if (!folio_try_get_rcu(folio))
3292 /* Has the page moved or been split? */
3293 if (unlikely(folio != xas_reload(xas)))
3295 if (!folio_test_uptodate(folio) || folio_test_readahead(folio))
3297 if (!folio_trylock(folio))
3299 if (folio->mapping != mapping)
3301 if (!folio_test_uptodate(folio))
3303 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
3304 if (xas->xa_index >= max_idx)
3308 folio_unlock(folio);
3311 } while ((folio = xas_next_entry(xas, end_pgoff)) != NULL);
3316 static inline struct folio *first_map_page(struct address_space *mapping,
3317 struct xa_state *xas,
3320 return next_uptodate_page(xas_find(xas, end_pgoff),
3321 mapping, xas, end_pgoff);
3324 static inline struct folio *next_map_page(struct address_space *mapping,
3325 struct xa_state *xas,
3328 return next_uptodate_page(xas_next_entry(xas, end_pgoff),
3329 mapping, xas, end_pgoff);
3332 vm_fault_t filemap_map_pages(struct vm_fault *vmf,
3333 pgoff_t start_pgoff, pgoff_t end_pgoff)
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;
3340 XA_STATE(xas, &mapping->i_pages, start_pgoff);
3341 struct folio *folio;
3343 unsigned int mmap_miss = READ_ONCE(file->f_ra.mmap_miss);
3347 folio = first_map_page(mapping, &xas, end_pgoff);
3351 if (filemap_map_pmd(vmf, &folio->page)) {
3352 ret = VM_FAULT_NOPAGE;
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);
3360 page = folio_file_page(folio, xas.xa_index);
3361 if (PageHWPoison(page))
3367 addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
3368 vmf->pte += xas.xa_index - last_pgoff;
3369 last_pgoff = xas.xa_index;
3371 if (!pte_none(*vmf->pte))
3374 /* We're about to handle the fault */
3375 if (vmf->address == addr)
3376 ret = VM_FAULT_NOPAGE;
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)) {
3383 folio_ref_inc(folio);
3386 folio_unlock(folio);
3389 if (folio_more_pages(folio, xas.xa_index, end_pgoff)) {
3393 folio_unlock(folio);
3395 } while ((folio = next_map_page(mapping, &xas, end_pgoff)) != NULL);
3396 pte_unmap_unlock(vmf->pte, vmf->ptl);
3399 WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss);
3402 EXPORT_SYMBOL(filemap_map_pages);
3404 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
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;
3410 sb_start_pagefault(mapping->host->i_sb);
3411 file_update_time(vmf->vma->vm_file);
3413 if (folio->mapping != mapping) {
3414 folio_unlock(folio);
3415 ret = VM_FAULT_NOPAGE;
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.
3423 folio_mark_dirty(folio);
3424 folio_wait_stable(folio);
3426 sb_end_pagefault(mapping->host->i_sb);
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,
3436 /* This is used for a general mmap of a disk file */
3438 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3440 struct address_space *mapping = file->f_mapping;
3442 if (!mapping->a_ops->readpage)
3444 file_accessed(file);
3445 vma->vm_ops = &generic_file_vm_ops;
3450 * This is for filesystems which do not implement ->writepage.
3452 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3454 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
3456 return generic_file_mmap(file, vma);
3459 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
3461 return VM_FAULT_SIGBUS;
3463 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3467 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3471 #endif /* CONFIG_MMU */
3473 EXPORT_SYMBOL(filemap_page_mkwrite);
3474 EXPORT_SYMBOL(generic_file_mmap);
3475 EXPORT_SYMBOL(generic_file_readonly_mmap);
3477 static struct folio *do_read_cache_folio(struct address_space *mapping,
3478 pgoff_t index, filler_t filler, void *data, gfp_t gfp)
3480 struct folio *folio;
3483 folio = filemap_get_folio(mapping, index);
3485 folio = filemap_alloc_folio(gfp, 0);
3487 return ERR_PTR(-ENOMEM);
3488 err = filemap_add_folio(mapping, folio, index, gfp);
3489 if (unlikely(err)) {
3493 /* Presumably ENOMEM for xarray node */
3494 return ERR_PTR(err);
3499 err = filler(data, &folio->page);
3501 err = mapping->a_ops->readpage(data, &folio->page);
3505 return ERR_PTR(err);
3508 folio_wait_locked(folio);
3509 if (!folio_test_uptodate(folio)) {
3511 return ERR_PTR(-EIO);
3516 if (folio_test_uptodate(folio))
3519 if (!folio_trylock(folio)) {
3520 folio_put_wait_locked(folio, TASK_UNINTERRUPTIBLE);
3524 /* Folio was truncated from mapping */
3525 if (!folio->mapping) {
3526 folio_unlock(folio);
3531 /* Someone else locked and filled the page in a very small window */
3532 if (folio_test_uptodate(folio)) {
3533 folio_unlock(folio);
3538 * A previous I/O error may have been due to temporary
3540 * Clear page error before actual read, PG_error will be
3541 * set again if read page fails.
3543 folio_clear_error(folio);
3547 folio_mark_accessed(folio);
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
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.
3561 * If the page does not get brought uptodate, return -EIO.
3563 * The function expects mapping->invalidate_lock to be already held.
3565 * Return: up to date page on success, ERR_PTR() on failure.
3567 struct folio *read_cache_folio(struct address_space *mapping, pgoff_t index,
3568 filler_t filler, void *data)
3570 return do_read_cache_folio(mapping, index, filler, data,
3571 mapping_gfp_mask(mapping));
3573 EXPORT_SYMBOL(read_cache_folio);
3575 static struct page *do_read_cache_page(struct address_space *mapping,
3576 pgoff_t index, filler_t *filler, void *data, gfp_t gfp)
3578 struct folio *folio;
3580 folio = do_read_cache_folio(mapping, index, filler, data, gfp);
3582 return &folio->page;
3583 return folio_file_page(folio, index);
3586 struct page *read_cache_page(struct address_space *mapping,
3587 pgoff_t index, filler_t *filler, void *data)
3589 return do_read_cache_page(mapping, index, filler, data,
3590 mapping_gfp_mask(mapping));
3592 EXPORT_SYMBOL(read_cache_page);
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
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.
3603 * If the page does not get brought uptodate, return -EIO.
3605 * The function expects mapping->invalidate_lock to be already held.
3607 * Return: up to date page on success, ERR_PTR() on failure.
3609 struct page *read_cache_page_gfp(struct address_space *mapping,
3613 return do_read_cache_page(mapping, index, NULL, NULL, gfp);
3615 EXPORT_SYMBOL(read_cache_page_gfp);
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)
3621 const struct address_space_operations *aops = mapping->a_ops;
3623 return aops->write_begin(file, mapping, pos, len, flags,
3626 EXPORT_SYMBOL(pagecache_write_begin);
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)
3632 const struct address_space_operations *aops = mapping->a_ops;
3634 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
3636 EXPORT_SYMBOL(pagecache_write_end);
3639 * Warn about a page cache invalidation failure during a direct I/O write.
3641 void dio_warn_stale_pagecache(struct file *filp)
3643 static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
3647 errseq_set(&filp->f_mapping->wb_err, -EIO);
3648 if (__ratelimit(&_rs)) {
3649 path = file_path(filp, pathname, sizeof(pathname));
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,
3659 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
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;
3669 write_len = iov_iter_count(from);
3670 end = (pos + write_len - 1) >> PAGE_SHIFT;
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))
3678 written = filemap_write_and_wait_range(mapping, pos,
3679 pos + write_len - 1);
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().
3690 written = invalidate_inode_pages2_range(mapping,
3691 pos >> PAGE_SHIFT, end);
3693 * If a page can not be invalidated, return 0 to fall back
3694 * to buffered write.
3697 if (written == -EBUSY)
3702 written = mapping->a_ops->direct_IO(iocb, from);
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...
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.
3717 * Noticeable example is a blkdev_direct_IO().
3719 * Skip invalidation for async writes or if mapping has no pages.
3721 if (written > 0 && mapping->nrpages &&
3722 invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT, end))
3723 dio_warn_stale_pagecache(file);
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);
3734 if (written != -EIOCBQUEUED)
3735 iov_iter_revert(from, write_len - iov_iter_count(from));
3739 EXPORT_SYMBOL(generic_file_direct_write);
3741 ssize_t generic_perform_write(struct file *file,
3742 struct iov_iter *i, loff_t pos)
3744 struct address_space *mapping = file->f_mapping;
3745 const struct address_space_operations *a_ops = mapping->a_ops;
3747 ssize_t written = 0;
3748 unsigned int flags = 0;
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 */
3757 offset = (pos & (PAGE_SIZE - 1));
3758 bytes = min_t(unsigned long, PAGE_SIZE - offset,
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
3768 if (unlikely(fault_in_iov_iter_readable(i, bytes))) {
3773 if (fatal_signal_pending(current)) {
3778 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
3780 if (unlikely(status < 0))
3783 if (mapping_writably_mapped(mapping))
3784 flush_dcache_page(page);
3786 copied = copy_page_from_iter_atomic(page, offset, bytes, i);
3787 flush_dcache_page(page);
3789 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3791 if (unlikely(status != copied)) {
3792 iov_iter_revert(i, copied - max(status, 0L));
3793 if (unlikely(status < 0))
3798 if (unlikely(status == 0)) {
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.
3812 balance_dirty_pages_ratelimited(mapping);
3813 } while (iov_iter_count(i));
3815 return written ? written : status;
3817 EXPORT_SYMBOL(generic_perform_write);
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
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.
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.
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.
3837 * * number of bytes written, even for truncated writes
3838 * * negative error code if no data has been written at all
3840 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
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;
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);
3855 err = file_update_time(file);
3859 if (iocb->ki_flags & IOCB_DIRECT) {
3860 loff_t pos, endbyte;
3862 written = generic_file_direct_write(iocb, from);
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).
3870 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
3873 status = generic_perform_write(file, from, pos = iocb->ki_pos);
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.
3881 if (unlikely(status < 0)) {
3886 * We need to ensure that the page cache pages are written to
3887 * disk and invalidated to preserve the expected O_DIRECT
3890 endbyte = pos + status - 1;
3891 err = filemap_write_and_wait_range(mapping, pos, endbyte);
3893 iocb->ki_pos = endbyte + 1;
3895 invalidate_mapping_pages(mapping,
3897 endbyte >> PAGE_SHIFT);
3900 * We don't know how much we wrote, so just return
3901 * the number of bytes which were direct-written
3905 written = generic_perform_write(file, from, iocb->ki_pos);
3906 if (likely(written > 0))
3907 iocb->ki_pos += written;
3910 current->backing_dev_info = NULL;
3911 return written ? written : err;
3913 EXPORT_SYMBOL(__generic_file_write_iter);
3916 * generic_file_write_iter - write data to a file
3917 * @iocb: IO state structure
3918 * @from: iov_iter with data to write
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.
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
3928 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3930 struct file *file = iocb->ki_filp;
3931 struct inode *inode = file->f_mapping->host;
3935 ret = generic_write_checks(iocb, from);
3937 ret = __generic_file_write_iter(iocb, from);
3938 inode_unlock(inode);
3941 ret = generic_write_sync(iocb, ret);
3944 EXPORT_SYMBOL(generic_file_write_iter);
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).
3951 * The address_space is trying to release any data attached to a folio
3952 * (presumably at folio->private).
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.
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).
3961 * Return: %true if the release was successful, otherwise %false.
3963 bool filemap_release_folio(struct folio *folio, gfp_t gfp)
3965 struct address_space * const mapping = folio->mapping;
3967 BUG_ON(!folio_test_locked(folio));
3968 if (folio_test_writeback(folio))
3971 if (mapping && mapping->a_ops->releasepage)
3972 return mapping->a_ops->releasepage(&folio->page, gfp);
3973 return try_to_free_buffers(&folio->page);
3975 EXPORT_SYMBOL(filemap_release_folio);