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>
46 #define CREATE_TRACE_POINTS
47 #include <trace/events/filemap.h>
50 * FIXME: remove all knowledge of the buffer layer from the core VM
52 #include <linux/buffer_head.h> /* for try_to_free_buffers */
57 * Shared mappings implemented 30.11.1994. It's not fully working yet,
60 * Shared mappings now work. 15.8.1995 Bruno.
62 * finished 'unifying' the page and buffer cache and SMP-threaded the
63 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
65 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
71 * ->i_mmap_rwsem (truncate_pagecache)
72 * ->private_lock (__free_pte->__set_page_dirty_buffers)
73 * ->swap_lock (exclusive_swap_page, others)
77 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
81 * ->page_table_lock or pte_lock (various, mainly in memory.c)
82 * ->i_pages lock (arch-dependent flush_dcache_mmap_lock)
85 * ->lock_page (access_process_vm)
87 * ->i_mutex (generic_perform_write)
88 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
91 * sb_lock (fs/fs-writeback.c)
92 * ->i_pages lock (__sync_single_inode)
95 * ->anon_vma.lock (vma_adjust)
98 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
100 * ->page_table_lock or pte_lock
101 * ->swap_lock (try_to_unmap_one)
102 * ->private_lock (try_to_unmap_one)
103 * ->i_pages lock (try_to_unmap_one)
104 * ->pgdat->lru_lock (follow_page->mark_page_accessed)
105 * ->pgdat->lru_lock (check_pte_range->isolate_lru_page)
106 * ->private_lock (page_remove_rmap->set_page_dirty)
107 * ->i_pages lock (page_remove_rmap->set_page_dirty)
108 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
109 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
110 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
111 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
112 * ->inode->i_lock (zap_pte_range->set_page_dirty)
113 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
116 * ->tasklist_lock (memory_failure, collect_procs_ao)
119 static void page_cache_delete(struct address_space *mapping,
120 struct page *page, void *shadow)
122 XA_STATE(xas, &mapping->i_pages, page->index);
125 mapping_set_update(&xas, mapping);
127 /* hugetlb pages are represented by a single entry in the xarray */
128 if (!PageHuge(page)) {
129 xas_set_order(&xas, page->index, compound_order(page));
130 nr = compound_nr(page);
133 VM_BUG_ON_PAGE(!PageLocked(page), page);
134 VM_BUG_ON_PAGE(PageTail(page), page);
135 VM_BUG_ON_PAGE(nr != 1 && shadow, page);
137 xas_store(&xas, shadow);
138 xas_init_marks(&xas);
140 page->mapping = NULL;
141 /* Leave page->index set: truncation lookup relies upon it */
144 mapping->nrexceptional += nr;
146 * Make sure the nrexceptional update is committed before
147 * the nrpages update so that final truncate racing
148 * with reclaim does not see both counters 0 at the
149 * same time and miss a shadow entry.
153 mapping->nrpages -= nr;
156 static void unaccount_page_cache_page(struct address_space *mapping,
162 * if we're uptodate, flush out into the cleancache, otherwise
163 * invalidate any existing cleancache entries. We can't leave
164 * stale data around in the cleancache once our page is gone
166 if (PageUptodate(page) && PageMappedToDisk(page))
167 cleancache_put_page(page);
169 cleancache_invalidate_page(mapping, page);
171 VM_BUG_ON_PAGE(PageTail(page), page);
172 VM_BUG_ON_PAGE(page_mapped(page), page);
173 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
176 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
177 current->comm, page_to_pfn(page));
178 dump_page(page, "still mapped when deleted");
180 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
182 mapcount = page_mapcount(page);
183 if (mapping_exiting(mapping) &&
184 page_count(page) >= mapcount + 2) {
186 * All vmas have already been torn down, so it's
187 * a good bet that actually the page is unmapped,
188 * and we'd prefer not to leak it: if we're wrong,
189 * some other bad page check should catch it later.
191 page_mapcount_reset(page);
192 page_ref_sub(page, mapcount);
196 /* hugetlb pages do not participate in page cache accounting. */
200 nr = hpage_nr_pages(page);
202 __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, -nr);
203 if (PageSwapBacked(page)) {
204 __mod_node_page_state(page_pgdat(page), NR_SHMEM, -nr);
205 if (PageTransHuge(page))
206 __dec_node_page_state(page, NR_SHMEM_THPS);
207 } else if (PageTransHuge(page)) {
208 __dec_node_page_state(page, NR_FILE_THPS);
209 filemap_nr_thps_dec(mapping);
213 * At this point page must be either written or cleaned by
214 * truncate. Dirty page here signals a bug and loss of
217 * This fixes dirty accounting after removing the page entirely
218 * but leaves PageDirty set: it has no effect for truncated
219 * page and anyway will be cleared before returning page into
222 if (WARN_ON_ONCE(PageDirty(page)))
223 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
227 * Delete a page from the page cache and free it. Caller has to make
228 * sure the page is locked and that nobody else uses it - or that usage
229 * is safe. The caller must hold the i_pages lock.
231 void __delete_from_page_cache(struct page *page, void *shadow)
233 struct address_space *mapping = page->mapping;
235 trace_mm_filemap_delete_from_page_cache(page);
237 unaccount_page_cache_page(mapping, page);
238 page_cache_delete(mapping, page, shadow);
241 static void page_cache_free_page(struct address_space *mapping,
244 void (*freepage)(struct page *);
246 freepage = mapping->a_ops->freepage;
250 if (PageTransHuge(page) && !PageHuge(page)) {
251 page_ref_sub(page, HPAGE_PMD_NR);
252 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
259 * delete_from_page_cache - delete page from page cache
260 * @page: the page which the kernel is trying to remove from page cache
262 * This must be called only on pages that have been verified to be in the page
263 * cache and locked. It will never put the page into the free list, the caller
264 * has a reference on the page.
266 void delete_from_page_cache(struct page *page)
268 struct address_space *mapping = page_mapping(page);
271 BUG_ON(!PageLocked(page));
272 xa_lock_irqsave(&mapping->i_pages, flags);
273 __delete_from_page_cache(page, NULL);
274 xa_unlock_irqrestore(&mapping->i_pages, flags);
276 page_cache_free_page(mapping, page);
278 EXPORT_SYMBOL(delete_from_page_cache);
281 * page_cache_delete_batch - delete several pages from page cache
282 * @mapping: the mapping to which pages belong
283 * @pvec: pagevec with pages to delete
285 * The function walks over mapping->i_pages and removes pages passed in @pvec
286 * from the mapping. The function expects @pvec to be sorted by page index
287 * and is optimised for it to be dense.
288 * It tolerates holes in @pvec (mapping entries at those indices are not
289 * modified). The function expects only THP head pages to be present in the
292 * The function expects the i_pages lock to be held.
294 static void page_cache_delete_batch(struct address_space *mapping,
295 struct pagevec *pvec)
297 XA_STATE(xas, &mapping->i_pages, pvec->pages[0]->index);
302 mapping_set_update(&xas, mapping);
303 xas_for_each(&xas, page, ULONG_MAX) {
304 if (i >= pagevec_count(pvec))
307 /* A swap/dax/shadow entry got inserted? Skip it. */
308 if (xa_is_value(page))
311 * A page got inserted in our range? Skip it. We have our
312 * pages locked so they are protected from being removed.
313 * If we see a page whose index is higher than ours, it
314 * means our page has been removed, which shouldn't be
315 * possible because we're holding the PageLock.
317 if (page != pvec->pages[i]) {
318 VM_BUG_ON_PAGE(page->index > pvec->pages[i]->index,
323 WARN_ON_ONCE(!PageLocked(page));
325 if (page->index == xas.xa_index)
326 page->mapping = NULL;
327 /* Leave page->index set: truncation lookup relies on it */
330 * Move to the next page in the vector if this is a regular
331 * page or the index is of the last sub-page of this compound
334 if (page->index + compound_nr(page) - 1 == xas.xa_index)
336 xas_store(&xas, NULL);
339 mapping->nrpages -= total_pages;
342 void delete_from_page_cache_batch(struct address_space *mapping,
343 struct pagevec *pvec)
348 if (!pagevec_count(pvec))
351 xa_lock_irqsave(&mapping->i_pages, flags);
352 for (i = 0; i < pagevec_count(pvec); i++) {
353 trace_mm_filemap_delete_from_page_cache(pvec->pages[i]);
355 unaccount_page_cache_page(mapping, pvec->pages[i]);
357 page_cache_delete_batch(mapping, pvec);
358 xa_unlock_irqrestore(&mapping->i_pages, flags);
360 for (i = 0; i < pagevec_count(pvec); i++)
361 page_cache_free_page(mapping, pvec->pages[i]);
364 int filemap_check_errors(struct address_space *mapping)
367 /* Check for outstanding write errors */
368 if (test_bit(AS_ENOSPC, &mapping->flags) &&
369 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
371 if (test_bit(AS_EIO, &mapping->flags) &&
372 test_and_clear_bit(AS_EIO, &mapping->flags))
376 EXPORT_SYMBOL(filemap_check_errors);
378 static int filemap_check_and_keep_errors(struct address_space *mapping)
380 /* Check for outstanding write errors */
381 if (test_bit(AS_EIO, &mapping->flags))
383 if (test_bit(AS_ENOSPC, &mapping->flags))
389 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
390 * @mapping: address space structure to write
391 * @start: offset in bytes where the range starts
392 * @end: offset in bytes where the range ends (inclusive)
393 * @sync_mode: enable synchronous operation
395 * Start writeback against all of a mapping's dirty pages that lie
396 * within the byte offsets <start, end> inclusive.
398 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
399 * opposed to a regular memory cleansing writeback. The difference between
400 * these two operations is that if a dirty page/buffer is encountered, it must
401 * be waited upon, and not just skipped over.
403 * Return: %0 on success, negative error code otherwise.
405 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
406 loff_t end, int sync_mode)
409 struct writeback_control wbc = {
410 .sync_mode = sync_mode,
411 .nr_to_write = LONG_MAX,
412 .range_start = start,
416 if (!mapping_cap_writeback_dirty(mapping) ||
417 !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
420 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
421 ret = do_writepages(mapping, &wbc);
422 wbc_detach_inode(&wbc);
426 static inline int __filemap_fdatawrite(struct address_space *mapping,
429 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
432 int filemap_fdatawrite(struct address_space *mapping)
434 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
436 EXPORT_SYMBOL(filemap_fdatawrite);
438 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
441 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
443 EXPORT_SYMBOL(filemap_fdatawrite_range);
446 * filemap_flush - mostly a non-blocking flush
447 * @mapping: target address_space
449 * This is a mostly non-blocking flush. Not suitable for data-integrity
450 * purposes - I/O may not be started against all dirty pages.
452 * Return: %0 on success, negative error code otherwise.
454 int filemap_flush(struct address_space *mapping)
456 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
458 EXPORT_SYMBOL(filemap_flush);
461 * filemap_range_has_page - check if a page exists in range.
462 * @mapping: address space within which to check
463 * @start_byte: offset in bytes where the range starts
464 * @end_byte: offset in bytes where the range ends (inclusive)
466 * Find at least one page in the range supplied, usually used to check if
467 * direct writing in this range will trigger a writeback.
469 * Return: %true if at least one page exists in the specified range,
472 bool filemap_range_has_page(struct address_space *mapping,
473 loff_t start_byte, loff_t end_byte)
476 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
477 pgoff_t max = end_byte >> PAGE_SHIFT;
479 if (end_byte < start_byte)
484 page = xas_find(&xas, max);
485 if (xas_retry(&xas, page))
487 /* Shadow entries don't count */
488 if (xa_is_value(page))
491 * We don't need to try to pin this page; we're about to
492 * release the RCU lock anyway. It is enough to know that
493 * there was a page here recently.
501 EXPORT_SYMBOL(filemap_range_has_page);
503 static void __filemap_fdatawait_range(struct address_space *mapping,
504 loff_t start_byte, loff_t end_byte)
506 pgoff_t index = start_byte >> PAGE_SHIFT;
507 pgoff_t end = end_byte >> PAGE_SHIFT;
511 if (end_byte < start_byte)
515 while (index <= end) {
518 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
519 end, PAGECACHE_TAG_WRITEBACK);
523 for (i = 0; i < nr_pages; i++) {
524 struct page *page = pvec.pages[i];
526 wait_on_page_writeback(page);
527 ClearPageError(page);
529 pagevec_release(&pvec);
535 * filemap_fdatawait_range - wait for writeback to complete
536 * @mapping: address space structure to wait for
537 * @start_byte: offset in bytes where the range starts
538 * @end_byte: offset in bytes where the range ends (inclusive)
540 * Walk the list of under-writeback pages of the given address space
541 * in the given range and wait for all of them. Check error status of
542 * the address space and return it.
544 * Since the error status of the address space is cleared by this function,
545 * callers are responsible for checking the return value and handling and/or
546 * reporting the error.
548 * Return: error status of the address space.
550 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
553 __filemap_fdatawait_range(mapping, start_byte, end_byte);
554 return filemap_check_errors(mapping);
556 EXPORT_SYMBOL(filemap_fdatawait_range);
559 * filemap_fdatawait_range_keep_errors - wait for writeback to complete
560 * @mapping: address space structure to wait for
561 * @start_byte: offset in bytes where the range starts
562 * @end_byte: offset in bytes where the range ends (inclusive)
564 * Walk the list of under-writeback pages of the given address space in the
565 * given range and wait for all of them. Unlike filemap_fdatawait_range(),
566 * this function does not clear error status of the address space.
568 * Use this function if callers don't handle errors themselves. Expected
569 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
572 int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
573 loff_t start_byte, loff_t end_byte)
575 __filemap_fdatawait_range(mapping, start_byte, end_byte);
576 return filemap_check_and_keep_errors(mapping);
578 EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
581 * file_fdatawait_range - wait for writeback to complete
582 * @file: file pointing to address space structure to wait for
583 * @start_byte: offset in bytes where the range starts
584 * @end_byte: offset in bytes where the range ends (inclusive)
586 * Walk the list of under-writeback pages of the address space that file
587 * refers to, in the given range and wait for all of them. Check error
588 * status of the address space vs. the file->f_wb_err cursor and return it.
590 * Since the error status of the file is advanced by this function,
591 * callers are responsible for checking the return value and handling and/or
592 * reporting the error.
594 * Return: error status of the address space vs. the file->f_wb_err cursor.
596 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
598 struct address_space *mapping = file->f_mapping;
600 __filemap_fdatawait_range(mapping, start_byte, end_byte);
601 return file_check_and_advance_wb_err(file);
603 EXPORT_SYMBOL(file_fdatawait_range);
606 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
607 * @mapping: address space structure to wait for
609 * Walk the list of under-writeback pages of the given address space
610 * and wait for all of them. Unlike filemap_fdatawait(), this function
611 * does not clear error status of the address space.
613 * Use this function if callers don't handle errors themselves. Expected
614 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
617 * Return: error status of the address space.
619 int filemap_fdatawait_keep_errors(struct address_space *mapping)
621 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
622 return filemap_check_and_keep_errors(mapping);
624 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
626 /* Returns true if writeback might be needed or already in progress. */
627 static bool mapping_needs_writeback(struct address_space *mapping)
629 if (dax_mapping(mapping))
630 return mapping->nrexceptional;
632 return mapping->nrpages;
635 int filemap_write_and_wait(struct address_space *mapping)
639 if (mapping_needs_writeback(mapping)) {
640 err = filemap_fdatawrite(mapping);
642 * Even if the above returned error, the pages may be
643 * written partially (e.g. -ENOSPC), so we wait for it.
644 * But the -EIO is special case, it may indicate the worst
645 * thing (e.g. bug) happened, so we avoid waiting for it.
648 int err2 = filemap_fdatawait(mapping);
652 /* Clear any previously stored errors */
653 filemap_check_errors(mapping);
656 err = filemap_check_errors(mapping);
660 EXPORT_SYMBOL(filemap_write_and_wait);
663 * filemap_write_and_wait_range - write out & wait on a file range
664 * @mapping: the address_space for the pages
665 * @lstart: offset in bytes where the range starts
666 * @lend: offset in bytes where the range ends (inclusive)
668 * Write out and wait upon file offsets lstart->lend, inclusive.
670 * Note that @lend is inclusive (describes the last byte to be written) so
671 * that this function can be used to write to the very end-of-file (end = -1).
673 * Return: error status of the address space.
675 int filemap_write_and_wait_range(struct address_space *mapping,
676 loff_t lstart, loff_t lend)
680 if (mapping_needs_writeback(mapping)) {
681 err = __filemap_fdatawrite_range(mapping, lstart, lend,
683 /* See comment of filemap_write_and_wait() */
685 int err2 = filemap_fdatawait_range(mapping,
690 /* Clear any previously stored errors */
691 filemap_check_errors(mapping);
694 err = filemap_check_errors(mapping);
698 EXPORT_SYMBOL(filemap_write_and_wait_range);
700 void __filemap_set_wb_err(struct address_space *mapping, int err)
702 errseq_t eseq = errseq_set(&mapping->wb_err, err);
704 trace_filemap_set_wb_err(mapping, eseq);
706 EXPORT_SYMBOL(__filemap_set_wb_err);
709 * file_check_and_advance_wb_err - report wb error (if any) that was previously
710 * and advance wb_err to current one
711 * @file: struct file on which the error is being reported
713 * When userland calls fsync (or something like nfsd does the equivalent), we
714 * want to report any writeback errors that occurred since the last fsync (or
715 * since the file was opened if there haven't been any).
717 * Grab the wb_err from the mapping. If it matches what we have in the file,
718 * then just quickly return 0. The file is all caught up.
720 * If it doesn't match, then take the mapping value, set the "seen" flag in
721 * it and try to swap it into place. If it works, or another task beat us
722 * to it with the new value, then update the f_wb_err and return the error
723 * portion. The error at this point must be reported via proper channels
724 * (a'la fsync, or NFS COMMIT operation, etc.).
726 * While we handle mapping->wb_err with atomic operations, the f_wb_err
727 * value is protected by the f_lock since we must ensure that it reflects
728 * the latest value swapped in for this file descriptor.
730 * Return: %0 on success, negative error code otherwise.
732 int file_check_and_advance_wb_err(struct file *file)
735 errseq_t old = READ_ONCE(file->f_wb_err);
736 struct address_space *mapping = file->f_mapping;
738 /* Locklessly handle the common case where nothing has changed */
739 if (errseq_check(&mapping->wb_err, old)) {
740 /* Something changed, must use slow path */
741 spin_lock(&file->f_lock);
742 old = file->f_wb_err;
743 err = errseq_check_and_advance(&mapping->wb_err,
745 trace_file_check_and_advance_wb_err(file, old);
746 spin_unlock(&file->f_lock);
750 * We're mostly using this function as a drop in replacement for
751 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
752 * that the legacy code would have had on these flags.
754 clear_bit(AS_EIO, &mapping->flags);
755 clear_bit(AS_ENOSPC, &mapping->flags);
758 EXPORT_SYMBOL(file_check_and_advance_wb_err);
761 * file_write_and_wait_range - write out & wait on a file range
762 * @file: file pointing to address_space with pages
763 * @lstart: offset in bytes where the range starts
764 * @lend: offset in bytes where the range ends (inclusive)
766 * Write out and wait upon file offsets lstart->lend, inclusive.
768 * Note that @lend is inclusive (describes the last byte to be written) so
769 * that this function can be used to write to the very end-of-file (end = -1).
771 * After writing out and waiting on the data, we check and advance the
772 * f_wb_err cursor to the latest value, and return any errors detected there.
774 * Return: %0 on success, negative error code otherwise.
776 int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
779 struct address_space *mapping = file->f_mapping;
781 if (mapping_needs_writeback(mapping)) {
782 err = __filemap_fdatawrite_range(mapping, lstart, lend,
784 /* See comment of filemap_write_and_wait() */
786 __filemap_fdatawait_range(mapping, lstart, lend);
788 err2 = file_check_and_advance_wb_err(file);
793 EXPORT_SYMBOL(file_write_and_wait_range);
796 * replace_page_cache_page - replace a pagecache page with a new one
797 * @old: page to be replaced
798 * @new: page to replace with
799 * @gfp_mask: allocation mode
801 * This function replaces a page in the pagecache with a new one. On
802 * success it acquires the pagecache reference for the new page and
803 * drops it for the old page. Both the old and new pages must be
804 * locked. This function does not add the new page to the LRU, the
805 * caller must do that.
807 * The remove + add is atomic. This function cannot fail.
811 int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
813 struct address_space *mapping = old->mapping;
814 void (*freepage)(struct page *) = mapping->a_ops->freepage;
815 pgoff_t offset = old->index;
816 XA_STATE(xas, &mapping->i_pages, offset);
819 VM_BUG_ON_PAGE(!PageLocked(old), old);
820 VM_BUG_ON_PAGE(!PageLocked(new), new);
821 VM_BUG_ON_PAGE(new->mapping, new);
824 new->mapping = mapping;
827 xas_lock_irqsave(&xas, flags);
828 xas_store(&xas, new);
831 /* hugetlb pages do not participate in page cache accounting. */
833 __dec_node_page_state(new, NR_FILE_PAGES);
835 __inc_node_page_state(new, NR_FILE_PAGES);
836 if (PageSwapBacked(old))
837 __dec_node_page_state(new, NR_SHMEM);
838 if (PageSwapBacked(new))
839 __inc_node_page_state(new, NR_SHMEM);
840 xas_unlock_irqrestore(&xas, flags);
841 mem_cgroup_migrate(old, new);
848 EXPORT_SYMBOL_GPL(replace_page_cache_page);
850 noinline int __add_to_page_cache_locked(struct page *page,
851 struct address_space *mapping,
852 pgoff_t offset, gfp_t gfp_mask,
855 XA_STATE(xas, &mapping->i_pages, offset);
856 int huge = PageHuge(page);
857 struct mem_cgroup *memcg;
860 VM_BUG_ON_PAGE(!PageLocked(page), page);
861 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
862 mapping_set_update(&xas, mapping);
865 error = mem_cgroup_try_charge(page, current->mm,
866 gfp_mask, &memcg, false);
872 page->mapping = mapping;
873 page->index = offset;
874 gfp_mask &= GFP_RECLAIM_MASK;
877 unsigned int order = xa_get_order(xas.xa, xas.xa_index);
878 void *entry, *old = NULL;
880 if (order > thp_order(page))
881 xas_split_alloc(&xas, xa_load(xas.xa, xas.xa_index),
884 xas_for_each_conflict(&xas, entry) {
886 if (!xa_is_value(entry)) {
887 xas_set_err(&xas, -EEXIST);
895 /* entry may have been split before we acquired lock */
896 order = xa_get_order(xas.xa, xas.xa_index);
897 if (order > thp_order(page)) {
898 xas_split(&xas, old, order);
903 xas_store(&xas, page);
908 mapping->nrexceptional--;
911 /* hugetlb pages do not participate in page cache accounting */
913 __inc_node_page_state(page, NR_FILE_PAGES);
915 xas_unlock_irq(&xas);
916 } while (xas_nomem(&xas, gfp_mask));
922 mem_cgroup_commit_charge(page, memcg, false, false);
923 trace_mm_filemap_add_to_page_cache(page);
926 page->mapping = NULL;
927 /* Leave page->index set: truncation relies upon it */
929 mem_cgroup_cancel_charge(page, memcg, false);
931 return xas_error(&xas);
933 ALLOW_ERROR_INJECTION(__add_to_page_cache_locked, ERRNO);
936 * add_to_page_cache_locked - add a locked page to the pagecache
938 * @mapping: the page's address_space
939 * @offset: page index
940 * @gfp_mask: page allocation mode
942 * This function is used to add a page to the pagecache. It must be locked.
943 * This function does not add the page to the LRU. The caller must do that.
945 * Return: %0 on success, negative error code otherwise.
947 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
948 pgoff_t offset, gfp_t gfp_mask)
950 return __add_to_page_cache_locked(page, mapping, offset,
953 EXPORT_SYMBOL(add_to_page_cache_locked);
955 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
956 pgoff_t offset, gfp_t gfp_mask)
961 __SetPageLocked(page);
962 ret = __add_to_page_cache_locked(page, mapping, offset,
965 __ClearPageLocked(page);
968 * The page might have been evicted from cache only
969 * recently, in which case it should be activated like
970 * any other repeatedly accessed page.
971 * The exception is pages getting rewritten; evicting other
972 * data from the working set, only to cache data that will
973 * get overwritten with something else, is a waste of memory.
975 WARN_ON_ONCE(PageActive(page));
976 if (!(gfp_mask & __GFP_WRITE) && shadow)
977 workingset_refault(page, shadow);
982 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
985 struct page *__page_cache_alloc(gfp_t gfp)
990 if (cpuset_do_page_mem_spread()) {
991 unsigned int cpuset_mems_cookie;
993 cpuset_mems_cookie = read_mems_allowed_begin();
994 n = cpuset_mem_spread_node();
995 page = __alloc_pages_node(n, gfp, 0);
996 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
1000 return alloc_pages(gfp, 0);
1002 EXPORT_SYMBOL(__page_cache_alloc);
1006 * In order to wait for pages to become available there must be
1007 * waitqueues associated with pages. By using a hash table of
1008 * waitqueues where the bucket discipline is to maintain all
1009 * waiters on the same queue and wake all when any of the pages
1010 * become available, and for the woken contexts to check to be
1011 * sure the appropriate page became available, this saves space
1012 * at a cost of "thundering herd" phenomena during rare hash
1015 #define PAGE_WAIT_TABLE_BITS 8
1016 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
1017 static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
1019 static wait_queue_head_t *page_waitqueue(struct page *page)
1021 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
1024 void __init pagecache_init(void)
1028 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1029 init_waitqueue_head(&page_wait_table[i]);
1031 page_writeback_init();
1034 /* This has the same layout as wait_bit_key - see fs/cachefiles/rdwr.c */
1035 struct wait_page_key {
1041 struct wait_page_queue {
1044 wait_queue_entry_t wait;
1048 * The page wait code treats the "wait->flags" somewhat unusually, because
1049 * we have multiple different kinds of waits, not just he usual "exclusive"
1054 * (a) no special bits set:
1056 * We're just waiting for the bit to be released, and when a waker
1057 * calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up,
1058 * and remove it from the wait queue.
1060 * Simple and straightforward.
1062 * (b) WQ_FLAG_EXCLUSIVE:
1064 * The waiter is waiting to get the lock, and only one waiter should
1065 * be woken up to avoid any thundering herd behavior. We'll set the
1066 * WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue.
1068 * This is the traditional exclusive wait.
1070 * (b) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
1072 * The waiter is waiting to get the bit, and additionally wants the
1073 * lock to be transferred to it for fair lock behavior. If the lock
1074 * cannot be taken, we stop walking the wait queue without waking
1077 * This is the "fair lock handoff" case, and in addition to setting
1078 * WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see
1079 * that it now has the lock.
1081 static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
1084 struct wait_page_key *key = arg;
1085 struct wait_page_queue *wait_page
1086 = container_of(wait, struct wait_page_queue, wait);
1088 if (wait_page->page != key->page)
1090 key->page_match = 1;
1092 if (wait_page->bit_nr != key->bit_nr)
1096 * If it's a lock handoff wait, we get the bit for it, and
1097 * stop walking (and do not wake it up) if we can't.
1099 flags = wait->flags;
1100 if (flags & WQ_FLAG_EXCLUSIVE) {
1101 if (test_bit(key->bit_nr, &key->page->flags))
1103 if (flags & WQ_FLAG_CUSTOM) {
1104 if (test_and_set_bit(key->bit_nr, &key->page->flags))
1106 flags |= WQ_FLAG_DONE;
1111 * We are holding the wait-queue lock, but the waiter that
1112 * is waiting for this will be checking the flags without
1115 * So update the flags atomically, and wake up the waiter
1116 * afterwards to avoid any races. This store-release pairs
1117 * with the load-acquire in wait_on_page_bit_common().
1119 smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
1120 wake_up_state(wait->private, mode);
1123 * Ok, we have successfully done what we're waiting for,
1124 * and we can unconditionally remove the wait entry.
1126 * Note that this pairs with the "finish_wait()" in the
1127 * waiter, and has to be the absolute last thing we do.
1128 * After this list_del_init(&wait->entry) the wait entry
1129 * might be de-allocated and the process might even have
1132 list_del_init_careful(&wait->entry);
1133 return (flags & WQ_FLAG_EXCLUSIVE) != 0;
1136 static void wake_up_page_bit(struct page *page, int bit_nr)
1138 wait_queue_head_t *q = page_waitqueue(page);
1139 struct wait_page_key key;
1140 unsigned long flags;
1141 wait_queue_entry_t bookmark;
1144 key.bit_nr = bit_nr;
1148 bookmark.private = NULL;
1149 bookmark.func = NULL;
1150 INIT_LIST_HEAD(&bookmark.entry);
1152 spin_lock_irqsave(&q->lock, flags);
1153 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1155 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1157 * Take a breather from holding the lock,
1158 * allow pages that finish wake up asynchronously
1159 * to acquire the lock and remove themselves
1162 spin_unlock_irqrestore(&q->lock, flags);
1164 spin_lock_irqsave(&q->lock, flags);
1165 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1169 * It is possible for other pages to have collided on the waitqueue
1170 * hash, so in that case check for a page match. That prevents a long-
1173 * It is still possible to miss a case here, when we woke page waiters
1174 * and removed them from the waitqueue, but there are still other
1177 if (!waitqueue_active(q) || !key.page_match) {
1178 ClearPageWaiters(page);
1180 * It's possible to miss clearing Waiters here, when we woke
1181 * our page waiters, but the hashed waitqueue has waiters for
1182 * other pages on it.
1184 * That's okay, it's a rare case. The next waker will clear it.
1187 spin_unlock_irqrestore(&q->lock, flags);
1190 static void wake_up_page(struct page *page, int bit)
1192 if (!PageWaiters(page))
1194 wake_up_page_bit(page, bit);
1198 * A choice of three behaviors for wait_on_page_bit_common():
1201 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
1202 * __lock_page() waiting on then setting PG_locked.
1204 SHARED, /* Hold ref to page and check the bit when woken, like
1205 * wait_on_page_writeback() waiting on PG_writeback.
1207 DROP, /* Drop ref to page before wait, no check when woken,
1208 * like put_and_wait_on_page_locked() on PG_locked.
1213 * Attempt to check (or get) the page bit, and mark us done
1216 static inline bool trylock_page_bit_common(struct page *page, int bit_nr,
1217 struct wait_queue_entry *wait)
1219 if (wait->flags & WQ_FLAG_EXCLUSIVE) {
1220 if (test_and_set_bit(bit_nr, &page->flags))
1222 } else if (test_bit(bit_nr, &page->flags))
1225 wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
1229 /* How many times do we accept lock stealing from under a waiter? */
1230 int sysctl_page_lock_unfairness = 5;
1232 static inline int wait_on_page_bit_common(wait_queue_head_t *q,
1233 struct page *page, int bit_nr, int state, enum behavior behavior)
1235 int unfairness = sysctl_page_lock_unfairness;
1236 struct wait_page_queue wait_page;
1237 wait_queue_entry_t *wait = &wait_page.wait;
1238 bool thrashing = false;
1239 bool delayacct = false;
1240 unsigned long pflags;
1242 if (bit_nr == PG_locked &&
1243 !PageUptodate(page) && PageWorkingset(page)) {
1244 if (!PageSwapBacked(page)) {
1245 delayacct_thrashing_start();
1248 psi_memstall_enter(&pflags);
1253 wait->func = wake_page_function;
1254 wait_page.page = page;
1255 wait_page.bit_nr = bit_nr;
1259 if (behavior == EXCLUSIVE) {
1260 wait->flags = WQ_FLAG_EXCLUSIVE;
1261 if (--unfairness < 0)
1262 wait->flags |= WQ_FLAG_CUSTOM;
1266 * Do one last check whether we can get the
1267 * page bit synchronously.
1269 * Do the SetPageWaiters() marking before that
1270 * to let any waker we _just_ missed know they
1271 * need to wake us up (otherwise they'll never
1272 * even go to the slow case that looks at the
1273 * page queue), and add ourselves to the wait
1274 * queue if we need to sleep.
1276 * This part needs to be done under the queue
1277 * lock to avoid races.
1279 spin_lock_irq(&q->lock);
1280 SetPageWaiters(page);
1281 if (!trylock_page_bit_common(page, bit_nr, wait))
1282 __add_wait_queue_entry_tail(q, wait);
1283 spin_unlock_irq(&q->lock);
1286 * From now on, all the logic will be based on
1287 * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to
1288 * see whether the page bit testing has already
1289 * been done by the wake function.
1291 * We can drop our reference to the page.
1293 if (behavior == DROP)
1297 * Note that until the "finish_wait()", or until
1298 * we see the WQ_FLAG_WOKEN flag, we need to
1299 * be very careful with the 'wait->flags', because
1300 * we may race with a waker that sets them.
1305 set_current_state(state);
1307 /* Loop until we've been woken or interrupted */
1308 flags = smp_load_acquire(&wait->flags);
1309 if (!(flags & WQ_FLAG_WOKEN)) {
1310 if (signal_pending_state(state, current))
1317 /* If we were non-exclusive, we're done */
1318 if (behavior != EXCLUSIVE)
1321 /* If the waker got the lock for us, we're done */
1322 if (flags & WQ_FLAG_DONE)
1326 * Otherwise, if we're getting the lock, we need to
1327 * try to get it ourselves.
1329 * And if that fails, we'll have to retry this all.
1331 if (unlikely(test_and_set_bit(bit_nr, &page->flags)))
1334 wait->flags |= WQ_FLAG_DONE;
1339 * If a signal happened, this 'finish_wait()' may remove the last
1340 * waiter from the wait-queues, but the PageWaiters bit will remain
1341 * set. That's ok. The next wakeup will take care of it, and trying
1342 * to do it here would be difficult and prone to races.
1344 finish_wait(q, wait);
1348 delayacct_thrashing_end();
1349 psi_memstall_leave(&pflags);
1353 * NOTE! The wait->flags weren't stable until we've done the
1354 * 'finish_wait()', and we could have exited the loop above due
1355 * to a signal, and had a wakeup event happen after the signal
1356 * test but before the 'finish_wait()'.
1358 * So only after the finish_wait() can we reliably determine
1359 * if we got woken up or not, so we can now figure out the final
1360 * return value based on that state without races.
1362 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
1363 * waiter, but an exclusive one requires WQ_FLAG_DONE.
1365 if (behavior == EXCLUSIVE)
1366 return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
1368 return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
1371 void wait_on_page_bit(struct page *page, int bit_nr)
1373 wait_queue_head_t *q = page_waitqueue(page);
1374 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
1376 EXPORT_SYMBOL(wait_on_page_bit);
1378 int wait_on_page_bit_killable(struct page *page, int bit_nr)
1380 wait_queue_head_t *q = page_waitqueue(page);
1381 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, SHARED);
1383 EXPORT_SYMBOL(wait_on_page_bit_killable);
1386 * put_and_wait_on_page_locked - Drop a reference and wait for it to be unlocked
1387 * @page: The page to wait for.
1389 * The caller should hold a reference on @page. They expect the page to
1390 * become unlocked relatively soon, but do not wish to hold up migration
1391 * (for example) by holding the reference while waiting for the page to
1392 * come unlocked. After this function returns, the caller should not
1393 * dereference @page.
1395 void put_and_wait_on_page_locked(struct page *page)
1397 wait_queue_head_t *q;
1399 page = compound_head(page);
1400 q = page_waitqueue(page);
1401 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE, DROP);
1405 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
1406 * @page: Page defining the wait queue of interest
1407 * @waiter: Waiter to add to the queue
1409 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1411 void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
1413 wait_queue_head_t *q = page_waitqueue(page);
1414 unsigned long flags;
1416 spin_lock_irqsave(&q->lock, flags);
1417 __add_wait_queue_entry_tail(q, waiter);
1418 SetPageWaiters(page);
1419 spin_unlock_irqrestore(&q->lock, flags);
1421 EXPORT_SYMBOL_GPL(add_page_wait_queue);
1423 #ifndef clear_bit_unlock_is_negative_byte
1426 * PG_waiters is the high bit in the same byte as PG_lock.
1428 * On x86 (and on many other architectures), we can clear PG_lock and
1429 * test the sign bit at the same time. But if the architecture does
1430 * not support that special operation, we just do this all by hand
1433 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1434 * being cleared, but a memory barrier should be unneccssary since it is
1435 * in the same byte as PG_locked.
1437 static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1439 clear_bit_unlock(nr, mem);
1440 /* smp_mb__after_atomic(); */
1441 return test_bit(PG_waiters, mem);
1447 * unlock_page - unlock a locked page
1450 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
1451 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
1452 * mechanism between PageLocked pages and PageWriteback pages is shared.
1453 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1455 * Note that this depends on PG_waiters being the sign bit in the byte
1456 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1457 * clear the PG_locked bit and test PG_waiters at the same time fairly
1458 * portably (architectures that do LL/SC can test any bit, while x86 can
1459 * test the sign bit).
1461 void unlock_page(struct page *page)
1463 BUILD_BUG_ON(PG_waiters != 7);
1464 page = compound_head(page);
1465 VM_BUG_ON_PAGE(!PageLocked(page), page);
1466 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1467 wake_up_page_bit(page, PG_locked);
1469 EXPORT_SYMBOL(unlock_page);
1472 * end_page_writeback - end writeback against a page
1475 void end_page_writeback(struct page *page)
1478 * TestClearPageReclaim could be used here but it is an atomic
1479 * operation and overkill in this particular case. Failing to
1480 * shuffle a page marked for immediate reclaim is too mild to
1481 * justify taking an atomic operation penalty at the end of
1482 * ever page writeback.
1484 if (PageReclaim(page)) {
1485 ClearPageReclaim(page);
1486 rotate_reclaimable_page(page);
1490 * Writeback does not hold a page reference of its own, relying
1491 * on truncation to wait for the clearing of PG_writeback.
1492 * But here we must make sure that the page is not freed and
1493 * reused before the wake_up_page().
1496 if (!test_clear_page_writeback(page))
1499 smp_mb__after_atomic();
1500 wake_up_page(page, PG_writeback);
1503 EXPORT_SYMBOL(end_page_writeback);
1506 * After completing I/O on a page, call this routine to update the page
1507 * flags appropriately
1509 void page_endio(struct page *page, bool is_write, int err)
1513 SetPageUptodate(page);
1515 ClearPageUptodate(page);
1521 struct address_space *mapping;
1524 mapping = page_mapping(page);
1526 mapping_set_error(mapping, err);
1528 end_page_writeback(page);
1531 EXPORT_SYMBOL_GPL(page_endio);
1534 * __lock_page - get a lock on the page, assuming we need to sleep to get it
1535 * @__page: the page to lock
1537 void __lock_page(struct page *__page)
1539 struct page *page = compound_head(__page);
1540 wait_queue_head_t *q = page_waitqueue(page);
1541 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE,
1544 EXPORT_SYMBOL(__lock_page);
1546 int __lock_page_killable(struct page *__page)
1548 struct page *page = compound_head(__page);
1549 wait_queue_head_t *q = page_waitqueue(page);
1550 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE,
1553 EXPORT_SYMBOL_GPL(__lock_page_killable);
1557 * 1 - page is locked; mmap_sem is still held.
1558 * 0 - page is not locked.
1559 * mmap_sem has been released (up_read()), unless flags had both
1560 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1561 * which case mmap_sem is still held.
1563 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1564 * with the page locked and the mmap_sem unperturbed.
1566 int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1569 if (flags & FAULT_FLAG_ALLOW_RETRY) {
1571 * CAUTION! In this case, mmap_sem is not released
1572 * even though return 0.
1574 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1577 up_read(&mm->mmap_sem);
1578 if (flags & FAULT_FLAG_KILLABLE)
1579 wait_on_page_locked_killable(page);
1581 wait_on_page_locked(page);
1584 if (flags & FAULT_FLAG_KILLABLE) {
1587 ret = __lock_page_killable(page);
1589 up_read(&mm->mmap_sem);
1599 * page_cache_next_miss() - Find the next gap in the page cache.
1600 * @mapping: Mapping.
1602 * @max_scan: Maximum range to search.
1604 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1605 * gap with the lowest index.
1607 * This function may be called under the rcu_read_lock. However, this will
1608 * not atomically search a snapshot of the cache at a single point in time.
1609 * For example, if a gap is created at index 5, then subsequently a gap is
1610 * created at index 10, page_cache_next_miss covering both indices may
1611 * return 10 if called under the rcu_read_lock.
1613 * Return: The index of the gap if found, otherwise an index outside the
1614 * range specified (in which case 'return - index >= max_scan' will be true).
1615 * In the rare case of index wrap-around, 0 will be returned.
1617 pgoff_t page_cache_next_miss(struct address_space *mapping,
1618 pgoff_t index, unsigned long max_scan)
1620 XA_STATE(xas, &mapping->i_pages, index);
1622 while (max_scan--) {
1623 void *entry = xas_next(&xas);
1624 if (!entry || xa_is_value(entry))
1626 if (xas.xa_index == 0)
1630 return xas.xa_index;
1632 EXPORT_SYMBOL(page_cache_next_miss);
1635 * page_cache_prev_miss() - Find the previous gap in the page cache.
1636 * @mapping: Mapping.
1638 * @max_scan: Maximum range to search.
1640 * Search the range [max(index - max_scan + 1, 0), index] for the
1641 * gap with the highest index.
1643 * This function may be called under the rcu_read_lock. However, this will
1644 * not atomically search a snapshot of the cache at a single point in time.
1645 * For example, if a gap is created at index 10, then subsequently a gap is
1646 * created at index 5, page_cache_prev_miss() covering both indices may
1647 * return 5 if called under the rcu_read_lock.
1649 * Return: The index of the gap if found, otherwise an index outside the
1650 * range specified (in which case 'index - return >= max_scan' will be true).
1651 * In the rare case of wrap-around, ULONG_MAX will be returned.
1653 pgoff_t page_cache_prev_miss(struct address_space *mapping,
1654 pgoff_t index, unsigned long max_scan)
1656 XA_STATE(xas, &mapping->i_pages, index);
1658 while (max_scan--) {
1659 void *entry = xas_prev(&xas);
1660 if (!entry || xa_is_value(entry))
1662 if (xas.xa_index == ULONG_MAX)
1666 return xas.xa_index;
1668 EXPORT_SYMBOL(page_cache_prev_miss);
1671 * find_get_entry - find and get a page cache entry
1672 * @mapping: the address_space to search
1673 * @offset: the page cache index
1675 * Looks up the page cache slot at @mapping & @offset. If there is a
1676 * page cache page, it is returned with an increased refcount.
1678 * If the slot holds a shadow entry of a previously evicted page, or a
1679 * swap entry from shmem/tmpfs, it is returned.
1681 * Return: the found page or shadow entry, %NULL if nothing is found.
1683 struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
1685 XA_STATE(xas, &mapping->i_pages, offset);
1691 page = xas_load(&xas);
1692 if (xas_retry(&xas, page))
1695 * A shadow entry of a recently evicted page, or a swap entry from
1696 * shmem/tmpfs. Return it without attempting to raise page count.
1698 if (!page || xa_is_value(page))
1701 if (!page_cache_get_speculative(page))
1705 * Has the page moved or been split?
1706 * This is part of the lockless pagecache protocol. See
1707 * include/linux/pagemap.h for details.
1709 if (unlikely(page != xas_reload(&xas))) {
1713 page = find_subpage(page, offset);
1719 EXPORT_SYMBOL(find_get_entry);
1722 * find_lock_entry - locate, pin and lock a page cache entry
1723 * @mapping: the address_space to search
1724 * @offset: the page cache index
1726 * Looks up the page cache slot at @mapping & @offset. If there is a
1727 * page cache page, it is returned locked and with an increased
1730 * If the slot holds a shadow entry of a previously evicted page, or a
1731 * swap entry from shmem/tmpfs, it is returned.
1733 * find_lock_entry() may sleep.
1735 * Return: the found page or shadow entry, %NULL if nothing is found.
1737 struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
1742 page = find_get_entry(mapping, offset);
1743 if (page && !xa_is_value(page)) {
1745 /* Has the page been truncated? */
1746 if (unlikely(page_mapping(page) != mapping)) {
1751 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
1755 EXPORT_SYMBOL(find_lock_entry);
1758 * pagecache_get_page - find and get a page reference
1759 * @mapping: the address_space to search
1760 * @offset: the page index
1761 * @fgp_flags: PCG flags
1762 * @gfp_mask: gfp mask to use for the page cache data page allocation
1764 * Looks up the page cache slot at @mapping & @offset.
1766 * PCG flags modify how the page is returned.
1768 * @fgp_flags can be:
1770 * - FGP_ACCESSED: the page will be marked accessed
1771 * - FGP_LOCK: Page is return locked
1772 * - FGP_CREAT: If page is not present then a new page is allocated using
1773 * @gfp_mask and added to the page cache and the VM's LRU
1774 * list. The page is returned locked and with an increased
1776 * - FGP_FOR_MMAP: Similar to FGP_CREAT, only we want to allow the caller to do
1777 * its own locking dance if the page is already in cache, or unlock the page
1778 * before returning if we had to add the page to pagecache.
1780 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1781 * if the GFP flags specified for FGP_CREAT are atomic.
1783 * If there is a page cache page, it is returned with an increased refcount.
1785 * Return: the found page or %NULL otherwise.
1787 struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
1788 int fgp_flags, gfp_t gfp_mask)
1793 page = find_get_entry(mapping, offset);
1794 if (xa_is_value(page))
1799 if (fgp_flags & FGP_LOCK) {
1800 if (fgp_flags & FGP_NOWAIT) {
1801 if (!trylock_page(page)) {
1809 /* Has the page been truncated? */
1810 if (unlikely(compound_head(page)->mapping != mapping)) {
1815 VM_BUG_ON_PAGE(page->index != offset, page);
1818 if (fgp_flags & FGP_ACCESSED)
1819 mark_page_accessed(page);
1822 if (!page && (fgp_flags & FGP_CREAT)) {
1824 if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
1825 gfp_mask |= __GFP_WRITE;
1826 if (fgp_flags & FGP_NOFS)
1827 gfp_mask &= ~__GFP_FS;
1829 page = __page_cache_alloc(gfp_mask);
1833 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
1834 fgp_flags |= FGP_LOCK;
1836 /* Init accessed so avoid atomic mark_page_accessed later */
1837 if (fgp_flags & FGP_ACCESSED)
1838 __SetPageReferenced(page);
1840 err = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
1841 if (unlikely(err)) {
1849 * add_to_page_cache_lru locks the page, and for mmap we expect
1852 if (page && (fgp_flags & FGP_FOR_MMAP))
1858 EXPORT_SYMBOL(pagecache_get_page);
1861 * find_get_entries - gang pagecache lookup
1862 * @mapping: The address_space to search
1863 * @start: The starting page cache index
1864 * @nr_entries: The maximum number of entries
1865 * @entries: Where the resulting entries are placed
1866 * @indices: The cache indices corresponding to the entries in @entries
1868 * find_get_entries() will search for and return a group of up to
1869 * @nr_entries entries in the mapping. The entries are placed at
1870 * @entries. find_get_entries() takes a reference against any actual
1873 * The search returns a group of mapping-contiguous page cache entries
1874 * with ascending indexes. There may be holes in the indices due to
1875 * not-present pages.
1877 * Any shadow entries of evicted pages, or swap entries from
1878 * shmem/tmpfs, are included in the returned array.
1880 * Return: the number of pages and shadow entries which were found.
1882 unsigned find_get_entries(struct address_space *mapping,
1883 pgoff_t start, unsigned int nr_entries,
1884 struct page **entries, pgoff_t *indices)
1886 XA_STATE(xas, &mapping->i_pages, start);
1888 unsigned int ret = 0;
1894 xas_for_each(&xas, page, ULONG_MAX) {
1895 if (xas_retry(&xas, page))
1898 * A shadow entry of a recently evicted page, a swap
1899 * entry from shmem/tmpfs or a DAX entry. Return it
1900 * without attempting to raise page count.
1902 if (xa_is_value(page))
1905 if (!page_cache_get_speculative(page))
1908 /* Has the page moved or been split? */
1909 if (unlikely(page != xas_reload(&xas)))
1911 page = find_subpage(page, xas.xa_index);
1914 indices[ret] = xas.xa_index;
1915 entries[ret] = page;
1916 if (++ret == nr_entries)
1929 * find_get_pages_range - gang pagecache lookup
1930 * @mapping: The address_space to search
1931 * @start: The starting page index
1932 * @end: The final page index (inclusive)
1933 * @nr_pages: The maximum number of pages
1934 * @pages: Where the resulting pages are placed
1936 * find_get_pages_range() will search for and return a group of up to @nr_pages
1937 * pages in the mapping starting at index @start and up to index @end
1938 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
1939 * a reference against the returned pages.
1941 * The search returns a group of mapping-contiguous pages with ascending
1942 * indexes. There may be holes in the indices due to not-present pages.
1943 * We also update @start to index the next page for the traversal.
1945 * Return: the number of pages which were found. If this number is
1946 * smaller than @nr_pages, the end of specified range has been
1949 unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
1950 pgoff_t end, unsigned int nr_pages,
1951 struct page **pages)
1953 XA_STATE(xas, &mapping->i_pages, *start);
1957 if (unlikely(!nr_pages))
1961 xas_for_each(&xas, page, end) {
1962 if (xas_retry(&xas, page))
1964 /* Skip over shadow, swap and DAX entries */
1965 if (xa_is_value(page))
1968 if (!page_cache_get_speculative(page))
1971 /* Has the page moved or been split? */
1972 if (unlikely(page != xas_reload(&xas)))
1975 pages[ret] = find_subpage(page, xas.xa_index);
1976 if (++ret == nr_pages) {
1977 *start = xas.xa_index + 1;
1988 * We come here when there is no page beyond @end. We take care to not
1989 * overflow the index @start as it confuses some of the callers. This
1990 * breaks the iteration when there is a page at index -1 but that is
1991 * already broken anyway.
1993 if (end == (pgoff_t)-1)
1994 *start = (pgoff_t)-1;
2004 * find_get_pages_contig - gang contiguous pagecache lookup
2005 * @mapping: The address_space to search
2006 * @index: The starting page index
2007 * @nr_pages: The maximum number of pages
2008 * @pages: Where the resulting pages are placed
2010 * find_get_pages_contig() works exactly like find_get_pages(), except
2011 * that the returned number of pages are guaranteed to be contiguous.
2013 * Return: the number of pages which were found.
2015 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
2016 unsigned int nr_pages, struct page **pages)
2018 XA_STATE(xas, &mapping->i_pages, index);
2020 unsigned int ret = 0;
2022 if (unlikely(!nr_pages))
2026 for (page = xas_load(&xas); page; page = xas_next(&xas)) {
2027 if (xas_retry(&xas, page))
2030 * If the entry has been swapped out, we can stop looking.
2031 * No current caller is looking for DAX entries.
2033 if (xa_is_value(page))
2036 if (!page_cache_get_speculative(page))
2039 /* Has the page moved or been split? */
2040 if (unlikely(page != xas_reload(&xas)))
2043 pages[ret] = find_subpage(page, xas.xa_index);
2044 if (++ret == nr_pages)
2055 EXPORT_SYMBOL(find_get_pages_contig);
2058 * find_get_pages_range_tag - find and return pages in given range matching @tag
2059 * @mapping: the address_space to search
2060 * @index: the starting page index
2061 * @end: The final page index (inclusive)
2062 * @tag: the tag index
2063 * @nr_pages: the maximum number of pages
2064 * @pages: where the resulting pages are placed
2066 * Like find_get_pages, except we only return pages which are tagged with
2067 * @tag. We update @index to index the next page for the traversal.
2069 * Return: the number of pages which were found.
2071 unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
2072 pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
2073 struct page **pages)
2075 XA_STATE(xas, &mapping->i_pages, *index);
2079 if (unlikely(!nr_pages))
2083 xas_for_each_marked(&xas, page, end, tag) {
2084 if (xas_retry(&xas, page))
2087 * Shadow entries should never be tagged, but this iteration
2088 * is lockless so there is a window for page reclaim to evict
2089 * a page we saw tagged. Skip over it.
2091 if (xa_is_value(page))
2094 if (!page_cache_get_speculative(page))
2097 /* Has the page moved or been split? */
2098 if (unlikely(page != xas_reload(&xas)))
2101 pages[ret] = find_subpage(page, xas.xa_index);
2102 if (++ret == nr_pages) {
2103 *index = xas.xa_index + 1;
2114 * We come here when we got to @end. We take care to not overflow the
2115 * index @index as it confuses some of the callers. This breaks the
2116 * iteration when there is a page at index -1 but that is already
2119 if (end == (pgoff_t)-1)
2120 *index = (pgoff_t)-1;
2128 EXPORT_SYMBOL(find_get_pages_range_tag);
2131 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
2132 * a _large_ part of the i/o request. Imagine the worst scenario:
2134 * ---R__________________________________________B__________
2135 * ^ reading here ^ bad block(assume 4k)
2137 * read(R) => miss => readahead(R...B) => media error => frustrating retries
2138 * => failing the whole request => read(R) => read(R+1) =>
2139 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
2140 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
2141 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
2143 * It is going insane. Fix it by quickly scaling down the readahead size.
2145 static void shrink_readahead_size_eio(struct file *filp,
2146 struct file_ra_state *ra)
2152 * generic_file_buffered_read - generic file read routine
2153 * @iocb: the iocb to read
2154 * @iter: data destination
2155 * @written: already copied
2157 * This is a generic file read routine, and uses the
2158 * mapping->a_ops->readpage() function for the actual low-level stuff.
2160 * This is really ugly. But the goto's actually try to clarify some
2161 * of the logic when it comes to error handling etc.
2164 * * total number of bytes copied, including those the were already @written
2165 * * negative error code if nothing was copied
2167 static ssize_t generic_file_buffered_read(struct kiocb *iocb,
2168 struct iov_iter *iter, ssize_t written)
2170 struct file *filp = iocb->ki_filp;
2171 struct address_space *mapping = filp->f_mapping;
2172 struct inode *inode = mapping->host;
2173 struct file_ra_state *ra = &filp->f_ra;
2174 loff_t *ppos = &iocb->ki_pos;
2178 unsigned long offset; /* offset into pagecache page */
2179 unsigned int prev_offset;
2182 if (unlikely(*ppos >= inode->i_sb->s_maxbytes))
2184 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2186 index = *ppos >> PAGE_SHIFT;
2187 prev_index = ra->prev_pos >> PAGE_SHIFT;
2188 prev_offset = ra->prev_pos & (PAGE_SIZE-1);
2189 last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
2190 offset = *ppos & ~PAGE_MASK;
2196 unsigned long nr, ret;
2200 if (fatal_signal_pending(current)) {
2205 page = find_get_page(mapping, index);
2207 if (iocb->ki_flags & IOCB_NOWAIT)
2209 page_cache_sync_readahead(mapping,
2211 index, last_index - index);
2212 page = find_get_page(mapping, index);
2213 if (unlikely(page == NULL))
2214 goto no_cached_page;
2216 if (PageReadahead(page)) {
2217 page_cache_async_readahead(mapping,
2219 index, last_index - index);
2221 if (!PageUptodate(page)) {
2222 if (iocb->ki_flags & IOCB_NOWAIT) {
2228 * See comment in do_read_cache_page on why
2229 * wait_on_page_locked is used to avoid unnecessarily
2230 * serialisations and why it's safe.
2232 error = wait_on_page_locked_killable(page);
2233 if (unlikely(error))
2234 goto readpage_error;
2235 if (PageUptodate(page))
2238 if (inode->i_blkbits == PAGE_SHIFT ||
2239 !mapping->a_ops->is_partially_uptodate)
2240 goto page_not_up_to_date;
2241 /* pipes can't handle partially uptodate pages */
2242 if (unlikely(iov_iter_is_pipe(iter)))
2243 goto page_not_up_to_date;
2244 if (!trylock_page(page))
2245 goto page_not_up_to_date;
2246 /* Did it get truncated before we got the lock? */
2248 goto page_not_up_to_date_locked;
2249 if (!mapping->a_ops->is_partially_uptodate(page,
2250 offset, iter->count))
2251 goto page_not_up_to_date_locked;
2256 * i_size must be checked after we know the page is Uptodate.
2258 * Checking i_size after the check allows us to calculate
2259 * the correct value for "nr", which means the zero-filled
2260 * part of the page is not copied back to userspace (unless
2261 * another truncate extends the file - this is desired though).
2264 isize = i_size_read(inode);
2265 end_index = (isize - 1) >> PAGE_SHIFT;
2266 if (unlikely(!isize || index > end_index)) {
2271 /* nr is the maximum number of bytes to copy from this page */
2273 if (index == end_index) {
2274 nr = ((isize - 1) & ~PAGE_MASK) + 1;
2282 /* If users can be writing to this page using arbitrary
2283 * virtual addresses, take care about potential aliasing
2284 * before reading the page on the kernel side.
2286 if (mapping_writably_mapped(mapping))
2287 flush_dcache_page(page);
2290 * When a sequential read accesses a page several times,
2291 * only mark it as accessed the first time.
2293 if (prev_index != index || offset != prev_offset)
2294 mark_page_accessed(page);
2298 * Ok, we have the page, and it's up-to-date, so
2299 * now we can copy it to user space...
2302 ret = copy_page_to_iter(page, offset, nr, iter);
2304 index += offset >> PAGE_SHIFT;
2305 offset &= ~PAGE_MASK;
2306 prev_offset = offset;
2310 if (!iov_iter_count(iter))
2318 page_not_up_to_date:
2319 /* Get exclusive access to the page ... */
2320 error = lock_page_killable(page);
2321 if (unlikely(error))
2322 goto readpage_error;
2324 page_not_up_to_date_locked:
2325 /* Did it get truncated before we got the lock? */
2326 if (!page->mapping) {
2332 /* Did somebody else fill it already? */
2333 if (PageUptodate(page)) {
2340 * A previous I/O error may have been due to temporary
2341 * failures, eg. multipath errors.
2342 * PG_error will be set again if readpage fails.
2344 ClearPageError(page);
2345 /* Start the actual read. The read will unlock the page. */
2346 error = mapping->a_ops->readpage(filp, page);
2348 if (unlikely(error)) {
2349 if (error == AOP_TRUNCATED_PAGE) {
2354 goto readpage_error;
2357 if (!PageUptodate(page)) {
2358 error = lock_page_killable(page);
2359 if (unlikely(error))
2360 goto readpage_error;
2361 if (!PageUptodate(page)) {
2362 if (page->mapping == NULL) {
2364 * invalidate_mapping_pages got it
2371 shrink_readahead_size_eio(filp, ra);
2373 goto readpage_error;
2381 /* UHHUH! A synchronous read error occurred. Report it */
2387 * Ok, it wasn't cached, so we need to create a new
2390 page = page_cache_alloc(mapping);
2395 error = add_to_page_cache_lru(page, mapping, index,
2396 mapping_gfp_constraint(mapping, GFP_KERNEL));
2399 if (error == -EEXIST) {
2411 ra->prev_pos = prev_index;
2412 ra->prev_pos <<= PAGE_SHIFT;
2413 ra->prev_pos |= prev_offset;
2415 *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
2416 file_accessed(filp);
2417 return written ? written : error;
2421 * generic_file_read_iter - generic filesystem read routine
2422 * @iocb: kernel I/O control block
2423 * @iter: destination for the data read
2425 * This is the "read_iter()" routine for all filesystems
2426 * that can use the page cache directly.
2428 * * number of bytes copied, even for partial reads
2429 * * negative error code if nothing was read
2432 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2434 size_t count = iov_iter_count(iter);
2438 goto out; /* skip atime */
2440 if (iocb->ki_flags & IOCB_DIRECT) {
2441 struct file *file = iocb->ki_filp;
2442 struct address_space *mapping = file->f_mapping;
2443 struct inode *inode = mapping->host;
2446 size = i_size_read(inode);
2447 if (iocb->ki_flags & IOCB_NOWAIT) {
2448 if (filemap_range_has_page(mapping, iocb->ki_pos,
2449 iocb->ki_pos + count - 1))
2452 retval = filemap_write_and_wait_range(mapping,
2454 iocb->ki_pos + count - 1);
2459 file_accessed(file);
2461 retval = mapping->a_ops->direct_IO(iocb, iter);
2463 iocb->ki_pos += retval;
2466 iov_iter_revert(iter, count - iov_iter_count(iter));
2469 * Btrfs can have a short DIO read if we encounter
2470 * compressed extents, so if there was an error, or if
2471 * we've already read everything we wanted to, or if
2472 * there was a short read because we hit EOF, go ahead
2473 * and return. Otherwise fallthrough to buffered io for
2474 * the rest of the read. Buffered reads will not work for
2475 * DAX files, so don't bother trying.
2477 if (retval < 0 || !count || iocb->ki_pos >= size ||
2482 retval = generic_file_buffered_read(iocb, iter, retval);
2486 EXPORT_SYMBOL(generic_file_read_iter);
2489 #define MMAP_LOTSAMISS (100)
2491 * lock_page_maybe_drop_mmap - lock the page, possibly dropping the mmap_sem
2492 * @vmf - the vm_fault for this fault.
2493 * @page - the page to lock.
2494 * @fpin - the pointer to the file we may pin (or is already pinned).
2496 * This works similar to lock_page_or_retry in that it can drop the mmap_sem.
2497 * It differs in that it actually returns the page locked if it returns 1 and 0
2498 * if it couldn't lock the page. If we did have to drop the mmap_sem then fpin
2499 * will point to the pinned file and needs to be fput()'ed at a later point.
2501 static int lock_page_maybe_drop_mmap(struct vm_fault *vmf, struct page *page,
2504 if (trylock_page(page))
2508 * NOTE! This will make us return with VM_FAULT_RETRY, but with
2509 * the mmap_sem still held. That's how FAULT_FLAG_RETRY_NOWAIT
2510 * is supposed to work. We have way too many special cases..
2512 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2515 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2516 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2517 if (__lock_page_killable(page)) {
2519 * We didn't have the right flags to drop the mmap_sem,
2520 * but all fault_handlers only check for fatal signals
2521 * if we return VM_FAULT_RETRY, so we need to drop the
2522 * mmap_sem here and return 0 if we don't have a fpin.
2525 up_read(&vmf->vma->vm_mm->mmap_sem);
2535 * Synchronous readahead happens when we don't even find a page in the page
2536 * cache at all. We don't want to perform IO under the mmap sem, so if we have
2537 * to drop the mmap sem we return the file that was pinned in order for us to do
2538 * that. If we didn't pin a file then we return NULL. The file that is
2539 * returned needs to be fput()'ed when we're done with it.
2541 static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
2543 struct file *file = vmf->vma->vm_file;
2544 struct file_ra_state *ra = &file->f_ra;
2545 struct address_space *mapping = file->f_mapping;
2546 struct file *fpin = NULL;
2547 pgoff_t offset = vmf->pgoff;
2549 /* If we don't want any read-ahead, don't bother */
2550 if (vmf->vma->vm_flags & VM_RAND_READ)
2555 if (vmf->vma->vm_flags & VM_SEQ_READ) {
2556 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2557 page_cache_sync_readahead(mapping, ra, file, offset,
2562 /* Avoid banging the cache line if not needed */
2563 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
2567 * Do we miss much more than hit in this file? If so,
2568 * stop bothering with read-ahead. It will only hurt.
2570 if (ra->mmap_miss > MMAP_LOTSAMISS)
2576 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2577 ra->start = max_t(long, 0, offset - ra->ra_pages / 2);
2578 ra->size = ra->ra_pages;
2579 ra->async_size = ra->ra_pages / 4;
2580 ra_submit(ra, mapping, file);
2585 * Asynchronous readahead happens when we find the page and PG_readahead,
2586 * so we want to possibly extend the readahead further. We return the file that
2587 * was pinned if we have to drop the mmap_sem in order to do IO.
2589 static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2592 struct file *file = vmf->vma->vm_file;
2593 struct file_ra_state *ra = &file->f_ra;
2594 struct address_space *mapping = file->f_mapping;
2595 struct file *fpin = NULL;
2596 pgoff_t offset = vmf->pgoff;
2598 /* If we don't want any read-ahead, don't bother */
2599 if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
2601 if (ra->mmap_miss > 0)
2603 if (PageReadahead(page)) {
2604 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2605 page_cache_async_readahead(mapping, ra, file,
2606 page, offset, ra->ra_pages);
2612 * filemap_fault - read in file data for page fault handling
2613 * @vmf: struct vm_fault containing details of the fault
2615 * filemap_fault() is invoked via the vma operations vector for a
2616 * mapped memory region to read in file data during a page fault.
2618 * The goto's are kind of ugly, but this streamlines the normal case of having
2619 * it in the page cache, and handles the special cases reasonably without
2620 * having a lot of duplicated code.
2622 * vma->vm_mm->mmap_sem must be held on entry.
2624 * If our return value has VM_FAULT_RETRY set, it's because the mmap_sem
2625 * may be dropped before doing I/O or by lock_page_maybe_drop_mmap().
2627 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
2628 * has not been released.
2630 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
2632 * Return: bitwise-OR of %VM_FAULT_ codes.
2634 vm_fault_t filemap_fault(struct vm_fault *vmf)
2637 struct file *file = vmf->vma->vm_file;
2638 struct file *fpin = NULL;
2639 struct address_space *mapping = file->f_mapping;
2640 struct file_ra_state *ra = &file->f_ra;
2641 struct inode *inode = mapping->host;
2642 pgoff_t offset = vmf->pgoff;
2647 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2648 if (unlikely(offset >= max_off))
2649 return VM_FAULT_SIGBUS;
2652 * Do we have something in the page cache already?
2654 page = find_get_page(mapping, offset);
2655 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
2657 * We found the page, so try async readahead before
2658 * waiting for the lock.
2660 fpin = do_async_mmap_readahead(vmf, page);
2662 /* No page in the page cache at all */
2663 count_vm_event(PGMAJFAULT);
2664 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
2665 ret = VM_FAULT_MAJOR;
2666 fpin = do_sync_mmap_readahead(vmf);
2668 page = pagecache_get_page(mapping, offset,
2669 FGP_CREAT|FGP_FOR_MMAP,
2674 return vmf_error(-ENOMEM);
2678 if (!lock_page_maybe_drop_mmap(vmf, page, &fpin))
2681 /* Did it get truncated? */
2682 if (unlikely(compound_head(page)->mapping != mapping)) {
2687 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
2690 * We have a locked page in the page cache, now we need to check
2691 * that it's up-to-date. If not, it is going to be due to an error.
2693 if (unlikely(!PageUptodate(page)))
2694 goto page_not_uptodate;
2697 * We've made it this far and we had to drop our mmap_sem, now is the
2698 * time to return to the upper layer and have it re-find the vma and
2707 * Found the page and have a reference on it.
2708 * We must recheck i_size under page lock.
2710 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2711 if (unlikely(offset >= max_off)) {
2714 return VM_FAULT_SIGBUS;
2718 return ret | VM_FAULT_LOCKED;
2722 * Umm, take care of errors if the page isn't up-to-date.
2723 * Try to re-read it _once_. We do this synchronously,
2724 * because there really aren't any performance issues here
2725 * and we need to check for errors.
2727 ClearPageError(page);
2728 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2729 error = mapping->a_ops->readpage(file, page);
2731 wait_on_page_locked(page);
2732 if (!PageUptodate(page))
2739 if (!error || error == AOP_TRUNCATED_PAGE)
2742 /* Things didn't work out. Return zero to tell the mm layer so. */
2743 shrink_readahead_size_eio(file, ra);
2744 return VM_FAULT_SIGBUS;
2748 * We dropped the mmap_sem, we need to return to the fault handler to
2749 * re-find the vma and come back and find our hopefully still populated
2756 return ret | VM_FAULT_RETRY;
2758 EXPORT_SYMBOL(filemap_fault);
2760 void filemap_map_pages(struct vm_fault *vmf,
2761 pgoff_t start_pgoff, pgoff_t end_pgoff)
2763 struct file *file = vmf->vma->vm_file;
2764 struct address_space *mapping = file->f_mapping;
2765 pgoff_t last_pgoff = start_pgoff;
2766 unsigned long max_idx;
2767 XA_STATE(xas, &mapping->i_pages, start_pgoff);
2771 xas_for_each(&xas, page, end_pgoff) {
2772 if (xas_retry(&xas, page))
2774 if (xa_is_value(page))
2778 * Check for a locked page first, as a speculative
2779 * reference may adversely influence page migration.
2781 if (PageLocked(page))
2783 if (!page_cache_get_speculative(page))
2786 /* Has the page moved or been split? */
2787 if (unlikely(page != xas_reload(&xas)))
2789 page = find_subpage(page, xas.xa_index);
2791 if (!PageUptodate(page) ||
2792 PageReadahead(page) ||
2795 if (!trylock_page(page))
2798 if (page->mapping != mapping || !PageUptodate(page))
2801 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2802 if (page->index >= max_idx)
2805 if (file->f_ra.mmap_miss > 0)
2806 file->f_ra.mmap_miss--;
2808 vmf->address += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
2810 vmf->pte += xas.xa_index - last_pgoff;
2811 last_pgoff = xas.xa_index;
2812 if (alloc_set_pte(vmf, NULL, page))
2821 /* Huge page is mapped? No need to proceed. */
2822 if (pmd_trans_huge(*vmf->pmd))
2827 EXPORT_SYMBOL(filemap_map_pages);
2829 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
2831 struct page *page = vmf->page;
2832 struct inode *inode = file_inode(vmf->vma->vm_file);
2833 vm_fault_t ret = VM_FAULT_LOCKED;
2835 sb_start_pagefault(inode->i_sb);
2836 file_update_time(vmf->vma->vm_file);
2838 if (page->mapping != inode->i_mapping) {
2840 ret = VM_FAULT_NOPAGE;
2844 * We mark the page dirty already here so that when freeze is in
2845 * progress, we are guaranteed that writeback during freezing will
2846 * see the dirty page and writeprotect it again.
2848 set_page_dirty(page);
2849 wait_for_stable_page(page);
2851 sb_end_pagefault(inode->i_sb);
2855 const struct vm_operations_struct generic_file_vm_ops = {
2856 .fault = filemap_fault,
2857 .map_pages = filemap_map_pages,
2858 .page_mkwrite = filemap_page_mkwrite,
2861 /* This is used for a general mmap of a disk file */
2863 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2865 struct address_space *mapping = file->f_mapping;
2867 if (!mapping->a_ops->readpage)
2869 file_accessed(file);
2870 vma->vm_ops = &generic_file_vm_ops;
2875 * This is for filesystems which do not implement ->writepage.
2877 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2879 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2881 return generic_file_mmap(file, vma);
2884 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
2886 return VM_FAULT_SIGBUS;
2888 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2892 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2896 #endif /* CONFIG_MMU */
2898 EXPORT_SYMBOL(filemap_page_mkwrite);
2899 EXPORT_SYMBOL(generic_file_mmap);
2900 EXPORT_SYMBOL(generic_file_readonly_mmap);
2902 static struct page *wait_on_page_read(struct page *page)
2904 if (!IS_ERR(page)) {
2905 wait_on_page_locked(page);
2906 if (!PageUptodate(page)) {
2908 page = ERR_PTR(-EIO);
2914 static struct page *do_read_cache_page(struct address_space *mapping,
2916 int (*filler)(void *, struct page *),
2923 page = find_get_page(mapping, index);
2925 page = __page_cache_alloc(gfp);
2927 return ERR_PTR(-ENOMEM);
2928 err = add_to_page_cache_lru(page, mapping, index, gfp);
2929 if (unlikely(err)) {
2933 /* Presumably ENOMEM for xarray node */
2934 return ERR_PTR(err);
2939 err = filler(data, page);
2941 err = mapping->a_ops->readpage(data, page);
2945 return ERR_PTR(err);
2948 page = wait_on_page_read(page);
2953 if (PageUptodate(page))
2957 * Page is not up to date and may be locked due one of the following
2958 * case a: Page is being filled and the page lock is held
2959 * case b: Read/write error clearing the page uptodate status
2960 * case c: Truncation in progress (page locked)
2961 * case d: Reclaim in progress
2963 * Case a, the page will be up to date when the page is unlocked.
2964 * There is no need to serialise on the page lock here as the page
2965 * is pinned so the lock gives no additional protection. Even if the
2966 * the page is truncated, the data is still valid if PageUptodate as
2967 * it's a race vs truncate race.
2968 * Case b, the page will not be up to date
2969 * Case c, the page may be truncated but in itself, the data may still
2970 * be valid after IO completes as it's a read vs truncate race. The
2971 * operation must restart if the page is not uptodate on unlock but
2972 * otherwise serialising on page lock to stabilise the mapping gives
2973 * no additional guarantees to the caller as the page lock is
2974 * released before return.
2975 * Case d, similar to truncation. If reclaim holds the page lock, it
2976 * will be a race with remove_mapping that determines if the mapping
2977 * is valid on unlock but otherwise the data is valid and there is
2978 * no need to serialise with page lock.
2980 * As the page lock gives no additional guarantee, we optimistically
2981 * wait on the page to be unlocked and check if it's up to date and
2982 * use the page if it is. Otherwise, the page lock is required to
2983 * distinguish between the different cases. The motivation is that we
2984 * avoid spurious serialisations and wakeups when multiple processes
2985 * wait on the same page for IO to complete.
2987 wait_on_page_locked(page);
2988 if (PageUptodate(page))
2991 /* Distinguish between all the cases under the safety of the lock */
2994 /* Case c or d, restart the operation */
2995 if (!page->mapping) {
3001 /* Someone else locked and filled the page in a very small window */
3002 if (PageUptodate(page)) {
3008 * A previous I/O error may have been due to temporary
3010 * Clear page error before actual read, PG_error will be
3011 * set again if read page fails.
3013 ClearPageError(page);
3017 mark_page_accessed(page);
3022 * read_cache_page - read into page cache, fill it if needed
3023 * @mapping: the page's address_space
3024 * @index: the page index
3025 * @filler: function to perform the read
3026 * @data: first arg to filler(data, page) function, often left as NULL
3028 * Read into the page cache. If a page already exists, and PageUptodate() is
3029 * not set, try to fill the page and wait for it to become unlocked.
3031 * If the page does not get brought uptodate, return -EIO.
3033 * Return: up to date page on success, ERR_PTR() on failure.
3035 struct page *read_cache_page(struct address_space *mapping,
3037 int (*filler)(void *, struct page *),
3040 return do_read_cache_page(mapping, index, filler, data,
3041 mapping_gfp_mask(mapping));
3043 EXPORT_SYMBOL(read_cache_page);
3046 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
3047 * @mapping: the page's address_space
3048 * @index: the page index
3049 * @gfp: the page allocator flags to use if allocating
3051 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
3052 * any new page allocations done using the specified allocation flags.
3054 * If the page does not get brought uptodate, return -EIO.
3056 * Return: up to date page on success, ERR_PTR() on failure.
3058 struct page *read_cache_page_gfp(struct address_space *mapping,
3062 return do_read_cache_page(mapping, index, NULL, NULL, gfp);
3064 EXPORT_SYMBOL(read_cache_page_gfp);
3067 * Don't operate on ranges the page cache doesn't support, and don't exceed the
3068 * LFS limits. If pos is under the limit it becomes a short access. If it
3069 * exceeds the limit we return -EFBIG.
3071 static int generic_write_check_limits(struct file *file, loff_t pos,
3074 struct inode *inode = file->f_mapping->host;
3075 loff_t max_size = inode->i_sb->s_maxbytes;
3076 loff_t limit = rlimit(RLIMIT_FSIZE);
3078 if (limit != RLIM_INFINITY) {
3080 send_sig(SIGXFSZ, current, 0);
3083 *count = min(*count, limit - pos);
3086 if (!(file->f_flags & O_LARGEFILE))
3087 max_size = MAX_NON_LFS;
3089 if (unlikely(pos >= max_size))
3092 *count = min(*count, max_size - pos);
3098 * Performs necessary checks before doing a write
3100 * Can adjust writing position or amount of bytes to write.
3101 * Returns appropriate error code that caller should return or
3102 * zero in case that write should be allowed.
3104 inline ssize_t generic_write_checks(struct kiocb *iocb, struct iov_iter *from)
3106 struct file *file = iocb->ki_filp;
3107 struct inode *inode = file->f_mapping->host;
3111 if (IS_SWAPFILE(inode))
3114 if (!iov_iter_count(from))
3117 /* FIXME: this is for backwards compatibility with 2.4 */
3118 if (iocb->ki_flags & IOCB_APPEND)
3119 iocb->ki_pos = i_size_read(inode);
3121 if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT))
3124 count = iov_iter_count(from);
3125 ret = generic_write_check_limits(file, iocb->ki_pos, &count);
3129 iov_iter_truncate(from, count);
3130 return iov_iter_count(from);
3132 EXPORT_SYMBOL(generic_write_checks);
3135 * Performs necessary checks before doing a clone.
3137 * Can adjust amount of bytes to clone via @req_count argument.
3138 * Returns appropriate error code that caller should return or
3139 * zero in case the clone should be allowed.
3141 int generic_remap_checks(struct file *file_in, loff_t pos_in,
3142 struct file *file_out, loff_t pos_out,
3143 loff_t *req_count, unsigned int remap_flags)
3145 struct inode *inode_in = file_in->f_mapping->host;
3146 struct inode *inode_out = file_out->f_mapping->host;
3147 uint64_t count = *req_count;
3149 loff_t size_in, size_out;
3150 loff_t bs = inode_out->i_sb->s_blocksize;
3153 /* The start of both ranges must be aligned to an fs block. */
3154 if (!IS_ALIGNED(pos_in, bs) || !IS_ALIGNED(pos_out, bs))
3157 /* Ensure offsets don't wrap. */
3158 if (pos_in + count < pos_in || pos_out + count < pos_out)
3161 size_in = i_size_read(inode_in);
3162 size_out = i_size_read(inode_out);
3164 /* Dedupe requires both ranges to be within EOF. */
3165 if ((remap_flags & REMAP_FILE_DEDUP) &&
3166 (pos_in >= size_in || pos_in + count > size_in ||
3167 pos_out >= size_out || pos_out + count > size_out))
3170 /* Ensure the infile range is within the infile. */
3171 if (pos_in >= size_in)
3173 count = min(count, size_in - (uint64_t)pos_in);
3175 ret = generic_write_check_limits(file_out, pos_out, &count);
3180 * If the user wanted us to link to the infile's EOF, round up to the
3181 * next block boundary for this check.
3183 * Otherwise, make sure the count is also block-aligned, having
3184 * already confirmed the starting offsets' block alignment.
3186 if (pos_in + count == size_in) {
3187 bcount = ALIGN(size_in, bs) - pos_in;
3189 if (!IS_ALIGNED(count, bs))
3190 count = ALIGN_DOWN(count, bs);
3194 /* Don't allow overlapped cloning within the same file. */
3195 if (inode_in == inode_out &&
3196 pos_out + bcount > pos_in &&
3197 pos_out < pos_in + bcount)
3201 * We shortened the request but the caller can't deal with that, so
3202 * bounce the request back to userspace.
3204 if (*req_count != count && !(remap_flags & REMAP_FILE_CAN_SHORTEN))
3213 * Performs common checks before doing a file copy/clone
3214 * from @file_in to @file_out.
3216 int generic_file_rw_checks(struct file *file_in, struct file *file_out)
3218 struct inode *inode_in = file_inode(file_in);
3219 struct inode *inode_out = file_inode(file_out);
3221 /* Don't copy dirs, pipes, sockets... */
3222 if (S_ISDIR(inode_in->i_mode) || S_ISDIR(inode_out->i_mode))
3224 if (!S_ISREG(inode_in->i_mode) || !S_ISREG(inode_out->i_mode))
3227 if (!(file_in->f_mode & FMODE_READ) ||
3228 !(file_out->f_mode & FMODE_WRITE) ||
3229 (file_out->f_flags & O_APPEND))
3236 * Performs necessary checks before doing a file copy
3238 * Can adjust amount of bytes to copy via @req_count argument.
3239 * Returns appropriate error code that caller should return or
3240 * zero in case the copy should be allowed.
3242 int generic_copy_file_checks(struct file *file_in, loff_t pos_in,
3243 struct file *file_out, loff_t pos_out,
3244 size_t *req_count, unsigned int flags)
3246 struct inode *inode_in = file_inode(file_in);
3247 struct inode *inode_out = file_inode(file_out);
3248 uint64_t count = *req_count;
3252 ret = generic_file_rw_checks(file_in, file_out);
3256 /* Don't touch certain kinds of inodes */
3257 if (IS_IMMUTABLE(inode_out))
3260 if (IS_SWAPFILE(inode_in) || IS_SWAPFILE(inode_out))
3263 /* Ensure offsets don't wrap. */
3264 if (pos_in + count < pos_in || pos_out + count < pos_out)
3267 /* Shorten the copy to EOF */
3268 size_in = i_size_read(inode_in);
3269 if (pos_in >= size_in)
3272 count = min(count, size_in - (uint64_t)pos_in);
3274 ret = generic_write_check_limits(file_out, pos_out, &count);
3278 /* Don't allow overlapped copying within the same file. */
3279 if (inode_in == inode_out &&
3280 pos_out + count > pos_in &&
3281 pos_out < pos_in + count)
3288 int pagecache_write_begin(struct file *file, struct address_space *mapping,
3289 loff_t pos, unsigned len, unsigned flags,
3290 struct page **pagep, void **fsdata)
3292 const struct address_space_operations *aops = mapping->a_ops;
3294 return aops->write_begin(file, mapping, pos, len, flags,
3297 EXPORT_SYMBOL(pagecache_write_begin);
3299 int pagecache_write_end(struct file *file, struct address_space *mapping,
3300 loff_t pos, unsigned len, unsigned copied,
3301 struct page *page, void *fsdata)
3303 const struct address_space_operations *aops = mapping->a_ops;
3305 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
3307 EXPORT_SYMBOL(pagecache_write_end);
3310 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
3312 struct file *file = iocb->ki_filp;
3313 struct address_space *mapping = file->f_mapping;
3314 struct inode *inode = mapping->host;
3315 loff_t pos = iocb->ki_pos;
3320 write_len = iov_iter_count(from);
3321 end = (pos + write_len - 1) >> PAGE_SHIFT;
3323 if (iocb->ki_flags & IOCB_NOWAIT) {
3324 /* If there are pages to writeback, return */
3325 if (filemap_range_has_page(inode->i_mapping, pos,
3326 pos + write_len - 1))
3329 written = filemap_write_and_wait_range(mapping, pos,
3330 pos + write_len - 1);
3336 * After a write we want buffered reads to be sure to go to disk to get
3337 * the new data. We invalidate clean cached page from the region we're
3338 * about to write. We do this *before* the write so that we can return
3339 * without clobbering -EIOCBQUEUED from ->direct_IO().
3341 written = invalidate_inode_pages2_range(mapping,
3342 pos >> PAGE_SHIFT, end);
3344 * If a page can not be invalidated, return 0 to fall back
3345 * to buffered write.
3348 if (written == -EBUSY)
3353 written = mapping->a_ops->direct_IO(iocb, from);
3356 * Finally, try again to invalidate clean pages which might have been
3357 * cached by non-direct readahead, or faulted in by get_user_pages()
3358 * if the source of the write was an mmap'ed region of the file
3359 * we're writing. Either one is a pretty crazy thing to do,
3360 * so we don't support it 100%. If this invalidation
3361 * fails, tough, the write still worked...
3363 * Most of the time we do not need this since dio_complete() will do
3364 * the invalidation for us. However there are some file systems that
3365 * do not end up with dio_complete() being called, so let's not break
3366 * them by removing it completely
3368 if (mapping->nrpages)
3369 invalidate_inode_pages2_range(mapping,
3370 pos >> PAGE_SHIFT, end);
3374 write_len -= written;
3375 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3376 i_size_write(inode, pos);
3377 mark_inode_dirty(inode);
3381 iov_iter_revert(from, write_len - iov_iter_count(from));
3385 EXPORT_SYMBOL(generic_file_direct_write);
3388 * Find or create a page at the given pagecache position. Return the locked
3389 * page. This function is specifically for buffered writes.
3391 struct page *grab_cache_page_write_begin(struct address_space *mapping,
3392 pgoff_t index, unsigned flags)
3395 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
3397 if (flags & AOP_FLAG_NOFS)
3398 fgp_flags |= FGP_NOFS;
3400 page = pagecache_get_page(mapping, index, fgp_flags,
3401 mapping_gfp_mask(mapping));
3403 wait_for_stable_page(page);
3407 EXPORT_SYMBOL(grab_cache_page_write_begin);
3409 ssize_t generic_perform_write(struct file *file,
3410 struct iov_iter *i, loff_t pos)
3412 struct address_space *mapping = file->f_mapping;
3413 const struct address_space_operations *a_ops = mapping->a_ops;
3415 ssize_t written = 0;
3416 unsigned int flags = 0;
3420 unsigned long offset; /* Offset into pagecache page */
3421 unsigned long bytes; /* Bytes to write to page */
3422 size_t copied; /* Bytes copied from user */
3423 void *fsdata = NULL;
3425 offset = (pos & (PAGE_SIZE - 1));
3426 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3431 * Bring in the user page that we will copy from _first_.
3432 * Otherwise there's a nasty deadlock on copying from the
3433 * same page as we're writing to, without it being marked
3436 * Not only is this an optimisation, but it is also required
3437 * to check that the address is actually valid, when atomic
3438 * usercopies are used, below.
3440 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3445 if (fatal_signal_pending(current)) {
3450 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
3452 if (unlikely(status < 0))
3455 if (mapping_writably_mapped(mapping))
3456 flush_dcache_page(page);
3458 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
3459 flush_dcache_page(page);
3461 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3463 if (unlikely(status < 0))
3469 iov_iter_advance(i, copied);
3470 if (unlikely(copied == 0)) {
3472 * If we were unable to copy any data at all, we must
3473 * fall back to a single segment length write.
3475 * If we didn't fallback here, we could livelock
3476 * because not all segments in the iov can be copied at
3477 * once without a pagefault.
3479 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3480 iov_iter_single_seg_count(i));
3486 balance_dirty_pages_ratelimited(mapping);
3487 } while (iov_iter_count(i));
3489 return written ? written : status;
3491 EXPORT_SYMBOL(generic_perform_write);
3494 * __generic_file_write_iter - write data to a file
3495 * @iocb: IO state structure (file, offset, etc.)
3496 * @from: iov_iter with data to write
3498 * This function does all the work needed for actually writing data to a
3499 * file. It does all basic checks, removes SUID from the file, updates
3500 * modification times and calls proper subroutines depending on whether we
3501 * do direct IO or a standard buffered write.
3503 * It expects i_mutex to be grabbed unless we work on a block device or similar
3504 * object which does not need locking at all.
3506 * This function does *not* take care of syncing data in case of O_SYNC write.
3507 * A caller has to handle it. This is mainly due to the fact that we want to
3508 * avoid syncing under i_mutex.
3511 * * number of bytes written, even for truncated writes
3512 * * negative error code if no data has been written at all
3514 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3516 struct file *file = iocb->ki_filp;
3517 struct address_space * mapping = file->f_mapping;
3518 struct inode *inode = mapping->host;
3519 ssize_t written = 0;
3523 /* We can write back this queue in page reclaim */
3524 current->backing_dev_info = inode_to_bdi(inode);
3525 err = file_remove_privs(file);
3529 err = file_update_time(file);
3533 if (iocb->ki_flags & IOCB_DIRECT) {
3534 loff_t pos, endbyte;
3536 written = generic_file_direct_write(iocb, from);
3538 * If the write stopped short of completing, fall back to
3539 * buffered writes. Some filesystems do this for writes to
3540 * holes, for example. For DAX files, a buffered write will
3541 * not succeed (even if it did, DAX does not handle dirty
3542 * page-cache pages correctly).
3544 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
3547 status = generic_perform_write(file, from, pos = iocb->ki_pos);
3549 * If generic_perform_write() returned a synchronous error
3550 * then we want to return the number of bytes which were
3551 * direct-written, or the error code if that was zero. Note
3552 * that this differs from normal direct-io semantics, which
3553 * will return -EFOO even if some bytes were written.
3555 if (unlikely(status < 0)) {
3560 * We need to ensure that the page cache pages are written to
3561 * disk and invalidated to preserve the expected O_DIRECT
3564 endbyte = pos + status - 1;
3565 err = filemap_write_and_wait_range(mapping, pos, endbyte);
3567 iocb->ki_pos = endbyte + 1;
3569 invalidate_mapping_pages(mapping,
3571 endbyte >> PAGE_SHIFT);
3574 * We don't know how much we wrote, so just return
3575 * the number of bytes which were direct-written
3579 written = generic_perform_write(file, from, iocb->ki_pos);
3580 if (likely(written > 0))
3581 iocb->ki_pos += written;
3584 current->backing_dev_info = NULL;
3585 return written ? written : err;
3587 EXPORT_SYMBOL(__generic_file_write_iter);
3590 * generic_file_write_iter - write data to a file
3591 * @iocb: IO state structure
3592 * @from: iov_iter with data to write
3594 * This is a wrapper around __generic_file_write_iter() to be used by most
3595 * filesystems. It takes care of syncing the file in case of O_SYNC file
3596 * and acquires i_mutex as needed.
3598 * * negative error code if no data has been written at all of
3599 * vfs_fsync_range() failed for a synchronous write
3600 * * number of bytes written, even for truncated writes
3602 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3604 struct file *file = iocb->ki_filp;
3605 struct inode *inode = file->f_mapping->host;
3609 ret = generic_write_checks(iocb, from);
3611 ret = __generic_file_write_iter(iocb, from);
3612 inode_unlock(inode);
3615 ret = generic_write_sync(iocb, ret);
3618 EXPORT_SYMBOL(generic_file_write_iter);
3621 * try_to_release_page() - release old fs-specific metadata on a page
3623 * @page: the page which the kernel is trying to free
3624 * @gfp_mask: memory allocation flags (and I/O mode)
3626 * The address_space is to try to release any data against the page
3627 * (presumably at page->private).
3629 * This may also be called if PG_fscache is set on a page, indicating that the
3630 * page is known to the local caching routines.
3632 * The @gfp_mask argument specifies whether I/O may be performed to release
3633 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
3635 * Return: %1 if the release was successful, otherwise return zero.
3637 int try_to_release_page(struct page *page, gfp_t gfp_mask)
3639 struct address_space * const mapping = page->mapping;
3641 BUG_ON(!PageLocked(page));
3642 if (PageWriteback(page))
3645 if (mapping && mapping->a_ops->releasepage)
3646 return mapping->a_ops->releasepage(page, gfp_mask);
3647 return try_to_free_buffers(page);
3650 EXPORT_SYMBOL(try_to_release_page);