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/mman.h>
25 #include <linux/pagemap.h>
26 #include <linux/file.h>
27 #include <linux/uio.h>
28 #include <linux/error-injection.h>
29 #include <linux/hash.h>
30 #include <linux/writeback.h>
31 #include <linux/backing-dev.h>
32 #include <linux/pagevec.h>
33 #include <linux/security.h>
34 #include <linux/cpuset.h>
35 #include <linux/hugetlb.h>
36 #include <linux/memcontrol.h>
37 #include <linux/cleancache.h>
38 #include <linux/shmem_fs.h>
39 #include <linux/rmap.h>
40 #include <linux/delayacct.h>
41 #include <linux/psi.h>
42 #include <linux/ramfs.h>
43 #include <linux/page_idle.h>
44 #include <asm/pgalloc.h>
45 #include <asm/tlbflush.h>
48 #define CREATE_TRACE_POINTS
49 #include <trace/events/filemap.h>
52 * FIXME: remove all knowledge of the buffer layer from the core VM
54 #include <linux/buffer_head.h> /* for try_to_free_buffers */
59 * Shared mappings implemented 30.11.1994. It's not fully working yet,
62 * Shared mappings now work. 15.8.1995 Bruno.
64 * finished 'unifying' the page and buffer cache and SMP-threaded the
73 * ->i_mmap_rwsem (truncate_pagecache)
74 * ->private_lock (__free_pte->__set_page_dirty_buffers)
75 * ->swap_lock (exclusive_swap_page, others)
79 * ->invalidate_lock (acquired by fs in truncate path)
80 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
84 * ->page_table_lock or pte_lock (various, mainly in memory.c)
85 * ->i_pages lock (arch-dependent flush_dcache_mmap_lock)
88 * ->invalidate_lock (filemap_fault)
89 * ->lock_page (filemap_fault, access_process_vm)
91 * ->i_rwsem (generic_perform_write)
92 * ->mmap_lock (fault_in_readable->do_page_fault)
95 * sb_lock (fs/fs-writeback.c)
96 * ->i_pages lock (__sync_single_inode)
99 * ->anon_vma.lock (vma_adjust)
102 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
104 * ->page_table_lock or pte_lock
105 * ->swap_lock (try_to_unmap_one)
106 * ->private_lock (try_to_unmap_one)
107 * ->i_pages lock (try_to_unmap_one)
108 * ->lruvec->lru_lock (follow_page->mark_page_accessed)
109 * ->lruvec->lru_lock (check_pte_range->isolate_lru_page)
110 * ->private_lock (page_remove_rmap->set_page_dirty)
111 * ->i_pages lock (page_remove_rmap->set_page_dirty)
112 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
113 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
114 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
115 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
116 * ->inode->i_lock (zap_pte_range->set_page_dirty)
117 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
120 * ->tasklist_lock (memory_failure, collect_procs_ao)
123 static void page_cache_delete(struct address_space *mapping,
124 struct folio *folio, void *shadow)
126 XA_STATE(xas, &mapping->i_pages, folio->index);
129 mapping_set_update(&xas, mapping);
131 /* hugetlb pages are represented by a single entry in the xarray */
132 if (!folio_test_hugetlb(folio)) {
133 xas_set_order(&xas, folio->index, folio_order(folio));
134 nr = folio_nr_pages(folio);
137 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
139 xas_store(&xas, shadow);
140 xas_init_marks(&xas);
142 folio->mapping = NULL;
143 /* Leave page->index set: truncation lookup relies upon it */
144 mapping->nrpages -= nr;
147 static void filemap_unaccount_folio(struct address_space *mapping,
153 * if we're uptodate, flush out into the cleancache, otherwise
154 * invalidate any existing cleancache entries. We can't leave
155 * stale data around in the cleancache once our page is gone
157 if (folio_test_uptodate(folio) && folio_test_mappedtodisk(folio))
158 cleancache_put_page(&folio->page);
160 cleancache_invalidate_page(mapping, &folio->page);
162 VM_BUG_ON_FOLIO(folio_mapped(folio), folio);
163 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(folio_mapped(folio))) {
166 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
167 current->comm, folio_pfn(folio));
168 dump_page(&folio->page, "still mapped when deleted");
170 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
172 mapcount = page_mapcount(&folio->page);
173 if (mapping_exiting(mapping) &&
174 folio_ref_count(folio) >= mapcount + 2) {
176 * All vmas have already been torn down, so it's
177 * a good bet that actually the folio is unmapped,
178 * and we'd prefer not to leak it: if we're wrong,
179 * some other bad page check should catch it later.
181 page_mapcount_reset(&folio->page);
182 folio_ref_sub(folio, mapcount);
186 /* hugetlb folios do not participate in page cache accounting. */
187 if (folio_test_hugetlb(folio))
190 nr = folio_nr_pages(folio);
192 __lruvec_stat_mod_folio(folio, NR_FILE_PAGES, -nr);
193 if (folio_test_swapbacked(folio)) {
194 __lruvec_stat_mod_folio(folio, NR_SHMEM, -nr);
195 if (folio_test_pmd_mappable(folio))
196 __lruvec_stat_mod_folio(folio, NR_SHMEM_THPS, -nr);
197 } else if (folio_test_pmd_mappable(folio)) {
198 __lruvec_stat_mod_folio(folio, NR_FILE_THPS, -nr);
199 filemap_nr_thps_dec(mapping);
203 * At this point folio must be either written or cleaned by
204 * truncate. Dirty folio here signals a bug and loss of
207 * This fixes dirty accounting after removing the folio entirely
208 * but leaves the dirty flag set: it has no effect for truncated
209 * folio and anyway will be cleared before returning folio to
212 if (WARN_ON_ONCE(folio_test_dirty(folio)))
213 folio_account_cleaned(folio, mapping,
214 inode_to_wb(mapping->host));
218 * Delete a page from the page cache and free it. Caller has to make
219 * sure the page is locked and that nobody else uses it - or that usage
220 * is safe. The caller must hold the i_pages lock.
222 void __filemap_remove_folio(struct folio *folio, void *shadow)
224 struct address_space *mapping = folio->mapping;
226 trace_mm_filemap_delete_from_page_cache(folio);
227 filemap_unaccount_folio(mapping, folio);
228 page_cache_delete(mapping, folio, shadow);
231 void filemap_free_folio(struct address_space *mapping, struct folio *folio)
233 void (*freepage)(struct page *);
236 freepage = mapping->a_ops->freepage;
238 freepage(&folio->page);
240 if (folio_test_large(folio) && !folio_test_hugetlb(folio))
241 refs = folio_nr_pages(folio);
242 folio_put_refs(folio, refs);
246 * filemap_remove_folio - Remove folio from page cache.
249 * This must be called only on folios that are locked and have been
250 * verified to be in the page cache. It will never put the folio into
251 * the free list because the caller has a reference on the page.
253 void filemap_remove_folio(struct folio *folio)
255 struct address_space *mapping = folio->mapping;
257 BUG_ON(!folio_test_locked(folio));
258 spin_lock(&mapping->host->i_lock);
259 xa_lock_irq(&mapping->i_pages);
260 __filemap_remove_folio(folio, NULL);
261 xa_unlock_irq(&mapping->i_pages);
262 if (mapping_shrinkable(mapping))
263 inode_add_lru(mapping->host);
264 spin_unlock(&mapping->host->i_lock);
266 filemap_free_folio(mapping, folio);
270 * page_cache_delete_batch - delete several folios from page cache
271 * @mapping: the mapping to which folios belong
272 * @fbatch: batch of folios to delete
274 * The function walks over mapping->i_pages and removes folios passed in
275 * @fbatch from the mapping. The function expects @fbatch to be sorted
276 * by page index and is optimised for it to be dense.
277 * It tolerates holes in @fbatch (mapping entries at those indices are not
280 * The function expects the i_pages lock to be held.
282 static void page_cache_delete_batch(struct address_space *mapping,
283 struct folio_batch *fbatch)
285 XA_STATE(xas, &mapping->i_pages, fbatch->folios[0]->index);
286 long total_pages = 0;
290 mapping_set_update(&xas, mapping);
291 xas_for_each(&xas, folio, ULONG_MAX) {
292 if (i >= folio_batch_count(fbatch))
295 /* A swap/dax/shadow entry got inserted? Skip it. */
296 if (xa_is_value(folio))
299 * A page got inserted in our range? Skip it. We have our
300 * pages locked so they are protected from being removed.
301 * If we see a page whose index is higher than ours, it
302 * means our page has been removed, which shouldn't be
303 * possible because we're holding the PageLock.
305 if (folio != fbatch->folios[i]) {
306 VM_BUG_ON_FOLIO(folio->index >
307 fbatch->folios[i]->index, folio);
311 WARN_ON_ONCE(!folio_test_locked(folio));
313 folio->mapping = NULL;
314 /* Leave folio->index set: truncation lookup relies on it */
317 xas_store(&xas, NULL);
318 total_pages += folio_nr_pages(folio);
320 mapping->nrpages -= total_pages;
323 void delete_from_page_cache_batch(struct address_space *mapping,
324 struct folio_batch *fbatch)
328 if (!folio_batch_count(fbatch))
331 spin_lock(&mapping->host->i_lock);
332 xa_lock_irq(&mapping->i_pages);
333 for (i = 0; i < folio_batch_count(fbatch); i++) {
334 struct folio *folio = fbatch->folios[i];
336 trace_mm_filemap_delete_from_page_cache(folio);
337 filemap_unaccount_folio(mapping, folio);
339 page_cache_delete_batch(mapping, fbatch);
340 xa_unlock_irq(&mapping->i_pages);
341 if (mapping_shrinkable(mapping))
342 inode_add_lru(mapping->host);
343 spin_unlock(&mapping->host->i_lock);
345 for (i = 0; i < folio_batch_count(fbatch); i++)
346 filemap_free_folio(mapping, fbatch->folios[i]);
349 int filemap_check_errors(struct address_space *mapping)
352 /* Check for outstanding write errors */
353 if (test_bit(AS_ENOSPC, &mapping->flags) &&
354 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
356 if (test_bit(AS_EIO, &mapping->flags) &&
357 test_and_clear_bit(AS_EIO, &mapping->flags))
361 EXPORT_SYMBOL(filemap_check_errors);
363 static int filemap_check_and_keep_errors(struct address_space *mapping)
365 /* Check for outstanding write errors */
366 if (test_bit(AS_EIO, &mapping->flags))
368 if (test_bit(AS_ENOSPC, &mapping->flags))
374 * filemap_fdatawrite_wbc - start writeback on mapping dirty pages in range
375 * @mapping: address space structure to write
376 * @wbc: the writeback_control controlling the writeout
378 * Call writepages on the mapping using the provided wbc to control the
381 * Return: %0 on success, negative error code otherwise.
383 int filemap_fdatawrite_wbc(struct address_space *mapping,
384 struct writeback_control *wbc)
388 if (!mapping_can_writeback(mapping) ||
389 !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
392 wbc_attach_fdatawrite_inode(wbc, mapping->host);
393 ret = do_writepages(mapping, wbc);
394 wbc_detach_inode(wbc);
397 EXPORT_SYMBOL(filemap_fdatawrite_wbc);
400 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
401 * @mapping: address space structure to write
402 * @start: offset in bytes where the range starts
403 * @end: offset in bytes where the range ends (inclusive)
404 * @sync_mode: enable synchronous operation
406 * Start writeback against all of a mapping's dirty pages that lie
407 * within the byte offsets <start, end> inclusive.
409 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
410 * opposed to a regular memory cleansing writeback. The difference between
411 * these two operations is that if a dirty page/buffer is encountered, it must
412 * be waited upon, and not just skipped over.
414 * Return: %0 on success, negative error code otherwise.
416 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
417 loff_t end, int sync_mode)
419 struct writeback_control wbc = {
420 .sync_mode = sync_mode,
421 .nr_to_write = LONG_MAX,
422 .range_start = start,
426 return filemap_fdatawrite_wbc(mapping, &wbc);
429 static inline int __filemap_fdatawrite(struct address_space *mapping,
432 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
435 int filemap_fdatawrite(struct address_space *mapping)
437 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
439 EXPORT_SYMBOL(filemap_fdatawrite);
441 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
444 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
446 EXPORT_SYMBOL(filemap_fdatawrite_range);
449 * filemap_flush - mostly a non-blocking flush
450 * @mapping: target address_space
452 * This is a mostly non-blocking flush. Not suitable for data-integrity
453 * purposes - I/O may not be started against all dirty pages.
455 * Return: %0 on success, negative error code otherwise.
457 int filemap_flush(struct address_space *mapping)
459 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
461 EXPORT_SYMBOL(filemap_flush);
464 * filemap_range_has_page - check if a page exists in range.
465 * @mapping: address space within which to check
466 * @start_byte: offset in bytes where the range starts
467 * @end_byte: offset in bytes where the range ends (inclusive)
469 * Find at least one page in the range supplied, usually used to check if
470 * direct writing in this range will trigger a writeback.
472 * Return: %true if at least one page exists in the specified range,
475 bool filemap_range_has_page(struct address_space *mapping,
476 loff_t start_byte, loff_t end_byte)
479 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
480 pgoff_t max = end_byte >> PAGE_SHIFT;
482 if (end_byte < start_byte)
487 page = xas_find(&xas, max);
488 if (xas_retry(&xas, page))
490 /* Shadow entries don't count */
491 if (xa_is_value(page))
494 * We don't need to try to pin this page; we're about to
495 * release the RCU lock anyway. It is enough to know that
496 * there was a page here recently.
504 EXPORT_SYMBOL(filemap_range_has_page);
506 static void __filemap_fdatawait_range(struct address_space *mapping,
507 loff_t start_byte, loff_t end_byte)
509 pgoff_t index = start_byte >> PAGE_SHIFT;
510 pgoff_t end = end_byte >> PAGE_SHIFT;
514 if (end_byte < start_byte)
518 while (index <= end) {
521 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
522 end, PAGECACHE_TAG_WRITEBACK);
526 for (i = 0; i < nr_pages; i++) {
527 struct page *page = pvec.pages[i];
529 wait_on_page_writeback(page);
530 ClearPageError(page);
532 pagevec_release(&pvec);
538 * filemap_fdatawait_range - wait for writeback to complete
539 * @mapping: address space structure to wait for
540 * @start_byte: offset in bytes where the range starts
541 * @end_byte: offset in bytes where the range ends (inclusive)
543 * Walk the list of under-writeback pages of the given address space
544 * in the given range and wait for all of them. Check error status of
545 * the address space and return it.
547 * Since the error status of the address space is cleared by this function,
548 * callers are responsible for checking the return value and handling and/or
549 * reporting the error.
551 * Return: error status of the address space.
553 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
556 __filemap_fdatawait_range(mapping, start_byte, end_byte);
557 return filemap_check_errors(mapping);
559 EXPORT_SYMBOL(filemap_fdatawait_range);
562 * filemap_fdatawait_range_keep_errors - wait for writeback to complete
563 * @mapping: address space structure to wait for
564 * @start_byte: offset in bytes where the range starts
565 * @end_byte: offset in bytes where the range ends (inclusive)
567 * Walk the list of under-writeback pages of the given address space in the
568 * given range and wait for all of them. Unlike filemap_fdatawait_range(),
569 * this function does not clear error status of the address space.
571 * Use this function if callers don't handle errors themselves. Expected
572 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
575 int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
576 loff_t start_byte, loff_t end_byte)
578 __filemap_fdatawait_range(mapping, start_byte, end_byte);
579 return filemap_check_and_keep_errors(mapping);
581 EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
584 * file_fdatawait_range - wait for writeback to complete
585 * @file: file pointing to address space structure to wait for
586 * @start_byte: offset in bytes where the range starts
587 * @end_byte: offset in bytes where the range ends (inclusive)
589 * Walk the list of under-writeback pages of the address space that file
590 * refers to, in the given range and wait for all of them. Check error
591 * status of the address space vs. the file->f_wb_err cursor and return it.
593 * Since the error status of the file is advanced by this function,
594 * callers are responsible for checking the return value and handling and/or
595 * reporting the error.
597 * Return: error status of the address space vs. the file->f_wb_err cursor.
599 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
601 struct address_space *mapping = file->f_mapping;
603 __filemap_fdatawait_range(mapping, start_byte, end_byte);
604 return file_check_and_advance_wb_err(file);
606 EXPORT_SYMBOL(file_fdatawait_range);
609 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
610 * @mapping: address space structure to wait for
612 * Walk the list of under-writeback pages of the given address space
613 * and wait for all of them. Unlike filemap_fdatawait(), this function
614 * does not clear error status of the address space.
616 * Use this function if callers don't handle errors themselves. Expected
617 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
620 * Return: error status of the address space.
622 int filemap_fdatawait_keep_errors(struct address_space *mapping)
624 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
625 return filemap_check_and_keep_errors(mapping);
627 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
629 /* Returns true if writeback might be needed or already in progress. */
630 static bool mapping_needs_writeback(struct address_space *mapping)
632 return mapping->nrpages;
635 bool filemap_range_has_writeback(struct address_space *mapping,
636 loff_t start_byte, loff_t end_byte)
638 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
639 pgoff_t max = end_byte >> PAGE_SHIFT;
642 if (end_byte < start_byte)
646 xas_for_each(&xas, page, max) {
647 if (xas_retry(&xas, page))
649 if (xa_is_value(page))
651 if (PageDirty(page) || PageLocked(page) || PageWriteback(page))
657 EXPORT_SYMBOL_GPL(filemap_range_has_writeback);
660 * filemap_write_and_wait_range - write out & wait on a file range
661 * @mapping: the address_space for the pages
662 * @lstart: offset in bytes where the range starts
663 * @lend: offset in bytes where the range ends (inclusive)
665 * Write out and wait upon file offsets lstart->lend, inclusive.
667 * Note that @lend is inclusive (describes the last byte to be written) so
668 * that this function can be used to write to the very end-of-file (end = -1).
670 * Return: error status of the address space.
672 int filemap_write_and_wait_range(struct address_space *mapping,
673 loff_t lstart, loff_t lend)
677 if (mapping_needs_writeback(mapping)) {
678 err = __filemap_fdatawrite_range(mapping, lstart, lend,
681 * Even if the above returned error, the pages may be
682 * written partially (e.g. -ENOSPC), so we wait for it.
683 * But the -EIO is special case, it may indicate the worst
684 * thing (e.g. bug) happened, so we avoid waiting for it.
687 int err2 = filemap_fdatawait_range(mapping,
692 /* Clear any previously stored errors */
693 filemap_check_errors(mapping);
696 err = filemap_check_errors(mapping);
700 EXPORT_SYMBOL(filemap_write_and_wait_range);
702 void __filemap_set_wb_err(struct address_space *mapping, int err)
704 errseq_t eseq = errseq_set(&mapping->wb_err, err);
706 trace_filemap_set_wb_err(mapping, eseq);
708 EXPORT_SYMBOL(__filemap_set_wb_err);
711 * file_check_and_advance_wb_err - report wb error (if any) that was previously
712 * and advance wb_err to current one
713 * @file: struct file on which the error is being reported
715 * When userland calls fsync (or something like nfsd does the equivalent), we
716 * want to report any writeback errors that occurred since the last fsync (or
717 * since the file was opened if there haven't been any).
719 * Grab the wb_err from the mapping. If it matches what we have in the file,
720 * then just quickly return 0. The file is all caught up.
722 * If it doesn't match, then take the mapping value, set the "seen" flag in
723 * it and try to swap it into place. If it works, or another task beat us
724 * to it with the new value, then update the f_wb_err and return the error
725 * portion. The error at this point must be reported via proper channels
726 * (a'la fsync, or NFS COMMIT operation, etc.).
728 * While we handle mapping->wb_err with atomic operations, the f_wb_err
729 * value is protected by the f_lock since we must ensure that it reflects
730 * the latest value swapped in for this file descriptor.
732 * Return: %0 on success, negative error code otherwise.
734 int file_check_and_advance_wb_err(struct file *file)
737 errseq_t old = READ_ONCE(file->f_wb_err);
738 struct address_space *mapping = file->f_mapping;
740 /* Locklessly handle the common case where nothing has changed */
741 if (errseq_check(&mapping->wb_err, old)) {
742 /* Something changed, must use slow path */
743 spin_lock(&file->f_lock);
744 old = file->f_wb_err;
745 err = errseq_check_and_advance(&mapping->wb_err,
747 trace_file_check_and_advance_wb_err(file, old);
748 spin_unlock(&file->f_lock);
752 * We're mostly using this function as a drop in replacement for
753 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
754 * that the legacy code would have had on these flags.
756 clear_bit(AS_EIO, &mapping->flags);
757 clear_bit(AS_ENOSPC, &mapping->flags);
760 EXPORT_SYMBOL(file_check_and_advance_wb_err);
763 * file_write_and_wait_range - write out & wait on a file range
764 * @file: file pointing to address_space with pages
765 * @lstart: offset in bytes where the range starts
766 * @lend: offset in bytes where the range ends (inclusive)
768 * Write out and wait upon file offsets lstart->lend, inclusive.
770 * Note that @lend is inclusive (describes the last byte to be written) so
771 * that this function can be used to write to the very end-of-file (end = -1).
773 * After writing out and waiting on the data, we check and advance the
774 * f_wb_err cursor to the latest value, and return any errors detected there.
776 * Return: %0 on success, negative error code otherwise.
778 int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
781 struct address_space *mapping = file->f_mapping;
783 if (mapping_needs_writeback(mapping)) {
784 err = __filemap_fdatawrite_range(mapping, lstart, lend,
786 /* See comment of filemap_write_and_wait() */
788 __filemap_fdatawait_range(mapping, lstart, lend);
790 err2 = file_check_and_advance_wb_err(file);
795 EXPORT_SYMBOL(file_write_and_wait_range);
798 * replace_page_cache_page - replace a pagecache page with a new one
799 * @old: page to be replaced
800 * @new: page to replace with
802 * This function replaces a page in the pagecache with a new one. On
803 * success it acquires the pagecache reference for the new page and
804 * drops it for the old page. Both the old and new pages must be
805 * locked. This function does not add the new page to the LRU, the
806 * caller must do that.
808 * The remove + add is atomic. This function cannot fail.
810 void replace_page_cache_page(struct page *old, struct page *new)
812 struct folio *fold = page_folio(old);
813 struct folio *fnew = page_folio(new);
814 struct address_space *mapping = old->mapping;
815 void (*freepage)(struct page *) = mapping->a_ops->freepage;
816 pgoff_t offset = old->index;
817 XA_STATE(xas, &mapping->i_pages, offset);
819 VM_BUG_ON_PAGE(!PageLocked(old), old);
820 VM_BUG_ON_PAGE(!PageLocked(new), new);
821 VM_BUG_ON_PAGE(new->mapping, new);
824 new->mapping = mapping;
827 mem_cgroup_migrate(fold, fnew);
830 xas_store(&xas, new);
833 /* hugetlb pages do not participate in page cache accounting. */
835 __dec_lruvec_page_state(old, NR_FILE_PAGES);
837 __inc_lruvec_page_state(new, NR_FILE_PAGES);
838 if (PageSwapBacked(old))
839 __dec_lruvec_page_state(old, NR_SHMEM);
840 if (PageSwapBacked(new))
841 __inc_lruvec_page_state(new, NR_SHMEM);
842 xas_unlock_irq(&xas);
847 EXPORT_SYMBOL_GPL(replace_page_cache_page);
849 noinline int __filemap_add_folio(struct address_space *mapping,
850 struct folio *folio, pgoff_t index, gfp_t gfp, void **shadowp)
852 XA_STATE(xas, &mapping->i_pages, index);
853 int huge = folio_test_hugetlb(folio);
855 bool charged = false;
857 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
858 VM_BUG_ON_FOLIO(folio_test_swapbacked(folio), folio);
859 mapping_set_update(&xas, mapping);
862 folio->mapping = mapping;
863 folio->index = index;
866 error = mem_cgroup_charge(folio, NULL, gfp);
867 VM_BUG_ON_FOLIO(index & (folio_nr_pages(folio) - 1), folio);
873 gfp &= GFP_RECLAIM_MASK;
876 unsigned int order = xa_get_order(xas.xa, xas.xa_index);
877 void *entry, *old = NULL;
879 if (order > folio_order(folio))
880 xas_split_alloc(&xas, xa_load(xas.xa, xas.xa_index),
883 xas_for_each_conflict(&xas, entry) {
885 if (!xa_is_value(entry)) {
886 xas_set_err(&xas, -EEXIST);
894 /* entry may have been split before we acquired lock */
895 order = xa_get_order(xas.xa, xas.xa_index);
896 if (order > folio_order(folio)) {
897 xas_split(&xas, old, order);
902 xas_store(&xas, folio);
908 /* hugetlb pages do not participate in page cache accounting */
910 __lruvec_stat_add_folio(folio, NR_FILE_PAGES);
912 xas_unlock_irq(&xas);
913 } while (xas_nomem(&xas, gfp));
915 if (xas_error(&xas)) {
916 error = xas_error(&xas);
918 mem_cgroup_uncharge(folio);
922 trace_mm_filemap_add_to_page_cache(folio);
925 folio->mapping = NULL;
926 /* Leave page->index set: truncation relies upon it */
930 ALLOW_ERROR_INJECTION(__filemap_add_folio, ERRNO);
933 * add_to_page_cache_locked - add a locked page to the pagecache
935 * @mapping: the page's address_space
936 * @offset: page index
937 * @gfp_mask: page allocation mode
939 * This function is used to add a page to the pagecache. It must be locked.
940 * This function does not add the page to the LRU. The caller must do that.
942 * Return: %0 on success, negative error code otherwise.
944 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
945 pgoff_t offset, gfp_t gfp_mask)
947 return __filemap_add_folio(mapping, page_folio(page), offset,
950 EXPORT_SYMBOL(add_to_page_cache_locked);
952 int filemap_add_folio(struct address_space *mapping, struct folio *folio,
953 pgoff_t index, gfp_t gfp)
958 __folio_set_locked(folio);
959 ret = __filemap_add_folio(mapping, folio, index, gfp, &shadow);
961 __folio_clear_locked(folio);
964 * The folio might have been evicted from cache only
965 * recently, in which case it should be activated like
966 * any other repeatedly accessed folio.
967 * The exception is folios getting rewritten; evicting other
968 * data from the working set, only to cache data that will
969 * get overwritten with something else, is a waste of memory.
971 WARN_ON_ONCE(folio_test_active(folio));
972 if (!(gfp & __GFP_WRITE) && shadow)
973 workingset_refault(folio, shadow);
974 folio_add_lru(folio);
978 EXPORT_SYMBOL_GPL(filemap_add_folio);
981 struct folio *filemap_alloc_folio(gfp_t gfp, unsigned int order)
986 if (cpuset_do_page_mem_spread()) {
987 unsigned int cpuset_mems_cookie;
989 cpuset_mems_cookie = read_mems_allowed_begin();
990 n = cpuset_mem_spread_node();
991 folio = __folio_alloc_node(gfp, order, n);
992 } while (!folio && read_mems_allowed_retry(cpuset_mems_cookie));
996 return folio_alloc(gfp, order);
998 EXPORT_SYMBOL(filemap_alloc_folio);
1002 * filemap_invalidate_lock_two - lock invalidate_lock for two mappings
1004 * Lock exclusively invalidate_lock of any passed mapping that is not NULL.
1006 * @mapping1: the first mapping to lock
1007 * @mapping2: the second mapping to lock
1009 void filemap_invalidate_lock_two(struct address_space *mapping1,
1010 struct address_space *mapping2)
1012 if (mapping1 > mapping2)
1013 swap(mapping1, mapping2);
1015 down_write(&mapping1->invalidate_lock);
1016 if (mapping2 && mapping1 != mapping2)
1017 down_write_nested(&mapping2->invalidate_lock, 1);
1019 EXPORT_SYMBOL(filemap_invalidate_lock_two);
1022 * filemap_invalidate_unlock_two - unlock invalidate_lock for two mappings
1024 * Unlock exclusive invalidate_lock of any passed mapping that is not NULL.
1026 * @mapping1: the first mapping to unlock
1027 * @mapping2: the second mapping to unlock
1029 void filemap_invalidate_unlock_two(struct address_space *mapping1,
1030 struct address_space *mapping2)
1033 up_write(&mapping1->invalidate_lock);
1034 if (mapping2 && mapping1 != mapping2)
1035 up_write(&mapping2->invalidate_lock);
1037 EXPORT_SYMBOL(filemap_invalidate_unlock_two);
1040 * In order to wait for pages to become available there must be
1041 * waitqueues associated with pages. By using a hash table of
1042 * waitqueues where the bucket discipline is to maintain all
1043 * waiters on the same queue and wake all when any of the pages
1044 * become available, and for the woken contexts to check to be
1045 * sure the appropriate page became available, this saves space
1046 * at a cost of "thundering herd" phenomena during rare hash
1049 #define PAGE_WAIT_TABLE_BITS 8
1050 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
1051 static wait_queue_head_t folio_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
1053 static wait_queue_head_t *folio_waitqueue(struct folio *folio)
1055 return &folio_wait_table[hash_ptr(folio, PAGE_WAIT_TABLE_BITS)];
1058 void __init pagecache_init(void)
1062 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1063 init_waitqueue_head(&folio_wait_table[i]);
1065 page_writeback_init();
1069 * The page wait code treats the "wait->flags" somewhat unusually, because
1070 * we have multiple different kinds of waits, not just the usual "exclusive"
1075 * (a) no special bits set:
1077 * We're just waiting for the bit to be released, and when a waker
1078 * calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up,
1079 * and remove it from the wait queue.
1081 * Simple and straightforward.
1083 * (b) WQ_FLAG_EXCLUSIVE:
1085 * The waiter is waiting to get the lock, and only one waiter should
1086 * be woken up to avoid any thundering herd behavior. We'll set the
1087 * WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue.
1089 * This is the traditional exclusive wait.
1091 * (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
1093 * The waiter is waiting to get the bit, and additionally wants the
1094 * lock to be transferred to it for fair lock behavior. If the lock
1095 * cannot be taken, we stop walking the wait queue without waking
1098 * This is the "fair lock handoff" case, and in addition to setting
1099 * WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see
1100 * that it now has the lock.
1102 static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
1105 struct wait_page_key *key = arg;
1106 struct wait_page_queue *wait_page
1107 = container_of(wait, struct wait_page_queue, wait);
1109 if (!wake_page_match(wait_page, key))
1113 * If it's a lock handoff wait, we get the bit for it, and
1114 * stop walking (and do not wake it up) if we can't.
1116 flags = wait->flags;
1117 if (flags & WQ_FLAG_EXCLUSIVE) {
1118 if (test_bit(key->bit_nr, &key->folio->flags))
1120 if (flags & WQ_FLAG_CUSTOM) {
1121 if (test_and_set_bit(key->bit_nr, &key->folio->flags))
1123 flags |= WQ_FLAG_DONE;
1128 * We are holding the wait-queue lock, but the waiter that
1129 * is waiting for this will be checking the flags without
1132 * So update the flags atomically, and wake up the waiter
1133 * afterwards to avoid any races. This store-release pairs
1134 * with the load-acquire in folio_wait_bit_common().
1136 smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
1137 wake_up_state(wait->private, mode);
1140 * Ok, we have successfully done what we're waiting for,
1141 * and we can unconditionally remove the wait entry.
1143 * Note that this pairs with the "finish_wait()" in the
1144 * waiter, and has to be the absolute last thing we do.
1145 * After this list_del_init(&wait->entry) the wait entry
1146 * might be de-allocated and the process might even have
1149 list_del_init_careful(&wait->entry);
1150 return (flags & WQ_FLAG_EXCLUSIVE) != 0;
1153 static void folio_wake_bit(struct folio *folio, int bit_nr)
1155 wait_queue_head_t *q = folio_waitqueue(folio);
1156 struct wait_page_key key;
1157 unsigned long flags;
1158 wait_queue_entry_t bookmark;
1161 key.bit_nr = bit_nr;
1165 bookmark.private = NULL;
1166 bookmark.func = NULL;
1167 INIT_LIST_HEAD(&bookmark.entry);
1169 spin_lock_irqsave(&q->lock, flags);
1170 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1172 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1174 * Take a breather from holding the lock,
1175 * allow pages that finish wake up asynchronously
1176 * to acquire the lock and remove themselves
1179 spin_unlock_irqrestore(&q->lock, flags);
1181 spin_lock_irqsave(&q->lock, flags);
1182 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1186 * It is possible for other pages to have collided on the waitqueue
1187 * hash, so in that case check for a page match. That prevents a long-
1190 * It is still possible to miss a case here, when we woke page waiters
1191 * and removed them from the waitqueue, but there are still other
1194 if (!waitqueue_active(q) || !key.page_match) {
1195 folio_clear_waiters(folio);
1197 * It's possible to miss clearing Waiters here, when we woke
1198 * our page waiters, but the hashed waitqueue has waiters for
1199 * other pages on it.
1201 * That's okay, it's a rare case. The next waker will clear it.
1204 spin_unlock_irqrestore(&q->lock, flags);
1207 static void folio_wake(struct folio *folio, int bit)
1209 if (!folio_test_waiters(folio))
1211 folio_wake_bit(folio, bit);
1215 * A choice of three behaviors for folio_wait_bit_common():
1218 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
1219 * __folio_lock() waiting on then setting PG_locked.
1221 SHARED, /* Hold ref to page and check the bit when woken, like
1222 * folio_wait_writeback() waiting on PG_writeback.
1224 DROP, /* Drop ref to page before wait, no check when woken,
1225 * like folio_put_wait_locked() on PG_locked.
1230 * Attempt to check (or get) the folio flag, and mark us done
1233 static inline bool folio_trylock_flag(struct folio *folio, int bit_nr,
1234 struct wait_queue_entry *wait)
1236 if (wait->flags & WQ_FLAG_EXCLUSIVE) {
1237 if (test_and_set_bit(bit_nr, &folio->flags))
1239 } else if (test_bit(bit_nr, &folio->flags))
1242 wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
1246 /* How many times do we accept lock stealing from under a waiter? */
1247 int sysctl_page_lock_unfairness = 5;
1249 static inline int folio_wait_bit_common(struct folio *folio, int bit_nr,
1250 int state, enum behavior behavior)
1252 wait_queue_head_t *q = folio_waitqueue(folio);
1253 int unfairness = sysctl_page_lock_unfairness;
1254 struct wait_page_queue wait_page;
1255 wait_queue_entry_t *wait = &wait_page.wait;
1256 bool thrashing = false;
1257 bool delayacct = false;
1258 unsigned long pflags;
1260 if (bit_nr == PG_locked &&
1261 !folio_test_uptodate(folio) && folio_test_workingset(folio)) {
1262 if (!folio_test_swapbacked(folio)) {
1263 delayacct_thrashing_start();
1266 psi_memstall_enter(&pflags);
1271 wait->func = wake_page_function;
1272 wait_page.folio = folio;
1273 wait_page.bit_nr = bit_nr;
1277 if (behavior == EXCLUSIVE) {
1278 wait->flags = WQ_FLAG_EXCLUSIVE;
1279 if (--unfairness < 0)
1280 wait->flags |= WQ_FLAG_CUSTOM;
1284 * Do one last check whether we can get the
1285 * page bit synchronously.
1287 * Do the folio_set_waiters() marking before that
1288 * to let any waker we _just_ missed know they
1289 * need to wake us up (otherwise they'll never
1290 * even go to the slow case that looks at the
1291 * page queue), and add ourselves to the wait
1292 * queue if we need to sleep.
1294 * This part needs to be done under the queue
1295 * lock to avoid races.
1297 spin_lock_irq(&q->lock);
1298 folio_set_waiters(folio);
1299 if (!folio_trylock_flag(folio, bit_nr, wait))
1300 __add_wait_queue_entry_tail(q, wait);
1301 spin_unlock_irq(&q->lock);
1304 * From now on, all the logic will be based on
1305 * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to
1306 * see whether the page bit testing has already
1307 * been done by the wake function.
1309 * We can drop our reference to the folio.
1311 if (behavior == DROP)
1315 * Note that until the "finish_wait()", or until
1316 * we see the WQ_FLAG_WOKEN flag, we need to
1317 * be very careful with the 'wait->flags', because
1318 * we may race with a waker that sets them.
1323 set_current_state(state);
1325 /* Loop until we've been woken or interrupted */
1326 flags = smp_load_acquire(&wait->flags);
1327 if (!(flags & WQ_FLAG_WOKEN)) {
1328 if (signal_pending_state(state, current))
1335 /* If we were non-exclusive, we're done */
1336 if (behavior != EXCLUSIVE)
1339 /* If the waker got the lock for us, we're done */
1340 if (flags & WQ_FLAG_DONE)
1344 * Otherwise, if we're getting the lock, we need to
1345 * try to get it ourselves.
1347 * And if that fails, we'll have to retry this all.
1349 if (unlikely(test_and_set_bit(bit_nr, folio_flags(folio, 0))))
1352 wait->flags |= WQ_FLAG_DONE;
1357 * If a signal happened, this 'finish_wait()' may remove the last
1358 * waiter from the wait-queues, but the folio waiters bit will remain
1359 * set. That's ok. The next wakeup will take care of it, and trying
1360 * to do it here would be difficult and prone to races.
1362 finish_wait(q, wait);
1366 delayacct_thrashing_end();
1367 psi_memstall_leave(&pflags);
1371 * NOTE! The wait->flags weren't stable until we've done the
1372 * 'finish_wait()', and we could have exited the loop above due
1373 * to a signal, and had a wakeup event happen after the signal
1374 * test but before the 'finish_wait()'.
1376 * So only after the finish_wait() can we reliably determine
1377 * if we got woken up or not, so we can now figure out the final
1378 * return value based on that state without races.
1380 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
1381 * waiter, but an exclusive one requires WQ_FLAG_DONE.
1383 if (behavior == EXCLUSIVE)
1384 return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
1386 return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
1389 void folio_wait_bit(struct folio *folio, int bit_nr)
1391 folio_wait_bit_common(folio, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
1393 EXPORT_SYMBOL(folio_wait_bit);
1395 int folio_wait_bit_killable(struct folio *folio, int bit_nr)
1397 return folio_wait_bit_common(folio, bit_nr, TASK_KILLABLE, SHARED);
1399 EXPORT_SYMBOL(folio_wait_bit_killable);
1402 * folio_put_wait_locked - Drop a reference and wait for it to be unlocked
1403 * @folio: The folio to wait for.
1404 * @state: The sleep state (TASK_KILLABLE, TASK_UNINTERRUPTIBLE, etc).
1406 * The caller should hold a reference on @folio. They expect the page to
1407 * become unlocked relatively soon, but do not wish to hold up migration
1408 * (for example) by holding the reference while waiting for the folio to
1409 * come unlocked. After this function returns, the caller should not
1410 * dereference @folio.
1412 * Return: 0 if the folio was unlocked or -EINTR if interrupted by a signal.
1414 int folio_put_wait_locked(struct folio *folio, int state)
1416 return folio_wait_bit_common(folio, PG_locked, state, DROP);
1420 * folio_add_wait_queue - Add an arbitrary waiter to a folio's wait queue
1421 * @folio: Folio defining the wait queue of interest
1422 * @waiter: Waiter to add to the queue
1424 * Add an arbitrary @waiter to the wait queue for the nominated @folio.
1426 void folio_add_wait_queue(struct folio *folio, wait_queue_entry_t *waiter)
1428 wait_queue_head_t *q = folio_waitqueue(folio);
1429 unsigned long flags;
1431 spin_lock_irqsave(&q->lock, flags);
1432 __add_wait_queue_entry_tail(q, waiter);
1433 folio_set_waiters(folio);
1434 spin_unlock_irqrestore(&q->lock, flags);
1436 EXPORT_SYMBOL_GPL(folio_add_wait_queue);
1438 #ifndef clear_bit_unlock_is_negative_byte
1441 * PG_waiters is the high bit in the same byte as PG_lock.
1443 * On x86 (and on many other architectures), we can clear PG_lock and
1444 * test the sign bit at the same time. But if the architecture does
1445 * not support that special operation, we just do this all by hand
1448 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1449 * being cleared, but a memory barrier should be unnecessary since it is
1450 * in the same byte as PG_locked.
1452 static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1454 clear_bit_unlock(nr, mem);
1455 /* smp_mb__after_atomic(); */
1456 return test_bit(PG_waiters, mem);
1462 * folio_unlock - Unlock a locked folio.
1463 * @folio: The folio.
1465 * Unlocks the folio and wakes up any thread sleeping on the page lock.
1467 * Context: May be called from interrupt or process context. May not be
1468 * called from NMI context.
1470 void folio_unlock(struct folio *folio)
1472 /* Bit 7 allows x86 to check the byte's sign bit */
1473 BUILD_BUG_ON(PG_waiters != 7);
1474 BUILD_BUG_ON(PG_locked > 7);
1475 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
1476 if (clear_bit_unlock_is_negative_byte(PG_locked, folio_flags(folio, 0)))
1477 folio_wake_bit(folio, PG_locked);
1479 EXPORT_SYMBOL(folio_unlock);
1482 * folio_end_private_2 - Clear PG_private_2 and wake any waiters.
1483 * @folio: The folio.
1485 * Clear the PG_private_2 bit on a folio and wake up any sleepers waiting for
1486 * it. The folio reference held for PG_private_2 being set is released.
1488 * This is, for example, used when a netfs folio is being written to a local
1489 * disk cache, thereby allowing writes to the cache for the same folio to be
1492 void folio_end_private_2(struct folio *folio)
1494 VM_BUG_ON_FOLIO(!folio_test_private_2(folio), folio);
1495 clear_bit_unlock(PG_private_2, folio_flags(folio, 0));
1496 folio_wake_bit(folio, PG_private_2);
1499 EXPORT_SYMBOL(folio_end_private_2);
1502 * folio_wait_private_2 - Wait for PG_private_2 to be cleared on a folio.
1503 * @folio: The folio to wait on.
1505 * Wait for PG_private_2 (aka PG_fscache) to be cleared on a folio.
1507 void folio_wait_private_2(struct folio *folio)
1509 while (folio_test_private_2(folio))
1510 folio_wait_bit(folio, PG_private_2);
1512 EXPORT_SYMBOL(folio_wait_private_2);
1515 * folio_wait_private_2_killable - Wait for PG_private_2 to be cleared on a folio.
1516 * @folio: The folio to wait on.
1518 * Wait for PG_private_2 (aka PG_fscache) to be cleared on a folio or until a
1519 * fatal signal is received by the calling task.
1522 * - 0 if successful.
1523 * - -EINTR if a fatal signal was encountered.
1525 int folio_wait_private_2_killable(struct folio *folio)
1529 while (folio_test_private_2(folio)) {
1530 ret = folio_wait_bit_killable(folio, PG_private_2);
1537 EXPORT_SYMBOL(folio_wait_private_2_killable);
1540 * folio_end_writeback - End writeback against a folio.
1541 * @folio: The folio.
1543 void folio_end_writeback(struct folio *folio)
1546 * folio_test_clear_reclaim() could be used here but it is an
1547 * atomic operation and overkill in this particular case. Failing
1548 * to shuffle a folio marked for immediate reclaim is too mild
1549 * a gain to justify taking an atomic operation penalty at the
1550 * end of every folio writeback.
1552 if (folio_test_reclaim(folio)) {
1553 folio_clear_reclaim(folio);
1554 folio_rotate_reclaimable(folio);
1558 * Writeback does not hold a folio reference of its own, relying
1559 * on truncation to wait for the clearing of PG_writeback.
1560 * But here we must make sure that the folio is not freed and
1561 * reused before the folio_wake().
1564 if (!__folio_end_writeback(folio))
1567 smp_mb__after_atomic();
1568 folio_wake(folio, PG_writeback);
1569 acct_reclaim_writeback(folio);
1572 EXPORT_SYMBOL(folio_end_writeback);
1575 * After completing I/O on a page, call this routine to update the page
1576 * flags appropriately
1578 void page_endio(struct page *page, bool is_write, int err)
1582 SetPageUptodate(page);
1584 ClearPageUptodate(page);
1590 struct address_space *mapping;
1593 mapping = page_mapping(page);
1595 mapping_set_error(mapping, err);
1597 end_page_writeback(page);
1600 EXPORT_SYMBOL_GPL(page_endio);
1603 * __folio_lock - Get a lock on the folio, assuming we need to sleep to get it.
1604 * @folio: The folio to lock
1606 void __folio_lock(struct folio *folio)
1608 folio_wait_bit_common(folio, PG_locked, TASK_UNINTERRUPTIBLE,
1611 EXPORT_SYMBOL(__folio_lock);
1613 int __folio_lock_killable(struct folio *folio)
1615 return folio_wait_bit_common(folio, PG_locked, TASK_KILLABLE,
1618 EXPORT_SYMBOL_GPL(__folio_lock_killable);
1620 static int __folio_lock_async(struct folio *folio, struct wait_page_queue *wait)
1622 struct wait_queue_head *q = folio_waitqueue(folio);
1625 wait->folio = folio;
1626 wait->bit_nr = PG_locked;
1628 spin_lock_irq(&q->lock);
1629 __add_wait_queue_entry_tail(q, &wait->wait);
1630 folio_set_waiters(folio);
1631 ret = !folio_trylock(folio);
1633 * If we were successful now, we know we're still on the
1634 * waitqueue as we're still under the lock. This means it's
1635 * safe to remove and return success, we know the callback
1636 * isn't going to trigger.
1639 __remove_wait_queue(q, &wait->wait);
1642 spin_unlock_irq(&q->lock);
1648 * true - folio is locked; mmap_lock is still held.
1649 * false - folio is not locked.
1650 * mmap_lock has been released (mmap_read_unlock(), unless flags had both
1651 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1652 * which case mmap_lock is still held.
1654 * If neither ALLOW_RETRY nor KILLABLE are set, will always return true
1655 * with the folio locked and the mmap_lock unperturbed.
1657 bool __folio_lock_or_retry(struct folio *folio, struct mm_struct *mm,
1660 if (fault_flag_allow_retry_first(flags)) {
1662 * CAUTION! In this case, mmap_lock is not released
1663 * even though return 0.
1665 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1668 mmap_read_unlock(mm);
1669 if (flags & FAULT_FLAG_KILLABLE)
1670 folio_wait_locked_killable(folio);
1672 folio_wait_locked(folio);
1675 if (flags & FAULT_FLAG_KILLABLE) {
1678 ret = __folio_lock_killable(folio);
1680 mmap_read_unlock(mm);
1684 __folio_lock(folio);
1691 * page_cache_next_miss() - Find the next gap in the page cache.
1692 * @mapping: Mapping.
1694 * @max_scan: Maximum range to search.
1696 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1697 * gap with the lowest index.
1699 * This function may be called under the rcu_read_lock. However, this will
1700 * not atomically search a snapshot of the cache at a single point in time.
1701 * For example, if a gap is created at index 5, then subsequently a gap is
1702 * created at index 10, page_cache_next_miss covering both indices may
1703 * return 10 if called under the rcu_read_lock.
1705 * Return: The index of the gap if found, otherwise an index outside the
1706 * range specified (in which case 'return - index >= max_scan' will be true).
1707 * In the rare case of index wrap-around, 0 will be returned.
1709 pgoff_t page_cache_next_miss(struct address_space *mapping,
1710 pgoff_t index, unsigned long max_scan)
1712 XA_STATE(xas, &mapping->i_pages, index);
1714 while (max_scan--) {
1715 void *entry = xas_next(&xas);
1716 if (!entry || xa_is_value(entry))
1718 if (xas.xa_index == 0)
1722 return xas.xa_index;
1724 EXPORT_SYMBOL(page_cache_next_miss);
1727 * page_cache_prev_miss() - Find the previous gap in the page cache.
1728 * @mapping: Mapping.
1730 * @max_scan: Maximum range to search.
1732 * Search the range [max(index - max_scan + 1, 0), index] for the
1733 * gap with the highest index.
1735 * This function may be called under the rcu_read_lock. However, this will
1736 * not atomically search a snapshot of the cache at a single point in time.
1737 * For example, if a gap is created at index 10, then subsequently a gap is
1738 * created at index 5, page_cache_prev_miss() covering both indices may
1739 * return 5 if called under the rcu_read_lock.
1741 * Return: The index of the gap if found, otherwise an index outside the
1742 * range specified (in which case 'index - return >= max_scan' will be true).
1743 * In the rare case of wrap-around, ULONG_MAX will be returned.
1745 pgoff_t page_cache_prev_miss(struct address_space *mapping,
1746 pgoff_t index, unsigned long max_scan)
1748 XA_STATE(xas, &mapping->i_pages, index);
1750 while (max_scan--) {
1751 void *entry = xas_prev(&xas);
1752 if (!entry || xa_is_value(entry))
1754 if (xas.xa_index == ULONG_MAX)
1758 return xas.xa_index;
1760 EXPORT_SYMBOL(page_cache_prev_miss);
1763 * Lockless page cache protocol:
1764 * On the lookup side:
1765 * 1. Load the folio from i_pages
1766 * 2. Increment the refcount if it's not zero
1767 * 3. If the folio is not found by xas_reload(), put the refcount and retry
1769 * On the removal side:
1770 * A. Freeze the page (by zeroing the refcount if nobody else has a reference)
1771 * B. Remove the page from i_pages
1772 * C. Return the page to the page allocator
1774 * This means that any page may have its reference count temporarily
1775 * increased by a speculative page cache (or fast GUP) lookup as it can
1776 * be allocated by another user before the RCU grace period expires.
1777 * Because the refcount temporarily acquired here may end up being the
1778 * last refcount on the page, any page allocation must be freeable by
1783 * mapping_get_entry - Get a page cache entry.
1784 * @mapping: the address_space to search
1785 * @index: The page cache index.
1787 * Looks up the page cache entry at @mapping & @index. If it is a folio,
1788 * it is returned with an increased refcount. If it is a shadow entry
1789 * of a previously evicted folio, or a swap entry from shmem/tmpfs,
1790 * it is returned without further action.
1792 * Return: The folio, swap or shadow entry, %NULL if nothing is found.
1794 static void *mapping_get_entry(struct address_space *mapping, pgoff_t index)
1796 XA_STATE(xas, &mapping->i_pages, index);
1797 struct folio *folio;
1802 folio = xas_load(&xas);
1803 if (xas_retry(&xas, folio))
1806 * A shadow entry of a recently evicted page, or a swap entry from
1807 * shmem/tmpfs. Return it without attempting to raise page count.
1809 if (!folio || xa_is_value(folio))
1812 if (!folio_try_get_rcu(folio))
1815 if (unlikely(folio != xas_reload(&xas))) {
1826 * __filemap_get_folio - Find and get a reference to a folio.
1827 * @mapping: The address_space to search.
1828 * @index: The page index.
1829 * @fgp_flags: %FGP flags modify how the folio is returned.
1830 * @gfp: Memory allocation flags to use if %FGP_CREAT is specified.
1832 * Looks up the page cache entry at @mapping & @index.
1834 * @fgp_flags can be zero or more of these flags:
1836 * * %FGP_ACCESSED - The folio will be marked accessed.
1837 * * %FGP_LOCK - The folio is returned locked.
1838 * * %FGP_ENTRY - If there is a shadow / swap / DAX entry, return it
1839 * instead of allocating a new folio to replace it.
1840 * * %FGP_CREAT - If no page is present then a new page is allocated using
1841 * @gfp and added to the page cache and the VM's LRU list.
1842 * The page is returned locked and with an increased refcount.
1843 * * %FGP_FOR_MMAP - The caller wants to do its own locking dance if the
1844 * page is already in cache. If the page was allocated, unlock it before
1845 * returning so the caller can do the same dance.
1846 * * %FGP_WRITE - The page will be written to by the caller.
1847 * * %FGP_NOFS - __GFP_FS will get cleared in gfp.
1848 * * %FGP_NOWAIT - Don't get blocked by page lock.
1849 * * %FGP_STABLE - Wait for the folio to be stable (finished writeback)
1851 * If %FGP_LOCK or %FGP_CREAT are specified then the function may sleep even
1852 * if the %GFP flags specified for %FGP_CREAT are atomic.
1854 * If there is a page cache page, it is returned with an increased refcount.
1856 * Return: The found folio or %NULL otherwise.
1858 struct folio *__filemap_get_folio(struct address_space *mapping, pgoff_t index,
1859 int fgp_flags, gfp_t gfp)
1861 struct folio *folio;
1864 folio = mapping_get_entry(mapping, index);
1865 if (xa_is_value(folio)) {
1866 if (fgp_flags & FGP_ENTRY)
1873 if (fgp_flags & FGP_LOCK) {
1874 if (fgp_flags & FGP_NOWAIT) {
1875 if (!folio_trylock(folio)) {
1883 /* Has the page been truncated? */
1884 if (unlikely(folio->mapping != mapping)) {
1885 folio_unlock(folio);
1889 VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
1892 if (fgp_flags & FGP_ACCESSED)
1893 folio_mark_accessed(folio);
1894 else if (fgp_flags & FGP_WRITE) {
1895 /* Clear idle flag for buffer write */
1896 if (folio_test_idle(folio))
1897 folio_clear_idle(folio);
1900 if (fgp_flags & FGP_STABLE)
1901 folio_wait_stable(folio);
1903 if (!folio && (fgp_flags & FGP_CREAT)) {
1905 if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping))
1907 if (fgp_flags & FGP_NOFS)
1910 folio = filemap_alloc_folio(gfp, 0);
1914 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
1915 fgp_flags |= FGP_LOCK;
1917 /* Init accessed so avoid atomic mark_page_accessed later */
1918 if (fgp_flags & FGP_ACCESSED)
1919 __folio_set_referenced(folio);
1921 err = filemap_add_folio(mapping, folio, index, gfp);
1922 if (unlikely(err)) {
1930 * filemap_add_folio locks the page, and for mmap
1931 * we expect an unlocked page.
1933 if (folio && (fgp_flags & FGP_FOR_MMAP))
1934 folio_unlock(folio);
1939 EXPORT_SYMBOL(__filemap_get_folio);
1941 static inline struct folio *find_get_entry(struct xa_state *xas, pgoff_t max,
1944 struct folio *folio;
1947 if (mark == XA_PRESENT)
1948 folio = xas_find(xas, max);
1950 folio = xas_find_marked(xas, max, mark);
1952 if (xas_retry(xas, folio))
1955 * A shadow entry of a recently evicted page, a swap
1956 * entry from shmem/tmpfs or a DAX entry. Return it
1957 * without attempting to raise page count.
1959 if (!folio || xa_is_value(folio))
1962 if (!folio_try_get_rcu(folio))
1965 if (unlikely(folio != xas_reload(xas))) {
1977 * find_get_entries - gang pagecache lookup
1978 * @mapping: The address_space to search
1979 * @start: The starting page cache index
1980 * @end: The final page index (inclusive).
1981 * @fbatch: Where the resulting entries are placed.
1982 * @indices: The cache indices corresponding to the entries in @entries
1984 * find_get_entries() will search for and return a batch of entries in
1985 * the mapping. The entries are placed in @fbatch. find_get_entries()
1986 * takes a reference on any actual folios it returns.
1988 * The entries have ascending indexes. The indices may not be consecutive
1989 * due to not-present entries or large folios.
1991 * Any shadow entries of evicted folios, or swap entries from
1992 * shmem/tmpfs, are included in the returned array.
1994 * Return: The number of entries which were found.
1996 unsigned find_get_entries(struct address_space *mapping, pgoff_t start,
1997 pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
1999 XA_STATE(xas, &mapping->i_pages, start);
2000 struct folio *folio;
2003 while ((folio = find_get_entry(&xas, end, XA_PRESENT)) != NULL) {
2004 indices[fbatch->nr] = xas.xa_index;
2005 if (!folio_batch_add(fbatch, folio))
2010 return folio_batch_count(fbatch);
2014 * find_lock_entries - Find a batch of pagecache entries.
2015 * @mapping: The address_space to search.
2016 * @start: The starting page cache index.
2017 * @end: The final page index (inclusive).
2018 * @fbatch: Where the resulting entries are placed.
2019 * @indices: The cache indices of the entries in @fbatch.
2021 * find_lock_entries() will return a batch of entries from @mapping.
2022 * Swap, shadow and DAX entries are included. Folios are returned
2023 * locked and with an incremented refcount. Folios which are locked
2024 * by somebody else or under writeback are skipped. Folios which are
2025 * partially outside the range are not returned.
2027 * The entries have ascending indexes. The indices may not be consecutive
2028 * due to not-present entries, large folios, folios which could not be
2029 * locked or folios under writeback.
2031 * Return: The number of entries which were found.
2033 unsigned find_lock_entries(struct address_space *mapping, pgoff_t start,
2034 pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
2036 XA_STATE(xas, &mapping->i_pages, start);
2037 struct folio *folio;
2040 while ((folio = find_get_entry(&xas, end, XA_PRESENT))) {
2041 if (!xa_is_value(folio)) {
2042 if (folio->index < start)
2044 if (folio->index + folio_nr_pages(folio) - 1 > end)
2046 if (!folio_trylock(folio))
2048 if (folio->mapping != mapping ||
2049 folio_test_writeback(folio))
2051 VM_BUG_ON_FOLIO(!folio_contains(folio, xas.xa_index),
2054 indices[fbatch->nr] = xas.xa_index;
2055 if (!folio_batch_add(fbatch, folio))
2059 folio_unlock(folio);
2065 return folio_batch_count(fbatch);
2069 bool folio_more_pages(struct folio *folio, pgoff_t index, pgoff_t max)
2071 if (!folio_test_large(folio) || folio_test_hugetlb(folio))
2075 return index < folio->index + folio_nr_pages(folio) - 1;
2079 * find_get_pages_range - gang pagecache lookup
2080 * @mapping: The address_space to search
2081 * @start: The starting page index
2082 * @end: The final page index (inclusive)
2083 * @nr_pages: The maximum number of pages
2084 * @pages: Where the resulting pages are placed
2086 * find_get_pages_range() will search for and return a group of up to @nr_pages
2087 * pages in the mapping starting at index @start and up to index @end
2088 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
2089 * a reference against the returned pages.
2091 * The search returns a group of mapping-contiguous pages with ascending
2092 * indexes. There may be holes in the indices due to not-present pages.
2093 * We also update @start to index the next page for the traversal.
2095 * Return: the number of pages which were found. If this number is
2096 * smaller than @nr_pages, the end of specified range has been
2099 unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
2100 pgoff_t end, unsigned int nr_pages,
2101 struct page **pages)
2103 XA_STATE(xas, &mapping->i_pages, *start);
2104 struct folio *folio;
2107 if (unlikely(!nr_pages))
2111 while ((folio = find_get_entry(&xas, end, XA_PRESENT))) {
2112 /* Skip over shadow, swap and DAX entries */
2113 if (xa_is_value(folio))
2117 pages[ret] = folio_file_page(folio, xas.xa_index);
2118 if (++ret == nr_pages) {
2119 *start = xas.xa_index + 1;
2122 if (folio_more_pages(folio, xas.xa_index, end)) {
2124 folio_ref_inc(folio);
2130 * We come here when there is no page beyond @end. We take care to not
2131 * overflow the index @start as it confuses some of the callers. This
2132 * breaks the iteration when there is a page at index -1 but that is
2133 * already broken anyway.
2135 if (end == (pgoff_t)-1)
2136 *start = (pgoff_t)-1;
2146 * find_get_pages_contig - gang contiguous pagecache lookup
2147 * @mapping: The address_space to search
2148 * @index: The starting page index
2149 * @nr_pages: The maximum number of pages
2150 * @pages: Where the resulting pages are placed
2152 * find_get_pages_contig() works exactly like find_get_pages(), except
2153 * that the returned number of pages are guaranteed to be contiguous.
2155 * Return: the number of pages which were found.
2157 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
2158 unsigned int nr_pages, struct page **pages)
2160 XA_STATE(xas, &mapping->i_pages, index);
2161 struct folio *folio;
2162 unsigned int ret = 0;
2164 if (unlikely(!nr_pages))
2168 for (folio = xas_load(&xas); folio; folio = xas_next(&xas)) {
2169 if (xas_retry(&xas, folio))
2172 * If the entry has been swapped out, we can stop looking.
2173 * No current caller is looking for DAX entries.
2175 if (xa_is_value(folio))
2178 if (!folio_try_get_rcu(folio))
2181 if (unlikely(folio != xas_reload(&xas)))
2185 pages[ret] = folio_file_page(folio, xas.xa_index);
2186 if (++ret == nr_pages)
2188 if (folio_more_pages(folio, xas.xa_index, ULONG_MAX)) {
2190 folio_ref_inc(folio);
2202 EXPORT_SYMBOL(find_get_pages_contig);
2205 * find_get_pages_range_tag - Find and return head pages matching @tag.
2206 * @mapping: the address_space to search
2207 * @index: the starting page index
2208 * @end: The final page index (inclusive)
2209 * @tag: the tag index
2210 * @nr_pages: the maximum number of pages
2211 * @pages: where the resulting pages are placed
2213 * Like find_get_pages(), except we only return head pages which are tagged
2214 * with @tag. @index is updated to the index immediately after the last
2215 * page we return, ready for the next iteration.
2217 * Return: the number of pages which were found.
2219 unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
2220 pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
2221 struct page **pages)
2223 XA_STATE(xas, &mapping->i_pages, *index);
2224 struct folio *folio;
2227 if (unlikely(!nr_pages))
2231 while ((folio = find_get_entry(&xas, end, tag))) {
2233 * Shadow entries should never be tagged, but this iteration
2234 * is lockless so there is a window for page reclaim to evict
2235 * a page we saw tagged. Skip over it.
2237 if (xa_is_value(folio))
2240 pages[ret] = &folio->page;
2241 if (++ret == nr_pages) {
2242 *index = folio->index + folio_nr_pages(folio);
2248 * We come here when we got to @end. We take care to not overflow the
2249 * index @index as it confuses some of the callers. This breaks the
2250 * iteration when there is a page at index -1 but that is already
2253 if (end == (pgoff_t)-1)
2254 *index = (pgoff_t)-1;
2262 EXPORT_SYMBOL(find_get_pages_range_tag);
2265 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
2266 * a _large_ part of the i/o request. Imagine the worst scenario:
2268 * ---R__________________________________________B__________
2269 * ^ reading here ^ bad block(assume 4k)
2271 * read(R) => miss => readahead(R...B) => media error => frustrating retries
2272 * => failing the whole request => read(R) => read(R+1) =>
2273 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
2274 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
2275 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
2277 * It is going insane. Fix it by quickly scaling down the readahead size.
2279 static void shrink_readahead_size_eio(struct file_ra_state *ra)
2285 * filemap_get_read_batch - Get a batch of folios for read
2287 * Get a batch of folios which represent a contiguous range of bytes in
2288 * the file. No exceptional entries will be returned. If @index is in
2289 * the middle of a folio, the entire folio will be returned. The last
2290 * folio in the batch may have the readahead flag set or the uptodate flag
2291 * clear so that the caller can take the appropriate action.
2293 static void filemap_get_read_batch(struct address_space *mapping,
2294 pgoff_t index, pgoff_t max, struct folio_batch *fbatch)
2296 XA_STATE(xas, &mapping->i_pages, index);
2297 struct folio *folio;
2300 for (folio = xas_load(&xas); folio; folio = xas_next(&xas)) {
2301 if (xas_retry(&xas, folio))
2303 if (xas.xa_index > max || xa_is_value(folio))
2305 if (!folio_try_get_rcu(folio))
2308 if (unlikely(folio != xas_reload(&xas)))
2311 if (!folio_batch_add(fbatch, folio))
2313 if (!folio_test_uptodate(folio))
2315 if (folio_test_readahead(folio))
2317 xas_advance(&xas, folio->index + folio_nr_pages(folio) - 1);
2327 static int filemap_read_folio(struct file *file, struct address_space *mapping,
2328 struct folio *folio)
2333 * A previous I/O error may have been due to temporary failures,
2334 * eg. multipath errors. PG_error will be set again if readpage
2337 folio_clear_error(folio);
2338 /* Start the actual read. The read will unlock the page. */
2339 error = mapping->a_ops->readpage(file, &folio->page);
2343 error = folio_wait_locked_killable(folio);
2346 if (folio_test_uptodate(folio))
2348 shrink_readahead_size_eio(&file->f_ra);
2352 static bool filemap_range_uptodate(struct address_space *mapping,
2353 loff_t pos, struct iov_iter *iter, struct folio *folio)
2357 if (folio_test_uptodate(folio))
2359 /* pipes can't handle partially uptodate pages */
2360 if (iov_iter_is_pipe(iter))
2362 if (!mapping->a_ops->is_partially_uptodate)
2364 if (mapping->host->i_blkbits >= folio_shift(folio))
2367 count = iter->count;
2368 if (folio_pos(folio) > pos) {
2369 count -= folio_pos(folio) - pos;
2372 pos -= folio_pos(folio);
2375 return mapping->a_ops->is_partially_uptodate(&folio->page, pos, count);
2378 static int filemap_update_page(struct kiocb *iocb,
2379 struct address_space *mapping, struct iov_iter *iter,
2380 struct folio *folio)
2384 if (iocb->ki_flags & IOCB_NOWAIT) {
2385 if (!filemap_invalidate_trylock_shared(mapping))
2388 filemap_invalidate_lock_shared(mapping);
2391 if (!folio_trylock(folio)) {
2393 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO))
2394 goto unlock_mapping;
2395 if (!(iocb->ki_flags & IOCB_WAITQ)) {
2396 filemap_invalidate_unlock_shared(mapping);
2398 * This is where we usually end up waiting for a
2399 * previously submitted readahead to finish.
2401 folio_put_wait_locked(folio, TASK_KILLABLE);
2402 return AOP_TRUNCATED_PAGE;
2404 error = __folio_lock_async(folio, iocb->ki_waitq);
2406 goto unlock_mapping;
2409 error = AOP_TRUNCATED_PAGE;
2410 if (!folio->mapping)
2414 if (filemap_range_uptodate(mapping, iocb->ki_pos, iter, folio))
2418 if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT | IOCB_WAITQ))
2421 error = filemap_read_folio(iocb->ki_filp, mapping, folio);
2422 goto unlock_mapping;
2424 folio_unlock(folio);
2426 filemap_invalidate_unlock_shared(mapping);
2427 if (error == AOP_TRUNCATED_PAGE)
2432 static int filemap_create_folio(struct file *file,
2433 struct address_space *mapping, pgoff_t index,
2434 struct folio_batch *fbatch)
2436 struct folio *folio;
2439 folio = filemap_alloc_folio(mapping_gfp_mask(mapping), 0);
2444 * Protect against truncate / hole punch. Grabbing invalidate_lock
2445 * here assures we cannot instantiate and bring uptodate new
2446 * pagecache folios after evicting page cache during truncate
2447 * and before actually freeing blocks. Note that we could
2448 * release invalidate_lock after inserting the folio into
2449 * the page cache as the locked folio would then be enough to
2450 * synchronize with hole punching. But there are code paths
2451 * such as filemap_update_page() filling in partially uptodate
2452 * pages or ->readpages() that need to hold invalidate_lock
2453 * while mapping blocks for IO so let's hold the lock here as
2454 * well to keep locking rules simple.
2456 filemap_invalidate_lock_shared(mapping);
2457 error = filemap_add_folio(mapping, folio, index,
2458 mapping_gfp_constraint(mapping, GFP_KERNEL));
2459 if (error == -EEXIST)
2460 error = AOP_TRUNCATED_PAGE;
2464 error = filemap_read_folio(file, mapping, folio);
2468 filemap_invalidate_unlock_shared(mapping);
2469 folio_batch_add(fbatch, folio);
2472 filemap_invalidate_unlock_shared(mapping);
2477 static int filemap_readahead(struct kiocb *iocb, struct file *file,
2478 struct address_space *mapping, struct folio *folio,
2481 DEFINE_READAHEAD(ractl, file, &file->f_ra, mapping, folio->index);
2483 if (iocb->ki_flags & IOCB_NOIO)
2485 page_cache_async_ra(&ractl, folio, last_index - folio->index);
2489 static int filemap_get_pages(struct kiocb *iocb, struct iov_iter *iter,
2490 struct folio_batch *fbatch)
2492 struct file *filp = iocb->ki_filp;
2493 struct address_space *mapping = filp->f_mapping;
2494 struct file_ra_state *ra = &filp->f_ra;
2495 pgoff_t index = iocb->ki_pos >> PAGE_SHIFT;
2497 struct folio *folio;
2500 last_index = DIV_ROUND_UP(iocb->ki_pos + iter->count, PAGE_SIZE);
2502 if (fatal_signal_pending(current))
2505 filemap_get_read_batch(mapping, index, last_index, fbatch);
2506 if (!folio_batch_count(fbatch)) {
2507 if (iocb->ki_flags & IOCB_NOIO)
2509 page_cache_sync_readahead(mapping, ra, filp, index,
2510 last_index - index);
2511 filemap_get_read_batch(mapping, index, last_index, fbatch);
2513 if (!folio_batch_count(fbatch)) {
2514 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_WAITQ))
2516 err = filemap_create_folio(filp, mapping,
2517 iocb->ki_pos >> PAGE_SHIFT, fbatch);
2518 if (err == AOP_TRUNCATED_PAGE)
2523 folio = fbatch->folios[folio_batch_count(fbatch) - 1];
2524 if (folio_test_readahead(folio)) {
2525 err = filemap_readahead(iocb, filp, mapping, folio, last_index);
2529 if (!folio_test_uptodate(folio)) {
2530 if ((iocb->ki_flags & IOCB_WAITQ) &&
2531 folio_batch_count(fbatch) > 1)
2532 iocb->ki_flags |= IOCB_NOWAIT;
2533 err = filemap_update_page(iocb, mapping, iter, folio);
2542 if (likely(--fbatch->nr))
2544 if (err == AOP_TRUNCATED_PAGE)
2550 * filemap_read - Read data from the page cache.
2551 * @iocb: The iocb to read.
2552 * @iter: Destination for the data.
2553 * @already_read: Number of bytes already read by the caller.
2555 * Copies data from the page cache. If the data is not currently present,
2556 * uses the readahead and readpage address_space operations to fetch it.
2558 * Return: Total number of bytes copied, including those already read by
2559 * the caller. If an error happens before any bytes are copied, returns
2560 * a negative error number.
2562 ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,
2563 ssize_t already_read)
2565 struct file *filp = iocb->ki_filp;
2566 struct file_ra_state *ra = &filp->f_ra;
2567 struct address_space *mapping = filp->f_mapping;
2568 struct inode *inode = mapping->host;
2569 struct folio_batch fbatch;
2571 bool writably_mapped;
2572 loff_t isize, end_offset;
2574 if (unlikely(iocb->ki_pos >= inode->i_sb->s_maxbytes))
2576 if (unlikely(!iov_iter_count(iter)))
2579 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2580 folio_batch_init(&fbatch);
2586 * If we've already successfully copied some data, then we
2587 * can no longer safely return -EIOCBQUEUED. Hence mark
2588 * an async read NOWAIT at that point.
2590 if ((iocb->ki_flags & IOCB_WAITQ) && already_read)
2591 iocb->ki_flags |= IOCB_NOWAIT;
2593 if (unlikely(iocb->ki_pos >= i_size_read(inode)))
2596 error = filemap_get_pages(iocb, iter, &fbatch);
2601 * i_size must be checked after we know the pages are Uptodate.
2603 * Checking i_size after the check allows us to calculate
2604 * the correct value for "nr", which means the zero-filled
2605 * part of the page is not copied back to userspace (unless
2606 * another truncate extends the file - this is desired though).
2608 isize = i_size_read(inode);
2609 if (unlikely(iocb->ki_pos >= isize))
2611 end_offset = min_t(loff_t, isize, iocb->ki_pos + iter->count);
2614 * Once we start copying data, we don't want to be touching any
2615 * cachelines that might be contended:
2617 writably_mapped = mapping_writably_mapped(mapping);
2620 * When a sequential read accesses a page several times, only
2621 * mark it as accessed the first time.
2623 if (iocb->ki_pos >> PAGE_SHIFT !=
2624 ra->prev_pos >> PAGE_SHIFT)
2625 folio_mark_accessed(fbatch.folios[0]);
2627 for (i = 0; i < folio_batch_count(&fbatch); i++) {
2628 struct folio *folio = fbatch.folios[i];
2629 size_t fsize = folio_size(folio);
2630 size_t offset = iocb->ki_pos & (fsize - 1);
2631 size_t bytes = min_t(loff_t, end_offset - iocb->ki_pos,
2635 if (end_offset < folio_pos(folio))
2638 folio_mark_accessed(folio);
2640 * If users can be writing to this folio using arbitrary
2641 * virtual addresses, take care of potential aliasing
2642 * before reading the folio on the kernel side.
2644 if (writably_mapped)
2645 flush_dcache_folio(folio);
2647 copied = copy_folio_to_iter(folio, offset, bytes, iter);
2649 already_read += copied;
2650 iocb->ki_pos += copied;
2651 ra->prev_pos = iocb->ki_pos;
2653 if (copied < bytes) {
2659 for (i = 0; i < folio_batch_count(&fbatch); i++)
2660 folio_put(fbatch.folios[i]);
2661 folio_batch_init(&fbatch);
2662 } while (iov_iter_count(iter) && iocb->ki_pos < isize && !error);
2664 file_accessed(filp);
2666 return already_read ? already_read : error;
2668 EXPORT_SYMBOL_GPL(filemap_read);
2671 * generic_file_read_iter - generic filesystem read routine
2672 * @iocb: kernel I/O control block
2673 * @iter: destination for the data read
2675 * This is the "read_iter()" routine for all filesystems
2676 * that can use the page cache directly.
2678 * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
2679 * be returned when no data can be read without waiting for I/O requests
2680 * to complete; it doesn't prevent readahead.
2682 * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
2683 * requests shall be made for the read or for readahead. When no data
2684 * can be read, -EAGAIN shall be returned. When readahead would be
2685 * triggered, a partial, possibly empty read shall be returned.
2688 * * number of bytes copied, even for partial reads
2689 * * negative error code (or 0 if IOCB_NOIO) if nothing was read
2692 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2694 size_t count = iov_iter_count(iter);
2698 return 0; /* skip atime */
2700 if (iocb->ki_flags & IOCB_DIRECT) {
2701 struct file *file = iocb->ki_filp;
2702 struct address_space *mapping = file->f_mapping;
2703 struct inode *inode = mapping->host;
2705 if (iocb->ki_flags & IOCB_NOWAIT) {
2706 if (filemap_range_needs_writeback(mapping, iocb->ki_pos,
2707 iocb->ki_pos + count - 1))
2710 retval = filemap_write_and_wait_range(mapping,
2712 iocb->ki_pos + count - 1);
2717 file_accessed(file);
2719 retval = mapping->a_ops->direct_IO(iocb, iter);
2721 iocb->ki_pos += retval;
2724 if (retval != -EIOCBQUEUED)
2725 iov_iter_revert(iter, count - iov_iter_count(iter));
2728 * Btrfs can have a short DIO read if we encounter
2729 * compressed extents, so if there was an error, or if
2730 * we've already read everything we wanted to, or if
2731 * there was a short read because we hit EOF, go ahead
2732 * and return. Otherwise fallthrough to buffered io for
2733 * the rest of the read. Buffered reads will not work for
2734 * DAX files, so don't bother trying.
2736 if (retval < 0 || !count || IS_DAX(inode))
2738 if (iocb->ki_pos >= i_size_read(inode))
2742 return filemap_read(iocb, iter, retval);
2744 EXPORT_SYMBOL(generic_file_read_iter);
2746 static inline loff_t folio_seek_hole_data(struct xa_state *xas,
2747 struct address_space *mapping, struct folio *folio,
2748 loff_t start, loff_t end, bool seek_data)
2750 const struct address_space_operations *ops = mapping->a_ops;
2751 size_t offset, bsz = i_blocksize(mapping->host);
2753 if (xa_is_value(folio) || folio_test_uptodate(folio))
2754 return seek_data ? start : end;
2755 if (!ops->is_partially_uptodate)
2756 return seek_data ? end : start;
2761 if (unlikely(folio->mapping != mapping))
2764 offset = offset_in_folio(folio, start) & ~(bsz - 1);
2767 if (ops->is_partially_uptodate(&folio->page, offset, bsz) ==
2770 start = (start + bsz) & ~(bsz - 1);
2772 } while (offset < folio_size(folio));
2774 folio_unlock(folio);
2779 static inline size_t seek_folio_size(struct xa_state *xas, struct folio *folio)
2781 if (xa_is_value(folio))
2782 return PAGE_SIZE << xa_get_order(xas->xa, xas->xa_index);
2783 return folio_size(folio);
2787 * mapping_seek_hole_data - Seek for SEEK_DATA / SEEK_HOLE in the page cache.
2788 * @mapping: Address space to search.
2789 * @start: First byte to consider.
2790 * @end: Limit of search (exclusive).
2791 * @whence: Either SEEK_HOLE or SEEK_DATA.
2793 * If the page cache knows which blocks contain holes and which blocks
2794 * contain data, your filesystem can use this function to implement
2795 * SEEK_HOLE and SEEK_DATA. This is useful for filesystems which are
2796 * entirely memory-based such as tmpfs, and filesystems which support
2797 * unwritten extents.
2799 * Return: The requested offset on success, or -ENXIO if @whence specifies
2800 * SEEK_DATA and there is no data after @start. There is an implicit hole
2801 * after @end - 1, so SEEK_HOLE returns @end if all the bytes between @start
2802 * and @end contain data.
2804 loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start,
2805 loff_t end, int whence)
2807 XA_STATE(xas, &mapping->i_pages, start >> PAGE_SHIFT);
2808 pgoff_t max = (end - 1) >> PAGE_SHIFT;
2809 bool seek_data = (whence == SEEK_DATA);
2810 struct folio *folio;
2816 while ((folio = find_get_entry(&xas, max, XA_PRESENT))) {
2817 loff_t pos = (u64)xas.xa_index << PAGE_SHIFT;
2826 seek_size = seek_folio_size(&xas, folio);
2827 pos = round_up((u64)pos + 1, seek_size);
2828 start = folio_seek_hole_data(&xas, mapping, folio, start, pos,
2834 if (seek_size > PAGE_SIZE)
2835 xas_set(&xas, pos >> PAGE_SHIFT);
2836 if (!xa_is_value(folio))
2843 if (folio && !xa_is_value(folio))
2851 #define MMAP_LOTSAMISS (100)
2853 * lock_folio_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock
2854 * @vmf - the vm_fault for this fault.
2855 * @folio - the folio to lock.
2856 * @fpin - the pointer to the file we may pin (or is already pinned).
2858 * This works similar to lock_folio_or_retry in that it can drop the
2859 * mmap_lock. It differs in that it actually returns the folio locked
2860 * if it returns 1 and 0 if it couldn't lock the folio. If we did have
2861 * to drop the mmap_lock then fpin will point to the pinned file and
2862 * needs to be fput()'ed at a later point.
2864 static int lock_folio_maybe_drop_mmap(struct vm_fault *vmf, struct folio *folio,
2867 if (folio_trylock(folio))
2871 * NOTE! This will make us return with VM_FAULT_RETRY, but with
2872 * the mmap_lock still held. That's how FAULT_FLAG_RETRY_NOWAIT
2873 * is supposed to work. We have way too many special cases..
2875 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2878 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2879 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2880 if (__folio_lock_killable(folio)) {
2882 * We didn't have the right flags to drop the mmap_lock,
2883 * but all fault_handlers only check for fatal signals
2884 * if we return VM_FAULT_RETRY, so we need to drop the
2885 * mmap_lock here and return 0 if we don't have a fpin.
2888 mmap_read_unlock(vmf->vma->vm_mm);
2892 __folio_lock(folio);
2898 * Synchronous readahead happens when we don't even find a page in the page
2899 * cache at all. We don't want to perform IO under the mmap sem, so if we have
2900 * to drop the mmap sem we return the file that was pinned in order for us to do
2901 * that. If we didn't pin a file then we return NULL. The file that is
2902 * returned needs to be fput()'ed when we're done with it.
2904 static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
2906 struct file *file = vmf->vma->vm_file;
2907 struct file_ra_state *ra = &file->f_ra;
2908 struct address_space *mapping = file->f_mapping;
2909 DEFINE_READAHEAD(ractl, file, ra, mapping, vmf->pgoff);
2910 struct file *fpin = NULL;
2911 unsigned int mmap_miss;
2913 /* If we don't want any read-ahead, don't bother */
2914 if (vmf->vma->vm_flags & VM_RAND_READ)
2919 if (vmf->vma->vm_flags & VM_SEQ_READ) {
2920 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2921 page_cache_sync_ra(&ractl, ra->ra_pages);
2925 /* Avoid banging the cache line if not needed */
2926 mmap_miss = READ_ONCE(ra->mmap_miss);
2927 if (mmap_miss < MMAP_LOTSAMISS * 10)
2928 WRITE_ONCE(ra->mmap_miss, ++mmap_miss);
2931 * Do we miss much more than hit in this file? If so,
2932 * stop bothering with read-ahead. It will only hurt.
2934 if (mmap_miss > MMAP_LOTSAMISS)
2940 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2941 ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2);
2942 ra->size = ra->ra_pages;
2943 ra->async_size = ra->ra_pages / 4;
2944 ractl._index = ra->start;
2945 do_page_cache_ra(&ractl, ra->size, ra->async_size);
2950 * Asynchronous readahead happens when we find the page and PG_readahead,
2951 * so we want to possibly extend the readahead further. We return the file that
2952 * was pinned if we have to drop the mmap_lock in order to do IO.
2954 static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2955 struct folio *folio)
2957 struct file *file = vmf->vma->vm_file;
2958 struct file_ra_state *ra = &file->f_ra;
2959 DEFINE_READAHEAD(ractl, file, ra, file->f_mapping, vmf->pgoff);
2960 struct file *fpin = NULL;
2961 unsigned int mmap_miss;
2963 /* If we don't want any read-ahead, don't bother */
2964 if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
2967 mmap_miss = READ_ONCE(ra->mmap_miss);
2969 WRITE_ONCE(ra->mmap_miss, --mmap_miss);
2971 if (folio_test_readahead(folio)) {
2972 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2973 page_cache_async_ra(&ractl, folio, ra->ra_pages);
2979 * filemap_fault - read in file data for page fault handling
2980 * @vmf: struct vm_fault containing details of the fault
2982 * filemap_fault() is invoked via the vma operations vector for a
2983 * mapped memory region to read in file data during a page fault.
2985 * The goto's are kind of ugly, but this streamlines the normal case of having
2986 * it in the page cache, and handles the special cases reasonably without
2987 * having a lot of duplicated code.
2989 * vma->vm_mm->mmap_lock must be held on entry.
2991 * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
2992 * may be dropped before doing I/O or by lock_folio_maybe_drop_mmap().
2994 * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
2995 * has not been released.
2997 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
2999 * Return: bitwise-OR of %VM_FAULT_ codes.
3001 vm_fault_t filemap_fault(struct vm_fault *vmf)
3004 struct file *file = vmf->vma->vm_file;
3005 struct file *fpin = NULL;
3006 struct address_space *mapping = file->f_mapping;
3007 struct inode *inode = mapping->host;
3008 pgoff_t max_idx, index = vmf->pgoff;
3009 struct folio *folio;
3011 bool mapping_locked = false;
3013 max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3014 if (unlikely(index >= max_idx))
3015 return VM_FAULT_SIGBUS;
3018 * Do we have something in the page cache already?
3020 folio = filemap_get_folio(mapping, index);
3021 if (likely(folio)) {
3023 * We found the page, so try async readahead before waiting for
3026 if (!(vmf->flags & FAULT_FLAG_TRIED))
3027 fpin = do_async_mmap_readahead(vmf, folio);
3028 if (unlikely(!folio_test_uptodate(folio))) {
3029 filemap_invalidate_lock_shared(mapping);
3030 mapping_locked = true;
3033 /* No page in the page cache at all */
3034 count_vm_event(PGMAJFAULT);
3035 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
3036 ret = VM_FAULT_MAJOR;
3037 fpin = do_sync_mmap_readahead(vmf);
3040 * See comment in filemap_create_folio() why we need
3043 if (!mapping_locked) {
3044 filemap_invalidate_lock_shared(mapping);
3045 mapping_locked = true;
3047 folio = __filemap_get_folio(mapping, index,
3048 FGP_CREAT|FGP_FOR_MMAP,
3053 filemap_invalidate_unlock_shared(mapping);
3054 return VM_FAULT_OOM;
3058 if (!lock_folio_maybe_drop_mmap(vmf, folio, &fpin))
3061 /* Did it get truncated? */
3062 if (unlikely(folio->mapping != mapping)) {
3063 folio_unlock(folio);
3067 VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
3070 * We have a locked page in the page cache, now we need to check
3071 * that it's up-to-date. If not, it is going to be due to an error.
3073 if (unlikely(!folio_test_uptodate(folio))) {
3075 * The page was in cache and uptodate and now it is not.
3076 * Strange but possible since we didn't hold the page lock all
3077 * the time. Let's drop everything get the invalidate lock and
3080 if (!mapping_locked) {
3081 folio_unlock(folio);
3085 goto page_not_uptodate;
3089 * We've made it this far and we had to drop our mmap_lock, now is the
3090 * time to return to the upper layer and have it re-find the vma and
3094 folio_unlock(folio);
3098 filemap_invalidate_unlock_shared(mapping);
3101 * Found the page and have a reference on it.
3102 * We must recheck i_size under page lock.
3104 max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3105 if (unlikely(index >= max_idx)) {
3106 folio_unlock(folio);
3108 return VM_FAULT_SIGBUS;
3111 vmf->page = folio_file_page(folio, index);
3112 return ret | VM_FAULT_LOCKED;
3116 * Umm, take care of errors if the page isn't up-to-date.
3117 * Try to re-read it _once_. We do this synchronously,
3118 * because there really aren't any performance issues here
3119 * and we need to check for errors.
3121 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3122 error = filemap_read_folio(file, mapping, folio);
3127 if (!error || error == AOP_TRUNCATED_PAGE)
3129 filemap_invalidate_unlock_shared(mapping);
3131 return VM_FAULT_SIGBUS;
3135 * We dropped the mmap_lock, we need to return to the fault handler to
3136 * re-find the vma and come back and find our hopefully still populated
3142 filemap_invalidate_unlock_shared(mapping);
3145 return ret | VM_FAULT_RETRY;
3147 EXPORT_SYMBOL(filemap_fault);
3149 static bool filemap_map_pmd(struct vm_fault *vmf, struct page *page)
3151 struct mm_struct *mm = vmf->vma->vm_mm;
3153 /* Huge page is mapped? No need to proceed. */
3154 if (pmd_trans_huge(*vmf->pmd)) {
3160 if (pmd_none(*vmf->pmd) && PageTransHuge(page)) {
3161 vm_fault_t ret = do_set_pmd(vmf, page);
3163 /* The page is mapped successfully, reference consumed. */
3169 if (pmd_none(*vmf->pmd))
3170 pmd_install(mm, vmf->pmd, &vmf->prealloc_pte);
3172 /* See comment in handle_pte_fault() */
3173 if (pmd_devmap_trans_unstable(vmf->pmd)) {
3182 static struct folio *next_uptodate_page(struct folio *folio,
3183 struct address_space *mapping,
3184 struct xa_state *xas, pgoff_t end_pgoff)
3186 unsigned long max_idx;
3191 if (xas_retry(xas, folio))
3193 if (xa_is_value(folio))
3195 if (folio_test_locked(folio))
3197 if (!folio_try_get_rcu(folio))
3199 /* Has the page moved or been split? */
3200 if (unlikely(folio != xas_reload(xas)))
3202 if (!folio_test_uptodate(folio) || folio_test_readahead(folio))
3204 if (!folio_trylock(folio))
3206 if (folio->mapping != mapping)
3208 if (!folio_test_uptodate(folio))
3210 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
3211 if (xas->xa_index >= max_idx)
3215 folio_unlock(folio);
3218 } while ((folio = xas_next_entry(xas, end_pgoff)) != NULL);
3223 static inline struct folio *first_map_page(struct address_space *mapping,
3224 struct xa_state *xas,
3227 return next_uptodate_page(xas_find(xas, end_pgoff),
3228 mapping, xas, end_pgoff);
3231 static inline struct folio *next_map_page(struct address_space *mapping,
3232 struct xa_state *xas,
3235 return next_uptodate_page(xas_next_entry(xas, end_pgoff),
3236 mapping, xas, end_pgoff);
3239 vm_fault_t filemap_map_pages(struct vm_fault *vmf,
3240 pgoff_t start_pgoff, pgoff_t end_pgoff)
3242 struct vm_area_struct *vma = vmf->vma;
3243 struct file *file = vma->vm_file;
3244 struct address_space *mapping = file->f_mapping;
3245 pgoff_t last_pgoff = start_pgoff;
3247 XA_STATE(xas, &mapping->i_pages, start_pgoff);
3248 struct folio *folio;
3250 unsigned int mmap_miss = READ_ONCE(file->f_ra.mmap_miss);
3254 folio = first_map_page(mapping, &xas, end_pgoff);
3258 if (filemap_map_pmd(vmf, &folio->page)) {
3259 ret = VM_FAULT_NOPAGE;
3263 addr = vma->vm_start + ((start_pgoff - vma->vm_pgoff) << PAGE_SHIFT);
3264 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl);
3267 page = folio_file_page(folio, xas.xa_index);
3268 if (PageHWPoison(page))
3274 addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
3275 vmf->pte += xas.xa_index - last_pgoff;
3276 last_pgoff = xas.xa_index;
3278 if (!pte_none(*vmf->pte))
3281 /* We're about to handle the fault */
3282 if (vmf->address == addr)
3283 ret = VM_FAULT_NOPAGE;
3285 do_set_pte(vmf, page, addr);
3286 /* no need to invalidate: a not-present page won't be cached */
3287 update_mmu_cache(vma, addr, vmf->pte);
3288 if (folio_more_pages(folio, xas.xa_index, end_pgoff)) {
3290 folio_ref_inc(folio);
3293 folio_unlock(folio);
3296 if (folio_more_pages(folio, xas.xa_index, end_pgoff)) {
3300 folio_unlock(folio);
3302 } while ((folio = next_map_page(mapping, &xas, end_pgoff)) != NULL);
3303 pte_unmap_unlock(vmf->pte, vmf->ptl);
3306 WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss);
3309 EXPORT_SYMBOL(filemap_map_pages);
3311 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
3313 struct address_space *mapping = vmf->vma->vm_file->f_mapping;
3314 struct folio *folio = page_folio(vmf->page);
3315 vm_fault_t ret = VM_FAULT_LOCKED;
3317 sb_start_pagefault(mapping->host->i_sb);
3318 file_update_time(vmf->vma->vm_file);
3320 if (folio->mapping != mapping) {
3321 folio_unlock(folio);
3322 ret = VM_FAULT_NOPAGE;
3326 * We mark the folio dirty already here so that when freeze is in
3327 * progress, we are guaranteed that writeback during freezing will
3328 * see the dirty folio and writeprotect it again.
3330 folio_mark_dirty(folio);
3331 folio_wait_stable(folio);
3333 sb_end_pagefault(mapping->host->i_sb);
3337 const struct vm_operations_struct generic_file_vm_ops = {
3338 .fault = filemap_fault,
3339 .map_pages = filemap_map_pages,
3340 .page_mkwrite = filemap_page_mkwrite,
3343 /* This is used for a general mmap of a disk file */
3345 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3347 struct address_space *mapping = file->f_mapping;
3349 if (!mapping->a_ops->readpage)
3351 file_accessed(file);
3352 vma->vm_ops = &generic_file_vm_ops;
3357 * This is for filesystems which do not implement ->writepage.
3359 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3361 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
3363 return generic_file_mmap(file, vma);
3366 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
3368 return VM_FAULT_SIGBUS;
3370 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3374 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3378 #endif /* CONFIG_MMU */
3380 EXPORT_SYMBOL(filemap_page_mkwrite);
3381 EXPORT_SYMBOL(generic_file_mmap);
3382 EXPORT_SYMBOL(generic_file_readonly_mmap);
3384 static struct folio *do_read_cache_folio(struct address_space *mapping,
3385 pgoff_t index, filler_t filler, void *data, gfp_t gfp)
3387 struct folio *folio;
3390 folio = filemap_get_folio(mapping, index);
3392 folio = filemap_alloc_folio(gfp, 0);
3394 return ERR_PTR(-ENOMEM);
3395 err = filemap_add_folio(mapping, folio, index, gfp);
3396 if (unlikely(err)) {
3400 /* Presumably ENOMEM for xarray node */
3401 return ERR_PTR(err);
3406 err = filler(data, &folio->page);
3408 err = mapping->a_ops->readpage(data, &folio->page);
3412 return ERR_PTR(err);
3415 folio_wait_locked(folio);
3416 if (!folio_test_uptodate(folio)) {
3418 return ERR_PTR(-EIO);
3423 if (folio_test_uptodate(folio))
3426 if (!folio_trylock(folio)) {
3427 folio_put_wait_locked(folio, TASK_UNINTERRUPTIBLE);
3431 /* Folio was truncated from mapping */
3432 if (!folio->mapping) {
3433 folio_unlock(folio);
3438 /* Someone else locked and filled the page in a very small window */
3439 if (folio_test_uptodate(folio)) {
3440 folio_unlock(folio);
3445 * A previous I/O error may have been due to temporary
3447 * Clear page error before actual read, PG_error will be
3448 * set again if read page fails.
3450 folio_clear_error(folio);
3454 folio_mark_accessed(folio);
3459 * read_cache_folio - read into page cache, fill it if needed
3460 * @mapping: the page's address_space
3461 * @index: the page index
3462 * @filler: function to perform the read
3463 * @data: first arg to filler(data, page) function, often left as NULL
3465 * Read into the page cache. If a page already exists, and PageUptodate() is
3466 * not set, try to fill the page and wait for it to become unlocked.
3468 * If the page does not get brought uptodate, return -EIO.
3470 * The function expects mapping->invalidate_lock to be already held.
3472 * Return: up to date page on success, ERR_PTR() on failure.
3474 struct folio *read_cache_folio(struct address_space *mapping, pgoff_t index,
3475 filler_t filler, void *data)
3477 return do_read_cache_folio(mapping, index, filler, data,
3478 mapping_gfp_mask(mapping));
3480 EXPORT_SYMBOL(read_cache_folio);
3482 static struct page *do_read_cache_page(struct address_space *mapping,
3483 pgoff_t index, filler_t *filler, void *data, gfp_t gfp)
3485 struct folio *folio;
3487 folio = do_read_cache_folio(mapping, index, filler, data, gfp);
3489 return &folio->page;
3490 return folio_file_page(folio, index);
3493 struct page *read_cache_page(struct address_space *mapping,
3494 pgoff_t index, filler_t *filler, void *data)
3496 return do_read_cache_page(mapping, index, filler, data,
3497 mapping_gfp_mask(mapping));
3499 EXPORT_SYMBOL(read_cache_page);
3502 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
3503 * @mapping: the page's address_space
3504 * @index: the page index
3505 * @gfp: the page allocator flags to use if allocating
3507 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
3508 * any new page allocations done using the specified allocation flags.
3510 * If the page does not get brought uptodate, return -EIO.
3512 * The function expects mapping->invalidate_lock to be already held.
3514 * Return: up to date page on success, ERR_PTR() on failure.
3516 struct page *read_cache_page_gfp(struct address_space *mapping,
3520 return do_read_cache_page(mapping, index, NULL, NULL, gfp);
3522 EXPORT_SYMBOL(read_cache_page_gfp);
3524 int pagecache_write_begin(struct file *file, struct address_space *mapping,
3525 loff_t pos, unsigned len, unsigned flags,
3526 struct page **pagep, void **fsdata)
3528 const struct address_space_operations *aops = mapping->a_ops;
3530 return aops->write_begin(file, mapping, pos, len, flags,
3533 EXPORT_SYMBOL(pagecache_write_begin);
3535 int pagecache_write_end(struct file *file, struct address_space *mapping,
3536 loff_t pos, unsigned len, unsigned copied,
3537 struct page *page, void *fsdata)
3539 const struct address_space_operations *aops = mapping->a_ops;
3541 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
3543 EXPORT_SYMBOL(pagecache_write_end);
3546 * Warn about a page cache invalidation failure during a direct I/O write.
3548 void dio_warn_stale_pagecache(struct file *filp)
3550 static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
3554 errseq_set(&filp->f_mapping->wb_err, -EIO);
3555 if (__ratelimit(&_rs)) {
3556 path = file_path(filp, pathname, sizeof(pathname));
3559 pr_crit("Page cache invalidation failure on direct I/O. Possible data corruption due to collision with buffered I/O!\n");
3560 pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
3566 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
3568 struct file *file = iocb->ki_filp;
3569 struct address_space *mapping = file->f_mapping;
3570 struct inode *inode = mapping->host;
3571 loff_t pos = iocb->ki_pos;
3576 write_len = iov_iter_count(from);
3577 end = (pos + write_len - 1) >> PAGE_SHIFT;
3579 if (iocb->ki_flags & IOCB_NOWAIT) {
3580 /* If there are pages to writeback, return */
3581 if (filemap_range_has_page(file->f_mapping, pos,
3582 pos + write_len - 1))
3585 written = filemap_write_and_wait_range(mapping, pos,
3586 pos + write_len - 1);
3592 * After a write we want buffered reads to be sure to go to disk to get
3593 * the new data. We invalidate clean cached page from the region we're
3594 * about to write. We do this *before* the write so that we can return
3595 * without clobbering -EIOCBQUEUED from ->direct_IO().
3597 written = invalidate_inode_pages2_range(mapping,
3598 pos >> PAGE_SHIFT, end);
3600 * If a page can not be invalidated, return 0 to fall back
3601 * to buffered write.
3604 if (written == -EBUSY)
3609 written = mapping->a_ops->direct_IO(iocb, from);
3612 * Finally, try again to invalidate clean pages which might have been
3613 * cached by non-direct readahead, or faulted in by get_user_pages()
3614 * if the source of the write was an mmap'ed region of the file
3615 * we're writing. Either one is a pretty crazy thing to do,
3616 * so we don't support it 100%. If this invalidation
3617 * fails, tough, the write still worked...
3619 * Most of the time we do not need this since dio_complete() will do
3620 * the invalidation for us. However there are some file systems that
3621 * do not end up with dio_complete() being called, so let's not break
3622 * them by removing it completely.
3624 * Noticeable example is a blkdev_direct_IO().
3626 * Skip invalidation for async writes or if mapping has no pages.
3628 if (written > 0 && mapping->nrpages &&
3629 invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT, end))
3630 dio_warn_stale_pagecache(file);
3634 write_len -= written;
3635 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3636 i_size_write(inode, pos);
3637 mark_inode_dirty(inode);
3641 if (written != -EIOCBQUEUED)
3642 iov_iter_revert(from, write_len - iov_iter_count(from));
3646 EXPORT_SYMBOL(generic_file_direct_write);
3648 ssize_t generic_perform_write(struct file *file,
3649 struct iov_iter *i, loff_t pos)
3651 struct address_space *mapping = file->f_mapping;
3652 const struct address_space_operations *a_ops = mapping->a_ops;
3654 ssize_t written = 0;
3655 unsigned int flags = 0;
3659 unsigned long offset; /* Offset into pagecache page */
3660 unsigned long bytes; /* Bytes to write to page */
3661 size_t copied; /* Bytes copied from user */
3664 offset = (pos & (PAGE_SIZE - 1));
3665 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3670 * Bring in the user page that we will copy from _first_.
3671 * Otherwise there's a nasty deadlock on copying from the
3672 * same page as we're writing to, without it being marked
3675 if (unlikely(fault_in_iov_iter_readable(i, bytes))) {
3680 if (fatal_signal_pending(current)) {
3685 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
3687 if (unlikely(status < 0))
3690 if (mapping_writably_mapped(mapping))
3691 flush_dcache_page(page);
3693 copied = copy_page_from_iter_atomic(page, offset, bytes, i);
3694 flush_dcache_page(page);
3696 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3698 if (unlikely(status != copied)) {
3699 iov_iter_revert(i, copied - max(status, 0L));
3700 if (unlikely(status < 0))
3705 if (unlikely(status == 0)) {
3707 * A short copy made ->write_end() reject the
3708 * thing entirely. Might be memory poisoning
3709 * halfway through, might be a race with munmap,
3710 * might be severe memory pressure.
3719 balance_dirty_pages_ratelimited(mapping);
3720 } while (iov_iter_count(i));
3722 return written ? written : status;
3724 EXPORT_SYMBOL(generic_perform_write);
3727 * __generic_file_write_iter - write data to a file
3728 * @iocb: IO state structure (file, offset, etc.)
3729 * @from: iov_iter with data to write
3731 * This function does all the work needed for actually writing data to a
3732 * file. It does all basic checks, removes SUID from the file, updates
3733 * modification times and calls proper subroutines depending on whether we
3734 * do direct IO or a standard buffered write.
3736 * It expects i_rwsem to be grabbed unless we work on a block device or similar
3737 * object which does not need locking at all.
3739 * This function does *not* take care of syncing data in case of O_SYNC write.
3740 * A caller has to handle it. This is mainly due to the fact that we want to
3741 * avoid syncing under i_rwsem.
3744 * * number of bytes written, even for truncated writes
3745 * * negative error code if no data has been written at all
3747 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3749 struct file *file = iocb->ki_filp;
3750 struct address_space *mapping = file->f_mapping;
3751 struct inode *inode = mapping->host;
3752 ssize_t written = 0;
3756 /* We can write back this queue in page reclaim */
3757 current->backing_dev_info = inode_to_bdi(inode);
3758 err = file_remove_privs(file);
3762 err = file_update_time(file);
3766 if (iocb->ki_flags & IOCB_DIRECT) {
3767 loff_t pos, endbyte;
3769 written = generic_file_direct_write(iocb, from);
3771 * If the write stopped short of completing, fall back to
3772 * buffered writes. Some filesystems do this for writes to
3773 * holes, for example. For DAX files, a buffered write will
3774 * not succeed (even if it did, DAX does not handle dirty
3775 * page-cache pages correctly).
3777 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
3780 status = generic_perform_write(file, from, pos = iocb->ki_pos);
3782 * If generic_perform_write() returned a synchronous error
3783 * then we want to return the number of bytes which were
3784 * direct-written, or the error code if that was zero. Note
3785 * that this differs from normal direct-io semantics, which
3786 * will return -EFOO even if some bytes were written.
3788 if (unlikely(status < 0)) {
3793 * We need to ensure that the page cache pages are written to
3794 * disk and invalidated to preserve the expected O_DIRECT
3797 endbyte = pos + status - 1;
3798 err = filemap_write_and_wait_range(mapping, pos, endbyte);
3800 iocb->ki_pos = endbyte + 1;
3802 invalidate_mapping_pages(mapping,
3804 endbyte >> PAGE_SHIFT);
3807 * We don't know how much we wrote, so just return
3808 * the number of bytes which were direct-written
3812 written = generic_perform_write(file, from, iocb->ki_pos);
3813 if (likely(written > 0))
3814 iocb->ki_pos += written;
3817 current->backing_dev_info = NULL;
3818 return written ? written : err;
3820 EXPORT_SYMBOL(__generic_file_write_iter);
3823 * generic_file_write_iter - write data to a file
3824 * @iocb: IO state structure
3825 * @from: iov_iter with data to write
3827 * This is a wrapper around __generic_file_write_iter() to be used by most
3828 * filesystems. It takes care of syncing the file in case of O_SYNC file
3829 * and acquires i_rwsem as needed.
3831 * * negative error code if no data has been written at all of
3832 * vfs_fsync_range() failed for a synchronous write
3833 * * number of bytes written, even for truncated writes
3835 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3837 struct file *file = iocb->ki_filp;
3838 struct inode *inode = file->f_mapping->host;
3842 ret = generic_write_checks(iocb, from);
3844 ret = __generic_file_write_iter(iocb, from);
3845 inode_unlock(inode);
3848 ret = generic_write_sync(iocb, ret);
3851 EXPORT_SYMBOL(generic_file_write_iter);
3854 * filemap_release_folio() - Release fs-specific metadata on a folio.
3855 * @folio: The folio which the kernel is trying to free.
3856 * @gfp: Memory allocation flags (and I/O mode).
3858 * The address_space is trying to release any data attached to a folio
3859 * (presumably at folio->private).
3861 * This will also be called if the private_2 flag is set on a page,
3862 * indicating that the folio has other metadata associated with it.
3864 * The @gfp argument specifies whether I/O may be performed to release
3865 * this page (__GFP_IO), and whether the call may block
3866 * (__GFP_RECLAIM & __GFP_FS).
3868 * Return: %true if the release was successful, otherwise %false.
3870 bool filemap_release_folio(struct folio *folio, gfp_t gfp)
3872 struct address_space * const mapping = folio->mapping;
3874 BUG_ON(!folio_test_locked(folio));
3875 if (folio_test_writeback(folio))
3878 if (mapping && mapping->a_ops->releasepage)
3879 return mapping->a_ops->releasepage(&folio->page, gfp);
3880 return try_to_free_buffers(&folio->page);
3882 EXPORT_SYMBOL(filemap_release_folio);