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/blkdev.h>
34 #include <linux/security.h>
35 #include <linux/cpuset.h>
36 #include <linux/hugetlb.h>
37 #include <linux/memcontrol.h>
38 #include <linux/cleancache.h>
39 #include <linux/shmem_fs.h>
40 #include <linux/rmap.h>
41 #include <linux/delayacct.h>
42 #include <linux/psi.h>
43 #include <linux/ramfs.h>
44 #include <linux/page_idle.h>
45 #include <asm/pgalloc.h>
46 #include <asm/tlbflush.h>
49 #define CREATE_TRACE_POINTS
50 #include <trace/events/filemap.h>
53 * FIXME: remove all knowledge of the buffer layer from the core VM
55 #include <linux/buffer_head.h> /* for try_to_free_buffers */
60 * Shared mappings implemented 30.11.1994. It's not fully working yet,
63 * Shared mappings now work. 15.8.1995 Bruno.
65 * finished 'unifying' the page and buffer cache and SMP-threaded the
66 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
68 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
74 * ->i_mmap_rwsem (truncate_pagecache)
75 * ->private_lock (__free_pte->__set_page_dirty_buffers)
76 * ->swap_lock (exclusive_swap_page, others)
80 * ->invalidate_lock (acquired by fs in truncate path)
81 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
85 * ->page_table_lock or pte_lock (various, mainly in memory.c)
86 * ->i_pages lock (arch-dependent flush_dcache_mmap_lock)
89 * ->invalidate_lock (filemap_fault)
90 * ->lock_page (filemap_fault, access_process_vm)
92 * ->i_rwsem (generic_perform_write)
93 * ->mmap_lock (fault_in_pages_readable->do_page_fault)
96 * sb_lock (fs/fs-writeback.c)
97 * ->i_pages lock (__sync_single_inode)
100 * ->anon_vma.lock (vma_adjust)
103 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
105 * ->page_table_lock or pte_lock
106 * ->swap_lock (try_to_unmap_one)
107 * ->private_lock (try_to_unmap_one)
108 * ->i_pages lock (try_to_unmap_one)
109 * ->lruvec->lru_lock (follow_page->mark_page_accessed)
110 * ->lruvec->lru_lock (check_pte_range->isolate_lru_page)
111 * ->private_lock (page_remove_rmap->set_page_dirty)
112 * ->i_pages lock (page_remove_rmap->set_page_dirty)
113 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
114 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
115 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
116 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
117 * ->inode->i_lock (zap_pte_range->set_page_dirty)
118 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
121 * ->tasklist_lock (memory_failure, collect_procs_ao)
124 static void page_cache_delete(struct address_space *mapping,
125 struct page *page, void *shadow)
127 XA_STATE(xas, &mapping->i_pages, page->index);
130 mapping_set_update(&xas, mapping);
132 /* hugetlb pages are represented by a single entry in the xarray */
133 if (!PageHuge(page)) {
134 xas_set_order(&xas, page->index, compound_order(page));
135 nr = compound_nr(page);
138 VM_BUG_ON_PAGE(!PageLocked(page), page);
139 VM_BUG_ON_PAGE(PageTail(page), page);
140 VM_BUG_ON_PAGE(nr != 1 && shadow, page);
142 xas_store(&xas, shadow);
143 xas_init_marks(&xas);
145 page->mapping = NULL;
146 /* Leave page->index set: truncation lookup relies upon it */
147 mapping->nrpages -= nr;
150 static void unaccount_page_cache_page(struct address_space *mapping,
156 * if we're uptodate, flush out into the cleancache, otherwise
157 * invalidate any existing cleancache entries. We can't leave
158 * stale data around in the cleancache once our page is gone
160 if (PageUptodate(page) && PageMappedToDisk(page))
161 cleancache_put_page(page);
163 cleancache_invalidate_page(mapping, page);
165 VM_BUG_ON_PAGE(PageTail(page), page);
166 VM_BUG_ON_PAGE(page_mapped(page), page);
167 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
170 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
171 current->comm, page_to_pfn(page));
172 dump_page(page, "still mapped when deleted");
174 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
176 mapcount = page_mapcount(page);
177 if (mapping_exiting(mapping) &&
178 page_count(page) >= mapcount + 2) {
180 * All vmas have already been torn down, so it's
181 * a good bet that actually the page is unmapped,
182 * and we'd prefer not to leak it: if we're wrong,
183 * some other bad page check should catch it later.
185 page_mapcount_reset(page);
186 page_ref_sub(page, mapcount);
190 /* hugetlb pages do not participate in page cache accounting. */
194 nr = thp_nr_pages(page);
196 __mod_lruvec_page_state(page, NR_FILE_PAGES, -nr);
197 if (PageSwapBacked(page)) {
198 __mod_lruvec_page_state(page, NR_SHMEM, -nr);
199 if (PageTransHuge(page))
200 __mod_lruvec_page_state(page, NR_SHMEM_THPS, -nr);
201 } else if (PageTransHuge(page)) {
202 __mod_lruvec_page_state(page, NR_FILE_THPS, -nr);
203 filemap_nr_thps_dec(mapping);
207 * At this point page must be either written or cleaned by
208 * truncate. Dirty page here signals a bug and loss of
211 * This fixes dirty accounting after removing the page entirely
212 * but leaves PageDirty set: it has no effect for truncated
213 * page and anyway will be cleared before returning page into
216 if (WARN_ON_ONCE(PageDirty(page)))
217 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
221 * Delete a page from the page cache and free it. Caller has to make
222 * sure the page is locked and that nobody else uses it - or that usage
223 * is safe. The caller must hold the i_pages lock.
225 void __delete_from_page_cache(struct page *page, void *shadow)
227 struct address_space *mapping = page->mapping;
229 trace_mm_filemap_delete_from_page_cache(page);
231 unaccount_page_cache_page(mapping, page);
232 page_cache_delete(mapping, page, shadow);
235 static void page_cache_free_page(struct address_space *mapping,
238 void (*freepage)(struct page *);
240 freepage = mapping->a_ops->freepage;
244 if (PageTransHuge(page) && !PageHuge(page)) {
245 page_ref_sub(page, thp_nr_pages(page));
246 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
253 * delete_from_page_cache - delete page from page cache
254 * @page: the page which the kernel is trying to remove from page cache
256 * This must be called only on pages that have been verified to be in the page
257 * cache and locked. It will never put the page into the free list, the caller
258 * has a reference on the page.
260 void delete_from_page_cache(struct page *page)
262 struct address_space *mapping = page_mapping(page);
265 BUG_ON(!PageLocked(page));
266 xa_lock_irqsave(&mapping->i_pages, flags);
267 __delete_from_page_cache(page, NULL);
268 xa_unlock_irqrestore(&mapping->i_pages, flags);
270 page_cache_free_page(mapping, page);
272 EXPORT_SYMBOL(delete_from_page_cache);
275 * page_cache_delete_batch - delete several pages from page cache
276 * @mapping: the mapping to which pages belong
277 * @pvec: pagevec with pages to delete
279 * The function walks over mapping->i_pages and removes pages passed in @pvec
280 * from the mapping. The function expects @pvec to be sorted by page index
281 * and is optimised for it to be dense.
282 * It tolerates holes in @pvec (mapping entries at those indices are not
283 * modified). The function expects only THP head pages to be present in the
286 * The function expects the i_pages lock to be held.
288 static void page_cache_delete_batch(struct address_space *mapping,
289 struct pagevec *pvec)
291 XA_STATE(xas, &mapping->i_pages, pvec->pages[0]->index);
296 mapping_set_update(&xas, mapping);
297 xas_for_each(&xas, page, ULONG_MAX) {
298 if (i >= pagevec_count(pvec))
301 /* A swap/dax/shadow entry got inserted? Skip it. */
302 if (xa_is_value(page))
305 * A page got inserted in our range? Skip it. We have our
306 * pages locked so they are protected from being removed.
307 * If we see a page whose index is higher than ours, it
308 * means our page has been removed, which shouldn't be
309 * possible because we're holding the PageLock.
311 if (page != pvec->pages[i]) {
312 VM_BUG_ON_PAGE(page->index > pvec->pages[i]->index,
317 WARN_ON_ONCE(!PageLocked(page));
319 if (page->index == xas.xa_index)
320 page->mapping = NULL;
321 /* Leave page->index set: truncation lookup relies on it */
324 * Move to the next page in the vector if this is a regular
325 * page or the index is of the last sub-page of this compound
328 if (page->index + compound_nr(page) - 1 == xas.xa_index)
330 xas_store(&xas, NULL);
333 mapping->nrpages -= total_pages;
336 void delete_from_page_cache_batch(struct address_space *mapping,
337 struct pagevec *pvec)
342 if (!pagevec_count(pvec))
345 xa_lock_irqsave(&mapping->i_pages, flags);
346 for (i = 0; i < pagevec_count(pvec); i++) {
347 trace_mm_filemap_delete_from_page_cache(pvec->pages[i]);
349 unaccount_page_cache_page(mapping, pvec->pages[i]);
351 page_cache_delete_batch(mapping, pvec);
352 xa_unlock_irqrestore(&mapping->i_pages, flags);
354 for (i = 0; i < pagevec_count(pvec); i++)
355 page_cache_free_page(mapping, pvec->pages[i]);
358 int filemap_check_errors(struct address_space *mapping)
361 /* Check for outstanding write errors */
362 if (test_bit(AS_ENOSPC, &mapping->flags) &&
363 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
365 if (test_bit(AS_EIO, &mapping->flags) &&
366 test_and_clear_bit(AS_EIO, &mapping->flags))
370 EXPORT_SYMBOL(filemap_check_errors);
372 static int filemap_check_and_keep_errors(struct address_space *mapping)
374 /* Check for outstanding write errors */
375 if (test_bit(AS_EIO, &mapping->flags))
377 if (test_bit(AS_ENOSPC, &mapping->flags))
383 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
384 * @mapping: address space structure to write
385 * @start: offset in bytes where the range starts
386 * @end: offset in bytes where the range ends (inclusive)
387 * @sync_mode: enable synchronous operation
389 * Start writeback against all of a mapping's dirty pages that lie
390 * within the byte offsets <start, end> inclusive.
392 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
393 * opposed to a regular memory cleansing writeback. The difference between
394 * these two operations is that if a dirty page/buffer is encountered, it must
395 * be waited upon, and not just skipped over.
397 * Return: %0 on success, negative error code otherwise.
399 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
400 loff_t end, int sync_mode)
403 struct writeback_control wbc = {
404 .sync_mode = sync_mode,
405 .nr_to_write = LONG_MAX,
406 .range_start = start,
410 if (!mapping_can_writeback(mapping) ||
411 !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
414 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
415 ret = do_writepages(mapping, &wbc);
416 wbc_detach_inode(&wbc);
420 static inline int __filemap_fdatawrite(struct address_space *mapping,
423 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
426 int filemap_fdatawrite(struct address_space *mapping)
428 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
430 EXPORT_SYMBOL(filemap_fdatawrite);
432 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
435 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
437 EXPORT_SYMBOL(filemap_fdatawrite_range);
440 * filemap_flush - mostly a non-blocking flush
441 * @mapping: target address_space
443 * This is a mostly non-blocking flush. Not suitable for data-integrity
444 * purposes - I/O may not be started against all dirty pages.
446 * Return: %0 on success, negative error code otherwise.
448 int filemap_flush(struct address_space *mapping)
450 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
452 EXPORT_SYMBOL(filemap_flush);
455 * filemap_range_has_page - check if a page exists in range.
456 * @mapping: address space within which to check
457 * @start_byte: offset in bytes where the range starts
458 * @end_byte: offset in bytes where the range ends (inclusive)
460 * Find at least one page in the range supplied, usually used to check if
461 * direct writing in this range will trigger a writeback.
463 * Return: %true if at least one page exists in the specified range,
466 bool filemap_range_has_page(struct address_space *mapping,
467 loff_t start_byte, loff_t end_byte)
470 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
471 pgoff_t max = end_byte >> PAGE_SHIFT;
473 if (end_byte < start_byte)
478 page = xas_find(&xas, max);
479 if (xas_retry(&xas, page))
481 /* Shadow entries don't count */
482 if (xa_is_value(page))
485 * We don't need to try to pin this page; we're about to
486 * release the RCU lock anyway. It is enough to know that
487 * there was a page here recently.
495 EXPORT_SYMBOL(filemap_range_has_page);
497 static void __filemap_fdatawait_range(struct address_space *mapping,
498 loff_t start_byte, loff_t end_byte)
500 pgoff_t index = start_byte >> PAGE_SHIFT;
501 pgoff_t end = end_byte >> PAGE_SHIFT;
505 if (end_byte < start_byte)
509 while (index <= end) {
512 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
513 end, PAGECACHE_TAG_WRITEBACK);
517 for (i = 0; i < nr_pages; i++) {
518 struct page *page = pvec.pages[i];
520 wait_on_page_writeback(page);
521 ClearPageError(page);
523 pagevec_release(&pvec);
529 * filemap_fdatawait_range - wait for writeback to complete
530 * @mapping: address space structure to wait for
531 * @start_byte: offset in bytes where the range starts
532 * @end_byte: offset in bytes where the range ends (inclusive)
534 * Walk the list of under-writeback pages of the given address space
535 * in the given range and wait for all of them. Check error status of
536 * the address space and return it.
538 * Since the error status of the address space is cleared by this function,
539 * callers are responsible for checking the return value and handling and/or
540 * reporting the error.
542 * Return: error status of the address space.
544 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
547 __filemap_fdatawait_range(mapping, start_byte, end_byte);
548 return filemap_check_errors(mapping);
550 EXPORT_SYMBOL(filemap_fdatawait_range);
553 * filemap_fdatawait_range_keep_errors - wait for writeback to complete
554 * @mapping: address space structure to wait for
555 * @start_byte: offset in bytes where the range starts
556 * @end_byte: offset in bytes where the range ends (inclusive)
558 * Walk the list of under-writeback pages of the given address space in the
559 * given range and wait for all of them. Unlike filemap_fdatawait_range(),
560 * this function does not clear error status of the address space.
562 * Use this function if callers don't handle errors themselves. Expected
563 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
566 int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
567 loff_t start_byte, loff_t end_byte)
569 __filemap_fdatawait_range(mapping, start_byte, end_byte);
570 return filemap_check_and_keep_errors(mapping);
572 EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
575 * file_fdatawait_range - wait for writeback to complete
576 * @file: file pointing to address space structure to wait for
577 * @start_byte: offset in bytes where the range starts
578 * @end_byte: offset in bytes where the range ends (inclusive)
580 * Walk the list of under-writeback pages of the address space that file
581 * refers to, in the given range and wait for all of them. Check error
582 * status of the address space vs. the file->f_wb_err cursor and return it.
584 * Since the error status of the file is advanced by this function,
585 * callers are responsible for checking the return value and handling and/or
586 * reporting the error.
588 * Return: error status of the address space vs. the file->f_wb_err cursor.
590 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
592 struct address_space *mapping = file->f_mapping;
594 __filemap_fdatawait_range(mapping, start_byte, end_byte);
595 return file_check_and_advance_wb_err(file);
597 EXPORT_SYMBOL(file_fdatawait_range);
600 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
601 * @mapping: address space structure to wait for
603 * Walk the list of under-writeback pages of the given address space
604 * and wait for all of them. Unlike filemap_fdatawait(), this function
605 * does not clear error status of the address space.
607 * Use this function if callers don't handle errors themselves. Expected
608 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
611 * Return: error status of the address space.
613 int filemap_fdatawait_keep_errors(struct address_space *mapping)
615 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
616 return filemap_check_and_keep_errors(mapping);
618 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
620 /* Returns true if writeback might be needed or already in progress. */
621 static bool mapping_needs_writeback(struct address_space *mapping)
623 return mapping->nrpages;
627 * filemap_range_needs_writeback - check if range potentially needs writeback
628 * @mapping: address space within which to check
629 * @start_byte: offset in bytes where the range starts
630 * @end_byte: offset in bytes where the range ends (inclusive)
632 * Find at least one page in the range supplied, usually used to check if
633 * direct writing in this range will trigger a writeback. Used by O_DIRECT
634 * read/write with IOCB_NOWAIT, to see if the caller needs to do
635 * filemap_write_and_wait_range() before proceeding.
637 * Return: %true if the caller should do filemap_write_and_wait_range() before
638 * doing O_DIRECT to a page in this range, %false otherwise.
640 bool filemap_range_needs_writeback(struct address_space *mapping,
641 loff_t start_byte, loff_t end_byte)
643 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
644 pgoff_t max = end_byte >> PAGE_SHIFT;
647 if (!mapping_needs_writeback(mapping))
649 if (!mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
650 !mapping_tagged(mapping, PAGECACHE_TAG_WRITEBACK))
652 if (end_byte < start_byte)
656 xas_for_each(&xas, page, max) {
657 if (xas_retry(&xas, page))
659 if (xa_is_value(page))
661 if (PageDirty(page) || PageLocked(page) || PageWriteback(page))
667 EXPORT_SYMBOL_GPL(filemap_range_needs_writeback);
670 * filemap_write_and_wait_range - write out & wait on a file range
671 * @mapping: the address_space for the pages
672 * @lstart: offset in bytes where the range starts
673 * @lend: offset in bytes where the range ends (inclusive)
675 * Write out and wait upon file offsets lstart->lend, inclusive.
677 * Note that @lend is inclusive (describes the last byte to be written) so
678 * that this function can be used to write to the very end-of-file (end = -1).
680 * Return: error status of the address space.
682 int filemap_write_and_wait_range(struct address_space *mapping,
683 loff_t lstart, loff_t lend)
687 if (mapping_needs_writeback(mapping)) {
688 err = __filemap_fdatawrite_range(mapping, lstart, lend,
691 * Even if the above returned error, the pages may be
692 * written partially (e.g. -ENOSPC), so we wait for it.
693 * But the -EIO is special case, it may indicate the worst
694 * thing (e.g. bug) happened, so we avoid waiting for it.
697 int err2 = filemap_fdatawait_range(mapping,
702 /* Clear any previously stored errors */
703 filemap_check_errors(mapping);
706 err = filemap_check_errors(mapping);
710 EXPORT_SYMBOL(filemap_write_and_wait_range);
712 void __filemap_set_wb_err(struct address_space *mapping, int err)
714 errseq_t eseq = errseq_set(&mapping->wb_err, err);
716 trace_filemap_set_wb_err(mapping, eseq);
718 EXPORT_SYMBOL(__filemap_set_wb_err);
721 * file_check_and_advance_wb_err - report wb error (if any) that was previously
722 * and advance wb_err to current one
723 * @file: struct file on which the error is being reported
725 * When userland calls fsync (or something like nfsd does the equivalent), we
726 * want to report any writeback errors that occurred since the last fsync (or
727 * since the file was opened if there haven't been any).
729 * Grab the wb_err from the mapping. If it matches what we have in the file,
730 * then just quickly return 0. The file is all caught up.
732 * If it doesn't match, then take the mapping value, set the "seen" flag in
733 * it and try to swap it into place. If it works, or another task beat us
734 * to it with the new value, then update the f_wb_err and return the error
735 * portion. The error at this point must be reported via proper channels
736 * (a'la fsync, or NFS COMMIT operation, etc.).
738 * While we handle mapping->wb_err with atomic operations, the f_wb_err
739 * value is protected by the f_lock since we must ensure that it reflects
740 * the latest value swapped in for this file descriptor.
742 * Return: %0 on success, negative error code otherwise.
744 int file_check_and_advance_wb_err(struct file *file)
747 errseq_t old = READ_ONCE(file->f_wb_err);
748 struct address_space *mapping = file->f_mapping;
750 /* Locklessly handle the common case where nothing has changed */
751 if (errseq_check(&mapping->wb_err, old)) {
752 /* Something changed, must use slow path */
753 spin_lock(&file->f_lock);
754 old = file->f_wb_err;
755 err = errseq_check_and_advance(&mapping->wb_err,
757 trace_file_check_and_advance_wb_err(file, old);
758 spin_unlock(&file->f_lock);
762 * We're mostly using this function as a drop in replacement for
763 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
764 * that the legacy code would have had on these flags.
766 clear_bit(AS_EIO, &mapping->flags);
767 clear_bit(AS_ENOSPC, &mapping->flags);
770 EXPORT_SYMBOL(file_check_and_advance_wb_err);
773 * file_write_and_wait_range - write out & wait on a file range
774 * @file: file pointing to address_space with pages
775 * @lstart: offset in bytes where the range starts
776 * @lend: offset in bytes where the range ends (inclusive)
778 * Write out and wait upon file offsets lstart->lend, inclusive.
780 * Note that @lend is inclusive (describes the last byte to be written) so
781 * that this function can be used to write to the very end-of-file (end = -1).
783 * After writing out and waiting on the data, we check and advance the
784 * f_wb_err cursor to the latest value, and return any errors detected there.
786 * Return: %0 on success, negative error code otherwise.
788 int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
791 struct address_space *mapping = file->f_mapping;
793 if (mapping_needs_writeback(mapping)) {
794 err = __filemap_fdatawrite_range(mapping, lstart, lend,
796 /* See comment of filemap_write_and_wait() */
798 __filemap_fdatawait_range(mapping, lstart, lend);
800 err2 = file_check_and_advance_wb_err(file);
805 EXPORT_SYMBOL(file_write_and_wait_range);
808 * replace_page_cache_page - replace a pagecache page with a new one
809 * @old: page to be replaced
810 * @new: page to replace with
812 * This function replaces a page in the pagecache with a new one. On
813 * success it acquires the pagecache reference for the new page and
814 * drops it for the old page. Both the old and new pages must be
815 * locked. This function does not add the new page to the LRU, the
816 * caller must do that.
818 * The remove + add is atomic. This function cannot fail.
820 void replace_page_cache_page(struct page *old, struct page *new)
822 struct address_space *mapping = old->mapping;
823 void (*freepage)(struct page *) = mapping->a_ops->freepage;
824 pgoff_t offset = old->index;
825 XA_STATE(xas, &mapping->i_pages, offset);
828 VM_BUG_ON_PAGE(!PageLocked(old), old);
829 VM_BUG_ON_PAGE(!PageLocked(new), new);
830 VM_BUG_ON_PAGE(new->mapping, new);
833 new->mapping = mapping;
836 mem_cgroup_migrate(old, new);
838 xas_lock_irqsave(&xas, flags);
839 xas_store(&xas, new);
842 /* hugetlb pages do not participate in page cache accounting. */
844 __dec_lruvec_page_state(old, NR_FILE_PAGES);
846 __inc_lruvec_page_state(new, NR_FILE_PAGES);
847 if (PageSwapBacked(old))
848 __dec_lruvec_page_state(old, NR_SHMEM);
849 if (PageSwapBacked(new))
850 __inc_lruvec_page_state(new, NR_SHMEM);
851 xas_unlock_irqrestore(&xas, flags);
856 EXPORT_SYMBOL_GPL(replace_page_cache_page);
858 noinline int __add_to_page_cache_locked(struct page *page,
859 struct address_space *mapping,
860 pgoff_t offset, gfp_t gfp,
863 XA_STATE(xas, &mapping->i_pages, offset);
864 int huge = PageHuge(page);
866 bool charged = false;
868 VM_BUG_ON_PAGE(!PageLocked(page), page);
869 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
870 mapping_set_update(&xas, mapping);
873 page->mapping = mapping;
874 page->index = offset;
877 error = mem_cgroup_charge(page, NULL, gfp);
883 gfp &= GFP_RECLAIM_MASK;
886 unsigned int order = xa_get_order(xas.xa, xas.xa_index);
887 void *entry, *old = NULL;
889 if (order > thp_order(page))
890 xas_split_alloc(&xas, xa_load(xas.xa, xas.xa_index),
893 xas_for_each_conflict(&xas, entry) {
895 if (!xa_is_value(entry)) {
896 xas_set_err(&xas, -EEXIST);
904 /* entry may have been split before we acquired lock */
905 order = xa_get_order(xas.xa, xas.xa_index);
906 if (order > thp_order(page)) {
907 xas_split(&xas, old, order);
912 xas_store(&xas, page);
918 /* hugetlb pages do not participate in page cache accounting */
920 __inc_lruvec_page_state(page, NR_FILE_PAGES);
922 xas_unlock_irq(&xas);
923 } while (xas_nomem(&xas, gfp));
925 if (xas_error(&xas)) {
926 error = xas_error(&xas);
928 mem_cgroup_uncharge(page);
932 trace_mm_filemap_add_to_page_cache(page);
935 page->mapping = NULL;
936 /* Leave page->index set: truncation relies upon it */
940 ALLOW_ERROR_INJECTION(__add_to_page_cache_locked, ERRNO);
943 * add_to_page_cache_locked - add a locked page to the pagecache
945 * @mapping: the page's address_space
946 * @offset: page index
947 * @gfp_mask: page allocation mode
949 * This function is used to add a page to the pagecache. It must be locked.
950 * This function does not add the page to the LRU. The caller must do that.
952 * Return: %0 on success, negative error code otherwise.
954 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
955 pgoff_t offset, gfp_t gfp_mask)
957 return __add_to_page_cache_locked(page, mapping, offset,
960 EXPORT_SYMBOL(add_to_page_cache_locked);
962 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
963 pgoff_t offset, gfp_t gfp_mask)
968 __SetPageLocked(page);
969 ret = __add_to_page_cache_locked(page, mapping, offset,
972 __ClearPageLocked(page);
975 * The page might have been evicted from cache only
976 * recently, in which case it should be activated like
977 * any other repeatedly accessed page.
978 * The exception is pages getting rewritten; evicting other
979 * data from the working set, only to cache data that will
980 * get overwritten with something else, is a waste of memory.
982 WARN_ON_ONCE(PageActive(page));
983 if (!(gfp_mask & __GFP_WRITE) && shadow)
984 workingset_refault(page, shadow);
989 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
992 struct page *__page_cache_alloc(gfp_t gfp)
997 if (cpuset_do_page_mem_spread()) {
998 unsigned int cpuset_mems_cookie;
1000 cpuset_mems_cookie = read_mems_allowed_begin();
1001 n = cpuset_mem_spread_node();
1002 page = __alloc_pages_node(n, gfp, 0);
1003 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
1007 return alloc_pages(gfp, 0);
1009 EXPORT_SYMBOL(__page_cache_alloc);
1013 * filemap_invalidate_lock_two - lock invalidate_lock for two mappings
1015 * Lock exclusively invalidate_lock of any passed mapping that is not NULL.
1017 * @mapping1: the first mapping to lock
1018 * @mapping2: the second mapping to lock
1020 void filemap_invalidate_lock_two(struct address_space *mapping1,
1021 struct address_space *mapping2)
1023 if (mapping1 > mapping2)
1024 swap(mapping1, mapping2);
1026 down_write(&mapping1->invalidate_lock);
1027 if (mapping2 && mapping1 != mapping2)
1028 down_write_nested(&mapping2->invalidate_lock, 1);
1030 EXPORT_SYMBOL(filemap_invalidate_lock_two);
1033 * filemap_invalidate_unlock_two - unlock invalidate_lock for two mappings
1035 * Unlock exclusive invalidate_lock of any passed mapping that is not NULL.
1037 * @mapping1: the first mapping to unlock
1038 * @mapping2: the second mapping to unlock
1040 void filemap_invalidate_unlock_two(struct address_space *mapping1,
1041 struct address_space *mapping2)
1044 up_write(&mapping1->invalidate_lock);
1045 if (mapping2 && mapping1 != mapping2)
1046 up_write(&mapping2->invalidate_lock);
1048 EXPORT_SYMBOL(filemap_invalidate_unlock_two);
1051 * In order to wait for pages to become available there must be
1052 * waitqueues associated with pages. By using a hash table of
1053 * waitqueues where the bucket discipline is to maintain all
1054 * waiters on the same queue and wake all when any of the pages
1055 * become available, and for the woken contexts to check to be
1056 * sure the appropriate page became available, this saves space
1057 * at a cost of "thundering herd" phenomena during rare hash
1060 #define PAGE_WAIT_TABLE_BITS 8
1061 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
1062 static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
1064 static wait_queue_head_t *page_waitqueue(struct page *page)
1066 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
1069 void __init pagecache_init(void)
1073 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1074 init_waitqueue_head(&page_wait_table[i]);
1076 page_writeback_init();
1080 * The page wait code treats the "wait->flags" somewhat unusually, because
1081 * we have multiple different kinds of waits, not just the usual "exclusive"
1086 * (a) no special bits set:
1088 * We're just waiting for the bit to be released, and when a waker
1089 * calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up,
1090 * and remove it from the wait queue.
1092 * Simple and straightforward.
1094 * (b) WQ_FLAG_EXCLUSIVE:
1096 * The waiter is waiting to get the lock, and only one waiter should
1097 * be woken up to avoid any thundering herd behavior. We'll set the
1098 * WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue.
1100 * This is the traditional exclusive wait.
1102 * (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
1104 * The waiter is waiting to get the bit, and additionally wants the
1105 * lock to be transferred to it for fair lock behavior. If the lock
1106 * cannot be taken, we stop walking the wait queue without waking
1109 * This is the "fair lock handoff" case, and in addition to setting
1110 * WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see
1111 * that it now has the lock.
1113 static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
1116 struct wait_page_key *key = arg;
1117 struct wait_page_queue *wait_page
1118 = container_of(wait, struct wait_page_queue, wait);
1120 if (!wake_page_match(wait_page, key))
1124 * If it's a lock handoff wait, we get the bit for it, and
1125 * stop walking (and do not wake it up) if we can't.
1127 flags = wait->flags;
1128 if (flags & WQ_FLAG_EXCLUSIVE) {
1129 if (test_bit(key->bit_nr, &key->page->flags))
1131 if (flags & WQ_FLAG_CUSTOM) {
1132 if (test_and_set_bit(key->bit_nr, &key->page->flags))
1134 flags |= WQ_FLAG_DONE;
1139 * We are holding the wait-queue lock, but the waiter that
1140 * is waiting for this will be checking the flags without
1143 * So update the flags atomically, and wake up the waiter
1144 * afterwards to avoid any races. This store-release pairs
1145 * with the load-acquire in wait_on_page_bit_common().
1147 smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
1148 wake_up_state(wait->private, mode);
1151 * Ok, we have successfully done what we're waiting for,
1152 * and we can unconditionally remove the wait entry.
1154 * Note that this pairs with the "finish_wait()" in the
1155 * waiter, and has to be the absolute last thing we do.
1156 * After this list_del_init(&wait->entry) the wait entry
1157 * might be de-allocated and the process might even have
1160 list_del_init_careful(&wait->entry);
1161 return (flags & WQ_FLAG_EXCLUSIVE) != 0;
1164 static void wake_up_page_bit(struct page *page, int bit_nr)
1166 wait_queue_head_t *q = page_waitqueue(page);
1167 struct wait_page_key key;
1168 unsigned long flags;
1169 wait_queue_entry_t bookmark;
1172 key.bit_nr = bit_nr;
1176 bookmark.private = NULL;
1177 bookmark.func = NULL;
1178 INIT_LIST_HEAD(&bookmark.entry);
1180 spin_lock_irqsave(&q->lock, flags);
1181 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1183 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1185 * Take a breather from holding the lock,
1186 * allow pages that finish wake up asynchronously
1187 * to acquire the lock and remove themselves
1190 spin_unlock_irqrestore(&q->lock, flags);
1192 spin_lock_irqsave(&q->lock, flags);
1193 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1197 * It is possible for other pages to have collided on the waitqueue
1198 * hash, so in that case check for a page match. That prevents a long-
1201 * It is still possible to miss a case here, when we woke page waiters
1202 * and removed them from the waitqueue, but there are still other
1205 if (!waitqueue_active(q) || !key.page_match) {
1206 ClearPageWaiters(page);
1208 * It's possible to miss clearing Waiters here, when we woke
1209 * our page waiters, but the hashed waitqueue has waiters for
1210 * other pages on it.
1212 * That's okay, it's a rare case. The next waker will clear it.
1215 spin_unlock_irqrestore(&q->lock, flags);
1218 static void wake_up_page(struct page *page, int bit)
1220 if (!PageWaiters(page))
1222 wake_up_page_bit(page, bit);
1226 * A choice of three behaviors for wait_on_page_bit_common():
1229 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
1230 * __lock_page() waiting on then setting PG_locked.
1232 SHARED, /* Hold ref to page and check the bit when woken, like
1233 * wait_on_page_writeback() waiting on PG_writeback.
1235 DROP, /* Drop ref to page before wait, no check when woken,
1236 * like put_and_wait_on_page_locked() on PG_locked.
1241 * Attempt to check (or get) the page bit, and mark us done
1244 static inline bool trylock_page_bit_common(struct page *page, int bit_nr,
1245 struct wait_queue_entry *wait)
1247 if (wait->flags & WQ_FLAG_EXCLUSIVE) {
1248 if (test_and_set_bit(bit_nr, &page->flags))
1250 } else if (test_bit(bit_nr, &page->flags))
1253 wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
1257 /* How many times do we accept lock stealing from under a waiter? */
1258 int sysctl_page_lock_unfairness = 5;
1260 static inline int wait_on_page_bit_common(wait_queue_head_t *q,
1261 struct page *page, int bit_nr, int state, enum behavior behavior)
1263 int unfairness = sysctl_page_lock_unfairness;
1264 struct wait_page_queue wait_page;
1265 wait_queue_entry_t *wait = &wait_page.wait;
1266 bool thrashing = false;
1267 bool delayacct = false;
1268 unsigned long pflags;
1270 if (bit_nr == PG_locked &&
1271 !PageUptodate(page) && PageWorkingset(page)) {
1272 if (!PageSwapBacked(page)) {
1273 delayacct_thrashing_start();
1276 psi_memstall_enter(&pflags);
1281 wait->func = wake_page_function;
1282 wait_page.page = page;
1283 wait_page.bit_nr = bit_nr;
1287 if (behavior == EXCLUSIVE) {
1288 wait->flags = WQ_FLAG_EXCLUSIVE;
1289 if (--unfairness < 0)
1290 wait->flags |= WQ_FLAG_CUSTOM;
1294 * Do one last check whether we can get the
1295 * page bit synchronously.
1297 * Do the SetPageWaiters() marking before that
1298 * to let any waker we _just_ missed know they
1299 * need to wake us up (otherwise they'll never
1300 * even go to the slow case that looks at the
1301 * page queue), and add ourselves to the wait
1302 * queue if we need to sleep.
1304 * This part needs to be done under the queue
1305 * lock to avoid races.
1307 spin_lock_irq(&q->lock);
1308 SetPageWaiters(page);
1309 if (!trylock_page_bit_common(page, bit_nr, wait))
1310 __add_wait_queue_entry_tail(q, wait);
1311 spin_unlock_irq(&q->lock);
1314 * From now on, all the logic will be based on
1315 * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to
1316 * see whether the page bit testing has already
1317 * been done by the wake function.
1319 * We can drop our reference to the page.
1321 if (behavior == DROP)
1325 * Note that until the "finish_wait()", or until
1326 * we see the WQ_FLAG_WOKEN flag, we need to
1327 * be very careful with the 'wait->flags', because
1328 * we may race with a waker that sets them.
1333 set_current_state(state);
1335 /* Loop until we've been woken or interrupted */
1336 flags = smp_load_acquire(&wait->flags);
1337 if (!(flags & WQ_FLAG_WOKEN)) {
1338 if (signal_pending_state(state, current))
1345 /* If we were non-exclusive, we're done */
1346 if (behavior != EXCLUSIVE)
1349 /* If the waker got the lock for us, we're done */
1350 if (flags & WQ_FLAG_DONE)
1354 * Otherwise, if we're getting the lock, we need to
1355 * try to get it ourselves.
1357 * And if that fails, we'll have to retry this all.
1359 if (unlikely(test_and_set_bit(bit_nr, &page->flags)))
1362 wait->flags |= WQ_FLAG_DONE;
1367 * If a signal happened, this 'finish_wait()' may remove the last
1368 * waiter from the wait-queues, but the PageWaiters bit will remain
1369 * set. That's ok. The next wakeup will take care of it, and trying
1370 * to do it here would be difficult and prone to races.
1372 finish_wait(q, wait);
1376 delayacct_thrashing_end();
1377 psi_memstall_leave(&pflags);
1381 * NOTE! The wait->flags weren't stable until we've done the
1382 * 'finish_wait()', and we could have exited the loop above due
1383 * to a signal, and had a wakeup event happen after the signal
1384 * test but before the 'finish_wait()'.
1386 * So only after the finish_wait() can we reliably determine
1387 * if we got woken up or not, so we can now figure out the final
1388 * return value based on that state without races.
1390 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
1391 * waiter, but an exclusive one requires WQ_FLAG_DONE.
1393 if (behavior == EXCLUSIVE)
1394 return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
1396 return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
1399 void wait_on_page_bit(struct page *page, int bit_nr)
1401 wait_queue_head_t *q = page_waitqueue(page);
1402 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
1404 EXPORT_SYMBOL(wait_on_page_bit);
1406 int wait_on_page_bit_killable(struct page *page, int bit_nr)
1408 wait_queue_head_t *q = page_waitqueue(page);
1409 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, SHARED);
1411 EXPORT_SYMBOL(wait_on_page_bit_killable);
1414 * put_and_wait_on_page_locked - Drop a reference and wait for it to be unlocked
1415 * @page: The page to wait for.
1416 * @state: The sleep state (TASK_KILLABLE, TASK_UNINTERRUPTIBLE, etc).
1418 * The caller should hold a reference on @page. They expect the page to
1419 * become unlocked relatively soon, but do not wish to hold up migration
1420 * (for example) by holding the reference while waiting for the page to
1421 * come unlocked. After this function returns, the caller should not
1422 * dereference @page.
1424 * Return: 0 if the page was unlocked or -EINTR if interrupted by a signal.
1426 int put_and_wait_on_page_locked(struct page *page, int state)
1428 wait_queue_head_t *q;
1430 page = compound_head(page);
1431 q = page_waitqueue(page);
1432 return wait_on_page_bit_common(q, page, PG_locked, state, DROP);
1436 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
1437 * @page: Page defining the wait queue of interest
1438 * @waiter: Waiter to add to the queue
1440 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1442 void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
1444 wait_queue_head_t *q = page_waitqueue(page);
1445 unsigned long flags;
1447 spin_lock_irqsave(&q->lock, flags);
1448 __add_wait_queue_entry_tail(q, waiter);
1449 SetPageWaiters(page);
1450 spin_unlock_irqrestore(&q->lock, flags);
1452 EXPORT_SYMBOL_GPL(add_page_wait_queue);
1454 #ifndef clear_bit_unlock_is_negative_byte
1457 * PG_waiters is the high bit in the same byte as PG_lock.
1459 * On x86 (and on many other architectures), we can clear PG_lock and
1460 * test the sign bit at the same time. But if the architecture does
1461 * not support that special operation, we just do this all by hand
1464 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1465 * being cleared, but a memory barrier should be unnecessary since it is
1466 * in the same byte as PG_locked.
1468 static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1470 clear_bit_unlock(nr, mem);
1471 /* smp_mb__after_atomic(); */
1472 return test_bit(PG_waiters, mem);
1478 * unlock_page - unlock a locked page
1481 * Unlocks the page and wakes up sleepers in wait_on_page_locked().
1482 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
1483 * mechanism between PageLocked pages and PageWriteback pages is shared.
1484 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1486 * Note that this depends on PG_waiters being the sign bit in the byte
1487 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1488 * clear the PG_locked bit and test PG_waiters at the same time fairly
1489 * portably (architectures that do LL/SC can test any bit, while x86 can
1490 * test the sign bit).
1492 void unlock_page(struct page *page)
1494 BUILD_BUG_ON(PG_waiters != 7);
1495 page = compound_head(page);
1496 VM_BUG_ON_PAGE(!PageLocked(page), page);
1497 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1498 wake_up_page_bit(page, PG_locked);
1500 EXPORT_SYMBOL(unlock_page);
1503 * end_page_private_2 - Clear PG_private_2 and release any waiters
1506 * Clear the PG_private_2 bit on a page and wake up any sleepers waiting for
1507 * this. The page ref held for PG_private_2 being set is released.
1509 * This is, for example, used when a netfs page is being written to a local
1510 * disk cache, thereby allowing writes to the cache for the same page to be
1513 void end_page_private_2(struct page *page)
1515 page = compound_head(page);
1516 VM_BUG_ON_PAGE(!PagePrivate2(page), page);
1517 clear_bit_unlock(PG_private_2, &page->flags);
1518 wake_up_page_bit(page, PG_private_2);
1521 EXPORT_SYMBOL(end_page_private_2);
1524 * wait_on_page_private_2 - Wait for PG_private_2 to be cleared on a page
1525 * @page: The page to wait on
1527 * Wait for PG_private_2 (aka PG_fscache) to be cleared on a page.
1529 void wait_on_page_private_2(struct page *page)
1531 page = compound_head(page);
1532 while (PagePrivate2(page))
1533 wait_on_page_bit(page, PG_private_2);
1535 EXPORT_SYMBOL(wait_on_page_private_2);
1538 * wait_on_page_private_2_killable - Wait for PG_private_2 to be cleared on a page
1539 * @page: The page to wait on
1541 * Wait for PG_private_2 (aka PG_fscache) to be cleared on a page or until a
1542 * fatal signal is received by the calling task.
1545 * - 0 if successful.
1546 * - -EINTR if a fatal signal was encountered.
1548 int wait_on_page_private_2_killable(struct page *page)
1552 page = compound_head(page);
1553 while (PagePrivate2(page)) {
1554 ret = wait_on_page_bit_killable(page, PG_private_2);
1561 EXPORT_SYMBOL(wait_on_page_private_2_killable);
1564 * end_page_writeback - end writeback against a page
1567 void end_page_writeback(struct page *page)
1570 * TestClearPageReclaim could be used here but it is an atomic
1571 * operation and overkill in this particular case. Failing to
1572 * shuffle a page marked for immediate reclaim is too mild to
1573 * justify taking an atomic operation penalty at the end of
1574 * ever page writeback.
1576 if (PageReclaim(page)) {
1577 ClearPageReclaim(page);
1578 rotate_reclaimable_page(page);
1582 * Writeback does not hold a page reference of its own, relying
1583 * on truncation to wait for the clearing of PG_writeback.
1584 * But here we must make sure that the page is not freed and
1585 * reused before the wake_up_page().
1588 if (!test_clear_page_writeback(page))
1591 smp_mb__after_atomic();
1592 wake_up_page(page, PG_writeback);
1595 EXPORT_SYMBOL(end_page_writeback);
1598 * After completing I/O on a page, call this routine to update the page
1599 * flags appropriately
1601 void page_endio(struct page *page, bool is_write, int err)
1605 SetPageUptodate(page);
1607 ClearPageUptodate(page);
1613 struct address_space *mapping;
1616 mapping = page_mapping(page);
1618 mapping_set_error(mapping, err);
1620 end_page_writeback(page);
1623 EXPORT_SYMBOL_GPL(page_endio);
1626 * __lock_page - get a lock on the page, assuming we need to sleep to get it
1627 * @__page: the page to lock
1629 void __lock_page(struct page *__page)
1631 struct page *page = compound_head(__page);
1632 wait_queue_head_t *q = page_waitqueue(page);
1633 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE,
1636 EXPORT_SYMBOL(__lock_page);
1638 int __lock_page_killable(struct page *__page)
1640 struct page *page = compound_head(__page);
1641 wait_queue_head_t *q = page_waitqueue(page);
1642 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE,
1645 EXPORT_SYMBOL_GPL(__lock_page_killable);
1647 int __lock_page_async(struct page *page, struct wait_page_queue *wait)
1649 struct wait_queue_head *q = page_waitqueue(page);
1653 wait->bit_nr = PG_locked;
1655 spin_lock_irq(&q->lock);
1656 __add_wait_queue_entry_tail(q, &wait->wait);
1657 SetPageWaiters(page);
1658 ret = !trylock_page(page);
1660 * If we were successful now, we know we're still on the
1661 * waitqueue as we're still under the lock. This means it's
1662 * safe to remove and return success, we know the callback
1663 * isn't going to trigger.
1666 __remove_wait_queue(q, &wait->wait);
1669 spin_unlock_irq(&q->lock);
1675 * 1 - page is locked; mmap_lock is still held.
1676 * 0 - page is not locked.
1677 * mmap_lock has been released (mmap_read_unlock(), unless flags had both
1678 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1679 * which case mmap_lock is still held.
1681 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1682 * with the page locked and the mmap_lock unperturbed.
1684 int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1687 if (fault_flag_allow_retry_first(flags)) {
1689 * CAUTION! In this case, mmap_lock is not released
1690 * even though return 0.
1692 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1695 mmap_read_unlock(mm);
1696 if (flags & FAULT_FLAG_KILLABLE)
1697 wait_on_page_locked_killable(page);
1699 wait_on_page_locked(page);
1702 if (flags & FAULT_FLAG_KILLABLE) {
1705 ret = __lock_page_killable(page);
1707 mmap_read_unlock(mm);
1718 * page_cache_next_miss() - Find the next gap in the page cache.
1719 * @mapping: Mapping.
1721 * @max_scan: Maximum range to search.
1723 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1724 * gap with the lowest index.
1726 * This function may be called under the rcu_read_lock. However, this will
1727 * not atomically search a snapshot of the cache at a single point in time.
1728 * For example, if a gap is created at index 5, then subsequently a gap is
1729 * created at index 10, page_cache_next_miss covering both indices may
1730 * return 10 if called under the rcu_read_lock.
1732 * Return: The index of the gap if found, otherwise an index outside the
1733 * range specified (in which case 'return - index >= max_scan' will be true).
1734 * In the rare case of index wrap-around, 0 will be returned.
1736 pgoff_t page_cache_next_miss(struct address_space *mapping,
1737 pgoff_t index, unsigned long max_scan)
1739 XA_STATE(xas, &mapping->i_pages, index);
1741 while (max_scan--) {
1742 void *entry = xas_next(&xas);
1743 if (!entry || xa_is_value(entry))
1745 if (xas.xa_index == 0)
1749 return xas.xa_index;
1751 EXPORT_SYMBOL(page_cache_next_miss);
1754 * page_cache_prev_miss() - Find the previous gap in the page cache.
1755 * @mapping: Mapping.
1757 * @max_scan: Maximum range to search.
1759 * Search the range [max(index - max_scan + 1, 0), index] for the
1760 * gap with the highest index.
1762 * This function may be called under the rcu_read_lock. However, this will
1763 * not atomically search a snapshot of the cache at a single point in time.
1764 * For example, if a gap is created at index 10, then subsequently a gap is
1765 * created at index 5, page_cache_prev_miss() covering both indices may
1766 * return 5 if called under the rcu_read_lock.
1768 * Return: The index of the gap if found, otherwise an index outside the
1769 * range specified (in which case 'index - return >= max_scan' will be true).
1770 * In the rare case of wrap-around, ULONG_MAX will be returned.
1772 pgoff_t page_cache_prev_miss(struct address_space *mapping,
1773 pgoff_t index, unsigned long max_scan)
1775 XA_STATE(xas, &mapping->i_pages, index);
1777 while (max_scan--) {
1778 void *entry = xas_prev(&xas);
1779 if (!entry || xa_is_value(entry))
1781 if (xas.xa_index == ULONG_MAX)
1785 return xas.xa_index;
1787 EXPORT_SYMBOL(page_cache_prev_miss);
1790 * mapping_get_entry - Get a page cache entry.
1791 * @mapping: the address_space to search
1792 * @index: The page cache index.
1794 * Looks up the page cache slot at @mapping & @index. If there is a
1795 * page cache page, the head page is returned with an increased refcount.
1797 * If the slot holds a shadow entry of a previously evicted page, or a
1798 * swap entry from shmem/tmpfs, it is returned.
1800 * Return: The head page or shadow entry, %NULL if nothing is found.
1802 static struct page *mapping_get_entry(struct address_space *mapping,
1805 XA_STATE(xas, &mapping->i_pages, index);
1811 page = xas_load(&xas);
1812 if (xas_retry(&xas, page))
1815 * A shadow entry of a recently evicted page, or a swap entry from
1816 * shmem/tmpfs. Return it without attempting to raise page count.
1818 if (!page || xa_is_value(page))
1821 if (!page_cache_get_speculative(page))
1825 * Has the page moved or been split?
1826 * This is part of the lockless pagecache protocol. See
1827 * include/linux/pagemap.h for details.
1829 if (unlikely(page != xas_reload(&xas))) {
1840 * pagecache_get_page - Find and get a reference to a page.
1841 * @mapping: The address_space to search.
1842 * @index: The page index.
1843 * @fgp_flags: %FGP flags modify how the page is returned.
1844 * @gfp_mask: Memory allocation flags to use if %FGP_CREAT is specified.
1846 * Looks up the page cache entry at @mapping & @index.
1848 * @fgp_flags can be zero or more of these flags:
1850 * * %FGP_ACCESSED - The page will be marked accessed.
1851 * * %FGP_LOCK - The page is returned locked.
1852 * * %FGP_HEAD - If the page is present and a THP, return the head page
1853 * rather than the exact page specified by the index.
1854 * * %FGP_ENTRY - If there is a shadow / swap / DAX entry, return it
1855 * instead of allocating a new page to replace it.
1856 * * %FGP_CREAT - If no page is present then a new page is allocated using
1857 * @gfp_mask and added to the page cache and the VM's LRU list.
1858 * The page is returned locked and with an increased refcount.
1859 * * %FGP_FOR_MMAP - The caller wants to do its own locking dance if the
1860 * page is already in cache. If the page was allocated, unlock it before
1861 * returning so the caller can do the same dance.
1862 * * %FGP_WRITE - The page will be written
1863 * * %FGP_NOFS - __GFP_FS will get cleared in gfp mask
1864 * * %FGP_NOWAIT - Don't get blocked by page lock
1866 * If %FGP_LOCK or %FGP_CREAT are specified then the function may sleep even
1867 * if the %GFP flags specified for %FGP_CREAT are atomic.
1869 * If there is a page cache page, it is returned with an increased refcount.
1871 * Return: The found page or %NULL otherwise.
1873 struct page *pagecache_get_page(struct address_space *mapping, pgoff_t index,
1874 int fgp_flags, gfp_t gfp_mask)
1879 page = mapping_get_entry(mapping, index);
1880 if (xa_is_value(page)) {
1881 if (fgp_flags & FGP_ENTRY)
1888 if (fgp_flags & FGP_LOCK) {
1889 if (fgp_flags & FGP_NOWAIT) {
1890 if (!trylock_page(page)) {
1898 /* Has the page been truncated? */
1899 if (unlikely(page->mapping != mapping)) {
1904 VM_BUG_ON_PAGE(!thp_contains(page, index), page);
1907 if (fgp_flags & FGP_ACCESSED)
1908 mark_page_accessed(page);
1909 else if (fgp_flags & FGP_WRITE) {
1910 /* Clear idle flag for buffer write */
1911 if (page_is_idle(page))
1912 clear_page_idle(page);
1914 if (!(fgp_flags & FGP_HEAD))
1915 page = find_subpage(page, index);
1918 if (!page && (fgp_flags & FGP_CREAT)) {
1920 if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping))
1921 gfp_mask |= __GFP_WRITE;
1922 if (fgp_flags & FGP_NOFS)
1923 gfp_mask &= ~__GFP_FS;
1925 page = __page_cache_alloc(gfp_mask);
1929 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
1930 fgp_flags |= FGP_LOCK;
1932 /* Init accessed so avoid atomic mark_page_accessed later */
1933 if (fgp_flags & FGP_ACCESSED)
1934 __SetPageReferenced(page);
1936 err = add_to_page_cache_lru(page, mapping, index, gfp_mask);
1937 if (unlikely(err)) {
1945 * add_to_page_cache_lru locks the page, and for mmap we expect
1948 if (page && (fgp_flags & FGP_FOR_MMAP))
1954 EXPORT_SYMBOL(pagecache_get_page);
1956 static inline struct page *find_get_entry(struct xa_state *xas, pgoff_t max,
1962 if (mark == XA_PRESENT)
1963 page = xas_find(xas, max);
1965 page = xas_find_marked(xas, max, mark);
1967 if (xas_retry(xas, page))
1970 * A shadow entry of a recently evicted page, a swap
1971 * entry from shmem/tmpfs or a DAX entry. Return it
1972 * without attempting to raise page count.
1974 if (!page || xa_is_value(page))
1977 if (!page_cache_get_speculative(page))
1980 /* Has the page moved or been split? */
1981 if (unlikely(page != xas_reload(xas))) {
1993 * find_get_entries - gang pagecache lookup
1994 * @mapping: The address_space to search
1995 * @start: The starting page cache index
1996 * @end: The final page index (inclusive).
1997 * @pvec: Where the resulting entries are placed.
1998 * @indices: The cache indices corresponding to the entries in @entries
2000 * find_get_entries() will search for and return a batch of entries in
2001 * the mapping. The entries are placed in @pvec. find_get_entries()
2002 * takes a reference on any actual pages it returns.
2004 * The search returns a group of mapping-contiguous page cache entries
2005 * with ascending indexes. There may be holes in the indices due to
2006 * not-present pages.
2008 * Any shadow entries of evicted pages, or swap entries from
2009 * shmem/tmpfs, are included in the returned array.
2011 * If it finds a Transparent Huge Page, head or tail, find_get_entries()
2012 * stops at that page: the caller is likely to have a better way to handle
2013 * the compound page as a whole, and then skip its extent, than repeatedly
2014 * calling find_get_entries() to return all its tails.
2016 * Return: the number of pages and shadow entries which were found.
2018 unsigned find_get_entries(struct address_space *mapping, pgoff_t start,
2019 pgoff_t end, struct pagevec *pvec, pgoff_t *indices)
2021 XA_STATE(xas, &mapping->i_pages, start);
2023 unsigned int ret = 0;
2024 unsigned nr_entries = PAGEVEC_SIZE;
2027 while ((page = find_get_entry(&xas, end, XA_PRESENT))) {
2029 * Terminate early on finding a THP, to allow the caller to
2030 * handle it all at once; but continue if this is hugetlbfs.
2032 if (!xa_is_value(page) && PageTransHuge(page) &&
2034 page = find_subpage(page, xas.xa_index);
2035 nr_entries = ret + 1;
2038 indices[ret] = xas.xa_index;
2039 pvec->pages[ret] = page;
2040 if (++ret == nr_entries)
2050 * find_lock_entries - Find a batch of pagecache entries.
2051 * @mapping: The address_space to search.
2052 * @start: The starting page cache index.
2053 * @end: The final page index (inclusive).
2054 * @pvec: Where the resulting entries are placed.
2055 * @indices: The cache indices of the entries in @pvec.
2057 * find_lock_entries() will return a batch of entries from @mapping.
2058 * Swap, shadow and DAX entries are included. Pages are returned
2059 * locked and with an incremented refcount. Pages which are locked by
2060 * somebody else or under writeback are skipped. Only the head page of
2061 * a THP is returned. Pages which are partially outside the range are
2064 * The entries have ascending indexes. The indices may not be consecutive
2065 * due to not-present entries, THP pages, pages which could not be locked
2066 * or pages under writeback.
2068 * Return: The number of entries which were found.
2070 unsigned find_lock_entries(struct address_space *mapping, pgoff_t start,
2071 pgoff_t end, struct pagevec *pvec, pgoff_t *indices)
2073 XA_STATE(xas, &mapping->i_pages, start);
2077 while ((page = find_get_entry(&xas, end, XA_PRESENT))) {
2078 if (!xa_is_value(page)) {
2079 if (page->index < start)
2081 VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
2082 if (page->index + thp_nr_pages(page) - 1 > end)
2084 if (!trylock_page(page))
2086 if (page->mapping != mapping || PageWriteback(page))
2088 VM_BUG_ON_PAGE(!thp_contains(page, xas.xa_index),
2091 indices[pvec->nr] = xas.xa_index;
2092 if (!pagevec_add(pvec, page))
2100 if (!xa_is_value(page) && PageTransHuge(page)) {
2101 unsigned int nr_pages = thp_nr_pages(page);
2103 /* Final THP may cross MAX_LFS_FILESIZE on 32-bit */
2104 xas_set(&xas, page->index + nr_pages);
2105 if (xas.xa_index < nr_pages)
2111 return pagevec_count(pvec);
2115 * find_get_pages_range - gang pagecache lookup
2116 * @mapping: The address_space to search
2117 * @start: The starting page index
2118 * @end: The final page index (inclusive)
2119 * @nr_pages: The maximum number of pages
2120 * @pages: Where the resulting pages are placed
2122 * find_get_pages_range() will search for and return a group of up to @nr_pages
2123 * pages in the mapping starting at index @start and up to index @end
2124 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
2125 * a reference against the returned pages.
2127 * The search returns a group of mapping-contiguous pages with ascending
2128 * indexes. There may be holes in the indices due to not-present pages.
2129 * We also update @start to index the next page for the traversal.
2131 * Return: the number of pages which were found. If this number is
2132 * smaller than @nr_pages, the end of specified range has been
2135 unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
2136 pgoff_t end, unsigned int nr_pages,
2137 struct page **pages)
2139 XA_STATE(xas, &mapping->i_pages, *start);
2143 if (unlikely(!nr_pages))
2147 while ((page = find_get_entry(&xas, end, XA_PRESENT))) {
2148 /* Skip over shadow, swap and DAX entries */
2149 if (xa_is_value(page))
2152 pages[ret] = find_subpage(page, xas.xa_index);
2153 if (++ret == nr_pages) {
2154 *start = xas.xa_index + 1;
2160 * We come here when there is no page beyond @end. We take care to not
2161 * overflow the index @start as it confuses some of the callers. This
2162 * breaks the iteration when there is a page at index -1 but that is
2163 * already broken anyway.
2165 if (end == (pgoff_t)-1)
2166 *start = (pgoff_t)-1;
2176 * find_get_pages_contig - gang contiguous pagecache lookup
2177 * @mapping: The address_space to search
2178 * @index: The starting page index
2179 * @nr_pages: The maximum number of pages
2180 * @pages: Where the resulting pages are placed
2182 * find_get_pages_contig() works exactly like find_get_pages(), except
2183 * that the returned number of pages are guaranteed to be contiguous.
2185 * Return: the number of pages which were found.
2187 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
2188 unsigned int nr_pages, struct page **pages)
2190 XA_STATE(xas, &mapping->i_pages, index);
2192 unsigned int ret = 0;
2194 if (unlikely(!nr_pages))
2198 for (page = xas_load(&xas); page; page = xas_next(&xas)) {
2199 if (xas_retry(&xas, page))
2202 * If the entry has been swapped out, we can stop looking.
2203 * No current caller is looking for DAX entries.
2205 if (xa_is_value(page))
2208 if (!page_cache_get_speculative(page))
2211 /* Has the page moved or been split? */
2212 if (unlikely(page != xas_reload(&xas)))
2215 pages[ret] = find_subpage(page, xas.xa_index);
2216 if (++ret == nr_pages)
2227 EXPORT_SYMBOL(find_get_pages_contig);
2230 * find_get_pages_range_tag - Find and return head pages matching @tag.
2231 * @mapping: the address_space to search
2232 * @index: the starting page index
2233 * @end: The final page index (inclusive)
2234 * @tag: the tag index
2235 * @nr_pages: the maximum number of pages
2236 * @pages: where the resulting pages are placed
2238 * Like find_get_pages(), except we only return head pages which are tagged
2239 * with @tag. @index is updated to the index immediately after the last
2240 * page we return, ready for the next iteration.
2242 * Return: the number of pages which were found.
2244 unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
2245 pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
2246 struct page **pages)
2248 XA_STATE(xas, &mapping->i_pages, *index);
2252 if (unlikely(!nr_pages))
2256 while ((page = find_get_entry(&xas, end, tag))) {
2258 * Shadow entries should never be tagged, but this iteration
2259 * is lockless so there is a window for page reclaim to evict
2260 * a page we saw tagged. Skip over it.
2262 if (xa_is_value(page))
2266 if (++ret == nr_pages) {
2267 *index = page->index + thp_nr_pages(page);
2273 * We come here when we got to @end. We take care to not overflow the
2274 * index @index as it confuses some of the callers. This breaks the
2275 * iteration when there is a page at index -1 but that is already
2278 if (end == (pgoff_t)-1)
2279 *index = (pgoff_t)-1;
2287 EXPORT_SYMBOL(find_get_pages_range_tag);
2290 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
2291 * a _large_ part of the i/o request. Imagine the worst scenario:
2293 * ---R__________________________________________B__________
2294 * ^ reading here ^ bad block(assume 4k)
2296 * read(R) => miss => readahead(R...B) => media error => frustrating retries
2297 * => failing the whole request => read(R) => read(R+1) =>
2298 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
2299 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
2300 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
2302 * It is going insane. Fix it by quickly scaling down the readahead size.
2304 static void shrink_readahead_size_eio(struct file_ra_state *ra)
2310 * filemap_get_read_batch - Get a batch of pages for read
2312 * Get a batch of pages which represent a contiguous range of bytes
2313 * in the file. No tail pages will be returned. If @index is in the
2314 * middle of a THP, the entire THP will be returned. The last page in
2315 * the batch may have Readahead set or be not Uptodate so that the
2316 * caller can take the appropriate action.
2318 static void filemap_get_read_batch(struct address_space *mapping,
2319 pgoff_t index, pgoff_t max, struct pagevec *pvec)
2321 XA_STATE(xas, &mapping->i_pages, index);
2325 for (head = xas_load(&xas); head; head = xas_next(&xas)) {
2326 if (xas_retry(&xas, head))
2328 if (xas.xa_index > max || xa_is_value(head))
2330 if (!page_cache_get_speculative(head))
2333 /* Has the page moved or been split? */
2334 if (unlikely(head != xas_reload(&xas)))
2337 if (!pagevec_add(pvec, head))
2339 if (!PageUptodate(head))
2341 if (PageReadahead(head))
2343 xas.xa_index = head->index + thp_nr_pages(head) - 1;
2344 xas.xa_offset = (xas.xa_index >> xas.xa_shift) & XA_CHUNK_MASK;
2354 static int filemap_read_page(struct file *file, struct address_space *mapping,
2360 * A previous I/O error may have been due to temporary failures,
2361 * eg. multipath errors. PG_error will be set again if readpage
2364 ClearPageError(page);
2365 /* Start the actual read. The read will unlock the page. */
2366 error = mapping->a_ops->readpage(file, page);
2370 error = wait_on_page_locked_killable(page);
2373 if (PageUptodate(page))
2375 shrink_readahead_size_eio(&file->f_ra);
2379 static bool filemap_range_uptodate(struct address_space *mapping,
2380 loff_t pos, struct iov_iter *iter, struct page *page)
2384 if (PageUptodate(page))
2386 /* pipes can't handle partially uptodate pages */
2387 if (iov_iter_is_pipe(iter))
2389 if (!mapping->a_ops->is_partially_uptodate)
2391 if (mapping->host->i_blkbits >= (PAGE_SHIFT + thp_order(page)))
2394 count = iter->count;
2395 if (page_offset(page) > pos) {
2396 count -= page_offset(page) - pos;
2399 pos -= page_offset(page);
2402 return mapping->a_ops->is_partially_uptodate(page, pos, count);
2405 static int filemap_update_page(struct kiocb *iocb,
2406 struct address_space *mapping, struct iov_iter *iter,
2411 if (iocb->ki_flags & IOCB_NOWAIT) {
2412 if (!filemap_invalidate_trylock_shared(mapping))
2415 filemap_invalidate_lock_shared(mapping);
2418 if (!trylock_page(page)) {
2420 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO))
2421 goto unlock_mapping;
2422 if (!(iocb->ki_flags & IOCB_WAITQ)) {
2423 filemap_invalidate_unlock_shared(mapping);
2424 put_and_wait_on_page_locked(page, TASK_KILLABLE);
2425 return AOP_TRUNCATED_PAGE;
2427 error = __lock_page_async(page, iocb->ki_waitq);
2429 goto unlock_mapping;
2432 error = AOP_TRUNCATED_PAGE;
2437 if (filemap_range_uptodate(mapping, iocb->ki_pos, iter, page))
2441 if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT | IOCB_WAITQ))
2444 error = filemap_read_page(iocb->ki_filp, mapping, page);
2445 goto unlock_mapping;
2449 filemap_invalidate_unlock_shared(mapping);
2450 if (error == AOP_TRUNCATED_PAGE)
2455 static int filemap_create_page(struct file *file,
2456 struct address_space *mapping, pgoff_t index,
2457 struct pagevec *pvec)
2462 page = page_cache_alloc(mapping);
2467 * Protect against truncate / hole punch. Grabbing invalidate_lock here
2468 * assures we cannot instantiate and bring uptodate new pagecache pages
2469 * after evicting page cache during truncate and before actually
2470 * freeing blocks. Note that we could release invalidate_lock after
2471 * inserting the page into page cache as the locked page would then be
2472 * enough to synchronize with hole punching. But there are code paths
2473 * such as filemap_update_page() filling in partially uptodate pages or
2474 * ->readpages() that need to hold invalidate_lock while mapping blocks
2475 * for IO so let's hold the lock here as well to keep locking rules
2478 filemap_invalidate_lock_shared(mapping);
2479 error = add_to_page_cache_lru(page, mapping, index,
2480 mapping_gfp_constraint(mapping, GFP_KERNEL));
2481 if (error == -EEXIST)
2482 error = AOP_TRUNCATED_PAGE;
2486 error = filemap_read_page(file, mapping, page);
2490 filemap_invalidate_unlock_shared(mapping);
2491 pagevec_add(pvec, page);
2494 filemap_invalidate_unlock_shared(mapping);
2499 static int filemap_readahead(struct kiocb *iocb, struct file *file,
2500 struct address_space *mapping, struct page *page,
2503 if (iocb->ki_flags & IOCB_NOIO)
2505 page_cache_async_readahead(mapping, &file->f_ra, file, page,
2506 page->index, last_index - page->index);
2510 static int filemap_get_pages(struct kiocb *iocb, struct iov_iter *iter,
2511 struct pagevec *pvec)
2513 struct file *filp = iocb->ki_filp;
2514 struct address_space *mapping = filp->f_mapping;
2515 struct file_ra_state *ra = &filp->f_ra;
2516 pgoff_t index = iocb->ki_pos >> PAGE_SHIFT;
2521 last_index = DIV_ROUND_UP(iocb->ki_pos + iter->count, PAGE_SIZE);
2523 if (fatal_signal_pending(current))
2526 filemap_get_read_batch(mapping, index, last_index, pvec);
2527 if (!pagevec_count(pvec)) {
2528 if (iocb->ki_flags & IOCB_NOIO)
2530 page_cache_sync_readahead(mapping, ra, filp, index,
2531 last_index - index);
2532 filemap_get_read_batch(mapping, index, last_index, pvec);
2534 if (!pagevec_count(pvec)) {
2535 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_WAITQ))
2537 err = filemap_create_page(filp, mapping,
2538 iocb->ki_pos >> PAGE_SHIFT, pvec);
2539 if (err == AOP_TRUNCATED_PAGE)
2544 page = pvec->pages[pagevec_count(pvec) - 1];
2545 if (PageReadahead(page)) {
2546 err = filemap_readahead(iocb, filp, mapping, page, last_index);
2550 if (!PageUptodate(page)) {
2551 if ((iocb->ki_flags & IOCB_WAITQ) && pagevec_count(pvec) > 1)
2552 iocb->ki_flags |= IOCB_NOWAIT;
2553 err = filemap_update_page(iocb, mapping, iter, page);
2562 if (likely(--pvec->nr))
2564 if (err == AOP_TRUNCATED_PAGE)
2570 * filemap_read - Read data from the page cache.
2571 * @iocb: The iocb to read.
2572 * @iter: Destination for the data.
2573 * @already_read: Number of bytes already read by the caller.
2575 * Copies data from the page cache. If the data is not currently present,
2576 * uses the readahead and readpage address_space operations to fetch it.
2578 * Return: Total number of bytes copied, including those already read by
2579 * the caller. If an error happens before any bytes are copied, returns
2580 * a negative error number.
2582 ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,
2583 ssize_t already_read)
2585 struct file *filp = iocb->ki_filp;
2586 struct file_ra_state *ra = &filp->f_ra;
2587 struct address_space *mapping = filp->f_mapping;
2588 struct inode *inode = mapping->host;
2589 struct pagevec pvec;
2591 bool writably_mapped;
2592 loff_t isize, end_offset;
2594 if (unlikely(iocb->ki_pos >= inode->i_sb->s_maxbytes))
2596 if (unlikely(!iov_iter_count(iter)))
2599 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2600 pagevec_init(&pvec);
2606 * If we've already successfully copied some data, then we
2607 * can no longer safely return -EIOCBQUEUED. Hence mark
2608 * an async read NOWAIT at that point.
2610 if ((iocb->ki_flags & IOCB_WAITQ) && already_read)
2611 iocb->ki_flags |= IOCB_NOWAIT;
2613 error = filemap_get_pages(iocb, iter, &pvec);
2618 * i_size must be checked after we know the pages are Uptodate.
2620 * Checking i_size after the check allows us to calculate
2621 * the correct value for "nr", which means the zero-filled
2622 * part of the page is not copied back to userspace (unless
2623 * another truncate extends the file - this is desired though).
2625 isize = i_size_read(inode);
2626 if (unlikely(iocb->ki_pos >= isize))
2628 end_offset = min_t(loff_t, isize, iocb->ki_pos + iter->count);
2631 * Once we start copying data, we don't want to be touching any
2632 * cachelines that might be contended:
2634 writably_mapped = mapping_writably_mapped(mapping);
2637 * When a sequential read accesses a page several times, only
2638 * mark it as accessed the first time.
2640 if (iocb->ki_pos >> PAGE_SHIFT !=
2641 ra->prev_pos >> PAGE_SHIFT)
2642 mark_page_accessed(pvec.pages[0]);
2644 for (i = 0; i < pagevec_count(&pvec); i++) {
2645 struct page *page = pvec.pages[i];
2646 size_t page_size = thp_size(page);
2647 size_t offset = iocb->ki_pos & (page_size - 1);
2648 size_t bytes = min_t(loff_t, end_offset - iocb->ki_pos,
2649 page_size - offset);
2652 if (end_offset < page_offset(page))
2655 mark_page_accessed(page);
2657 * If users can be writing to this page using arbitrary
2658 * virtual addresses, take care about potential aliasing
2659 * before reading the page on the kernel side.
2661 if (writably_mapped) {
2664 for (j = 0; j < thp_nr_pages(page); j++)
2665 flush_dcache_page(page + j);
2668 copied = copy_page_to_iter(page, offset, bytes, iter);
2670 already_read += copied;
2671 iocb->ki_pos += copied;
2672 ra->prev_pos = iocb->ki_pos;
2674 if (copied < bytes) {
2680 for (i = 0; i < pagevec_count(&pvec); i++)
2681 put_page(pvec.pages[i]);
2682 pagevec_reinit(&pvec);
2683 } while (iov_iter_count(iter) && iocb->ki_pos < isize && !error);
2685 file_accessed(filp);
2687 return already_read ? already_read : error;
2689 EXPORT_SYMBOL_GPL(filemap_read);
2692 * generic_file_read_iter - generic filesystem read routine
2693 * @iocb: kernel I/O control block
2694 * @iter: destination for the data read
2696 * This is the "read_iter()" routine for all filesystems
2697 * that can use the page cache directly.
2699 * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
2700 * be returned when no data can be read without waiting for I/O requests
2701 * to complete; it doesn't prevent readahead.
2703 * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
2704 * requests shall be made for the read or for readahead. When no data
2705 * can be read, -EAGAIN shall be returned. When readahead would be
2706 * triggered, a partial, possibly empty read shall be returned.
2709 * * number of bytes copied, even for partial reads
2710 * * negative error code (or 0 if IOCB_NOIO) if nothing was read
2713 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2715 size_t count = iov_iter_count(iter);
2719 return 0; /* skip atime */
2721 if (iocb->ki_flags & IOCB_DIRECT) {
2722 struct file *file = iocb->ki_filp;
2723 struct address_space *mapping = file->f_mapping;
2724 struct inode *inode = mapping->host;
2727 size = i_size_read(inode);
2728 if (iocb->ki_flags & IOCB_NOWAIT) {
2729 if (filemap_range_needs_writeback(mapping, iocb->ki_pos,
2730 iocb->ki_pos + count - 1))
2733 retval = filemap_write_and_wait_range(mapping,
2735 iocb->ki_pos + count - 1);
2740 file_accessed(file);
2742 retval = mapping->a_ops->direct_IO(iocb, iter);
2744 iocb->ki_pos += retval;
2747 if (retval != -EIOCBQUEUED)
2748 iov_iter_revert(iter, count - iov_iter_count(iter));
2751 * Btrfs can have a short DIO read if we encounter
2752 * compressed extents, so if there was an error, or if
2753 * we've already read everything we wanted to, or if
2754 * there was a short read because we hit EOF, go ahead
2755 * and return. Otherwise fallthrough to buffered io for
2756 * the rest of the read. Buffered reads will not work for
2757 * DAX files, so don't bother trying.
2759 if (retval < 0 || !count || iocb->ki_pos >= size ||
2764 return filemap_read(iocb, iter, retval);
2766 EXPORT_SYMBOL(generic_file_read_iter);
2768 static inline loff_t page_seek_hole_data(struct xa_state *xas,
2769 struct address_space *mapping, struct page *page,
2770 loff_t start, loff_t end, bool seek_data)
2772 const struct address_space_operations *ops = mapping->a_ops;
2773 size_t offset, bsz = i_blocksize(mapping->host);
2775 if (xa_is_value(page) || PageUptodate(page))
2776 return seek_data ? start : end;
2777 if (!ops->is_partially_uptodate)
2778 return seek_data ? end : start;
2783 if (unlikely(page->mapping != mapping))
2786 offset = offset_in_thp(page, start) & ~(bsz - 1);
2789 if (ops->is_partially_uptodate(page, offset, bsz) == seek_data)
2791 start = (start + bsz) & ~(bsz - 1);
2793 } while (offset < thp_size(page));
2801 unsigned int seek_page_size(struct xa_state *xas, struct page *page)
2803 if (xa_is_value(page))
2804 return PAGE_SIZE << xa_get_order(xas->xa, xas->xa_index);
2805 return thp_size(page);
2809 * mapping_seek_hole_data - Seek for SEEK_DATA / SEEK_HOLE in the page cache.
2810 * @mapping: Address space to search.
2811 * @start: First byte to consider.
2812 * @end: Limit of search (exclusive).
2813 * @whence: Either SEEK_HOLE or SEEK_DATA.
2815 * If the page cache knows which blocks contain holes and which blocks
2816 * contain data, your filesystem can use this function to implement
2817 * SEEK_HOLE and SEEK_DATA. This is useful for filesystems which are
2818 * entirely memory-based such as tmpfs, and filesystems which support
2819 * unwritten extents.
2821 * Return: The requested offset on success, or -ENXIO if @whence specifies
2822 * SEEK_DATA and there is no data after @start. There is an implicit hole
2823 * after @end - 1, so SEEK_HOLE returns @end if all the bytes between @start
2824 * and @end contain data.
2826 loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start,
2827 loff_t end, int whence)
2829 XA_STATE(xas, &mapping->i_pages, start >> PAGE_SHIFT);
2830 pgoff_t max = (end - 1) >> PAGE_SHIFT;
2831 bool seek_data = (whence == SEEK_DATA);
2838 while ((page = find_get_entry(&xas, max, XA_PRESENT))) {
2839 loff_t pos = (u64)xas.xa_index << PAGE_SHIFT;
2840 unsigned int seek_size;
2848 seek_size = seek_page_size(&xas, page);
2849 pos = round_up(pos + 1, seek_size);
2850 start = page_seek_hole_data(&xas, mapping, page, start, pos,
2856 if (seek_size > PAGE_SIZE)
2857 xas_set(&xas, pos >> PAGE_SHIFT);
2858 if (!xa_is_value(page))
2865 if (page && !xa_is_value(page))
2873 #define MMAP_LOTSAMISS (100)
2875 * lock_page_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock
2876 * @vmf - the vm_fault for this fault.
2877 * @page - the page to lock.
2878 * @fpin - the pointer to the file we may pin (or is already pinned).
2880 * This works similar to lock_page_or_retry in that it can drop the mmap_lock.
2881 * It differs in that it actually returns the page locked if it returns 1 and 0
2882 * if it couldn't lock the page. If we did have to drop the mmap_lock then fpin
2883 * will point to the pinned file and needs to be fput()'ed at a later point.
2885 static int lock_page_maybe_drop_mmap(struct vm_fault *vmf, struct page *page,
2888 if (trylock_page(page))
2892 * NOTE! This will make us return with VM_FAULT_RETRY, but with
2893 * the mmap_lock still held. That's how FAULT_FLAG_RETRY_NOWAIT
2894 * is supposed to work. We have way too many special cases..
2896 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2899 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2900 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2901 if (__lock_page_killable(page)) {
2903 * We didn't have the right flags to drop the mmap_lock,
2904 * but all fault_handlers only check for fatal signals
2905 * if we return VM_FAULT_RETRY, so we need to drop the
2906 * mmap_lock here and return 0 if we don't have a fpin.
2909 mmap_read_unlock(vmf->vma->vm_mm);
2919 * Synchronous readahead happens when we don't even find a page in the page
2920 * cache at all. We don't want to perform IO under the mmap sem, so if we have
2921 * to drop the mmap sem we return the file that was pinned in order for us to do
2922 * that. If we didn't pin a file then we return NULL. The file that is
2923 * returned needs to be fput()'ed when we're done with it.
2925 static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
2927 struct file *file = vmf->vma->vm_file;
2928 struct file_ra_state *ra = &file->f_ra;
2929 struct address_space *mapping = file->f_mapping;
2930 DEFINE_READAHEAD(ractl, file, ra, mapping, vmf->pgoff);
2931 struct file *fpin = NULL;
2932 unsigned int mmap_miss;
2934 /* If we don't want any read-ahead, don't bother */
2935 if (vmf->vma->vm_flags & VM_RAND_READ)
2940 if (vmf->vma->vm_flags & VM_SEQ_READ) {
2941 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2942 page_cache_sync_ra(&ractl, ra->ra_pages);
2946 /* Avoid banging the cache line if not needed */
2947 mmap_miss = READ_ONCE(ra->mmap_miss);
2948 if (mmap_miss < MMAP_LOTSAMISS * 10)
2949 WRITE_ONCE(ra->mmap_miss, ++mmap_miss);
2952 * Do we miss much more than hit in this file? If so,
2953 * stop bothering with read-ahead. It will only hurt.
2955 if (mmap_miss > MMAP_LOTSAMISS)
2961 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2962 ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2);
2963 ra->size = ra->ra_pages;
2964 ra->async_size = ra->ra_pages / 4;
2965 ractl._index = ra->start;
2966 do_page_cache_ra(&ractl, ra->size, ra->async_size);
2971 * Asynchronous readahead happens when we find the page and PG_readahead,
2972 * so we want to possibly extend the readahead further. We return the file that
2973 * was pinned if we have to drop the mmap_lock in order to do IO.
2975 static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2978 struct file *file = vmf->vma->vm_file;
2979 struct file_ra_state *ra = &file->f_ra;
2980 struct address_space *mapping = file->f_mapping;
2981 struct file *fpin = NULL;
2982 unsigned int mmap_miss;
2983 pgoff_t offset = vmf->pgoff;
2985 /* If we don't want any read-ahead, don't bother */
2986 if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
2988 mmap_miss = READ_ONCE(ra->mmap_miss);
2990 WRITE_ONCE(ra->mmap_miss, --mmap_miss);
2991 if (PageReadahead(page)) {
2992 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2993 page_cache_async_readahead(mapping, ra, file,
2994 page, offset, ra->ra_pages);
3000 * filemap_fault - read in file data for page fault handling
3001 * @vmf: struct vm_fault containing details of the fault
3003 * filemap_fault() is invoked via the vma operations vector for a
3004 * mapped memory region to read in file data during a page fault.
3006 * The goto's are kind of ugly, but this streamlines the normal case of having
3007 * it in the page cache, and handles the special cases reasonably without
3008 * having a lot of duplicated code.
3010 * vma->vm_mm->mmap_lock must be held on entry.
3012 * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
3013 * may be dropped before doing I/O or by lock_page_maybe_drop_mmap().
3015 * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
3016 * has not been released.
3018 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
3020 * Return: bitwise-OR of %VM_FAULT_ codes.
3022 vm_fault_t filemap_fault(struct vm_fault *vmf)
3025 struct file *file = vmf->vma->vm_file;
3026 struct file *fpin = NULL;
3027 struct address_space *mapping = file->f_mapping;
3028 struct inode *inode = mapping->host;
3029 pgoff_t offset = vmf->pgoff;
3033 bool mapping_locked = false;
3035 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3036 if (unlikely(offset >= max_off))
3037 return VM_FAULT_SIGBUS;
3040 * Do we have something in the page cache already?
3042 page = find_get_page(mapping, offset);
3045 * We found the page, so try async readahead before waiting for
3048 if (!(vmf->flags & FAULT_FLAG_TRIED))
3049 fpin = do_async_mmap_readahead(vmf, page);
3050 if (unlikely(!PageUptodate(page))) {
3051 filemap_invalidate_lock_shared(mapping);
3052 mapping_locked = true;
3055 /* No page in the page cache at all */
3056 count_vm_event(PGMAJFAULT);
3057 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
3058 ret = VM_FAULT_MAJOR;
3059 fpin = do_sync_mmap_readahead(vmf);
3062 * See comment in filemap_create_page() why we need
3065 if (!mapping_locked) {
3066 filemap_invalidate_lock_shared(mapping);
3067 mapping_locked = true;
3069 page = pagecache_get_page(mapping, offset,
3070 FGP_CREAT|FGP_FOR_MMAP,
3075 filemap_invalidate_unlock_shared(mapping);
3076 return VM_FAULT_OOM;
3080 if (!lock_page_maybe_drop_mmap(vmf, page, &fpin))
3083 /* Did it get truncated? */
3084 if (unlikely(compound_head(page)->mapping != mapping)) {
3089 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
3092 * We have a locked page in the page cache, now we need to check
3093 * that it's up-to-date. If not, it is going to be due to an error.
3095 if (unlikely(!PageUptodate(page))) {
3097 * The page was in cache and uptodate and now it is not.
3098 * Strange but possible since we didn't hold the page lock all
3099 * the time. Let's drop everything get the invalidate lock and
3102 if (!mapping_locked) {
3107 goto page_not_uptodate;
3111 * We've made it this far and we had to drop our mmap_lock, now is the
3112 * time to return to the upper layer and have it re-find the vma and
3120 filemap_invalidate_unlock_shared(mapping);
3123 * Found the page and have a reference on it.
3124 * We must recheck i_size under page lock.
3126 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3127 if (unlikely(offset >= max_off)) {
3130 return VM_FAULT_SIGBUS;
3134 return ret | VM_FAULT_LOCKED;
3138 * Umm, take care of errors if the page isn't up-to-date.
3139 * Try to re-read it _once_. We do this synchronously,
3140 * because there really aren't any performance issues here
3141 * and we need to check for errors.
3143 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3144 error = filemap_read_page(file, mapping, page);
3149 if (!error || error == AOP_TRUNCATED_PAGE)
3151 filemap_invalidate_unlock_shared(mapping);
3153 return VM_FAULT_SIGBUS;
3157 * We dropped the mmap_lock, we need to return to the fault handler to
3158 * re-find the vma and come back and find our hopefully still populated
3164 filemap_invalidate_unlock_shared(mapping);
3167 return ret | VM_FAULT_RETRY;
3169 EXPORT_SYMBOL(filemap_fault);
3171 static bool filemap_map_pmd(struct vm_fault *vmf, struct page *page)
3173 struct mm_struct *mm = vmf->vma->vm_mm;
3175 /* Huge page is mapped? No need to proceed. */
3176 if (pmd_trans_huge(*vmf->pmd)) {
3182 if (pmd_none(*vmf->pmd) && PageTransHuge(page)) {
3183 vm_fault_t ret = do_set_pmd(vmf, page);
3185 /* The page is mapped successfully, reference consumed. */
3191 if (pmd_none(*vmf->pmd)) {
3192 vmf->ptl = pmd_lock(mm, vmf->pmd);
3193 if (likely(pmd_none(*vmf->pmd))) {
3195 pmd_populate(mm, vmf->pmd, vmf->prealloc_pte);
3196 vmf->prealloc_pte = NULL;
3198 spin_unlock(vmf->ptl);
3201 /* See comment in handle_pte_fault() */
3202 if (pmd_devmap_trans_unstable(vmf->pmd)) {
3211 static struct page *next_uptodate_page(struct page *page,
3212 struct address_space *mapping,
3213 struct xa_state *xas, pgoff_t end_pgoff)
3215 unsigned long max_idx;
3220 if (xas_retry(xas, page))
3222 if (xa_is_value(page))
3224 if (PageLocked(page))
3226 if (!page_cache_get_speculative(page))
3228 /* Has the page moved or been split? */
3229 if (unlikely(page != xas_reload(xas)))
3231 if (!PageUptodate(page) || PageReadahead(page))
3233 if (PageHWPoison(page))
3235 if (!trylock_page(page))
3237 if (page->mapping != mapping)
3239 if (!PageUptodate(page))
3241 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
3242 if (xas->xa_index >= max_idx)
3249 } while ((page = xas_next_entry(xas, end_pgoff)) != NULL);
3254 static inline struct page *first_map_page(struct address_space *mapping,
3255 struct xa_state *xas,
3258 return next_uptodate_page(xas_find(xas, end_pgoff),
3259 mapping, xas, end_pgoff);
3262 static inline struct page *next_map_page(struct address_space *mapping,
3263 struct xa_state *xas,
3266 return next_uptodate_page(xas_next_entry(xas, end_pgoff),
3267 mapping, xas, end_pgoff);
3270 vm_fault_t filemap_map_pages(struct vm_fault *vmf,
3271 pgoff_t start_pgoff, pgoff_t end_pgoff)
3273 struct vm_area_struct *vma = vmf->vma;
3274 struct file *file = vma->vm_file;
3275 struct address_space *mapping = file->f_mapping;
3276 pgoff_t last_pgoff = start_pgoff;
3278 XA_STATE(xas, &mapping->i_pages, start_pgoff);
3279 struct page *head, *page;
3280 unsigned int mmap_miss = READ_ONCE(file->f_ra.mmap_miss);
3284 head = first_map_page(mapping, &xas, end_pgoff);
3288 if (filemap_map_pmd(vmf, head)) {
3289 ret = VM_FAULT_NOPAGE;
3293 addr = vma->vm_start + ((start_pgoff - vma->vm_pgoff) << PAGE_SHIFT);
3294 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl);
3296 page = find_subpage(head, xas.xa_index);
3297 if (PageHWPoison(page))
3303 addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
3304 vmf->pte += xas.xa_index - last_pgoff;
3305 last_pgoff = xas.xa_index;
3307 if (!pte_none(*vmf->pte))
3310 /* We're about to handle the fault */
3311 if (vmf->address == addr)
3312 ret = VM_FAULT_NOPAGE;
3314 do_set_pte(vmf, page, addr);
3315 /* no need to invalidate: a not-present page won't be cached */
3316 update_mmu_cache(vma, addr, vmf->pte);
3322 } while ((head = next_map_page(mapping, &xas, end_pgoff)) != NULL);
3323 pte_unmap_unlock(vmf->pte, vmf->ptl);
3326 WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss);
3329 EXPORT_SYMBOL(filemap_map_pages);
3331 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
3333 struct address_space *mapping = vmf->vma->vm_file->f_mapping;
3334 struct page *page = vmf->page;
3335 vm_fault_t ret = VM_FAULT_LOCKED;
3337 sb_start_pagefault(mapping->host->i_sb);
3338 file_update_time(vmf->vma->vm_file);
3340 if (page->mapping != mapping) {
3342 ret = VM_FAULT_NOPAGE;
3346 * We mark the page dirty already here so that when freeze is in
3347 * progress, we are guaranteed that writeback during freezing will
3348 * see the dirty page and writeprotect it again.
3350 set_page_dirty(page);
3351 wait_for_stable_page(page);
3353 sb_end_pagefault(mapping->host->i_sb);
3357 const struct vm_operations_struct generic_file_vm_ops = {
3358 .fault = filemap_fault,
3359 .map_pages = filemap_map_pages,
3360 .page_mkwrite = filemap_page_mkwrite,
3363 /* This is used for a general mmap of a disk file */
3365 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3367 struct address_space *mapping = file->f_mapping;
3369 if (!mapping->a_ops->readpage)
3371 file_accessed(file);
3372 vma->vm_ops = &generic_file_vm_ops;
3377 * This is for filesystems which do not implement ->writepage.
3379 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3381 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
3383 return generic_file_mmap(file, vma);
3386 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
3388 return VM_FAULT_SIGBUS;
3390 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3394 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3398 #endif /* CONFIG_MMU */
3400 EXPORT_SYMBOL(filemap_page_mkwrite);
3401 EXPORT_SYMBOL(generic_file_mmap);
3402 EXPORT_SYMBOL(generic_file_readonly_mmap);
3404 static struct page *wait_on_page_read(struct page *page)
3406 if (!IS_ERR(page)) {
3407 wait_on_page_locked(page);
3408 if (!PageUptodate(page)) {
3410 page = ERR_PTR(-EIO);
3416 static struct page *do_read_cache_page(struct address_space *mapping,
3418 int (*filler)(void *, struct page *),
3425 page = find_get_page(mapping, index);
3427 page = __page_cache_alloc(gfp);
3429 return ERR_PTR(-ENOMEM);
3430 err = add_to_page_cache_lru(page, mapping, index, gfp);
3431 if (unlikely(err)) {
3435 /* Presumably ENOMEM for xarray node */
3436 return ERR_PTR(err);
3441 err = filler(data, page);
3443 err = mapping->a_ops->readpage(data, page);
3447 return ERR_PTR(err);
3450 page = wait_on_page_read(page);
3455 if (PageUptodate(page))
3459 * Page is not up to date and may be locked due to one of the following
3460 * case a: Page is being filled and the page lock is held
3461 * case b: Read/write error clearing the page uptodate status
3462 * case c: Truncation in progress (page locked)
3463 * case d: Reclaim in progress
3465 * Case a, the page will be up to date when the page is unlocked.
3466 * There is no need to serialise on the page lock here as the page
3467 * is pinned so the lock gives no additional protection. Even if the
3468 * page is truncated, the data is still valid if PageUptodate as
3469 * it's a race vs truncate race.
3470 * Case b, the page will not be up to date
3471 * Case c, the page may be truncated but in itself, the data may still
3472 * be valid after IO completes as it's a read vs truncate race. The
3473 * operation must restart if the page is not uptodate on unlock but
3474 * otherwise serialising on page lock to stabilise the mapping gives
3475 * no additional guarantees to the caller as the page lock is
3476 * released before return.
3477 * Case d, similar to truncation. If reclaim holds the page lock, it
3478 * will be a race with remove_mapping that determines if the mapping
3479 * is valid on unlock but otherwise the data is valid and there is
3480 * no need to serialise with page lock.
3482 * As the page lock gives no additional guarantee, we optimistically
3483 * wait on the page to be unlocked and check if it's up to date and
3484 * use the page if it is. Otherwise, the page lock is required to
3485 * distinguish between the different cases. The motivation is that we
3486 * avoid spurious serialisations and wakeups when multiple processes
3487 * wait on the same page for IO to complete.
3489 wait_on_page_locked(page);
3490 if (PageUptodate(page))
3493 /* Distinguish between all the cases under the safety of the lock */
3496 /* Case c or d, restart the operation */
3497 if (!page->mapping) {
3503 /* Someone else locked and filled the page in a very small window */
3504 if (PageUptodate(page)) {
3510 * A previous I/O error may have been due to temporary
3512 * Clear page error before actual read, PG_error will be
3513 * set again if read page fails.
3515 ClearPageError(page);
3519 mark_page_accessed(page);
3524 * read_cache_page - read into page cache, fill it if needed
3525 * @mapping: the page's address_space
3526 * @index: the page index
3527 * @filler: function to perform the read
3528 * @data: first arg to filler(data, page) function, often left as NULL
3530 * Read into the page cache. If a page already exists, and PageUptodate() is
3531 * not set, try to fill the page and wait for it to become unlocked.
3533 * If the page does not get brought uptodate, return -EIO.
3535 * The function expects mapping->invalidate_lock to be already held.
3537 * Return: up to date page on success, ERR_PTR() on failure.
3539 struct page *read_cache_page(struct address_space *mapping,
3541 int (*filler)(void *, struct page *),
3544 return do_read_cache_page(mapping, index, filler, data,
3545 mapping_gfp_mask(mapping));
3547 EXPORT_SYMBOL(read_cache_page);
3550 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
3551 * @mapping: the page's address_space
3552 * @index: the page index
3553 * @gfp: the page allocator flags to use if allocating
3555 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
3556 * any new page allocations done using the specified allocation flags.
3558 * If the page does not get brought uptodate, return -EIO.
3560 * The function expects mapping->invalidate_lock to be already held.
3562 * Return: up to date page on success, ERR_PTR() on failure.
3564 struct page *read_cache_page_gfp(struct address_space *mapping,
3568 return do_read_cache_page(mapping, index, NULL, NULL, gfp);
3570 EXPORT_SYMBOL(read_cache_page_gfp);
3572 int pagecache_write_begin(struct file *file, struct address_space *mapping,
3573 loff_t pos, unsigned len, unsigned flags,
3574 struct page **pagep, void **fsdata)
3576 const struct address_space_operations *aops = mapping->a_ops;
3578 return aops->write_begin(file, mapping, pos, len, flags,
3581 EXPORT_SYMBOL(pagecache_write_begin);
3583 int pagecache_write_end(struct file *file, struct address_space *mapping,
3584 loff_t pos, unsigned len, unsigned copied,
3585 struct page *page, void *fsdata)
3587 const struct address_space_operations *aops = mapping->a_ops;
3589 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
3591 EXPORT_SYMBOL(pagecache_write_end);
3594 * Warn about a page cache invalidation failure during a direct I/O write.
3596 void dio_warn_stale_pagecache(struct file *filp)
3598 static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
3602 errseq_set(&filp->f_mapping->wb_err, -EIO);
3603 if (__ratelimit(&_rs)) {
3604 path = file_path(filp, pathname, sizeof(pathname));
3607 pr_crit("Page cache invalidation failure on direct I/O. Possible data corruption due to collision with buffered I/O!\n");
3608 pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
3614 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
3616 struct file *file = iocb->ki_filp;
3617 struct address_space *mapping = file->f_mapping;
3618 struct inode *inode = mapping->host;
3619 loff_t pos = iocb->ki_pos;
3624 write_len = iov_iter_count(from);
3625 end = (pos + write_len - 1) >> PAGE_SHIFT;
3627 if (iocb->ki_flags & IOCB_NOWAIT) {
3628 /* If there are pages to writeback, return */
3629 if (filemap_range_has_page(file->f_mapping, pos,
3630 pos + write_len - 1))
3633 written = filemap_write_and_wait_range(mapping, pos,
3634 pos + write_len - 1);
3640 * After a write we want buffered reads to be sure to go to disk to get
3641 * the new data. We invalidate clean cached page from the region we're
3642 * about to write. We do this *before* the write so that we can return
3643 * without clobbering -EIOCBQUEUED from ->direct_IO().
3645 written = invalidate_inode_pages2_range(mapping,
3646 pos >> PAGE_SHIFT, end);
3648 * If a page can not be invalidated, return 0 to fall back
3649 * to buffered write.
3652 if (written == -EBUSY)
3657 written = mapping->a_ops->direct_IO(iocb, from);
3660 * Finally, try again to invalidate clean pages which might have been
3661 * cached by non-direct readahead, or faulted in by get_user_pages()
3662 * if the source of the write was an mmap'ed region of the file
3663 * we're writing. Either one is a pretty crazy thing to do,
3664 * so we don't support it 100%. If this invalidation
3665 * fails, tough, the write still worked...
3667 * Most of the time we do not need this since dio_complete() will do
3668 * the invalidation for us. However there are some file systems that
3669 * do not end up with dio_complete() being called, so let's not break
3670 * them by removing it completely.
3672 * Noticeable example is a blkdev_direct_IO().
3674 * Skip invalidation for async writes or if mapping has no pages.
3676 if (written > 0 && mapping->nrpages &&
3677 invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT, end))
3678 dio_warn_stale_pagecache(file);
3682 write_len -= written;
3683 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3684 i_size_write(inode, pos);
3685 mark_inode_dirty(inode);
3689 if (written != -EIOCBQUEUED)
3690 iov_iter_revert(from, write_len - iov_iter_count(from));
3694 EXPORT_SYMBOL(generic_file_direct_write);
3697 * Find or create a page at the given pagecache position. Return the locked
3698 * page. This function is specifically for buffered writes.
3700 struct page *grab_cache_page_write_begin(struct address_space *mapping,
3701 pgoff_t index, unsigned flags)
3704 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
3706 if (flags & AOP_FLAG_NOFS)
3707 fgp_flags |= FGP_NOFS;
3709 page = pagecache_get_page(mapping, index, fgp_flags,
3710 mapping_gfp_mask(mapping));
3712 wait_for_stable_page(page);
3716 EXPORT_SYMBOL(grab_cache_page_write_begin);
3718 ssize_t generic_perform_write(struct file *file,
3719 struct iov_iter *i, loff_t pos)
3721 struct address_space *mapping = file->f_mapping;
3722 const struct address_space_operations *a_ops = mapping->a_ops;
3724 ssize_t written = 0;
3725 unsigned int flags = 0;
3729 unsigned long offset; /* Offset into pagecache page */
3730 unsigned long bytes; /* Bytes to write to page */
3731 size_t copied; /* Bytes copied from user */
3734 offset = (pos & (PAGE_SIZE - 1));
3735 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3740 * Bring in the user page that we will copy from _first_.
3741 * Otherwise there's a nasty deadlock on copying from the
3742 * same page as we're writing to, without it being marked
3745 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3750 if (fatal_signal_pending(current)) {
3755 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
3757 if (unlikely(status < 0))
3760 if (mapping_writably_mapped(mapping))
3761 flush_dcache_page(page);
3763 copied = copy_page_from_iter_atomic(page, offset, bytes, i);
3764 flush_dcache_page(page);
3766 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3768 if (unlikely(status != copied)) {
3769 iov_iter_revert(i, copied - max(status, 0L));
3770 if (unlikely(status < 0))
3775 if (unlikely(status == 0)) {
3777 * A short copy made ->write_end() reject the
3778 * thing entirely. Might be memory poisoning
3779 * halfway through, might be a race with munmap,
3780 * might be severe memory pressure.
3789 balance_dirty_pages_ratelimited(mapping);
3790 } while (iov_iter_count(i));
3792 return written ? written : status;
3794 EXPORT_SYMBOL(generic_perform_write);
3797 * __generic_file_write_iter - write data to a file
3798 * @iocb: IO state structure (file, offset, etc.)
3799 * @from: iov_iter with data to write
3801 * This function does all the work needed for actually writing data to a
3802 * file. It does all basic checks, removes SUID from the file, updates
3803 * modification times and calls proper subroutines depending on whether we
3804 * do direct IO or a standard buffered write.
3806 * It expects i_rwsem to be grabbed unless we work on a block device or similar
3807 * object which does not need locking at all.
3809 * This function does *not* take care of syncing data in case of O_SYNC write.
3810 * A caller has to handle it. This is mainly due to the fact that we want to
3811 * avoid syncing under i_rwsem.
3814 * * number of bytes written, even for truncated writes
3815 * * negative error code if no data has been written at all
3817 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3819 struct file *file = iocb->ki_filp;
3820 struct address_space *mapping = file->f_mapping;
3821 struct inode *inode = mapping->host;
3822 ssize_t written = 0;
3826 /* We can write back this queue in page reclaim */
3827 current->backing_dev_info = inode_to_bdi(inode);
3828 err = file_remove_privs(file);
3832 err = file_update_time(file);
3836 if (iocb->ki_flags & IOCB_DIRECT) {
3837 loff_t pos, endbyte;
3839 written = generic_file_direct_write(iocb, from);
3841 * If the write stopped short of completing, fall back to
3842 * buffered writes. Some filesystems do this for writes to
3843 * holes, for example. For DAX files, a buffered write will
3844 * not succeed (even if it did, DAX does not handle dirty
3845 * page-cache pages correctly).
3847 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
3850 status = generic_perform_write(file, from, pos = iocb->ki_pos);
3852 * If generic_perform_write() returned a synchronous error
3853 * then we want to return the number of bytes which were
3854 * direct-written, or the error code if that was zero. Note
3855 * that this differs from normal direct-io semantics, which
3856 * will return -EFOO even if some bytes were written.
3858 if (unlikely(status < 0)) {
3863 * We need to ensure that the page cache pages are written to
3864 * disk and invalidated to preserve the expected O_DIRECT
3867 endbyte = pos + status - 1;
3868 err = filemap_write_and_wait_range(mapping, pos, endbyte);
3870 iocb->ki_pos = endbyte + 1;
3872 invalidate_mapping_pages(mapping,
3874 endbyte >> PAGE_SHIFT);
3877 * We don't know how much we wrote, so just return
3878 * the number of bytes which were direct-written
3882 written = generic_perform_write(file, from, iocb->ki_pos);
3883 if (likely(written > 0))
3884 iocb->ki_pos += written;
3887 current->backing_dev_info = NULL;
3888 return written ? written : err;
3890 EXPORT_SYMBOL(__generic_file_write_iter);
3893 * generic_file_write_iter - write data to a file
3894 * @iocb: IO state structure
3895 * @from: iov_iter with data to write
3897 * This is a wrapper around __generic_file_write_iter() to be used by most
3898 * filesystems. It takes care of syncing the file in case of O_SYNC file
3899 * and acquires i_rwsem as needed.
3901 * * negative error code if no data has been written at all of
3902 * vfs_fsync_range() failed for a synchronous write
3903 * * number of bytes written, even for truncated writes
3905 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3907 struct file *file = iocb->ki_filp;
3908 struct inode *inode = file->f_mapping->host;
3912 ret = generic_write_checks(iocb, from);
3914 ret = __generic_file_write_iter(iocb, from);
3915 inode_unlock(inode);
3918 ret = generic_write_sync(iocb, ret);
3921 EXPORT_SYMBOL(generic_file_write_iter);
3924 * try_to_release_page() - release old fs-specific metadata on a page
3926 * @page: the page which the kernel is trying to free
3927 * @gfp_mask: memory allocation flags (and I/O mode)
3929 * The address_space is to try to release any data against the page
3930 * (presumably at page->private).
3932 * This may also be called if PG_fscache is set on a page, indicating that the
3933 * page is known to the local caching routines.
3935 * The @gfp_mask argument specifies whether I/O may be performed to release
3936 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
3938 * Return: %1 if the release was successful, otherwise return zero.
3940 int try_to_release_page(struct page *page, gfp_t gfp_mask)
3942 struct address_space * const mapping = page->mapping;
3944 BUG_ON(!PageLocked(page));
3945 if (PageWriteback(page))
3948 if (mapping && mapping->a_ops->releasepage)
3949 return mapping->a_ops->releasepage(page, gfp_mask);
3950 return try_to_free_buffers(page);
3953 EXPORT_SYMBOL(try_to_release_page);