blob: 580c1b90b6057a534d387c34c160e7c68a55348d [file] [log] [blame]
Thomas Gleixner457c8992019-05-19 13:08:55 +01001// SPDX-License-Identifier: GPL-2.0-only
Linus Torvalds1da177e2005-04-16 15:20:36 -07002/*
3 * linux/mm/filemap.c
4 *
5 * Copyright (C) 1994-1999 Linus Torvalds
6 */
7
8/*
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)
12 */
Paul Gortmakerb95f1b312011-10-16 02:01:52 -040013#include <linux/export.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070014#include <linux/compiler.h>
Ross Zwislerf9fe48b2016-01-22 15:10:40 -080015#include <linux/dax.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070016#include <linux/fs.h>
Ingo Molnar3f07c012017-02-08 18:51:30 +010017#include <linux/sched/signal.h>
Hiro Yoshiokac22ce142006-06-23 02:04:16 -070018#include <linux/uaccess.h>
Randy.Dunlapc59ede72006-01-11 12:17:46 -080019#include <linux/capability.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070020#include <linux/kernel_stat.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090021#include <linux/gfp.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070022#include <linux/mm.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>
Josef Bacikcfcbfb12019-05-13 17:21:04 -070028#include <linux/error-injection.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070029#include <linux/hash.h>
30#include <linux/writeback.h>
Linus Torvalds53253382007-10-18 14:47:32 -070031#include <linux/backing-dev.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070032#include <linux/pagevec.h>
33#include <linux/blkdev.h>
34#include <linux/security.h>
Paul Jackson44110fe2006-03-24 03:16:04 -080035#include <linux/cpuset.h>
Johannes Weiner00501b52014-08-08 14:19:20 -070036#include <linux/hugetlb.h>
Balbir Singh8a9f3cc2008-02-07 00:13:53 -080037#include <linux/memcontrol.h>
Dan Magenheimerc515e1f2011-05-26 10:01:43 -060038#include <linux/cleancache.h>
Mel Gormanc7df8ad2017-11-15 17:37:41 -080039#include <linux/shmem_fs.h>
Kirill A. Shutemovf1820362014-04-07 15:37:19 -070040#include <linux/rmap.h>
Johannes Weinerb1d29ba2018-10-26 15:06:08 -070041#include <linux/delayacct.h>
Johannes Weinereb414682018-10-26 15:06:27 -070042#include <linux/psi.h>
Ben Dooksd0e6a582019-10-18 20:20:20 -070043#include <linux/ramfs.h>
Yang Shib9306a72020-08-06 23:19:55 -070044#include <linux/page_idle.h>
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +030045#include <asm/pgalloc.h>
Will Deacon906d3502021-02-10 11:15:11 +000046#include <asm/tlbflush.h>
Nick Piggin0f8053a2006-03-22 00:08:33 -080047#include "internal.h"
48
Robert Jarzmikfe0bfaa2013-04-29 15:06:10 -070049#define CREATE_TRACE_POINTS
50#include <trace/events/filemap.h>
51
Chiawei Wangdb158b42021-02-18 10:47:37 +080052#undef CREATE_TRACE_POINTS
53#include <trace/hooks/mm.h>
54
Linus Torvalds1da177e2005-04-16 15:20:36 -070055/*
Linus Torvalds1da177e2005-04-16 15:20:36 -070056 * FIXME: remove all knowledge of the buffer layer from the core VM
57 */
Jan Kara148f9482009-08-17 19:52:36 +020058#include <linux/buffer_head.h> /* for try_to_free_buffers */
Linus Torvalds1da177e2005-04-16 15:20:36 -070059
Linus Torvalds1da177e2005-04-16 15:20:36 -070060#include <asm/mman.h>
61
62/*
63 * Shared mappings implemented 30.11.1994. It's not fully working yet,
64 * though.
65 *
66 * Shared mappings now work. 15.8.1995 Bruno.
67 *
68 * finished 'unifying' the page and buffer cache and SMP-threaded the
69 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
70 *
71 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
72 */
73
74/*
75 * Lock ordering:
76 *
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080077 * ->i_mmap_rwsem (truncate_pagecache)
Linus Torvalds1da177e2005-04-16 15:20:36 -070078 * ->private_lock (__free_pte->__set_page_dirty_buffers)
Hugh Dickins5d337b92005-09-03 15:54:41 -070079 * ->swap_lock (exclusive_swap_page, others)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -070080 * ->i_pages lock
Linus Torvalds1da177e2005-04-16 15:20:36 -070081 *
Jes Sorensen1b1dcc12006-01-09 15:59:24 -080082 * ->i_mutex
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080083 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
Linus Torvalds1da177e2005-04-16 15:20:36 -070084 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -070085 * ->mmap_lock
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080086 * ->i_mmap_rwsem
Hugh Dickinsb8072f02005-10-29 18:16:41 -070087 * ->page_table_lock or pte_lock (various, mainly in memory.c)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -070088 * ->i_pages lock (arch-dependent flush_dcache_mmap_lock)
Linus Torvalds1da177e2005-04-16 15:20:36 -070089 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -070090 * ->mmap_lock
Linus Torvalds1da177e2005-04-16 15:20:36 -070091 * ->lock_page (access_process_vm)
92 *
Al Viroccad2362014-02-11 22:36:48 -050093 * ->i_mutex (generic_perform_write)
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -070094 * ->mmap_lock (fault_in_pages_readable->do_page_fault)
Linus Torvalds1da177e2005-04-16 15:20:36 -070095 *
Christoph Hellwigf758eea2011-04-21 18:19:44 -060096 * bdi->wb.list_lock
Dave Chinnera66979a2011-03-22 22:23:41 +110097 * sb_lock (fs/fs-writeback.c)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -070098 * ->i_pages lock (__sync_single_inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -070099 *
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -0800100 * ->i_mmap_rwsem
Linus Torvalds1da177e2005-04-16 15:20:36 -0700101 * ->anon_vma.lock (vma_adjust)
102 *
103 * ->anon_vma.lock
Hugh Dickinsb8072f02005-10-29 18:16:41 -0700104 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700105 *
Hugh Dickinsb8072f02005-10-29 18:16:41 -0700106 * ->page_table_lock or pte_lock
Hugh Dickins5d337b92005-09-03 15:54:41 -0700107 * ->swap_lock (try_to_unmap_one)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700108 * ->private_lock (try_to_unmap_one)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700109 * ->i_pages lock (try_to_unmap_one)
Andrey Ryabininf4b7e272019-03-05 15:49:39 -0800110 * ->pgdat->lru_lock (follow_page->mark_page_accessed)
111 * ->pgdat->lru_lock (check_pte_range->isolate_lru_page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700112 * ->private_lock (page_remove_rmap->set_page_dirty)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700113 * ->i_pages lock (page_remove_rmap->set_page_dirty)
Christoph Hellwigf758eea2011-04-21 18:19:44 -0600114 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
Dave Chinner250df6e2011-03-22 22:23:36 +1100115 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
Johannes Weiner81f8c3a2016-03-15 14:57:04 -0700116 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
Christoph Hellwigf758eea2011-04-21 18:19:44 -0600117 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
Dave Chinner250df6e2011-03-22 22:23:36 +1100118 * ->inode->i_lock (zap_pte_range->set_page_dirty)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700119 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
120 *
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -0800121 * ->i_mmap_rwsem
Andi Kleen9a3c5312012-03-21 16:34:09 -0700122 * ->tasklist_lock (memory_failure, collect_procs_ao)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700123 */
124
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500125static void page_cache_delete(struct address_space *mapping,
Johannes Weiner91b0abe2014-04-03 14:47:49 -0700126 struct page *page, void *shadow)
127{
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500128 XA_STATE(xas, &mapping->i_pages, page->index);
129 unsigned int nr = 1;
Kirill A. Shutemovc70b6472016-12-12 16:43:17 -0800130
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500131 mapping_set_update(&xas, mapping);
132
133 /* hugetlb pages are represented by a single entry in the xarray */
134 if (!PageHuge(page)) {
135 xas_set_order(&xas, page->index, compound_order(page));
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -0700136 nr = compound_nr(page);
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500137 }
Johannes Weiner91b0abe2014-04-03 14:47:49 -0700138
Kirill A. Shutemov83929372016-07-26 15:26:04 -0700139 VM_BUG_ON_PAGE(!PageLocked(page), page);
140 VM_BUG_ON_PAGE(PageTail(page), page);
141 VM_BUG_ON_PAGE(nr != 1 && shadow, page);
Johannes Weiner449dd692014-04-03 14:47:56 -0700142
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500143 xas_store(&xas, shadow);
144 xas_init_marks(&xas);
Johannes Weinerd3798ae2016-10-04 22:02:08 +0200145
Jan Kara23006382017-11-15 17:37:26 -0800146 page->mapping = NULL;
147 /* Leave page->index set: truncation lookup relies upon it */
148
Johannes Weinerd3798ae2016-10-04 22:02:08 +0200149 if (shadow) {
150 mapping->nrexceptional += nr;
151 /*
152 * Make sure the nrexceptional update is committed before
153 * the nrpages update so that final truncate racing
154 * with reclaim does not see both counters 0 at the
155 * same time and miss a shadow entry.
156 */
157 smp_wmb();
158 }
159 mapping->nrpages -= nr;
Johannes Weiner91b0abe2014-04-03 14:47:49 -0700160}
161
Jan Kara5ecc4d82017-11-15 17:37:29 -0800162static void unaccount_page_cache_page(struct address_space *mapping,
163 struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700164{
Jan Kara5ecc4d82017-11-15 17:37:29 -0800165 int nr;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700166
Dan Magenheimerc515e1f2011-05-26 10:01:43 -0600167 /*
168 * if we're uptodate, flush out into the cleancache, otherwise
169 * invalidate any existing cleancache entries. We can't leave
170 * stale data around in the cleancache once our page is gone
171 */
172 if (PageUptodate(page) && PageMappedToDisk(page))
173 cleancache_put_page(page);
174 else
Dan Magenheimer31677602011-09-21 11:56:28 -0400175 cleancache_invalidate_page(mapping, page);
Dan Magenheimerc515e1f2011-05-26 10:01:43 -0600176
Kirill A. Shutemov83929372016-07-26 15:26:04 -0700177 VM_BUG_ON_PAGE(PageTail(page), page);
Hugh Dickins06b241f2016-03-09 14:08:07 -0800178 VM_BUG_ON_PAGE(page_mapped(page), page);
179 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
180 int mapcount;
181
182 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
183 current->comm, page_to_pfn(page));
184 dump_page(page, "still mapped when deleted");
185 dump_stack();
186 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
187
188 mapcount = page_mapcount(page);
189 if (mapping_exiting(mapping) &&
190 page_count(page) >= mapcount + 2) {
191 /*
192 * All vmas have already been torn down, so it's
193 * a good bet that actually the page is unmapped,
194 * and we'd prefer not to leak it: if we're wrong,
195 * some other bad page check should catch it later.
196 */
197 page_mapcount_reset(page);
Joonsoo Kim6d061f92016-05-19 17:10:46 -0700198 page_ref_sub(page, mapcount);
Hugh Dickins06b241f2016-03-09 14:08:07 -0800199 }
200 }
201
Jan Kara76253fb2017-11-15 17:37:22 -0800202 /* hugetlb pages do not participate in page cache accounting. */
Jan Kara5ecc4d82017-11-15 17:37:29 -0800203 if (PageHuge(page))
204 return;
Jan Kara76253fb2017-11-15 17:37:22 -0800205
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -0700206 nr = thp_nr_pages(page);
Jan Kara5ecc4d82017-11-15 17:37:29 -0800207
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700208 __mod_lruvec_page_state(page, NR_FILE_PAGES, -nr);
Jan Kara5ecc4d82017-11-15 17:37:29 -0800209 if (PageSwapBacked(page)) {
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700210 __mod_lruvec_page_state(page, NR_SHMEM, -nr);
Jan Kara5ecc4d82017-11-15 17:37:29 -0800211 if (PageTransHuge(page))
212 __dec_node_page_state(page, NR_SHMEM_THPS);
Song Liu99cb0db2019-09-23 15:38:00 -0700213 } else if (PageTransHuge(page)) {
214 __dec_node_page_state(page, NR_FILE_THPS);
Song Liu09d91cd2019-09-23 15:38:03 -0700215 filemap_nr_thps_dec(mapping);
Jan Kara76253fb2017-11-15 17:37:22 -0800216 }
Jan Kara5ecc4d82017-11-15 17:37:29 -0800217
218 /*
219 * At this point page must be either written or cleaned by
220 * truncate. Dirty page here signals a bug and loss of
221 * unwritten data.
222 *
223 * This fixes dirty accounting after removing the page entirely
224 * but leaves PageDirty set: it has no effect for truncated
225 * page and anyway will be cleared before returning page into
226 * buddy allocator.
227 */
228 if (WARN_ON_ONCE(PageDirty(page)))
229 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
230}
231
232/*
233 * Delete a page from the page cache and free it. Caller has to make
234 * sure the page is locked and that nobody else uses it - or that usage
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700235 * is safe. The caller must hold the i_pages lock.
Jan Kara5ecc4d82017-11-15 17:37:29 -0800236 */
237void __delete_from_page_cache(struct page *page, void *shadow)
238{
239 struct address_space *mapping = page->mapping;
240
241 trace_mm_filemap_delete_from_page_cache(page);
242
243 unaccount_page_cache_page(mapping, page);
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500244 page_cache_delete(mapping, page, shadow);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700245}
246
Jan Kara59c66c52017-11-15 17:37:18 -0800247static void page_cache_free_page(struct address_space *mapping,
248 struct page *page)
249{
250 void (*freepage)(struct page *);
251
252 freepage = mapping->a_ops->freepage;
253 if (freepage)
254 freepage(page);
255
256 if (PageTransHuge(page) && !PageHuge(page)) {
Matthew Wilcox (Oracle)887b22c2020-10-15 20:05:23 -0700257 page_ref_sub(page, thp_nr_pages(page));
Jan Kara59c66c52017-11-15 17:37:18 -0800258 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
259 } else {
260 put_page(page);
261 }
262}
263
Minchan Kim702cfbf2011-03-22 16:32:43 -0700264/**
265 * delete_from_page_cache - delete page from page cache
266 * @page: the page which the kernel is trying to remove from page cache
267 *
268 * This must be called only on pages that have been verified to be in the page
269 * cache and locked. It will never put the page into the free list, the caller
270 * has a reference on the page.
271 */
272void delete_from_page_cache(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700273{
Kirill A. Shutemov83929372016-07-26 15:26:04 -0700274 struct address_space *mapping = page_mapping(page);
Greg Thelenc4843a72015-05-22 17:13:16 -0400275 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700276
Matt Mackallcd7619d2005-05-01 08:59:01 -0700277 BUG_ON(!PageLocked(page));
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700278 xa_lock_irqsave(&mapping->i_pages, flags);
Johannes Weiner62cccb82016-03-15 14:57:22 -0700279 __delete_from_page_cache(page, NULL);
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700280 xa_unlock_irqrestore(&mapping->i_pages, flags);
Linus Torvalds6072d132010-12-01 13:35:19 -0500281
Jan Kara59c66c52017-11-15 17:37:18 -0800282 page_cache_free_page(mapping, page);
Minchan Kim97cecb52011-03-22 16:30:53 -0700283}
284EXPORT_SYMBOL(delete_from_page_cache);
285
Jan Karaaa65c292017-11-15 17:37:33 -0800286/*
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500287 * page_cache_delete_batch - delete several pages from page cache
Jan Karaaa65c292017-11-15 17:37:33 -0800288 * @mapping: the mapping to which pages belong
289 * @pvec: pagevec with pages to delete
290 *
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700291 * The function walks over mapping->i_pages and removes pages passed in @pvec
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700292 * from the mapping. The function expects @pvec to be sorted by page index
293 * and is optimised for it to be dense.
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700294 * It tolerates holes in @pvec (mapping entries at those indices are not
Jan Karaaa65c292017-11-15 17:37:33 -0800295 * modified). The function expects only THP head pages to be present in the
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700296 * @pvec.
Jan Karaaa65c292017-11-15 17:37:33 -0800297 *
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700298 * The function expects the i_pages lock to be held.
Jan Karaaa65c292017-11-15 17:37:33 -0800299 */
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500300static void page_cache_delete_batch(struct address_space *mapping,
Jan Karaaa65c292017-11-15 17:37:33 -0800301 struct pagevec *pvec)
302{
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500303 XA_STATE(xas, &mapping->i_pages, pvec->pages[0]->index);
Jan Karaaa65c292017-11-15 17:37:33 -0800304 int total_pages = 0;
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700305 int i = 0;
Jan Karaaa65c292017-11-15 17:37:33 -0800306 struct page *page;
Jan Karaaa65c292017-11-15 17:37:33 -0800307
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500308 mapping_set_update(&xas, mapping);
309 xas_for_each(&xas, page, ULONG_MAX) {
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700310 if (i >= pagevec_count(pvec))
Jan Karaaa65c292017-11-15 17:37:33 -0800311 break;
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700312
313 /* A swap/dax/shadow entry got inserted? Skip it. */
Matthew Wilcox3159f942017-11-03 13:30:42 -0400314 if (xa_is_value(page))
Jan Karaaa65c292017-11-15 17:37:33 -0800315 continue;
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700316 /*
317 * A page got inserted in our range? Skip it. We have our
318 * pages locked so they are protected from being removed.
319 * If we see a page whose index is higher than ours, it
320 * means our page has been removed, which shouldn't be
321 * possible because we're holding the PageLock.
322 */
323 if (page != pvec->pages[i]) {
324 VM_BUG_ON_PAGE(page->index > pvec->pages[i]->index,
325 page);
326 continue;
Linus Torvalds69bf4b62019-07-05 19:55:18 -0700327 }
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700328
329 WARN_ON_ONCE(!PageLocked(page));
330
331 if (page->index == xas.xa_index)
332 page->mapping = NULL;
333 /* Leave page->index set: truncation lookup relies on it */
334
335 /*
336 * Move to the next page in the vector if this is a regular
337 * page or the index is of the last sub-page of this compound
338 * page.
339 */
340 if (page->index + compound_nr(page) - 1 == xas.xa_index)
341 i++;
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500342 xas_store(&xas, NULL);
Jan Karaaa65c292017-11-15 17:37:33 -0800343 total_pages++;
344 }
345 mapping->nrpages -= total_pages;
346}
347
348void delete_from_page_cache_batch(struct address_space *mapping,
349 struct pagevec *pvec)
350{
351 int i;
352 unsigned long flags;
353
354 if (!pagevec_count(pvec))
355 return;
356
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700357 xa_lock_irqsave(&mapping->i_pages, flags);
Jan Karaaa65c292017-11-15 17:37:33 -0800358 for (i = 0; i < pagevec_count(pvec); i++) {
359 trace_mm_filemap_delete_from_page_cache(pvec->pages[i]);
360
361 unaccount_page_cache_page(mapping, pvec->pages[i]);
362 }
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500363 page_cache_delete_batch(mapping, pvec);
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700364 xa_unlock_irqrestore(&mapping->i_pages, flags);
Jan Karaaa65c292017-11-15 17:37:33 -0800365
366 for (i = 0; i < pagevec_count(pvec); i++)
367 page_cache_free_page(mapping, pvec->pages[i]);
368}
369
Miklos Szeredid72d9e22016-07-29 14:10:57 +0200370int filemap_check_errors(struct address_space *mapping)
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700371{
372 int ret = 0;
373 /* Check for outstanding write errors */
Jens Axboe7fcbbaf2014-05-22 11:54:16 -0700374 if (test_bit(AS_ENOSPC, &mapping->flags) &&
375 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700376 ret = -ENOSPC;
Jens Axboe7fcbbaf2014-05-22 11:54:16 -0700377 if (test_bit(AS_EIO, &mapping->flags) &&
378 test_and_clear_bit(AS_EIO, &mapping->flags))
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700379 ret = -EIO;
380 return ret;
381}
Miklos Szeredid72d9e22016-07-29 14:10:57 +0200382EXPORT_SYMBOL(filemap_check_errors);
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700383
Jeff Layton76341ca2017-07-06 07:02:22 -0400384static int filemap_check_and_keep_errors(struct address_space *mapping)
385{
386 /* Check for outstanding write errors */
387 if (test_bit(AS_EIO, &mapping->flags))
388 return -EIO;
389 if (test_bit(AS_ENOSPC, &mapping->flags))
390 return -ENOSPC;
391 return 0;
392}
393
Linus Torvalds1da177e2005-04-16 15:20:36 -0700394/**
Randy Dunlap485bb992006-06-23 02:03:49 -0700395 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
Martin Waitz67be2dd2005-05-01 08:59:26 -0700396 * @mapping: address space structure to write
397 * @start: offset in bytes where the range starts
Andrew Morton469eb4d2006-03-24 03:17:45 -0800398 * @end: offset in bytes where the range ends (inclusive)
Martin Waitz67be2dd2005-05-01 08:59:26 -0700399 * @sync_mode: enable synchronous operation
Linus Torvalds1da177e2005-04-16 15:20:36 -0700400 *
Randy Dunlap485bb992006-06-23 02:03:49 -0700401 * Start writeback against all of a mapping's dirty pages that lie
402 * within the byte offsets <start, end> inclusive.
403 *
Linus Torvalds1da177e2005-04-16 15:20:36 -0700404 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
Randy Dunlap485bb992006-06-23 02:03:49 -0700405 * opposed to a regular memory cleansing writeback. The difference between
Linus Torvalds1da177e2005-04-16 15:20:36 -0700406 * these two operations is that if a dirty page/buffer is encountered, it must
407 * be waited upon, and not just skipped over.
Mike Rapoporta862f682019-03-05 15:48:42 -0800408 *
409 * Return: %0 on success, negative error code otherwise.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700410 */
Andrew Mortonebcf28e2006-03-24 03:18:04 -0800411int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
412 loff_t end, int sync_mode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700413{
414 int ret;
415 struct writeback_control wbc = {
416 .sync_mode = sync_mode,
Nick Piggin05fe4782009-01-06 14:39:08 -0800417 .nr_to_write = LONG_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -0700418 .range_start = start,
419 .range_end = end,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700420 };
421
Christoph Hellwigf56753a2020-09-24 08:51:40 +0200422 if (!mapping_can_writeback(mapping) ||
Konstantin Khlebnikovc3aab9a02019-09-23 15:34:45 -0700423 !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700424 return 0;
425
Tejun Heob16b1de2015-06-02 08:39:48 -0600426 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700427 ret = do_writepages(mapping, &wbc);
Tejun Heob16b1de2015-06-02 08:39:48 -0600428 wbc_detach_inode(&wbc);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700429 return ret;
430}
431
432static inline int __filemap_fdatawrite(struct address_space *mapping,
433 int sync_mode)
434{
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -0700435 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700436}
437
438int filemap_fdatawrite(struct address_space *mapping)
439{
440 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
441}
442EXPORT_SYMBOL(filemap_fdatawrite);
443
Jan Karaf4c0a0f2008-07-11 19:27:31 -0400444int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
Andrew Mortonebcf28e2006-03-24 03:18:04 -0800445 loff_t end)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700446{
447 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
448}
Jan Karaf4c0a0f2008-07-11 19:27:31 -0400449EXPORT_SYMBOL(filemap_fdatawrite_range);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700450
Randy Dunlap485bb992006-06-23 02:03:49 -0700451/**
452 * filemap_flush - mostly a non-blocking flush
453 * @mapping: target address_space
454 *
Linus Torvalds1da177e2005-04-16 15:20:36 -0700455 * This is a mostly non-blocking flush. Not suitable for data-integrity
456 * purposes - I/O may not be started against all dirty pages.
Mike Rapoporta862f682019-03-05 15:48:42 -0800457 *
458 * Return: %0 on success, negative error code otherwise.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700459 */
460int filemap_flush(struct address_space *mapping)
461{
462 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
463}
464EXPORT_SYMBOL(filemap_flush);
465
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500466/**
467 * filemap_range_has_page - check if a page exists in range.
468 * @mapping: address space within which to check
469 * @start_byte: offset in bytes where the range starts
470 * @end_byte: offset in bytes where the range ends (inclusive)
471 *
472 * Find at least one page in the range supplied, usually used to check if
473 * direct writing in this range will trigger a writeback.
Mike Rapoporta862f682019-03-05 15:48:42 -0800474 *
475 * Return: %true if at least one page exists in the specified range,
476 * %false otherwise.
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500477 */
478bool filemap_range_has_page(struct address_space *mapping,
479 loff_t start_byte, loff_t end_byte)
480{
Jan Karaf7b68042017-09-06 16:21:40 -0700481 struct page *page;
Matthew Wilcox8fa8e532018-01-16 06:26:49 -0500482 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
483 pgoff_t max = end_byte >> PAGE_SHIFT;
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500484
485 if (end_byte < start_byte)
486 return false;
487
Matthew Wilcox8fa8e532018-01-16 06:26:49 -0500488 rcu_read_lock();
489 for (;;) {
490 page = xas_find(&xas, max);
491 if (xas_retry(&xas, page))
492 continue;
493 /* Shadow entries don't count */
494 if (xa_is_value(page))
495 continue;
496 /*
497 * We don't need to try to pin this page; we're about to
498 * release the RCU lock anyway. It is enough to know that
499 * there was a page here recently.
500 */
501 break;
502 }
503 rcu_read_unlock();
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500504
Matthew Wilcox8fa8e532018-01-16 06:26:49 -0500505 return page != NULL;
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500506}
507EXPORT_SYMBOL(filemap_range_has_page);
508
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400509static void __filemap_fdatawait_range(struct address_space *mapping,
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800510 loff_t start_byte, loff_t end_byte)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700511{
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300512 pgoff_t index = start_byte >> PAGE_SHIFT;
513 pgoff_t end = end_byte >> PAGE_SHIFT;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700514 struct pagevec pvec;
515 int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700516
Christoph Hellwig94004ed2009-09-30 22:16:33 +0200517 if (end_byte < start_byte)
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400518 return;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700519
Mel Gorman86679822017-11-15 17:37:52 -0800520 pagevec_init(&pvec);
Jan Kara312e9d22017-11-15 17:35:05 -0800521 while (index <= end) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700522 unsigned i;
523
Jan Kara312e9d22017-11-15 17:35:05 -0800524 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
Jan Kara67fd7072017-11-15 17:35:19 -0800525 end, PAGECACHE_TAG_WRITEBACK);
Jan Kara312e9d22017-11-15 17:35:05 -0800526 if (!nr_pages)
527 break;
528
Linus Torvalds1da177e2005-04-16 15:20:36 -0700529 for (i = 0; i < nr_pages; i++) {
530 struct page *page = pvec.pages[i];
531
Linus Torvalds1da177e2005-04-16 15:20:36 -0700532 wait_on_page_writeback(page);
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400533 ClearPageError(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700534 }
535 pagevec_release(&pvec);
536 cond_resched();
537 }
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800538}
539
540/**
541 * filemap_fdatawait_range - wait for writeback to complete
542 * @mapping: address space structure to wait for
543 * @start_byte: offset in bytes where the range starts
544 * @end_byte: offset in bytes where the range ends (inclusive)
545 *
546 * Walk the list of under-writeback pages of the given address space
547 * in the given range and wait for all of them. Check error status of
548 * the address space and return it.
549 *
550 * Since the error status of the address space is cleared by this function,
551 * callers are responsible for checking the return value and handling and/or
552 * reporting the error.
Mike Rapoporta862f682019-03-05 15:48:42 -0800553 *
554 * Return: error status of the address space.
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800555 */
556int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
557 loff_t end_byte)
558{
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400559 __filemap_fdatawait_range(mapping, start_byte, end_byte);
560 return filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700561}
Jan Karad3bccb6f2009-08-17 19:30:27 +0200562EXPORT_SYMBOL(filemap_fdatawait_range);
563
564/**
Ross Zwisleraa0bfcd2019-06-20 17:05:37 -0400565 * filemap_fdatawait_range_keep_errors - wait for writeback to complete
566 * @mapping: address space structure to wait for
567 * @start_byte: offset in bytes where the range starts
568 * @end_byte: offset in bytes where the range ends (inclusive)
569 *
570 * Walk the list of under-writeback pages of the given address space in the
571 * given range and wait for all of them. Unlike filemap_fdatawait_range(),
572 * this function does not clear error status of the address space.
573 *
574 * Use this function if callers don't handle errors themselves. Expected
575 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
576 * fsfreeze(8)
577 */
578int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
579 loff_t start_byte, loff_t end_byte)
580{
581 __filemap_fdatawait_range(mapping, start_byte, end_byte);
582 return filemap_check_and_keep_errors(mapping);
583}
584EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
585
586/**
Jeff Laytona823e452017-07-28 07:24:43 -0400587 * file_fdatawait_range - wait for writeback to complete
588 * @file: file pointing to address space structure to wait for
589 * @start_byte: offset in bytes where the range starts
590 * @end_byte: offset in bytes where the range ends (inclusive)
591 *
592 * Walk the list of under-writeback pages of the address space that file
593 * refers to, in the given range and wait for all of them. Check error
594 * status of the address space vs. the file->f_wb_err cursor and return it.
595 *
596 * Since the error status of the file is advanced by this function,
597 * callers are responsible for checking the return value and handling and/or
598 * reporting the error.
Mike Rapoporta862f682019-03-05 15:48:42 -0800599 *
600 * Return: error status of the address space vs. the file->f_wb_err cursor.
Jeff Laytona823e452017-07-28 07:24:43 -0400601 */
602int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
603{
604 struct address_space *mapping = file->f_mapping;
605
606 __filemap_fdatawait_range(mapping, start_byte, end_byte);
607 return file_check_and_advance_wb_err(file);
608}
609EXPORT_SYMBOL(file_fdatawait_range);
610
611/**
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800612 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
613 * @mapping: address space structure to wait for
614 *
615 * Walk the list of under-writeback pages of the given address space
616 * and wait for all of them. Unlike filemap_fdatawait(), this function
617 * does not clear error status of the address space.
618 *
619 * Use this function if callers don't handle errors themselves. Expected
620 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
621 * fsfreeze(8)
Mike Rapoporta862f682019-03-05 15:48:42 -0800622 *
623 * Return: error status of the address space.
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800624 */
Jeff Layton76341ca2017-07-06 07:02:22 -0400625int filemap_fdatawait_keep_errors(struct address_space *mapping)
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800626{
Jeff Laytonffb959b2017-07-31 10:29:38 -0400627 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
Jeff Layton76341ca2017-07-06 07:02:22 -0400628 return filemap_check_and_keep_errors(mapping);
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800629}
Jeff Layton76341ca2017-07-06 07:02:22 -0400630EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800631
Konstantin Khlebnikov875d91b2019-09-23 15:34:48 -0700632/* Returns true if writeback might be needed or already in progress. */
Jeff Layton9326c9b2017-07-26 10:21:11 -0400633static bool mapping_needs_writeback(struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700634{
Konstantin Khlebnikov875d91b2019-09-23 15:34:48 -0700635 if (dax_mapping(mapping))
636 return mapping->nrexceptional;
637
638 return mapping->nrpages;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700639}
Linus Torvalds1da177e2005-04-16 15:20:36 -0700640
Randy Dunlap485bb992006-06-23 02:03:49 -0700641/**
642 * filemap_write_and_wait_range - write out & wait on a file range
643 * @mapping: the address_space for the pages
644 * @lstart: offset in bytes where the range starts
645 * @lend: offset in bytes where the range ends (inclusive)
646 *
Andrew Morton469eb4d2006-03-24 03:17:45 -0800647 * Write out and wait upon file offsets lstart->lend, inclusive.
648 *
mchehab@s-opensource.com0e056eb2017-03-30 17:11:36 -0300649 * Note that @lend is inclusive (describes the last byte to be written) so
Andrew Morton469eb4d2006-03-24 03:17:45 -0800650 * that this function can be used to write to the very end-of-file (end = -1).
Mike Rapoporta862f682019-03-05 15:48:42 -0800651 *
652 * Return: error status of the address space.
Andrew Morton469eb4d2006-03-24 03:17:45 -0800653 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700654int filemap_write_and_wait_range(struct address_space *mapping,
655 loff_t lstart, loff_t lend)
656{
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800657 int err = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700658
Jeff Layton9326c9b2017-07-26 10:21:11 -0400659 if (mapping_needs_writeback(mapping)) {
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800660 err = __filemap_fdatawrite_range(mapping, lstart, lend,
661 WB_SYNC_ALL);
Ira Weinyddf8f372020-01-30 22:12:07 -0800662 /*
663 * Even if the above returned error, the pages may be
664 * written partially (e.g. -ENOSPC), so we wait for it.
665 * But the -EIO is special case, it may indicate the worst
666 * thing (e.g. bug) happened, so we avoid waiting for it.
667 */
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800668 if (err != -EIO) {
Christoph Hellwig94004ed2009-09-30 22:16:33 +0200669 int err2 = filemap_fdatawait_range(mapping,
670 lstart, lend);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800671 if (!err)
672 err = err2;
Jeff Laytoncbeaf952017-07-06 07:02:23 -0400673 } else {
674 /* Clear any previously stored errors */
675 filemap_check_errors(mapping);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800676 }
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700677 } else {
678 err = filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700679 }
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800680 return err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700681}
Chris Masonf6995582009-04-15 13:22:37 -0400682EXPORT_SYMBOL(filemap_write_and_wait_range);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700683
Jeff Layton5660e132017-07-06 07:02:25 -0400684void __filemap_set_wb_err(struct address_space *mapping, int err)
685{
Jeff Layton3acdfd22017-07-24 06:22:15 -0400686 errseq_t eseq = errseq_set(&mapping->wb_err, err);
Jeff Layton5660e132017-07-06 07:02:25 -0400687
688 trace_filemap_set_wb_err(mapping, eseq);
689}
690EXPORT_SYMBOL(__filemap_set_wb_err);
691
692/**
693 * file_check_and_advance_wb_err - report wb error (if any) that was previously
694 * and advance wb_err to current one
695 * @file: struct file on which the error is being reported
696 *
697 * When userland calls fsync (or something like nfsd does the equivalent), we
698 * want to report any writeback errors that occurred since the last fsync (or
699 * since the file was opened if there haven't been any).
700 *
701 * Grab the wb_err from the mapping. If it matches what we have in the file,
702 * then just quickly return 0. The file is all caught up.
703 *
704 * If it doesn't match, then take the mapping value, set the "seen" flag in
705 * it and try to swap it into place. If it works, or another task beat us
706 * to it with the new value, then update the f_wb_err and return the error
707 * portion. The error at this point must be reported via proper channels
708 * (a'la fsync, or NFS COMMIT operation, etc.).
709 *
710 * While we handle mapping->wb_err with atomic operations, the f_wb_err
711 * value is protected by the f_lock since we must ensure that it reflects
712 * the latest value swapped in for this file descriptor.
Mike Rapoporta862f682019-03-05 15:48:42 -0800713 *
714 * Return: %0 on success, negative error code otherwise.
Jeff Layton5660e132017-07-06 07:02:25 -0400715 */
716int file_check_and_advance_wb_err(struct file *file)
717{
718 int err = 0;
719 errseq_t old = READ_ONCE(file->f_wb_err);
720 struct address_space *mapping = file->f_mapping;
721
722 /* Locklessly handle the common case where nothing has changed */
723 if (errseq_check(&mapping->wb_err, old)) {
724 /* Something changed, must use slow path */
725 spin_lock(&file->f_lock);
726 old = file->f_wb_err;
727 err = errseq_check_and_advance(&mapping->wb_err,
728 &file->f_wb_err);
729 trace_file_check_and_advance_wb_err(file, old);
730 spin_unlock(&file->f_lock);
731 }
Jeff Laytonf4e222c2017-10-03 16:15:25 -0700732
733 /*
734 * We're mostly using this function as a drop in replacement for
735 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
736 * that the legacy code would have had on these flags.
737 */
738 clear_bit(AS_EIO, &mapping->flags);
739 clear_bit(AS_ENOSPC, &mapping->flags);
Jeff Layton5660e132017-07-06 07:02:25 -0400740 return err;
741}
742EXPORT_SYMBOL(file_check_and_advance_wb_err);
743
744/**
745 * file_write_and_wait_range - write out & wait on a file range
746 * @file: file pointing to address_space with pages
747 * @lstart: offset in bytes where the range starts
748 * @lend: offset in bytes where the range ends (inclusive)
749 *
750 * Write out and wait upon file offsets lstart->lend, inclusive.
751 *
752 * Note that @lend is inclusive (describes the last byte to be written) so
753 * that this function can be used to write to the very end-of-file (end = -1).
754 *
755 * After writing out and waiting on the data, we check and advance the
756 * f_wb_err cursor to the latest value, and return any errors detected there.
Mike Rapoporta862f682019-03-05 15:48:42 -0800757 *
758 * Return: %0 on success, negative error code otherwise.
Jeff Layton5660e132017-07-06 07:02:25 -0400759 */
760int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
761{
762 int err = 0, err2;
763 struct address_space *mapping = file->f_mapping;
764
Jeff Layton9326c9b2017-07-26 10:21:11 -0400765 if (mapping_needs_writeback(mapping)) {
Jeff Layton5660e132017-07-06 07:02:25 -0400766 err = __filemap_fdatawrite_range(mapping, lstart, lend,
767 WB_SYNC_ALL);
768 /* See comment of filemap_write_and_wait() */
769 if (err != -EIO)
770 __filemap_fdatawait_range(mapping, lstart, lend);
771 }
772 err2 = file_check_and_advance_wb_err(file);
773 if (!err)
774 err = err2;
775 return err;
776}
777EXPORT_SYMBOL(file_write_and_wait_range);
778
Randy Dunlap485bb992006-06-23 02:03:49 -0700779/**
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700780 * replace_page_cache_page - replace a pagecache page with a new one
781 * @old: page to be replaced
782 * @new: page to replace with
783 * @gfp_mask: allocation mode
784 *
785 * This function replaces a page in the pagecache with a new one. On
786 * success it acquires the pagecache reference for the new page and
787 * drops it for the old page. Both the old and new pages must be
788 * locked. This function does not add the new page to the LRU, the
789 * caller must do that.
790 *
Matthew Wilcox74d60952017-11-17 10:01:45 -0500791 * The remove + add is atomic. This function cannot fail.
Mike Rapoporta862f682019-03-05 15:48:42 -0800792 *
793 * Return: %0
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700794 */
795int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
796{
Matthew Wilcox74d60952017-11-17 10:01:45 -0500797 struct address_space *mapping = old->mapping;
798 void (*freepage)(struct page *) = mapping->a_ops->freepage;
799 pgoff_t offset = old->index;
800 XA_STATE(xas, &mapping->i_pages, offset);
801 unsigned long flags;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700802
Sasha Levin309381fea2014-01-23 15:52:54 -0800803 VM_BUG_ON_PAGE(!PageLocked(old), old);
804 VM_BUG_ON_PAGE(!PageLocked(new), new);
805 VM_BUG_ON_PAGE(new->mapping, new);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700806
Matthew Wilcox74d60952017-11-17 10:01:45 -0500807 get_page(new);
808 new->mapping = mapping;
809 new->index = offset;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700810
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700811 mem_cgroup_migrate(old, new);
812
Matthew Wilcox74d60952017-11-17 10:01:45 -0500813 xas_lock_irqsave(&xas, flags);
814 xas_store(&xas, new);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700815
Matthew Wilcox74d60952017-11-17 10:01:45 -0500816 old->mapping = NULL;
817 /* hugetlb pages do not participate in page cache accounting. */
818 if (!PageHuge(old))
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700819 __dec_lruvec_page_state(old, NR_FILE_PAGES);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500820 if (!PageHuge(new))
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700821 __inc_lruvec_page_state(new, NR_FILE_PAGES);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500822 if (PageSwapBacked(old))
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700823 __dec_lruvec_page_state(old, NR_SHMEM);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500824 if (PageSwapBacked(new))
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700825 __inc_lruvec_page_state(new, NR_SHMEM);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500826 xas_unlock_irqrestore(&xas, flags);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500827 if (freepage)
828 freepage(old);
829 put_page(old);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700830
Matthew Wilcox74d60952017-11-17 10:01:45 -0500831 return 0;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700832}
833EXPORT_SYMBOL_GPL(replace_page_cache_page);
834
Andrew Morton16c0cc02020-12-11 13:36:27 -0800835noinline int __add_to_page_cache_locked(struct page *page,
Alexei Starovoitov76cd6172020-08-27 15:01:10 -0700836 struct address_space *mapping,
Linus Torvaldsc4cf4982020-10-16 11:31:55 -0700837 pgoff_t offset, gfp_t gfp,
Alexei Starovoitov76cd6172020-08-27 15:01:10 -0700838 void **shadowp)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700839{
Matthew Wilcox74d60952017-11-17 10:01:45 -0500840 XA_STATE(xas, &mapping->i_pages, offset);
Johannes Weiner00501b52014-08-08 14:19:20 -0700841 int huge = PageHuge(page);
Nick Piggine2867812008-07-25 19:45:30 -0700842 int error;
Waiman Long032f8e02021-02-04 18:32:45 -0800843 bool charged = false;
Nick Piggine2867812008-07-25 19:45:30 -0700844
Sasha Levin309381fea2014-01-23 15:52:54 -0800845 VM_BUG_ON_PAGE(!PageLocked(page), page);
846 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500847 mapping_set_update(&xas, mapping);
Nick Piggine2867812008-07-25 19:45:30 -0700848
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300849 get_page(page);
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700850 page->mapping = mapping;
851 page->index = offset;
852
Johannes Weiner3fea5a42020-06-03 16:01:41 -0700853 if (!huge) {
Matthew Wilcox (Oracle)198b62f2020-10-15 20:05:20 -0700854 error = mem_cgroup_charge(page, current->mm, gfp);
Johannes Weiner3fea5a42020-06-03 16:01:41 -0700855 if (error)
856 goto error;
Waiman Long032f8e02021-02-04 18:32:45 -0800857 charged = true;
Johannes Weiner3fea5a42020-06-03 16:01:41 -0700858 }
859
Matthew Wilcox (Oracle)198b62f2020-10-15 20:05:20 -0700860 gfp &= GFP_RECLAIM_MASK;
861
Matthew Wilcox74d60952017-11-17 10:01:45 -0500862 do {
Matthew Wilcox (Oracle)198b62f2020-10-15 20:05:20 -0700863 unsigned int order = xa_get_order(xas.xa, xas.xa_index);
864 void *entry, *old = NULL;
865
866 if (order > thp_order(page))
867 xas_split_alloc(&xas, xa_load(xas.xa, xas.xa_index),
868 order, gfp);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500869 xas_lock_irq(&xas);
Matthew Wilcox (Oracle)198b62f2020-10-15 20:05:20 -0700870 xas_for_each_conflict(&xas, entry) {
871 old = entry;
872 if (!xa_is_value(entry)) {
873 xas_set_err(&xas, -EEXIST);
874 goto unlock;
875 }
876 }
877
878 if (old) {
879 if (shadowp)
880 *shadowp = old;
881 /* entry may have been split before we acquired lock */
882 order = xa_get_order(xas.xa, xas.xa_index);
883 if (order > thp_order(page)) {
884 xas_split(&xas, old, order);
885 xas_reset(&xas);
886 }
887 }
888
Matthew Wilcox74d60952017-11-17 10:01:45 -0500889 xas_store(&xas, page);
890 if (xas_error(&xas))
891 goto unlock;
Michal Hocko4165b9b2015-06-24 16:57:24 -0700892
Matthew Wilcox (Oracle)198b62f2020-10-15 20:05:20 -0700893 if (old)
Matthew Wilcox74d60952017-11-17 10:01:45 -0500894 mapping->nrexceptional--;
Matthew Wilcox74d60952017-11-17 10:01:45 -0500895 mapping->nrpages++;
896
897 /* hugetlb pages do not participate in page cache accounting */
898 if (!huge)
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700899 __inc_lruvec_page_state(page, NR_FILE_PAGES);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500900unlock:
901 xas_unlock_irq(&xas);
Matthew Wilcox (Oracle)198b62f2020-10-15 20:05:20 -0700902 } while (xas_nomem(&xas, gfp));
Matthew Wilcox74d60952017-11-17 10:01:45 -0500903
Johannes Weiner3fea5a42020-06-03 16:01:41 -0700904 if (xas_error(&xas)) {
905 error = xas_error(&xas);
Waiman Long032f8e02021-02-04 18:32:45 -0800906 if (charged)
907 mem_cgroup_uncharge(page);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500908 goto error;
Johannes Weiner3fea5a42020-06-03 16:01:41 -0700909 }
Matthew Wilcox74d60952017-11-17 10:01:45 -0500910
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700911 trace_mm_filemap_add_to_page_cache(page);
912 return 0;
Matthew Wilcox74d60952017-11-17 10:01:45 -0500913error:
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700914 page->mapping = NULL;
915 /* Leave page->index set: truncation relies upon it */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300916 put_page(page);
Johannes Weiner3fea5a42020-06-03 16:01:41 -0700917 return error;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700918}
Josef Bacikcfcbfb12019-05-13 17:21:04 -0700919ALLOW_ERROR_INJECTION(__add_to_page_cache_locked, ERRNO);
Johannes Weinera5289102014-04-03 14:47:51 -0700920
921/**
922 * add_to_page_cache_locked - add a locked page to the pagecache
923 * @page: page to add
924 * @mapping: the page's address_space
925 * @offset: page index
926 * @gfp_mask: page allocation mode
927 *
928 * This function is used to add a page to the pagecache. It must be locked.
929 * This function does not add the page to the LRU. The caller must do that.
Mike Rapoporta862f682019-03-05 15:48:42 -0800930 *
931 * Return: %0 on success, negative error code otherwise.
Johannes Weinera5289102014-04-03 14:47:51 -0700932 */
933int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
934 pgoff_t offset, gfp_t gfp_mask)
935{
936 return __add_to_page_cache_locked(page, mapping, offset,
937 gfp_mask, NULL);
938}
Nick Piggine2867812008-07-25 19:45:30 -0700939EXPORT_SYMBOL(add_to_page_cache_locked);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700940
941int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
Al Viro6daa0e22005-10-21 03:18:50 -0400942 pgoff_t offset, gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700943{
Johannes Weinera5289102014-04-03 14:47:51 -0700944 void *shadow = NULL;
Rik van Riel4f98a2f2008-10-18 20:26:32 -0700945 int ret;
946
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -0800947 __SetPageLocked(page);
Johannes Weinera5289102014-04-03 14:47:51 -0700948 ret = __add_to_page_cache_locked(page, mapping, offset,
949 gfp_mask, &shadow);
950 if (unlikely(ret))
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -0800951 __ClearPageLocked(page);
Johannes Weinera5289102014-04-03 14:47:51 -0700952 else {
953 /*
954 * The page might have been evicted from cache only
955 * recently, in which case it should be activated like
956 * any other repeatedly accessed page.
Rik van Rielf0281a02016-05-20 16:56:25 -0700957 * The exception is pages getting rewritten; evicting other
958 * data from the working set, only to cache data that will
959 * get overwritten with something else, is a waste of memory.
Johannes Weinera5289102014-04-03 14:47:51 -0700960 */
Johannes Weiner1899ad12018-10-26 15:06:04 -0700961 WARN_ON_ONCE(PageActive(page));
962 if (!(gfp_mask & __GFP_WRITE) && shadow)
963 workingset_refault(page, shadow);
Johannes Weinera5289102014-04-03 14:47:51 -0700964 lru_cache_add(page);
965 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700966 return ret;
967}
Evgeniy Polyakov18bc0bb2009-02-09 17:02:42 +0300968EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700969
Paul Jackson44110fe2006-03-24 03:16:04 -0800970#ifdef CONFIG_NUMA
Nick Piggin2ae88142006-10-28 10:38:23 -0700971struct page *__page_cache_alloc(gfp_t gfp)
Paul Jackson44110fe2006-03-24 03:16:04 -0800972{
Miao Xiec0ff7452010-05-24 14:32:08 -0700973 int n;
974 struct page *page;
975
Paul Jackson44110fe2006-03-24 03:16:04 -0800976 if (cpuset_do_page_mem_spread()) {
Mel Gormancc9a6c82012-03-21 16:34:11 -0700977 unsigned int cpuset_mems_cookie;
978 do {
Mel Gormand26914d2014-04-03 14:47:24 -0700979 cpuset_mems_cookie = read_mems_allowed_begin();
Mel Gormancc9a6c82012-03-21 16:34:11 -0700980 n = cpuset_mem_spread_node();
Vlastimil Babka96db8002015-09-08 15:03:50 -0700981 page = __alloc_pages_node(n, gfp, 0);
Mel Gormand26914d2014-04-03 14:47:24 -0700982 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
Mel Gormancc9a6c82012-03-21 16:34:11 -0700983
Miao Xiec0ff7452010-05-24 14:32:08 -0700984 return page;
Paul Jackson44110fe2006-03-24 03:16:04 -0800985 }
Nick Piggin2ae88142006-10-28 10:38:23 -0700986 return alloc_pages(gfp, 0);
Paul Jackson44110fe2006-03-24 03:16:04 -0800987}
Nick Piggin2ae88142006-10-28 10:38:23 -0700988EXPORT_SYMBOL(__page_cache_alloc);
Paul Jackson44110fe2006-03-24 03:16:04 -0800989#endif
990
Linus Torvalds1da177e2005-04-16 15:20:36 -0700991/*
992 * In order to wait for pages to become available there must be
993 * waitqueues associated with pages. By using a hash table of
994 * waitqueues where the bucket discipline is to maintain all
995 * waiters on the same queue and wake all when any of the pages
996 * become available, and for the woken contexts to check to be
997 * sure the appropriate page became available, this saves space
998 * at a cost of "thundering herd" phenomena during rare hash
999 * collisions.
1000 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001001#define PAGE_WAIT_TABLE_BITS 8
1002#define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
1003static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
1004
1005static wait_queue_head_t *page_waitqueue(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001006{
Nicholas Piggin62906022016-12-25 13:00:30 +10001007 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
Linus Torvalds1da177e2005-04-16 15:20:36 -07001008}
Nicholas Piggin62906022016-12-25 13:00:30 +10001009
1010void __init pagecache_init(void)
1011{
1012 int i;
1013
1014 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1015 init_waitqueue_head(&page_wait_table[i]);
1016
1017 page_writeback_init();
1018}
1019
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001020/*
1021 * The page wait code treats the "wait->flags" somewhat unusually, because
Linus Torvalds5868ec22020-09-20 10:38:47 -07001022 * we have multiple different kinds of waits, not just the usual "exclusive"
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001023 * one.
1024 *
1025 * We have:
1026 *
1027 * (a) no special bits set:
1028 *
1029 * We're just waiting for the bit to be released, and when a waker
1030 * calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up,
1031 * and remove it from the wait queue.
1032 *
1033 * Simple and straightforward.
1034 *
1035 * (b) WQ_FLAG_EXCLUSIVE:
1036 *
1037 * The waiter is waiting to get the lock, and only one waiter should
1038 * be woken up to avoid any thundering herd behavior. We'll set the
1039 * WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue.
1040 *
1041 * This is the traditional exclusive wait.
1042 *
Linus Torvalds5868ec22020-09-20 10:38:47 -07001043 * (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001044 *
1045 * The waiter is waiting to get the bit, and additionally wants the
1046 * lock to be transferred to it for fair lock behavior. If the lock
1047 * cannot be taken, we stop walking the wait queue without waking
1048 * the waiter.
1049 *
1050 * This is the "fair lock handoff" case, and in addition to setting
1051 * WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see
1052 * that it now has the lock.
1053 */
Ingo Molnarac6424b2017-06-20 12:06:13 +02001054static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
Nicholas Piggin62906022016-12-25 13:00:30 +10001055{
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001056 unsigned int flags;
Nicholas Piggin62906022016-12-25 13:00:30 +10001057 struct wait_page_key *key = arg;
1058 struct wait_page_queue *wait_page
1059 = container_of(wait, struct wait_page_queue, wait);
1060
Linus Torvaldscdc8fcb2020-08-03 13:01:22 -07001061 if (!wake_page_match(wait_page, key))
Nicholas Piggin62906022016-12-25 13:00:30 +10001062 return 0;
Linus Torvalds3510ca22017-08-27 13:55:12 -07001063
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001064 /*
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001065 * If it's a lock handoff wait, we get the bit for it, and
1066 * stop walking (and do not wake it up) if we can't.
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001067 */
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001068 flags = wait->flags;
1069 if (flags & WQ_FLAG_EXCLUSIVE) {
1070 if (test_bit(key->bit_nr, &key->page->flags))
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001071 return -1;
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001072 if (flags & WQ_FLAG_CUSTOM) {
1073 if (test_and_set_bit(key->bit_nr, &key->page->flags))
1074 return -1;
1075 flags |= WQ_FLAG_DONE;
1076 }
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001077 }
Nicholas Piggin62906022016-12-25 13:00:30 +10001078
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001079 /*
1080 * We are holding the wait-queue lock, but the waiter that
1081 * is waiting for this will be checking the flags without
1082 * any locking.
1083 *
1084 * So update the flags atomically, and wake up the waiter
1085 * afterwards to avoid any races. This store-release pairs
1086 * with the load-acquire in wait_on_page_bit_common().
1087 */
1088 smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001089 wake_up_state(wait->private, mode);
1090
1091 /*
1092 * Ok, we have successfully done what we're waiting for,
1093 * and we can unconditionally remove the wait entry.
1094 *
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001095 * Note that this pairs with the "finish_wait()" in the
1096 * waiter, and has to be the absolute last thing we do.
1097 * After this list_del_init(&wait->entry) the wait entry
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001098 * might be de-allocated and the process might even have
1099 * exited.
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001100 */
Linus Torvaldsc6fe44d2020-07-23 12:33:41 -07001101 list_del_init_careful(&wait->entry);
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001102 return (flags & WQ_FLAG_EXCLUSIVE) != 0;
Nicholas Piggin62906022016-12-25 13:00:30 +10001103}
1104
Nicholas Piggin74d81bf2017-02-22 15:44:41 -08001105static void wake_up_page_bit(struct page *page, int bit_nr)
Nicholas Piggin62906022016-12-25 13:00:30 +10001106{
1107 wait_queue_head_t *q = page_waitqueue(page);
1108 struct wait_page_key key;
1109 unsigned long flags;
Tim Chen11a19c72017-08-25 09:13:55 -07001110 wait_queue_entry_t bookmark;
Nicholas Piggin62906022016-12-25 13:00:30 +10001111
1112 key.page = page;
1113 key.bit_nr = bit_nr;
1114 key.page_match = 0;
1115
Tim Chen11a19c72017-08-25 09:13:55 -07001116 bookmark.flags = 0;
1117 bookmark.private = NULL;
1118 bookmark.func = NULL;
1119 INIT_LIST_HEAD(&bookmark.entry);
1120
Nicholas Piggin62906022016-12-25 13:00:30 +10001121 spin_lock_irqsave(&q->lock, flags);
Tim Chen11a19c72017-08-25 09:13:55 -07001122 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1123
1124 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1125 /*
1126 * Take a breather from holding the lock,
1127 * allow pages that finish wake up asynchronously
1128 * to acquire the lock and remove themselves
1129 * from wait queue
1130 */
1131 spin_unlock_irqrestore(&q->lock, flags);
1132 cpu_relax();
1133 spin_lock_irqsave(&q->lock, flags);
1134 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1135 }
1136
Nicholas Piggin62906022016-12-25 13:00:30 +10001137 /*
1138 * It is possible for other pages to have collided on the waitqueue
1139 * hash, so in that case check for a page match. That prevents a long-
1140 * term waiter
1141 *
1142 * It is still possible to miss a case here, when we woke page waiters
1143 * and removed them from the waitqueue, but there are still other
1144 * page waiters.
1145 */
1146 if (!waitqueue_active(q) || !key.page_match) {
1147 ClearPageWaiters(page);
1148 /*
1149 * It's possible to miss clearing Waiters here, when we woke
1150 * our page waiters, but the hashed waitqueue has waiters for
1151 * other pages on it.
1152 *
1153 * That's okay, it's a rare case. The next waker will clear it.
1154 */
1155 }
1156 spin_unlock_irqrestore(&q->lock, flags);
1157}
Nicholas Piggin74d81bf2017-02-22 15:44:41 -08001158
1159static void wake_up_page(struct page *page, int bit)
1160{
1161 if (!PageWaiters(page))
1162 return;
1163 wake_up_page_bit(page, bit);
1164}
Nicholas Piggin62906022016-12-25 13:00:30 +10001165
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001166/*
1167 * A choice of three behaviors for wait_on_page_bit_common():
1168 */
1169enum behavior {
1170 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
1171 * __lock_page() waiting on then setting PG_locked.
1172 */
1173 SHARED, /* Hold ref to page and check the bit when woken, like
1174 * wait_on_page_writeback() waiting on PG_writeback.
1175 */
1176 DROP, /* Drop ref to page before wait, no check when woken,
1177 * like put_and_wait_on_page_locked() on PG_locked.
1178 */
1179};
1180
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001181/*
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001182 * Attempt to check (or get) the page bit, and mark us done
1183 * if successful.
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001184 */
1185static inline bool trylock_page_bit_common(struct page *page, int bit_nr,
1186 struct wait_queue_entry *wait)
1187{
1188 if (wait->flags & WQ_FLAG_EXCLUSIVE) {
1189 if (test_and_set_bit(bit_nr, &page->flags))
1190 return false;
1191 } else if (test_bit(bit_nr, &page->flags))
1192 return false;
1193
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001194 wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001195 return true;
1196}
1197
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001198/* How many times do we accept lock stealing from under a waiter? */
1199int sysctl_page_lock_unfairness = 5;
1200
Jimmy Shiudec0fd42020-11-03 00:16:37 +08001201static inline __sched int wait_on_page_bit_common(wait_queue_head_t *q,
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001202 struct page *page, int bit_nr, int state, enum behavior behavior)
Nicholas Piggin62906022016-12-25 13:00:30 +10001203{
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001204 int unfairness = sysctl_page_lock_unfairness;
Nicholas Piggin62906022016-12-25 13:00:30 +10001205 struct wait_page_queue wait_page;
Ingo Molnarac6424b2017-06-20 12:06:13 +02001206 wait_queue_entry_t *wait = &wait_page.wait;
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001207 bool thrashing = false;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001208 bool delayacct = false;
Johannes Weinereb414682018-10-26 15:06:27 -07001209 unsigned long pflags;
Nicholas Piggin62906022016-12-25 13:00:30 +10001210
Johannes Weinereb414682018-10-26 15:06:27 -07001211 if (bit_nr == PG_locked &&
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001212 !PageUptodate(page) && PageWorkingset(page)) {
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001213 if (!PageSwapBacked(page)) {
Johannes Weinereb414682018-10-26 15:06:27 -07001214 delayacct_thrashing_start();
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001215 delayacct = true;
1216 }
Johannes Weinereb414682018-10-26 15:06:27 -07001217 psi_memstall_enter(&pflags);
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001218 thrashing = true;
1219 }
1220
Nicholas Piggin62906022016-12-25 13:00:30 +10001221 init_wait(wait);
1222 wait->func = wake_page_function;
1223 wait_page.page = page;
1224 wait_page.bit_nr = bit_nr;
1225
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001226repeat:
1227 wait->flags = 0;
1228 if (behavior == EXCLUSIVE) {
1229 wait->flags = WQ_FLAG_EXCLUSIVE;
1230 if (--unfairness < 0)
1231 wait->flags |= WQ_FLAG_CUSTOM;
1232 }
1233
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001234 /*
1235 * Do one last check whether we can get the
1236 * page bit synchronously.
1237 *
1238 * Do the SetPageWaiters() marking before that
1239 * to let any waker we _just_ missed know they
1240 * need to wake us up (otherwise they'll never
1241 * even go to the slow case that looks at the
1242 * page queue), and add ourselves to the wait
1243 * queue if we need to sleep.
1244 *
1245 * This part needs to be done under the queue
1246 * lock to avoid races.
1247 */
1248 spin_lock_irq(&q->lock);
1249 SetPageWaiters(page);
1250 if (!trylock_page_bit_common(page, bit_nr, wait))
1251 __add_wait_queue_entry_tail(q, wait);
1252 spin_unlock_irq(&q->lock);
1253
1254 /*
1255 * From now on, all the logic will be based on
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001256 * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to
1257 * see whether the page bit testing has already
1258 * been done by the wake function.
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001259 *
1260 * We can drop our reference to the page.
1261 */
1262 if (behavior == DROP)
1263 put_page(page);
1264
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001265 /*
1266 * Note that until the "finish_wait()", or until
1267 * we see the WQ_FLAG_WOKEN flag, we need to
1268 * be very careful with the 'wait->flags', because
1269 * we may race with a waker that sets them.
1270 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001271 for (;;) {
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001272 unsigned int flags;
1273
Nicholas Piggin62906022016-12-25 13:00:30 +10001274 set_current_state(state);
1275
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001276 /* Loop until we've been woken or interrupted */
1277 flags = smp_load_acquire(&wait->flags);
1278 if (!(flags & WQ_FLAG_WOKEN)) {
1279 if (signal_pending_state(state, current))
1280 break;
1281
1282 io_schedule();
1283 continue;
1284 }
1285
1286 /* If we were non-exclusive, we're done */
1287 if (behavior != EXCLUSIVE)
Linus Torvaldsa8b169a2017-08-27 16:25:09 -07001288 break;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001289
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001290 /* If the waker got the lock for us, we're done */
1291 if (flags & WQ_FLAG_DONE)
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001292 break;
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001293
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001294 /*
1295 * Otherwise, if we're getting the lock, we need to
1296 * try to get it ourselves.
1297 *
1298 * And if that fails, we'll have to retry this all.
1299 */
1300 if (unlikely(test_and_set_bit(bit_nr, &page->flags)))
1301 goto repeat;
1302
1303 wait->flags |= WQ_FLAG_DONE;
1304 break;
Nicholas Piggin62906022016-12-25 13:00:30 +10001305 }
1306
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001307 /*
1308 * If a signal happened, this 'finish_wait()' may remove the last
1309 * waiter from the wait-queues, but the PageWaiters bit will remain
1310 * set. That's ok. The next wakeup will take care of it, and trying
1311 * to do it here would be difficult and prone to races.
1312 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001313 finish_wait(q, wait);
1314
Johannes Weinereb414682018-10-26 15:06:27 -07001315 if (thrashing) {
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001316 if (delayacct)
Johannes Weinereb414682018-10-26 15:06:27 -07001317 delayacct_thrashing_end();
1318 psi_memstall_leave(&pflags);
1319 }
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001320
Nicholas Piggin62906022016-12-25 13:00:30 +10001321 /*
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001322 * NOTE! The wait->flags weren't stable until we've done the
1323 * 'finish_wait()', and we could have exited the loop above due
1324 * to a signal, and had a wakeup event happen after the signal
1325 * test but before the 'finish_wait()'.
1326 *
1327 * So only after the finish_wait() can we reliably determine
1328 * if we got woken up or not, so we can now figure out the final
1329 * return value based on that state without races.
1330 *
1331 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
1332 * waiter, but an exclusive one requires WQ_FLAG_DONE.
Nicholas Piggin62906022016-12-25 13:00:30 +10001333 */
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001334 if (behavior == EXCLUSIVE)
1335 return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
Nicholas Piggin62906022016-12-25 13:00:30 +10001336
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001337 return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
Nicholas Piggin62906022016-12-25 13:00:30 +10001338}
Linus Torvalds1da177e2005-04-16 15:20:36 -07001339
Jimmy Shiudec0fd42020-11-03 00:16:37 +08001340__sched void wait_on_page_bit(struct page *page, int bit_nr)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001341{
Nicholas Piggin62906022016-12-25 13:00:30 +10001342 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001343 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001344}
1345EXPORT_SYMBOL(wait_on_page_bit);
1346
Jimmy Shiudec0fd42020-11-03 00:16:37 +08001347__sched int wait_on_page_bit_killable(struct page *page, int bit_nr)
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001348{
Nicholas Piggin62906022016-12-25 13:00:30 +10001349 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001350 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, SHARED);
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001351}
David Howells4343d002017-11-02 15:27:52 +00001352EXPORT_SYMBOL(wait_on_page_bit_killable);
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001353
Jens Axboedd3e6d52020-05-22 09:12:09 -06001354static int __wait_on_page_locked_async(struct page *page,
1355 struct wait_page_queue *wait, bool set)
1356{
1357 struct wait_queue_head *q = page_waitqueue(page);
1358 int ret = 0;
1359
1360 wait->page = page;
1361 wait->bit_nr = PG_locked;
1362
1363 spin_lock_irq(&q->lock);
1364 __add_wait_queue_entry_tail(q, &wait->wait);
1365 SetPageWaiters(page);
1366 if (set)
1367 ret = !trylock_page(page);
1368 else
1369 ret = PageLocked(page);
1370 /*
1371 * If we were succesful now, we know we're still on the
1372 * waitqueue as we're still under the lock. This means it's
1373 * safe to remove and return success, we know the callback
1374 * isn't going to trigger.
1375 */
1376 if (!ret)
1377 __remove_wait_queue(q, &wait->wait);
1378 else
1379 ret = -EIOCBQUEUED;
1380 spin_unlock_irq(&q->lock);
1381 return ret;
1382}
1383
Jens Axboe1a0a7852020-05-22 09:18:38 -06001384static int wait_on_page_locked_async(struct page *page,
1385 struct wait_page_queue *wait)
1386{
1387 if (!PageLocked(page))
1388 return 0;
1389 return __wait_on_page_locked_async(compound_head(page), wait, false);
1390}
1391
Linus Torvalds1da177e2005-04-16 15:20:36 -07001392/**
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001393 * put_and_wait_on_page_locked - Drop a reference and wait for it to be unlocked
1394 * @page: The page to wait for.
1395 *
1396 * The caller should hold a reference on @page. They expect the page to
1397 * become unlocked relatively soon, but do not wish to hold up migration
1398 * (for example) by holding the reference while waiting for the page to
1399 * come unlocked. After this function returns, the caller should not
1400 * dereference @page.
1401 */
1402void put_and_wait_on_page_locked(struct page *page)
1403{
1404 wait_queue_head_t *q;
1405
1406 page = compound_head(page);
1407 q = page_waitqueue(page);
1408 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE, DROP);
1409}
1410
1411/**
David Howells385e1ca5f2009-04-03 16:42:39 +01001412 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
Randy Dunlap697f6192009-04-13 14:39:54 -07001413 * @page: Page defining the wait queue of interest
1414 * @waiter: Waiter to add to the queue
David Howells385e1ca5f2009-04-03 16:42:39 +01001415 *
1416 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1417 */
Ingo Molnarac6424b2017-06-20 12:06:13 +02001418void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
David Howells385e1ca5f2009-04-03 16:42:39 +01001419{
1420 wait_queue_head_t *q = page_waitqueue(page);
1421 unsigned long flags;
1422
1423 spin_lock_irqsave(&q->lock, flags);
Linus Torvalds9c3a8152017-08-28 16:45:40 -07001424 __add_wait_queue_entry_tail(q, waiter);
Nicholas Piggin62906022016-12-25 13:00:30 +10001425 SetPageWaiters(page);
David Howells385e1ca5f2009-04-03 16:42:39 +01001426 spin_unlock_irqrestore(&q->lock, flags);
1427}
1428EXPORT_SYMBOL_GPL(add_page_wait_queue);
1429
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001430#ifndef clear_bit_unlock_is_negative_byte
1431
1432/*
1433 * PG_waiters is the high bit in the same byte as PG_lock.
1434 *
1435 * On x86 (and on many other architectures), we can clear PG_lock and
1436 * test the sign bit at the same time. But if the architecture does
1437 * not support that special operation, we just do this all by hand
1438 * instead.
1439 *
1440 * The read of PG_waiters has to be after (or concurrently with) PG_locked
Ethon Paulffceeb62020-06-04 16:49:22 -07001441 * being cleared, but a memory barrier should be unnecessary since it is
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001442 * in the same byte as PG_locked.
1443 */
1444static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1445{
1446 clear_bit_unlock(nr, mem);
1447 /* smp_mb__after_atomic(); */
Olof Johansson98473f92016-12-29 14:16:07 -08001448 return test_bit(PG_waiters, mem);
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001449}
1450
1451#endif
1452
David Howells385e1ca5f2009-04-03 16:42:39 +01001453/**
Randy Dunlap485bb992006-06-23 02:03:49 -07001454 * unlock_page - unlock a locked page
Linus Torvalds1da177e2005-04-16 15:20:36 -07001455 * @page: the page
1456 *
Miaohe Lin0e9aa672020-10-15 20:09:58 -07001457 * Unlocks the page and wakes up sleepers in wait_on_page_locked().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001458 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
Masanari Iidada3dae52014-09-09 01:27:23 +09001459 * mechanism between PageLocked pages and PageWriteback pages is shared.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001460 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1461 *
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001462 * Note that this depends on PG_waiters being the sign bit in the byte
1463 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1464 * clear the PG_locked bit and test PG_waiters at the same time fairly
1465 * portably (architectures that do LL/SC can test any bit, while x86 can
1466 * test the sign bit).
Linus Torvalds1da177e2005-04-16 15:20:36 -07001467 */
Harvey Harrison920c7a52008-02-04 22:29:26 -08001468void unlock_page(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001469{
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001470 BUILD_BUG_ON(PG_waiters != 7);
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -08001471 page = compound_head(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001472 VM_BUG_ON_PAGE(!PageLocked(page), page);
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001473 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1474 wake_up_page_bit(page, PG_locked);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001475}
1476EXPORT_SYMBOL(unlock_page);
1477
Randy Dunlap485bb992006-06-23 02:03:49 -07001478/**
1479 * end_page_writeback - end writeback against a page
1480 * @page: the page
Linus Torvalds1da177e2005-04-16 15:20:36 -07001481 */
1482void end_page_writeback(struct page *page)
1483{
Mel Gorman888cf2d2014-06-04 16:10:34 -07001484 /*
1485 * TestClearPageReclaim could be used here but it is an atomic
1486 * operation and overkill in this particular case. Failing to
1487 * shuffle a page marked for immediate reclaim is too mild to
1488 * justify taking an atomic operation penalty at the end of
1489 * ever page writeback.
1490 */
1491 if (PageReclaim(page)) {
1492 ClearPageReclaim(page);
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001493 rotate_reclaimable_page(page);
Mel Gorman888cf2d2014-06-04 16:10:34 -07001494 }
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001495
Hugh Dickins073861e2020-11-24 08:46:43 -08001496 /*
1497 * Writeback does not hold a page reference of its own, relying
1498 * on truncation to wait for the clearing of PG_writeback.
1499 * But here we must make sure that the page is not freed and
1500 * reused before the wake_up_page().
1501 */
1502 get_page(page);
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001503 if (!test_clear_page_writeback(page))
1504 BUG();
1505
Peter Zijlstra4e857c52014-03-17 18:06:10 +01001506 smp_mb__after_atomic();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001507 wake_up_page(page, PG_writeback);
Hugh Dickins073861e2020-11-24 08:46:43 -08001508 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001509}
1510EXPORT_SYMBOL(end_page_writeback);
1511
Matthew Wilcox57d99842014-06-04 16:07:45 -07001512/*
1513 * After completing I/O on a page, call this routine to update the page
1514 * flags appropriately
1515 */
Jens Axboec11f0c02016-08-05 08:11:04 -06001516void page_endio(struct page *page, bool is_write, int err)
Matthew Wilcox57d99842014-06-04 16:07:45 -07001517{
Jens Axboec11f0c02016-08-05 08:11:04 -06001518 if (!is_write) {
Matthew Wilcox57d99842014-06-04 16:07:45 -07001519 if (!err) {
1520 SetPageUptodate(page);
1521 } else {
1522 ClearPageUptodate(page);
1523 SetPageError(page);
1524 }
1525 unlock_page(page);
Mike Christieabf54542016-08-04 14:23:34 -06001526 } else {
Matthew Wilcox57d99842014-06-04 16:07:45 -07001527 if (err) {
Minchan Kimdd8416c2017-02-24 14:59:59 -08001528 struct address_space *mapping;
1529
Matthew Wilcox57d99842014-06-04 16:07:45 -07001530 SetPageError(page);
Minchan Kimdd8416c2017-02-24 14:59:59 -08001531 mapping = page_mapping(page);
1532 if (mapping)
1533 mapping_set_error(mapping, err);
Matthew Wilcox57d99842014-06-04 16:07:45 -07001534 }
1535 end_page_writeback(page);
1536 }
1537}
1538EXPORT_SYMBOL_GPL(page_endio);
1539
Randy Dunlap485bb992006-06-23 02:03:49 -07001540/**
1541 * __lock_page - get a lock on the page, assuming we need to sleep to get it
Randy Dunlap87066752017-02-22 15:44:44 -08001542 * @__page: the page to lock
Linus Torvalds1da177e2005-04-16 15:20:36 -07001543 */
Jimmy Shiudec0fd42020-11-03 00:16:37 +08001544__sched void __lock_page(struct page *__page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001545{
Nicholas Piggin62906022016-12-25 13:00:30 +10001546 struct page *page = compound_head(__page);
1547 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001548 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE,
1549 EXCLUSIVE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001550}
1551EXPORT_SYMBOL(__lock_page);
1552
Jimmy Shiudec0fd42020-11-03 00:16:37 +08001553__sched int __lock_page_killable(struct page *__page)
Matthew Wilcox2687a352007-12-06 11:18:49 -05001554{
Nicholas Piggin62906022016-12-25 13:00:30 +10001555 struct page *page = compound_head(__page);
1556 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001557 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE,
1558 EXCLUSIVE);
Matthew Wilcox2687a352007-12-06 11:18:49 -05001559}
Evgeniy Polyakov18bc0bb2009-02-09 17:02:42 +03001560EXPORT_SYMBOL_GPL(__lock_page_killable);
Matthew Wilcox2687a352007-12-06 11:18:49 -05001561
Jimmy Shiudec0fd42020-11-03 00:16:37 +08001562__sched int __lock_page_async(struct page *page, struct wait_page_queue *wait)
Jens Axboedd3e6d52020-05-22 09:12:09 -06001563{
1564 return __wait_on_page_locked_async(page, wait, true);
1565}
1566
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001567/*
1568 * Return values:
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07001569 * 1 - page is locked; mmap_lock is still held.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001570 * 0 - page is not locked.
Michel Lespinasse3e4e28c2020-06-08 21:33:51 -07001571 * mmap_lock has been released (mmap_read_unlock(), unless flags had both
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001572 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07001573 * which case mmap_lock is still held.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001574 *
1575 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07001576 * with the page locked and the mmap_lock unperturbed.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001577 */
Jimmy Shiudec0fd42020-11-03 00:16:37 +08001578__sched int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
Michel Lespinassed065bd82010-10-26 14:21:57 -07001579 unsigned int flags)
1580{
Peter Xu4064b982020-04-01 21:08:45 -07001581 if (fault_flag_allow_retry_first(flags)) {
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001582 /*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07001583 * CAUTION! In this case, mmap_lock is not released
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001584 * even though return 0.
1585 */
1586 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1587 return 0;
1588
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07001589 mmap_read_unlock(mm);
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001590 if (flags & FAULT_FLAG_KILLABLE)
1591 wait_on_page_locked_killable(page);
1592 else
Gleb Natapov318b2752011-03-22 16:30:51 -07001593 wait_on_page_locked(page);
Michel Lespinassed065bd82010-10-26 14:21:57 -07001594 return 0;
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001595 } else {
1596 if (flags & FAULT_FLAG_KILLABLE) {
1597 int ret;
1598
1599 ret = __lock_page_killable(page);
1600 if (ret) {
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07001601 mmap_read_unlock(mm);
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001602 return 0;
1603 }
1604 } else
1605 __lock_page(page);
1606 return 1;
Michel Lespinassed065bd82010-10-26 14:21:57 -07001607 }
1608}
1609
Randy Dunlap485bb992006-06-23 02:03:49 -07001610/**
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001611 * page_cache_next_miss() - Find the next gap in the page cache.
1612 * @mapping: Mapping.
1613 * @index: Index.
1614 * @max_scan: Maximum range to search.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001615 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001616 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1617 * gap with the lowest index.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001618 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001619 * This function may be called under the rcu_read_lock. However, this will
1620 * not atomically search a snapshot of the cache at a single point in time.
1621 * For example, if a gap is created at index 5, then subsequently a gap is
1622 * created at index 10, page_cache_next_miss covering both indices may
1623 * return 10 if called under the rcu_read_lock.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001624 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001625 * Return: The index of the gap if found, otherwise an index outside the
1626 * range specified (in which case 'return - index >= max_scan' will be true).
1627 * In the rare case of index wrap-around, 0 will be returned.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001628 */
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001629pgoff_t page_cache_next_miss(struct address_space *mapping,
Johannes Weinere7b563b2014-04-03 14:47:44 -07001630 pgoff_t index, unsigned long max_scan)
1631{
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001632 XA_STATE(xas, &mapping->i_pages, index);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001633
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001634 while (max_scan--) {
1635 void *entry = xas_next(&xas);
1636 if (!entry || xa_is_value(entry))
Johannes Weinere7b563b2014-04-03 14:47:44 -07001637 break;
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001638 if (xas.xa_index == 0)
Johannes Weinere7b563b2014-04-03 14:47:44 -07001639 break;
1640 }
1641
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001642 return xas.xa_index;
Johannes Weinere7b563b2014-04-03 14:47:44 -07001643}
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001644EXPORT_SYMBOL(page_cache_next_miss);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001645
1646/**
Laurent Dufour2346a562019-05-13 17:21:29 -07001647 * page_cache_prev_miss() - Find the previous gap in the page cache.
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001648 * @mapping: Mapping.
1649 * @index: Index.
1650 * @max_scan: Maximum range to search.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001651 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001652 * Search the range [max(index - max_scan + 1, 0), index] for the
1653 * gap with the highest index.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001654 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001655 * This function may be called under the rcu_read_lock. However, this will
1656 * not atomically search a snapshot of the cache at a single point in time.
1657 * For example, if a gap is created at index 10, then subsequently a gap is
1658 * created at index 5, page_cache_prev_miss() covering both indices may
1659 * return 5 if called under the rcu_read_lock.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001660 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001661 * Return: The index of the gap if found, otherwise an index outside the
1662 * range specified (in which case 'index - return >= max_scan' will be true).
1663 * In the rare case of wrap-around, ULONG_MAX will be returned.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001664 */
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001665pgoff_t page_cache_prev_miss(struct address_space *mapping,
Johannes Weinere7b563b2014-04-03 14:47:44 -07001666 pgoff_t index, unsigned long max_scan)
1667{
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001668 XA_STATE(xas, &mapping->i_pages, index);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001669
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001670 while (max_scan--) {
1671 void *entry = xas_prev(&xas);
1672 if (!entry || xa_is_value(entry))
Johannes Weinere7b563b2014-04-03 14:47:44 -07001673 break;
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001674 if (xas.xa_index == ULONG_MAX)
Johannes Weinere7b563b2014-04-03 14:47:44 -07001675 break;
1676 }
1677
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001678 return xas.xa_index;
Johannes Weinere7b563b2014-04-03 14:47:44 -07001679}
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001680EXPORT_SYMBOL(page_cache_prev_miss);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001681
1682/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001683 * find_get_entry - find and get a page cache entry
Randy Dunlap485bb992006-06-23 02:03:49 -07001684 * @mapping: the address_space to search
Matthew Wilcox (Oracle)a6de4b42020-10-13 16:51:34 -07001685 * @index: The page cache index.
Randy Dunlap485bb992006-06-23 02:03:49 -07001686 *
Johannes Weiner0cd61442014-04-03 14:47:46 -07001687 * Looks up the page cache slot at @mapping & @offset. If there is a
Matthew Wilcox (Oracle)a6de4b42020-10-13 16:51:34 -07001688 * page cache page, the head page is returned with an increased refcount.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001689 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001690 * If the slot holds a shadow entry of a previously evicted page, or a
1691 * swap entry from shmem/tmpfs, it is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001692 *
Matthew Wilcox (Oracle)a6de4b42020-10-13 16:51:34 -07001693 * Return: The head page or shadow entry, %NULL if nothing is found.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001694 */
Matthew Wilcox (Oracle)a6de4b42020-10-13 16:51:34 -07001695struct page *find_get_entry(struct address_space *mapping, pgoff_t index)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001696{
Matthew Wilcox (Oracle)a6de4b42020-10-13 16:51:34 -07001697 XA_STATE(xas, &mapping->i_pages, index);
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001698 struct page *page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001699
Nick Piggina60637c2008-07-25 19:45:31 -07001700 rcu_read_lock();
1701repeat:
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001702 xas_reset(&xas);
1703 page = xas_load(&xas);
1704 if (xas_retry(&xas, page))
1705 goto repeat;
1706 /*
1707 * A shadow entry of a recently evicted page, or a swap entry from
1708 * shmem/tmpfs. Return it without attempting to raise page count.
1709 */
1710 if (!page || xa_is_value(page))
1711 goto out;
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001712
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001713 if (!page_cache_get_speculative(page))
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001714 goto repeat;
Nick Piggina60637c2008-07-25 19:45:31 -07001715
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001716 /*
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001717 * Has the page moved or been split?
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001718 * This is part of the lockless pagecache protocol. See
1719 * include/linux/pagemap.h for details.
1720 */
1721 if (unlikely(page != xas_reload(&xas))) {
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001722 put_page(page);
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001723 goto repeat;
Nick Piggina60637c2008-07-25 19:45:31 -07001724 }
Nick Piggin27d20fd2010-11-11 14:05:19 -08001725out:
Nick Piggina60637c2008-07-25 19:45:31 -07001726 rcu_read_unlock();
1727
Linus Torvalds1da177e2005-04-16 15:20:36 -07001728 return page;
1729}
Linus Torvalds1da177e2005-04-16 15:20:36 -07001730
Randy Dunlap485bb992006-06-23 02:03:49 -07001731/**
Matthew Wilcox (Oracle)63ec1972020-10-13 16:51:38 -07001732 * find_lock_entry - Locate and lock a page cache entry.
1733 * @mapping: The address_space to search.
1734 * @index: The page cache index.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001735 *
Matthew Wilcox (Oracle)63ec1972020-10-13 16:51:38 -07001736 * Looks up the page at @mapping & @index. If there is a page in the
1737 * cache, the head page is returned locked and with an increased refcount.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001738 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001739 * If the slot holds a shadow entry of a previously evicted page, or a
1740 * swap entry from shmem/tmpfs, it is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001741 *
Matthew Wilcox (Oracle)63ec1972020-10-13 16:51:38 -07001742 * Context: May sleep.
1743 * Return: The head page or shadow entry, %NULL if nothing is found.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001744 */
Matthew Wilcox (Oracle)63ec1972020-10-13 16:51:38 -07001745struct page *find_lock_entry(struct address_space *mapping, pgoff_t index)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001746{
1747 struct page *page;
1748
Linus Torvalds1da177e2005-04-16 15:20:36 -07001749repeat:
Matthew Wilcox (Oracle)63ec1972020-10-13 16:51:38 -07001750 page = find_get_entry(mapping, index);
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001751 if (page && !xa_is_value(page)) {
Nick Piggina60637c2008-07-25 19:45:31 -07001752 lock_page(page);
1753 /* Has the page been truncated? */
Matthew Wilcox (Oracle)63ec1972020-10-13 16:51:38 -07001754 if (unlikely(page->mapping != mapping)) {
Nick Piggina60637c2008-07-25 19:45:31 -07001755 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001756 put_page(page);
Nick Piggina60637c2008-07-25 19:45:31 -07001757 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001758 }
Matthew Wilcox (Oracle)63ec1972020-10-13 16:51:38 -07001759 VM_BUG_ON_PAGE(!thp_contains(page, index), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001760 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001761 return page;
1762}
Johannes Weiner0cd61442014-04-03 14:47:46 -07001763
1764/**
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001765 * pagecache_get_page - Find and get a reference to a page.
1766 * @mapping: The address_space to search.
1767 * @index: The page index.
1768 * @fgp_flags: %FGP flags modify how the page is returned.
1769 * @gfp_mask: Memory allocation flags to use if %FGP_CREAT is specified.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001770 *
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001771 * Looks up the page cache entry at @mapping & @index.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001772 *
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001773 * @fgp_flags can be zero or more of these flags:
Johannes Weiner0cd61442014-04-03 14:47:46 -07001774 *
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001775 * * %FGP_ACCESSED - The page will be marked accessed.
1776 * * %FGP_LOCK - The page is returned locked.
Matthew Wilcox (Oracle)a8cf7f22020-10-13 16:51:41 -07001777 * * %FGP_HEAD - If the page is present and a THP, return the head page
1778 * rather than the exact page specified by the index.
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001779 * * %FGP_CREAT - If no page is present then a new page is allocated using
1780 * @gfp_mask and added to the page cache and the VM's LRU list.
1781 * The page is returned locked and with an increased refcount.
1782 * * %FGP_FOR_MMAP - The caller wants to do its own locking dance if the
1783 * page is already in cache. If the page was allocated, unlock it before
1784 * returning so the caller can do the same dance.
Yang Shi605cad82020-08-06 23:19:58 -07001785 * * %FGP_WRITE - The page will be written
1786 * * %FGP_NOFS - __GFP_FS will get cleared in gfp mask
1787 * * %FGP_NOWAIT - Don't get blocked by page lock
mchehab@s-opensource.com0e056eb2017-03-30 17:11:36 -03001788 *
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001789 * If %FGP_LOCK or %FGP_CREAT are specified then the function may sleep even
1790 * if the %GFP flags specified for %FGP_CREAT are atomic.
Mel Gorman2457aec2014-06-04 16:10:31 -07001791 *
1792 * If there is a page cache page, it is returned with an increased refcount.
Mike Rapoporta862f682019-03-05 15:48:42 -08001793 *
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001794 * Return: The found page or %NULL otherwise.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001795 */
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001796struct page *pagecache_get_page(struct address_space *mapping, pgoff_t index,
1797 int fgp_flags, gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001798{
Nick Piggineb2be182007-10-16 01:24:57 -07001799 struct page *page;
Mel Gorman2457aec2014-06-04 16:10:31 -07001800
Linus Torvalds1da177e2005-04-16 15:20:36 -07001801repeat:
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001802 page = find_get_entry(mapping, index);
Matthew Wilcox3159f942017-11-03 13:30:42 -04001803 if (xa_is_value(page))
Mel Gorman2457aec2014-06-04 16:10:31 -07001804 page = NULL;
Chiawei Wangdb158b42021-02-18 10:47:37 +08001805
1806 trace_android_vh_pagecache_get_page(mapping, index, fgp_flags,
1807 gfp_mask, page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001808 if (!page)
1809 goto no_page;
1810
1811 if (fgp_flags & FGP_LOCK) {
1812 if (fgp_flags & FGP_NOWAIT) {
1813 if (!trylock_page(page)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001814 put_page(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001815 return NULL;
1816 }
1817 } else {
1818 lock_page(page);
1819 }
1820
1821 /* Has the page been truncated? */
Matthew Wilcox (Oracle)a8cf7f22020-10-13 16:51:41 -07001822 if (unlikely(page->mapping != mapping)) {
Mel Gorman2457aec2014-06-04 16:10:31 -07001823 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001824 put_page(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001825 goto repeat;
1826 }
Matthew Wilcox (Oracle)a8cf7f22020-10-13 16:51:41 -07001827 VM_BUG_ON_PAGE(!thp_contains(page, index), page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001828 }
1829
Kirill Tkhaic16eb002018-12-28 00:37:35 -08001830 if (fgp_flags & FGP_ACCESSED)
Mel Gorman2457aec2014-06-04 16:10:31 -07001831 mark_page_accessed(page);
Yang Shib9306a72020-08-06 23:19:55 -07001832 else if (fgp_flags & FGP_WRITE) {
1833 /* Clear idle flag for buffer write */
1834 if (page_is_idle(page))
1835 clear_page_idle(page);
1836 }
Matthew Wilcox (Oracle)a8cf7f22020-10-13 16:51:41 -07001837 if (!(fgp_flags & FGP_HEAD))
1838 page = find_subpage(page, index);
Mel Gorman2457aec2014-06-04 16:10:31 -07001839
1840no_page:
1841 if (!page && (fgp_flags & FGP_CREAT)) {
1842 int err;
Christoph Hellwigf56753a2020-09-24 08:51:40 +02001843 if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping))
Michal Hocko45f87de2014-12-29 20:30:35 +01001844 gfp_mask |= __GFP_WRITE;
1845 if (fgp_flags & FGP_NOFS)
1846 gfp_mask &= ~__GFP_FS;
Mel Gorman2457aec2014-06-04 16:10:31 -07001847
Michal Hocko45f87de2014-12-29 20:30:35 +01001848 page = __page_cache_alloc(gfp_mask);
Nick Piggineb2be182007-10-16 01:24:57 -07001849 if (!page)
1850 return NULL;
Mel Gorman2457aec2014-06-04 16:10:31 -07001851
Josef Bacika75d4c32019-03-13 11:44:14 -07001852 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
Mel Gorman2457aec2014-06-04 16:10:31 -07001853 fgp_flags |= FGP_LOCK;
1854
Hugh Dickinseb39d612014-08-06 16:06:43 -07001855 /* Init accessed so avoid atomic mark_page_accessed later */
Mel Gorman2457aec2014-06-04 16:10:31 -07001856 if (fgp_flags & FGP_ACCESSED)
Hugh Dickinseb39d612014-08-06 16:06:43 -07001857 __SetPageReferenced(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001858
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001859 err = add_to_page_cache_lru(page, mapping, index, gfp_mask);
Nick Piggineb2be182007-10-16 01:24:57 -07001860 if (unlikely(err)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001861 put_page(page);
Nick Piggineb2be182007-10-16 01:24:57 -07001862 page = NULL;
1863 if (err == -EEXIST)
1864 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001865 }
Josef Bacika75d4c32019-03-13 11:44:14 -07001866
1867 /*
1868 * add_to_page_cache_lru locks the page, and for mmap we expect
1869 * an unlocked page.
1870 */
1871 if (page && (fgp_flags & FGP_FOR_MMAP))
1872 unlock_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001873 }
Mel Gorman2457aec2014-06-04 16:10:31 -07001874
Linus Torvalds1da177e2005-04-16 15:20:36 -07001875 return page;
1876}
Mel Gorman2457aec2014-06-04 16:10:31 -07001877EXPORT_SYMBOL(pagecache_get_page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001878
1879/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001880 * find_get_entries - gang pagecache lookup
1881 * @mapping: The address_space to search
1882 * @start: The starting page cache index
1883 * @nr_entries: The maximum number of entries
1884 * @entries: Where the resulting entries are placed
1885 * @indices: The cache indices corresponding to the entries in @entries
1886 *
1887 * find_get_entries() will search for and return a group of up to
1888 * @nr_entries entries in the mapping. The entries are placed at
1889 * @entries. find_get_entries() takes a reference against any actual
1890 * pages it returns.
1891 *
1892 * The search returns a group of mapping-contiguous page cache entries
1893 * with ascending indexes. There may be holes in the indices due to
1894 * not-present pages.
1895 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001896 * Any shadow entries of evicted pages, or swap entries from
1897 * shmem/tmpfs, are included in the returned array.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001898 *
Hugh Dickins71725ed2020-04-06 20:07:57 -07001899 * If it finds a Transparent Huge Page, head or tail, find_get_entries()
1900 * stops at that page: the caller is likely to have a better way to handle
1901 * the compound page as a whole, and then skip its extent, than repeatedly
1902 * calling find_get_entries() to return all its tails.
1903 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001904 * Return: the number of pages and shadow entries which were found.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001905 */
1906unsigned find_get_entries(struct address_space *mapping,
1907 pgoff_t start, unsigned int nr_entries,
1908 struct page **entries, pgoff_t *indices)
1909{
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001910 XA_STATE(xas, &mapping->i_pages, start);
1911 struct page *page;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001912 unsigned int ret = 0;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001913
1914 if (!nr_entries)
1915 return 0;
1916
1917 rcu_read_lock();
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001918 xas_for_each(&xas, page, ULONG_MAX) {
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001919 if (xas_retry(&xas, page))
Johannes Weiner0cd61442014-04-03 14:47:46 -07001920 continue;
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001921 /*
1922 * A shadow entry of a recently evicted page, a swap
1923 * entry from shmem/tmpfs or a DAX entry. Return it
1924 * without attempting to raise page count.
1925 */
1926 if (xa_is_value(page))
Johannes Weiner0cd61442014-04-03 14:47:46 -07001927 goto export;
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001928
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001929 if (!page_cache_get_speculative(page))
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001930 goto retry;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001931
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001932 /* Has the page moved or been split? */
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001933 if (unlikely(page != xas_reload(&xas)))
1934 goto put_page;
1935
Hugh Dickins71725ed2020-04-06 20:07:57 -07001936 /*
1937 * Terminate early on finding a THP, to allow the caller to
1938 * handle it all at once; but continue if this is hugetlbfs.
1939 */
1940 if (PageTransHuge(page) && !PageHuge(page)) {
1941 page = find_subpage(page, xas.xa_index);
1942 nr_entries = ret + 1;
1943 }
Johannes Weiner0cd61442014-04-03 14:47:46 -07001944export:
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001945 indices[ret] = xas.xa_index;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001946 entries[ret] = page;
1947 if (++ret == nr_entries)
1948 break;
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001949 continue;
1950put_page:
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001951 put_page(page);
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001952retry:
1953 xas_reset(&xas);
Johannes Weiner0cd61442014-04-03 14:47:46 -07001954 }
1955 rcu_read_unlock();
1956 return ret;
1957}
1958
1959/**
Jan Karab947cee2017-09-06 16:21:21 -07001960 * find_get_pages_range - gang pagecache lookup
Linus Torvalds1da177e2005-04-16 15:20:36 -07001961 * @mapping: The address_space to search
1962 * @start: The starting page index
Jan Karab947cee2017-09-06 16:21:21 -07001963 * @end: The final page index (inclusive)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001964 * @nr_pages: The maximum number of pages
1965 * @pages: Where the resulting pages are placed
1966 *
Jan Karab947cee2017-09-06 16:21:21 -07001967 * find_get_pages_range() will search for and return a group of up to @nr_pages
1968 * pages in the mapping starting at index @start and up to index @end
1969 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
1970 * a reference against the returned pages.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001971 *
1972 * The search returns a group of mapping-contiguous pages with ascending
1973 * indexes. There may be holes in the indices due to not-present pages.
Jan Karad72dc8a2017-09-06 16:21:18 -07001974 * We also update @start to index the next page for the traversal.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001975 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001976 * Return: the number of pages which were found. If this number is
1977 * smaller than @nr_pages, the end of specified range has been
Jan Karab947cee2017-09-06 16:21:21 -07001978 * reached.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001979 */
Jan Karab947cee2017-09-06 16:21:21 -07001980unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
1981 pgoff_t end, unsigned int nr_pages,
1982 struct page **pages)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001983{
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001984 XA_STATE(xas, &mapping->i_pages, *start);
1985 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001986 unsigned ret = 0;
1987
1988 if (unlikely(!nr_pages))
1989 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001990
Nick Piggina60637c2008-07-25 19:45:31 -07001991 rcu_read_lock();
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001992 xas_for_each(&xas, page, end) {
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001993 if (xas_retry(&xas, page))
Nick Piggina60637c2008-07-25 19:45:31 -07001994 continue;
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001995 /* Skip over shadow, swap and DAX entries */
1996 if (xa_is_value(page))
Hugh Dickins8079b1c2011-08-03 16:21:28 -07001997 continue;
Nick Piggina60637c2008-07-25 19:45:31 -07001998
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001999 if (!page_cache_get_speculative(page))
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04002000 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07002001
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002002 /* Has the page moved or been split? */
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04002003 if (unlikely(page != xas_reload(&xas)))
2004 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07002005
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002006 pages[ret] = find_subpage(page, xas.xa_index);
Jan Karab947cee2017-09-06 16:21:21 -07002007 if (++ret == nr_pages) {
Yu Zhao5d3ee422019-03-05 15:49:17 -08002008 *start = xas.xa_index + 1;
Jan Karab947cee2017-09-06 16:21:21 -07002009 goto out;
2010 }
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04002011 continue;
2012put_page:
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002013 put_page(page);
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04002014retry:
2015 xas_reset(&xas);
Nick Piggina60637c2008-07-25 19:45:31 -07002016 }
Hugh Dickins5b280c02011-03-22 16:33:07 -07002017
Jan Karab947cee2017-09-06 16:21:21 -07002018 /*
2019 * We come here when there is no page beyond @end. We take care to not
2020 * overflow the index @start as it confuses some of the callers. This
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04002021 * breaks the iteration when there is a page at index -1 but that is
Jan Karab947cee2017-09-06 16:21:21 -07002022 * already broken anyway.
2023 */
2024 if (end == (pgoff_t)-1)
2025 *start = (pgoff_t)-1;
2026 else
2027 *start = end + 1;
2028out:
Nick Piggina60637c2008-07-25 19:45:31 -07002029 rcu_read_unlock();
Jan Karad72dc8a2017-09-06 16:21:18 -07002030
Linus Torvalds1da177e2005-04-16 15:20:36 -07002031 return ret;
2032}
2033
Jens Axboeebf43502006-04-27 08:46:01 +02002034/**
2035 * find_get_pages_contig - gang contiguous pagecache lookup
2036 * @mapping: The address_space to search
2037 * @index: The starting page index
2038 * @nr_pages: The maximum number of pages
2039 * @pages: Where the resulting pages are placed
2040 *
2041 * find_get_pages_contig() works exactly like find_get_pages(), except
2042 * that the returned number of pages are guaranteed to be contiguous.
2043 *
Mike Rapoporta862f682019-03-05 15:48:42 -08002044 * Return: the number of pages which were found.
Jens Axboeebf43502006-04-27 08:46:01 +02002045 */
2046unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
2047 unsigned int nr_pages, struct page **pages)
2048{
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002049 XA_STATE(xas, &mapping->i_pages, index);
2050 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07002051 unsigned int ret = 0;
2052
2053 if (unlikely(!nr_pages))
2054 return 0;
Jens Axboeebf43502006-04-27 08:46:01 +02002055
Nick Piggina60637c2008-07-25 19:45:31 -07002056 rcu_read_lock();
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002057 for (page = xas_load(&xas); page; page = xas_next(&xas)) {
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002058 if (xas_retry(&xas, page))
2059 continue;
2060 /*
2061 * If the entry has been swapped out, we can stop looking.
2062 * No current caller is looking for DAX entries.
2063 */
2064 if (xa_is_value(page))
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07002065 break;
Hugh Dickins9d8aa4e2011-03-22 16:33:06 -07002066
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002067 if (!page_cache_get_speculative(page))
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002068 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07002069
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002070 /* Has the page moved or been split? */
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002071 if (unlikely(page != xas_reload(&xas)))
2072 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07002073
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002074 pages[ret] = find_subpage(page, xas.xa_index);
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07002075 if (++ret == nr_pages)
2076 break;
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002077 continue;
2078put_page:
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002079 put_page(page);
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002080retry:
2081 xas_reset(&xas);
Jens Axboeebf43502006-04-27 08:46:01 +02002082 }
Nick Piggina60637c2008-07-25 19:45:31 -07002083 rcu_read_unlock();
2084 return ret;
Jens Axboeebf43502006-04-27 08:46:01 +02002085}
David Howellsef71c152007-05-09 02:33:44 -07002086EXPORT_SYMBOL(find_get_pages_contig);
Jens Axboeebf43502006-04-27 08:46:01 +02002087
Randy Dunlap485bb992006-06-23 02:03:49 -07002088/**
Jan Kara72b045a2017-11-15 17:34:33 -08002089 * find_get_pages_range_tag - find and return pages in given range matching @tag
Randy Dunlap485bb992006-06-23 02:03:49 -07002090 * @mapping: the address_space to search
2091 * @index: the starting page index
Jan Kara72b045a2017-11-15 17:34:33 -08002092 * @end: The final page index (inclusive)
Randy Dunlap485bb992006-06-23 02:03:49 -07002093 * @tag: the tag index
2094 * @nr_pages: the maximum number of pages
2095 * @pages: where the resulting pages are placed
2096 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07002097 * Like find_get_pages, except we only return pages which are tagged with
Randy Dunlap485bb992006-06-23 02:03:49 -07002098 * @tag. We update @index to index the next page for the traversal.
Mike Rapoporta862f682019-03-05 15:48:42 -08002099 *
2100 * Return: the number of pages which were found.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002101 */
Jan Kara72b045a2017-11-15 17:34:33 -08002102unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002103 pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
Jan Kara72b045a2017-11-15 17:34:33 -08002104 struct page **pages)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002105{
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002106 XA_STATE(xas, &mapping->i_pages, *index);
2107 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07002108 unsigned ret = 0;
2109
2110 if (unlikely(!nr_pages))
2111 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002112
Nick Piggina60637c2008-07-25 19:45:31 -07002113 rcu_read_lock();
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002114 xas_for_each_marked(&xas, page, end, tag) {
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002115 if (xas_retry(&xas, page))
Nick Piggina60637c2008-07-25 19:45:31 -07002116 continue;
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002117 /*
2118 * Shadow entries should never be tagged, but this iteration
2119 * is lockless so there is a window for page reclaim to evict
2120 * a page we saw tagged. Skip over it.
2121 */
2122 if (xa_is_value(page))
Johannes Weiner139b6a62014-05-06 12:50:05 -07002123 continue;
Nick Piggina60637c2008-07-25 19:45:31 -07002124
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002125 if (!page_cache_get_speculative(page))
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002126 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07002127
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002128 /* Has the page moved or been split? */
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002129 if (unlikely(page != xas_reload(&xas)))
2130 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07002131
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002132 pages[ret] = find_subpage(page, xas.xa_index);
Jan Kara72b045a2017-11-15 17:34:33 -08002133 if (++ret == nr_pages) {
Yu Zhao5d3ee422019-03-05 15:49:17 -08002134 *index = xas.xa_index + 1;
Jan Kara72b045a2017-11-15 17:34:33 -08002135 goto out;
2136 }
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002137 continue;
2138put_page:
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002139 put_page(page);
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002140retry:
2141 xas_reset(&xas);
Nick Piggina60637c2008-07-25 19:45:31 -07002142 }
Hugh Dickins5b280c02011-03-22 16:33:07 -07002143
Jan Kara72b045a2017-11-15 17:34:33 -08002144 /*
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002145 * We come here when we got to @end. We take care to not overflow the
Jan Kara72b045a2017-11-15 17:34:33 -08002146 * index @index as it confuses some of the callers. This breaks the
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002147 * iteration when there is a page at index -1 but that is already
2148 * broken anyway.
Jan Kara72b045a2017-11-15 17:34:33 -08002149 */
2150 if (end == (pgoff_t)-1)
2151 *index = (pgoff_t)-1;
2152 else
2153 *index = end + 1;
2154out:
Nick Piggina60637c2008-07-25 19:45:31 -07002155 rcu_read_unlock();
2156
Linus Torvalds1da177e2005-04-16 15:20:36 -07002157 return ret;
2158}
Jan Kara72b045a2017-11-15 17:34:33 -08002159EXPORT_SYMBOL(find_get_pages_range_tag);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002160
Wu Fengguang76d42bd2006-06-25 05:48:43 -07002161/*
2162 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
2163 * a _large_ part of the i/o request. Imagine the worst scenario:
2164 *
2165 * ---R__________________________________________B__________
2166 * ^ reading here ^ bad block(assume 4k)
2167 *
2168 * read(R) => miss => readahead(R...B) => media error => frustrating retries
2169 * => failing the whole request => read(R) => read(R+1) =>
2170 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
2171 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
2172 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
2173 *
2174 * It is going insane. Fix it by quickly scaling down the readahead size.
2175 */
Souptick Joarder0f8e2db2020-04-01 21:04:50 -07002176static void shrink_readahead_size_eio(struct file_ra_state *ra)
Wu Fengguang76d42bd2006-06-25 05:48:43 -07002177{
Wu Fengguang76d42bd2006-06-25 05:48:43 -07002178 ra->ra_pages /= 4;
Wu Fengguang76d42bd2006-06-25 05:48:43 -07002179}
2180
Randy Dunlap485bb992006-06-23 02:03:49 -07002181/**
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002182 * generic_file_buffered_read - generic file read routine
2183 * @iocb: the iocb to read
Al Viro6e58e792014-02-03 17:07:03 -05002184 * @iter: data destination
2185 * @written: already copied
Randy Dunlap485bb992006-06-23 02:03:49 -07002186 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07002187 * This is a generic file read routine, and uses the
Randy Dunlap485bb992006-06-23 02:03:49 -07002188 * mapping->a_ops->readpage() function for the actual low-level stuff.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002189 *
2190 * This is really ugly. But the goto's actually try to clarify some
2191 * of the logic when it comes to error handling etc.
Mike Rapoporta862f682019-03-05 15:48:42 -08002192 *
2193 * Return:
2194 * * total number of bytes copied, including those the were already @written
2195 * * negative error code if nothing was copied
Linus Torvalds1da177e2005-04-16 15:20:36 -07002196 */
Goldwyn Rodriguesd85dc2e2019-08-30 12:09:24 -05002197ssize_t generic_file_buffered_read(struct kiocb *iocb,
Al Viro6e58e792014-02-03 17:07:03 -05002198 struct iov_iter *iter, ssize_t written)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002199{
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002200 struct file *filp = iocb->ki_filp;
Christoph Hellwig36e78912008-02-08 04:21:24 -08002201 struct address_space *mapping = filp->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002202 struct inode *inode = mapping->host;
Christoph Hellwig36e78912008-02-08 04:21:24 -08002203 struct file_ra_state *ra = &filp->f_ra;
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002204 loff_t *ppos = &iocb->ki_pos;
Fengguang Wu57f6b962007-10-16 01:24:37 -07002205 pgoff_t index;
2206 pgoff_t last_index;
2207 pgoff_t prev_index;
2208 unsigned long offset; /* offset into pagecache page */
Jan Karaec0f1632007-05-06 14:49:25 -07002209 unsigned int prev_offset;
Al Viro6e58e792014-02-03 17:07:03 -05002210 int error = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002211
Wei Fangc2a97372016-10-07 17:01:52 -07002212 if (unlikely(*ppos >= inode->i_sb->s_maxbytes))
Linus Torvaldsd05c5f72016-12-14 12:45:25 -08002213 return 0;
Kent Overstreet2cdcf642020-12-18 04:07:11 -05002214 if (unlikely(!iov_iter_count(iter)))
2215 return 0;
2216
Wei Fangc2a97372016-10-07 17:01:52 -07002217 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2218
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002219 index = *ppos >> PAGE_SHIFT;
2220 prev_index = ra->prev_pos >> PAGE_SHIFT;
2221 prev_offset = ra->prev_pos & (PAGE_SIZE-1);
2222 last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
2223 offset = *ppos & ~PAGE_MASK;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002224
Jens Axboe13bd6912020-10-17 08:31:29 -06002225 /*
2226 * If we've already successfully copied some data, then we
2227 * can no longer safely return -EIOCBQUEUED. Hence mark
2228 * an async read NOWAIT at that point.
2229 */
2230 if (written && (iocb->ki_flags & IOCB_WAITQ))
2231 iocb->ki_flags |= IOCB_NOWAIT;
2232
Linus Torvalds1da177e2005-04-16 15:20:36 -07002233 for (;;) {
2234 struct page *page;
Fengguang Wu57f6b962007-10-16 01:24:37 -07002235 pgoff_t end_index;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002236 loff_t isize;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002237 unsigned long nr, ret;
2238
Linus Torvalds1da177e2005-04-16 15:20:36 -07002239 cond_resched();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002240find_page:
Michal Hocko5abf1862017-02-03 13:13:29 -08002241 if (fatal_signal_pending(current)) {
2242 error = -EINTR;
2243 goto out;
2244 }
2245
Linus Torvalds1da177e2005-04-16 15:20:36 -07002246 page = find_get_page(mapping, index);
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002247 if (!page) {
Linus Torvaldscdc8fcb2020-08-03 13:01:22 -07002248 if (iocb->ki_flags & IOCB_NOIO)
Milosz Tanski3239d832017-08-29 16:13:19 +02002249 goto would_block;
Rusty Russellcf914a72007-07-19 01:48:08 -07002250 page_cache_sync_readahead(mapping,
Fengguang Wu7ff81072007-10-16 01:24:35 -07002251 ra, filp,
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002252 index, last_index - index);
2253 page = find_get_page(mapping, index);
2254 if (unlikely(page == NULL))
2255 goto no_cached_page;
2256 }
2257 if (PageReadahead(page)) {
Andreas Gruenbacher41da51b2019-11-21 23:25:07 +00002258 if (iocb->ki_flags & IOCB_NOIO) {
2259 put_page(page);
2260 goto out;
2261 }
Rusty Russellcf914a72007-07-19 01:48:08 -07002262 page_cache_async_readahead(mapping,
Fengguang Wu7ff81072007-10-16 01:24:35 -07002263 ra, filp, page,
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002264 index, last_index - index);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002265 }
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002266 if (!PageUptodate(page)) {
Mel Gormanebded022016-03-15 14:55:39 -07002267 /*
2268 * See comment in do_read_cache_page on why
2269 * wait_on_page_locked is used to avoid unnecessarily
2270 * serialisations and why it's safe.
2271 */
Jens Axboe1a0a7852020-05-22 09:18:38 -06002272 if (iocb->ki_flags & IOCB_WAITQ) {
2273 if (written) {
2274 put_page(page);
2275 goto out;
2276 }
2277 error = wait_on_page_locked_async(page,
2278 iocb->ki_waitq);
2279 } else {
2280 if (iocb->ki_flags & IOCB_NOWAIT) {
2281 put_page(page);
2282 goto would_block;
2283 }
2284 error = wait_on_page_locked_killable(page);
2285 }
Bart Van Asschec4b209a2016-10-07 16:58:33 -07002286 if (unlikely(error))
2287 goto readpage_error;
Mel Gormanebded022016-03-15 14:55:39 -07002288 if (PageUptodate(page))
2289 goto page_ok;
2290
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002291 if (inode->i_blkbits == PAGE_SHIFT ||
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002292 !mapping->a_ops->is_partially_uptodate)
2293 goto page_not_up_to_date;
Eryu Guan6d6d36b2016-11-01 15:43:07 +08002294 /* pipes can't handle partially uptodate pages */
David Howells00e23702018-10-22 13:07:28 +01002295 if (unlikely(iov_iter_is_pipe(iter)))
Eryu Guan6d6d36b2016-11-01 15:43:07 +08002296 goto page_not_up_to_date;
Nick Piggin529ae9a2008-08-02 12:01:03 +02002297 if (!trylock_page(page))
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002298 goto page_not_up_to_date;
Dave Hansen8d056cb2010-11-11 14:05:15 -08002299 /* Did it get truncated before we got the lock? */
2300 if (!page->mapping)
2301 goto page_not_up_to_date_locked;
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002302 if (!mapping->a_ops->is_partially_uptodate(page,
Al Viro6e58e792014-02-03 17:07:03 -05002303 offset, iter->count))
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002304 goto page_not_up_to_date_locked;
2305 unlock_page(page);
2306 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002307page_ok:
NeilBrowna32ea1e2007-07-17 04:03:04 -07002308 /*
2309 * i_size must be checked after we know the page is Uptodate.
2310 *
2311 * Checking i_size after the check allows us to calculate
2312 * the correct value for "nr", which means the zero-filled
2313 * part of the page is not copied back to userspace (unless
2314 * another truncate extends the file - this is desired though).
2315 */
2316
2317 isize = i_size_read(inode);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002318 end_index = (isize - 1) >> PAGE_SHIFT;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002319 if (unlikely(!isize || index > end_index)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002320 put_page(page);
NeilBrowna32ea1e2007-07-17 04:03:04 -07002321 goto out;
2322 }
2323
2324 /* nr is the maximum number of bytes to copy from this page */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002325 nr = PAGE_SIZE;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002326 if (index == end_index) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002327 nr = ((isize - 1) & ~PAGE_MASK) + 1;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002328 if (nr <= offset) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002329 put_page(page);
NeilBrowna32ea1e2007-07-17 04:03:04 -07002330 goto out;
2331 }
2332 }
2333 nr = nr - offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002334
2335 /* If users can be writing to this page using arbitrary
2336 * virtual addresses, take care about potential aliasing
2337 * before reading the page on the kernel side.
2338 */
2339 if (mapping_writably_mapped(mapping))
2340 flush_dcache_page(page);
2341
2342 /*
Jan Karaec0f1632007-05-06 14:49:25 -07002343 * When a sequential read accesses a page several times,
2344 * only mark it as accessed the first time.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002345 */
Jan Karaec0f1632007-05-06 14:49:25 -07002346 if (prev_index != index || offset != prev_offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002347 mark_page_accessed(page);
2348 prev_index = index;
2349
2350 /*
2351 * Ok, we have the page, and it's up-to-date, so
2352 * now we can copy it to user space...
Linus Torvalds1da177e2005-04-16 15:20:36 -07002353 */
Al Viro6e58e792014-02-03 17:07:03 -05002354
2355 ret = copy_page_to_iter(page, offset, nr, iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002356 offset += ret;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002357 index += offset >> PAGE_SHIFT;
2358 offset &= ~PAGE_MASK;
Jan Kara6ce745e2007-05-06 14:49:26 -07002359 prev_offset = offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002360
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002361 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002362 written += ret;
2363 if (!iov_iter_count(iter))
2364 goto out;
2365 if (ret < nr) {
2366 error = -EFAULT;
2367 goto out;
2368 }
2369 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002370
2371page_not_up_to_date:
2372 /* Get exclusive access to the page ... */
Jens Axboe0abed7c2020-11-16 13:36:24 -07002373 if (iocb->ki_flags & IOCB_WAITQ) {
2374 if (written) {
2375 put_page(page);
2376 goto out;
2377 }
Jens Axboe1a0a7852020-05-22 09:18:38 -06002378 error = lock_page_async(page, iocb->ki_waitq);
Jens Axboe0abed7c2020-11-16 13:36:24 -07002379 } else {
Jens Axboe1a0a7852020-05-22 09:18:38 -06002380 error = lock_page_killable(page);
Jens Axboe0abed7c2020-11-16 13:36:24 -07002381 }
Oleg Nesterov85462322008-06-08 21:20:43 +04002382 if (unlikely(error))
2383 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002384
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002385page_not_up_to_date_locked:
Nick Pigginda6052f2006-09-25 23:31:35 -07002386 /* Did it get truncated before we got the lock? */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002387 if (!page->mapping) {
2388 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002389 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002390 continue;
2391 }
2392
2393 /* Did somebody else fill it already? */
2394 if (PageUptodate(page)) {
2395 unlock_page(page);
2396 goto page_ok;
2397 }
2398
2399readpage:
Linus Torvaldscdc8fcb2020-08-03 13:01:22 -07002400 if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT)) {
Andreas Gruenbacher41da51b2019-11-21 23:25:07 +00002401 unlock_page(page);
2402 put_page(page);
2403 goto would_block;
2404 }
Jeff Moyer91803b42010-05-26 11:49:40 -04002405 /*
2406 * A previous I/O error may have been due to temporary
2407 * failures, eg. multipath errors.
2408 * PG_error will be set again if readpage fails.
2409 */
2410 ClearPageError(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002411 /* Start the actual read. The read will unlock the page. */
2412 error = mapping->a_ops->readpage(filp, page);
2413
Zach Brown994fc28c2005-12-15 14:28:17 -08002414 if (unlikely(error)) {
2415 if (error == AOP_TRUNCATED_PAGE) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002416 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002417 error = 0;
Zach Brown994fc28c2005-12-15 14:28:17 -08002418 goto find_page;
2419 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002420 goto readpage_error;
Zach Brown994fc28c2005-12-15 14:28:17 -08002421 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002422
2423 if (!PageUptodate(page)) {
Jens Axboe0abed7c2020-11-16 13:36:24 -07002424 if (iocb->ki_flags & IOCB_WAITQ) {
2425 if (written) {
2426 put_page(page);
2427 goto out;
2428 }
Hao Xuc8d317a2020-09-29 20:00:45 +08002429 error = lock_page_async(page, iocb->ki_waitq);
Jens Axboe0abed7c2020-11-16 13:36:24 -07002430 } else {
Hao Xuc8d317a2020-09-29 20:00:45 +08002431 error = lock_page_killable(page);
Jens Axboe0abed7c2020-11-16 13:36:24 -07002432 }
Hao Xuc8d317a2020-09-29 20:00:45 +08002433
Oleg Nesterov85462322008-06-08 21:20:43 +04002434 if (unlikely(error))
2435 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002436 if (!PageUptodate(page)) {
2437 if (page->mapping == NULL) {
2438 /*
Christoph Hellwig2ecdc822010-01-26 17:27:20 +01002439 * invalidate_mapping_pages got it
Linus Torvalds1da177e2005-04-16 15:20:36 -07002440 */
2441 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002442 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002443 goto find_page;
2444 }
2445 unlock_page(page);
Souptick Joarder0f8e2db2020-04-01 21:04:50 -07002446 shrink_readahead_size_eio(ra);
Oleg Nesterov85462322008-06-08 21:20:43 +04002447 error = -EIO;
2448 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002449 }
2450 unlock_page(page);
2451 }
2452
Linus Torvalds1da177e2005-04-16 15:20:36 -07002453 goto page_ok;
2454
2455readpage_error:
2456 /* UHHUH! A synchronous read error occurred. Report it */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002457 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002458 goto out;
2459
2460no_cached_page:
2461 /*
2462 * Ok, it wasn't cached, so we need to create a new
2463 * page..
2464 */
Mel Gorman453f85d2017-11-15 17:38:03 -08002465 page = page_cache_alloc(mapping);
Nick Piggineb2be182007-10-16 01:24:57 -07002466 if (!page) {
Al Viro6e58e792014-02-03 17:07:03 -05002467 error = -ENOMEM;
Nick Piggineb2be182007-10-16 01:24:57 -07002468 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002469 }
Michal Hocko6afdb852015-06-24 16:58:06 -07002470 error = add_to_page_cache_lru(page, mapping, index,
Michal Hockoc62d2552015-11-06 16:28:49 -08002471 mapping_gfp_constraint(mapping, GFP_KERNEL));
Linus Torvalds1da177e2005-04-16 15:20:36 -07002472 if (error) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002473 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002474 if (error == -EEXIST) {
2475 error = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002476 goto find_page;
Al Viro6e58e792014-02-03 17:07:03 -05002477 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002478 goto out;
2479 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002480 goto readpage;
2481 }
2482
Milosz Tanski3239d832017-08-29 16:13:19 +02002483would_block:
2484 error = -EAGAIN;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002485out:
Fengguang Wu7ff81072007-10-16 01:24:35 -07002486 ra->prev_pos = prev_index;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002487 ra->prev_pos <<= PAGE_SHIFT;
Fengguang Wu7ff81072007-10-16 01:24:35 -07002488 ra->prev_pos |= prev_offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002489
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002490 *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
Krishna Kumar0c6aa262008-10-15 22:01:13 -07002491 file_accessed(filp);
Al Viro6e58e792014-02-03 17:07:03 -05002492 return written ? written : error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002493}
Goldwyn Rodriguesd85dc2e2019-08-30 12:09:24 -05002494EXPORT_SYMBOL_GPL(generic_file_buffered_read);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002495
Randy Dunlap485bb992006-06-23 02:03:49 -07002496/**
Al Viro6abd2322014-04-04 14:20:57 -04002497 * generic_file_read_iter - generic filesystem read routine
Randy Dunlap485bb992006-06-23 02:03:49 -07002498 * @iocb: kernel I/O control block
Al Viro6abd2322014-04-04 14:20:57 -04002499 * @iter: destination for the data read
Randy Dunlap485bb992006-06-23 02:03:49 -07002500 *
Al Viro6abd2322014-04-04 14:20:57 -04002501 * This is the "read_iter()" routine for all filesystems
Linus Torvalds1da177e2005-04-16 15:20:36 -07002502 * that can use the page cache directly.
Andreas Gruenbacher41da51b2019-11-21 23:25:07 +00002503 *
2504 * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
2505 * be returned when no data can be read without waiting for I/O requests
2506 * to complete; it doesn't prevent readahead.
2507 *
2508 * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
2509 * requests shall be made for the read or for readahead. When no data
2510 * can be read, -EAGAIN shall be returned. When readahead would be
2511 * triggered, a partial, possibly empty read shall be returned.
2512 *
Mike Rapoporta862f682019-03-05 15:48:42 -08002513 * Return:
2514 * * number of bytes copied, even for partial reads
Andreas Gruenbacher41da51b2019-11-21 23:25:07 +00002515 * * negative error code (or 0 if IOCB_NOIO) if nothing was read
Linus Torvalds1da177e2005-04-16 15:20:36 -07002516 */
2517ssize_t
Al Viroed978a82014-03-05 22:53:04 -05002518generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002519{
Nicolai Stangee7080a42016-03-25 14:22:14 -07002520 size_t count = iov_iter_count(iter);
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002521 ssize_t retval = 0;
Nicolai Stangee7080a42016-03-25 14:22:14 -07002522
2523 if (!count)
2524 goto out; /* skip atime */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002525
Al Viro2ba48ce2015-04-09 13:52:01 -04002526 if (iocb->ki_flags & IOCB_DIRECT) {
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002527 struct file *file = iocb->ki_filp;
Al Viroed978a82014-03-05 22:53:04 -05002528 struct address_space *mapping = file->f_mapping;
2529 struct inode *inode = mapping->host;
Badari Pulavarty543ade12006-09-30 23:28:48 -07002530 loff_t size;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002531
Linus Torvalds1da177e2005-04-16 15:20:36 -07002532 size = i_size_read(inode);
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05002533 if (iocb->ki_flags & IOCB_NOWAIT) {
2534 if (filemap_range_has_page(mapping, iocb->ki_pos,
2535 iocb->ki_pos + count - 1))
2536 return -EAGAIN;
2537 } else {
2538 retval = filemap_write_and_wait_range(mapping,
2539 iocb->ki_pos,
2540 iocb->ki_pos + count - 1);
2541 if (retval < 0)
2542 goto out;
2543 }
Al Viroed978a82014-03-05 22:53:04 -05002544
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002545 file_accessed(file);
2546
Al Viro5ecda132017-04-13 14:13:36 -04002547 retval = mapping->a_ops->direct_IO(iocb, iter);
Al Viroc3a69022016-10-10 13:26:27 -04002548 if (retval >= 0) {
Christoph Hellwigc64fb5c2016-04-07 08:51:55 -07002549 iocb->ki_pos += retval;
Al Viro5ecda132017-04-13 14:13:36 -04002550 count -= retval;
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002551 }
Al Viro5b47d592017-05-08 13:54:47 -04002552 iov_iter_revert(iter, count - iov_iter_count(iter));
Josef Bacik66f998f2010-05-23 11:00:54 -04002553
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002554 /*
2555 * Btrfs can have a short DIO read if we encounter
2556 * compressed extents, so if there was an error, or if
2557 * we've already read everything we wanted to, or if
2558 * there was a short read because we hit EOF, go ahead
2559 * and return. Otherwise fallthrough to buffered io for
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08002560 * the rest of the read. Buffered reads will not work for
2561 * DAX files, so don't bother trying.
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002562 */
Al Viro5ecda132017-04-13 14:13:36 -04002563 if (retval < 0 || !count || iocb->ki_pos >= size ||
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002564 IS_DAX(inode))
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002565 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002566 }
2567
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002568 retval = generic_file_buffered_read(iocb, iter, retval);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002569out:
2570 return retval;
2571}
Al Viroed978a82014-03-05 22:53:04 -05002572EXPORT_SYMBOL(generic_file_read_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002573
Linus Torvalds1da177e2005-04-16 15:20:36 -07002574#ifdef CONFIG_MMU
Linus Torvalds1da177e2005-04-16 15:20:36 -07002575#define MMAP_LOTSAMISS (100)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002576/*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002577 * lock_page_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002578 * @vmf - the vm_fault for this fault.
2579 * @page - the page to lock.
2580 * @fpin - the pointer to the file we may pin (or is already pinned).
2581 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002582 * This works similar to lock_page_or_retry in that it can drop the mmap_lock.
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002583 * It differs in that it actually returns the page locked if it returns 1 and 0
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002584 * if it couldn't lock the page. If we did have to drop the mmap_lock then fpin
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002585 * will point to the pinned file and needs to be fput()'ed at a later point.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002586 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002587static int lock_page_maybe_drop_mmap(struct vm_fault *vmf, struct page *page,
2588 struct file **fpin)
2589{
2590 if (trylock_page(page))
2591 return 1;
2592
Linus Torvalds8b0f9fa2019-03-15 11:26:07 -07002593 /*
2594 * NOTE! This will make us return with VM_FAULT_RETRY, but with
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002595 * the mmap_lock still held. That's how FAULT_FLAG_RETRY_NOWAIT
Linus Torvalds8b0f9fa2019-03-15 11:26:07 -07002596 * is supposed to work. We have way too many special cases..
2597 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002598 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2599 return 0;
2600
2601 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2602 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2603 if (__lock_page_killable(page)) {
2604 /*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002605 * We didn't have the right flags to drop the mmap_lock,
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002606 * but all fault_handlers only check for fatal signals
2607 * if we return VM_FAULT_RETRY, so we need to drop the
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002608 * mmap_lock here and return 0 if we don't have a fpin.
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002609 */
2610 if (*fpin == NULL)
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07002611 mmap_read_unlock(vmf->vma->vm_mm);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002612 return 0;
2613 }
2614 } else
2615 __lock_page(page);
2616 return 1;
2617}
2618
2619
2620/*
2621 * Synchronous readahead happens when we don't even find a page in the page
2622 * cache at all. We don't want to perform IO under the mmap sem, so if we have
2623 * to drop the mmap sem we return the file that was pinned in order for us to do
2624 * that. If we didn't pin a file then we return NULL. The file that is
2625 * returned needs to be fput()'ed when we're done with it.
2626 */
2627static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002628{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002629 struct file *file = vmf->vma->vm_file;
2630 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002631 struct address_space *mapping = file->f_mapping;
David Howellsdb660d42020-10-15 20:06:31 -07002632 DEFINE_READAHEAD(ractl, file, mapping, vmf->pgoff);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002633 struct file *fpin = NULL;
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002634 unsigned int mmap_miss;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002635
2636 /* If we don't want any read-ahead, don't bother */
Josef Bacik2a1180f2019-03-13 11:44:18 -07002637 if (vmf->vma->vm_flags & VM_RAND_READ)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002638 return fpin;
Wu Fengguang275b12b2011-05-24 17:12:28 -07002639 if (!ra->ra_pages)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002640 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002641
Josef Bacik2a1180f2019-03-13 11:44:18 -07002642 if (vmf->vma->vm_flags & VM_SEQ_READ) {
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002643 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
David Howellsdb660d42020-10-15 20:06:31 -07002644 page_cache_sync_ra(&ractl, ra, ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002645 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002646 }
2647
Andi Kleen207d04b2011-05-24 17:12:29 -07002648 /* Avoid banging the cache line if not needed */
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002649 mmap_miss = READ_ONCE(ra->mmap_miss);
2650 if (mmap_miss < MMAP_LOTSAMISS * 10)
2651 WRITE_ONCE(ra->mmap_miss, ++mmap_miss);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002652
2653 /*
2654 * Do we miss much more than hit in this file? If so,
2655 * stop bothering with read-ahead. It will only hurt.
2656 */
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002657 if (mmap_miss > MMAP_LOTSAMISS)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002658 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002659
Wu Fengguangd30a1102009-06-16 15:31:30 -07002660 /*
2661 * mmap read-around
2662 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002663 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
David Howellsdb660d42020-10-15 20:06:31 -07002664 ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2);
Roman Gushchin600e19a2015-11-05 18:47:08 -08002665 ra->size = ra->ra_pages;
2666 ra->async_size = ra->ra_pages / 4;
Oven4782c8c2023-06-16 20:51:14 +08002667 trace_android_vh_tune_mmap_readaround(ra->ra_pages, vmf->pgoff,
2668 &ra->start, &ra->size, &ra->async_size);
David Howellsdb660d42020-10-15 20:06:31 -07002669 ractl._index = ra->start;
2670 do_page_cache_ra(&ractl, ra->size, ra->async_size);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002671 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002672}
2673
2674/*
2675 * Asynchronous readahead happens when we find the page and PG_readahead,
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002676 * so we want to possibly extend the readahead further. We return the file that
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002677 * was pinned if we have to drop the mmap_lock in order to do IO.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002678 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002679static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2680 struct page *page)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002681{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002682 struct file *file = vmf->vma->vm_file;
2683 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002684 struct address_space *mapping = file->f_mapping;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002685 struct file *fpin = NULL;
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002686 unsigned int mmap_miss;
Josef Bacik2a1180f2019-03-13 11:44:18 -07002687 pgoff_t offset = vmf->pgoff;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002688
2689 /* If we don't want any read-ahead, don't bother */
Jan Kara5c72fee2020-04-01 21:04:40 -07002690 if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002691 return fpin;
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002692 mmap_miss = READ_ONCE(ra->mmap_miss);
2693 if (mmap_miss)
2694 WRITE_ONCE(ra->mmap_miss, --mmap_miss);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002695 if (PageReadahead(page)) {
2696 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Wu Fengguang2fad6f52009-06-16 15:31:29 -07002697 page_cache_async_readahead(mapping, ra, file,
2698 page, offset, ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002699 }
2700 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002701}
2702
Randy Dunlap485bb992006-06-23 02:03:49 -07002703/**
Nick Piggin54cb8822007-07-19 01:46:59 -07002704 * filemap_fault - read in file data for page fault handling
Nick Piggind0217ac2007-07-19 01:47:03 -07002705 * @vmf: struct vm_fault containing details of the fault
Randy Dunlap485bb992006-06-23 02:03:49 -07002706 *
Nick Piggin54cb8822007-07-19 01:46:59 -07002707 * filemap_fault() is invoked via the vma operations vector for a
Linus Torvalds1da177e2005-04-16 15:20:36 -07002708 * mapped memory region to read in file data during a page fault.
2709 *
2710 * The goto's are kind of ugly, but this streamlines the normal case of having
2711 * it in the page cache, and handles the special cases reasonably without
2712 * having a lot of duplicated code.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002713 *
Michel Lespinasse59d4d122021-04-29 10:28:25 -07002714 * If FAULT_FLAG_SPECULATIVE is set, this function runs with elevated vma
2715 * refcount and with mmap lock not held.
2716 * Otherwise, vma->vm_mm->mmap_lock must be held on entry.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002717 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002718 * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
Yang Shia4985832019-07-11 20:55:29 -07002719 * may be dropped before doing I/O or by lock_page_maybe_drop_mmap().
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002720 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002721 * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002722 * has not been released.
2723 *
2724 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
Mike Rapoporta862f682019-03-05 15:48:42 -08002725 *
2726 * Return: bitwise-OR of %VM_FAULT_ codes.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002727 */
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002728vm_fault_t filemap_fault(struct vm_fault *vmf)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002729{
2730 int error;
Dave Jiang11bac802017-02-24 14:56:41 -08002731 struct file *file = vmf->vma->vm_file;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002732 struct file *fpin = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002733 struct address_space *mapping = file->f_mapping;
2734 struct file_ra_state *ra = &file->f_ra;
2735 struct inode *inode = mapping->host;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002736 pgoff_t offset = vmf->pgoff;
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002737 pgoff_t max_off;
Liangliang Lida33f6f2021-06-08 10:00:02 +08002738 struct page *page = NULL;
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002739 vm_fault_t ret = 0;
Liangliang Lida33f6f2021-06-08 10:00:02 +08002740 bool retry = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002741
Michel Lespinasse59d4d122021-04-29 10:28:25 -07002742 if (vmf->flags & FAULT_FLAG_SPECULATIVE) {
2743 page = find_get_page(mapping, offset);
Patrick Daly1d052132022-10-10 19:25:27 -07002744 if (unlikely(!page))
Michel Lespinasse59d4d122021-04-29 10:28:25 -07002745 return VM_FAULT_RETRY;
2746
Patrick Daly1d052132022-10-10 19:25:27 -07002747 if (unlikely(PageReadahead(page)))
2748 goto page_put;
2749
Michel Lespinasse59d4d122021-04-29 10:28:25 -07002750 if (!trylock_page(page))
Patrick Daly1d052132022-10-10 19:25:27 -07002751 goto page_put;
Michel Lespinasse59d4d122021-04-29 10:28:25 -07002752
2753 if (unlikely(compound_head(page)->mapping != mapping))
2754 goto page_unlock;
2755 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
2756 if (unlikely(!PageUptodate(page)))
2757 goto page_unlock;
2758
2759 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2760 if (unlikely(offset >= max_off))
2761 goto page_unlock;
2762
2763 /*
2764 * Update readahead mmap_miss statistic.
2765 *
2766 * Note that we are not sure if finish_fault() will
2767 * manage to complete the transaction. If it fails,
2768 * we'll come back to filemap_fault() non-speculative
2769 * case which will update mmap_miss a second time.
2770 * This is not ideal, we would prefer to guarantee the
2771 * update will happen exactly once.
2772 */
2773 if (!(vmf->vma->vm_flags & VM_RAND_READ) && ra->ra_pages) {
2774 unsigned int mmap_miss = READ_ONCE(ra->mmap_miss);
2775 if (mmap_miss)
2776 WRITE_ONCE(ra->mmap_miss, --mmap_miss);
2777 }
2778
2779 vmf->page = page;
2780 return VM_FAULT_LOCKED;
2781page_unlock:
2782 unlock_page(page);
Patrick Daly1d052132022-10-10 19:25:27 -07002783page_put:
2784 put_page(page);
Michel Lespinasse59d4d122021-04-29 10:28:25 -07002785 return VM_FAULT_RETRY;
2786 }
2787
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002788 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2789 if (unlikely(offset >= max_off))
Linus Torvalds5307cc12007-10-31 09:19:46 -07002790 return VM_FAULT_SIGBUS;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002791
Liangliang Lida33f6f2021-06-08 10:00:02 +08002792 trace_android_vh_filemap_fault_get_page(vmf, &page, &retry);
2793 if (unlikely(retry))
2794 goto out_retry;
2795 if (unlikely(page))
2796 goto page_ok;
2797
Linus Torvalds1da177e2005-04-16 15:20:36 -07002798 /*
Johannes Weiner49426422013-10-16 13:46:59 -07002799 * Do we have something in the page cache already?
Linus Torvalds1da177e2005-04-16 15:20:36 -07002800 */
Linus Torvaldsef00e082009-06-16 15:31:25 -07002801 page = find_get_page(mapping, offset);
Shaohua Li45cac652012-10-08 16:32:19 -07002802 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002803 /*
Linus Torvaldsef00e082009-06-16 15:31:25 -07002804 * We found the page, so try async readahead before
2805 * waiting for the lock.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002806 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002807 fpin = do_async_mmap_readahead(vmf, page);
Shaohua Li45cac652012-10-08 16:32:19 -07002808 } else if (!page) {
Linus Torvaldsef00e082009-06-16 15:31:25 -07002809 /* No page in the page cache at all */
Linus Torvaldsef00e082009-06-16 15:31:25 -07002810 count_vm_event(PGMAJFAULT);
Roman Gushchin22621852017-07-06 15:40:25 -07002811 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002812 ret = VM_FAULT_MAJOR;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002813 fpin = do_sync_mmap_readahead(vmf);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002814retry_find:
Josef Bacika75d4c32019-03-13 11:44:14 -07002815 page = pagecache_get_page(mapping, offset,
2816 FGP_CREAT|FGP_FOR_MMAP,
2817 vmf->gfp_mask);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002818 if (!page) {
2819 if (fpin)
2820 goto out_retry;
Matthew Wilcox (Oracle)e520e932020-04-01 21:04:53 -07002821 return VM_FAULT_OOM;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002822 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002823 }
2824
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002825 if (!lock_page_maybe_drop_mmap(vmf, page, &fpin))
2826 goto out_retry;
Michel Lespinasseb522c942010-10-26 14:21:56 -07002827
2828 /* Did it get truncated? */
Song Liu585e5a72019-09-23 15:37:44 -07002829 if (unlikely(compound_head(page)->mapping != mapping)) {
Michel Lespinasseb522c942010-10-26 14:21:56 -07002830 unlock_page(page);
2831 put_page(page);
2832 goto retry_find;
2833 }
Song Liu520e5ba2019-09-23 15:37:50 -07002834 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
Michel Lespinasseb522c942010-10-26 14:21:56 -07002835
Linus Torvalds1da177e2005-04-16 15:20:36 -07002836 /*
Nick Piggind00806b2007-07-19 01:46:57 -07002837 * We have a locked page in the page cache, now we need to check
2838 * that it's up-to-date. If not, it is going to be due to an error.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002839 */
Nick Piggind00806b2007-07-19 01:46:57 -07002840 if (unlikely(!PageUptodate(page)))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002841 goto page_not_uptodate;
2842
Linus Torvaldsef00e082009-06-16 15:31:25 -07002843 /*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002844 * We've made it this far and we had to drop our mmap_lock, now is the
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002845 * time to return to the upper layer and have it re-find the vma and
2846 * redo the fault.
2847 */
2848 if (fpin) {
2849 unlock_page(page);
2850 goto out_retry;
2851 }
2852
Liangliang Lida33f6f2021-06-08 10:00:02 +08002853page_ok:
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002854 /*
Linus Torvaldsef00e082009-06-16 15:31:25 -07002855 * Found the page and have a reference on it.
2856 * We must recheck i_size under page lock.
2857 */
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002858 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2859 if (unlikely(offset >= max_off)) {
Nick Piggind00806b2007-07-19 01:46:57 -07002860 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002861 put_page(page);
Linus Torvalds5307cc12007-10-31 09:19:46 -07002862 return VM_FAULT_SIGBUS;
Nick Piggind00806b2007-07-19 01:46:57 -07002863 }
2864
Nick Piggind0217ac2007-07-19 01:47:03 -07002865 vmf->page = page;
Nick Piggin83c54072007-07-19 01:47:05 -07002866 return ret | VM_FAULT_LOCKED;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002867
Linus Torvalds1da177e2005-04-16 15:20:36 -07002868page_not_uptodate:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002869 /*
2870 * Umm, take care of errors if the page isn't up-to-date.
2871 * Try to re-read it _once_. We do this synchronously,
2872 * because there really aren't any performance issues here
2873 * and we need to check for errors.
2874 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002875 ClearPageError(page);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002876 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Zach Brown994fc28c2005-12-15 14:28:17 -08002877 error = mapping->a_ops->readpage(file, page);
Miklos Szeredi3ef0f722008-05-14 16:05:37 -07002878 if (!error) {
2879 wait_on_page_locked(page);
2880 if (!PageUptodate(page))
2881 error = -EIO;
2882 }
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002883 if (fpin)
2884 goto out_retry;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002885 put_page(page);
Nick Piggind00806b2007-07-19 01:46:57 -07002886
2887 if (!error || error == AOP_TRUNCATED_PAGE)
2888 goto retry_find;
2889
Souptick Joarder0f8e2db2020-04-01 21:04:50 -07002890 shrink_readahead_size_eio(ra);
Nick Piggind0217ac2007-07-19 01:47:03 -07002891 return VM_FAULT_SIGBUS;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002892
2893out_retry:
2894 /*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002895 * We dropped the mmap_lock, we need to return to the fault handler to
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002896 * re-find the vma and come back and find our hopefully still populated
2897 * page.
2898 */
Liangliang Lida33f6f2021-06-08 10:00:02 +08002899 if (page) {
2900 trace_android_vh_filemap_fault_cache_page(vmf, page);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002901 put_page(page);
Liangliang Lida33f6f2021-06-08 10:00:02 +08002902 }
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002903 if (fpin)
2904 fput(fpin);
2905 return ret | VM_FAULT_RETRY;
Nick Piggin54cb8822007-07-19 01:46:59 -07002906}
2907EXPORT_SYMBOL(filemap_fault);
2908
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03002909static bool filemap_map_pmd(struct vm_fault *vmf, struct page *page)
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002910{
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03002911 struct mm_struct *mm = vmf->vma->vm_mm;
2912
2913 /* Huge page is mapped? No need to proceed. */
2914 if (pmd_trans_huge(*vmf->pmd)) {
2915 unlock_page(page);
2916 put_page(page);
2917 return true;
2918 }
2919
2920 if (pmd_none(*vmf->pmd) && PageTransHuge(page)) {
2921 vm_fault_t ret = do_set_pmd(vmf, page);
2922 if (!ret) {
2923 /* The page is mapped successfully, reference consumed. */
2924 unlock_page(page);
2925 return true;
2926 }
2927 }
2928
2929 if (pmd_none(*vmf->pmd)) {
2930 vmf->ptl = pmd_lock(mm, vmf->pmd);
2931 if (likely(pmd_none(*vmf->pmd))) {
2932 mm_inc_nr_ptes(mm);
2933 pmd_populate(mm, vmf->pmd, vmf->prealloc_pte);
2934 vmf->prealloc_pte = NULL;
2935 }
2936 spin_unlock(vmf->ptl);
2937 }
2938
2939 /* See comment in handle_pte_fault() */
2940 if (pmd_devmap_trans_unstable(vmf->pmd)) {
2941 unlock_page(page);
2942 put_page(page);
2943 return true;
2944 }
2945
2946 return false;
2947}
2948
2949static struct page *next_uptodate_page(struct page *page,
2950 struct address_space *mapping,
2951 struct xa_state *xas, pgoff_t end_pgoff)
2952{
2953 unsigned long max_idx;
2954
2955 do {
2956 if (!page)
2957 return NULL;
2958 if (xas_retry(xas, page))
2959 continue;
2960 if (xa_is_value(page))
2961 continue;
2962 if (PageLocked(page))
2963 continue;
2964 if (!page_cache_get_speculative(page))
2965 continue;
2966 /* Has the page moved or been split? */
2967 if (unlikely(page != xas_reload(xas)))
2968 goto skip;
2969 if (!PageUptodate(page) || PageReadahead(page))
2970 goto skip;
2971 if (PageHWPoison(page))
2972 goto skip;
2973 if (!trylock_page(page))
2974 goto skip;
2975 if (page->mapping != mapping)
2976 goto unlock;
2977 if (!PageUptodate(page))
2978 goto unlock;
2979 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2980 if (xas->xa_index >= max_idx)
2981 goto unlock;
2982 return page;
2983unlock:
2984 unlock_page(page);
2985skip:
2986 put_page(page);
2987 } while ((page = xas_next_entry(xas, end_pgoff)) != NULL);
2988
2989 return NULL;
2990}
2991
2992static inline struct page *first_map_page(struct address_space *mapping,
2993 struct xa_state *xas,
2994 pgoff_t end_pgoff)
2995{
2996 return next_uptodate_page(xas_find(xas, end_pgoff),
2997 mapping, xas, end_pgoff);
2998}
2999
3000static inline struct page *next_map_page(struct address_space *mapping,
3001 struct xa_state *xas,
3002 pgoff_t end_pgoff)
3003{
3004 return next_uptodate_page(xas_next_entry(xas, end_pgoff),
3005 mapping, xas, end_pgoff);
3006}
3007
Vinayak Menon35eacb52021-03-18 15:20:17 +05303008#ifdef CONFIG_SPECULATIVE_PAGE_FAULT
3009bool filemap_allow_speculation(void)
3010{
3011 return true;
3012}
3013EXPORT_SYMBOL_GPL(filemap_allow_speculation);
3014#endif
3015
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003016vm_fault_t filemap_map_pages(struct vm_fault *vmf,
3017 pgoff_t start_pgoff, pgoff_t end_pgoff)
3018{
3019 struct vm_area_struct *vma = vmf->vma;
3020 struct file *file = vma->vm_file;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003021 struct address_space *mapping = file->f_mapping;
Kirill A. Shutemovbae473a2016-07-26 15:25:20 -07003022 pgoff_t last_pgoff = start_pgoff;
Will Deacondb6cf102021-01-14 15:24:19 +00003023 unsigned long addr;
Matthew Wilcox070e8072018-05-17 00:08:30 -04003024 XA_STATE(xas, &mapping->i_pages, start_pgoff);
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003025 struct page *head, *page;
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07003026 unsigned int mmap_miss = READ_ONCE(file->f_ra.mmap_miss);
Suren Baghdasaryan2bb39b92022-11-18 15:36:13 -08003027 vm_fault_t ret = (vmf->flags & FAULT_FLAG_SPECULATIVE) ?
3028 VM_FAULT_RETRY : 0;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003029
3030 rcu_read_lock();
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003031 head = first_map_page(mapping, &xas, end_pgoff);
3032 if (!head)
3033 goto out;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003034
Suren Baghdasaryan2bb39b92022-11-18 15:36:13 -08003035 if (!(vmf->flags & FAULT_FLAG_SPECULATIVE) &&
3036 filemap_map_pmd(vmf, head)) {
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003037 ret = VM_FAULT_NOPAGE;
3038 goto out;
3039 }
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003040
Will Deacondb6cf102021-01-14 15:24:19 +00003041 addr = vma->vm_start + ((start_pgoff - vma->vm_pgoff) << PAGE_SHIFT);
Vinayak Menon35eacb52021-03-18 15:20:17 +05303042 if (!pte_map_lock_addr(vmf, addr)) {
Vinayak Menon4d9d8662021-09-13 16:27:10 +05303043 unlock_page(head);
3044 put_page(head);
Vinayak Menon35eacb52021-03-18 15:20:17 +05303045 goto out;
3046 }
3047
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003048 do {
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003049 page = find_subpage(head, xas.xa_index);
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003050 if (PageHWPoison(page))
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003051 goto unlock;
3052
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07003053 if (mmap_miss > 0)
3054 mmap_miss--;
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07003055
Will Deacondb6cf102021-01-14 15:24:19 +00003056 addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003057 vmf->pte += xas.xa_index - last_pgoff;
Matthew Wilcox070e8072018-05-17 00:08:30 -04003058 last_pgoff = xas.xa_index;
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003059
3060 if (!pte_none(*vmf->pte))
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07003061 goto unlock;
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003062
Will Deaconef3b7322020-11-24 18:48:26 +00003063 /* We're about to handle the fault */
Will Deacondb6cf102021-01-14 15:24:19 +00003064 if (vmf->address == addr)
Will Deaconef3b7322020-11-24 18:48:26 +00003065 ret = VM_FAULT_NOPAGE;
Will Deaconef3b7322020-11-24 18:48:26 +00003066
Will Deacondb6cf102021-01-14 15:24:19 +00003067 do_set_pte(vmf, page, addr);
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003068 /* no need to invalidate: a not-present page won't be cached */
Will Deacondb6cf102021-01-14 15:24:19 +00003069 update_mmu_cache(vma, addr, vmf->pte);
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003070 unlock_page(head);
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003071 continue;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003072unlock:
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003073 unlock_page(head);
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003074 put_page(head);
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003075 } while ((head = next_map_page(mapping, &xas, end_pgoff)) != NULL);
3076 pte_unmap_unlock(vmf->pte, vmf->ptl);
3077out:
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003078 rcu_read_unlock();
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07003079 WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss);
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003080 return ret;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003081}
3082EXPORT_SYMBOL(filemap_map_pages);
3083
Souptick Joarder2bcd6452018-06-07 17:08:00 -07003084vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Jan Kara4fcf1c62012-06-12 16:20:29 +02003085{
3086 struct page *page = vmf->page;
Dave Jiang11bac802017-02-24 14:56:41 -08003087 struct inode *inode = file_inode(vmf->vma->vm_file);
Souptick Joarder2bcd6452018-06-07 17:08:00 -07003088 vm_fault_t ret = VM_FAULT_LOCKED;
Jan Kara4fcf1c62012-06-12 16:20:29 +02003089
Jan Kara14da9202012-06-12 16:20:37 +02003090 sb_start_pagefault(inode->i_sb);
Dave Jiang11bac802017-02-24 14:56:41 -08003091 file_update_time(vmf->vma->vm_file);
Jan Kara4fcf1c62012-06-12 16:20:29 +02003092 lock_page(page);
3093 if (page->mapping != inode->i_mapping) {
3094 unlock_page(page);
3095 ret = VM_FAULT_NOPAGE;
3096 goto out;
3097 }
Jan Kara14da9202012-06-12 16:20:37 +02003098 /*
3099 * We mark the page dirty already here so that when freeze is in
3100 * progress, we are guaranteed that writeback during freezing will
3101 * see the dirty page and writeprotect it again.
3102 */
3103 set_page_dirty(page);
Darrick J. Wong1d1d1a72013-02-21 16:42:51 -08003104 wait_for_stable_page(page);
Jan Kara4fcf1c62012-06-12 16:20:29 +02003105out:
Jan Kara14da9202012-06-12 16:20:37 +02003106 sb_end_pagefault(inode->i_sb);
Jan Kara4fcf1c62012-06-12 16:20:29 +02003107 return ret;
3108}
Jan Kara4fcf1c62012-06-12 16:20:29 +02003109
Alexey Dobriyanf0f37e2f2009-09-27 22:29:37 +04003110const struct vm_operations_struct generic_file_vm_ops = {
Nick Piggin54cb8822007-07-19 01:46:59 -07003111 .fault = filemap_fault,
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003112 .map_pages = filemap_map_pages,
Jan Kara4fcf1c62012-06-12 16:20:29 +02003113 .page_mkwrite = filemap_page_mkwrite,
Vinayak Menon35eacb52021-03-18 15:20:17 +05303114#ifdef CONFIG_SPECULATIVE_PAGE_FAULT
3115 .allow_speculation = filemap_allow_speculation,
3116#endif
Linus Torvalds1da177e2005-04-16 15:20:36 -07003117};
3118
3119/* This is used for a general mmap of a disk file */
3120
3121int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
3122{
3123 struct address_space *mapping = file->f_mapping;
3124
3125 if (!mapping->a_ops->readpage)
3126 return -ENOEXEC;
3127 file_accessed(file);
3128 vma->vm_ops = &generic_file_vm_ops;
3129 return 0;
3130}
Linus Torvalds1da177e2005-04-16 15:20:36 -07003131
3132/*
3133 * This is for filesystems which do not implement ->writepage.
3134 */
3135int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3136{
3137 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
3138 return -EINVAL;
3139 return generic_file_mmap(file, vma);
3140}
3141#else
Souptick Joarder4b96a372018-10-26 15:04:03 -07003142vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Arnd Bergmann45397222018-04-13 15:35:27 -07003143{
Souptick Joarder4b96a372018-10-26 15:04:03 -07003144 return VM_FAULT_SIGBUS;
Arnd Bergmann45397222018-04-13 15:35:27 -07003145}
Linus Torvalds1da177e2005-04-16 15:20:36 -07003146int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
3147{
3148 return -ENOSYS;
3149}
3150int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
3151{
3152 return -ENOSYS;
3153}
3154#endif /* CONFIG_MMU */
3155
Arnd Bergmann45397222018-04-13 15:35:27 -07003156EXPORT_SYMBOL(filemap_page_mkwrite);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003157EXPORT_SYMBOL(generic_file_mmap);
3158EXPORT_SYMBOL(generic_file_readonly_mmap);
3159
Sasha Levin67f9fd92014-04-03 14:48:18 -07003160static struct page *wait_on_page_read(struct page *page)
3161{
3162 if (!IS_ERR(page)) {
3163 wait_on_page_locked(page);
3164 if (!PageUptodate(page)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003165 put_page(page);
Sasha Levin67f9fd92014-04-03 14:48:18 -07003166 page = ERR_PTR(-EIO);
3167 }
3168 }
3169 return page;
3170}
3171
Mel Gorman32b63522016-03-15 14:55:36 -07003172static struct page *do_read_cache_page(struct address_space *mapping,
Fengguang Wu57f6b962007-10-16 01:24:37 -07003173 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07003174 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003175 void *data,
3176 gfp_t gfp)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003177{
Nick Piggineb2be182007-10-16 01:24:57 -07003178 struct page *page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003179 int err;
3180repeat:
3181 page = find_get_page(mapping, index);
3182 if (!page) {
Mel Gorman453f85d2017-11-15 17:38:03 -08003183 page = __page_cache_alloc(gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07003184 if (!page)
3185 return ERR_PTR(-ENOMEM);
Dave Kleikampe6f67b82011-12-21 11:05:48 -06003186 err = add_to_page_cache_lru(page, mapping, index, gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07003187 if (unlikely(err)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003188 put_page(page);
Nick Piggineb2be182007-10-16 01:24:57 -07003189 if (err == -EEXIST)
3190 goto repeat;
Matthew Wilcox22ecdb42017-12-04 04:02:00 -05003191 /* Presumably ENOMEM for xarray node */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003192 return ERR_PTR(err);
3193 }
Mel Gorman32b63522016-03-15 14:55:36 -07003194
3195filler:
Christoph Hellwig6c45b452019-07-11 20:55:20 -07003196 if (filler)
3197 err = filler(data, page);
3198 else
3199 err = mapping->a_ops->readpage(data, page);
3200
Linus Torvalds1da177e2005-04-16 15:20:36 -07003201 if (err < 0) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003202 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07003203 return ERR_PTR(err);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003204 }
Mel Gorman32b63522016-03-15 14:55:36 -07003205
3206 page = wait_on_page_read(page);
3207 if (IS_ERR(page))
3208 return page;
3209 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003210 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003211 if (PageUptodate(page))
3212 goto out;
3213
Mel Gormanebded022016-03-15 14:55:39 -07003214 /*
Miaohe Lin0e9aa672020-10-15 20:09:58 -07003215 * Page is not up to date and may be locked due to one of the following
Mel Gormanebded022016-03-15 14:55:39 -07003216 * case a: Page is being filled and the page lock is held
3217 * case b: Read/write error clearing the page uptodate status
3218 * case c: Truncation in progress (page locked)
3219 * case d: Reclaim in progress
3220 *
3221 * Case a, the page will be up to date when the page is unlocked.
3222 * There is no need to serialise on the page lock here as the page
3223 * is pinned so the lock gives no additional protection. Even if the
Randy Dunlapce89fddf2020-08-11 18:32:53 -07003224 * page is truncated, the data is still valid if PageUptodate as
Mel Gormanebded022016-03-15 14:55:39 -07003225 * it's a race vs truncate race.
3226 * Case b, the page will not be up to date
3227 * Case c, the page may be truncated but in itself, the data may still
3228 * be valid after IO completes as it's a read vs truncate race. The
3229 * operation must restart if the page is not uptodate on unlock but
3230 * otherwise serialising on page lock to stabilise the mapping gives
3231 * no additional guarantees to the caller as the page lock is
3232 * released before return.
3233 * Case d, similar to truncation. If reclaim holds the page lock, it
3234 * will be a race with remove_mapping that determines if the mapping
3235 * is valid on unlock but otherwise the data is valid and there is
3236 * no need to serialise with page lock.
3237 *
3238 * As the page lock gives no additional guarantee, we optimistically
3239 * wait on the page to be unlocked and check if it's up to date and
3240 * use the page if it is. Otherwise, the page lock is required to
3241 * distinguish between the different cases. The motivation is that we
3242 * avoid spurious serialisations and wakeups when multiple processes
3243 * wait on the same page for IO to complete.
3244 */
3245 wait_on_page_locked(page);
3246 if (PageUptodate(page))
3247 goto out;
3248
3249 /* Distinguish between all the cases under the safety of the lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003250 lock_page(page);
Mel Gormanebded022016-03-15 14:55:39 -07003251
3252 /* Case c or d, restart the operation */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003253 if (!page->mapping) {
3254 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003255 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07003256 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003257 }
Mel Gormanebded022016-03-15 14:55:39 -07003258
3259 /* Someone else locked and filled the page in a very small window */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003260 if (PageUptodate(page)) {
3261 unlock_page(page);
3262 goto out;
3263 }
Xianting Tianfaffdfa2020-04-01 21:04:47 -07003264
3265 /*
3266 * A previous I/O error may have been due to temporary
3267 * failures.
3268 * Clear page error before actual read, PG_error will be
3269 * set again if read page fails.
3270 */
3271 ClearPageError(page);
Mel Gorman32b63522016-03-15 14:55:36 -07003272 goto filler;
3273
David Howellsc855ff32007-05-09 13:42:20 +01003274out:
Nick Piggin6fe69002007-05-06 14:49:04 -07003275 mark_page_accessed(page);
3276 return page;
3277}
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003278
3279/**
Sasha Levin67f9fd92014-04-03 14:48:18 -07003280 * read_cache_page - read into page cache, fill it if needed
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003281 * @mapping: the page's address_space
3282 * @index: the page index
3283 * @filler: function to perform the read
Hugh Dickins5e5358e2011-07-25 17:12:23 -07003284 * @data: first arg to filler(data, page) function, often left as NULL
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003285 *
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003286 * Read into the page cache. If a page already exists, and PageUptodate() is
Sasha Levin67f9fd92014-04-03 14:48:18 -07003287 * not set, try to fill the page and wait for it to become unlocked.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003288 *
3289 * If the page does not get brought uptodate, return -EIO.
Mike Rapoporta862f682019-03-05 15:48:42 -08003290 *
3291 * Return: up to date page on success, ERR_PTR() on failure.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003292 */
Sasha Levin67f9fd92014-04-03 14:48:18 -07003293struct page *read_cache_page(struct address_space *mapping,
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003294 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07003295 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003296 void *data)
3297{
Christoph Hellwigd322a8e2019-07-11 20:55:17 -07003298 return do_read_cache_page(mapping, index, filler, data,
3299 mapping_gfp_mask(mapping));
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003300}
Sasha Levin67f9fd92014-04-03 14:48:18 -07003301EXPORT_SYMBOL(read_cache_page);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003302
3303/**
3304 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
3305 * @mapping: the page's address_space
3306 * @index: the page index
3307 * @gfp: the page allocator flags to use if allocating
3308 *
3309 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
Dave Kleikampe6f67b82011-12-21 11:05:48 -06003310 * any new page allocations done using the specified allocation flags.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003311 *
3312 * If the page does not get brought uptodate, return -EIO.
Mike Rapoporta862f682019-03-05 15:48:42 -08003313 *
3314 * Return: up to date page on success, ERR_PTR() on failure.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003315 */
3316struct page *read_cache_page_gfp(struct address_space *mapping,
3317 pgoff_t index,
3318 gfp_t gfp)
3319{
Christoph Hellwig6c45b452019-07-11 20:55:20 -07003320 return do_read_cache_page(mapping, index, NULL, NULL, gfp);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003321}
3322EXPORT_SYMBOL(read_cache_page_gfp);
3323
Nick Pigginafddba42007-10-16 01:25:01 -07003324int pagecache_write_begin(struct file *file, struct address_space *mapping,
3325 loff_t pos, unsigned len, unsigned flags,
3326 struct page **pagep, void **fsdata)
3327{
3328 const struct address_space_operations *aops = mapping->a_ops;
3329
Nick Piggin4e02ed42008-10-29 14:00:55 -07003330 return aops->write_begin(file, mapping, pos, len, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003331 pagep, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003332}
3333EXPORT_SYMBOL(pagecache_write_begin);
3334
3335int pagecache_write_end(struct file *file, struct address_space *mapping,
3336 loff_t pos, unsigned len, unsigned copied,
3337 struct page *page, void *fsdata)
3338{
3339 const struct address_space_operations *aops = mapping->a_ops;
Nick Pigginafddba42007-10-16 01:25:01 -07003340
Nick Piggin4e02ed42008-10-29 14:00:55 -07003341 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003342}
3343EXPORT_SYMBOL(pagecache_write_end);
3344
Konstantin Khlebnikova92853b2019-11-30 17:49:44 -08003345/*
3346 * Warn about a page cache invalidation failure during a direct I/O write.
3347 */
3348void dio_warn_stale_pagecache(struct file *filp)
3349{
3350 static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
3351 char pathname[128];
3352 struct inode *inode = file_inode(filp);
3353 char *path;
3354
3355 errseq_set(&inode->i_mapping->wb_err, -EIO);
3356 if (__ratelimit(&_rs)) {
3357 path = file_path(filp, pathname, sizeof(pathname));
3358 if (IS_ERR(path))
3359 path = "(unknown)";
3360 pr_crit("Page cache invalidation failure on direct I/O. Possible data corruption due to collision with buffered I/O!\n");
3361 pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
3362 current->comm);
3363 }
3364}
3365
Linus Torvalds1da177e2005-04-16 15:20:36 -07003366ssize_t
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003367generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003368{
3369 struct file *file = iocb->ki_filp;
3370 struct address_space *mapping = file->f_mapping;
3371 struct inode *inode = mapping->host;
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003372 loff_t pos = iocb->ki_pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003373 ssize_t written;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003374 size_t write_len;
3375 pgoff_t end;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003376
Al Viro0c949332014-03-22 06:51:37 -04003377 write_len = iov_iter_count(from);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003378 end = (pos + write_len - 1) >> PAGE_SHIFT;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003379
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003380 if (iocb->ki_flags & IOCB_NOWAIT) {
3381 /* If there are pages to writeback, return */
3382 if (filemap_range_has_page(inode->i_mapping, pos,
zhengbin35f12f02019-03-05 15:44:21 -08003383 pos + write_len - 1))
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003384 return -EAGAIN;
3385 } else {
3386 written = filemap_write_and_wait_range(mapping, pos,
3387 pos + write_len - 1);
3388 if (written)
3389 goto out;
3390 }
Christoph Hellwiga969e902008-07-23 21:27:04 -07003391
3392 /*
3393 * After a write we want buffered reads to be sure to go to disk to get
3394 * the new data. We invalidate clean cached page from the region we're
3395 * about to write. We do this *before* the write so that we can return
Hisashi Hifumi6ccfa802008-09-02 14:35:40 -07003396 * without clobbering -EIOCBQUEUED from ->direct_IO().
Christoph Hellwiga969e902008-07-23 21:27:04 -07003397 */
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003398 written = invalidate_inode_pages2_range(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003399 pos >> PAGE_SHIFT, end);
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003400 /*
3401 * If a page can not be invalidated, return 0 to fall back
3402 * to buffered write.
3403 */
3404 if (written) {
3405 if (written == -EBUSY)
3406 return 0;
3407 goto out;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003408 }
3409
Al Viro639a93a52017-04-13 14:10:15 -04003410 written = mapping->a_ops->direct_IO(iocb, from);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003411
3412 /*
3413 * Finally, try again to invalidate clean pages which might have been
3414 * cached by non-direct readahead, or faulted in by get_user_pages()
3415 * if the source of the write was an mmap'ed region of the file
3416 * we're writing. Either one is a pretty crazy thing to do,
3417 * so we don't support it 100%. If this invalidation
3418 * fails, tough, the write still worked...
Lukas Czerner332391a2017-09-21 08:16:29 -06003419 *
3420 * Most of the time we do not need this since dio_complete() will do
3421 * the invalidation for us. However there are some file systems that
3422 * do not end up with dio_complete() being called, so let's not break
Konstantin Khlebnikov80c1fe92019-11-30 17:49:41 -08003423 * them by removing it completely.
3424 *
Konstantin Khlebnikov9266a142019-11-30 17:49:47 -08003425 * Noticeable example is a blkdev_direct_IO().
3426 *
Konstantin Khlebnikov80c1fe92019-11-30 17:49:41 -08003427 * Skip invalidation for async writes or if mapping has no pages.
Christoph Hellwiga969e902008-07-23 21:27:04 -07003428 */
Konstantin Khlebnikov9266a142019-11-30 17:49:47 -08003429 if (written > 0 && mapping->nrpages &&
3430 invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT, end))
3431 dio_warn_stale_pagecache(file);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003432
Linus Torvalds1da177e2005-04-16 15:20:36 -07003433 if (written > 0) {
Namhyung Kim01166512010-10-26 14:21:58 -07003434 pos += written;
Al Viro639a93a52017-04-13 14:10:15 -04003435 write_len -= written;
Namhyung Kim01166512010-10-26 14:21:58 -07003436 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3437 i_size_write(inode, pos);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003438 mark_inode_dirty(inode);
3439 }
Al Viro5cb6c6c2014-02-11 20:58:20 -05003440 iocb->ki_pos = pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003441 }
Al Viro639a93a52017-04-13 14:10:15 -04003442 iov_iter_revert(from, write_len - iov_iter_count(from));
Christoph Hellwiga969e902008-07-23 21:27:04 -07003443out:
Linus Torvalds1da177e2005-04-16 15:20:36 -07003444 return written;
3445}
3446EXPORT_SYMBOL(generic_file_direct_write);
3447
Nick Piggineb2be182007-10-16 01:24:57 -07003448/*
3449 * Find or create a page at the given pagecache position. Return the locked
3450 * page. This function is specifically for buffered writes.
3451 */
Nick Piggin54566b22009-01-04 12:00:53 -08003452struct page *grab_cache_page_write_begin(struct address_space *mapping,
3453 pgoff_t index, unsigned flags)
Nick Piggineb2be182007-10-16 01:24:57 -07003454{
Nick Piggineb2be182007-10-16 01:24:57 -07003455 struct page *page;
Johannes Weinerbbddabe2016-05-20 16:56:28 -07003456 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
Johannes Weiner0faa70c2012-01-10 15:07:53 -08003457
Nick Piggin54566b22009-01-04 12:00:53 -08003458 if (flags & AOP_FLAG_NOFS)
Mel Gorman2457aec2014-06-04 16:10:31 -07003459 fgp_flags |= FGP_NOFS;
Nick Piggineb2be182007-10-16 01:24:57 -07003460
Mel Gorman2457aec2014-06-04 16:10:31 -07003461 page = pagecache_get_page(mapping, index, fgp_flags,
Michal Hocko45f87de2014-12-29 20:30:35 +01003462 mapping_gfp_mask(mapping));
Mel Gorman2457aec2014-06-04 16:10:31 -07003463 if (page)
3464 wait_for_stable_page(page);
3465
Nick Piggineb2be182007-10-16 01:24:57 -07003466 return page;
3467}
Nick Piggin54566b22009-01-04 12:00:53 -08003468EXPORT_SYMBOL(grab_cache_page_write_begin);
Nick Piggineb2be182007-10-16 01:24:57 -07003469
Al Viro3b93f912014-02-11 21:34:08 -05003470ssize_t generic_perform_write(struct file *file,
Nick Pigginafddba42007-10-16 01:25:01 -07003471 struct iov_iter *i, loff_t pos)
3472{
3473 struct address_space *mapping = file->f_mapping;
3474 const struct address_space_operations *a_ops = mapping->a_ops;
3475 long status = 0;
3476 ssize_t written = 0;
Nick Piggin674b8922007-10-16 01:25:03 -07003477 unsigned int flags = 0;
3478
Nick Pigginafddba42007-10-16 01:25:01 -07003479 do {
3480 struct page *page;
Nick Pigginafddba42007-10-16 01:25:01 -07003481 unsigned long offset; /* Offset into pagecache page */
3482 unsigned long bytes; /* Bytes to write to page */
3483 size_t copied; /* Bytes copied from user */
Alexander Potapenko294ef122022-09-15 17:04:16 +02003484 void *fsdata = NULL;
Nick Pigginafddba42007-10-16 01:25:01 -07003485
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003486 offset = (pos & (PAGE_SIZE - 1));
3487 bytes = min_t(unsigned long, PAGE_SIZE - offset,
Nick Pigginafddba42007-10-16 01:25:01 -07003488 iov_iter_count(i));
3489
3490again:
Linus Torvalds00a3d662015-10-07 08:32:38 +01003491 /*
3492 * Bring in the user page that we will copy from _first_.
3493 * Otherwise there's a nasty deadlock on copying from the
3494 * same page as we're writing to, without it being marked
3495 * up-to-date.
3496 *
3497 * Not only is this an optimisation, but it is also required
3498 * to check that the address is actually valid, when atomic
3499 * usercopies are used, below.
3500 */
3501 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3502 status = -EFAULT;
3503 break;
3504 }
3505
Jan Kara296291c2015-10-22 13:32:21 -07003506 if (fatal_signal_pending(current)) {
3507 status = -EINTR;
3508 break;
3509 }
3510
Nick Piggin674b8922007-10-16 01:25:03 -07003511 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003512 &page, &fsdata);
Mel Gorman2457aec2014-06-04 16:10:31 -07003513 if (unlikely(status < 0))
Nick Pigginafddba42007-10-16 01:25:01 -07003514 break;
3515
anfei zhou931e80e2010-02-02 13:44:02 -08003516 if (mapping_writably_mapped(mapping))
3517 flush_dcache_page(page);
Linus Torvalds00a3d662015-10-07 08:32:38 +01003518
Nick Pigginafddba42007-10-16 01:25:01 -07003519 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
Nick Pigginafddba42007-10-16 01:25:01 -07003520 flush_dcache_page(page);
3521
3522 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3523 page, fsdata);
3524 if (unlikely(status < 0))
3525 break;
3526 copied = status;
3527
3528 cond_resched();
3529
Nick Piggin124d3b72008-02-02 15:01:17 +01003530 iov_iter_advance(i, copied);
Nick Pigginafddba42007-10-16 01:25:01 -07003531 if (unlikely(copied == 0)) {
3532 /*
3533 * If we were unable to copy any data at all, we must
3534 * fall back to a single segment length write.
3535 *
3536 * If we didn't fallback here, we could livelock
3537 * because not all segments in the iov can be copied at
3538 * once without a pagefault.
3539 */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003540 bytes = min_t(unsigned long, PAGE_SIZE - offset,
Nick Pigginafddba42007-10-16 01:25:01 -07003541 iov_iter_single_seg_count(i));
3542 goto again;
3543 }
Nick Pigginafddba42007-10-16 01:25:01 -07003544 pos += copied;
3545 written += copied;
3546
3547 balance_dirty_pages_ratelimited(mapping);
Nick Pigginafddba42007-10-16 01:25:01 -07003548 } while (iov_iter_count(i));
3549
3550 return written ? written : status;
3551}
Al Viro3b93f912014-02-11 21:34:08 -05003552EXPORT_SYMBOL(generic_perform_write);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003553
Jan Karae4dd9de2009-08-17 18:10:06 +02003554/**
Al Viro81742022014-04-03 03:17:43 -04003555 * __generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003556 * @iocb: IO state structure (file, offset, etc.)
Al Viro81742022014-04-03 03:17:43 -04003557 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003558 *
3559 * This function does all the work needed for actually writing data to a
3560 * file. It does all basic checks, removes SUID from the file, updates
3561 * modification times and calls proper subroutines depending on whether we
3562 * do direct IO or a standard buffered write.
3563 *
3564 * It expects i_mutex to be grabbed unless we work on a block device or similar
3565 * object which does not need locking at all.
3566 *
3567 * This function does *not* take care of syncing data in case of O_SYNC write.
3568 * A caller has to handle it. This is mainly due to the fact that we want to
3569 * avoid syncing under i_mutex.
Mike Rapoporta862f682019-03-05 15:48:42 -08003570 *
3571 * Return:
3572 * * number of bytes written, even for truncated writes
3573 * * negative error code if no data has been written at all
Jan Karae4dd9de2009-08-17 18:10:06 +02003574 */
Al Viro81742022014-04-03 03:17:43 -04003575ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003576{
3577 struct file *file = iocb->ki_filp;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003578 struct address_space * mapping = file->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003579 struct inode *inode = mapping->host;
Al Viro3b93f912014-02-11 21:34:08 -05003580 ssize_t written = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003581 ssize_t err;
Al Viro3b93f912014-02-11 21:34:08 -05003582 ssize_t status;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003583
Linus Torvalds1da177e2005-04-16 15:20:36 -07003584 /* We can write back this queue in page reclaim */
Christoph Hellwigde1414a2015-01-14 10:42:36 +01003585 current->backing_dev_info = inode_to_bdi(inode);
Jan Kara5fa8e0a2015-05-21 16:05:53 +02003586 err = file_remove_privs(file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003587 if (err)
3588 goto out;
3589
Josef Bacikc3b2da32012-03-26 09:59:21 -04003590 err = file_update_time(file);
3591 if (err)
3592 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003593
Al Viro2ba48ce2015-04-09 13:52:01 -04003594 if (iocb->ki_flags & IOCB_DIRECT) {
Al Viro0b8def92015-04-07 10:22:53 -04003595 loff_t pos, endbyte;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003596
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003597 written = generic_file_direct_write(iocb, from);
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08003598 /*
3599 * If the write stopped short of completing, fall back to
3600 * buffered writes. Some filesystems do this for writes to
3601 * holes, for example. For DAX files, a buffered write will
3602 * not succeed (even if it did, DAX does not handle dirty
3603 * page-cache pages correctly).
3604 */
Al Viro0b8def92015-04-07 10:22:53 -04003605 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003606 goto out;
Al Viro3b93f912014-02-11 21:34:08 -05003607
Al Viro0b8def92015-04-07 10:22:53 -04003608 status = generic_perform_write(file, from, pos = iocb->ki_pos);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003609 /*
Al Viro3b93f912014-02-11 21:34:08 -05003610 * If generic_perform_write() returned a synchronous error
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003611 * then we want to return the number of bytes which were
3612 * direct-written, or the error code if that was zero. Note
3613 * that this differs from normal direct-io semantics, which
3614 * will return -EFOO even if some bytes were written.
3615 */
Al Viro60bb4522014-08-08 12:39:16 -04003616 if (unlikely(status < 0)) {
Al Viro3b93f912014-02-11 21:34:08 -05003617 err = status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003618 goto out;
3619 }
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003620 /*
3621 * We need to ensure that the page cache pages are written to
3622 * disk and invalidated to preserve the expected O_DIRECT
3623 * semantics.
3624 */
Al Viro3b93f912014-02-11 21:34:08 -05003625 endbyte = pos + status - 1;
Al Viro0b8def92015-04-07 10:22:53 -04003626 err = filemap_write_and_wait_range(mapping, pos, endbyte);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003627 if (err == 0) {
Al Viro0b8def92015-04-07 10:22:53 -04003628 iocb->ki_pos = endbyte + 1;
Al Viro3b93f912014-02-11 21:34:08 -05003629 written += status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003630 invalidate_mapping_pages(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003631 pos >> PAGE_SHIFT,
3632 endbyte >> PAGE_SHIFT);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003633 } else {
3634 /*
3635 * We don't know how much we wrote, so just return
3636 * the number of bytes which were direct-written
3637 */
3638 }
3639 } else {
Al Viro0b8def92015-04-07 10:22:53 -04003640 written = generic_perform_write(file, from, iocb->ki_pos);
3641 if (likely(written > 0))
3642 iocb->ki_pos += written;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003643 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003644out:
3645 current->backing_dev_info = NULL;
3646 return written ? written : err;
3647}
Al Viro81742022014-04-03 03:17:43 -04003648EXPORT_SYMBOL(__generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003649
Jan Karae4dd9de2009-08-17 18:10:06 +02003650/**
Al Viro81742022014-04-03 03:17:43 -04003651 * generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003652 * @iocb: IO state structure
Al Viro81742022014-04-03 03:17:43 -04003653 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003654 *
Al Viro81742022014-04-03 03:17:43 -04003655 * This is a wrapper around __generic_file_write_iter() to be used by most
Jan Karae4dd9de2009-08-17 18:10:06 +02003656 * filesystems. It takes care of syncing the file in case of O_SYNC file
3657 * and acquires i_mutex as needed.
Mike Rapoporta862f682019-03-05 15:48:42 -08003658 * Return:
3659 * * negative error code if no data has been written at all of
3660 * vfs_fsync_range() failed for a synchronous write
3661 * * number of bytes written, even for truncated writes
Jan Karae4dd9de2009-08-17 18:10:06 +02003662 */
Al Viro81742022014-04-03 03:17:43 -04003663ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003664{
3665 struct file *file = iocb->ki_filp;
Jan Kara148f9482009-08-17 19:52:36 +02003666 struct inode *inode = file->f_mapping->host;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003667 ssize_t ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003668
Al Viro59551022016-01-22 15:40:57 -05003669 inode_lock(inode);
Al Viro3309dd02015-04-09 12:55:47 -04003670 ret = generic_write_checks(iocb, from);
3671 if (ret > 0)
Al Viro5f380c72015-04-07 11:28:12 -04003672 ret = __generic_file_write_iter(iocb, from);
Al Viro59551022016-01-22 15:40:57 -05003673 inode_unlock(inode);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003674
Christoph Hellwige2592212016-04-07 08:52:01 -07003675 if (ret > 0)
3676 ret = generic_write_sync(iocb, ret);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003677 return ret;
3678}
Al Viro81742022014-04-03 03:17:43 -04003679EXPORT_SYMBOL(generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003680
David Howellscf9a2ae2006-08-29 19:05:54 +01003681/**
3682 * try_to_release_page() - release old fs-specific metadata on a page
3683 *
3684 * @page: the page which the kernel is trying to free
3685 * @gfp_mask: memory allocation flags (and I/O mode)
3686 *
3687 * The address_space is to try to release any data against the page
Mike Rapoporta862f682019-03-05 15:48:42 -08003688 * (presumably at page->private).
David Howellscf9a2ae2006-08-29 19:05:54 +01003689 *
David Howells266cf652009-04-03 16:42:36 +01003690 * This may also be called if PG_fscache is set on a page, indicating that the
3691 * page is known to the local caching routines.
3692 *
David Howellscf9a2ae2006-08-29 19:05:54 +01003693 * The @gfp_mask argument specifies whether I/O may be performed to release
Mel Gorman71baba42015-11-06 16:28:28 -08003694 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
David Howellscf9a2ae2006-08-29 19:05:54 +01003695 *
Mike Rapoporta862f682019-03-05 15:48:42 -08003696 * Return: %1 if the release was successful, otherwise return zero.
David Howellscf9a2ae2006-08-29 19:05:54 +01003697 */
3698int try_to_release_page(struct page *page, gfp_t gfp_mask)
3699{
3700 struct address_space * const mapping = page->mapping;
3701
3702 BUG_ON(!PageLocked(page));
3703 if (PageWriteback(page))
3704 return 0;
3705
3706 if (mapping && mapping->a_ops->releasepage)
3707 return mapping->a_ops->releasepage(page, gfp_mask);
3708 return try_to_free_buffers(page);
3709}
3710
3711EXPORT_SYMBOL(try_to_release_page);