1 // SPDX-License-Identifier: GPL-2.0-only
5 * Copyright (C) 1994-1999 Linus Torvalds
9 * This file handles the generic file mmap semantics used by
10 * most "normal" filesystems (but you don't /have/ to use this:
11 * the NFS filesystem used to do this differently, for example)
13 #include <linux/export.h>
14 #include <linux/compiler.h>
15 #include <linux/dax.h>
17 #include <linux/sched/signal.h>
18 #include <linux/uaccess.h>
19 #include <linux/capability.h>
20 #include <linux/kernel_stat.h>
21 #include <linux/gfp.h>
23 #include <linux/swap.h>
24 #include <linux/mman.h>
25 #include <linux/pagemap.h>
26 #include <linux/file.h>
27 #include <linux/uio.h>
28 #include <linux/error-injection.h>
29 #include <linux/hash.h>
30 #include <linux/writeback.h>
31 #include <linux/backing-dev.h>
32 #include <linux/pagevec.h>
33 #include <linux/blkdev.h>
34 #include <linux/security.h>
35 #include <linux/cpuset.h>
36 #include <linux/hugetlb.h>
37 #include <linux/memcontrol.h>
38 #include <linux/cleancache.h>
39 #include <linux/shmem_fs.h>
40 #include <linux/rmap.h>
41 #include <linux/delayacct.h>
42 #include <linux/psi.h>
43 #include <linux/ramfs.h>
44 #include <linux/page_idle.h>
47 #define CREATE_TRACE_POINTS
48 #include <trace/events/filemap.h>
51 * FIXME: remove all knowledge of the buffer layer from the core VM
53 #include <linux/buffer_head.h> /* for try_to_free_buffers */
58 * Shared mappings implemented 30.11.1994. It's not fully working yet,
61 * Shared mappings now work. 15.8.1995 Bruno.
63 * finished 'unifying' the page and buffer cache and SMP-threaded the
64 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
66 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
72 * ->i_mmap_rwsem (truncate_pagecache)
73 * ->private_lock (__free_pte->__set_page_dirty_buffers)
74 * ->swap_lock (exclusive_swap_page, others)
78 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
82 * ->page_table_lock or pte_lock (various, mainly in memory.c)
83 * ->i_pages lock (arch-dependent flush_dcache_mmap_lock)
86 * ->lock_page (access_process_vm)
88 * ->i_mutex (generic_perform_write)
89 * ->mmap_lock (fault_in_pages_readable->do_page_fault)
92 * sb_lock (fs/fs-writeback.c)
93 * ->i_pages lock (__sync_single_inode)
96 * ->anon_vma.lock (vma_adjust)
99 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
101 * ->page_table_lock or pte_lock
102 * ->swap_lock (try_to_unmap_one)
103 * ->private_lock (try_to_unmap_one)
104 * ->i_pages lock (try_to_unmap_one)
105 * ->pgdat->lru_lock (follow_page->mark_page_accessed)
106 * ->pgdat->lru_lock (check_pte_range->isolate_lru_page)
107 * ->private_lock (page_remove_rmap->set_page_dirty)
108 * ->i_pages lock (page_remove_rmap->set_page_dirty)
109 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
110 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
111 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
112 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
113 * ->inode->i_lock (zap_pte_range->set_page_dirty)
114 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
117 * ->tasklist_lock (memory_failure, collect_procs_ao)
120 static void page_cache_delete(struct address_space *mapping,
121 struct page *page, void *shadow)
123 XA_STATE(xas, &mapping->i_pages, page->index);
126 mapping_set_update(&xas, mapping);
128 /* hugetlb pages are represented by a single entry in the xarray */
129 if (!PageHuge(page)) {
130 xas_set_order(&xas, page->index, compound_order(page));
131 nr = compound_nr(page);
134 VM_BUG_ON_PAGE(!PageLocked(page), page);
135 VM_BUG_ON_PAGE(PageTail(page), page);
136 VM_BUG_ON_PAGE(nr != 1 && shadow, page);
138 xas_store(&xas, shadow);
139 xas_init_marks(&xas);
141 page->mapping = NULL;
142 /* Leave page->index set: truncation lookup relies upon it */
145 mapping->nrexceptional += nr;
147 * Make sure the nrexceptional update is committed before
148 * the nrpages update so that final truncate racing
149 * with reclaim does not see both counters 0 at the
150 * same time and miss a shadow entry.
154 mapping->nrpages -= nr;
157 static void unaccount_page_cache_page(struct address_space *mapping,
163 * if we're uptodate, flush out into the cleancache, otherwise
164 * invalidate any existing cleancache entries. We can't leave
165 * stale data around in the cleancache once our page is gone
167 if (PageUptodate(page) && PageMappedToDisk(page))
168 cleancache_put_page(page);
170 cleancache_invalidate_page(mapping, page);
172 VM_BUG_ON_PAGE(PageTail(page), page);
173 VM_BUG_ON_PAGE(page_mapped(page), page);
174 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
177 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
178 current->comm, page_to_pfn(page));
179 dump_page(page, "still mapped when deleted");
181 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
183 mapcount = page_mapcount(page);
184 if (mapping_exiting(mapping) &&
185 page_count(page) >= mapcount + 2) {
187 * All vmas have already been torn down, so it's
188 * a good bet that actually the page is unmapped,
189 * and we'd prefer not to leak it: if we're wrong,
190 * some other bad page check should catch it later.
192 page_mapcount_reset(page);
193 page_ref_sub(page, mapcount);
197 /* hugetlb pages do not participate in page cache accounting. */
201 nr = thp_nr_pages(page);
203 __mod_lruvec_page_state(page, NR_FILE_PAGES, -nr);
204 if (PageSwapBacked(page)) {
205 __mod_lruvec_page_state(page, NR_SHMEM, -nr);
206 if (PageTransHuge(page)) {
207 #ifdef CONFIG_FINEGRAINED_THP
208 if (thp_nr_pages(page) == HPAGE_PMD_NR)
209 __dec_node_page_state(page, NR_SHMEM_THPS);
211 __dec_node_page_state(page, NR_SHMEM_64KB_THPS);
212 #else /* CONFIG_FINEGRAINED_THP */
213 __dec_node_page_state(page, NR_SHMEM_THPS);
214 #endif /* CONFIG_FINEGRAINED_THP */
216 } else if (PageTransHuge(page)) {
217 #ifdef CONFIG_FINEGRAINED_THP
218 if (thp_nr_pages(page) == HPAGE_PMD_NR)
219 __dec_node_page_state(page, NR_FILE_THPS);
221 __dec_node_page_state(page, NR_FILE_64KB_THPS);
222 #else /* CONFIG_FINEGRAINED_THP */
223 __dec_node_page_state(page, NR_FILE_THPS);
224 #endif /* CONFIG_FINEGRAINED_THP */
225 filemap_nr_thps_dec(mapping);
229 * At this point page must be either written or cleaned by
230 * truncate. Dirty page here signals a bug and loss of
233 * This fixes dirty accounting after removing the page entirely
234 * but leaves PageDirty set: it has no effect for truncated
235 * page and anyway will be cleared before returning page into
238 if (WARN_ON_ONCE(PageDirty(page)))
239 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
243 * Delete a page from the page cache and free it. Caller has to make
244 * sure the page is locked and that nobody else uses it - or that usage
245 * is safe. The caller must hold the i_pages lock.
247 void __delete_from_page_cache(struct page *page, void *shadow)
249 struct address_space *mapping = page->mapping;
251 trace_mm_filemap_delete_from_page_cache(page);
253 unaccount_page_cache_page(mapping, page);
254 page_cache_delete(mapping, page, shadow);
257 static void page_cache_free_page(struct address_space *mapping,
260 void (*freepage)(struct page *);
262 freepage = mapping->a_ops->freepage;
266 if (PageTransHuge(page) && !PageHuge(page)) {
267 page_ref_sub(page, thp_nr_pages(page));
268 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
275 * delete_from_page_cache - delete page from page cache
276 * @page: the page which the kernel is trying to remove from page cache
278 * This must be called only on pages that have been verified to be in the page
279 * cache and locked. It will never put the page into the free list, the caller
280 * has a reference on the page.
282 void delete_from_page_cache(struct page *page)
284 struct address_space *mapping = page_mapping(page);
287 BUG_ON(!PageLocked(page));
288 xa_lock_irqsave(&mapping->i_pages, flags);
289 __delete_from_page_cache(page, NULL);
290 xa_unlock_irqrestore(&mapping->i_pages, flags);
292 page_cache_free_page(mapping, page);
294 EXPORT_SYMBOL(delete_from_page_cache);
297 * page_cache_delete_batch - delete several pages from page cache
298 * @mapping: the mapping to which pages belong
299 * @pvec: pagevec with pages to delete
301 * The function walks over mapping->i_pages and removes pages passed in @pvec
302 * from the mapping. The function expects @pvec to be sorted by page index
303 * and is optimised for it to be dense.
304 * It tolerates holes in @pvec (mapping entries at those indices are not
305 * modified). The function expects only THP head pages to be present in the
308 * The function expects the i_pages lock to be held.
310 static void page_cache_delete_batch(struct address_space *mapping,
311 struct pagevec *pvec)
313 XA_STATE(xas, &mapping->i_pages, pvec->pages[0]->index);
318 mapping_set_update(&xas, mapping);
319 xas_for_each(&xas, page, ULONG_MAX) {
320 if (i >= pagevec_count(pvec))
323 /* A swap/dax/shadow entry got inserted? Skip it. */
324 if (xa_is_value(page))
327 * A page got inserted in our range? Skip it. We have our
328 * pages locked so they are protected from being removed.
329 * If we see a page whose index is higher than ours, it
330 * means our page has been removed, which shouldn't be
331 * possible because we're holding the PageLock.
333 if (page != pvec->pages[i]) {
334 VM_BUG_ON_PAGE(page->index > pvec->pages[i]->index,
339 WARN_ON_ONCE(!PageLocked(page));
341 if (page->index == xas.xa_index)
342 page->mapping = NULL;
343 /* Leave page->index set: truncation lookup relies on it */
346 * Move to the next page in the vector if this is a regular
347 * page or the index is of the last sub-page of this compound
350 if (page->index + compound_nr(page) - 1 == xas.xa_index)
352 xas_store(&xas, NULL);
355 mapping->nrpages -= total_pages;
358 void delete_from_page_cache_batch(struct address_space *mapping,
359 struct pagevec *pvec)
364 if (!pagevec_count(pvec))
367 xa_lock_irqsave(&mapping->i_pages, flags);
368 for (i = 0; i < pagevec_count(pvec); i++) {
369 trace_mm_filemap_delete_from_page_cache(pvec->pages[i]);
371 unaccount_page_cache_page(mapping, pvec->pages[i]);
373 page_cache_delete_batch(mapping, pvec);
374 xa_unlock_irqrestore(&mapping->i_pages, flags);
376 for (i = 0; i < pagevec_count(pvec); i++)
377 page_cache_free_page(mapping, pvec->pages[i]);
380 int filemap_check_errors(struct address_space *mapping)
383 /* Check for outstanding write errors */
384 if (test_bit(AS_ENOSPC, &mapping->flags) &&
385 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
387 if (test_bit(AS_EIO, &mapping->flags) &&
388 test_and_clear_bit(AS_EIO, &mapping->flags))
392 EXPORT_SYMBOL(filemap_check_errors);
394 static int filemap_check_and_keep_errors(struct address_space *mapping)
396 /* Check for outstanding write errors */
397 if (test_bit(AS_EIO, &mapping->flags))
399 if (test_bit(AS_ENOSPC, &mapping->flags))
405 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
406 * @mapping: address space structure to write
407 * @start: offset in bytes where the range starts
408 * @end: offset in bytes where the range ends (inclusive)
409 * @sync_mode: enable synchronous operation
411 * Start writeback against all of a mapping's dirty pages that lie
412 * within the byte offsets <start, end> inclusive.
414 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
415 * opposed to a regular memory cleansing writeback. The difference between
416 * these two operations is that if a dirty page/buffer is encountered, it must
417 * be waited upon, and not just skipped over.
419 * Return: %0 on success, negative error code otherwise.
421 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
422 loff_t end, int sync_mode)
425 struct writeback_control wbc = {
426 .sync_mode = sync_mode,
427 .nr_to_write = LONG_MAX,
428 .range_start = start,
432 if (!mapping_can_writeback(mapping) ||
433 !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
436 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
437 ret = do_writepages(mapping, &wbc);
438 wbc_detach_inode(&wbc);
442 static inline int __filemap_fdatawrite(struct address_space *mapping,
445 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
448 int filemap_fdatawrite(struct address_space *mapping)
450 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
452 EXPORT_SYMBOL(filemap_fdatawrite);
454 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
457 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
459 EXPORT_SYMBOL(filemap_fdatawrite_range);
462 * filemap_flush - mostly a non-blocking flush
463 * @mapping: target address_space
465 * This is a mostly non-blocking flush. Not suitable for data-integrity
466 * purposes - I/O may not be started against all dirty pages.
468 * Return: %0 on success, negative error code otherwise.
470 int filemap_flush(struct address_space *mapping)
472 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
474 EXPORT_SYMBOL(filemap_flush);
477 * filemap_range_has_page - check if a page exists in range.
478 * @mapping: address space within which to check
479 * @start_byte: offset in bytes where the range starts
480 * @end_byte: offset in bytes where the range ends (inclusive)
482 * Find at least one page in the range supplied, usually used to check if
483 * direct writing in this range will trigger a writeback.
485 * Return: %true if at least one page exists in the specified range,
488 bool filemap_range_has_page(struct address_space *mapping,
489 loff_t start_byte, loff_t end_byte)
492 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
493 pgoff_t max = end_byte >> PAGE_SHIFT;
495 if (end_byte < start_byte)
500 page = xas_find(&xas, max);
501 if (xas_retry(&xas, page))
503 /* Shadow entries don't count */
504 if (xa_is_value(page))
507 * We don't need to try to pin this page; we're about to
508 * release the RCU lock anyway. It is enough to know that
509 * there was a page here recently.
517 EXPORT_SYMBOL(filemap_range_has_page);
519 static void __filemap_fdatawait_range(struct address_space *mapping,
520 loff_t start_byte, loff_t end_byte)
522 pgoff_t index = start_byte >> PAGE_SHIFT;
523 pgoff_t end = end_byte >> PAGE_SHIFT;
527 if (end_byte < start_byte)
531 while (index <= end) {
534 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
535 end, PAGECACHE_TAG_WRITEBACK);
539 for (i = 0; i < nr_pages; i++) {
540 struct page *page = pvec.pages[i];
542 wait_on_page_writeback(page);
543 ClearPageError(page);
545 pagevec_release(&pvec);
551 * filemap_fdatawait_range - wait for writeback to complete
552 * @mapping: address space structure to wait for
553 * @start_byte: offset in bytes where the range starts
554 * @end_byte: offset in bytes where the range ends (inclusive)
556 * Walk the list of under-writeback pages of the given address space
557 * in the given range and wait for all of them. Check error status of
558 * the address space and return it.
560 * Since the error status of the address space is cleared by this function,
561 * callers are responsible for checking the return value and handling and/or
562 * reporting the error.
564 * Return: error status of the address space.
566 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
569 __filemap_fdatawait_range(mapping, start_byte, end_byte);
570 return filemap_check_errors(mapping);
572 EXPORT_SYMBOL(filemap_fdatawait_range);
575 * filemap_fdatawait_range_keep_errors - wait for writeback to complete
576 * @mapping: address space structure to wait for
577 * @start_byte: offset in bytes where the range starts
578 * @end_byte: offset in bytes where the range ends (inclusive)
580 * Walk the list of under-writeback pages of the given address space in the
581 * given range and wait for all of them. Unlike filemap_fdatawait_range(),
582 * this function does not clear error status of the address space.
584 * Use this function if callers don't handle errors themselves. Expected
585 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
588 int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
589 loff_t start_byte, loff_t end_byte)
591 __filemap_fdatawait_range(mapping, start_byte, end_byte);
592 return filemap_check_and_keep_errors(mapping);
594 EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
597 * file_fdatawait_range - wait for writeback to complete
598 * @file: file pointing to address space structure to wait for
599 * @start_byte: offset in bytes where the range starts
600 * @end_byte: offset in bytes where the range ends (inclusive)
602 * Walk the list of under-writeback pages of the address space that file
603 * refers to, in the given range and wait for all of them. Check error
604 * status of the address space vs. the file->f_wb_err cursor and return it.
606 * Since the error status of the file is advanced by this function,
607 * callers are responsible for checking the return value and handling and/or
608 * reporting the error.
610 * Return: error status of the address space vs. the file->f_wb_err cursor.
612 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
614 struct address_space *mapping = file->f_mapping;
616 __filemap_fdatawait_range(mapping, start_byte, end_byte);
617 return file_check_and_advance_wb_err(file);
619 EXPORT_SYMBOL(file_fdatawait_range);
622 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
623 * @mapping: address space structure to wait for
625 * Walk the list of under-writeback pages of the given address space
626 * and wait for all of them. Unlike filemap_fdatawait(), this function
627 * does not clear error status of the address space.
629 * Use this function if callers don't handle errors themselves. Expected
630 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
633 * Return: error status of the address space.
635 int filemap_fdatawait_keep_errors(struct address_space *mapping)
637 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
638 return filemap_check_and_keep_errors(mapping);
640 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
642 /* Returns true if writeback might be needed or already in progress. */
643 static bool mapping_needs_writeback(struct address_space *mapping)
645 if (dax_mapping(mapping))
646 return mapping->nrexceptional;
648 return mapping->nrpages;
652 * filemap_write_and_wait_range - write out & wait on a file range
653 * @mapping: the address_space for the pages
654 * @lstart: offset in bytes where the range starts
655 * @lend: offset in bytes where the range ends (inclusive)
657 * Write out and wait upon file offsets lstart->lend, inclusive.
659 * Note that @lend is inclusive (describes the last byte to be written) so
660 * that this function can be used to write to the very end-of-file (end = -1).
662 * Return: error status of the address space.
664 int filemap_write_and_wait_range(struct address_space *mapping,
665 loff_t lstart, loff_t lend)
669 if (mapping_needs_writeback(mapping)) {
670 err = __filemap_fdatawrite_range(mapping, lstart, lend,
673 * Even if the above returned error, the pages may be
674 * written partially (e.g. -ENOSPC), so we wait for it.
675 * But the -EIO is special case, it may indicate the worst
676 * thing (e.g. bug) happened, so we avoid waiting for it.
679 int err2 = filemap_fdatawait_range(mapping,
684 /* Clear any previously stored errors */
685 filemap_check_errors(mapping);
688 err = filemap_check_errors(mapping);
692 EXPORT_SYMBOL(filemap_write_and_wait_range);
694 void __filemap_set_wb_err(struct address_space *mapping, int err)
696 errseq_t eseq = errseq_set(&mapping->wb_err, err);
698 trace_filemap_set_wb_err(mapping, eseq);
700 EXPORT_SYMBOL(__filemap_set_wb_err);
703 * file_check_and_advance_wb_err - report wb error (if any) that was previously
704 * and advance wb_err to current one
705 * @file: struct file on which the error is being reported
707 * When userland calls fsync (or something like nfsd does the equivalent), we
708 * want to report any writeback errors that occurred since the last fsync (or
709 * since the file was opened if there haven't been any).
711 * Grab the wb_err from the mapping. If it matches what we have in the file,
712 * then just quickly return 0. The file is all caught up.
714 * If it doesn't match, then take the mapping value, set the "seen" flag in
715 * it and try to swap it into place. If it works, or another task beat us
716 * to it with the new value, then update the f_wb_err and return the error
717 * portion. The error at this point must be reported via proper channels
718 * (a'la fsync, or NFS COMMIT operation, etc.).
720 * While we handle mapping->wb_err with atomic operations, the f_wb_err
721 * value is protected by the f_lock since we must ensure that it reflects
722 * the latest value swapped in for this file descriptor.
724 * Return: %0 on success, negative error code otherwise.
726 int file_check_and_advance_wb_err(struct file *file)
729 errseq_t old = READ_ONCE(file->f_wb_err);
730 struct address_space *mapping = file->f_mapping;
732 /* Locklessly handle the common case where nothing has changed */
733 if (errseq_check(&mapping->wb_err, old)) {
734 /* Something changed, must use slow path */
735 spin_lock(&file->f_lock);
736 old = file->f_wb_err;
737 err = errseq_check_and_advance(&mapping->wb_err,
739 trace_file_check_and_advance_wb_err(file, old);
740 spin_unlock(&file->f_lock);
744 * We're mostly using this function as a drop in replacement for
745 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
746 * that the legacy code would have had on these flags.
748 clear_bit(AS_EIO, &mapping->flags);
749 clear_bit(AS_ENOSPC, &mapping->flags);
752 EXPORT_SYMBOL(file_check_and_advance_wb_err);
755 * file_write_and_wait_range - write out & wait on a file range
756 * @file: file pointing to address_space with pages
757 * @lstart: offset in bytes where the range starts
758 * @lend: offset in bytes where the range ends (inclusive)
760 * Write out and wait upon file offsets lstart->lend, inclusive.
762 * Note that @lend is inclusive (describes the last byte to be written) so
763 * that this function can be used to write to the very end-of-file (end = -1).
765 * After writing out and waiting on the data, we check and advance the
766 * f_wb_err cursor to the latest value, and return any errors detected there.
768 * Return: %0 on success, negative error code otherwise.
770 int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
773 struct address_space *mapping = file->f_mapping;
775 if (mapping_needs_writeback(mapping)) {
776 err = __filemap_fdatawrite_range(mapping, lstart, lend,
778 /* See comment of filemap_write_and_wait() */
780 __filemap_fdatawait_range(mapping, lstart, lend);
782 err2 = file_check_and_advance_wb_err(file);
787 EXPORT_SYMBOL(file_write_and_wait_range);
790 * replace_page_cache_page - replace a pagecache page with a new one
791 * @old: page to be replaced
792 * @new: page to replace with
793 * @gfp_mask: allocation mode
795 * This function replaces a page in the pagecache with a new one. On
796 * success it acquires the pagecache reference for the new page and
797 * drops it for the old page. Both the old and new pages must be
798 * locked. This function does not add the new page to the LRU, the
799 * caller must do that.
801 * The remove + add is atomic. This function cannot fail.
805 int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
807 struct address_space *mapping = old->mapping;
808 void (*freepage)(struct page *) = mapping->a_ops->freepage;
809 pgoff_t offset = old->index;
810 XA_STATE(xas, &mapping->i_pages, offset);
813 VM_BUG_ON_PAGE(!PageLocked(old), old);
814 VM_BUG_ON_PAGE(!PageLocked(new), new);
815 VM_BUG_ON_PAGE(new->mapping, new);
818 new->mapping = mapping;
821 mem_cgroup_migrate(old, new);
823 xas_lock_irqsave(&xas, flags);
824 xas_store(&xas, new);
827 /* hugetlb pages do not participate in page cache accounting. */
829 __dec_lruvec_page_state(old, NR_FILE_PAGES);
831 __inc_lruvec_page_state(new, NR_FILE_PAGES);
832 if (PageSwapBacked(old))
833 __dec_lruvec_page_state(old, NR_SHMEM);
834 if (PageSwapBacked(new))
835 __inc_lruvec_page_state(new, NR_SHMEM);
836 xas_unlock_irqrestore(&xas, flags);
843 EXPORT_SYMBOL_GPL(replace_page_cache_page);
845 noinline int __add_to_page_cache_locked(struct page *page,
846 struct address_space *mapping,
847 pgoff_t offset, gfp_t gfp,
850 XA_STATE(xas, &mapping->i_pages, offset);
851 int huge = PageHuge(page);
853 bool charged = false;
855 VM_BUG_ON_PAGE(!PageLocked(page), page);
856 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
857 mapping_set_update(&xas, mapping);
860 page->mapping = mapping;
861 page->index = offset;
864 error = mem_cgroup_charge(page, current->mm, gfp);
870 gfp &= GFP_RECLAIM_MASK;
873 unsigned int order = xa_get_order(xas.xa, xas.xa_index);
874 void *entry, *old = NULL;
876 if (order > thp_order(page))
877 xas_split_alloc(&xas, xa_load(xas.xa, xas.xa_index),
880 xas_for_each_conflict(&xas, entry) {
882 if (!xa_is_value(entry)) {
883 xas_set_err(&xas, -EEXIST);
891 /* entry may have been split before we acquired lock */
892 order = xa_get_order(xas.xa, xas.xa_index);
893 if (order > thp_order(page)) {
894 xas_split(&xas, old, order);
899 xas_store(&xas, page);
904 mapping->nrexceptional--;
907 /* hugetlb pages do not participate in page cache accounting */
909 __inc_lruvec_page_state(page, NR_FILE_PAGES);
911 xas_unlock_irq(&xas);
912 } while (xas_nomem(&xas, gfp));
914 if (xas_error(&xas)) {
915 error = xas_error(&xas);
917 mem_cgroup_uncharge(page);
921 trace_mm_filemap_add_to_page_cache(page);
924 page->mapping = NULL;
925 /* Leave page->index set: truncation relies upon it */
929 ALLOW_ERROR_INJECTION(__add_to_page_cache_locked, ERRNO);
932 * add_to_page_cache_locked - add a locked page to the pagecache
934 * @mapping: the page's address_space
935 * @offset: page index
936 * @gfp_mask: page allocation mode
938 * This function is used to add a page to the pagecache. It must be locked.
939 * This function does not add the page to the LRU. The caller must do that.
941 * Return: %0 on success, negative error code otherwise.
943 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
944 pgoff_t offset, gfp_t gfp_mask)
946 return __add_to_page_cache_locked(page, mapping, offset,
949 EXPORT_SYMBOL(add_to_page_cache_locked);
951 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
952 pgoff_t offset, gfp_t gfp_mask)
957 __SetPageLocked(page);
958 ret = __add_to_page_cache_locked(page, mapping, offset,
961 __ClearPageLocked(page);
964 * The page might have been evicted from cache only
965 * recently, in which case it should be activated like
966 * any other repeatedly accessed page.
967 * The exception is pages getting rewritten; evicting other
968 * data from the working set, only to cache data that will
969 * get overwritten with something else, is a waste of memory.
971 WARN_ON_ONCE(PageActive(page));
972 if (!(gfp_mask & __GFP_WRITE) && shadow)
973 workingset_refault(page, shadow);
978 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
981 struct page *__page_cache_alloc(gfp_t gfp)
986 if (cpuset_do_page_mem_spread()) {
987 unsigned int cpuset_mems_cookie;
989 cpuset_mems_cookie = read_mems_allowed_begin();
990 n = cpuset_mem_spread_node();
991 page = __alloc_pages_node(n, gfp, 0);
992 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
996 return alloc_pages(gfp, 0);
998 EXPORT_SYMBOL(__page_cache_alloc);
1002 * In order to wait for pages to become available there must be
1003 * waitqueues associated with pages. By using a hash table of
1004 * waitqueues where the bucket discipline is to maintain all
1005 * waiters on the same queue and wake all when any of the pages
1006 * become available, and for the woken contexts to check to be
1007 * sure the appropriate page became available, this saves space
1008 * at a cost of "thundering herd" phenomena during rare hash
1011 #define PAGE_WAIT_TABLE_BITS 8
1012 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
1013 static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
1015 static wait_queue_head_t *page_waitqueue(struct page *page)
1017 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
1020 void __init pagecache_init(void)
1024 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1025 init_waitqueue_head(&page_wait_table[i]);
1027 page_writeback_init();
1031 * The page wait code treats the "wait->flags" somewhat unusually, because
1032 * we have multiple different kinds of waits, not just the usual "exclusive"
1037 * (a) no special bits set:
1039 * We're just waiting for the bit to be released, and when a waker
1040 * calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up,
1041 * and remove it from the wait queue.
1043 * Simple and straightforward.
1045 * (b) WQ_FLAG_EXCLUSIVE:
1047 * The waiter is waiting to get the lock, and only one waiter should
1048 * be woken up to avoid any thundering herd behavior. We'll set the
1049 * WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue.
1051 * This is the traditional exclusive wait.
1053 * (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
1055 * The waiter is waiting to get the bit, and additionally wants the
1056 * lock to be transferred to it for fair lock behavior. If the lock
1057 * cannot be taken, we stop walking the wait queue without waking
1060 * This is the "fair lock handoff" case, and in addition to setting
1061 * WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see
1062 * that it now has the lock.
1064 static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
1067 struct wait_page_key *key = arg;
1068 struct wait_page_queue *wait_page
1069 = container_of(wait, struct wait_page_queue, wait);
1071 if (!wake_page_match(wait_page, key))
1075 * If it's a lock handoff wait, we get the bit for it, and
1076 * stop walking (and do not wake it up) if we can't.
1078 flags = wait->flags;
1079 if (flags & WQ_FLAG_EXCLUSIVE) {
1080 if (test_bit(key->bit_nr, &key->page->flags))
1082 if (flags & WQ_FLAG_CUSTOM) {
1083 if (test_and_set_bit(key->bit_nr, &key->page->flags))
1085 flags |= WQ_FLAG_DONE;
1090 * We are holding the wait-queue lock, but the waiter that
1091 * is waiting for this will be checking the flags without
1094 * So update the flags atomically, and wake up the waiter
1095 * afterwards to avoid any races. This store-release pairs
1096 * with the load-acquire in wait_on_page_bit_common().
1098 smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
1099 wake_up_state(wait->private, mode);
1102 * Ok, we have successfully done what we're waiting for,
1103 * and we can unconditionally remove the wait entry.
1105 * Note that this pairs with the "finish_wait()" in the
1106 * waiter, and has to be the absolute last thing we do.
1107 * After this list_del_init(&wait->entry) the wait entry
1108 * might be de-allocated and the process might even have
1111 list_del_init_careful(&wait->entry);
1112 return (flags & WQ_FLAG_EXCLUSIVE) != 0;
1115 static void wake_up_page_bit(struct page *page, int bit_nr)
1117 wait_queue_head_t *q = page_waitqueue(page);
1118 struct wait_page_key key;
1119 unsigned long flags;
1120 wait_queue_entry_t bookmark;
1123 key.bit_nr = bit_nr;
1127 bookmark.private = NULL;
1128 bookmark.func = NULL;
1129 INIT_LIST_HEAD(&bookmark.entry);
1131 spin_lock_irqsave(&q->lock, flags);
1132 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1134 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1136 * Take a breather from holding the lock,
1137 * allow pages that finish wake up asynchronously
1138 * to acquire the lock and remove themselves
1141 spin_unlock_irqrestore(&q->lock, flags);
1143 spin_lock_irqsave(&q->lock, flags);
1144 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1148 * It is possible for other pages to have collided on the waitqueue
1149 * hash, so in that case check for a page match. That prevents a long-
1152 * It is still possible to miss a case here, when we woke page waiters
1153 * and removed them from the waitqueue, but there are still other
1156 if (!waitqueue_active(q) || !key.page_match) {
1157 ClearPageWaiters(page);
1159 * It's possible to miss clearing Waiters here, when we woke
1160 * our page waiters, but the hashed waitqueue has waiters for
1161 * other pages on it.
1163 * That's okay, it's a rare case. The next waker will clear it.
1166 spin_unlock_irqrestore(&q->lock, flags);
1169 static void wake_up_page(struct page *page, int bit)
1171 if (!PageWaiters(page))
1173 wake_up_page_bit(page, bit);
1177 * A choice of three behaviors for wait_on_page_bit_common():
1180 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
1181 * __lock_page() waiting on then setting PG_locked.
1183 SHARED, /* Hold ref to page and check the bit when woken, like
1184 * wait_on_page_writeback() waiting on PG_writeback.
1186 DROP, /* Drop ref to page before wait, no check when woken,
1187 * like put_and_wait_on_page_locked() on PG_locked.
1192 * Attempt to check (or get) the page bit, and mark us done
1195 static inline bool trylock_page_bit_common(struct page *page, int bit_nr,
1196 struct wait_queue_entry *wait)
1198 if (wait->flags & WQ_FLAG_EXCLUSIVE) {
1199 if (test_and_set_bit(bit_nr, &page->flags))
1201 } else if (test_bit(bit_nr, &page->flags))
1204 wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
1208 /* How many times do we accept lock stealing from under a waiter? */
1209 int sysctl_page_lock_unfairness = 5;
1211 static inline int wait_on_page_bit_common(wait_queue_head_t *q,
1212 struct page *page, int bit_nr, int state, enum behavior behavior)
1214 int unfairness = sysctl_page_lock_unfairness;
1215 struct wait_page_queue wait_page;
1216 wait_queue_entry_t *wait = &wait_page.wait;
1217 bool thrashing = false;
1218 bool delayacct = false;
1219 unsigned long pflags;
1221 if (bit_nr == PG_locked &&
1222 !PageUptodate(page) && PageWorkingset(page)) {
1223 if (!PageSwapBacked(page)) {
1224 delayacct_thrashing_start();
1227 psi_memstall_enter(&pflags);
1232 wait->func = wake_page_function;
1233 wait_page.page = page;
1234 wait_page.bit_nr = bit_nr;
1238 if (behavior == EXCLUSIVE) {
1239 wait->flags = WQ_FLAG_EXCLUSIVE;
1240 if (--unfairness < 0)
1241 wait->flags |= WQ_FLAG_CUSTOM;
1245 * Do one last check whether we can get the
1246 * page bit synchronously.
1248 * Do the SetPageWaiters() marking before that
1249 * to let any waker we _just_ missed know they
1250 * need to wake us up (otherwise they'll never
1251 * even go to the slow case that looks at the
1252 * page queue), and add ourselves to the wait
1253 * queue if we need to sleep.
1255 * This part needs to be done under the queue
1256 * lock to avoid races.
1258 spin_lock_irq(&q->lock);
1259 SetPageWaiters(page);
1260 if (!trylock_page_bit_common(page, bit_nr, wait))
1261 __add_wait_queue_entry_tail(q, wait);
1262 spin_unlock_irq(&q->lock);
1265 * From now on, all the logic will be based on
1266 * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to
1267 * see whether the page bit testing has already
1268 * been done by the wake function.
1270 * We can drop our reference to the page.
1272 if (behavior == DROP)
1276 * Note that until the "finish_wait()", or until
1277 * we see the WQ_FLAG_WOKEN flag, we need to
1278 * be very careful with the 'wait->flags', because
1279 * we may race with a waker that sets them.
1284 set_current_state(state);
1286 /* Loop until we've been woken or interrupted */
1287 flags = smp_load_acquire(&wait->flags);
1288 if (!(flags & WQ_FLAG_WOKEN)) {
1289 if (signal_pending_state(state, current))
1296 /* If we were non-exclusive, we're done */
1297 if (behavior != EXCLUSIVE)
1300 /* If the waker got the lock for us, we're done */
1301 if (flags & WQ_FLAG_DONE)
1305 * Otherwise, if we're getting the lock, we need to
1306 * try to get it ourselves.
1308 * And if that fails, we'll have to retry this all.
1310 if (unlikely(test_and_set_bit(bit_nr, &page->flags)))
1313 wait->flags |= WQ_FLAG_DONE;
1318 * If a signal happened, this 'finish_wait()' may remove the last
1319 * waiter from the wait-queues, but the PageWaiters bit will remain
1320 * set. That's ok. The next wakeup will take care of it, and trying
1321 * to do it here would be difficult and prone to races.
1323 finish_wait(q, wait);
1327 delayacct_thrashing_end();
1328 psi_memstall_leave(&pflags);
1332 * NOTE! The wait->flags weren't stable until we've done the
1333 * 'finish_wait()', and we could have exited the loop above due
1334 * to a signal, and had a wakeup event happen after the signal
1335 * test but before the 'finish_wait()'.
1337 * So only after the finish_wait() can we reliably determine
1338 * if we got woken up or not, so we can now figure out the final
1339 * return value based on that state without races.
1341 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
1342 * waiter, but an exclusive one requires WQ_FLAG_DONE.
1344 if (behavior == EXCLUSIVE)
1345 return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
1347 return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
1350 void wait_on_page_bit(struct page *page, int bit_nr)
1352 wait_queue_head_t *q = page_waitqueue(page);
1353 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
1355 EXPORT_SYMBOL(wait_on_page_bit);
1357 int wait_on_page_bit_killable(struct page *page, int bit_nr)
1359 wait_queue_head_t *q = page_waitqueue(page);
1360 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, SHARED);
1362 EXPORT_SYMBOL(wait_on_page_bit_killable);
1364 static int __wait_on_page_locked_async(struct page *page,
1365 struct wait_page_queue *wait, bool set)
1367 struct wait_queue_head *q = page_waitqueue(page);
1371 wait->bit_nr = PG_locked;
1373 spin_lock_irq(&q->lock);
1374 __add_wait_queue_entry_tail(q, &wait->wait);
1375 SetPageWaiters(page);
1377 ret = !trylock_page(page);
1379 ret = PageLocked(page);
1381 * If we were succesful now, we know we're still on the
1382 * waitqueue as we're still under the lock. This means it's
1383 * safe to remove and return success, we know the callback
1384 * isn't going to trigger.
1387 __remove_wait_queue(q, &wait->wait);
1390 spin_unlock_irq(&q->lock);
1394 static int wait_on_page_locked_async(struct page *page,
1395 struct wait_page_queue *wait)
1397 if (!PageLocked(page))
1399 return __wait_on_page_locked_async(compound_head(page), wait, false);
1403 * put_and_wait_on_page_locked - Drop a reference and wait for it to be unlocked
1404 * @page: The page to wait for.
1406 * The caller should hold a reference on @page. They expect the page to
1407 * become unlocked relatively soon, but do not wish to hold up migration
1408 * (for example) by holding the reference while waiting for the page to
1409 * come unlocked. After this function returns, the caller should not
1410 * dereference @page.
1412 void put_and_wait_on_page_locked(struct page *page)
1414 wait_queue_head_t *q;
1416 page = compound_head(page);
1417 q = page_waitqueue(page);
1418 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE, DROP);
1422 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
1423 * @page: Page defining the wait queue of interest
1424 * @waiter: Waiter to add to the queue
1426 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1428 void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
1430 wait_queue_head_t *q = page_waitqueue(page);
1431 unsigned long flags;
1433 spin_lock_irqsave(&q->lock, flags);
1434 __add_wait_queue_entry_tail(q, waiter);
1435 SetPageWaiters(page);
1436 spin_unlock_irqrestore(&q->lock, flags);
1438 EXPORT_SYMBOL_GPL(add_page_wait_queue);
1440 #ifndef clear_bit_unlock_is_negative_byte
1443 * PG_waiters is the high bit in the same byte as PG_lock.
1445 * On x86 (and on many other architectures), we can clear PG_lock and
1446 * test the sign bit at the same time. But if the architecture does
1447 * not support that special operation, we just do this all by hand
1450 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1451 * being cleared, but a memory barrier should be unnecessary since it is
1452 * in the same byte as PG_locked.
1454 static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1456 clear_bit_unlock(nr, mem);
1457 /* smp_mb__after_atomic(); */
1458 return test_bit(PG_waiters, mem);
1464 * unlock_page - unlock a locked page
1467 * Unlocks the page and wakes up sleepers in wait_on_page_locked().
1468 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
1469 * mechanism between PageLocked pages and PageWriteback pages is shared.
1470 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1472 * Note that this depends on PG_waiters being the sign bit in the byte
1473 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1474 * clear the PG_locked bit and test PG_waiters at the same time fairly
1475 * portably (architectures that do LL/SC can test any bit, while x86 can
1476 * test the sign bit).
1478 void unlock_page(struct page *page)
1480 BUILD_BUG_ON(PG_waiters != 7);
1481 page = compound_head(page);
1482 VM_BUG_ON_PAGE(!PageLocked(page), page);
1483 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1484 wake_up_page_bit(page, PG_locked);
1486 EXPORT_SYMBOL(unlock_page);
1489 * end_page_writeback - end writeback against a page
1492 void end_page_writeback(struct page *page)
1495 * TestClearPageReclaim could be used here but it is an atomic
1496 * operation and overkill in this particular case. Failing to
1497 * shuffle a page marked for immediate reclaim is too mild to
1498 * justify taking an atomic operation penalty at the end of
1499 * ever page writeback.
1501 if (PageReclaim(page)) {
1502 ClearPageReclaim(page);
1503 rotate_reclaimable_page(page);
1507 * Writeback does not hold a page reference of its own, relying
1508 * on truncation to wait for the clearing of PG_writeback.
1509 * But here we must make sure that the page is not freed and
1510 * reused before the wake_up_page().
1513 if (!test_clear_page_writeback(page))
1516 smp_mb__after_atomic();
1517 wake_up_page(page, PG_writeback);
1520 EXPORT_SYMBOL(end_page_writeback);
1523 * After completing I/O on a page, call this routine to update the page
1524 * flags appropriately
1526 void page_endio(struct page *page, bool is_write, int err)
1530 SetPageUptodate(page);
1532 ClearPageUptodate(page);
1538 struct address_space *mapping;
1541 mapping = page_mapping(page);
1543 mapping_set_error(mapping, err);
1545 end_page_writeback(page);
1548 EXPORT_SYMBOL_GPL(page_endio);
1551 * __lock_page - get a lock on the page, assuming we need to sleep to get it
1552 * @__page: the page to lock
1554 void __lock_page(struct page *__page)
1556 struct page *page = compound_head(__page);
1557 wait_queue_head_t *q = page_waitqueue(page);
1558 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE,
1561 EXPORT_SYMBOL(__lock_page);
1563 int __lock_page_killable(struct page *__page)
1565 struct page *page = compound_head(__page);
1566 wait_queue_head_t *q = page_waitqueue(page);
1567 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE,
1570 EXPORT_SYMBOL_GPL(__lock_page_killable);
1572 int __lock_page_async(struct page *page, struct wait_page_queue *wait)
1574 return __wait_on_page_locked_async(page, wait, true);
1579 * 1 - page is locked; mmap_lock is still held.
1580 * 0 - page is not locked.
1581 * mmap_lock has been released (mmap_read_unlock(), unless flags had both
1582 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1583 * which case mmap_lock is still held.
1585 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1586 * with the page locked and the mmap_lock unperturbed.
1588 int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1591 if (fault_flag_allow_retry_first(flags)) {
1593 * CAUTION! In this case, mmap_lock is not released
1594 * even though return 0.
1596 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1599 mmap_read_unlock(mm);
1600 if (flags & FAULT_FLAG_KILLABLE)
1601 wait_on_page_locked_killable(page);
1603 wait_on_page_locked(page);
1606 if (flags & FAULT_FLAG_KILLABLE) {
1609 ret = __lock_page_killable(page);
1611 mmap_read_unlock(mm);
1621 * page_cache_next_miss() - Find the next gap in the page cache.
1622 * @mapping: Mapping.
1624 * @max_scan: Maximum range to search.
1626 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1627 * gap with the lowest index.
1629 * This function may be called under the rcu_read_lock. However, this will
1630 * not atomically search a snapshot of the cache at a single point in time.
1631 * For example, if a gap is created at index 5, then subsequently a gap is
1632 * created at index 10, page_cache_next_miss covering both indices may
1633 * return 10 if called under the rcu_read_lock.
1635 * Return: The index of the gap if found, otherwise an index outside the
1636 * range specified (in which case 'return - index >= max_scan' will be true).
1637 * In the rare case of index wrap-around, 0 will be returned.
1639 pgoff_t page_cache_next_miss(struct address_space *mapping,
1640 pgoff_t index, unsigned long max_scan)
1642 XA_STATE(xas, &mapping->i_pages, index);
1644 while (max_scan--) {
1645 void *entry = xas_next(&xas);
1646 if (!entry || xa_is_value(entry))
1648 if (xas.xa_index == 0)
1652 return xas.xa_index;
1654 EXPORT_SYMBOL(page_cache_next_miss);
1657 * page_cache_prev_miss() - Find the previous gap in the page cache.
1658 * @mapping: Mapping.
1660 * @max_scan: Maximum range to search.
1662 * Search the range [max(index - max_scan + 1, 0), index] for the
1663 * gap with the highest index.
1665 * This function may be called under the rcu_read_lock. However, this will
1666 * not atomically search a snapshot of the cache at a single point in time.
1667 * For example, if a gap is created at index 10, then subsequently a gap is
1668 * created at index 5, page_cache_prev_miss() covering both indices may
1669 * return 5 if called under the rcu_read_lock.
1671 * Return: The index of the gap if found, otherwise an index outside the
1672 * range specified (in which case 'index - return >= max_scan' will be true).
1673 * In the rare case of wrap-around, ULONG_MAX will be returned.
1675 pgoff_t page_cache_prev_miss(struct address_space *mapping,
1676 pgoff_t index, unsigned long max_scan)
1678 XA_STATE(xas, &mapping->i_pages, index);
1680 while (max_scan--) {
1681 void *entry = xas_prev(&xas);
1682 if (!entry || xa_is_value(entry))
1684 if (xas.xa_index == ULONG_MAX)
1688 return xas.xa_index;
1690 EXPORT_SYMBOL(page_cache_prev_miss);
1693 * find_get_entry - find and get a page cache entry
1694 * @mapping: the address_space to search
1695 * @index: The page cache index.
1697 * Looks up the page cache slot at @mapping & @offset. If there is a
1698 * page cache page, the head page is returned with an increased refcount.
1700 * If the slot holds a shadow entry of a previously evicted page, or a
1701 * swap entry from shmem/tmpfs, it is returned.
1703 * Return: The head page or shadow entry, %NULL if nothing is found.
1705 struct page *find_get_entry(struct address_space *mapping, pgoff_t index)
1707 XA_STATE(xas, &mapping->i_pages, index);
1713 page = xas_load(&xas);
1714 if (xas_retry(&xas, page))
1717 * A shadow entry of a recently evicted page, or a swap entry from
1718 * shmem/tmpfs. Return it without attempting to raise page count.
1720 if (!page || xa_is_value(page))
1723 if (!page_cache_get_speculative(page))
1727 * Has the page moved or been split?
1728 * This is part of the lockless pagecache protocol. See
1729 * include/linux/pagemap.h for details.
1731 if (unlikely(page != xas_reload(&xas))) {
1742 * find_lock_entry - Locate and lock a page cache entry.
1743 * @mapping: The address_space to search.
1744 * @index: The page cache index.
1746 * Looks up the page at @mapping & @index. If there is a page in the
1747 * cache, the head page is returned locked and with an increased refcount.
1749 * If the slot holds a shadow entry of a previously evicted page, or a
1750 * swap entry from shmem/tmpfs, it is returned.
1752 * Context: May sleep.
1753 * Return: The head page or shadow entry, %NULL if nothing is found.
1755 struct page *find_lock_entry(struct address_space *mapping, pgoff_t index)
1760 page = find_get_entry(mapping, index);
1761 if (page && !xa_is_value(page)) {
1763 /* Has the page been truncated? */
1764 if (unlikely(page->mapping != mapping)) {
1769 VM_BUG_ON_PAGE(!thp_contains(page, index), page);
1775 * pagecache_get_page - Find and get a reference to a page.
1776 * @mapping: The address_space to search.
1777 * @index: The page index.
1778 * @fgp_flags: %FGP flags modify how the page is returned.
1779 * @gfp_mask: Memory allocation flags to use if %FGP_CREAT is specified.
1781 * Looks up the page cache entry at @mapping & @index.
1783 * @fgp_flags can be zero or more of these flags:
1785 * * %FGP_ACCESSED - The page will be marked accessed.
1786 * * %FGP_LOCK - The page is returned locked.
1787 * * %FGP_HEAD - If the page is present and a THP, return the head page
1788 * rather than the exact page specified by the index.
1789 * * %FGP_CREAT - If no page is present then a new page is allocated using
1790 * @gfp_mask and added to the page cache and the VM's LRU list.
1791 * The page is returned locked and with an increased refcount.
1792 * * %FGP_FOR_MMAP - The caller wants to do its own locking dance if the
1793 * page is already in cache. If the page was allocated, unlock it before
1794 * returning so the caller can do the same dance.
1795 * * %FGP_WRITE - The page will be written
1796 * * %FGP_NOFS - __GFP_FS will get cleared in gfp mask
1797 * * %FGP_NOWAIT - Don't get blocked by page lock
1799 * If %FGP_LOCK or %FGP_CREAT are specified then the function may sleep even
1800 * if the %GFP flags specified for %FGP_CREAT are atomic.
1802 * If there is a page cache page, it is returned with an increased refcount.
1804 * Return: The found page or %NULL otherwise.
1806 struct page *pagecache_get_page(struct address_space *mapping, pgoff_t index,
1807 int fgp_flags, gfp_t gfp_mask)
1812 page = find_get_entry(mapping, index);
1813 if (xa_is_value(page))
1818 if (fgp_flags & FGP_LOCK) {
1819 if (fgp_flags & FGP_NOWAIT) {
1820 if (!trylock_page(page)) {
1828 /* Has the page been truncated? */
1829 if (unlikely(page->mapping != mapping)) {
1834 VM_BUG_ON_PAGE(!thp_contains(page, index), page);
1837 if (fgp_flags & FGP_ACCESSED)
1838 mark_page_accessed(page);
1839 else if (fgp_flags & FGP_WRITE) {
1840 /* Clear idle flag for buffer write */
1841 if (page_is_idle(page))
1842 clear_page_idle(page);
1844 if (!(fgp_flags & FGP_HEAD))
1845 page = find_subpage(page, index);
1848 if (!page && (fgp_flags & FGP_CREAT)) {
1850 if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping))
1851 gfp_mask |= __GFP_WRITE;
1852 if (fgp_flags & FGP_NOFS)
1853 gfp_mask &= ~__GFP_FS;
1855 page = __page_cache_alloc(gfp_mask);
1859 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
1860 fgp_flags |= FGP_LOCK;
1862 /* Init accessed so avoid atomic mark_page_accessed later */
1863 if (fgp_flags & FGP_ACCESSED)
1864 __SetPageReferenced(page);
1866 err = add_to_page_cache_lru(page, mapping, index, gfp_mask);
1867 if (unlikely(err)) {
1875 * add_to_page_cache_lru locks the page, and for mmap we expect
1878 if (page && (fgp_flags & FGP_FOR_MMAP))
1884 EXPORT_SYMBOL(pagecache_get_page);
1887 * find_get_entries - gang pagecache lookup
1888 * @mapping: The address_space to search
1889 * @start: The starting page cache index
1890 * @nr_entries: The maximum number of entries
1891 * @entries: Where the resulting entries are placed
1892 * @indices: The cache indices corresponding to the entries in @entries
1894 * find_get_entries() will search for and return a group of up to
1895 * @nr_entries entries in the mapping. The entries are placed at
1896 * @entries. find_get_entries() takes a reference against any actual
1899 * The search returns a group of mapping-contiguous page cache entries
1900 * with ascending indexes. There may be holes in the indices due to
1901 * not-present pages.
1903 * Any shadow entries of evicted pages, or swap entries from
1904 * shmem/tmpfs, are included in the returned array.
1906 * If it finds a Transparent Huge Page, head or tail, find_get_entries()
1907 * stops at that page: the caller is likely to have a better way to handle
1908 * the compound page as a whole, and then skip its extent, than repeatedly
1909 * calling find_get_entries() to return all its tails.
1911 * Return: the number of pages and shadow entries which were found.
1913 unsigned find_get_entries(struct address_space *mapping,
1914 pgoff_t start, unsigned int nr_entries,
1915 struct page **entries, pgoff_t *indices)
1917 XA_STATE(xas, &mapping->i_pages, start);
1919 unsigned int ret = 0;
1925 xas_for_each(&xas, page, ULONG_MAX) {
1926 if (xas_retry(&xas, page))
1929 * A shadow entry of a recently evicted page, a swap
1930 * entry from shmem/tmpfs or a DAX entry. Return it
1931 * without attempting to raise page count.
1933 if (xa_is_value(page))
1936 if (!page_cache_get_speculative(page))
1939 /* Has the page moved or been split? */
1940 if (unlikely(page != xas_reload(&xas)))
1944 * Terminate early on finding a THP, to allow the caller to
1945 * handle it all at once; but continue if this is hugetlbfs.
1947 if (PageTransHuge(page) && !PageHuge(page)) {
1948 page = find_subpage(page, xas.xa_index);
1949 nr_entries = ret + 1;
1952 indices[ret] = xas.xa_index;
1953 entries[ret] = page;
1954 if (++ret == nr_entries)
1967 * find_get_pages_range - gang pagecache lookup
1968 * @mapping: The address_space to search
1969 * @start: The starting page index
1970 * @end: The final page index (inclusive)
1971 * @nr_pages: The maximum number of pages
1972 * @pages: Where the resulting pages are placed
1974 * find_get_pages_range() will search for and return a group of up to @nr_pages
1975 * pages in the mapping starting at index @start and up to index @end
1976 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
1977 * a reference against the returned pages.
1979 * The search returns a group of mapping-contiguous pages with ascending
1980 * indexes. There may be holes in the indices due to not-present pages.
1981 * We also update @start to index the next page for the traversal.
1983 * Return: the number of pages which were found. If this number is
1984 * smaller than @nr_pages, the end of specified range has been
1987 unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
1988 pgoff_t end, unsigned int nr_pages,
1989 struct page **pages)
1991 XA_STATE(xas, &mapping->i_pages, *start);
1995 if (unlikely(!nr_pages))
1999 xas_for_each(&xas, page, end) {
2000 if (xas_retry(&xas, page))
2002 /* Skip over shadow, swap and DAX entries */
2003 if (xa_is_value(page))
2006 if (!page_cache_get_speculative(page))
2009 /* Has the page moved or been split? */
2010 if (unlikely(page != xas_reload(&xas)))
2013 pages[ret] = find_subpage(page, xas.xa_index);
2014 if (++ret == nr_pages) {
2015 *start = xas.xa_index + 1;
2026 * We come here when there is no page beyond @end. We take care to not
2027 * overflow the index @start as it confuses some of the callers. This
2028 * breaks the iteration when there is a page at index -1 but that is
2029 * already broken anyway.
2031 if (end == (pgoff_t)-1)
2032 *start = (pgoff_t)-1;
2042 * find_get_pages_contig - gang contiguous pagecache lookup
2043 * @mapping: The address_space to search
2044 * @index: The starting page index
2045 * @nr_pages: The maximum number of pages
2046 * @pages: Where the resulting pages are placed
2048 * find_get_pages_contig() works exactly like find_get_pages(), except
2049 * that the returned number of pages are guaranteed to be contiguous.
2051 * Return: the number of pages which were found.
2053 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
2054 unsigned int nr_pages, struct page **pages)
2056 XA_STATE(xas, &mapping->i_pages, index);
2058 unsigned int ret = 0;
2060 if (unlikely(!nr_pages))
2064 for (page = xas_load(&xas); page; page = xas_next(&xas)) {
2065 if (xas_retry(&xas, page))
2068 * If the entry has been swapped out, we can stop looking.
2069 * No current caller is looking for DAX entries.
2071 if (xa_is_value(page))
2074 if (!page_cache_get_speculative(page))
2077 /* Has the page moved or been split? */
2078 if (unlikely(page != xas_reload(&xas)))
2081 pages[ret] = find_subpage(page, xas.xa_index);
2082 if (++ret == nr_pages)
2093 EXPORT_SYMBOL(find_get_pages_contig);
2096 * find_get_pages_range_tag - find and return pages in given range matching @tag
2097 * @mapping: the address_space to search
2098 * @index: the starting page index
2099 * @end: The final page index (inclusive)
2100 * @tag: the tag index
2101 * @nr_pages: the maximum number of pages
2102 * @pages: where the resulting pages are placed
2104 * Like find_get_pages, except we only return pages which are tagged with
2105 * @tag. We update @index to index the next page for the traversal.
2107 * Return: the number of pages which were found.
2109 unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
2110 pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
2111 struct page **pages)
2113 XA_STATE(xas, &mapping->i_pages, *index);
2117 if (unlikely(!nr_pages))
2121 xas_for_each_marked(&xas, page, end, tag) {
2122 if (xas_retry(&xas, page))
2125 * Shadow entries should never be tagged, but this iteration
2126 * is lockless so there is a window for page reclaim to evict
2127 * a page we saw tagged. Skip over it.
2129 if (xa_is_value(page))
2132 if (!page_cache_get_speculative(page))
2135 /* Has the page moved or been split? */
2136 if (unlikely(page != xas_reload(&xas)))
2139 pages[ret] = find_subpage(page, xas.xa_index);
2140 if (++ret == nr_pages) {
2141 *index = xas.xa_index + 1;
2152 * We come here when we got to @end. We take care to not overflow the
2153 * index @index as it confuses some of the callers. This breaks the
2154 * iteration when there is a page at index -1 but that is already
2157 if (end == (pgoff_t)-1)
2158 *index = (pgoff_t)-1;
2166 EXPORT_SYMBOL(find_get_pages_range_tag);
2169 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
2170 * a _large_ part of the i/o request. Imagine the worst scenario:
2172 * ---R__________________________________________B__________
2173 * ^ reading here ^ bad block(assume 4k)
2175 * read(R) => miss => readahead(R...B) => media error => frustrating retries
2176 * => failing the whole request => read(R) => read(R+1) =>
2177 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
2178 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
2179 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
2181 * It is going insane. Fix it by quickly scaling down the readahead size.
2183 static void shrink_readahead_size_eio(struct file_ra_state *ra)
2189 * generic_file_buffered_read - generic file read routine
2190 * @iocb: the iocb to read
2191 * @iter: data destination
2192 * @written: already copied
2194 * This is a generic file read routine, and uses the
2195 * mapping->a_ops->readpage() function for the actual low-level stuff.
2197 * This is really ugly. But the goto's actually try to clarify some
2198 * of the logic when it comes to error handling etc.
2201 * * total number of bytes copied, including those the were already @written
2202 * * negative error code if nothing was copied
2204 ssize_t generic_file_buffered_read(struct kiocb *iocb,
2205 struct iov_iter *iter, ssize_t written)
2207 struct file *filp = iocb->ki_filp;
2208 struct address_space *mapping = filp->f_mapping;
2209 struct inode *inode = mapping->host;
2210 struct file_ra_state *ra = &filp->f_ra;
2211 loff_t *ppos = &iocb->ki_pos;
2215 unsigned long offset; /* offset into pagecache page */
2216 unsigned int prev_offset;
2219 if (unlikely(*ppos >= inode->i_sb->s_maxbytes))
2221 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2223 index = *ppos >> PAGE_SHIFT;
2224 prev_index = ra->prev_pos >> PAGE_SHIFT;
2225 prev_offset = ra->prev_pos & (PAGE_SIZE-1);
2226 last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
2227 offset = *ppos & ~PAGE_MASK;
2230 * If we've already successfully copied some data, then we
2231 * can no longer safely return -EIOCBQUEUED. Hence mark
2232 * an async read NOWAIT at that point.
2234 if (written && (iocb->ki_flags & IOCB_WAITQ))
2235 iocb->ki_flags |= IOCB_NOWAIT;
2241 unsigned long nr, ret;
2245 if (fatal_signal_pending(current)) {
2250 page = find_get_page(mapping, index);
2252 if (iocb->ki_flags & IOCB_NOIO)
2254 page_cache_sync_readahead(mapping,
2256 index, last_index - index);
2257 page = find_get_page(mapping, index);
2258 if (unlikely(page == NULL))
2259 goto no_cached_page;
2261 if (PageReadahead(page)) {
2262 if (iocb->ki_flags & IOCB_NOIO) {
2266 page_cache_async_readahead(mapping,
2268 index, last_index - index);
2270 if (!PageUptodate(page)) {
2272 * See comment in do_read_cache_page on why
2273 * wait_on_page_locked is used to avoid unnecessarily
2274 * serialisations and why it's safe.
2276 if (iocb->ki_flags & IOCB_WAITQ) {
2281 error = wait_on_page_locked_async(page,
2284 if (iocb->ki_flags & IOCB_NOWAIT) {
2288 error = wait_on_page_locked_killable(page);
2290 if (unlikely(error))
2291 goto readpage_error;
2292 if (PageUptodate(page))
2295 if (inode->i_blkbits == PAGE_SHIFT ||
2296 !mapping->a_ops->is_partially_uptodate)
2297 goto page_not_up_to_date;
2298 /* pipes can't handle partially uptodate pages */
2299 if (unlikely(iov_iter_is_pipe(iter)))
2300 goto page_not_up_to_date;
2301 if (!trylock_page(page))
2302 goto page_not_up_to_date;
2303 /* Did it get truncated before we got the lock? */
2305 goto page_not_up_to_date_locked;
2306 if (!mapping->a_ops->is_partially_uptodate(page,
2307 offset, iter->count))
2308 goto page_not_up_to_date_locked;
2313 * i_size must be checked after we know the page is Uptodate.
2315 * Checking i_size after the check allows us to calculate
2316 * the correct value for "nr", which means the zero-filled
2317 * part of the page is not copied back to userspace (unless
2318 * another truncate extends the file - this is desired though).
2321 isize = i_size_read(inode);
2322 end_index = (isize - 1) >> PAGE_SHIFT;
2323 if (unlikely(!isize || index > end_index)) {
2328 /* nr is the maximum number of bytes to copy from this page */
2330 if (index == end_index) {
2331 nr = ((isize - 1) & ~PAGE_MASK) + 1;
2339 /* If users can be writing to this page using arbitrary
2340 * virtual addresses, take care about potential aliasing
2341 * before reading the page on the kernel side.
2343 if (mapping_writably_mapped(mapping))
2344 flush_dcache_page(page);
2347 * When a sequential read accesses a page several times,
2348 * only mark it as accessed the first time.
2350 if (prev_index != index || offset != prev_offset)
2351 mark_page_accessed(page);
2355 * Ok, we have the page, and it's up-to-date, so
2356 * now we can copy it to user space...
2359 ret = copy_page_to_iter(page, offset, nr, iter);
2361 index += offset >> PAGE_SHIFT;
2362 offset &= ~PAGE_MASK;
2363 prev_offset = offset;
2367 if (!iov_iter_count(iter))
2375 page_not_up_to_date:
2376 /* Get exclusive access to the page ... */
2377 if (iocb->ki_flags & IOCB_WAITQ) {
2382 error = lock_page_async(page, iocb->ki_waitq);
2384 error = lock_page_killable(page);
2386 if (unlikely(error))
2387 goto readpage_error;
2389 page_not_up_to_date_locked:
2390 /* Did it get truncated before we got the lock? */
2391 if (!page->mapping) {
2397 /* Did somebody else fill it already? */
2398 if (PageUptodate(page)) {
2404 if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT)) {
2410 * A previous I/O error may have been due to temporary
2411 * failures, eg. multipath errors.
2412 * PG_error will be set again if readpage fails.
2414 ClearPageError(page);
2415 /* Start the actual read. The read will unlock the page. */
2416 error = mapping->a_ops->readpage(filp, page);
2418 if (unlikely(error)) {
2419 if (error == AOP_TRUNCATED_PAGE) {
2424 goto readpage_error;
2427 if (!PageUptodate(page)) {
2428 if (iocb->ki_flags & IOCB_WAITQ) {
2433 error = lock_page_async(page, iocb->ki_waitq);
2435 error = lock_page_killable(page);
2438 if (unlikely(error))
2439 goto readpage_error;
2440 if (!PageUptodate(page)) {
2441 if (page->mapping == NULL) {
2443 * invalidate_mapping_pages got it
2450 shrink_readahead_size_eio(ra);
2452 goto readpage_error;
2460 /* UHHUH! A synchronous read error occurred. Report it */
2466 * Ok, it wasn't cached, so we need to create a new
2469 page = page_cache_alloc(mapping);
2474 error = add_to_page_cache_lru(page, mapping, index,
2475 mapping_gfp_constraint(mapping, GFP_KERNEL));
2478 if (error == -EEXIST) {
2490 ra->prev_pos = prev_index;
2491 ra->prev_pos <<= PAGE_SHIFT;
2492 ra->prev_pos |= prev_offset;
2494 *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
2495 file_accessed(filp);
2496 return written ? written : error;
2498 EXPORT_SYMBOL_GPL(generic_file_buffered_read);
2501 * generic_file_read_iter - generic filesystem read routine
2502 * @iocb: kernel I/O control block
2503 * @iter: destination for the data read
2505 * This is the "read_iter()" routine for all filesystems
2506 * that can use the page cache directly.
2508 * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
2509 * be returned when no data can be read without waiting for I/O requests
2510 * to complete; it doesn't prevent readahead.
2512 * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
2513 * requests shall be made for the read or for readahead. When no data
2514 * can be read, -EAGAIN shall be returned. When readahead would be
2515 * triggered, a partial, possibly empty read shall be returned.
2518 * * number of bytes copied, even for partial reads
2519 * * negative error code (or 0 if IOCB_NOIO) if nothing was read
2522 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2524 size_t count = iov_iter_count(iter);
2528 goto out; /* skip atime */
2530 if (iocb->ki_flags & IOCB_DIRECT) {
2531 struct file *file = iocb->ki_filp;
2532 struct address_space *mapping = file->f_mapping;
2533 struct inode *inode = mapping->host;
2536 size = i_size_read(inode);
2537 if (iocb->ki_flags & IOCB_NOWAIT) {
2538 if (filemap_range_has_page(mapping, iocb->ki_pos,
2539 iocb->ki_pos + count - 1))
2542 retval = filemap_write_and_wait_range(mapping,
2544 iocb->ki_pos + count - 1);
2549 file_accessed(file);
2551 retval = mapping->a_ops->direct_IO(iocb, iter);
2553 iocb->ki_pos += retval;
2556 iov_iter_revert(iter, count - iov_iter_count(iter));
2559 * Btrfs can have a short DIO read if we encounter
2560 * compressed extents, so if there was an error, or if
2561 * we've already read everything we wanted to, or if
2562 * there was a short read because we hit EOF, go ahead
2563 * and return. Otherwise fallthrough to buffered io for
2564 * the rest of the read. Buffered reads will not work for
2565 * DAX files, so don't bother trying.
2567 if (retval < 0 || !count || iocb->ki_pos >= size ||
2572 retval = generic_file_buffered_read(iocb, iter, retval);
2576 EXPORT_SYMBOL(generic_file_read_iter);
2579 #define MMAP_LOTSAMISS (100)
2581 * lock_page_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock
2582 * @vmf - the vm_fault for this fault.
2583 * @page - the page to lock.
2584 * @fpin - the pointer to the file we may pin (or is already pinned).
2586 * This works similar to lock_page_or_retry in that it can drop the mmap_lock.
2587 * It differs in that it actually returns the page locked if it returns 1 and 0
2588 * if it couldn't lock the page. If we did have to drop the mmap_lock then fpin
2589 * will point to the pinned file and needs to be fput()'ed at a later point.
2591 static int lock_page_maybe_drop_mmap(struct vm_fault *vmf, struct page *page,
2594 if (trylock_page(page))
2598 * NOTE! This will make us return with VM_FAULT_RETRY, but with
2599 * the mmap_lock still held. That's how FAULT_FLAG_RETRY_NOWAIT
2600 * is supposed to work. We have way too many special cases..
2602 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2605 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2606 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2607 if (__lock_page_killable(page)) {
2609 * We didn't have the right flags to drop the mmap_lock,
2610 * but all fault_handlers only check for fatal signals
2611 * if we return VM_FAULT_RETRY, so we need to drop the
2612 * mmap_lock here and return 0 if we don't have a fpin.
2615 mmap_read_unlock(vmf->vma->vm_mm);
2625 * Synchronous readahead happens when we don't even find a page in the page
2626 * cache at all. We don't want to perform IO under the mmap sem, so if we have
2627 * to drop the mmap sem we return the file that was pinned in order for us to do
2628 * that. If we didn't pin a file then we return NULL. The file that is
2629 * returned needs to be fput()'ed when we're done with it.
2631 static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
2633 struct file *file = vmf->vma->vm_file;
2634 struct file_ra_state *ra = &file->f_ra;
2635 struct address_space *mapping = file->f_mapping;
2636 DEFINE_READAHEAD(ractl, file, mapping, vmf->pgoff);
2637 struct file *fpin = NULL;
2638 unsigned int mmap_miss;
2640 /* If we don't want any read-ahead, don't bother */
2641 if (vmf->vma->vm_flags & VM_RAND_READ)
2646 if (vmf->vma->vm_flags & VM_SEQ_READ) {
2647 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2648 page_cache_sync_ra(&ractl, ra, ra->ra_pages);
2652 /* Avoid banging the cache line if not needed */
2653 mmap_miss = READ_ONCE(ra->mmap_miss);
2654 if (mmap_miss < MMAP_LOTSAMISS * 10)
2655 WRITE_ONCE(ra->mmap_miss, ++mmap_miss);
2658 * Do we miss much more than hit in this file? If so,
2659 * stop bothering with read-ahead. It will only hurt.
2661 if (mmap_miss > MMAP_LOTSAMISS)
2667 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2668 ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2);
2669 ra->size = ra->ra_pages;
2670 ra->async_size = ra->ra_pages / 4;
2671 ractl._index = ra->start;
2672 do_page_cache_ra(&ractl, ra->size, ra->async_size);
2677 * Asynchronous readahead happens when we find the page and PG_readahead,
2678 * so we want to possibly extend the readahead further. We return the file that
2679 * was pinned if we have to drop the mmap_lock in order to do IO.
2681 static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2684 struct file *file = vmf->vma->vm_file;
2685 struct file_ra_state *ra = &file->f_ra;
2686 struct address_space *mapping = file->f_mapping;
2687 struct file *fpin = NULL;
2688 unsigned int mmap_miss;
2689 pgoff_t offset = vmf->pgoff;
2691 /* If we don't want any read-ahead, don't bother */
2692 if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
2694 mmap_miss = READ_ONCE(ra->mmap_miss);
2696 WRITE_ONCE(ra->mmap_miss, --mmap_miss);
2697 if (PageReadahead(page)) {
2698 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2699 page_cache_async_readahead(mapping, ra, file,
2700 page, offset, ra->ra_pages);
2706 * filemap_fault - read in file data for page fault handling
2707 * @vmf: struct vm_fault containing details of the fault
2709 * filemap_fault() is invoked via the vma operations vector for a
2710 * mapped memory region to read in file data during a page fault.
2712 * The goto's are kind of ugly, but this streamlines the normal case of having
2713 * it in the page cache, and handles the special cases reasonably without
2714 * having a lot of duplicated code.
2716 * vma->vm_mm->mmap_lock must be held on entry.
2718 * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
2719 * may be dropped before doing I/O or by lock_page_maybe_drop_mmap().
2721 * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
2722 * has not been released.
2724 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
2726 * Return: bitwise-OR of %VM_FAULT_ codes.
2728 vm_fault_t filemap_fault(struct vm_fault *vmf)
2731 struct file *file = vmf->vma->vm_file;
2732 struct file *fpin = NULL;
2733 struct address_space *mapping = file->f_mapping;
2734 struct file_ra_state *ra = &file->f_ra;
2735 struct inode *inode = mapping->host;
2736 pgoff_t offset = vmf->pgoff;
2741 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2742 if (unlikely(offset >= max_off))
2743 return VM_FAULT_SIGBUS;
2746 * Do we have something in the page cache already?
2748 page = find_get_page(mapping, offset);
2749 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
2751 * We found the page, so try async readahead before
2752 * waiting for the lock.
2754 fpin = do_async_mmap_readahead(vmf, page);
2756 /* No page in the page cache at all */
2757 count_vm_event(PGMAJFAULT);
2758 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
2759 ret = VM_FAULT_MAJOR;
2760 fpin = do_sync_mmap_readahead(vmf);
2762 page = pagecache_get_page(mapping, offset,
2763 FGP_CREAT|FGP_FOR_MMAP,
2768 return VM_FAULT_OOM;
2772 if (!lock_page_maybe_drop_mmap(vmf, page, &fpin))
2775 /* Did it get truncated? */
2776 if (unlikely(compound_head(page)->mapping != mapping)) {
2781 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
2784 * We have a locked page in the page cache, now we need to check
2785 * that it's up-to-date. If not, it is going to be due to an error.
2787 if (unlikely(!PageUptodate(page)))
2788 goto page_not_uptodate;
2791 * We've made it this far and we had to drop our mmap_lock, now is the
2792 * time to return to the upper layer and have it re-find the vma and
2801 * Found the page and have a reference on it.
2802 * We must recheck i_size under page lock.
2804 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2805 if (unlikely(offset >= max_off)) {
2808 return VM_FAULT_SIGBUS;
2812 return ret | VM_FAULT_LOCKED;
2816 * Umm, take care of errors if the page isn't up-to-date.
2817 * Try to re-read it _once_. We do this synchronously,
2818 * because there really aren't any performance issues here
2819 * and we need to check for errors.
2821 ClearPageError(page);
2822 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2823 error = mapping->a_ops->readpage(file, page);
2825 wait_on_page_locked(page);
2826 if (!PageUptodate(page))
2833 if (!error || error == AOP_TRUNCATED_PAGE)
2836 shrink_readahead_size_eio(ra);
2837 return VM_FAULT_SIGBUS;
2841 * We dropped the mmap_lock, we need to return to the fault handler to
2842 * re-find the vma and come back and find our hopefully still populated
2849 return ret | VM_FAULT_RETRY;
2851 EXPORT_SYMBOL(filemap_fault);
2853 void filemap_map_pages(struct vm_fault *vmf,
2854 pgoff_t start_pgoff, pgoff_t end_pgoff)
2856 struct file *file = vmf->vma->vm_file;
2857 struct address_space *mapping = file->f_mapping;
2858 pgoff_t last_pgoff = start_pgoff;
2859 unsigned long max_idx;
2860 XA_STATE(xas, &mapping->i_pages, start_pgoff);
2861 struct page *head, *page;
2862 unsigned int mmap_miss = READ_ONCE(file->f_ra.mmap_miss);
2865 xas_for_each(&xas, head, end_pgoff) {
2866 if (xas_retry(&xas, head))
2868 if (xa_is_value(head))
2872 * Check for a locked page first, as a speculative
2873 * reference may adversely influence page migration.
2875 if (PageLocked(head))
2877 if (!page_cache_get_speculative(head))
2880 /* Has the page moved or been split? */
2881 if (unlikely(head != xas_reload(&xas)))
2883 page = find_subpage(head, xas.xa_index);
2885 if (!PageUptodate(head) ||
2886 PageReadahead(page) ||
2889 if (!trylock_page(head))
2892 if (head->mapping != mapping || !PageUptodate(head))
2895 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2896 if (xas.xa_index >= max_idx)
2902 vmf->address += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
2904 vmf->pte += xas.xa_index - last_pgoff;
2905 last_pgoff = xas.xa_index;
2906 if (alloc_set_pte(vmf, page))
2915 /* Huge page is mapped? No need to proceed. */
2916 if (pmd_trans_huge(*vmf->pmd))
2920 WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss);
2922 EXPORT_SYMBOL(filemap_map_pages);
2924 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
2926 struct page *page = vmf->page;
2927 struct inode *inode = file_inode(vmf->vma->vm_file);
2928 vm_fault_t ret = VM_FAULT_LOCKED;
2930 sb_start_pagefault(inode->i_sb);
2931 file_update_time(vmf->vma->vm_file);
2933 if (page->mapping != inode->i_mapping) {
2935 ret = VM_FAULT_NOPAGE;
2939 * We mark the page dirty already here so that when freeze is in
2940 * progress, we are guaranteed that writeback during freezing will
2941 * see the dirty page and writeprotect it again.
2943 set_page_dirty(page);
2944 wait_for_stable_page(page);
2946 sb_end_pagefault(inode->i_sb);
2950 const struct vm_operations_struct generic_file_vm_ops = {
2951 .fault = filemap_fault,
2952 .map_pages = filemap_map_pages,
2953 .page_mkwrite = filemap_page_mkwrite,
2956 /* This is used for a general mmap of a disk file */
2958 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2960 struct address_space *mapping = file->f_mapping;
2962 if (!mapping->a_ops->readpage)
2964 file_accessed(file);
2965 vma->vm_ops = &generic_file_vm_ops;
2970 * This is for filesystems which do not implement ->writepage.
2972 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2974 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2976 return generic_file_mmap(file, vma);
2979 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
2981 return VM_FAULT_SIGBUS;
2983 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2987 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2991 #endif /* CONFIG_MMU */
2993 EXPORT_SYMBOL(filemap_page_mkwrite);
2994 EXPORT_SYMBOL(generic_file_mmap);
2995 EXPORT_SYMBOL(generic_file_readonly_mmap);
2997 static struct page *wait_on_page_read(struct page *page)
2999 if (!IS_ERR(page)) {
3000 wait_on_page_locked(page);
3001 if (!PageUptodate(page)) {
3003 page = ERR_PTR(-EIO);
3009 static struct page *do_read_cache_page(struct address_space *mapping,
3011 int (*filler)(void *, struct page *),
3018 page = find_get_page(mapping, index);
3020 page = __page_cache_alloc(gfp);
3022 return ERR_PTR(-ENOMEM);
3023 err = add_to_page_cache_lru(page, mapping, index, gfp);
3024 if (unlikely(err)) {
3028 /* Presumably ENOMEM for xarray node */
3029 return ERR_PTR(err);
3034 err = filler(data, page);
3036 err = mapping->a_ops->readpage(data, page);
3040 return ERR_PTR(err);
3043 page = wait_on_page_read(page);
3048 if (PageUptodate(page))
3052 * Page is not up to date and may be locked due to one of the following
3053 * case a: Page is being filled and the page lock is held
3054 * case b: Read/write error clearing the page uptodate status
3055 * case c: Truncation in progress (page locked)
3056 * case d: Reclaim in progress
3058 * Case a, the page will be up to date when the page is unlocked.
3059 * There is no need to serialise on the page lock here as the page
3060 * is pinned so the lock gives no additional protection. Even if the
3061 * page is truncated, the data is still valid if PageUptodate as
3062 * it's a race vs truncate race.
3063 * Case b, the page will not be up to date
3064 * Case c, the page may be truncated but in itself, the data may still
3065 * be valid after IO completes as it's a read vs truncate race. The
3066 * operation must restart if the page is not uptodate on unlock but
3067 * otherwise serialising on page lock to stabilise the mapping gives
3068 * no additional guarantees to the caller as the page lock is
3069 * released before return.
3070 * Case d, similar to truncation. If reclaim holds the page lock, it
3071 * will be a race with remove_mapping that determines if the mapping
3072 * is valid on unlock but otherwise the data is valid and there is
3073 * no need to serialise with page lock.
3075 * As the page lock gives no additional guarantee, we optimistically
3076 * wait on the page to be unlocked and check if it's up to date and
3077 * use the page if it is. Otherwise, the page lock is required to
3078 * distinguish between the different cases. The motivation is that we
3079 * avoid spurious serialisations and wakeups when multiple processes
3080 * wait on the same page for IO to complete.
3082 wait_on_page_locked(page);
3083 if (PageUptodate(page))
3086 /* Distinguish between all the cases under the safety of the lock */
3089 /* Case c or d, restart the operation */
3090 if (!page->mapping) {
3096 /* Someone else locked and filled the page in a very small window */
3097 if (PageUptodate(page)) {
3103 * A previous I/O error may have been due to temporary
3105 * Clear page error before actual read, PG_error will be
3106 * set again if read page fails.
3108 ClearPageError(page);
3112 mark_page_accessed(page);
3117 * read_cache_page - read into page cache, fill it if needed
3118 * @mapping: the page's address_space
3119 * @index: the page index
3120 * @filler: function to perform the read
3121 * @data: first arg to filler(data, page) function, often left as NULL
3123 * Read into the page cache. If a page already exists, and PageUptodate() is
3124 * not set, try to fill the page and wait for it to become unlocked.
3126 * If the page does not get brought uptodate, return -EIO.
3128 * Return: up to date page on success, ERR_PTR() on failure.
3130 struct page *read_cache_page(struct address_space *mapping,
3132 int (*filler)(void *, struct page *),
3135 return do_read_cache_page(mapping, index, filler, data,
3136 mapping_gfp_mask(mapping));
3138 EXPORT_SYMBOL(read_cache_page);
3141 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
3142 * @mapping: the page's address_space
3143 * @index: the page index
3144 * @gfp: the page allocator flags to use if allocating
3146 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
3147 * any new page allocations done using the specified allocation flags.
3149 * If the page does not get brought uptodate, return -EIO.
3151 * Return: up to date page on success, ERR_PTR() on failure.
3153 struct page *read_cache_page_gfp(struct address_space *mapping,
3157 return do_read_cache_page(mapping, index, NULL, NULL, gfp);
3159 EXPORT_SYMBOL(read_cache_page_gfp);
3161 int pagecache_write_begin(struct file *file, struct address_space *mapping,
3162 loff_t pos, unsigned len, unsigned flags,
3163 struct page **pagep, void **fsdata)
3165 const struct address_space_operations *aops = mapping->a_ops;
3167 return aops->write_begin(file, mapping, pos, len, flags,
3170 EXPORT_SYMBOL(pagecache_write_begin);
3172 int pagecache_write_end(struct file *file, struct address_space *mapping,
3173 loff_t pos, unsigned len, unsigned copied,
3174 struct page *page, void *fsdata)
3176 const struct address_space_operations *aops = mapping->a_ops;
3178 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
3180 EXPORT_SYMBOL(pagecache_write_end);
3183 * Warn about a page cache invalidation failure during a direct I/O write.
3185 void dio_warn_stale_pagecache(struct file *filp)
3187 static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
3189 struct inode *inode = file_inode(filp);
3192 errseq_set(&inode->i_mapping->wb_err, -EIO);
3193 if (__ratelimit(&_rs)) {
3194 path = file_path(filp, pathname, sizeof(pathname));
3197 pr_crit("Page cache invalidation failure on direct I/O. Possible data corruption due to collision with buffered I/O!\n");
3198 pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
3204 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
3206 struct file *file = iocb->ki_filp;
3207 struct address_space *mapping = file->f_mapping;
3208 struct inode *inode = mapping->host;
3209 loff_t pos = iocb->ki_pos;
3214 write_len = iov_iter_count(from);
3215 end = (pos + write_len - 1) >> PAGE_SHIFT;
3217 if (iocb->ki_flags & IOCB_NOWAIT) {
3218 /* If there are pages to writeback, return */
3219 if (filemap_range_has_page(inode->i_mapping, pos,
3220 pos + write_len - 1))
3223 written = filemap_write_and_wait_range(mapping, pos,
3224 pos + write_len - 1);
3230 * After a write we want buffered reads to be sure to go to disk to get
3231 * the new data. We invalidate clean cached page from the region we're
3232 * about to write. We do this *before* the write so that we can return
3233 * without clobbering -EIOCBQUEUED from ->direct_IO().
3235 written = invalidate_inode_pages2_range(mapping,
3236 pos >> PAGE_SHIFT, end);
3238 * If a page can not be invalidated, return 0 to fall back
3239 * to buffered write.
3242 if (written == -EBUSY)
3247 written = mapping->a_ops->direct_IO(iocb, from);
3250 * Finally, try again to invalidate clean pages which might have been
3251 * cached by non-direct readahead, or faulted in by get_user_pages()
3252 * if the source of the write was an mmap'ed region of the file
3253 * we're writing. Either one is a pretty crazy thing to do,
3254 * so we don't support it 100%. If this invalidation
3255 * fails, tough, the write still worked...
3257 * Most of the time we do not need this since dio_complete() will do
3258 * the invalidation for us. However there are some file systems that
3259 * do not end up with dio_complete() being called, so let's not break
3260 * them by removing it completely.
3262 * Noticeable example is a blkdev_direct_IO().
3264 * Skip invalidation for async writes or if mapping has no pages.
3266 if (written > 0 && mapping->nrpages &&
3267 invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT, end))
3268 dio_warn_stale_pagecache(file);
3272 write_len -= written;
3273 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3274 i_size_write(inode, pos);
3275 mark_inode_dirty(inode);
3279 iov_iter_revert(from, write_len - iov_iter_count(from));
3283 EXPORT_SYMBOL(generic_file_direct_write);
3286 * Find or create a page at the given pagecache position. Return the locked
3287 * page. This function is specifically for buffered writes.
3289 struct page *grab_cache_page_write_begin(struct address_space *mapping,
3290 pgoff_t index, unsigned flags)
3293 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
3295 if (flags & AOP_FLAG_NOFS)
3296 fgp_flags |= FGP_NOFS;
3298 page = pagecache_get_page(mapping, index, fgp_flags,
3299 mapping_gfp_mask(mapping));
3301 wait_for_stable_page(page);
3305 EXPORT_SYMBOL(grab_cache_page_write_begin);
3307 ssize_t generic_perform_write(struct file *file,
3308 struct iov_iter *i, loff_t pos)
3310 struct address_space *mapping = file->f_mapping;
3311 const struct address_space_operations *a_ops = mapping->a_ops;
3313 ssize_t written = 0;
3314 unsigned int flags = 0;
3318 unsigned long offset; /* Offset into pagecache page */
3319 unsigned long bytes; /* Bytes to write to page */
3320 size_t copied; /* Bytes copied from user */
3323 offset = (pos & (PAGE_SIZE - 1));
3324 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3329 * Bring in the user page that we will copy from _first_.
3330 * Otherwise there's a nasty deadlock on copying from the
3331 * same page as we're writing to, without it being marked
3334 * Not only is this an optimisation, but it is also required
3335 * to check that the address is actually valid, when atomic
3336 * usercopies are used, below.
3338 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3343 if (fatal_signal_pending(current)) {
3348 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
3350 if (unlikely(status < 0))
3353 if (mapping_writably_mapped(mapping))
3354 flush_dcache_page(page);
3356 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
3357 flush_dcache_page(page);
3359 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3361 if (unlikely(status < 0))
3367 iov_iter_advance(i, copied);
3368 if (unlikely(copied == 0)) {
3370 * If we were unable to copy any data at all, we must
3371 * fall back to a single segment length write.
3373 * If we didn't fallback here, we could livelock
3374 * because not all segments in the iov can be copied at
3375 * once without a pagefault.
3377 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3378 iov_iter_single_seg_count(i));
3384 balance_dirty_pages_ratelimited(mapping);
3385 } while (iov_iter_count(i));
3387 return written ? written : status;
3389 EXPORT_SYMBOL(generic_perform_write);
3392 * __generic_file_write_iter - write data to a file
3393 * @iocb: IO state structure (file, offset, etc.)
3394 * @from: iov_iter with data to write
3396 * This function does all the work needed for actually writing data to a
3397 * file. It does all basic checks, removes SUID from the file, updates
3398 * modification times and calls proper subroutines depending on whether we
3399 * do direct IO or a standard buffered write.
3401 * It expects i_mutex to be grabbed unless we work on a block device or similar
3402 * object which does not need locking at all.
3404 * This function does *not* take care of syncing data in case of O_SYNC write.
3405 * A caller has to handle it. This is mainly due to the fact that we want to
3406 * avoid syncing under i_mutex.
3409 * * number of bytes written, even for truncated writes
3410 * * negative error code if no data has been written at all
3412 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3414 struct file *file = iocb->ki_filp;
3415 struct address_space * mapping = file->f_mapping;
3416 struct inode *inode = mapping->host;
3417 ssize_t written = 0;
3421 /* We can write back this queue in page reclaim */
3422 current->backing_dev_info = inode_to_bdi(inode);
3423 err = file_remove_privs(file);
3427 err = file_update_time(file);
3431 if (iocb->ki_flags & IOCB_DIRECT) {
3432 loff_t pos, endbyte;
3434 written = generic_file_direct_write(iocb, from);
3436 * If the write stopped short of completing, fall back to
3437 * buffered writes. Some filesystems do this for writes to
3438 * holes, for example. For DAX files, a buffered write will
3439 * not succeed (even if it did, DAX does not handle dirty
3440 * page-cache pages correctly).
3442 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
3445 status = generic_perform_write(file, from, pos = iocb->ki_pos);
3447 * If generic_perform_write() returned a synchronous error
3448 * then we want to return the number of bytes which were
3449 * direct-written, or the error code if that was zero. Note
3450 * that this differs from normal direct-io semantics, which
3451 * will return -EFOO even if some bytes were written.
3453 if (unlikely(status < 0)) {
3458 * We need to ensure that the page cache pages are written to
3459 * disk and invalidated to preserve the expected O_DIRECT
3462 endbyte = pos + status - 1;
3463 err = filemap_write_and_wait_range(mapping, pos, endbyte);
3465 iocb->ki_pos = endbyte + 1;
3467 invalidate_mapping_pages(mapping,
3469 endbyte >> PAGE_SHIFT);
3472 * We don't know how much we wrote, so just return
3473 * the number of bytes which were direct-written
3477 written = generic_perform_write(file, from, iocb->ki_pos);
3478 if (likely(written > 0))
3479 iocb->ki_pos += written;
3482 current->backing_dev_info = NULL;
3483 return written ? written : err;
3485 EXPORT_SYMBOL(__generic_file_write_iter);
3488 * generic_file_write_iter - write data to a file
3489 * @iocb: IO state structure
3490 * @from: iov_iter with data to write
3492 * This is a wrapper around __generic_file_write_iter() to be used by most
3493 * filesystems. It takes care of syncing the file in case of O_SYNC file
3494 * and acquires i_mutex as needed.
3496 * * negative error code if no data has been written at all of
3497 * vfs_fsync_range() failed for a synchronous write
3498 * * number of bytes written, even for truncated writes
3500 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3502 struct file *file = iocb->ki_filp;
3503 struct inode *inode = file->f_mapping->host;
3507 ret = generic_write_checks(iocb, from);
3509 ret = __generic_file_write_iter(iocb, from);
3510 inode_unlock(inode);
3513 ret = generic_write_sync(iocb, ret);
3516 EXPORT_SYMBOL(generic_file_write_iter);
3519 * try_to_release_page() - release old fs-specific metadata on a page
3521 * @page: the page which the kernel is trying to free
3522 * @gfp_mask: memory allocation flags (and I/O mode)
3524 * The address_space is to try to release any data against the page
3525 * (presumably at page->private).
3527 * This may also be called if PG_fscache is set on a page, indicating that the
3528 * page is known to the local caching routines.
3530 * The @gfp_mask argument specifies whether I/O may be performed to release
3531 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
3533 * Return: %1 if the release was successful, otherwise return zero.
3535 int try_to_release_page(struct page *page, gfp_t gfp_mask)
3537 struct address_space * const mapping = page->mapping;
3539 BUG_ON(!PageLocked(page));
3540 if (PageWriteback(page))
3543 if (mapping && mapping->a_ops->releasepage)
3544 return mapping->a_ops->releasepage(page, gfp_mask);
3545 return try_to_free_buffers(page);
3548 EXPORT_SYMBOL(try_to_release_page);